From 00f1f7cca4ad8e1439f69b445b0bebc555877025 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 04:23:56 +0000 Subject: [PATCH 01/26] MCP addons: direct commands, watches and an outbox, plus the GeoGuess addon An MCP stdio server with an "addon" block in MCP_CONFIG can now hook the bot through a small signalbot extension of MCP 2025-06-18: - direct chat commands the bot runs itself, without the model - tools hidden from the model, callable only by the bot - watches: messages matching an addon's pattern in one chat go to the addon instead of the model or history, on both the reader and slot paths - an outbox resource the addon updates, for posts and reactions on its own schedule - per-chat pseudonyms, chat allowlist and permissions, settings passed through by name prefix from the one env file, stderr counted never logged Core ports, generic: Action.Pictures, OnSent, Done and IsZero; Host.Post (replacing Tell) with Network.Reachable; Host.React at low priority in the mailbox. groupctx now runs after mcp. kit/img gains Safe (header-only size check, JPEG metadata stripped). Telegram locations become map links. cmd/geoguess is a GeoGuessr-style game addon on the standard library: Mapillary and Panoramax street-level photos with quality filters, guesses by shared location, ranked by distance, keeping only distances. No new dependencies. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- CONTRIBUTING.md | 7 +- PRIVACY.md | 41 +- README.md | 1 + TECHNICAL.md | 52 +- cmd/geoguess/README.md | 147 +++ cmd/geoguess/clock.go | 19 + cmd/geoguess/config.go | 151 +++ cmd/geoguess/game.go | 398 ++++++++ cmd/geoguess/geo/find.go | 113 +++ cmd/geoguess/geo/find_test.go | 178 ++++ cmd/geoguess/geo/mapillary.go | 177 ++++ cmd/geoguess/geo/panoramax.go | 214 ++++ cmd/geoguess/geo/parse.go | 223 +++++ cmd/geoguess/geo/parse_test.go | 136 +++ cmd/geoguess/geo/pixels.go | 277 ++++++ cmd/geoguess/geo/pixels_test.go | 267 +++++ cmd/geoguess/geo/place.go | 81 ++ cmd/geoguess/geo/place_test.go | 56 ++ cmd/geoguess/geo/rules.go | 134 +++ cmd/geoguess/geo/rules_test.go | 100 ++ cmd/geoguess/geo/score.go | 108 ++ cmd/geoguess/geo/score_test.go | 93 ++ cmd/geoguess/geo/seeds.go | 149 +++ cmd/geoguess/geo/seeds.json | 270 +++++ cmd/geoguess/geo/seeds_test.go | 155 +++ cmd/geoguess/geo/source.go | 176 ++++ cmd/geoguess/geo/source_test.go | 372 +++++++ cmd/geoguess/geo/testdata/mapillary_bbox.json | 244 +++++ .../geo/testdata/mapillary_error.json | 1 + .../geo/testdata/mapillary_radius.json | 154 +++ .../geo/testdata/panoramax_search.json | 614 ++++++++++++ cmd/geoguess/main.go | 113 +++ cmd/geoguess/main_test.go | 803 +++++++++++++++ cmd/geoguess/prefetch.go | 223 +++++ cmd/geoguess/rpc.go | 410 ++++++++ cmd/geoguess/server.go | 307 ++++++ docs/CONFIGURATION.md | 5 +- docs/FILES_LINKS_TOOLS_MCP.md | 59 +- docs/SCENARIOS.md | 2 +- docs/architecture.svg | 2 +- docs/message-flow.svg | 2 +- examples/signalbot-mcp.json | 5 + features.go | 2 +- internal/arch/arch_test.go | 5 +- internal/bot/answer.go | 57 +- internal/bot/bot.go | 89 +- internal/bot/fakes_test.go | 8 + internal/bot/host.go | 97 +- internal/bot/host_test.go | 251 +++++ internal/bot/received.go | 22 +- internal/chats/chats.go | 51 +- internal/chats/chats_test.go | 52 + internal/feature/command_test.go | 4 +- internal/feature/feature.go | 42 +- internal/feature/feature_test.go | 40 + internal/feature/featuretest/featuretest.go | 37 +- .../feature/featuretest/featuretest_test.go | 18 +- internal/features/groupctx/groupctx_test.go | 6 +- internal/features/intro/intro_test.go | 4 +- internal/features/mcp/addon.go | 356 +++++++ internal/features/mcp/addon_test.go | 631 ++++++++++++ internal/features/mcp/conn.go | 205 +++- internal/features/mcp/corpus.go | 239 +++++ internal/features/mcp/direct.go | 134 +++ internal/features/mcp/keep.go | 179 ++++ internal/features/mcp/mcp.go | 307 ++++-- internal/features/mcp/mcp_test.go | 21 +- internal/features/mcp/outbox.go | 440 +++++++++ internal/features/mcp/proc_other.go | 15 + internal/features/mcp/proc_unix.go | 15 + internal/features/mcp/watch.go | 411 ++++++++ internal/features/mcp/watch_test.go | 935 ++++++++++++++++++ internal/features/schedule/schedule.go | 4 +- internal/features/schedule/schedule_test.go | 9 +- internal/kit/img/safe.go | 119 +++ internal/kit/img/safe_test.go | 183 ++++ internal/signal/decode.go | 23 + internal/signal/decode_test.go | 23 + internal/telegram/decode.go | 48 + internal/telegram/telegram_test.go | 48 + scenario_fakes_test.go | 81 +- scenario_test.go | 74 +- 82 files changed, 12083 insertions(+), 241 deletions(-) create mode 100644 cmd/geoguess/README.md create mode 100644 cmd/geoguess/clock.go create mode 100644 cmd/geoguess/config.go create mode 100644 cmd/geoguess/game.go create mode 100644 cmd/geoguess/geo/find.go create mode 100644 cmd/geoguess/geo/find_test.go create mode 100644 cmd/geoguess/geo/mapillary.go create mode 100644 cmd/geoguess/geo/panoramax.go create mode 100644 cmd/geoguess/geo/parse.go create mode 100644 cmd/geoguess/geo/parse_test.go create mode 100644 cmd/geoguess/geo/pixels.go create mode 100644 cmd/geoguess/geo/pixels_test.go create mode 100644 cmd/geoguess/geo/place.go create mode 100644 cmd/geoguess/geo/place_test.go create mode 100644 cmd/geoguess/geo/rules.go create mode 100644 cmd/geoguess/geo/rules_test.go create mode 100644 cmd/geoguess/geo/score.go create mode 100644 cmd/geoguess/geo/score_test.go create mode 100644 cmd/geoguess/geo/seeds.go create mode 100644 cmd/geoguess/geo/seeds.json create mode 100644 cmd/geoguess/geo/seeds_test.go create mode 100644 cmd/geoguess/geo/source.go create mode 100644 cmd/geoguess/geo/source_test.go create mode 100644 cmd/geoguess/geo/testdata/mapillary_bbox.json create mode 100644 cmd/geoguess/geo/testdata/mapillary_error.json create mode 100644 cmd/geoguess/geo/testdata/mapillary_radius.json create mode 100644 cmd/geoguess/geo/testdata/panoramax_search.json create mode 100644 cmd/geoguess/main.go create mode 100644 cmd/geoguess/main_test.go create mode 100644 cmd/geoguess/prefetch.go create mode 100644 cmd/geoguess/rpc.go create mode 100644 cmd/geoguess/server.go create mode 100644 internal/feature/feature_test.go create mode 100644 internal/features/mcp/addon.go create mode 100644 internal/features/mcp/addon_test.go create mode 100644 internal/features/mcp/corpus.go create mode 100644 internal/features/mcp/direct.go create mode 100644 internal/features/mcp/keep.go create mode 100644 internal/features/mcp/outbox.go create mode 100644 internal/features/mcp/proc_other.go create mode 100644 internal/features/mcp/proc_unix.go create mode 100644 internal/features/mcp/watch.go create mode 100644 internal/features/mcp/watch_test.go create mode 100644 internal/kit/img/safe.go create mode 100644 internal/kit/img/safe_test.go diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 92d70f0..e5a3f70 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,6 +16,7 @@ internal/feature/ the ports and shared types, command parsing, featuretest internal/features/* one package per feature internal/kit/* code with two or more users and no bot knowledge cmd/signalctl/ a small client for signal-cli's daemon socket, for one-off chores such as blocking; not part of the bot +cmd/geoguess/ GeoGuess, an addon: a separate program the bot runs as a local MCP server, speaking MCP over stdio by hand ``` ## The port rule @@ -24,11 +25,11 @@ Features reach the core only through the ports in `internal/feature`, one per st | Stage | Port | |---|---| -| A message arrives | `OnMessage`: carry on, answer without the model, choose a tool, or keep text as context | +| A message arrives | `OnMessage`: carry on, answer without the model (text or pictures), choose a tool, keep text as context, or mark it done | | The model is asked | `OnTurn` (a note on the message, images) and `Tools` (a `ToolGroup`) | | Time arrives | `At`: a one-shot timer | -and the host's services: `Env`, `Info`, `Media`, `CallAPI`, `Deliver`, `Groups`, `Redact` and `Go`. Hooks run in `features.go` order. An `OnMessage` hook for an unaddressed message runs on the reader goroutine, so it must not block or call the network. +and the host's services: `Env`, `Info`, `Media`, `CallAPI`, `Deliver`, `Post`, `React`, `Groups`, `Redact` and `Go`. Hooks run in `features.go` order. An `OnMessage` hook for an unaddressed message runs on the reader goroutine, so it must not block or call the network. If a feature can't be built on these, that's a design finding. Either a port becomes more generic, and stays tied to its stage, or the feature takes on more of the work. A feature-shaped field in the core is never the answer: delete any feature and the core doesn't change. @@ -53,7 +54,7 @@ Give a feature a tag only for a real saving, such as a dependency; a runtime set Tests in `internal/arch` enforce these: -- **Imports:** only the main package, at the module root, imports features and `internal/signal`; a feature imports only `internal/feature`, `internal/kit` and its own packages; `internal/signal` imports only `internal/feature`, kit, `internal/config` and `internal/bot` (network to core, never the reverse); `internal/config` and kit import no other internal package. +- **Imports:** only the main package, at the module root, imports features and `internal/signal`; a feature imports only `internal/feature`, `internal/kit` and its own packages; `internal/signal` imports only `internal/feature`, kit, `internal/config` and `internal/bot` (network to core, never the reverse); `internal/config` and kit import no other internal package; `cmd/geoguess` imports only kit and its own packages. - **No feature names in the core:** the core's source mentions no feature name or feature-only word (chart, MCP, group context, `/intro`, `/schedule`, …). - **Docs:** every setting read, the core's or a feature's (`h.Env("NAME", …)`), is in the table in [docs/CONFIGURATION.md](docs/CONFIGURATION.md). diff --git a/PRIVACY.md b/PRIVACY.md index 1533cb6..228c228 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -23,6 +23,8 @@ When asked for a picture, the model writes a prompt for the image model, which c With MCP tools configured, the model may call them. A call sends the arguments the model wrote, which can quote anything above, to that tool's MCP server, and the tool's result goes to the model's API with the next request. +With an [addon](#addons) configured, the bot sends that program, on the same machine, what its permissions allow: see below. Whatever the addon then sends elsewhere is up to it. + Every request to OpenRouter tells it to use only model providers that do not collect data (`data_collection: deny`). That is a request the bot cannot check or enforce, so read OpenRouter's policy and the model provider's. Other APIs get no such request, since it is OpenRouter's own; read their data policy. A local server, such as Ollama on the same machine, keeps everything on it. ## What the bot keeps @@ -34,8 +36,9 @@ Every request to OpenRouter tells it to use only model providers that do not col - **No swap or core dumps.** The included systemd unit and Docker command forbid both, so history cannot reach disk that way. - **Memory is freed, not wiped.** An expired message is dropped and Go's garbage collector reclaims its memory, but the bytes may linger until overwritten, and someone with root access to the host could read them from the running process. - **What features save, on disk.** Features save state only through the core, one file each in the state directory (`/var/lib/private/signalbot`), so everything the bot keeps on disk is listed here. -- **Schedules are kept on disk.** Each `/schedule` saves, in `schedules.json` in the state directory (`/var/lib/private/signalbot`), the scheduling user's ID, the group's ID and its name when scheduled (if it's for a group), the time and repeat, and the text to post, until the user deletes it with `/schedule del`. The file also keeps, for each user who has scheduled, the last schedule number they were given, so numbers are never reused; it stays after their schedules are deleted. A one-off dropped because the bot was down is deleted, and its user is told in their DM, with the first 80 characters of its text. Besides today's spending (below), nothing else the bot keeps is written to disk. +- **Schedules are kept on disk.** Each `/schedule` saves, in `schedules.json` in the state directory (`/var/lib/private/signalbot`), the scheduling user's ID, the group's ID and its name when scheduled (if it's for a group), the time and repeat, and the text to post, until the user deletes it with `/schedule del`. The file also keeps, for each user who has scheduled, the last schedule number they were given, so numbers are never reused; it stays after their schedules are deleted. A one-off dropped because the bot was down is deleted, and its user is told in their DM, with the first 80 characters of its text. Besides today's spending and, with an addon, `mcp.json` (both below), nothing else the bot keeps is written to disk. - **Today's spending, on disk.** With a daily budget (`DAILY_BUDGET`, on by default), `budget.json` in the state directory holds today's date and, for each chat that used the model today, what it spent and whether it was told it reached the limit. Chats are stored under a SHA-256 hash of their ID, so the file holds no phone numbers, account IDs or group IDs as such. A hash of a phone number could be matched by trying every number, so treat the file as you would the schedules. Each day's file replaces the last. +- **Addon state, on disk.** With an MCP server configured as an addon, `mcp.json` in the state directory holds what is listed under [Addons](#addons). Without one, the file is never written. - **Recent attachments, in memory only.** So that "@bot summarise this" in reply to someone's file can fetch the original, the bot remembers, for each group message and each DM from an allowed sender with attachments, the attachments' IDs, file names, types and sizes, never their content, under the chat, sender and time. Each is forgotten after a day, or sooner when 2,000 newer messages are remembered, and a restart clears them all. On Signal the bot also keeps a copy of each picture it sent (a chart, a picture it made), content and all, for at most a day and 32 MB in all, since signal-cli keeps none: a reply quoting it then shows the model the picture rather than Signal's small thumbnail. A delete of that message from the account's linked device drops it, and a restart clears them all. - **Names.** The bot keeps a copy of signal-cli's contact list (names and IDs) in memory, so it can show and mention people by name. It reloads the list at startup, after reconnecting, when a group changes, and at least daily when in use, replacing what it had, so people who leave a group are forgotten. It also keeps the name of anyone who sends it an addressed message. It never keeps what anyone wrote. @@ -48,17 +51,17 @@ Every level, debug included, is always written; there is no setting to turn any - **A message not addressed to the bot:** nothing, not even a note that it arrived. - **Reactions and changes in a group's members:** nothing. They are passed to features that ask for them (who reacted, with what, to whose message; who joined or left), never logged, kept or shown to the model. With no such feature, they are dropped as they arrive. - **A DM from someone not in `SIGNAL_DM_USER_IDS`:** their ID, every time, never a name or text. The same goes for a scheduled run in the DM of a user since removed from the list. -- **A tool call:** the tool's name and how long it took; never the arguments or the result. +- **A tool call:** the tool's name and how long it took; never the arguments or the result. An addon's calls, made by the bot itself, are logged the same way, with the result's size and code, as are counts of what it had dropped; never what was said, nor the addon's own error text. - **A link, file, photo or sticker in a message addressed to the bot:** one line each with what the bot did with it and, once it was fetched, its size (how much text was read, a PDF or audio attached, an image shrunk, or why it failed); one line when a link wasn't fetched (it looked private or one-time, it wasn't on port 80 or 443, the chat's 20 an hour were used, or it was past the second in a message) or when the model can't see the images or sticker; never the link, not even its host, the file's name or the type it was sent as (a file the bot can't read is logged with the type sniffed from its content), the page's title, a sticker's emoji or pack title, or any text. - **Schedules:** how many were loaded at startup, a run skipped or dropped, and how long each run took; never the text or who made it. A run dropped because its user left the group is logged without content. - **Names and IDs:** never anyone's name, and never anyone's ID except as above for a DM from someone not in `SIGNAL_DM_USER_IDS`. The bot logs its own account ID at startup. -- **Debug lines:** the number of contacts loaded, that a repeated message was dropped, and a local MCP server's own error output, which the bot doesn't control, so each line has every name and ID the bot knows replaced with "redacted" ("Alice's" becomes "redacted's"), along with any UUID or phone number, before it is written. +- **Debug lines:** the number of contacts loaded, that a repeated message was dropped, and a local MCP server's own error output, which the bot doesn't control, so each line has every name and ID the bot knows replaced with "redacted" ("Alice's" becomes "redacted's"), along with any UUID or phone number, before it is written. An addon's error output is never written at all, only counted ("addon geo wrote 3 lines (210 bytes) to stderr", at most once a minute, and once more when it exits), since it may repeat what it was sent. Logs go to the journal or Docker's log driver and are kept as long as your settings keep them. ## What the bot can see -In a group, signal-cli passes every message to the bot, which checks each one for whether it is addressed to it. Messages not addressed to it are never logged and never answered. Their text, with the sender's display name, is kept in that group's history as context, the same way and for the same time as everything else there, unless `GROUP_CONTEXT=false`, in which case they are dropped on the spot. In DMs, the bot answers only the IDs listed in `SIGNAL_DM_USER_IDS`. +In a group, signal-cli passes every message to the bot, which checks each one for whether it is addressed to it. Messages not addressed to it are never logged and never answered. Their text, with the sender's display name, is kept in that group's history as context, the same way and for the same time as everything else there, unless `GROUP_CONTEXT=false`, in which case they are dropped on the spot. In DMs, the bot answers only the IDs listed in `SIGNAL_DM_USER_IDS`. A message an addon's watch takes (see below) is neither answered nor kept, even as context. ## Telegram @@ -71,8 +74,38 @@ On Telegram (`TELEGRAM_BOT_TOKEN` set) the above holds, with these differences: - **Photos and files** are fetched from Telegram's servers by file ID, only while answering the message that has them. - **Who it answers in groups.** Anyone can add a Telegram bot to a group, so the bot answers in a group only while someone in `TELEGRAM_DM_USER_IDS` is a member, and leaves one where no one is. Until it has checked, a stranger's group can briefly reach it: such messages are never answered, and chatter is dropped once the check is done. - **Topics.** In a group with topics, each topic keeps its own history. +- **Locations.** A shared location or venue reaches the bot as a map link with its coordinates, as on Signal, so it is kept, and sent to the model, like any text. A live location, which follows its sender, is left out. - **The token** is in every request's URL; the bot takes it out of every error before logging it. +## Addons + +An addon is a program the bot runs on its own machine, as an [MCP server](docs/FILES_LINKS_TOOLS_MCP.md#addons), that answers its own commands, reads the messages it asks for and posts on its own, such as the [GeoGuess](cmd/geoguess/README.md) game. With none configured, none of this applies. + +- **It is trusted code.** It runs as the bot's user, in the same sandbox, and could read what the bot's user can, the state directory included. What follows limits what the bot hands it; it guards against mistakes and leaks, not against a hostile program. Install only addons you would let run as the bot. +- **What it never gets:** phone numbers, account IDs or group IDs. Chats and people are pseudonyms, made from a secret in `mcp.json` and different for each addon; by default the same person has a different one in each chat, so an addon can't follow them between groups. It gets none of the bot's settings or keys either: only `PATH`, `HOME`, the time zone and proxy settings (`TZ`, `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, `SSL_CERT_FILE`, `SSL_CERT_DIR`) if set, and the variables named for it (such as `GEO_…`). +- **Where it works:** only in the groups its `chats` lists (or all, if set to `all`), and in DMs only with `dms`. +- **What each permission sends:** + - a command (`/geo …`) sends the text after it, and who sent it, as a pseudonym, and when the bot got it, never the sender's own clock; + - `watch` sends the messages its watch matches (GeoGuess: map links and coordinates during a round), with the same; nothing else said in the chat. A pattern that would match ordinary chat is refused, so there is no feed of everything; + - `names` adds each sender's display name. Without it, the addon writes a pseudonym where a name goes, and the bot puts in the name it last saw that person use in that chat, kept in memory for a day; + - `global_ids` gives a person the same pseudonym in every chat, so the addon can link them across groups; + - `post` and `react` send nothing: they let it post and react, only in a chat where it was used in the last day. +- **What the addon keeps** is its own, in whatever directory you give it (GeoGuess: `GEO_STATE_DIR`), outside what this page lists for the bot. Read its own documentation. +- **Deletes and edits are not passed on.** A message an addon took stays with the addon if its sender later deletes it for everyone. An edit of one is passed on, as a new version. +- **Taken messages are kept nowhere by the bot:** not in history, not as context (so `GROUP_CONTEXT=false` makes no difference to them), not in the log. The addon still gets them. +- **What it posts** is kept in history as the bot's own words, labelled with the addon's name (`[GeoGuess] …`) and cut to 500 characters, so later model requests can see it but it never poses as a person. +- **`mcp.json`,** in the state directory, written only when some MCP server is an addon: + + | Item | Kept for | + |---|---| + | The pseudonym secret | Until `mcp.json` is deleted, which gives everyone new pseudonyms | + | Chats an addon may post in: the chat's pseudonym and its real ID | 24 hours after the addon was last used there | + | Live watches: the chat's pseudonym, the pattern, and the times of the bot's messages with the command's pictures | Until the watch ends, at most `watch_max` (24 hours at most) | + | Messages a watch took: the chat's ID, the sender's pseudonym and the message's time, never its text | 48 hours, so a later edit is taken too | + | How far the bot has read each addon's outbox, and the last 1,000 outbox entries' IDs | Replaced on each save; dropped once the server is no longer an addon | + + Refs to messages (for reactions, a day), display names (a day) and posts waiting to go out are kept in memory only. + ## What this does not cover - **The provider.** Once a message is sent, the model provider's retention, logging and sub-processors apply. diff --git a/README.md b/README.md index e53c002..0801db5 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,7 @@ A small, [privacy-conscious](PRIVACY.md) chat bot for Signal, through a running - Responds to @mentions, replies to its messages, and DMs from whitelisted contacts - Tools: web search, line and pie charts, [pictures](docs/FILES_LINKS_TOOLS_MCP.md#images) (drawings, art, diagrams) with GPT Image 2, and your own [MCP connectors](docs/FILES_LINKS_TOOLS_MCP.md#mcp-connectors) - [`/schedule`](docs/SCHEDULING.md) a message or command, once or repeating +- [Addons](docs/FILES_LINKS_TOOLS_MCP.md#addons): MCP servers that run their own commands and games in chosen groups, without the model, such as [GeoGuess](cmd/geoguess/README.md), seeing only pseudonyms - Understands [files](docs/FILES_LINKS_TOOLS_MCP.md#files) (PDFs, text and code, Word, Excel and PowerPoint) and the [pages you link to](docs/FILES_LINKS_TOOLS_MCP.md#links), and if the model supports it, images, stickers, voice notes and other audio - Typing indicators, reactions, stickers, @mentions and replies - In-memory conversation context (Default: 10 messages). Never logged to disk, forgotten after 24 hours, or sooner if _disappearing messages_ requires. diff --git a/TECHNICAL.md b/TECHNICAL.md index b94fa9c..e7f936a 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -62,9 +62,9 @@ Each line has a journald priority, and every priority is always written: ## Concurrency and scale -- **Reader goroutine.** The Signal client's reader parses each frame and decides "addressed?" without blocking or calling the network, then hands the bot a `bot.Received`, one of a closed set of types (`internal/bot/received.go`): `Incoming`, a message completed in its slot by its `Load` (an addressed one, or any other data message that arrived before the bot's own ID was known); `Chatter`, an unaddressed group message; `GroupChanged`; `Deleted`, a delete or a replacing edit, handled on the spot like `GroupChanged`; and `Happened` for a reaction, never passed to `OnMessage`. A member change, also a `Happened`, comes from the client's member-comparison goroutine through the same handler. The core switches on the type. `Incoming` goes to its chat's mailbox from here, and `Happened` too when an `OnEvent` hook is registered; the only other kinds there are `Told`, a text the bot sends a user (`Tell`), and `Posted`, a message a feature delivers, which `Network.Delivered` turns into a `Ready` (its sender's name, the bot's @name stripped, a group's members) in its slot. The bot may briefly take the chat store's lock (to queue a message or keep context). Unaddressed group messages go to the `OnMessage` hooks here. +- **Reader goroutine.** The Signal client's reader parses each frame and decides "addressed?" without blocking or calling the network, then hands the bot a `bot.Received`, one of a closed set of types (`internal/bot/received.go`): `Incoming`, a message completed in its slot by its `Load` (an addressed one, or any other data message that arrived before the bot's own ID was known); `Chatter`, an unaddressed group message; `GroupChanged`; `Deleted`, a delete or a replacing edit, handled on the spot like `GroupChanged`; and `Happened` for a reaction, never passed to `OnMessage`. A member change, also a `Happened`, comes from the client's member-comparison goroutine through the same handler. The core switches on the type. `Incoming` goes to its chat's mailbox from here, and `Happened` too when an `OnEvent` hook is registered; the only other kinds there are `Outgoing`, a post the bot makes on its own (`Post`), `Reacted`, the bot's reactions (`React`), and `Posted`, a message a feature delivers, which `Network.Delivered` turns into a `Ready` (its sender's name, the bot's @name stripped, a group's members) in its slot. The bot may briefly take the chat store's lock (to queue a message or keep context). Unaddressed group messages go to the `OnMessage` hooks here. - **Worker slots.** A fixed pool of `MAX_CONCURRENCY`. Message handling that may call the network (waiting for the account ID, contacts a message needs, sticker labels, media, the model) runs only in a slot. The contact reloads on connect and on group changes run on their own timer, one at a time, and `listAccounts` on each connection's own goroutine. Until the bot's own ID is known, a message waits for it in a slot, up to 10s. A full pool drops the message with a warning. -- **Per-chat mailbox.** An addressed message, one a feature delivers, or one waiting for the bot's own ID joins its chat's mailbox (`chats.Store.Post`, generic over what it holds, so chats needn't know the bot's type); at most 4 wait, and more are dropped with a warning. One deleted, or replaced by an edit, before its turn is skipped (see Edits and deletes). A chat with work has one worker, holding one slot, which takes everything waiting at once, handles it in order, and exits when nothing is left, so each answer sees the ones before it. Different chats run in parallel. +- **Per-chat mailbox.** An addressed message, one a feature delivers, or one waiting for the bot's own ID joins its chat's mailbox (`chats.Store.Post`, generic over what it holds, so chats needn't know the bot's type); at most 4 wait, and more are dropped with a warning that says what was dropped (a message, a post or reactions). The bot's own reactions wait at low priority: those for one chat are merged into one item, handled after everything else waiting, and dropped first, with a warning, when a message needs their place, so they never cost an addressed message its place. One deleted, or replaced by an edit, before its turn is skipped (see Edits and deletes). A chat with work has one worker, holding one slot, which takes everything waiting at once, handles it in order, and exits when nothing is left, so each answer sees the ones before it. Different chats run in parallel. - **Answered together.** Messages that arrive while the worker is busy are answered as one turn, a line each (in a group with the sender's name), so "actually" and "forget it" get one reply that sees both. On its own, in order, goes a message a hook acts on (such as a command), a delivered one, and one that waited for the bot's ID and was not addressed after all; a run is split where it would carry more than 4 images or a second sticker. A panic loses only the message or turn that caused it, and once shutdown begins nothing more that waited starts, not even its hooks. - **Per-chat state.** One struct per chat (`internal/chats`), in one capped map: the history and its expiry timer, recent message keys (for dedupe), mention names, the tool groups' follow-up counts, the cuts of deleted or edited messages (at most 64, kept while anything waits), and the mailbox. One lock guards the whole map and is held only to read or change it, never across a model call. The struct is deleted, or evicted when the map is full, only once its mailbox is empty and no worker is active, so a chat never gets a second worker. - **HTTP.** The model client keeps up to `MAX_CONCURRENCY` idle connections (Go's default is 2 per host). @@ -90,11 +90,12 @@ internal/features/* one package per feature internal/kit/* code with two or more users and no bot knowledge internal/arch/ the guardrail tests and the sizes report cmd/signalctl/ a small client for signal-cli's daemon socket, for one-off chores such as blocking; not part of the bot +cmd/geoguess/ GeoGuess, an MCP addon the bot can run as a child process (its own README); not part of the bot, and of the bot's packages it imports only internal/kit ``` - Core packages are concrete and call each other directly, with no interfaces between them. Files by role, no line limit. - **The network seam.** The bot reaches its chat network only through `bot.Network`; `*signal.Client` and `*telegram.Client` implement it, one process runs one (`TELEGRAM_BOT_TOKEN` set chooses Telegram, and `SIGNALCLI_SOCKET` set too is an error), only main imports them, and the interface exists for the bot's in-memory test fake. The network depends on the core, never the reverse: `internal/signal` imports `internal/bot` for `Received`, which sits next to `Network`. The core's prompt names no network: Signal's line, that a long message shows only its start until Read more, comes from `Network.Prompt`, and the golden prompts pin it. -- **`bot.Received`** is what the network hands the core, and what a chat's mailbox holds: one of the kinds above, `Told`, or `Posted`, a message a feature delivers. Features never see one, so it isn't in `internal/feature`. `Network.Delivered(ctx, msg)` returns a `Ready` and ok: the message with its sender's name and without the bot's @name, `Mentioned` if that was there, and in a group its `Members` (name and ID), which the core claims into the names a post links. +- **`bot.Received`** is what the network hands the core, and what a chat's mailbox holds: one of the kinds above, `Outgoing`, `Reacted`, or `Posted`, a message a feature delivers. Features never see one, so it isn't in `internal/feature`. `Network.Reachable(ctx, chat)` says, in the chat's slot, whether the bot may still post there on its own: on Signal, a group it is still a member of (`listGroups`) or the DM of someone still in `SIGNAL_DM_USER_IDS`; on Telegram, a group that passes the `TELEGRAM_DM_USER_IDS` member check, or a listed user's DM. `Network.Delivered(ctx, msg)` returns a `Ready` and ok: the message with its sender's name and without the bot's @name, `Mentioned` if that was there, and in a group its `Members` (name and ID), which the core claims into the names a post links. - **`Send` returns what it sent.** It waits for signal-cli's answer to each `send` (up to a minute; attachments take longer) and returns the messages' timestamps, which the core keeps with the reply in history so a delete from the account's linked device can find it. A reply is added to history before it is sent, holding a placeholder ref, and `chats.Store.Retag` swaps in the timestamps once `Send` returns, so a message that arrives while the send is out lands after the turn in history, not before it; a recipient it wasn't delivered to is logged as each send returns. - **Why `Send` takes the names to link.** The chat's `@Name`-to-ID map is per-chat state, so it lives in `internal/chats` with the rest: learned from the names the model was shown, cleared on a group change, gone when the history goes, and with one rule for a name two people claim (`chats.Claim`). The network keeps no per-chat state, and only the core knows which map a send needs: the chat's for a reply, the group's members for a delivered post. So `Send` takes it as an argument rather than the network keeping a copy. - **Why the caption rule is the core's.** When a reply's pictures have captions, the core sends those in place of the model's text, and history keeps only the pictures' notes. It decides what history keeps, which is core state, and it happens after the model answers, where no port reaches; a feature doing it would need a fourth stage for this alone. `Picture.Caption` is generic (any tool's picture may have one), so the rule stays a few lines in the core. @@ -108,7 +109,7 @@ The core's lifecycle has three stages. Each port is one stage; nothing else is a | Stage | Port | Returns | |---|---|---| -| A message arrives | `OnMessage(func(ctx, Message) Action)` | carry on, answer with text without the model, choose a tool, or keep text as context | +| A message arrives | `OnMessage(func(ctx, Message) Action)` | carry on, answer with text or pictures without the model, choose a tool, keep text as context, or mark it done | | The model is asked | `OnTurn(func(ctx, Message) Additions)`, plus `OfferTools(ToolGroup)` | a note on the message (with its own version for history), and images | | Time arrives | `At` ([Timers](#timers)) | nothing: the timer may deliver a message | | Something besides a message happens | `OnEvent(func(ctx, Event) string)` | a reply to send to the chat, without the model, or "" | @@ -116,7 +117,7 @@ The core's lifecycle has three stages. Each port is one stage; nothing else is a **Hook rules:** - Hooks run in feature order (`features.go`). - For an unaddressed message, `OnMessage` runs on the reader goroutine, so it must not block or call the network. For an addressed or delivered one it runs in the message's slot. The first non-zero `Action` wins. -- `Answer` and `ToolChoice` count only on an addressed message, and `Context` only on an unaddressed one. +- `Answer`, `Pictures`, `OnSent` and `ToolChoice` count only on an addressed message, and `Context` only on an unaddressed one. `Done` counts on both: the hook handled the message, so it gets no answer and no model; an unaddressed one is kept nowhere, even with a `Context`, and later hooks never see it. An `Answer` and `Pictures` are sent together, with the caption rule as for a tool's pictures, and `OnSent`, if set, is called with the timestamps of the messages they went out in. Nothing of them is kept in history. - An `Event` is a reaction (its emoji, whether it was taken back, who wrote the message and when, and whether that was the bot) or a change in a group's members (who joined, who left, or that the bot was added), with who did it. The network decides which reach the core, as for messages: never the bot's own, in a DM only an allowed sender's, member changes only in groups. With no `OnEvent` hook the core drops events as they arrive. Otherwise each goes into its chat's mailbox and runs on a slot of its own, so a hook may block or call the network: a reaction in order with that chat's messages, a member change once the network has worked it out, which can be after messages that came later (below); the first non-empty reply is sent with `@Name` linked to the chat's known names and the event's people. Events are never logged, kept in history or shown to the model. - **Member changes on Signal:** signal-cli's group `UPDATE` says only that something changed, so the client keeps each group's members from `listGroups`, loaded once the bot's ID is known, and on an update reloads them and compares, only when the core has an `OnEvent` hook (`Network.Watch`). Updates are folded and spaced like the contact list, at most one load per 15 seconds after a contact load, so a member change can reach features after messages read later. Members already there at startup are never reported; a group the bot wasn't in is `BotAdded`; a change of name or description alone is no event. The bot's own update (from its linked phone) refreshes the members it compares with but reaches no feature. `By` is whoever sent the update, or empty when several people's updates were folded together. Each comparison updates only the groups it compares, and one whose `listGroups` call fails keeps its updates for the next. - `OnTurn` runs only when the model is about to be asked. @@ -136,14 +137,16 @@ The core's lifecycle has three stages. Each port is one stage; nothing else is a - anything else the bot posts as written, with @Name linked against the group's members (never an ambiguous name), and history keeps it as the sender's message, ": ", not as something the bot chose to say. These rules are what "as if its sender had just posted it" means for any feature, not just `/schedule`, so the host applies them rather than each feature. The membership check calls the network, so it runs in the message's slot; a feature's timer callback has no slot to make that call in. -- `Tell(user, text)`: the bot sends `text` to a user in their DM, as written, never through the model, through that chat's mailbox; in the slot the user must still be in `SIGNAL_DM_USER_IDS` (checked as for a delivered DM). Nothing is kept in history. `/schedule` uses it to say a one-off was dropped. +- `Post(Post)`: the bot posts `Text`, with any `Pictures` (the caption rule applies), to a group or a DM, as written, never through the model, through that chat's mailbox. In the slot, `Network.Reachable` must say the bot may still post there, or it is dropped and logged at info. `@Name` is linked against the chat's known names. With a `Label`, history keeps the post as the bot's own entry, `[Label] text` (the pictures' notes in place of text they replaced), clamped to 500 characters, so a feature's text can never pose as a person; with none, or with no model, nothing is kept. `Done`, if set, is called once, with the timestamps sent, or with dropped set when it never goes out (a full mailbox, an unreachable chat, shutdown). `/schedule` uses it, with no label, to tell an owner in their DM that a one-off was dropped. +- `React(chat, msg, emoji)`: the bot puts `emoji` on `msg`, through the chat's mailbox at low priority (see the per-chat mailbox): a later reaction to the same message replaces a waiting one, at most 16 wait per chat, and one to a message deleted or replaced by an edit since is skipped. - `Groups(ctx, user)`: the groups the bot shares with a user, with their names (`listGroups`). - `Redact(text)`: text with every name and ID the bot knows for anyone but itself, and any UUID or phone number, replaced with "redacted", for logging text the bot doesn't control (a local MCP server's output). - `Go(fn)`: run `fn` for as long as the bot runs. Its ctx ends when the bot stops, which then waits for `fn` to return (MCP stops its local servers this way). **Types**, each field being a stage's natural input or output: ```go -type Action struct{ Answer, ToolChoice, Context string } // zero value: carry on +type Action struct{ Answer string; Pictures []Picture; OnSent func(sent []int64); ToolChoice, Context string; Done bool } // IsZero: carry on +type Post struct{ Chat Chat; Label, Text string; Pictures []Picture; Done func(sent []int64, dropped bool) } type Additions struct{ Note, HistoryNote string; Images []string; Files []File } type File struct{ Name, MIME string; Data []byte } type Picture struct{ Data []byte; Caption, HistoryNote string } @@ -210,29 +213,43 @@ In `features.go` order, which is the order hooks run in and of the tools line an |---|---| | `example` | `Command`, `Info` | | `websearch` | `OfferTools`, `Info` | -| `groupctx` | `OnMessage` returning `Context` | | `vision` | `OnTurn`, `Info`, `Media` | | `files` | `OnTurn` returning `Files`, `Info`, `Media` | | `links` | `OnTurn` returning `Note` and `Files`, `Info` | | `charts` | `OfferTools` with `Keywords` | | `imagegen` | `OfferTools` with `Keywords`, `CallAPI`, `Info` | -| `mcp` | `OfferTools` (one group per server), `Command` returning `ToolChoice`, `Info`, `Redact`, `Go` | -| `schedule` | `Command`, `ListCommands`, `IntroLineDM`, `At`, `Deliver`, `Tell`, `Groups`, `Info`, `Store` | +| `mcp` | `OfferTools` (one group per server), `Command` returning `ToolChoice`, or `Answer` and `Pictures` for an addon's direct command, `ListCommands`, `OnMessage` returning `Done` (or `Answer`, for a guard), `Post`, `React`, `Info`, `Redact`, `Store`, `Go` | +| `groupctx` | `OnMessage` returning `Context` | +| `schedule` | `Command`, `ListCommands`, `IntroLineDM`, `At`, `Deliver`, `Post`, `Groups`, `Info`, `Store` | - **`intro`** answers `/intro`, and its alias `/help`, itself, never through the model, with the bot's introduction: `INTRO` with `{name}`, `{model}` (or "no model"), `{tools}` and `{more}` filled in by the core (`Info.IntroDM` in a DM, `Info.Intro` in a group), the same text the model gives when asked to introduce itself, followed by "This message did not use the model." (left out with no model, where it goes without saying) The tool labels are Markdown, so they arrive in bold. It leaves no history. `/intro` or `/help` with anything after it carries on as a normal message. - **`websearch`** offers OpenRouter's server-side web search tool (`openrouter:web_search`), which the model calls only when it decides to, unless `MODEL_SEARCH` is off. Its `System` line asks the model to cite the sites it used by url. It logs "web search on" only when the core kept the tool: on another API the core leaves it out and warns ([Capabilities](#the-core)), and with no model nothing is offered or logged. -- **`groupctx`** (`GROUP_CONTEXT`, on by default) keeps each unaddressed group message as context: `Name: text`, capped at 2,000 characters, with photos, stickers and files noted as `[image]`, `[sticker]` and `[file "name"]` but never fetched. The core keeps it like any history entry, marked as context, and never logs it. - **`vision`** adds a message's images (and a quoted message's: the originals if the network still has them, else Signal's thumbnails; on Signal the adapter keeps the pictures the bot sent, up to a day and 32 MB, under IDs `sent::` that `Media` serves itself, as signal-cli has no copy of what it sent), up to 4 and 12 MB each, fetched with `getAttachment`. One over the model's 5 MB becomes a JPEG: turned upright by its EXIF orientation, shrunk by averaging blocks of pixels to at most 2,048 a side, on white. Only one is shrunk at a time, and one that would decode to over 64 MB (about 21 megapixels of JPEG) is refused, so a photo takes tens of MB, not hundreds, under the unit's 512 MB. and its sticker, fetched with `getSticker` and labelled with its emoji and pack title from `listStickerPacks` (quoted, since anyone can make a pack). If the model takes images they go as image parts; otherwise the model is told it can't see them, and a sticker still gets its label. One that can't be fetched or shrunk is left out, logged, and noted as one that couldn't be fetched ("you can see images, just not this one"), so the model doesn't claim it can't see images. Each image or sticker is logged by size, the size sent if it was shrunk, and the time taken, or that the model can't see images. So a photo or sticker alone is answered in a DM or a reply to the bot. History keeps only a note, ending as files' and links' do (`feature.NotKept`): "it isn't kept, so to see it again they must reply to the message with it and mention you". - **`files`** handles each `Media` with `File` set, fetched with `getAttachment`, by its content, extension and declared type. A PDF (`%PDF-`) goes to the model as a `File` when `Info.PDFs`, which the model client sends as a `file` part; on OpenRouter, for a model whose list entry lacks `file`, the request also names the `file-parser` plugin with the `mistral-ocr` engine, named rather than left to OpenRouter's default so what is billed is predictable. Audio goes as an `input_audio` part (format from its type, such as `aac` for Signal's voice notes) when `Info.Audio`. Text (valid UTF-8, no NUL, by type or extension) and docx, xlsx and pptx (text extracted with `archive/zip` and `encoding/xml`; a file is refused before its directory is built if its end record declares over 20,000 entries, each part is read to at most 10 MB and all parts to 32 MB together, past which the text read so far stands, cut, so a deck heavy with shapes is read as far as it goes, and its note says "only the first part of its text is shown, as the file is too big to read whole"; a sheet is headed with its name from `xl/workbook.xml` and its relationships (`Sheet "Budget":`, made one line and cut to 40 characters), else `Sheet N:`; and elements nested past 256 deep, which the decoder keeps a stack of, stop the read) are shown inline in a Markdown fence longer than any backticks in them, capped at 50,000 characters. A file's note says "attached; its text follows" when its text is shown; anything else is noted as one that "can't be read", or one that "couldn't be fetched" or "is no longer available". Each outcome is a value (`outcome`) that builds the whole note, and what history keeps, in one place. Each file is logged by kind and size with what the model got (how many characters of text, a PDF or audio attached, or why not), never its name or declared type; an Office file past the cap is logged as "first 50000 chars of text", since extraction stops there and the document's length is unknown; an Office file that can't be read is logged by the kind of error only (`not a zip`, `missing part`, `bad xml`, `no text`, `too many parts`, `too deep`, `too much xml`, `unreadable`), since the XML decoder's messages quote the document. The core sends at most 16 MB of files with one message, in order (`maxFileBytes`): each goes as base64 in a JSON request, copied a few times on the way, so several large files stay inside the bot's memory; any left out are noted for the model. Names come from the sender, so they are made safe and quoted. History keeps only the notes: for a file the model was shown, `[file "name" was shown to you; it isn't kept, so to see it again they must reply to the message with it and mention you]`. OpenRouter's `annotations` on a reply (such as a parsed PDF) are sent back with it in later tool rounds, so the PDF isn't parsed again within the reply. Each request of a reply is logged at debug level, `request 2: tokens in/out 8120/40, $0.0013, annotations returned: no, sent back: yes, server tools used: no`, with no content (`server tools used` says whether a server tool, such as OpenRouter's web search, ran for that request, seen from a `url_citation` annotation or a use counted in its `server_tool_use`, as a server tool runs on the provider's side and gets no tool line), so the journal shows whether that holds: a later round's cost should be its tokens only, not another ~$0.002 a page. - **`links`** fetches the http and https URLs in the addressed message, then in its quote unless the quote is the bot's own (the model's words), at most 5 a turn (sentence punctuation and unbalanced brackets trimmed, fragments dropped, a URL ending at white space or any Unicode separator, control or format character, any with a user name or password skipped), so only URLs a person sent are ever requested, never one the model or a page names. Only ports 80 and 443 are fetched, on redirects too, so the bot can't be pointed at another service on a host. A link that looks private or one-time isn't requested, and neither is a redirect to one: a query parameter named (lowercased, without - or _) token, accesstoken, authtoken, key, apikey, secret, password, passwd, pwd, sig, signature, otp, sessionid or jwt, or ending in signature or token; or a whole path segment that is unsubscribe, confirm, verify, verification, reset, magic, activate, delete, remove, approve, webhook, webhooks or trigger. Words common in ordinary links (code, session, hash, hooks) and pages harmless to open signed out, as the bot always is (login, logout, oauth), are left out, to avoid skipping ordinary pages. A GET that spends someone's reset, confirmation or unsubscribe link, or sets off a webhook, is the bot carrying out an action for whoever posted it, so these are noted for the model instead. Distinct links past the fifth get one note to the model, not history (which keeps the message, URLs and all), `[1 more link not opened: the bot reads at most 5 a message; send it on its own to have it read]`, and one log line counting them. Each chat can have 20 links fetched an hour, counted in memory by time only, never URL, and forgotten after an hour idle; past that a link's note says `not fetched: this chat has had its 20 links for the hour; links can be read again in about N minutes`, the time until the oldest of them is an hour old, and the log `link not fetched: this chat reached its 20 links an hour`. Its own HTTP client: no proxy; TLS 1.2 or later; 15s in all; at most 3 redirects, each to http or https; the user agent `signalbot (+https://github.com/robdevops/signalbot)`, which names the bot, never the person. HTML is read as a stream of tokens (`html.Tokenizer`), never built into a tree, each text token cut to what the cap can still use, and reading stops at twice the text cap, so a huge page takes little memory. When a redirect changed the URL, the note names where it ended up (`[page , redirected to `), cut to 200 characters and without any user name or password, since the redirecting server chose it. Its dialer's `Control` refuses any address that isn't public, after DNS and for every connection attempt and redirect: unmapped first, it must be global unicast and outside private, shared, loopback, link-local (169.254.169.254 included), documentation, benchmarking, multicast and reserved ranges and the IPv6 ranges that can carry IPv4 (IPv4-compatible and -translated, NAT64, 6to4, Teredo). A page is read to 5 MB (a PDF to 12 MB) and converted to UTF-8 from its declared charset. HTML becomes its title and its text, a line per block, with scripts, navigation, headers, footers, asides and forms left out: the text of its first `article` or `main` element (nested ones included) if that has 200 characters or more, so menus and sidebars of plain `div`s don't crowd out the content, else the whole page's; plain text and JSON are shown as they are; both in a fence, capped at 15,000 characters. A PDF goes to the model as a `File`, like an attached one. Anything else is noted as one that "can't be read", and an error status, a timeout or a refused address as one that "couldn't be fetched", with the reason; a status is said in plain words with its number (401 or 403 "the site refused the request (403); it may need signing in or block bots", 404 or 410 "the page wasn't found (404)", 429 "the site is limiting requests (429); try again later", 5xx "the site had an error (503)", else "the site answered with status N"), the same in the log. Each outcome is a value (`outcome`) that builds the whole note, and what history keeps, in one place. Each link gets one log line: its time, size, its kind (from a fixed list, never the server's own media type) and what came of it (how many characters of text and whether from an `article`, a `main` or the whole page; a PDF attached; no readable text; or why it failed or wasn't fetched), never the URL, title or text. History keeps "[page was shown to you; it isn't kept, so to see it again they must reply to the message with it and mention you]" (`feature.NotKept`, the same ending files and images use). The package's own tests let the dialer reach loopback through an unexported variable; nothing outside it can. - **`charts`** offers `make_chart` and `make_pie_chart` when a message asks for a chart (chart, graph, plot, visualise/visualize, pie, donut and their forms) or for what a line chart shows (projection, forward estimate, trending, forecast and their forms). `make_chart` draws line charts of up to 6 series on one Y axis, set by a top-level `y_axis` (an axis given as just its title, `"y_axis": "…"` or `"axes": {"label": "…"}`, is taken as meant), and refuses a right axis, saying to use change mode for series on different scales. A second axis is only on request: `make_dual_axis_chart`, the same chart with a left and a right Y axis, is a tool group of its own (no `Names`, so the intro is unchanged), offered only when a message asks for one (second, secondary, dual, two, right-hand… axis or axes), and for the replies that follow. Each axis has its own mode (values as given, the default, or % change from each series' first point, for comparing series on different scales such as two stocks), unit, title and optional inversion, and in value mode `show_change`, on unless the model sets it false, which labels each line's last value with its % change from its first point, computed by the bot (nothing from a start of 0 or less). It is on by default because models leave optional settings unset (off by default, it never appeared); the model turns it off where a % change means nothing, such as temperatures, rates or values already in %; a single series is an area, green if it ends up and red if down, with its high, low and current value marked, the change on a line of its own beneath the value; its subtitle is drawn in the line's colour, led by the change with an arrow (`▼ 15.2%`), and the caption is the title with that change in place of the subtitle. An axis sent as a string holding its JSON is decoded as the axis, not taken for a title. `make_pie_chart` draws 2–12 shares of a total as a ring (its description still says donut), largest first, the legend giving each amount and the centre the total, both shortened (K, M, B, T) by the bot; a unit or suffix over 4 characters (such as a word) is dropped rather than cut. Both take an optional `source` (where the data came from, trimmed and capped at 80 characters), written as "Source: …" small and muted at the bottom left and cut with "…" to the chart's width, in a band below the date labels and the legend, whose row gaps shrink to stay above it (and if that is not enough, the smallest slices' labels go back to one line, cut before their amount); it is not in the caption. Charts are 1280×800 PNGs on white (at most 256 colours: anti-aliased shades are grouped and the theme's colours kept exact, for about a third the size), or with `DARKMODE` on (or `true`, `yes`, `1`, `dark`; off is also `false`, `no`, `0`, `light`) in a dark theme (near-black navy, light text, a lighter palette); a range of times (`18:00-6:00`, `18-6`, `6pm-6am`) is dark from its start up to its end, local time (`TZ`), wrapping midnight when the end is earlier, decided as each chart is drawn, and any other value is off with a warning at startup. A reply with a chart is the chart alone, captioned with its title (and subtitle, if both fit on one line) in place of the model's text; history notes it by caption. Arguments sent as a string holding their JSON, whole or for one field (such as `axes` or one series' `points`), are taken as meant, as smaller models often send them; any other mistake is named back to the model, with how to fix it, so it can correct its call. - **`imagegen`** offers `make_image` when a message asks for a picture (draw, sketch, doodle, paint, illustrate, art, diagram, image, picture, pic, photo, photorealistic, logo, icon, poster, banner, graphic, meme, avatar, pfp, sticker, selfie, cartoon, comic, portrait, wallpaper, render, watercolour, anime, clip art, infographic, mock-up, cutaway, cross-section, schematic, exploded view, blueprint, flowchart, org chart, gantt, mind map, visualise and their forms), if `Info.Provider` is `openrouter` and `IMAGE_MODEL` isn't off. The model writes the full prompt, an aspect ratio of seven (1:1 by default), a title for the file name, and a `kind`: `technical` (a diagram, cutaway, schematic, infographic, labelled or educational picture) or `artistic`. For `technical` it also lists up to 12 `requirements`, the facts the picture must get right, worked out before it writes the prompt, and the prompt the image model gets is a fixed brief (a teaching picture that must be accurate, in the style asked for, else a rich infographic: bold title, detailed main illustration, colour-coded sections, icons, callouts with the given facts and figures, a legend) then the model's prompt, the requirements as must-haves, and rules for text (only the words given, labels, title or caption, spelled exactly, short and legible; no invented numbers; arrows exactly as described); an `artistic` prompt goes unchanged; the feature posts the request to `/images` itself through `CallAPI` (one PNG, `n` 1) with `IMAGE_MODEL` (default `openai/gpt-image-2`) at `IMAGE_QUALITY` (default `medium`; anything but low, medium, high or auto stops the bot), goes through `img.Fit`, and is sent with the model's words, no caption. History notes `[sent a picture made from the prompt: …]`, up to 400 characters of it; a technical one `[sent a technical picture made from the prompt: …]`, up to 1,200, and its requirements, so a follow-up ("add the other planets") keeps them: the description tells the model to start a change from that note, keeping the kind and every requirement. A failure tells the model in a few fixed words (refused under the content policy, out of credit, rate-limited, too slow, or failed), never the API's text. -- **`mcp`** (`MCP_CONFIG`; `${NAME}` in a server's `url`, `headers`, `args` or `env` is the bot's environment variable `NAME`, filled in at startup, and one that isn't set is a startup error naming the variable, never its value) connects to MCP servers: remote ones (`url`, `headers`) over Streamable HTTP (JSON or server-sent events, with the session re-established if the server forgets it) and local ones (`command`, `args`, `env`) over stdio (restarted with backoff if they exit, given only `PATH`, `HOME` and their `env`, and stopped when the bot stops; each line a local server writes to stderr is logged at debug only after `Redact`). It identifies itself in the handshake as `signalbot` with the bot's version (`Info.Version`, or `dev`). A server with `disabled` is skipped unchecked; one that can't be reached is logged and left out. At startup it logs each server's tools, one line per server (" MCP: …", the server's name alone when it already says MCP, as in the intro), and the chat commands ("chat commands: …"). +- **`mcp`** (`MCP_CONFIG`; `${NAME}` in a server's `url`, `headers`, `args` or `env` is the bot's environment variable `NAME`, filled in at startup, and one that isn't set is a startup error naming the variable, never its value) connects to MCP servers: remote ones (`url`, `headers`) over Streamable HTTP (JSON or server-sent events, with the session re-established if the server forgets it) and local ones (`command`, `args`, `env`) over stdio (restarted with backoff if they exit, given only `PATH`, `HOME` and their `env`, run in a process group of their own, and stopped when the bot stops: stdin closed, then SIGTERM to the group after 2s, then SIGKILL after 2s more, and the group killed once the server exits, so whatever it started stops too; a line over 4 MiB on stdout gets the server killed, with a warning, and restarted; stderr is read in pieces, and each line a plain server writes there is logged at debug, cut to 4 KB, only after `Redact`). It identifies itself in the handshake as `signalbot` with the bot's version (`Info.Version`, or `dev`), and offers signalbot's addon extension (below) under `capabilities.experimental`. A server with `disabled` is skipped unchecked; one that can't be reached is logged and left out. At startup it logs each server's tools, one line per server (" MCP: …", the server's name alone when it already says MCP, as in the intro), and the chat commands ("chat commands: …"). - Each server is one tool group, listed as `server: tool, …, /command`. In the intro's `{tools}` and the prompt's `If asked what tools you have:` list its label is `**server MCP**: tool, …, /command`, without the added ` MCP` when the server's name already contains MCP in any case. `allowed_tools` or `blocked_tools` decide its tools (a name in either that the server lacks stops the bot), named `server__tool` for the model. `instructions` is its system-prompt line while offered: the config's if set (even to `""`), otherwise the `instructions` the server sent in the MCP handshake, capped at 1,000 characters. `keywords` (whole words, any case) gate it like the chart tools. - - Each call has 30s (past that the model is told "the tool didn't answer within 30s; try a narrower request or later") and its text result is capped at 16K characters; images in a result are sent with the reply, up to 4. Tool results are untrusted input to the model, like a quote. Only the question and the final answer go into history; arguments and results are never logged. - - `chat_commands` make `/name text` a turn in which that `tool` is added to whatever else is offered and must be called first; with `require_arg`, a bare `/name` is answered by the bot, "Put what you want after it, like /name . Or just ask me in plain words.", with `Try: .` before the last sentence when the command has an `example`. A command whose name is invalid or taken (the warning gives the reason), or whose tool isn't offered, is skipped with a warning; none is registered when the model can't call tools. A server's group adds one entry to `{tools}`, grouped by server: its name in bold, a colon, then its tools and its own `/commands`, sorted, such as `**weather**: get_forecast, /forecast`. The tools line lists it as `weather: get_forecast, /forecast`. - - With no model it connects to no server and warns "MCP_CONFIG is set but no model is configured, so MCP servers were not started". - - Config errors stop the bot, each starting with the file's path and naming the server: a key that is neither a setting nor one other clients write (`type`, `transport`, `timeout`, `alwaysAllow`, `autoApprove`, `description`, ignored), with the settings listed, in a server or a chat command; both `allowed_tools` and `blocked_tools`; a tool name the server lacks, with the list it is in and the server's tools (the first 20, then "…"); and two tools that become one name for the model, naming both. + - Each call has 30s (past that the model is told "the tool didn't answer within 30s; try a narrower request or later") and its text result is capped at 16K characters; images in a result are sent with the reply, up to 4, each through `img.Safe` first (below). Tool results are untrusted input to the model, like a quote. Only the question and the final answer go into history; arguments and results are never logged. + - `chat_commands` make `/name text` a turn in which that `tool` is added to whatever else is offered and must be called first; with `require_arg`, a bare `/name` is answered by the bot, "Put what you want after it, like /name . Or just ask me in plain words.", with `Try: .` before the last sentence when the command has an `example`. A command whose name is invalid or taken (the warning gives the reason), or whose tool isn't offered, is skipped with a warning; when the model can't call tools only an addon's `direct` commands are registered. A server's group adds one entry to `{tools}`, grouped by server: its name in bold, a colon, then its tools and its own `/commands`, sorted, such as `**weather**: get_forecast, /forecast`. The tools line lists it as `weather: get_forecast, /forecast`. + - With no model it starts only addon servers, offers no tools, and warns "MCP_CONFIG is set but no model is configured, so only addon servers were started". + - Config errors stop the bot, each starting with the file's path and naming the server: a key that is neither a setting nor one other clients write (`type`, `transport`, `timeout`, `alwaysAllow`, `autoApprove`, `description`, ignored), with the settings listed, in a server or a chat command; both `allowed_tools` and `blocked_tools`; a tool name the server lacks, with the list it is in and the server's tools (the first 20, then "…"); and two tools that become one name for the model, naming both. An addon server adds its own (below). + - Tools are filtered by `_meta`: a tool whose `io.github.robdevops.signalbot/visibility` array, or MCP Apps' `ui.visibility`, leaves out `"model"` is never offered to the model, nor listed in `{tools}` or the tools line. A missing array means the model may see it. The bot calls a tool itself (an addon's direct command or watch) only if signalbot's array has `"bot"`; MCP Apps' `"app"` means a UI, not the bot. + - **`img.Safe`** (`kit/img`) checks any image from a server before it is sent: only PNG, JPEG, GIF or WebP, read from the header alone, at most 8,192 pixels a side and 40 megapixels, so a small file claiming a huge canvas never reaches phones; a JPEG loses its EXIF (keeping its orientation), XMP, IPTC, comments and anything after the image, by walking its segments without decoding pixels, since signal-cli sends attachments as they are and GPS tags would say where a photo was taken. +- **Addons** are local MCP servers with an `addon` block in `MCP_CONFIG` that also advertise `io.github.robdevops.signalbot/addon` at version 1 in their `initialize` result's `capabilities.experimental`. One with the block that doesn't advertise it runs as a plain server, with a warning. They are part of `mcp`: no port of the core names them. + - **Config:** the block's keys are `chats` (group IDs exactly as Signal or Telegram shows them, a Telegram topic counting as its group, or `["all"]` alone; anything else is an error asking for the group's ID), `dms`, `post`, `react`, `watch` (each off unless set), `watch_max` (1s to 24h, default 1h), `names`, `global_ids` and `rate` (`per_minute`, default 20, and `burst`, default 5). Unknown keys get the same error as a server's. An addon must be local (`command`), can't have an `env` block, and its server's name can't make a prefix (below) that one of the bot's own settings starts with (the names in `docs/CONFIGURATION.md`'s table, plus `STATE_DIRECTORY`, a list a test keeps in step); a `direct` chat command without an addon block is an error. Its error text and its start, initialize and call failures are logged by code only, never the server's words. + - **Environment:** an addon gets `PATH`, `HOME`, those of `TZ`, `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` (and their lowercase forms), `SSL_CERT_FILE` and `SSL_CERT_DIR` that are set, so it keeps the bot's time zone and reaches the internet as the bot does, and every variable of the bot's environment that starts with its prefix: its server's name in capitals, anything but letters and digits as `_`, then `_` (`geo` gets `GEO_…`). Nothing else, so the bot's keys never reach it. These are read with `os.Environ`, not `Env`, so each addon documents its own. + - **Stderr:** an addon's is never logged, since it may write what it was sent: only "addon wrote N lines (M bytes) to stderr", at most once a minute, and once more when it exits for what was counted since, so a crash's output is never left uncounted. + - **The store:** with any addon configured, `mcp` opens its `Store` (`mcp`, `mcp.json`), so MCP without addons needs no state directory. It holds a 32-byte random secret, made once, and each addon's state (below). If the store can't be opened, or the secret read or saved, addons run as plain servers, with an error at startup, rather than with a new secret that would change every pseudonym. A damaged secret is an error too. One saver goroutine writes the document whenever told something changed (a non-blocking send on a 1-buffered channel), and once at shutdown, so a hook never waits on the disk and a burst is one write; a failed save is logged once, the state stays in memory, and the next change tries again. The state of a server no longer configured as an addon is dropped at the first save. + - **Pseudonyms:** an addon never sees a phone number, account ID or group ID. Each addon has its own key, HMAC-SHA256 of the secret and its server's name. A chat is `c_` and HMAC(key, `chat\0` + chat key); a sender `u_` and HMAC(key, `user\0` + chat key + `\0` + ID), so the same person is someone else in each chat, or with `global_ids` HMAC(key, `user\0` + ID), the same everywhere; each cut to 128 bits and written in lowercase base32. A ref, `r_` and 128 random bits, names one message, for a reaction, and is kept in memory for 24 hours. + - **Context:** each `tools/call` the bot makes itself carries the message's context in `_meta["io.github.robdevops.signalbot/context"]`: `chat`, `sender`, `ref`, `addressed`, `group`, `sent` and `edited` (when the bot got the message and its edit, in Unix seconds, never the sender's clock; `edited` is 0 for an original), and `name`, the sender's display name, only with `names`. Otherwise the bot keeps, in memory for 24 hours, the last name it saw each pseudonym use in the chat: a `{u_…}` placeholder in an addon's answer or post becomes `@Name`, linked as a mention, or "someone". + - **Direct commands:** a chat command with `direct` makes `/name args` a call the bot makes itself, without the model, to a tool whose visibility has `"bot"` (looked up among all the server's tools; one without it is skipped with a warning), with `{"args": ""}`. It runs in the message's slot, with 15s, and at most 2 at once per server: a third is told " is busy, try again in a moment." at once. The title is the server's `serverInfo.title`, else its name, made safe. In a chat its `chats` or `dms` don't allow, it answers "/name isn't available in this chat.". The result's text parts, joined, become the `Answer` (placeholders filled in, capped at 4,000 characters) and its image parts up to 2 `Pictures`, 2 MB together after `img.Safe` (any left out are counted in a warning); a result with neither is `Done`. An error result, a timeout, a bad result or a server that can't be reached answers "<title> couldn't do that just now.". Each call logs the command, the tool, the outcome (ok, or a code), the time and the result's size. Direct commands are kept with no model or one that can't call tools; a server with no tool for the model lists them with `ListCommands` under its label. + - **Watches:** a direct command's result may ask, in `_meta["io.github.robdevops.signalbot/watch"]`, for a watch on the chat the command came from (the only way to make one, so an addon can't watch a chat it wasn't used in): an `id` (at most 64 bytes), an RE2 `pattern` (at most 1 KB), `until` (RFC 3339, cut to `watch_max` from now and never extended), the `tool` to call with each match (one the bot may call) and an optional `guard` (at most 500 characters). It needs `watch`, and at most 8 are live in a chat per addon (one with the same ID is replaced). A pattern that matches the empty string or any of about 200 ordinary chat lines in `corpus.go` is refused, so no watch is a feed of the chat; a refusal is logged by reason, never the pattern. One `OnMessage` hook, registered after the chat commands, checks each message with text in an allowed chat against the chat's live watches, on both paths: unaddressed ones on the reader goroutine (only a map lookup and the patterns, under a mutex held briefly), addressed ones (a reply to the bot, a DM, an @mention) in their slot. A watch matches any message the bot gets while it lasts, by when the bot got it, not by its `Timestamp` (on Signal the sender's clock, which may be behind); an edit, unless its original was claimed, only if its original's `Timestamp` is at or after the command's, so an older message's edit isn't taken. An addressed message with no text (a bare mention, or a reply with only a picture) is still checked for the guard. A match is `Done`, so it is never answered, sent to the model or kept in history, and `groupctx` never sees it; it is claimed for 48 hours (chat key, sender's pseudonym, sent time), so a later edit of it goes the same way, to the same tool, whether or not the watch is still live; and it is passed without waiting to the addon's watch worker, whose queue holds 256 (when full, "addon <name>: watch queue full, a matched message dropped", still `Done`). The worker calls the watch's tool with `{"text": …}` and the context, within 120 calls a minute per chat (bursts of 20; a match past it waits its turn in the worker's queue, while other chats' matches go ahead), and keeps a match whose call found the server down (not running, or exited before answering) at the head of the queue until the server has started again (or a minute has passed), dropping it with a warning after 3 such calls, and if the result's `_meta["io.github.robdevops.signalbot/react"]` is one emoji, reacts with it (`React`), which needs `react` and counts against the addon's rate. A watch whose command answered with pictures records, through `OnSent`, the timestamps of the messages they went out in; while it lives, an addressed message quoting one of them gets the `guard` as its `Answer`, so nobody can ask the model about the picture. + - **Leases:** an addon may post or react only in a chat where it had a direct command or a watch match in the last 24 hours; the lease maps the chat's pseudonym to the chat. + - **Outbox:** if the server advertises `resources.subscribe`, the bot sends `resources/subscribe` for `signalbot://outbox` after each (re)start's `initialize`, then reads it; otherwise the outbox is off, with a warning. Any `notifications/resources/updated` from the server marks the outbox as having news (whatever the URI, which may be under the one subscribed). One reader goroutine per addon reads `resources/read` of `signalbot://outbox/<cursor>` (`0` at first), page by page while `more` is true, up to 100 pages, so two reads never race and news during a read is read after it. A page is one text content holding `{"cursor", "more", "ops"}`; a not-found error (-32002, or the Go SDK's -32602) is logged as no outbox. Ops are applied once each by `id`, the last 1,000 IDs remembered, and are `post` (`chat`, Markdown `text` with placeholders, up to 2 `images` as `{data, mimeType, name}`, 2 MB together), needing `post`; `react` (`ref`, `emoji`), needing `react`; and `unwatch` (`chat`, `watch`), which, for a watch not yet made, stops it being made for 10 minutes. A post or reaction needs a live lease in a chat the addon is still allowed, and counts against `rate` per chat. A post goes through `Post` with the addon's title as its `Label`, so history keeps it as `[Title] …`, the bot's own words. At most one of an addon's posts waits in a chat's mailbox: until its `Done`, later posts for that chat are held, each merged into the one held before it while their pictures together stay within 2 and 2 MB, and sent in turn. Delivery is at least once: a post counts as applied, and the cursor moves past it, only once its `Done` says it was sent. Until then each read starts from the cursor before it and skips it while it waits; one dropped before it was sent (as while the bot stops, or before the network is up at startup, when `Post` gives up on the chat) is posted again by a read 10s later, then 20s, doubling to 5 minutes, not counted against `rate` again, and given up with a warning after 6 tries. A page with `more` waits for its posts before the next is read, since reading past the cursor lets the addon forget them. A read that fails, is malformed, or stops at 100 pages is tried again after 10s, doubling to 5 minutes, without waiting for news. What a read drops is counted in one warning by reason, never content. + - **What is saved,** per addon, in `mcp.json`: live watches (with their guard pictures' timestamps), claims, leases, the outbox cursor and the last 1,000 applied op IDs. Anything expired is left out. At startup they are restored, leaving out a watch whose chat is no longer allowed or whose pattern no longer passes, so a restart of the bot or the addon never lets a match fall through to history. Refs, names, tombstones and held posts are in memory only. +- **`groupctx`** (`GROUP_CONTEXT`, on by default) comes after `mcp`, so an earlier hook can claim a message (`Done`) before it is kept, and keeps each other unaddressed group message as context: `Name: text`, capped at 2,000 characters, with photos, stickers and files noted as `[image]`, `[sticker]` and `[file "name"]` but never fetched. The core keeps it like any history entry, marked as context, and never logs it. - **`schedule`** is `/schedule` ([below](#schedule)). ### `/schedule` @@ -258,7 +275,7 @@ Arguments that don't start with a quote and aren't a subcommand are answered `I - **The group name** is the rest of the line, so it needs no quotes even with spaces. It is matched among the groups the user shares with the bot, ignoring capitals: an exact match first, otherwise with emoji and symbols removed and extra spaces collapsed on both sides ("family" matches "🏡 Family 🎉"). No match is refused with the list of the user's groups; more than one is refused as ambiguous. - **A schedule keeps the group's ID**, so it survives a rename. If the user has left the group, the core drops that run and logs it; the schedule stays in `/schedule list`, marked as left, until deleted. - **Numbers** are per user and never reused, so `del` of one that has already run says so rather than deleting another. -- **Missed runs:** a repeating run a minute or more late is skipped, and the next is the next time still in the future (after the due time, if the clock went back). A one-off up to an hour late runs; an older one is dropped and logged, and its owner is told in their DM (`Tell`), `I was offline at <when>, so your reminder "<text, at most 80 characters>" didn't post.` A one-off is deleted from the saved file when it comes due. +- **Missed runs:** a repeating run a minute or more late is skipped, and the next is the next time still in the future (after the due time, if the clock went back). A one-off up to an hour late runs; an older one is dropped and logged, and its owner is told in their DM (`Post`), `I was offline at <when>, so your reminder "<text, at most 80 characters>" didn't post.` A one-off is deleted from the saved file when it comes due. - **No loops:** scheduling any of the three commands is refused, even after an @mention of the bot, so a schedule can't make schedules; with the bot ignoring its own posts, a scheduled mention of the bot gets exactly one answer. There is no per-user cap: only users in `SIGNAL_DM_USER_IDS` can schedule. The scheduled text is never logged; the timer's name is "schedule". - **Refusals:** at the timer cap, or if saving fails, the schedule is refused and nothing is kept. At startup, a malformed saved schedule is logged by its position and the field at fault, never its user or text (`schedules.json: entry 4 skipped: bad start; it will be removed at the next save`), and dropped; one that can't be set (at the timer cap) is logged and kept, listed and saved, but doesn't run until the next start. A file that can't be read stops the bot rather than being overwritten. Once a file exists, startup logs "loaded N schedules". - **Saving:** `schedules.json`, the feature's `Store` (`schedules`), in the state directory. Schedules hold the user's ID, the group's ID and name, the time and the text until deleted. The file also keeps, for each user who has scheduled, the last number they were given (`last_id`), so numbers are never reused; it stays after their schedules are deleted (see [PRIVACY.md](PRIVACY.md)). @@ -303,6 +320,7 @@ Only the Bot API, at `TELEGRAM_API_URL`, over HTTPS (TLS 1.3, `kit/httpx`). At s - **Groups:** anyone can add a bot to a group by its username, so the bot answers in a group only while someone in `TELEGRAM_DM_USER_IDS` is a member, by `getChatMember` for each listed ID until one is there. The answer is kept an hour (ten minutes if no, a minute if Telegram couldn't say). It is checked in the background when a group is first seen, so chatter from a stranger's group is dropped once known, and in an addressed message's slot before it is answered. Where no one listed is, the bot leaves (`leaveChat`), at most every ten minutes, so a failed leave is tried again. Added by someone listed, it answers at once. When anyone leaves, it asks again. Reactions and member changes, which come with no slot to check in, go by the last answer even when out of date, and set off a new check; in a group never checked they are dropped. With no one listed, every group is a no. A restricted member counts only with `is_member`, as a restriction outlasts leaving. A forum topic is a chat of its own, `GroupID` `group/topic`, as it is a conversation of its own: replies go to it by `message_thread_id`, and a topic message's `reply_to_message`, the topic's creation, is no quote. A member joining or leaving changes the group and each topic seen in it. A group that becomes a supergroup (`migrate_to_chat_id`) is moved to its new ID, and a send or a membership check at the old one, as after a restart, is told the new ID and goes there. - **Addressed:** in a DM, a sender in `TELEGRAM_DM_USER_IDS`; in a group, a `mention` of the bot's @username, a `text_mention` of it, a reply to one of its messages, or a `bot_command` at the start without another bot's `@suffix`. The mention and the suffix are taken out of the text. An unlisted DM's edit is passed on as a delete of the original, so history never keeps a message the sender couldn't have had answered. - **Message IDs:** `Message.Timestamp` holds Telegram's `message_id`, which reactions, replies and edits name; Telegram's IDs are per chat, as the core's keys are. +- **Locations:** a shared location or venue becomes a Google Maps link (`https://maps.google.com/maps?q=<lat>,<lon>`) on a line before the message's text, as Signal sends one, so features read both networks' the same way; a live location, which follows its sender as they move, is left out. - **Expiry:** the chat's `message_auto_delete_time` from `getChat`, asked once per chat. - **Deletes:** the Bot API never reports them, so history keeps a deleted message until it expires. - **Sending:** Markdown becomes text and `entities` (bold, italic, strikethrough, code, `pre` for a block, spoiler, `text_link` for `[text](url)`, and `text_mention` for a known `@Name`), with offsets in UTF-16 units. A reply is cut at 4,096 units, at a line break or space past halfway, and capped at 8,000 characters in all; if Telegram refuses the entities, the text is sent without them. Pictures go first, by `sendPhoto` or `sendMediaGroup`, with the reply as the caption when it fits in 1,024 (without entities if refused); if the pictures fail, the text goes alone. An emoji Telegram refuses as a reaction (`REACTION_INVALID`) is sent as a message. diff --git a/cmd/geoguess/README.md b/cmd/geoguess/README.md new file mode 100644 index 0000000..945ce4c --- /dev/null +++ b/cmd/geoguess/README.md @@ -0,0 +1,147 @@ +# GeoGuess + +A GeoGuessr-style game for signalbot. `/geo` posts a street-level photo; +players answer by sending a location (Signal's 📎 → Location with the pin +moved, or typed coordinates such as `-37.81, 144.96`); when time is up the +bot names the place and ranks players by how far off they were. + +``` +/geo start a round (GEO_ROUND, default 3 minutes) +/geo 90s | /geo 5m start a round of that length (30s to 30m) +/geo europe a round in a continent or countries (/geo AU,NZ); combines with a length +/geo end finish now and reveal (only the player who started it) +/geo skip cancel and reveal without scoring (only the player who started it) +/geo scores this chat's totals over the last 7 days +``` + +It is a separate program that signalbot starts as an +[MCP addon](../../docs/FILES_LINKS_TOOLS_MCP.md#addons) server. It speaks MCP +2025-06-18 over stdio (newline-delimited JSON-RPC) by hand, with signalbot's +addon extension, and uses no MCP library. It needs no model: its commands and +guesses never reach one. + +## Install + +Build it as a static binary, which the Docker image needs (it has no shell +or runtimes) and systemd is happy with: + +``` +CGO_ENABLED=0 go build -o /opt/signalbot-addons/geoguess ./cmd/geoguess +``` + +Mount it read-only: under Docker, add `- /opt/signalbot-addons:/addons:ro` to +the volumes in `compose.yaml`; under systemd, use the host path, or bind it +with `BindReadOnlyPaths=/opt/signalbot-addons:/addons` in a drop-in. Then add +it to the MCP servers file (`MCP_CONFIG`). The server must be called `geo`, +which is what gives it the `GEO_` settings below: + +```jsonc +"geo": { + "command": "/addons/geoguess", + "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m"}}, + "addon": {"chats": ["<group id>"], "post": true, "react": true, "watch": true, "watch_max": "1h"} +} +``` + +`chats` takes the groups' IDs as Signal or Telegram shows them, or `["all"]`; +add `"dms": true` to play in DMs too. GeoGuess needs `post` (for the results), +`react` (the 📍 on a counted guess) and `watch` (to read guesses). A round +lasts at most 30 minutes, so the default `watch_max` of 1h is enough. + +GeoGuess keeps its own files in `GEO_STATE_DIR`, which you create, writable by +the bot's user, and set in `/etc/signalbot.env`: + +- **systemd:** in a drop-in (`sudo systemctl edit signalbot`), add + `StateDirectory=geoguess` (the unit's `DynamicUser=` makes it and owns it), + and set `GEO_STATE_DIR=/var/lib/geoguess`. +- **Docker:** `sudo install -d -o 65532 -g 65532 -m 700 /var/lib/private/geoguess`, + add `- /var/lib/private/geoguess:/geo` to the volumes, and set + `GEO_STATE_DIR=/geo`. + +It shares the bot's memory limit, so allow for `GEO_MEMLIMIT` in `mem_limit` +or `MemoryMax`. + +## Settings + +signalbot passes an addon server called `geo` every `GEO_` variable from its +environment file, plus `PATH`, `HOME` and, if set, `TZ` (the round's deadline +is written in it), `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, `SSL_CERT_FILE` and +`SSL_CERT_DIR` (so it reaches the photo sources through the bot's proxy, and +trusts its CA), and nothing else. + +| Variable | Default | Description | +|---|---|---| +| `GEO_STATE_DIR` | — (required) | Where GeoGuess keeps `geo.json` and its log. Create it, writable by the bot's user; GeoGuess exits at start if it can't list and write it | +| `GEO_MAPILLARY_TOKEN` | empty | Mapillary client token (`MLY\|…`), sent as `Authorization: OAuth <token>`. Empty means Panoramax only, and then rounds are in France unless `GEO_REGIONS` says otherwise | +| `GEO_MEMLIMIT` | `200MiB` | Memory limit, applied with `debug.SetMemoryLimit`, written as `GOMEMLIMIT` is (`B`, `KiB`, `MiB`, `GiB`, `TiB`) | +| `GEO_ROUND` | `3m` | Default round length, 30s to 30m | +| `GEO_REGIONS` | empty (world) | Continents (`europe`, `asia`, `africa`, `north-america`, `south-america`, `oceania`) or ISO country codes, comma-separated | +| `GEO_MIN_QUALITY` | `0.5` | Minimum Mapillary `quality_score` (0 to 1), when a photo has one | +| `GEO_MAX_AGE_YEARS` | `10` | Ignore older photos | +| `GEO_BUFFER` | `3` | Checked photos kept ready (1 to 20) | +| `GEO_NOMINATIM_URL` | `https://nominatim.openstreetmap.org` | Reverse geocoder for the place names; `https://` only, as it is sent each round's answer | +| `GEO_PANORAMAX_URL` | `https://api.panoramax.xyz` | Panoramax API (a STAC catalogue), such as one instance's; `https://` only | +| `GEO_MAPILLARY_URL` | `https://graph.mapillary.com` | Mapillary Graph API; `https://` only | + +It reaches `graph.mapillary.com` and Mapillary's image CDN, `api.panoramax.xyz` +and the Panoramax instances' image hosts, and the Nominatim server, over +TLS 1.3. + +## Privacy + +GeoGuess gets only what signalbot's addon block allows: the text after +`/geo`, and during a round the messages that look like a location (a map link +or coordinates), each with the chat and sender as pseudonyms and the time the +bot got it. It never sees a phone number, account ID, group ID or, unless +`names` is set, a display name; it writes players as `{u_…}` and the bot puts +their names in. Guesses are claimed by the bot, so they are never answered, +sent to the model or kept in the chat's history. + +What it sends out is about photos, never about players: map areas to search +and photo IDs to Mapillary and Panoramax, and the answer's coordinates to +Nominatim for the place's name, each with the user agent +`geoguess (+https://github.com/robdevops/signalbot)`. + +A guess deleted for everyone afterwards is not passed on to GeoGuess, which +keeps only its distance anyway. + +### What it keeps + +`$GEO_STATE_DIR/geo.json`, rewritten whole on each change: + +- open rounds: the chat's pseudonym, who started it, its deadline, the answer + and its credit, and for each player (a per-chat pseudonym) only how far + their last guess was and when. Where anyone guessed is never kept, in + memory or on disk; +- the keys of the last 1,000 photos used, so none comes round again soon; +- 7 days of points per chat, by player pseudonym; +- outbox ops the bot hasn't read yet, for at most an hour. + +`$GEO_STATE_DIR/geoguess.log` (moved to `geoguess.log.1` past 4 MiB at start) +records rounds started and revealed with their guess counts, photos +rejected by reason, and API errors by status. It never holds a guess, a +coordinate, a place or person's name, a pseudonym or message text. + +## The protocol + +- `initialize` advertises `tools`, `resources.subscribe` and + `experimental["io.github.robdevops.signalbot/addon"] = {"version": 1}`. +- `tools/list` has `geo` (`{args}`) and `geo_guess` (`{text}`), both with + `_meta["io.github.robdevops.signalbot/visibility"] = ["bot"]`, so neither is + offered to the model. +- `tools/call` reads the chat, the sender and the receive times from + `_meta["io.github.robdevops.signalbot/context"]`. Starting a round answers + with the photo, its caption and a `…/watch` for `geo_guess`, until 5s past + the deadline; a recorded guess answers with `…/react: "📍"`. +- When a round's time is up GeoGuess queues a `post` with the results, its + players as `{u_…}` placeholders, and an `unwatch`, and sends + `notifications/resources/updated` for `signalbot://outbox` if subscribed. + `/geo end` and `/geo skip` answer with the results themselves and queue + only the `unwatch`. +- `resources/read` of `signalbot://outbox/<cursor>` returns + `{"cursor", "more", "ops"}`. A cursor is `<boot-nonce>.<seq>`; reading one of + this run lets go of the ops up to it, and any other cursor, such as `0` or + one from before a restart, gets everything still held. Op IDs survive a + restart, so the bot can skip those it already applied. +- On start, rounds still open get their timers back, and those whose time + passed while GeoGuess was down are revealed at once. diff --git a/cmd/geoguess/clock.go b/cmd/geoguess/clock.go new file mode 100644 index 0000000..b6a9b3d --- /dev/null +++ b/cmd/geoguess/clock.go @@ -0,0 +1,19 @@ +package main + +import "time" + +// clock is the time and timers the game runs on: the real ones, or a test's. +type clock interface { + Now() time.Time + // AfterFunc calls f on its own goroutine once d has passed. + AfterFunc(d time.Duration, f func()) stopper +} + +// stopper is a timer that can be stopped before it fires. +type stopper interface{ Stop() bool } + +// realClock is the system's clock. +type realClock struct{} + +func (realClock) Now() time.Time { return time.Now() } +func (realClock) AfterFunc(d time.Duration, f func()) stopper { return time.AfterFunc(d, f) } diff --git a/cmd/geoguess/config.go b/cmd/geoguess/config.go new file mode 100644 index 0000000..bb73082 --- /dev/null +++ b/cmd/geoguess/config.go @@ -0,0 +1,151 @@ +package main + +import ( + "cmp" + "errors" + "fmt" + "math" + "os" + "strconv" + "strings" + "time" + + "github.com/robdevops/signalbot/cmd/geoguess/geo" +) + +// config is GeoGuess's settings, every one from a GEO_ variable, the only +// ones signalbot passes an addon called geo. +type config struct { + StateDir string // GEO_STATE_DIR: where geo.json and the log are kept + Token string // GEO_MAPILLARY_TOKEN: empty is Panoramax only + MemLimit int64 // GEO_MEMLIMIT, in bytes + Round time.Duration // GEO_ROUND: a round's default length + Regions string // GEO_REGIONS: continents or country codes; empty is the world + MinQuality float64 // GEO_MIN_QUALITY: the least Mapillary quality_score + MaxAge time.Duration // GEO_MAX_AGE_YEARS, as a duration + Buffer int // GEO_BUFFER: checked photos kept ready + Nominatim string // GEO_NOMINATIM_URL + Panoramax string // GEO_PANORAMAX_URL + Mapillary string // GEO_MAPILLARY_URL +} + +// The shortest and longest round, and the defaults of the settings. +const ( + minRound = 30 * time.Second + maxRound = 30 * time.Minute + defaultRound = 3 * time.Minute + defaultMemLimit = "200MiB" +) + +// year is a year as GEO_MAX_AGE_YEARS counts it. +const year = 365*24*time.Hour + 6*time.Hour + +// loadConfig reads the settings through getenv (os.Getenv), failing with a +// message that names the setting. +func loadConfig(getenv func(string) string) (config, error) { + c := config{ + StateDir: strings.TrimSpace(getenv("GEO_STATE_DIR")), + Token: strings.TrimSpace(getenv("GEO_MAPILLARY_TOKEN")), + Regions: strings.TrimSpace(getenv("GEO_REGIONS")), + Nominatim: cmp.Or(strings.TrimSpace(getenv("GEO_NOMINATIM_URL")), geo.NominatimURL), + Panoramax: cmp.Or(strings.TrimSpace(getenv("GEO_PANORAMAX_URL")), geo.PanoramaxURL), + Mapillary: cmp.Or(strings.TrimSpace(getenv("GEO_MAPILLARY_URL")), geo.MapillaryURL), + } + var errs []error + if c.StateDir == "" { + errs = append(errs, errors.New("GEO_STATE_DIR is not set: set it to a directory GeoGuess can write, and create it")) + } + var err error + if c.MemLimit, err = parseSize(cmp.Or(strings.TrimSpace(getenv("GEO_MEMLIMIT")), defaultMemLimit)); err != nil { + errs = append(errs, fmt.Errorf("GEO_MEMLIMIT: %v", err)) + } + c.Round = defaultRound + if v := strings.TrimSpace(getenv("GEO_ROUND")); v != "" { + if c.Round, err = roundLength(v); err != nil { + errs = append(errs, fmt.Errorf("GEO_ROUND: %v", err)) + } + } + if _, err := geo.LoadSeeds(c.Regions); err != nil { + errs = append(errs, fmt.Errorf("GEO_REGIONS: %v", err)) + } + c.MinQuality = 0.5 + if v := strings.TrimSpace(getenv("GEO_MIN_QUALITY")); v != "" { + if c.MinQuality, err = strconv.ParseFloat(v, 64); err != nil || c.MinQuality < 0 || c.MinQuality > 1 { + errs = append(errs, fmt.Errorf("GEO_MIN_QUALITY is %q: use a number from 0 to 1", v)) + } + } + years := 10.0 + if v := strings.TrimSpace(getenv("GEO_MAX_AGE_YEARS")); v != "" { + if years, err = strconv.ParseFloat(v, 64); err != nil || years <= 0 || years > 100 { + errs = append(errs, fmt.Errorf("GEO_MAX_AGE_YEARS is %q: use a number of years above 0", v)) + } + } + c.MaxAge = time.Duration(years * float64(year)) + c.Buffer = 3 + if v := strings.TrimSpace(getenv("GEO_BUFFER")); v != "" { + if c.Buffer, err = strconv.Atoi(v); err != nil || c.Buffer < 1 || c.Buffer > 20 { + errs = append(errs, fmt.Errorf("GEO_BUFFER is %q: use a whole number from 1 to 20", v)) + } + } + // Over TLS only: the geocoder is sent each round's answer. + for _, u := range []struct{ name, url string }{ + {"GEO_NOMINATIM_URL", c.Nominatim}, {"GEO_PANORAMAX_URL", c.Panoramax}, {"GEO_MAPILLARY_URL", c.Mapillary}, + } { + if !strings.HasPrefix(u.url, "https://") { + errs = append(errs, fmt.Errorf("%s must start with https://", u.name)) + } + } + return c, errors.Join(errs...) +} + +// roundLength reads a round's length, such as 90s or 5m, from 30s to 30m. +func roundLength(s string) (time.Duration, error) { + d, err := time.ParseDuration(s) + if err != nil || d < minRound || d > maxRound { + return 0, fmt.Errorf("%q isn't a round length: use 30s to 30m, such as 90s or 5m", s) + } + return d, nil +} + +// sizeUnits are the suffixes parseSize takes, as GOMEMLIMIT does. +var sizeUnits = []struct { + suffix string + mult int64 +}{{"TiB", 1 << 40}, {"GiB", 1 << 30}, {"MiB", 1 << 20}, {"KiB", 1 << 10}, {"B", 1}} + +// parseSize reads a number of bytes written as GOMEMLIMIT is, such as +// 200MiB or 1GiB. +func parseSize(s string) (int64, error) { + mult := int64(1) + num := s + for _, u := range sizeUnits { + if n, ok := strings.CutSuffix(s, u.suffix); ok { + num, mult = n, u.mult + break + } + } + n, err := strconv.ParseFloat(strings.TrimSpace(num), 64) + if err != nil || n < 0 || n*float64(mult) >= math.MaxInt64 { + return 0, fmt.Errorf("%q isn't a size: use a number of bytes with B, KiB, MiB or GiB, such as 200MiB", s) + } + if n*float64(mult) < 16<<20 { + return 0, fmt.Errorf("%q is too small: GeoGuess needs at least 16MiB", s) + } + return int64(n * float64(mult)), nil +} + +// checkDir fails unless dir can be listed and written, leaving nothing. +func checkDir(dir string) error { + if _, err := os.ReadDir(dir); err != nil { + return fmt.Errorf("GEO_STATE_DIR %s can't be read (%v): create it, writable by the bot's user", dir, err) + } + f, err := os.CreateTemp(dir, ".check-*") + if err == nil { + f.Close() + err = os.Remove(f.Name()) + } + if err != nil { + return fmt.Errorf("GEO_STATE_DIR %s can't be written (%v): make it writable by the bot's user", dir, err) + } + return nil +} diff --git a/cmd/geoguess/game.go b/cmd/geoguess/game.go new file mode 100644 index 0000000..c44bd0d --- /dev/null +++ b/cmd/geoguess/game.go @@ -0,0 +1,398 @@ +package main + +import ( + "cmp" + "context" + "encoding/base64" + "fmt" + "slices" + "strconv" + "strings" + "time" + + "github.com/robdevops/signalbot/cmd/geoguess/geo" +) + +// The texts players see. +const ( + guard = "No hints during a round 😉" + noChat = "GeoGuess works only in a chat." + noRound = "There's no round on. Start one with /geo." + noPhoto = "I'm still looking for a photo. Try again in a minute." + badLength = "A round can be 30s to 30m, such as /geo 90s or /geo 5m." + usage = "Try /geo, /geo 90s, /geo end, /geo skip, /geo scores, or a region such as /geo europe or /geo AU,NZ." +) + +// pin is the reaction to a recorded guess. +const pin = "📍" + +// call runs one tool. Only an unknown tool is a protocol error; the rest +// answer in words. +func (s *server) call(ctx context.Context, p callParams) (any, error) { + switch p.Name { + case "geo": + var a struct { + Args string `json:"args"` + } + if err := params(p.Arguments, &a); err != nil { + return nil, err + } + return s.command(ctx, p.Meta.Context, a.Args), nil + case "geo_guess": + var a struct { + Text string `json:"text"` + } + if err := params(p.Arguments, &a); err != nil { + return nil, err + } + return s.guess(p.Meta.Context, a.Text), nil + } + return nil, &rpcError{codeInvalidParams, "unknown tool"} +} + +// text is a tool result of words alone. +func text(s string) toolResult { return toolResult{Content: []content{{Type: "text", Text: s}}} } + +// fromChat reports whether c names a chat and a sender. +func fromChat(c *callContext) bool { + return c != nil && validID(c.Chat, "c_") && validID(c.Sender, "u_") +} + +// command is /geo with its arguments. +func (s *server) command(ctx context.Context, c *callContext, args string) toolResult { + if !fromChat(c) { + return toolResult{Content: text(noChat).Content, IsError: true} + } + fields := strings.Fields(args) + if len(fields) == 1 { + switch strings.ToLower(fields[0]) { + case "end": + return s.finish(c, false) + case "skip": + return s.finish(c, true) + case "scores": + return text(s.scoreboard(c.Chat)) + } + } + length := s.cfg.Round + var regions []string + for _, f := range fields { + if f[0] >= '0' && f[0] <= '9' { + d, err := roundLength(strings.ToLower(f)) + if err != nil { + return text(badLength) + } + length = d + continue + } + regions = append(regions, f) + } + region := strings.Join(regions, ",") + if region != "" { + if _, err := s.regionSeeds(region); err != nil { + return text("I don't know that region. " + usage) + } + } + return s.start(ctx, c, length, region) +} + +// busy is the answer to /geo while a round is on. +func busy(r *round, now time.Time) toolResult { + left := max(r.Deadline.Sub(now), 0).Round(time.Second) + m, sec := int(left/time.Minute), int(left%time.Minute/time.Second) + var label string + switch { + case m == 0: + label = fmt.Sprintf("%ds", sec) + case sec == 0: + label = fmt.Sprintf("%dm", m) + default: + label = fmt.Sprintf("%dm%ds", m, sec) + } + return text("A round is on: " + label + " left.") +} + +// start begins a round in c's chat with a photo from the buffer, and +// answers with the photo, its caption and the watch for guesses. +func (s *server) start(ctx context.Context, c *callContext, length time.Duration, region string) toolResult { + s.mu.Lock() + r := s.rounds[c.Chat] + s.mu.Unlock() + if r != nil { + return busy(r, s.clock.Now()) + } + photo, ok := s.take(ctx, region) + if !ok { + return text(noPhoto) + } + s.mu.Lock() + now := s.clock.Now() + if r := s.rounds[c.Chat]; r != nil { // another /geo began one meanwhile + s.buffer = append([]geo.Photo{photo}, s.buffer...) + s.mu.Unlock() + return busy(r, now) + } + r = &round{ + ID: "r" + randomID(6), Chat: c.Chat, Starter: c.Sender, + Started: now, Deadline: now.Add(length), + Answer: photo.At, Place: photo.Place.Name, + Credit: credit{Creator: photo.Creator, Source: photo.Source, Licence: photo.Licence, Link: photo.Link}, + Guesses: map[string]guess{}, + } + s.rounds[c.Chat] = r + s.arm(r) + s.mu.Unlock() + s.save() + s.log.Printf("round %s started: %s, a %s photo", r.ID, length, photo.Source) + return toolResult{ + Content: []content{ + {Type: "image", Data: base64.StdEncoding.EncodeToString(photo.JPEG), MimeType: "image/jpeg"}, + {Type: "text", Text: caption(r.Deadline, length)}, + }, + Meta: &resultMeta{Watch: &watch{ + ID: r.ID, Pattern: geo.Pattern, Until: r.Deadline.Add(watchSlack).Format(time.RFC3339), + Tool: "geo_guess", Guard: guard, + }}, + } +} + +// caption is the photo's caption: how to guess, and by when. +func caption(deadline time.Time, length time.Duration) string { + return "🌍 **Where is this?** Send a location before " + deadline.Local().Format("15:04") + " (" + lengthLabel(length) + ").\n" + + "Signal: 📎 → Location → **drag the pin**, then send. Or type coordinates, e.g. `-37.81, 144.96`.\n" + + "⚠️ Location starts at *your* position. Move the pin before you send." +} + +// lengthLabel is a round's length as the caption says it: 3 min, 90 sec. +func lengthLabel(d time.Duration) string { + if d%time.Minute == 0 { + return strconv.Itoa(int(d/time.Minute)) + " min" + } + return strconv.Itoa(int(d.Round(time.Second)/time.Second)) + " sec" +} + +// arm sets r's timer to reveal it once its time is up. s.mu is held. +func (s *server) arm(r *round) { + chat, id := r.Chat, r.ID + s.timers[chat] = s.clock.AfterFunc(r.Deadline.Add(settle).Sub(s.clock.Now()), func() { s.timeUp(chat, id) }) +} + +// timeUp reveals the round id in chat, if it is still on. +func (s *server) timeUp(chat, id string) { + s.mu.Lock() + r := s.rounds[chat] + if r == nil || r.ID != id { + s.mu.Unlock() + return + } + s.timeUpLocked(r) + s.mu.Unlock() + s.poke() + s.save() +} + +// timeUpLocked ends r and queues its results and the end of its watch for +// the bot to post. s.mu is held. +func (s *server) timeUpLocked(r *round) { + results := s.end(r, true) + s.queue(op{Op: "post", Chat: r.Chat, Text: results}) + s.queue(op{Op: "unwatch", Chat: r.Chat, Watch: r.ID}) +} + +// finish is /geo end (skip false) or /geo skip, which only the player who +// started the round may use. It answers with the results, and queues the +// end of the round's watch. +func (s *server) finish(c *callContext, skip bool) toolResult { + s.mu.Lock() + r := s.rounds[c.Chat] + switch { + case r == nil: + s.mu.Unlock() + return text(noRound) + case r.Starter != c.Sender && skip: + s.mu.Unlock() + return text("Only the player who started this round can skip it.") + case r.Starter != c.Sender: + s.mu.Unlock() + return text("Only the player who started this round can end it.") + } + results := s.end(r, !skip) + s.queue(op{Op: "unwatch", Chat: r.Chat, Watch: r.ID}) + s.mu.Unlock() + s.poke() + s.save() + return text(results) +} + +// end closes r, adding its points to the chat's scores if scored, and +// returns its results. s.mu is held. +func (s *server) end(r *round, scored bool) string { + delete(s.rounds, r.Chat) + if t := s.timers[r.Chat]; t != nil { + t.Stop() + delete(s.timers, r.Chat) + } + guesses := make([]geo.Guess, 0, len(r.Guesses)) + for user, g := range r.Guesses { + guesses = append(guesses, geo.Guess{User: user, Km: g.Km, At: g.At}) + } + placings := geo.Rank(guesses) + how := "revealed" + if scored { + now := s.clock.Now() + s.pruneScores(now) + for _, p := range placings { + s.scores[r.Chat] = append(s.scores[r.Chat], score{User: p.User, Points: p.Points, At: now}) + } + } else { + how = "skipped" + } + s.log.Printf("round %s %s: %d guesses", r.ID, how, len(placings)) + return results(r, placings, scored) +} + +// results is a round's reveal: the place, then each player's distance and +// points, never where they guessed, then the photo's credit. Players are +// {u_…} placeholders, which the bot turns into names. +func results(r *round, placings []geo.Placing, scored bool) string { + place := "📍 [**" + plain(r.Place) + "**](" + mapLink(r.Answer) + ")" + var b strings.Builder + switch { + case !scored: + b.WriteString("Round skipped. It was " + place) + case len(placings) == 0: + b.WriteString("Nobody guessed. It was " + place) + default: + b.WriteString(place) + for _, p := range placings { + b.WriteString("\n" + medal(p.Rank) + " {" + p.User + "} " + geo.Distance(p.Km) + " · " + geo.Thousands(p.Points)) + } + } + b.WriteString("\n" + r.Credit.String()) + return b.String() +} + +// String is the credit line: "Photo: jsmith, Mapillary, CC BY-SA 4.0", +// linked to the photo's page. +func (c credit) String() string { + var parts []string + for _, p := range []string{plain(c.Creator), c.Source, c.Licence} { + if p != "" { + parts = append(parts, p) + } + } + line := strings.Join(parts, ", ") + if strings.HasPrefix(c.Link, "https://") && !strings.ContainsAny(c.Link, " ()") { + line = "[" + line + "](" + c.Link + ")" + } + return "Photo: " + line +} + +// plain is s without the characters Markdown would read, so a photo's +// author can't style or link the results. +func plain(s string) string { + return strings.Join(strings.Fields(strings.Map(func(r rune) rune { + if strings.ContainsRune("[]()*_`~\\<>|#", r) { + return -1 + } + return r + }, s)), " ") +} + +// mapLink is a map of the answer on OpenStreetMap. +func mapLink(p geo.Point) string { + lat, lon := strconv.FormatFloat(p.Lat, 'f', 5, 64), strconv.FormatFloat(p.Lon, 'f', 5, 64) + return "https://www.openstreetmap.org/?mlat=" + lat + "&mlon=" + lon + "#map=12/" + lat + "/" + lon +} + +// medal marks a rank: a medal for the first three, else the number. +func medal(rank int) string { + if rank <= 3 { + return []string{"🥇", "🥈", "🥉"}[rank-1] + } + return strconv.Itoa(rank) + "." +} + +// guess records the location in a chat message as its sender's guess in +// the chat's round: only how far it is from the answer, never where it is. +// A recorded guess answers with a pin for the bot to react with. +func (s *server) guess(c *callContext, msg string) toolResult { + if !fromChat(c) { + return text(noChat) + } + p, ok := geo.Parse(msg) + if !ok { + return text("No location found.") + } + at := s.clock.Now() + if t := cmp.Or(c.Edited, c.Sent); t > 0 { + at = time.Unix(t, 0) + } + s.mu.Lock() + r := s.rounds[c.Chat] + switch { + case r == nil: + s.mu.Unlock() + return text(noRound) + case c.Sent > 0 && c.Sent < r.Started.Unix(): + s.mu.Unlock() + return text("That message is from before this round.") + case at.After(r.Deadline): + s.mu.Unlock() + return text("Too late for this round.") + } + r.Guesses[c.Sender] = guess{Km: geo.Km(p, r.Answer), At: at} + s.mu.Unlock() + s.save() + return toolResult{Content: text("Recorded.").Content, Meta: &resultMeta{React: pin}} +} + +// scoreboard is /geo scores: the chat's totals over the last scoreDays. +func (s *server) scoreboard(chat string) string { + s.mu.Lock() + s.pruneScores(s.clock.Now()) + type total struct { + user string + points, rounds int + } + byUser := map[string]*total{} + var totals []*total + for _, sc := range s.scores[chat] { + t := byUser[sc.User] + if t == nil { + t = &total{user: sc.User} + byUser[sc.User] = t + totals = append(totals, t) + } + t.points += sc.Points + t.rounds++ + } + s.mu.Unlock() + if len(totals) == 0 { + return "No scores in the last 7 days. Start a round with /geo." + } + // Scores are kept in the order they were won, so a tie goes to who + // scored first. + slices.SortStableFunc(totals, func(a, b *total) int { return cmp.Compare(b.points, a.points) }) + var b strings.Builder + b.WriteString("🏆 **Scores, last 7 days**") + for i, t := range totals[:min(len(totals), 10)] { + rounds := "1 round" + if t.rounds != 1 { + rounds = strconv.Itoa(t.rounds) + " rounds" + } + fmt.Fprintf(&b, "\n%s {%s} %s · %s", medal(i+1), t.user, geo.Thousands(t.points), rounds) + } + return b.String() +} + +// pruneScores forgets scores older than scoreDays. s.mu is held. +func (s *server) pruneScores(now time.Time) { + since := now.Add(-scoreDays * 24 * time.Hour) + for chat, list := range s.scores { + s.scores[chat] = slices.DeleteFunc(list, func(sc score) bool { return sc.At.Before(since) }) + if len(s.scores[chat]) == 0 { + delete(s.scores, chat) + } + } +} diff --git a/cmd/geoguess/geo/find.go b/cmd/geoguess/geo/find.go new file mode 100644 index 0000000..466ecd8 --- /dev/null +++ b/cmd/geoguess/geo/find.go @@ -0,0 +1,113 @@ +package geo + +import ( + "context" + "errors" + "math/rand/v2" + "time" +) + +// Photo is a photo that passed every check, with its place named: ready for +// a round. +type Photo struct { + Candidate + Place Place + JPEG []byte +} + +// Finder looks for a photo worth a round: it picks a seed region, searches +// random boxes in it, and checks what it finds, cheapest checks first. +type Finder struct { + Sources []Source // tried in order for each box + Seeds *Seeds + Rules Rules + Places *Nominatim + Rand *rand.Rand + Now func() time.Time + + // Used reports whether a candidate's Key was used recently; nil is none. + Used func(key string) bool + // Rejected, if set, is told why each candidate was turned down. + Rejected func(source string, why Reject) + // Failed, if set, is told of each failed search or download, whose + // error holds no URL. + Failed func(err error) +} + +// The search's limits: boxes tried in a seed, seeds tried in one Find, and +// photos downloaded from one box. +const ( + boxesPerSeed = 4 + seedsPerFind = 8 + fetchesPerBox = 3 +) + +// ErrNotFound is a Find that tried its seeds and found nothing. +var ErrNotFound = errors.New("no photo found") + +// Find is a photo that passed every check. It gives up with ErrNotFound +// after seedsPerFind seeds, at once with ErrSlowDown if a source asks it to, +// or when ctx ends. +func (f *Finder) Find(ctx context.Context) (Photo, error) { + for range seedsPerFind { + seed := f.Seeds.Pick(f.Rand) + for range boxesPerSeed { + box := Around(seed.Point(f.Rand)) + for _, src := range f.Sources { + p, err := f.search(ctx, src, box) + if err == nil || errors.Is(err, ErrSlowDown) || ctx.Err() != nil { + return p, err + } + } + } + } + return Photo{}, ErrNotFound +} + +// search looks in one box of one source. +func (f *Finder) search(ctx context.Context, src Source, box BBox) (Photo, error) { + cands, err := src.Candidates(ctx, box) + if err != nil { + if !errors.Is(err, ErrSlowDown) && ctx.Err() == nil && f.Failed != nil { + f.Failed(err) + } + return Photo{}, err + } + reject := func(why Reject) { + if f.Rejected != nil { + f.Rejected(src.Name(), why) + } + } + kept := f.Rules.Filter(cands, f.Now(), f.Used, reject) + f.Rand.Shuffle(len(kept), func(i, j int) { kept[i], kept[j] = kept[j], kept[i] }) + for _, c := range kept[:min(len(kept), fetchesPerBox)] { + data, err := src.Fetch(ctx, c) + if err != nil { + if ctx.Err() != nil { + return Photo{}, ctx.Err() + } + if f.Failed != nil { + f.Failed(err) + } + continue + } + jpeg, err := Vet(data, c.Pano, f.Rand) + if err != nil { + reject(err.(Reject)) + continue + } + place, err := f.Places.Reverse(ctx, c.At) + if err != nil { + if why, ok := err.(Reject); ok { + reject(why) + } else if ctx.Err() != nil { + return Photo{}, ctx.Err() + } else if f.Failed != nil { + f.Failed(err) + } + continue + } + return Photo{Candidate: c, Place: place, JPEG: jpeg}, nil + } + return Photo{}, ErrNotFound +} diff --git a/cmd/geoguess/geo/find_test.go b/cmd/geoguess/geo/find_test.go new file mode 100644 index 0000000..1bbb8df --- /dev/null +++ b/cmd/geoguess/geo/find_test.go @@ -0,0 +1,178 @@ +package geo + +import ( + "context" + "errors" + "math/rand/v2" + "net/http" + "slices" + "testing" + "time" +) + +// fakeSource offers the same candidates in every box, or with once only in +// the first, with photos by ID. +type fakeSource struct { + cands []Candidate + once bool + photos map[string][]byte + err error + boxes []BBox + fetched []string +} + +func (f *fakeSource) Name() string { return "Fake" } + +func (f *fakeSource) Candidates(ctx context.Context, b BBox) ([]Candidate, error) { + f.boxes = append(f.boxes, b) + if f.once && len(f.boxes) > 1 { + return nil, f.err + } + return f.cands, f.err +} + +func (f *fakeSource) Fetch(ctx context.Context, c Candidate) ([]byte, error) { + f.fetched = append(f.fetched, c.ID) + if p, ok := f.photos[c.ID]; ok { + return p, nil + } + return nil, StatusError{Source: "Fake", Code: 404} +} + +func newTestFinder(t *testing.T, country string, sources ...Source) (*Finder, *[]Reject, *[]error) { + api := newFakeAPI(t) + api.handle = func(w http.ResponseWriter, r *http.Request) { + if country == "" { + w.Write([]byte(`{"error":"Unable to geocode"}`)) + return + } + w.Write([]byte(`{"address":{"town":"Ballarat","state":"Victoria","country":"` + country + `","country_code":"au"}}`)) + } + places := NewNominatim(api.URL, api.Client()) + places.pace.every = 0 + seeds, err := LoadSeeds("AU") + if err != nil { + t.Fatal(err) + } + var rejects []Reject + var fails []error + f := &Finder{ + Sources: sources, Seeds: seeds, Places: places, + Rules: Rules{MinQuality: 0.5, MaxAge: 10 * 365 * 24 * time.Hour}, + Rand: rand.New(rand.NewPCG(1, 2)), + Now: func() time.Time { return time.Date(2026, 11, 20, 0, 0, 0, 0, time.UTC) }, + Used: func(key string) bool { return key == "Fake:used" }, + Rejected: func(source string, why Reject) { + if source != "Fake" { + t.Errorf("rejected by %q", source) + } + rejects = append(rejects, why) + }, + Failed: func(err error) { fails = append(fails, err) }, + } + return f, &rejects, &fails +} + +func TestFind(t *testing.T) { + t.Parallel() + noon := time.Date(2024, 12, 21, 2, 19, 0, 0, time.UTC) // in Victoria + at := Point{-37.56, 143.85} + c := func(id string) Candidate { + return Candidate{ID: id, Source: "Fake", Sequence: id, At: at, Raw: at, Captured: noon, Quality: 0.9} + } + r := rand.New(rand.NewPCG(3, 3)) + good := jpegOf(t, scene(1024, 768, r)) + foggy := jpegOf(t, testPhotos(1024, 768)[3].m) + night := c("night") + night.Captured = noon.Add(12 * time.Hour) + src := &fakeSource{ + cands: []Candidate{c("used"), night, c("foggy"), c("good")}, + photos: map[string][]byte{"foggy": foggy, "good": good}, + } + f, rejects, _ := newTestFinder(t, "Australia", src) + // The candidates kept are tried in a random order: search until the + // foggy one is tried before the good one. + for range 10 { + *rejects = nil + src.fetched = nil + p, err := f.Find(context.Background()) + if err != nil { + t.Fatal(err) + } + if p.ID != "good" || p.Place.Name != "Ballarat, Victoria, Australia" || len(p.JPEG) == 0 { + t.Fatalf("found %+v", p.Candidate) + } + if !slices.Contains(*rejects, RejectUsed) || !slices.Contains(*rejects, RejectDark) { + t.Errorf("rejected for %v", *rejects) + } + if slices.Contains(src.fetched, "foggy") { + if !slices.Contains(*rejects, RejectContrast) { + t.Errorf("fog rejected for %v", *rejects) + } + return + } + } + t.Error("the foggy photo was never tried") +} + +func TestFindBoxes(t *testing.T) { + src := &fakeSource{} + f, _, _ := newTestFinder(t, "Australia", src) + if _, err := f.Find(context.Background()); err != ErrNotFound { + t.Errorf("empty: %v", err) + } + if len(src.boxes) != seedsPerFind*boxesPerSeed { + t.Errorf("%d boxes searched", len(src.boxes)) + } + for _, b := range src.boxes { + c := b.Centre() + if c.Lat > -10 || c.Lat < -44 || c.Lon < 113 || c.Lon > 154 { + t.Errorf("searched outside Australia: %v", c) + } + } +} + +func TestFindErrors(t *testing.T) { + noon := time.Date(2024, 12, 21, 2, 19, 0, 0, time.UTC) + at := Point{-37.56, 143.85} + good := Candidate{ID: "good", Source: "Fake", At: at, Raw: at, Captured: noon, Quality: -1} + photo := jpegOf(t, scene(1024, 768, rand.New(rand.NewPCG(4, 4)))) + + // A failing source falls through to the next. + broken := &fakeSource{err: StatusError{Source: "Fake", Code: 500}} + working := &fakeSource{cands: []Candidate{good}, photos: map[string][]byte{"good": photo}} + f, _, fails := newTestFinder(t, "Australia", broken, working) + if p, err := f.Find(context.Background()); err != nil || p.ID != "good" { + t.Errorf("fallback: %+v, %v", p.Candidate, err) + } + if len(*fails) != 1 || (*fails)[0] != (StatusError{Source: "Fake", Code: 500}) { + t.Errorf("failures %v", *fails) + } + + // A source that asks to slow down stops the search. + slow := &fakeSource{err: ErrSlowDown} + f, _, _ = newTestFinder(t, "Australia", slow, working) + if _, err := f.Find(context.Background()); !errors.Is(err, ErrSlowDown) || len(slow.boxes) != 1 || len(working.boxes) != 1 { + t.Errorf("slow down: %v after %d boxes", err, len(slow.boxes)) + } + + // A photo with no country is dropped. + f, rejects, _ := newTestFinder(t, "", &fakeSource{cands: []Candidate{good}, photos: map[string][]byte{"good": photo}, once: true}) + if _, err := f.Find(context.Background()); err != ErrNotFound || !slices.Contains(*rejects, RejectNoPlace) { + t.Errorf("no country: %v, %v", err, *rejects) + } + + // A download that fails is reported, and the search goes on. + f, _, fails = newTestFinder(t, "Australia", &fakeSource{cands: []Candidate{good}}) + if _, err := f.Find(context.Background()); err != ErrNotFound || len(*fails) != seedsPerFind*boxesPerSeed { + t.Errorf("failed downloads: %v, %d reported", err, len(*fails)) + } + + // A cancelled search stops. + ctx, cancel := context.WithCancel(context.Background()) + cancel() + f, _, _ = newTestFinder(t, "Australia", &fakeSource{err: context.Canceled}) + if _, err := f.Find(ctx); !errors.Is(err, context.Canceled) { + t.Errorf("cancelled: %v", err) + } +} diff --git a/cmd/geoguess/geo/mapillary.go b/cmd/geoguess/geo/mapillary.go new file mode 100644 index 0000000..6759eec --- /dev/null +++ b/cmd/geoguess/geo/mapillary.go @@ -0,0 +1,177 @@ +package geo + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/url" + "strconv" + "time" +) + +// MapillaryURL is Mapillary's Graph API. +const MapillaryURL = "https://graph.mapillary.com" + +// mapillaryFields are the fields a search asks for. +const mapillaryFields = "id,computed_geometry,geometry,captured_at,camera_type,is_pano,quality_score,width,height,sequence,creator,thumb_2048_url" + +// mapillaryLimit is the most images one search returns. +const mapillaryLimit = 100 + +// maxMapillaryAnswer caps one search's answer. +const maxMapillaryAnswer = 4 << 20 + +// Mapillary searches Mapillary's Graph API v4. Its photos are CC BY-SA 4.0. +type Mapillary struct { + url string + token string + client *http.Client +} + +// NewMapillary is a Mapillary client for the API at base (MapillaryURL), +// sending token (MLY|…) as "Authorization: OAuth <token>": Mapillary's +// answers to a Bearer token hold no data. +func NewMapillary(base, token string, client *http.Client) *Mapillary { + return &Mapillary{url: base, token: token, client: client} +} + +// Name is "Mapillary". +func (m *Mapillary) Name() string { return "Mapillary" } + +type mapillaryImage struct { + ID string `json:"id"` + ComputedGeometry *geoJSONPoint `json:"computed_geometry"` + Geometry *geoJSONPoint `json:"geometry"` + CapturedAt int64 `json:"captured_at"` // ms since the epoch, by the camera's clock + CameraType string `json:"camera_type"` + IsPano bool `json:"is_pano"` + QualityScore *float64 `json:"quality_score"` // null is unknown, not bad + Width int `json:"width"` + Height int `json:"height"` + Sequence string `json:"sequence"` + Creator struct { + Username string `json:"username"` + } `json:"creator"` + Thumb string `json:"thumb_2048_url"` +} + +type mapillaryAnswer struct { + Data []mapillaryImage `json:"data"` + Error *struct { + Code int `json:"code"` + } `json:"error"` +} + +// Candidates searches b, which must be under 0.01 deg². An empty answer is +// asked again once, since Mapillary sometimes leaves out images it has; a +// server error (Mapillary's answer to an area too dense to list) falls back +// to a radius search around b's centre. +func (m *Mapillary) Candidates(ctx context.Context, b BBox) ([]Candidate, error) { + q := url.Values{"bbox": {b.String()}, "fields": {mapillaryFields}, "limit": {strconv.Itoa(mapillaryLimit)}} + images, err := m.search(ctx, q) + if err == nil && len(images) == 0 { + images, err = m.search(ctx, q) + } + if se := (StatusError{}); errors.As(err, &se) && se.Code >= 500 { + c := b.Centre() + images, err = m.search(ctx, url.Values{ + "lat": {coord(c.Lat)}, "lng": {coord(c.Lon)}, "radius": {"50"}, + "fields": {mapillaryFields}, "limit": {strconv.Itoa(mapillaryLimit)}, + }) + } + if err != nil { + return nil, err + } + out := make([]Candidate, 0, len(images)) + for _, im := range images { + if c, ok := im.candidate(); ok { + out = append(out, c) + } + } + return out, nil +} + +// search is one call to /images. +func (m *Mapillary) search(ctx context.Context, q url.Values) ([]mapillaryImage, error) { + r := request{client: m.client, source: m.Name(), url: m.url + "/images?" + q.Encode(), auth: "OAuth " + m.token, limit: maxMapillaryAnswer} + body, err := r.get(ctx) + var a mapillaryAnswer + jerr := json.Unmarshal(body, &a) + if a.Error != nil && a.Error.Code == 4 { + return nil, ErrSlowDown // "application request limit reached" + } + if err != nil { + return nil, err + } + if jerr != nil || a.Error != nil { + return nil, fmt.Errorf("%s: unreadable answer", m.Name()) + } + return a.Data, nil +} + +// candidate is im as a Candidate, if it has an ID and a position. +func (im mapillaryImage) candidate() (Candidate, bool) { + raw, rawOK := im.Geometry.point() + at, ok := im.ComputedGeometry.point() + if !ok { + at, ok = raw, rawOK + } + if !rawOK { + raw = at + } + if im.ID == "" || !ok { + return Candidate{}, false + } + c := Candidate{ + ID: im.ID, + Source: "Mapillary", + Creator: im.Creator.Username, + Licence: "CC BY-SA 4.0", + Link: "https://www.mapillary.com/app/?pKey=" + url.QueryEscape(im.ID), + At: at, + Raw: raw, + Pano: im.IsPano || im.CameraType == "spherical" || im.CameraType == "equirectangular", + Fisheye: im.CameraType == "fisheye", + Quality: -1, + Width: im.Width, + Height: im.Height, + Sequence: im.Sequence, + image: im.Thumb, + } + if im.CapturedAt > 0 { + c.Captured = time.UnixMilli(im.CapturedAt).UTC() + } + if im.QualityScore != nil { + c.Quality = *im.QualityScore + } + return c, true +} + +// Fetch downloads c's 2048-px thumbnail. The URL a search gave is signed and +// expires, so a candidate without one, or whose URL has expired, gets a fresh +// one by ID. +func (m *Mapillary) Fetch(ctx context.Context, c Candidate) ([]byte, error) { + if c.image != "" { + data, err := request{client: m.client, source: m.Name(), url: c.image, limit: maxPhoto}.get(ctx) + if err == nil { + return data, nil + } + if se := (StatusError{}); !errors.As(err, &se) || (se.Code != http.StatusForbidden && se.Code != http.StatusNotFound && se.Code != http.StatusGone) { + return nil, err + } + } + var fresh struct { + Thumb string `json:"thumb_2048_url"` + } + q := url.Values{"fields": {"thumb_2048_url"}} + r := request{client: m.client, source: m.Name(), url: m.url + "/" + url.PathEscape(c.ID) + "?" + q.Encode(), auth: "OAuth " + m.token, limit: 64 << 10} + if err := r.getJSON(ctx, &fresh); err != nil { + return nil, err + } + if fresh.Thumb == "" { + return nil, fmt.Errorf("%s: no image", m.Name()) + } + return request{client: m.client, source: m.Name(), url: fresh.Thumb, limit: maxPhoto}.get(ctx) +} diff --git a/cmd/geoguess/geo/panoramax.go b/cmd/geoguess/geo/panoramax.go new file mode 100644 index 0000000..33c6d00 --- /dev/null +++ b/cmd/geoguess/geo/panoramax.go @@ -0,0 +1,214 @@ +package geo + +import ( + "context" + "fmt" + "math" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +// PanoramaxURL is Panoramax's meta-catalogue, which lists the photos of +// every instance. +const PanoramaxURL = "https://api.panoramax.xyz" + +// panoramaxLimit is the most items one search returns. +const panoramaxLimit = 100 + +// maxPanoramaxAnswer caps one search's answer; items carry their EXIF. +const maxPanoramaxAnswer = 16 << 20 + +// Panoramax searches Panoramax's STAC API. It needs no key; it publishes no +// rate limit, so it is called at most once a second. +type Panoramax struct { + url string + client *http.Client + pace *pacer +} + +// NewPanoramax is a Panoramax client for the catalogue at base +// (PanoramaxURL). +func NewPanoramax(base string, client *http.Client) *Panoramax { + return &Panoramax{url: base, client: client, pace: &pacer{every: time.Second}} +} + +// Name is "Panoramax". +func (p *Panoramax) Name() string { return "Panoramax" } + +type panoramaxItem struct { + ID string `json:"id"` + Geometry *geoJSONPoint `json:"geometry"` + Collection string `json:"collection"` + Providers []struct { + Name string `json:"name"` + Roles []string `json:"roles"` + } `json:"providers"` + Assets map[string]struct { + Href string `json:"href"` + } `json:"assets"` + Properties struct { + Datetime string `json:"datetime"` // UTC + License string `json:"license"` // an SPDX ID + Orientation struct { + FieldOfView *float64 `json:"field_of_view"` + Dimensions []int `json:"sensor_array_dimensions"` + } `json:"pers:interior_orientation"` + Accuracy *float64 `json:"quality:horizontal_accuracy"` // m + Density *float64 `json:"panoramax:horizontal_pixel_density"` + } `json:"properties"` +} + +// Candidates searches b. +func (p *Panoramax) Candidates(ctx context.Context, b BBox) ([]Candidate, error) { + if err := p.pace.wait(ctx); err != nil { + return nil, err + } + q := url.Values{"bbox": {b.String()}, "limit": {strconv.Itoa(panoramaxLimit)}} + var a struct { + Features []panoramaxItem `json:"features"` + } + r := request{client: p.client, source: p.Name(), url: p.url + "/api/search?" + q.Encode(), limit: maxPanoramaxAnswer} + if err := r.getJSON(ctx, &a); err != nil { + if se, ok := err.(StatusError); ok && se.Code == http.StatusTooManyRequests { + return nil, ErrSlowDown + } + return nil, err + } + out := make([]Candidate, 0, len(a.Features)) + for _, it := range a.Features { + if c, ok := p.candidate(it); ok { + out = append(out, c) + } + } + return out, nil +} + +// candidate is it as a Candidate, if it has an ID, a position, a licence +// the credit can name, and an SD picture. +func (p *Panoramax) candidate(it panoramaxItem) (Candidate, bool) { + at, ok := it.Geometry.point() + licence := licenceName(it.Properties.License) + sd := it.Assets["sd"].Href + if it.ID == "" || !ok || licence == "" || sd == "" { + return Candidate{}, false + } + props := it.Properties + c := Candidate{ + ID: it.ID, + Source: "Panoramax", + Creator: producer(it), + Licence: licence, + Link: p.url + "/#focus=pic&pic=" + url.QueryEscape(it.ID), + At: at, + Raw: at, + Pano: props.Orientation.FieldOfView != nil && *props.Orientation.FieldOfView == 360, + Quality: -1, + Sequence: it.Collection, + image: sd, + } + if d := props.Orientation.Dimensions; len(d) == 2 { + c.Width, c.Height = d[0], d[1] + } + if t, err := time.Parse(time.RFC3339, props.Datetime); err == nil { + c.Captured = t.UTC() + } + c.Grade = grade(c.Pano, props.Density, props.Accuracy) + return c, true +} + +// producer is the first provider with the producer role: the author. +func producer(it panoramaxItem) string { + for _, pr := range it.Providers { + for _, role := range pr.Roles { + if role == "producer" { + return pr.Name + } + } + } + return "" +} + +// licenceName is an SPDX ID as the credit shows it: "CC-BY-SA-4.0" is +// "CC BY-SA 4.0", "etalab-2.0" is "Etalab 2.0". It is empty for a licence +// that isn't open (only Creative Commons and Etalab are). +func licenceName(spdx string) string { + parts := strings.Split(spdx, "-") + if len(parts) < 2 { + return "" + } + last := len(parts) - 1 + switch first := strings.ToLower(parts[0]); { + case first == "cc" && last >= 2: + return "CC " + strings.Join(parts[1:last], "-") + " " + parts[last] + case first == "cc0": + return "CC0 " + parts[last] + case first == "etalab" && last == 1: + return "Etalab " + parts[last] + } + return "" +} + +// grade is the A–E grade (5 to 1) that Panoramax's viewer shows, from the +// picture's horizontal pixel density and GPS accuracy: +// round(0.8 × resolution + 0.2 × GPS). Each is often missing, which is +// unknown rather than bad: the grade is then the known one's alone, or 0 if +// neither is known. +func grade(pano bool, density, accuracy *float64) int { + res := 0 + if density != nil { + d := *density + switch { + case pano && d < 15: + res = 3 + case pano && d < 30: + res = 4 + case pano: + res = 5 + case d < 10: + res = 1 + case d < 15: + res = 2 + case d < 30: + res = 3 + default: + res = 4 + } + } + gps := 0 + if accuracy != nil { + switch a := *accuracy; { + case a < 0.5: + gps = 5 + case a <= 2: + gps = 4 + case a <= 5: + gps = 3 + case a <= 10: + gps = 2 + default: + gps = 1 + } + } + switch { + case res == 0: + return gps + case gps == 0: + return res + } + return int(math.Round(0.8*float64(res) + 0.2*float64(gps))) +} + +// Fetch downloads c's SD picture, 2048 px wide, from the instance that holds +// it. +func (p *Panoramax) Fetch(ctx context.Context, c Candidate) ([]byte, error) { + if c.image == "" { + return nil, fmt.Errorf("%s: no image", p.Name()) + } + if err := p.pace.wait(ctx); err != nil { + return nil, err + } + return request{client: p.client, source: p.Name(), url: c.image, limit: maxPhoto}.get(ctx) +} diff --git a/cmd/geoguess/geo/parse.go b/cmd/geoguess/geo/parse.go new file mode 100644 index 0000000..3843e9f --- /dev/null +++ b/cmd/geoguess/geo/parse.go @@ -0,0 +1,223 @@ +package geo + +import ( + "net/url" + "regexp" + "strconv" + "strings" +) + +// Pattern is the watch pattern for a round: Go RE2 that catches a message +// that may hold a location. It is specific, so ordinary chatter doesn't +// match: a map URL's host, a geo: URI, or a decimal coordinate pair. Parse +// does the real reading, and a message it can't read isn't a guess. +const Pattern = `(?i)(?:\bmaps\.google\.[a-z.]+/|\bgoogle\.[a-z.]+/maps|\bmaps\.apple\.com\b|\bgeo:[+-]?\d|\bopenstreetmap\.org/|(?:^|[^\w.])-?\d{1,3}\.\d+°?\s*,\s*-?\d{1,3}\.\d+)` + +// Parse reads the first location in text: a Google, Apple or OpenStreetMap +// map URL, a geo: URI (RFC 5870), or typed coordinates such as +// "-37.81, 144.96", each number with a decimal point. Only decimal degrees +// are read, and only a latitude in [-90, 90] with a longitude in +// [-180, 180]. Text that only looks like coordinates ("3, 4", times such as +// "12.30, 14.45", prices) isn't a location. +func Parse(text string) (Point, bool) { + text = strings.ReplaceAll(text, "−", "-") // U+2212 MINUS SIGN + for _, field := range strings.FieldsFunc(text, isFieldBreak) { + field = strings.TrimRight(field, ".,;:!?") + if p, ok := parseLink(field); ok { + return p, true + } + } + return parseTyped(text) +} + +// isFieldBreak ends a link: white space, or a bracket or quote around one. +func isFieldBreak(r rune) bool { + switch r { + case ' ', '\t', '\n', '\r', '<', '>', '(', ')', '[', ']', '"', '\'', '`': + return true + } + return false +} + +// parseLink reads a location from one map link or geo: URI. +func parseLink(s string) (Point, bool) { + if len(s) > 4 && strings.EqualFold(s[:4], "geo:") { + return parseGeoURI(s[4:]) + } + if !strings.Contains(s, "://") { + s = "https://" + s + } + u, err := url.Parse(s) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") { + return Point{}, false + } + host := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") + switch { + case isGoogle(host) && (strings.HasPrefix(host, "maps.") || strings.HasPrefix(u.Path, "/maps")): + return parseGoogle(u) + case host == "maps.apple.com": + return firstParam(u.Query(), "ll", "coordinate", "q", "sll") + case host == "openstreetmap.org": + return parseOSM(u) + } + return Point{}, false +} + +// googleHost is a Google host: google.com, google.com.au, maps.google.fr… +var googleHost = regexp.MustCompile(`^(?:maps\.)?google\.(?:[a-z]{2,3}|co|com)(?:\.[a-z]{2})?$`) + +func isGoogle(host string) bool { return googleHost.MatchString(host) } + +// googleAt is the map centre in a Google path: /maps/@-37.81,144.96,15z. +var googleAt = regexp.MustCompile(`/@([+-]?\d+(?:\.\d+)?),([+-]?\d+(?:\.\d+)?)(?:[,/]|$)`) + +// parseGoogle reads q= (what Signal sends), ll= or query=, then a place or +// search path segment that is a coordinate pair, then the @ map centre. +func parseGoogle(u *url.URL) (Point, bool) { + if p, ok := firstParam(u.Query(), "q", "ll", "query"); ok { + return p, true + } + segs := strings.Split(u.Path, "/") + for i, seg := range segs { + if (seg == "place" || seg == "search") && i+1 < len(segs) { + if v, err := url.PathUnescape(segs[i+1]); err == nil { + if p, ok := parsePair(strings.ReplaceAll(v, "+", " ")); ok { + return p, true + } + } + } + } + if m := googleAt.FindStringSubmatch(u.Path); m != nil { + return point(m[1], m[2]) + } + return Point{}, false +} + +// parseOSM reads a marker (mlat, mlon), else the map centre in the fragment +// (#map=15/-37.81/144.96). +func parseOSM(u *url.URL) (Point, bool) { + q := u.Query() + if q.Has("mlat") && q.Has("mlon") { + return point(q.Get("mlat"), q.Get("mlon")) + } + frag, err := url.ParseQuery(u.Fragment) + if err != nil { + return Point{}, false + } + parts := strings.Split(frag.Get("map"), "/") + if len(parts) != 3 { + return Point{}, false + } + return point(parts[1], parts[2]) +} + +// parseGeoURI reads what follows "geo:": lat,lon[,alt][;params][?q=…]. +// Android's geo:0,0?q=lat,lon(label) puts the place in q. +func parseGeoURI(s string) (Point, bool) { + coords, query, _ := strings.Cut(s, "?") + coords, _, _ = strings.Cut(coords, ";") + parts := strings.Split(coords, ",") + if len(parts) < 2 || len(parts) > 3 { + return Point{}, false + } + p, ok := point(parts[0], parts[1]) + if ok && (p != Point{}) { + return p, true + } + if q, err := url.ParseQuery(query); err == nil && q.Has("q") { + v, _, _ := strings.Cut(q.Get("q"), "(") + if qp, qok := parsePair(v); qok { + return qp, true + } + } + return p, ok +} + +// firstParam is the first of the named query parameters that is a +// coordinate pair. +func firstParam(q url.Values, names ...string) (Point, bool) { + for _, n := range names { + if p, ok := parsePair(q.Get(n)); ok { + return p, true + } + } + return Point{}, false +} + +// pair is a coordinate pair as a link holds it, maybe after "loc:". +var pair = regexp.MustCompile(`^\s*(?:loc:\s*)?([+-]?\d{1,3}(?:\.\d+)?)\s*,\s*([+-]?\d{1,3}(?:\.\d+)?)\s*$`) + +func parsePair(s string) (Point, bool) { + m := pair.FindStringSubmatch(s) + if m == nil { + return Point{}, false + } + return point(m[1], m[2]) +} + +// point is lat and lon as numbers, if both are in range. +func point(lat, lon string) (Point, bool) { + φ, err1 := strconv.ParseFloat(lat, 64) + λ, err2 := strconv.ParseFloat(lon, 64) + p := Point{Lat: φ, Lon: λ} + if err1 != nil || err2 != nil || !p.valid() { + return Point{}, false + } + return p, true +} + +// typed is a typed coordinate pair, each number with a decimal point, not +// part of a longer number, word, version ("v1.2.3") or link, nor next to a currency +// sign or a percent sign. A full stop may end the sentence after it. +var typed = regexp.MustCompile(`(?:^|[^\w.$€£¥=/@&?#+-])(-?\d{1,3}\.\d+)°?\s*,\s*(-?\d{1,3}\.\d+)°?(?:$|[^\w.%$€£¥]|\.(?:$|\D))`) + +// parseTyped reads the first typed coordinate pair in text that isn't a +// pair of clock times or prices. +func parseTyped(text string) (Point, bool) { + for _, m := range typed.FindAllStringSubmatchIndex(text, -1) { + lat, lon := text[m[2]:m[3]], text[m[4]:m[5]] + if (clock(lat) && clock(lon)) || money(text[:m[2]], text[m[5]:]) { + continue + } + if p, ok := point(lat, lon); ok { + return p, true + } + } + return Point{}, false +} + +// clock reports whether s reads as a time of day written with a dot, such +// as 9.30 or 14.45. +func clock(s string) bool { + h, m, _ := strings.Cut(s, ".") + if len(m) != 2 || len(h) > 2 || strings.HasPrefix(h, "-") { + return false + } + hh, _ := strconv.Atoi(h) + mm, _ := strconv.Atoi(m) + return hh <= 23 && mm <= 59 +} + +// currencies are the words and signs that make a pair of numbers prices. +var currencies = []string{"$", "€", "£", "¥", "aud", "usd", "eur", "gbp", "nzd", "cad", "dollars", "dollar", "euros", "euro", "pounds", "bucks", "each"} + +// money reports whether the text just before or after a pair names a +// currency, as in "AUD 3.50, 4.20" or "3.50, 4.20 euros". +func money(before, after string) bool { + before = strings.ToLower(strings.TrimRight(before, " ")) + after = strings.ToLower(strings.TrimLeft(strings.TrimLeft(after, "°"), " ")) + for _, c := range currencies { + sign := !isWordByte(c[0]) + if rest, ok := strings.CutSuffix(before, c); ok && (sign || rest == "" || !isWordByte(rest[len(rest)-1])) { + return true + } + if rest, ok := strings.CutPrefix(after, c); ok && (sign || rest == "" || !isWordByte(rest[0])) { + return true + } + } + return false +} + +func isWordByte(b byte) bool { + return b == '_' || ('0' <= b && b <= '9') || ('a' <= b && b <= 'z') +} diff --git a/cmd/geoguess/geo/parse_test.go b/cmd/geoguess/geo/parse_test.go new file mode 100644 index 0000000..b7b9dbb --- /dev/null +++ b/cmd/geoguess/geo/parse_test.go @@ -0,0 +1,136 @@ +package geo + +import ( + "math" + "regexp" + "testing" +) + +func TestParse(t *testing.T) { + mel := Point{-37.8136, 144.9631} + for _, tc := range []struct { + text string + want Point + ok bool + }{ + // Signal Android's Attach → Location. + {"https://maps.google.com/maps?q=-37.8136%2C144.9631", mel, true}, + {"https://maps.google.com/maps?q=-37.8136,144.9631", mel, true}, + {"Here: https://maps.google.com/maps?q=-37.8136%2C144.9631.", mel, true}, + {"maps.google.com/maps?q=-37.8136%2C%20144.9631", mel, true}, + {"https://www.google.com/maps?q=loc:-37.8136,144.9631", mel, true}, + {"https://www.google.com.au/maps?ll=-37.8136,144.9631&z=15", mel, true}, + {"https://www.google.com/maps/search/?api=1&query=-37.8136%2C144.9631", mel, true}, + {"google.com/maps/@-37.8136,144.9631,15z", mel, true}, + {"https://www.google.com/maps/place/Melbourne+VIC/@-37.8136,144.9631,12z/data=!3m1", mel, true}, + {"https://www.google.com/maps/place/-37.8136,+144.9631", mel, true}, + {"(https://maps.google.fr/?q=-37.8136,144.9631)", mel, true}, + // Apple. + {"https://maps.apple.com/?ll=-37.8136,144.9631&q=Pin", mel, true}, + {"https://maps.apple.com/?q=Cafe&sll=-37.8136,144.9631", mel, true}, + {"https://maps.apple.com/place?coordinate=-37.8136,144.9631", mel, true}, + // geo: URIs. + {"geo:-37.8136,144.9631", mel, true}, + {"GEO:-37.8136,144.9631,30;u=35", mel, true}, + {"geo:0,0?q=-37.8136,144.9631(Pin)", mel, true}, + {"geo:0,0", Point{}, true}, + // OpenStreetMap. + {"https://www.openstreetmap.org/#map=15/-37.8136/144.9631", mel, true}, + {"https://www.openstreetmap.org/#map=15/-37.8136/144.9631&layers=H", mel, true}, + {"https://www.openstreetmap.org/?mlat=-37.8136&mlon=144.9631#map=3/0/0", mel, true}, + // Typed. + {"-37.8136, 144.9631", mel, true}, + {"-37.8136,144.9631", mel, true}, + {"I reckon −37.8136 , 144.9631.", mel, true}, + {"-37.8136°, 144.9631°", mel, true}, + {"my guess is 48.8584, 2.2945 final answer", Point{48.8584, 2.2945}, true}, + {"0.0, 0.0", Point{}, true}, + {"90.0, -180.0", Point{90, -180}, true}, + + // Not locations. + {"3, 4", Point{}, false}, + {"-37, 144", Point{}, false}, + {"meet at 12.30, 14.45 or later", Point{}, false}, + {"9.30, 10.15", Point{}, false}, + {"$3.50, $4.20", Point{}, false}, + {"they were 3.50, 4.20 each", Point{}, false}, + {"AUD 3.50, 4.20", Point{}, false}, + {"3.50, 4.20 euros", Point{}, false}, + {"3.5%, 4.2%", Point{}, false}, + {"v1.2, v1.3", Point{}, false}, + {"versions 1.2.3, 1.2.4", Point{}, false}, + {"91.5, 10.0", Point{}, false}, + {"45.5, 180.5", Point{}, false}, + {"https://maps.google.com/maps?q=Melbourne", Point{}, false}, + {"https://maps.google.com/maps?q=-97.1,144.9", Point{}, false}, + {"https://example.com/maps?q=-37.8136,144.9631", Point{}, false}, + {"https://maps.google.com.evil.example/?q=-37.8136,144.9631", Point{}, false}, + {"https://www.google.com/search?q=-37.8136,144.9631", Point{}, false}, + {"https://maps.app.goo.gl/abc123", Point{}, false}, + {"geo: what a game", Point{}, false}, + {"geo:-37.8136", Point{}, false}, + {"https://www.openstreetmap.org/#map=15/-37.8136", Point{}, false}, + {"", Point{}, false}, + } { + got, ok := Parse(tc.text) + if ok != tc.ok || !near(got, tc.want) { + t.Errorf("Parse(%q) = %v, %v; want %v, %v", tc.text, got, ok, tc.want, tc.ok) + } + } +} + +func near(a, b Point) bool { + return math.Abs(a.Lat-b.Lat) < 1e-9 && math.Abs(a.Lon-b.Lon) < 1e-9 +} + +// TestPatternCatchesEveryForm checks the watch pattern catches every text +// Parse reads, so no guess is missed. +func TestPatternCatchesEveryForm(t *testing.T) { + re := regexp.MustCompile(Pattern) + for _, text := range []string{ + "https://maps.google.com/maps?q=-37.8136%2C144.9631", + "google.com/maps/@-37.81,144.96,15z", + "https://www.google.com.au/maps/place/X/@-37.81,144.96,12z", + "https://maps.apple.com/?ll=-37.81,144.96", + "https://maps.apple.com?q=x&sll=-37.81,144.96", + "geo:-37.81,144.96", + "geo:0,0?q=-37.81,144.96", + "https://www.openstreetmap.org/#map=15/-37.81/144.96", + "https://www.openstreetmap.org/?mlat=-37.81&mlon=144.96", + "-37.81, 144.96", + "guess: 48.85,2.29", + "-37.81°, 144.96°", + } { + if !re.MatchString(text) { + t.Errorf("pattern misses %q", text) + } + if _, ok := Parse(text); !ok { + t.Errorf("Parse misses %q", text) + } + } +} + +// TestPatternSkipsChatter checks the watch pattern is specific: ordinary +// chat lines, links and numbers don't match, so it passes signalbot's +// catch-all check. +func TestPatternSkipsChatter(t *testing.T) { + re := regexp.MustCompile(Pattern) + if len(Pattern) > 1024 { + t.Errorf("pattern is %d bytes, over the 1 KB limit", len(Pattern)) + } + for _, text := range []string{ + "", "lol", "ok", "see you at 5", "what's for dinner?", "running 10 min late", + "meet at 12:30, 14:45 is too late", "3, 4", "it cost 3.50", "1.5 litres, 2 eggs", + "version 1.2.3 is out", "the score was 3-4", "call me on 0412 345 678", + "https://www.abc.net.au/news/2024-05-01/some-story/103789456", + "https://www.google.com/search?q=weather", "https://youtu.be/dQw4w9WgXcQ", + "Alice: are we still on for Saturday?", "Bob, can you grab milk", + "I'm at the station", "we're in Melbourne now", "geography homework is due", + "lat long of the house?", "😂😂😂", "100%", "1,000,000", "pi is 3.14159", + "Google Maps says 20 min", "check apple maps", "openstreetmap is great", + } { + if re.MatchString(text) { + t.Errorf("pattern matches chatter %q", text) + } + } +} diff --git a/cmd/geoguess/geo/pixels.go b/cmd/geoguess/geo/pixels.go new file mode 100644 index 0000000..72e9a2a --- /dev/null +++ b/cmd/geoguess/geo/pixels.go @@ -0,0 +1,277 @@ +package geo + +import ( + "bytes" + "image" + "image/color" + "image/jpeg" + "math" + "math/rand/v2" + + xdraw "golang.org/x/image/draw" +) + +// The pixel checks' limits, on a view scaled to analysisWidth. The +// sharpness and detail limits were tuned on test images: a street scene +// passes them with room to spare, and the same scene blurred, or a bare wall, +// doesn't. +const ( + analysisWidth = 256 + minMeanLuma = 55 + maxMeanLuma = 205 + maxClipped = 0.15 // of pixels at luma ≤ 5 or ≥ 250 + minLumaSD = 28 + minSharpness = 100 // variance of the Laplacian + maxSky = 0.65 // of the top two-thirds + maxBand = 0.20 // of the height: a larger dark band at the bottom is a dashboard + minEdges = 0.02 // of pixels with a Sobel magnitude over edgeLevel + edgeLevel = 100 +) + +// The output and the panorama view. +const ( + outWidth = 1600 + outQuality = 85 + maxOut = 1 << 20 + viewFOV = math.Pi / 2 // a panorama's view is 90° wide + maxYaw = math.Pi / 3 // and turned up to 60° either way from the capture heading + maxPixels = 50 << 20 // the largest photo decoded +) + +// Vet runs the pixel checks on a downloaded photo and returns it ready to +// post: a 90° view of a panorama, at the capture heading turned a random +// angle by r, or a flat photo as it is, with any dashboard band cropped off, +// as a JPEG about 1600 px wide and under 1 MB, which carries no metadata. +// The error is a Reject. +func Vet(data []byte, pano bool, r *rand.Rand) ([]byte, error) { + cfg, _, err := image.DecodeConfig(bytes.NewReader(data)) + if err != nil || cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width)*int64(cfg.Height) > maxPixels { + return nil, RejectUnreadable + } + m, _, err := image.Decode(bytes.NewReader(data)) + if err != nil { + return nil, RejectUnreadable + } + src := image.NewRGBA(image.Rect(0, 0, cfg.Width, cfg.Height)) + xdraw.Draw(src, src.Bounds(), m, m.Bounds().Min, xdraw.Src) + + var render func(w int) *image.RGBA + width := min(outWidth, cfg.Width) + switch { + case pano && math.Abs(float64(cfg.Width)/float64(cfg.Height)-2) < 0.05: + yaw := (2*r.Float64() - 1) * maxYaw + render = func(w int) *image.RGBA { return gnomonic(src, yaw, w, w*3/4) } + width = min(outWidth, cfg.Width/2) // a 90° view holds a quarter of the width + case cfg.Width < minWidth: + return nil, RejectSmall + default: + render = func(w int) *image.RGBA { + if w == cfg.Width { + return src + } + return scale(src, w, w*cfg.Height/cfg.Width, xdraw.CatmullRom) + } + } + small := render(analysisWidth) + keep, err := checkPixels(small) + if err != nil { + return nil, err + } + out := render(width) + h := int(math.Round(float64(out.Bounds().Dy()) * keep)) + return encode(out.SubImage(image.Rect(0, 0, out.Bounds().Dx(), h))) +} + +// scale is src scaled to w × h. +func scale(src image.Image, w, h int, s xdraw.Scaler) *image.RGBA { + dst := image.NewRGBA(image.Rect(0, 0, max(w, 1), max(h, 1))) + s.Scale(dst, dst.Bounds(), src, src.Bounds(), xdraw.Src, nil) + return dst +} + +// gnomonic is a w × h rectilinear view, 90° wide and level, of the +// equirectangular panorama src, looking yaw radians right of its centre +// (the capture heading). +func gnomonic(src *image.RGBA, yaw float64, w, h int) *image.RGBA { + dst := image.NewRGBA(image.Rect(0, 0, w, h)) + sw, sh := float64(src.Bounds().Dx()), float64(src.Bounds().Dy()) + f := float64(w) / 2 / math.Tan(viewFOV/2) + for y := range h { + dy := (float64(y) + 0.5 - float64(h)/2) / f + for x := range w { + dx := (float64(x) + 0.5 - float64(w)/2) / f + lon := yaw + math.Atan(dx) // the ray (dx, dy, 1) + lat := -math.Atan2(dy, math.Hypot(dx, 1)) + u := (lon/(2*math.Pi)+0.5)*sw - 0.5 + v := (0.5-lat/math.Pi)*sh - 0.5 + dst.SetRGBA(x, y, bilinear(src, u, v)) + } + } + return dst +} + +// bilinear samples src at (u, v), wrapping round horizontally. +func bilinear(src *image.RGBA, u, v float64) color.RGBA { + w, h := src.Bounds().Dx(), src.Bounds().Dy() + v = math.Max(0, math.Min(float64(h-1), v)) + x0, y0 := int(math.Floor(u)), int(v) + fx, fy := u-math.Floor(u), v-float64(y0) + y1 := min(y0+1, h-1) + x0 = ((x0 % w) + w) % w + x1 := (x0 + 1) % w + var acc [4]float64 + for _, s := range [4]struct { + x, y int + k float64 + }{{x0, y0, (1 - fx) * (1 - fy)}, {x1, y0, fx * (1 - fy)}, {x0, y1, (1 - fx) * fy}, {x1, y1, fx * fy}} { + i := src.PixOffset(s.x, s.y) + for j := range acc { + acc[j] += s.k * float64(src.Pix[i+j]) + } + } + return color.RGBA{uint8(acc[0] + 0.5), uint8(acc[1] + 0.5), uint8(acc[2] + 0.5), 255} +} + +// checkPixels runs the pixel checks on m, cheapest first, and returns the +// share of its height to keep: less than 1 when a dashboard band is cropped +// off the bottom. +func checkPixels(m *image.RGBA) (float64, error) { + w, h := m.Bounds().Dx(), m.Bounds().Dy() + if w < 3 || h < 3 { + return 0, RejectUnreadable + } + luma := make([]float64, w*h) + var sum, sq float64 + clipped := 0 + for y := range h { + for x := range w { + i := m.PixOffset(x, y) + l := 0.299*float64(m.Pix[i]) + 0.587*float64(m.Pix[i+1]) + 0.114*float64(m.Pix[i+2]) + luma[y*w+x] = l + sum += l + sq += l * l + if l <= 5 || l >= 250 { + clipped++ + } + } + } + n := float64(w * h) + mean := sum / n + if mean < minMeanLuma || mean > maxMeanLuma || float64(clipped)/n >= maxClipped { + return 0, RejectExposure + } + if math.Sqrt(max(sq/n-mean*mean, 0)) <= minLumaSD { + return 0, RejectContrast + } + if laplacianVariance(luma, w, h) <= minSharpness { + return 0, RejectBlurry + } + edges := sobel(luma, w, h) + if sky(m, edges, w, h) >= maxSky { + return 0, RejectSky + } + band := dashboard(luma, w, h) + if float64(band) > maxBand*float64(h) { + return 0, RejectDashboard + } + keep := h - band + strong := 0 + for y := 1; y < keep-1; y++ { + for x := 1; x < w-1; x++ { + if edges[y*w+x] > edgeLevel { + strong++ + } + } + } + if float64(strong)/float64((keep-2)*(w-2)) < minEdges { + return 0, RejectBare + } + return float64(keep) / float64(h), nil +} + +// laplacianVariance is the variance of the 4-neighbour Laplacian of luma, +// over its inner pixels: low for a blurred photo. +func laplacianVariance(luma []float64, w, h int) float64 { + var sum, sq float64 + for y := 1; y < h-1; y++ { + for x := 1; x < w-1; x++ { + i := y*w + x + l := luma[i-1] + luma[i+1] + luma[i-w] + luma[i+w] - 4*luma[i] + sum += l + sq += l * l + } + } + n := float64((w - 2) * (h - 2)) + mean := sum / n + return sq/n - mean*mean +} + +// sobel is the Sobel gradient magnitude of luma, 0 on the border. +func sobel(luma []float64, w, h int) []float64 { + out := make([]float64, w*h) + for y := 1; y < h-1; y++ { + for x := 1; x < w-1; x++ { + i := y*w + x + gx := luma[i-w+1] + 2*luma[i+1] + luma[i+w+1] - luma[i-w-1] - 2*luma[i-1] - luma[i+w-1] + gy := luma[i+w-1] + 2*luma[i+w] + luma[i+w+1] - luma[i-w-1] - 2*luma[i-w] - luma[i-w+1] + out[i] = math.Hypot(gx, gy) + } + } + return out +} + +// sky is the share of the top two-thirds of m that looks like sky: smooth, +// and either blue or a bright, colourless overcast. +func sky(m *image.RGBA, edges []float64, w, h int) float64 { + top := h * 2 / 3 + count := 0 + for y := range top { + for x := range w { + if edges[y*w+x] > 40 { + continue + } + i := m.PixOffset(x, y) + r, g, b := int(m.Pix[i]), int(m.Pix[i+1]), int(m.Pix[i+2]) + l := (299*r + 587*g + 114*b) / 1000 + blue := b > r+10 && b >= g && l > 100 + overcast := l > 190 && max(r, g, b)-min(r, g, b) < 25 + if blue || overcast { + count++ + } + } + } + return float64(count) / float64(top*w) +} + +// dashboard is the height in rows of a dark, flat band along the bottom of +// luma, such as a car's dashboard or bonnet. +func dashboard(luma []float64, w, h int) int { + band := 0 + for y := h - 1; y >= 0; y-- { + var sum, sq float64 + for _, l := range luma[y*w : (y+1)*w] { + sum += l + sq += l * l + } + mean := sum / float64(w) + if mean >= 50 || math.Sqrt(max(sq/float64(w)-mean*mean, 0)) >= 12 { + break + } + band++ + } + return band +} + +// encode is m as a JPEG of quality 85, lower if that is over 1 MB. +func encode(m image.Image) ([]byte, error) { + for _, q := range []int{outQuality, 75, 65} { + var b bytes.Buffer + if err := jpeg.Encode(&b, m, &jpeg.Options{Quality: q}); err != nil { + return nil, RejectUnreadable + } + if b.Len() <= maxOut { + return b.Bytes(), nil + } + } + return nil, RejectUnreadable +} diff --git a/cmd/geoguess/geo/pixels_test.go b/cmd/geoguess/geo/pixels_test.go new file mode 100644 index 0000000..8231b36 --- /dev/null +++ b/cmd/geoguess/geo/pixels_test.go @@ -0,0 +1,267 @@ +package geo + +import ( + "bytes" + "image" + "image/color" + "image/jpeg" + "math" + "math/rand/v2" + "testing" + + xdraw "golang.org/x/image/draw" +) + +// The test photos are drawn, not downloaded: a street scene of sky, +// buildings with windows and a textured road, and variations on it that +// each fail one check. + +// scene is the street scene, w × h, drawn with r's noise. +func scene(w, h int, r *rand.Rand) *image.RGBA { + m := image.NewRGBA(image.Rect(0, 0, w, h)) + horizon := h / 3 + for y := range h { + for x := range w { + var c color.RGBA + switch { + case y < horizon: // sky, paler towards the horizon + k := uint8(80 * y / horizon) + c = color.RGBA{90 + k, 140 + k, 220, 255} + case y < h*3/4: // buildings, each its own colour, with windows + b := x * 7 / w + c = color.RGBA{uint8(60 + 25*b), uint8(50 + 15*b), uint8(40 + 10*b), 255} + if (x*40/w)%3 == 1 && ((y-horizon)*20/h)%2 == 1 { + c = color.RGBA{30, 35, 45, 255} + } + default: // road with lane marks + c = color.RGBA{105, 105, 110, 255} + if (x*10/w)%2 == 0 && y > h*7/8 && y < h*7/8+h/40 { + c = color.RGBA{230, 230, 230, 255} + } + } + n := int(r.NormFloat64() * 10) + m.SetRGBA(x, y, color.RGBA{clamp(int(c.R) + n), clamp(int(c.G) + n), clamp(int(c.B) + n), 255}) + } + } + // A tall building cuts into the sky. + for y := h / 6; y < horizon; y++ { + for x := w / 3; x < w/2; x++ { + m.SetRGBA(x, y, color.RGBA{150, 120, 100, 255}) + } + } + return m +} + +func clamp(v int) uint8 { return uint8(max(0, min(255, v))) } + +// mapPixels sets every pixel of m by f of its position and colour. +func mapPixels(m *image.RGBA, f func(x, y int, c color.RGBA) color.RGBA) *image.RGBA { + b := m.Bounds() + for y := b.Min.Y; y < b.Max.Y; y++ { + for x := b.Min.X; x < b.Max.X; x++ { + m.SetRGBA(x, y, f(x, y, m.RGBAAt(x, y))) + } + } + return m +} + +// blur is m out of focus: shrunk by k and scaled back up. +func blur(m *image.RGBA, k int) *image.RGBA { + w, h := m.Bounds().Dx(), m.Bounds().Dy() + return scale(scale(m, w/k, h/k, xdraw.ApproxBiLinear), w, h, xdraw.BiLinear) +} + +func jpegOf(t testing.TB, m image.Image) []byte { + t.Helper() + var b bytes.Buffer + if err := jpeg.Encode(&b, m, &jpeg.Options{Quality: 92}); err != nil { + t.Fatal(err) + } + return b.Bytes() +} + +// testPhotos are the test photos at w × h: name, image, the Reject wanted. +func testPhotos(w, h int) []struct { + name string + m *image.RGBA + want error +} { + r := rand.New(rand.NewPCG(1, 2)) + return []struct { + name string + m *image.RGBA + want error + }{ + {"good", scene(w, h, r), nil}, + {"night", mapPixels(scene(w, h, r), func(_, _ int, c color.RGBA) color.RGBA { + return color.RGBA{c.R / 6, c.G / 6, c.B / 6, 255} + }), RejectExposure}, + {"burnt out", mapPixels(scene(w, h, r), func(_, _ int, c color.RGBA) color.RGBA { + return color.RGBA{clamp(int(c.R) * 3), clamp(int(c.G) * 3), clamp(int(c.B) * 3), 255} + }), RejectExposure}, + {"fog", mapPixels(scene(w, h, r), func(_, _ int, c color.RGBA) color.RGBA { + return color.RGBA{150 + c.R/10, 150 + c.G/10, 150 + c.B/10, 255} + }), RejectContrast}, + {"blurry", blur(scene(w, h, r), max(w/64, 4)), RejectBlurry}, + {"sky", mapPixels(scene(w, h, r), func(x, y int, c color.RGBA) color.RGBA { + if y < h*2/3 { + return color.RGBA{170, 200, 240, 255} + } + return c + }), RejectSky}, + {"dashboard", mapPixels(scene(w, h, r), func(_, y int, c color.RGBA) color.RGBA { + if y >= h*65/100 { + return color.RGBA{20, 20, 22, 255} + } + return c + }), RejectDashboard}, + {"bare wall", bareWall(w, h, r), RejectBare}, + } +} + +// bareWall is a smooth, sharp-grained plaster wall: exposed well, with +// contrast and grain, but no edges. +func bareWall(w, h int, r *rand.Rand) *image.RGBA { + m := image.NewRGBA(image.Rect(0, 0, w, h)) + for y := range h { + for x := range w { + l := 60 + 140*float64(x)/float64(w) + n := r.NormFloat64() * 6 * float64(w) / analysisWidth + m.SetRGBA(x, y, color.RGBA{clamp(int(l + n + 20)), clamp(int(l + n)), clamp(int(l + n - 25)), 255}) + } + } + return m +} + +func TestCheckPixels(t *testing.T) { + for _, tc := range testPhotos(analysisWidth, analysisWidth*3/4) { + _, err := checkPixels(tc.m) + if err != tc.want { + t.Errorf("%s: %v, want %v", tc.name, err, tc.want) + } + } +} + +func TestVet(t *testing.T) { + t.Parallel() + r := rand.New(rand.NewPCG(3, 4)) + for _, tc := range testPhotos(1024, 768) { + out, err := Vet(jpegOf(t, tc.m), false, r) + if err != tc.want { + t.Errorf("%s: %v, want %v", tc.name, err, tc.want) + continue + } + if err != nil { + continue + } + m, format, err := image.Decode(bytes.NewReader(out)) + if err != nil || format != "jpeg" { + t.Fatalf("%s: output %s, %v", tc.name, format, err) + } + if m.Bounds().Dx() != 1024 || m.Bounds().Dy() != 768 || len(out) > maxOut { + t.Errorf("%s: output %v, %d bytes", tc.name, m.Bounds(), len(out)) + } + } +} + +func TestVetScalesAndCrops(t *testing.T) { + t.Parallel() + r := rand.New(rand.NewPCG(5, 6)) + // A wide photo with a short dashboard band: shrunk to 1600 wide, and + // the band cut off. + m := mapPixels(scene(2048, 1536, r), func(_, y int, c color.RGBA) color.RGBA { + if y >= 1536*90/100 { + return color.RGBA{15, 15, 18, 255} + } + return c + }) + out, err := Vet(jpegOf(t, m), false, r) + if err != nil { + t.Fatal(err) + } + cfg, _ := jpeg.DecodeConfig(bytes.NewReader(out)) + if cfg.Width != 1600 || cfg.Height > 1200*91/100 || cfg.Height < 1200*85/100 { + t.Errorf("output %d × %d, want 1600 wide with about the bottom 10%% cut", cfg.Width, cfg.Height) + } +} + +func TestVetRejects(t *testing.T) { + r := rand.New(rand.NewPCG(7, 8)) + for _, tc := range []struct { + name string + data []byte + want error + }{ + {"not an image", []byte("hello"), RejectUnreadable}, + {"truncated", jpegOf(t, scene(1280, 960, r))[:500], RejectUnreadable}, + {"narrow", jpegOf(t, scene(800, 600, r)), RejectSmall}, + } { + if _, err := Vet(tc.data, false, r); err != tc.want { + t.Errorf("%s: %v, want %v", tc.name, err, tc.want) + } + } +} + +// equirect is a panorama that is a street scene ahead (its centre, the +// capture heading) and blank grey all round the rest. +func equirect(w, h int, r *rand.Rand) *image.RGBA { + pano := mapPixels(image.NewRGBA(image.Rect(0, 0, w, h)), func(_, _ int, _ color.RGBA) color.RGBA { + return color.RGBA{128, 128, 128, 255} + }) + front := scene(w/2, h, r) + for y := range h { + for x := range w / 2 { + pano.SetRGBA(w/4+x, y, front.RGBAAt(x, y)) + } + } + return pano +} + +func TestVetPanorama(t *testing.T) { + t.Parallel() + r := rand.New(rand.NewPCG(9, 10)) + data := jpegOf(t, equirect(2048, 1024, r)) + out, err := Vet(data, true, r) + if err != nil { + t.Fatal(err) + } + cfg, _ := jpeg.DecodeConfig(bytes.NewReader(out)) + if cfg.Width != 1024 || cfg.Height != 768 { + t.Errorf("view %d × %d, want 1024 × 768", cfg.Width, cfg.Height) + } + // A photo that isn't 2:1 is checked as a flat photo. + if _, err := Vet(jpegOf(t, scene(1024, 768, r)), true, r); err != nil { + t.Errorf("a pano-flagged 4:3 photo: %v", err) + } +} + +func TestGnomonic(t *testing.T) { + // A panorama whose colour is its longitude: the view's centre column + // shows the yaw, and its edges 45° either side. + src := image.NewRGBA(image.Rect(0, 0, 360, 180)) + mapPixels(src, func(x, _ int, _ color.RGBA) color.RGBA { return color.RGBA{uint8(x * 255 / 359), 0, 0, 255} }) + for _, yaw := range []float64{0, math.Pi / 4, -math.Pi / 3} { + v := gnomonic(src, yaw, 101, 75) + lonAt := func(x int) float64 { return float64(v.RGBAAt(x, 37).R)*359/255 - 180 } + want := yaw * 180 / math.Pi + if got := lonAt(50); math.Abs(got-want) > 2.5 { + t.Errorf("yaw %.0f°: centre shows %.1f°", want, got) + } + if got := lonAt(0); math.Abs(got-(want-45)) > 3 { + t.Errorf("yaw %.0f°: left edge shows %.1f°, want %.1f", want, got, want-45) + } + if got := lonAt(100); math.Abs(got-(want+45)) > 3 { + t.Errorf("yaw %.0f°: right edge shows %.1f°, want %.1f", want, got, want+45) + } + } + // Level: the horizon is the middle row, and straight up is out of view. + src = image.NewRGBA(image.Rect(0, 0, 360, 180)) + mapPixels(src, func(_, y int, _ color.RGBA) color.RGBA { return color.RGBA{0, uint8(y * 255 / 179), 0, 255} }) + v := gnomonic(src, 0, 100, 100) + if g := v.RGBAAt(50, 50).G; g < 120 || g > 135 { + t.Errorf("middle row shows latitude level %d, want about 128", g) + } + if g := v.RGBAAt(50, 0).G; g < 50 { + t.Errorf("top row shows latitude level %d, want under 45° up", g) + } +} diff --git a/cmd/geoguess/geo/place.go b/cmd/geoguess/geo/place.go new file mode 100644 index 0000000..7dba429 --- /dev/null +++ b/cmd/geoguess/geo/place.go @@ -0,0 +1,81 @@ +package geo + +import ( + "context" + "net/http" + "net/url" + "strings" + "time" +) + +// NominatimURL is OpenStreetMap's public Nominatim, whose policy allows at +// most one request a second, with a User-Agent that names the program. +const NominatimURL = "https://nominatim.openstreetmap.org" + +// Place is where a photo was taken, as the reveal names it. +type Place struct { + Name string // "Ballarat, Victoria, Australia" + Country string + CountryCode string // ISO 3166-1 alpha-2, upper case +} + +// Nominatim names places by reverse geocoding, at most once a second. +type Nominatim struct { + url string + client *http.Client + pace *pacer +} + +// NewNominatim is a client for the Nominatim at base (NominatimURL, or a +// self-hosted one). +func NewNominatim(base string, client *http.Client) *Nominatim { + return &Nominatim{url: strings.TrimRight(base, "/"), client: client, pace: &pacer{every: time.Second}} +} + +// Reverse names the town, region and country at p. A place with no country, +// such as the open sea, is RejectNoPlace. +func (n *Nominatim) Reverse(ctx context.Context, p Point) (Place, error) { + if err := n.pace.wait(ctx); err != nil { + return Place{}, err + } + q := url.Values{ + "format": {"jsonv2"}, "lat": {coord(p.Lat)}, "lon": {coord(p.Lon)}, + "zoom": {"10"}, "addressdetails": {"1"}, "accept-language": {"en"}, + } + var a struct { + Error string `json:"error"` + Address map[string]string `json:"address"` + } + r := request{client: n.client, source: "Nominatim", url: n.url + "/reverse?" + q.Encode(), limit: 1 << 20} + if err := r.getJSON(ctx, &a); err != nil { + return Place{}, err + } + country := a.Address["country"] + if a.Error != "" || country == "" { + return Place{}, RejectNoPlace + } + parts := []string{} + add := func(s string) { + if s != "" && (len(parts) == 0 || parts[len(parts)-1] != s) { + parts = append(parts, s) + } + } + add(first(a.Address, "city", "town", "village", "municipality", "hamlet", "suburb", "county")) + add(first(a.Address, "state", "region", "province", "state_district")) + add(country) + return Place{ + Name: strings.Join(parts, ", "), + Country: country, + CountryCode: strings.ToUpper(a.Address["country_code"]), + }, nil +} + +// first is the first of keys that address has. +func first(address map[string]string, keys ...string) string { + for _, k := range keys { + if v := address[k]; v != "" { + return v + } + } + return "" +} diff --git a/cmd/geoguess/geo/place_test.go b/cmd/geoguess/geo/place_test.go new file mode 100644 index 0000000..bf1de01 --- /dev/null +++ b/cmd/geoguess/geo/place_test.go @@ -0,0 +1,56 @@ +package geo + +import ( + "context" + "net/http" + "testing" +) + +func TestNominatimReverse(t *testing.T) { + api := newFakeAPI(t) + answer := "" + status := http.StatusOK + api.handle = func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(status) + w.Write([]byte(answer)) + } + n := NewNominatim(api.URL+"/", api.Client()) + n.pace.every = 0 + ctx := context.Background() + for _, tc := range []struct { + name string + answer string + want Place + err error + }{ + {"city", `{"display_name":"…","address":{"city":"Ballarat","state":"Victoria","country":"Australia","country_code":"au"}}`, + Place{Name: "Ballarat, Victoria, Australia", Country: "Australia", CountryCode: "AU"}, nil}, + {"village and county", `{"address":{"village":"Bob's Bay","county":"Some County","country":"Ireland","country_code":"ie"}}`, + Place{Name: "Bob's Bay, Ireland", Country: "Ireland", CountryCode: "IE"}, nil}, + {"county only", `{"address":{"county":"Alice County","state":"Ohio","country":"United States","country_code":"us"}}`, + Place{Name: "Alice County, Ohio, United States", Country: "United States", CountryCode: "US"}, nil}, + {"city-state", `{"address":{"city":"Singapore","country":"Singapore","country_code":"sg"}}`, + Place{Name: "Singapore", Country: "Singapore", CountryCode: "SG"}, nil}, + {"no country", `{"address":{"state":"International waters"}}`, Place{}, RejectNoPlace}, + {"open sea", `{"error":"Unable to geocode"}`, Place{}, RejectNoPlace}, + } { + answer = tc.answer + got, err := n.Reverse(ctx, Point{-37.5622, 143.8503}) + if got != tc.want || err != tc.err { + t.Errorf("%s: %+v, %v; want %+v, %v", tc.name, got, err, tc.want, tc.err) + } + } + req := api.requests()[0] + q := req.URL.Query() + if req.URL.Path != "/reverse" || q.Get("lat") != "-37.562200" || q.Get("lon") != "143.850300" || q.Get("zoom") != "10" || q.Get("format") != "jsonv2" { + t.Errorf("request %v", req.URL) + } + if req.Header.Get("User-Agent") != userAgent { + t.Errorf("User-Agent %q", req.Header.Get("User-Agent")) + } + + status = http.StatusServiceUnavailable + if _, err := n.Reverse(ctx, Point{}); err != (StatusError{Source: "Nominatim", Code: 503}) { + t.Errorf("503: %v", err) + } +} diff --git a/cmd/geoguess/geo/rules.go b/cmd/geoguess/geo/rules.go new file mode 100644 index 0000000..4fd9479 --- /dev/null +++ b/cmd/geoguess/geo/rules.go @@ -0,0 +1,134 @@ +package geo + +import ( + "math" + "time" +) + +// Reject is why a candidate or its photo was turned down: one of a fixed +// list, so it is safe to log. +type Reject string + +func (r Reject) Error() string { return string(r) } + +// The reasons a candidate is rejected, from its metadata and then its +// pixels. +const ( + RejectQuality Reject = "low quality" + RejectUndated Reject = "no capture time" + RejectOld Reject = "too old" + RejectSmall Reject = "too small" + RejectFisheye Reject = "fisheye" + RejectDark Reject = "not daylight" + RejectDrift Reject = "GPS drift" + RejectSequence Reject = "same sequence" + RejectUsed Reject = "used recently" + RejectUnreadable Reject = "unreadable image" + RejectExposure Reject = "badly exposed" + RejectContrast Reject = "low contrast" + RejectBlurry Reject = "blurry" + RejectSky Reject = "mostly sky" + RejectDashboard Reject = "dashboard" + RejectBare Reject = "little detail" + RejectNoPlace Reject = "no country" +) + +// Rules are the metadata checks, which need no download. +type Rules struct { + MinQuality float64 // the least Mapillary quality_score, when it has one + MaxAge time.Duration // the oldest photo taken +} + +// The fixed limits of the metadata checks. +const ( + minWidth = 1024 // pixels + minGrade = 3 // Panoramax's C + minSunAngle = 12 // degrees above the horizon, a margin for camera clocks + maxDriftKm = 0.05 // between Mapillary's corrected and raw positions +) + +// Check is nil if c passes the metadata checks at now, from cheapest to +// dearest, else the first it fails. +func (r Rules) Check(c Candidate, now time.Time) error { + switch { + case c.Quality >= 0 && c.Quality < r.MinQuality: + return RejectQuality + case c.Grade > 0 && c.Grade < minGrade: + return RejectQuality + case c.Captured.IsZero(): + return RejectUndated + case now.Sub(c.Captured) > r.MaxAge: + return RejectOld + case c.Width > 0 && c.Width < minWidth: + return RejectSmall + case c.Fisheye: + return RejectFisheye + case SunElevation(c.At, c.Captured) <= minSunAngle: + return RejectDark + case Km(c.At, c.Raw) > maxDriftKm: + return RejectDrift + } + return nil +} + +// Filter is the candidates that pass the checks, at most one from each +// sequence and none whose Key used reports as recently used, in their order. It +// calls reject with why each other one was turned down. +func (r Rules) Filter(cands []Candidate, now time.Time, used func(id string) bool, reject func(Reject)) []Candidate { + var out []Candidate + seqs := map[string]bool{} + for _, c := range cands { + err := r.Check(c, now) + switch { + case err != nil: + case used != nil && used(c.Key()): + err = RejectUsed + case c.Sequence != "" && seqs[c.Sequence]: + err = RejectSequence + } + if err != nil { + if reject != nil { + reject(err.(Reject)) + } + continue + } + seqs[c.Sequence] = true + out = append(out, c) + } + return out +} + +// SunElevation is the sun's angle above the horizon in degrees at p and t, +// by NOAA's solar position formulas (good to about a degree for a century +// either side of 2000). +func SunElevation(p Point, t time.Time) float64 { + t = t.UTC() + jd := float64(t.UnixNano())/float64(24*time.Hour) + 2440587.5 + T := (jd - 2451545) / 36525 // Julian centuries since J2000 + + l0 := math.Mod(280.46646+T*(36000.76983+T*0.0003032), 360) // mean longitude + m := 357.52911 + T*(35999.05029-0.0001537*T) // mean anomaly + e := 0.016708634 - T*(0.000042037+0.0000001267*T) // orbit eccentricity + mr := radians(m) + centre := math.Sin(mr)*(1.914602-T*(0.004817+0.000014*T)) + math.Sin(2*mr)*(0.019993-0.000101*T) + math.Sin(3*mr)*0.000289 + ω := radians(125.04 - 1934.136*T) + λ := radians(l0 + centre - 0.00569 - 0.00478*math.Sin(ω)) // apparent longitude + ε0 := 23 + (26+(21.448-T*(46.815+T*(0.00059-T*0.001813)))/60)/60 + ε := radians(ε0 + 0.00256*math.Cos(ω)) // obliquity, corrected + decl := math.Asin(math.Sin(ε) * math.Sin(λ)) + + y := math.Pow(math.Tan(ε/2), 2) + l0r := radians(l0) + eqTime := 4 * degrees(y*math.Sin(2*l0r)-2*e*math.Sin(mr)+4*e*y*math.Sin(mr)*math.Cos(2*l0r)- + 0.5*y*y*math.Sin(4*l0r)-1.25*e*e*math.Sin(2*mr)) // minutes + + minutes := float64(t.Hour()*60+t.Minute()) + float64(t.Second())/60 + float64(t.Nanosecond())/6e10 + solarTime := math.Mod(minutes+eqTime+4*p.Lon, 1440) + if solarTime < 0 { + solarTime += 1440 + } + hourAngle := radians(solarTime/4 - 180) + φ := radians(p.Lat) + cosZenith := math.Sin(φ)*math.Sin(decl) + math.Cos(φ)*math.Cos(decl)*math.Cos(hourAngle) + return 90 - degrees(math.Acos(math.Max(-1, math.Min(1, cosZenith)))) +} diff --git a/cmd/geoguess/geo/rules_test.go b/cmd/geoguess/geo/rules_test.go new file mode 100644 index 0000000..745ac1b --- /dev/null +++ b/cmd/geoguess/geo/rules_test.go @@ -0,0 +1,100 @@ +package geo + +import ( + "math" + "slices" + "testing" + "time" +) + +func TestSunElevation(t *testing.T) { + for _, tc := range []struct { + name string + p Point + t time.Time + want float64 // degrees, to within 0.5 + }{ + // At solar noon the sun is 90° − |latitude − declination| up, and at + // midnight latitude + declination − 90°. + {"June solstice noon at 40°N", Point{40, -105}, time.Date(2010, 6, 21, 19, 1, 40, 0, time.UTC), 73.44}, + {"March equinox noon at the equator", Point{0, 0}, time.Date(2024, 3, 20, 12, 7, 0, 0, time.UTC), 89.7}, + {"December solstice noon in Melbourne", Point{-37.81, 144.96}, time.Date(2025, 12, 21, 2, 19, 0, 0, time.UTC), 75.6}, + {"midnight in Melbourne", Point{-37.81, 144.96}, time.Date(2025, 12, 21, 14, 19, 0, 0, time.UTC), -28.7}, + {"midwinter noon in Tromsø", Point{69.65, 18.96}, time.Date(2025, 12, 21, 10, 45, 0, 0, time.UTC), -2.9}, + {"midsummer midnight in Tromsø", Point{69.65, 18.96}, time.Date(2025, 6, 21, 22, 45, 0, 0, time.UTC), 3.1}, + } { + if got := SunElevation(tc.p, tc.t); math.Abs(got-tc.want) > 0.5 { + t.Errorf("%s: %.2f°, want %.2f°", tc.name, got, tc.want) + } + } +} + +func TestRulesCheck(t *testing.T) { + now := time.Date(2026, 11, 20, 0, 0, 0, 0, time.UTC) + noon := time.Date(2024, 12, 21, 2, 19, 0, 0, time.UTC) // in Melbourne + mel := Point{-37.81, 144.96} + good := Candidate{ID: "1", At: mel, Raw: mel, Captured: noon, Quality: 0.8, Width: 2048} + rules := Rules{MinQuality: 0.5, MaxAge: 10 * 365 * 24 * time.Hour} + for _, tc := range []struct { + name string + edit func(*Candidate) + want error + }{ + {"good", func(*Candidate) {}, nil}, + {"quality unknown", func(c *Candidate) { c.Quality = -1 }, nil}, + {"quality at the minimum", func(c *Candidate) { c.Quality = 0.5 }, nil}, + {"low quality", func(c *Candidate) { c.Quality = 0.49 }, RejectQuality}, + {"grade C", func(c *Candidate) { c.Quality, c.Grade = -1, 3 }, nil}, + {"grade D", func(c *Candidate) { c.Quality, c.Grade = -1, 2 }, RejectQuality}, + {"undated", func(c *Candidate) { c.Captured = time.Time{} }, RejectUndated}, + {"11 years old", func(c *Candidate) { c.Captured = now.AddDate(-11, 0, 0) }, RejectOld}, + {"width unknown", func(c *Candidate) { c.Width = 0 }, nil}, + {"narrow", func(c *Candidate) { c.Width = 1023 }, RejectSmall}, + {"fisheye", func(c *Candidate) { c.Fisheye = true }, RejectFisheye}, + {"night", func(c *Candidate) { c.Captured = noon.Add(12 * time.Hour) }, RejectDark}, + {"dusk", func(c *Candidate) { c.Captured = noon.Add(7 * time.Hour) }, RejectDark}, + {"morning", func(c *Candidate) { c.Captured = noon.Add(-4 * time.Hour) }, nil}, + {"40 m drift", func(c *Candidate) { c.Raw.Lat += 0.00036 }, nil}, + {"60 m drift", func(c *Candidate) { c.Raw.Lat += 0.00054 }, RejectDrift}, + } { + c := good + tc.edit(&c) + if err := rules.Check(c, now); err != tc.want { + t.Errorf("%s: %v, want %v", tc.name, err, tc.want) + } + } +} + +func TestRulesFilter(t *testing.T) { + now := time.Date(2026, 11, 20, 0, 0, 0, 0, time.UTC) + noon := time.Date(2024, 12, 21, 2, 19, 0, 0, time.UTC) + mel := Point{-37.81, 144.96} + c := func(id, seq string, q float64) Candidate { + return Candidate{ID: id, Source: "Mapillary", Sequence: seq, At: mel, Raw: mel, Captured: noon, Quality: q} + } + cands := []Candidate{ + c("1", "a", 0.1), // low quality: doesn't take its sequence + c("2", "a", 0.9), + c("3", "a", 0.9), // same sequence + c("4", "b", 0.9), // used + c("5", "b", 0.9), + c("6", "", 0.9), + c("7", "", 0.9), // no sequence: each is its own + } + var why []Reject + used := func(key string) bool { return key == "Mapillary:4" } + got := Rules{MinQuality: 0.5, MaxAge: 24 * 365 * time.Hour * 10}.Filter(cands, now, used, func(r Reject) { why = append(why, r) }) + var ids []string + for _, g := range got { + ids = append(ids, g.ID) + } + if want := []string{"2", "5", "6", "7"}; !slices.Equal(ids, want) { + t.Errorf("kept %v, want %v", ids, want) + } + if want := []Reject{RejectQuality, RejectSequence, RejectUsed}; !slices.Equal(why, want) { + t.Errorf("rejected for %v, want %v", why, want) + } + if got := (Rules{}).Filter(nil, now, nil, nil); len(got) != 0 { + t.Errorf("Filter(nil) = %v", got) + } +} diff --git a/cmd/geoguess/geo/score.go b/cmd/geoguess/geo/score.go new file mode 100644 index 0000000..ffe0619 --- /dev/null +++ b/cmd/geoguess/geo/score.go @@ -0,0 +1,108 @@ +// Package geo is GeoGuess's game logic: reading a guess, scoring and ranking +// guesses, finding a street-level photo worth playing and naming its place. +// It knows nothing of MCP or of chats. +package geo + +import ( + "cmp" + "math" + "slices" + "strconv" + "time" +) + +// Point is a place on Earth in decimal degrees. +type Point struct { + Lat, Lon float64 +} + +// valid reports whether p's latitude is in [-90, 90] and its longitude in +// [-180, 180]. +func (p Point) valid() bool { + return p.Lat >= -90 && p.Lat <= 90 && p.Lon >= -180 && p.Lon <= 180 +} + +// earthRadius is the mean radius of the Earth in km (IUGG). +const earthRadius = 6371.0088 + +// Km is the great-circle distance between a and b in km, by the haversine +// formula. +func Km(a, b Point) float64 { + φ1, φ2 := radians(a.Lat), radians(b.Lat) + dφ, dλ := φ2-φ1, radians(b.Lon-a.Lon) + h := math.Pow(math.Sin(dφ/2), 2) + math.Cos(φ1)*math.Cos(φ2)*math.Pow(math.Sin(dλ/2), 2) + return 2 * earthRadius * math.Asin(math.Sqrt(min(h, 1))) +} + +func radians(deg float64) float64 { return deg * math.Pi / 180 } +func degrees(rad float64) float64 { return rad * 180 / math.Pi } + +// MaxPoints is the score of a guess within 25 m. +const MaxPoints = 5000 + +// Points is the score of a guess km away: 5000·e^(−km/2000), rounded, and +// the full 5000 within 25 m. +func Points(km float64) int { + if km <= 0.025 { + return MaxPoints + } + return int(math.Round(MaxPoints * math.Exp(-km/2000))) +} + +// Guess is one player's guess in a round: only how far off it was, never +// where it was. +type Guess struct { + User string // the chat's pseudonymous user ID + Km float64 + At time.Time +} + +// Placing is a guess in the results: its rank (from 1) and its points. +type Placing struct { + Guess + Rank int + Points int +} + +// Rank orders guesses by distance, nearest first; a tie goes to the earlier +// guess. Every placing has its own rank. +func Rank(guesses []Guess) []Placing { + sorted := slices.Clone(guesses) + slices.SortStableFunc(sorted, func(a, b Guess) int { + return cmp.Or(cmp.Compare(a.Km, b.Km), a.At.Compare(b.At)) + }) + out := make([]Placing, len(sorted)) + for i, g := range sorted { + out[i] = Placing{Guess: g, Rank: i + 1, Points: Points(g.Km)} + } + return out +} + +// Distance is km as the results show it: metres under 1 km, one decimal under +// 100 km, else whole km with thousands separators. +func Distance(km float64) string { + switch { + case km < 1: + // Rounding can reach 1000 m, which reads better as 1.0 km. + if m := math.Round(km * 1000); m < 1000 { + return strconv.Itoa(int(m)) + " m" + } + return "1.0 km" + case math.Round(km*10)/10 < 100: + return strconv.FormatFloat(km, 'f', 1, 64) + " km" + } + return Thousands(int(math.Round(km))) + " km" +} + +// Thousands is n with a comma between each group of three digits. +func Thousands(n int) string { + s := strconv.Itoa(n) + sign := "" + if s[0] == '-' { + sign, s = "-", s[1:] + } + for i := len(s) - 3; i > 0; i -= 3 { + s = s[:i] + "," + s[i:] + } + return sign + s +} diff --git a/cmd/geoguess/geo/score_test.go b/cmd/geoguess/geo/score_test.go new file mode 100644 index 0000000..7e9e0db --- /dev/null +++ b/cmd/geoguess/geo/score_test.go @@ -0,0 +1,93 @@ +package geo + +import ( + "math" + "slices" + "testing" + "time" +) + +func TestKm(t *testing.T) { + for _, tc := range []struct { + a, b Point + want float64 // km, to within 0.1% + }{ + {Point{-37.8136, 144.9631}, Point{-37.5622, 143.8503}, 101.8}, // Melbourne–Ballarat + {Point{51.5074, -0.1278}, Point{48.8566, 2.3522}, 343.9}, // London–Paris + {Point{0, 0}, Point{0, 180}, math.Pi * earthRadius}, + {Point{90, 0}, Point{-90, 0}, math.Pi * earthRadius}, + {Point{0, 179.9}, Point{0, -179.9}, 22.24}, + {Point{10, 10}, Point{10, 10}, 0}, + } { + got := Km(tc.a, tc.b) + if math.Abs(got-tc.want) > tc.want*0.001+1e-9 { + t.Errorf("Km(%v, %v) = %.3f, want %.3f", tc.a, tc.b, got, tc.want) + } + if back := Km(tc.b, tc.a); math.Abs(back-got) > 1e-9 { + t.Errorf("Km isn't symmetric: %v and %v", got, back) + } + } +} + +func TestPoints(t *testing.T) { + for _, tc := range []struct { + km float64 + want int + }{ + {0, 5000}, {0.025, 5000}, {0.026, 5000}, {1, 4998}, {12, 4970}, + {640, 3631}, {2000, 1839}, {9812, 37}, {20015, 0}, + } { + if got := Points(tc.km); got != tc.want { + t.Errorf("Points(%v) = %d, want %d", tc.km, got, tc.want) + } + } +} + +func TestRank(t *testing.T) { + t0 := time.Date(2026, 11, 19, 14, 30, 0, 0, time.UTC) + guesses := []Guess{ + {User: "u_bob", Km: 640, At: t0.Add(10 * time.Second)}, + {User: "u_alice", Km: 12, At: t0.Add(50 * time.Second)}, + {User: "u_3", Km: 640, At: t0.Add(5 * time.Second)}, // ties with Bob, but earlier + {User: "u_4", Km: 9812, At: t0}, + } + got := Rank(guesses) + want := []Placing{ + {Guess: guesses[1], Rank: 1, Points: 4970}, + {Guess: guesses[2], Rank: 2, Points: 3631}, + {Guess: guesses[0], Rank: 3, Points: 3631}, + {Guess: guesses[3], Rank: 4, Points: 37}, + } + if !slices.Equal(got, want) { + t.Errorf("Rank = %+v\nwant %+v", got, want) + } + if guesses[0].User != "u_bob" { + t.Error("Rank changed its input") + } + if len(Rank(nil)) != 0 { + t.Error("Rank(nil) isn't empty") + } +} + +func TestDistance(t *testing.T) { + for _, tc := range []struct { + km float64 + want string + }{ + {0, "0 m"}, {0.0124, "12 m"}, {0.640, "640 m"}, {0.9996, "1.0 km"}, + {1, "1.0 km"}, {12.345, "12.3 km"}, {99.94, "99.9 km"}, {99.96, "100 km"}, + {640.4, "640 km"}, {9812.2, "9,812 km"}, {20015.1, "20,015 km"}, + } { + if got := Distance(tc.km); got != tc.want { + t.Errorf("Distance(%v) = %q, want %q", tc.km, got, tc.want) + } + } +} + +func TestThousands(t *testing.T) { + for n, want := range map[int]string{0: "0", 37: "37", 999: "999", 1000: "1,000", 4970: "4,970", 1234567: "1,234,567", -1234: "-1,234"} { + if got := Thousands(n); got != want { + t.Errorf("Thousands(%d) = %q, want %q", n, got, want) + } + } +} diff --git a/cmd/geoguess/geo/seeds.go b/cmd/geoguess/geo/seeds.go new file mode 100644 index 0000000..f0fc3c5 --- /dev/null +++ b/cmd/geoguess/geo/seeds.go @@ -0,0 +1,149 @@ +package geo + +import ( + _ "embed" + "encoding/json" + "fmt" + "maps" + "math" + "math/rand/v2" + "slices" + "strings" +) + +// seedsJSON lists regions with street-level coverage, each a centre, a +// radius and a weight, with the continents their countries are in and a cap +// on any one country's total weight. +// +//go:embed seeds.json +var seedsJSON []byte + +// Seed is one region worth searching. +type Seed struct { + CC string `json:"cc"` // ISO 3166-1 alpha-2 + Lat float64 `json:"lat"` + Lon float64 `json:"lon"` + RadiusKm float64 `json:"radius_km"` + Weight float64 `json:"weight"` + Name string `json:"name"` // for people reading the file +} + +// Seeds are the regions a round's photo is looked for in, with the weights +// they are picked by after the per-country cap. +type Seeds struct { + list []Seed + weights []float64 // cumulative +} + +type seedFile struct { + CountryCap float64 `json:"country_cap"` + Continents map[string][]string `json:"continents"` + Seeds []Seed `json:"seeds"` +} + +// LoadSeeds is the embedded seeds, narrowed to regions: a comma-separated +// list of continents (europe, asia, africa, north-america, south-america, +// oceania) and ISO country codes, such as "europe" or "AU,NZ,JP". Empty is +// the whole world. A region with no seeds is an error. +func LoadSeeds(regions string) (*Seeds, error) { + var f seedFile + if err := json.Unmarshal(seedsJSON, &f); err != nil { + return nil, fmt.Errorf("seeds.json: %w", err) + } + want, err := countries(f.Continents, regions) + if err != nil { + return nil, err + } + var list []Seed + for _, s := range f.Seeds { + if want == nil || want[s.CC] { + list = append(list, s) + } + } + if len(list) == 0 { + return nil, fmt.Errorf("no seed regions in %q", regions) + } + return newSeeds(list, f.CountryCap), nil +} + +// countries is the set of country codes regions names, or nil for all. +func countries(continents map[string][]string, regions string) (map[string]bool, error) { + if strings.TrimSpace(regions) == "" { + return nil, nil + } + want := map[string]bool{} + for _, r := range strings.Split(regions, ",") { + r = strings.TrimSpace(r) + name := strings.NewReplacer(" ", "-", "_", "-").Replace(strings.ToLower(r)) + switch ccs, ok := continents[name]; { + case ok: + for _, cc := range ccs { + want[cc] = true + } + case len(r) == 2: + want[strings.ToUpper(r)] = true + case r != "": + return nil, fmt.Errorf("unknown region %q: use a continent (%s) or a two-letter country code", r, strings.Join(slices.Sorted(maps.Keys(continents)), ", ")) + } + } + return want, nil +} + +// newSeeds weighs list, scaling down each country whose seeds weigh more +// than countryCap in all, so a few countries don't take most rounds. +func newSeeds(list []Seed, countryCap float64) *Seeds { + total := map[string]float64{} + for _, s := range list { + total[s.CC] += s.Weight + } + s := &Seeds{list: list, weights: make([]float64, len(list))} + sum := 0.0 + for i, seed := range list { + w := seed.Weight + if countryCap > 0 && total[seed.CC] > countryCap { + w *= countryCap / total[seed.CC] + } + sum += w + s.weights[i] = sum + } + return s +} + +// Len is the number of seeds. +func (s *Seeds) Len() int { return len(s.list) } + +// Has reports whether any seed is in the country cc (ISO 3166-1 alpha-2), +// so a photo found for one round can be matched to another's regions. +func (s *Seeds) Has(cc string) bool { + return slices.ContainsFunc(s.list, func(seed Seed) bool { return seed.CC == cc }) +} + +// Pick is a seed chosen by weight. +func (s *Seeds) Pick(r *rand.Rand) Seed { + x := r.Float64() * s.weights[len(s.weights)-1] + i, _ := slices.BinarySearch(s.weights, x) + return s.list[min(i, len(s.list)-1)] +} + +// Point is a random point within the seed's radius, uniform over the disc. +func (s Seed) Point(r *rand.Rand) Point { + d := s.RadiusKm * math.Sqrt(r.Float64()) / earthRadius // radians + θ := 2 * math.Pi * r.Float64() + lat := s.Lat + degrees(d*math.Cos(θ)) + lon := s.Lon + degrees(d*math.Sin(θ))/math.Max(math.Cos(radians(s.Lat)), 0.01) + lat = math.Max(-89.9, math.Min(89.9, lat)) + lon = math.Mod(lon+540, 360) - 180 + return Point{Lat: lat, Lon: lon} +} + +// boxHalf is half a search box's side in degrees: a 0.04° square is +// 0.0016 deg², under Mapillary's limit of 0.01. +const boxHalf = 0.02 + +// Around is the search box centred on p. +func Around(p Point) BBox { + return BBox{ + MinLon: max(p.Lon-boxHalf, -180), MinLat: max(p.Lat-boxHalf, -90), + MaxLon: min(p.Lon+boxHalf, 180), MaxLat: min(p.Lat+boxHalf, 90), + } +} diff --git a/cmd/geoguess/geo/seeds.json b/cmd/geoguess/geo/seeds.json new file mode 100644 index 0000000..a3e025b --- /dev/null +++ b/cmd/geoguess/geo/seeds.json @@ -0,0 +1,270 @@ +{ + "country_cap": 8, + "continents": { + "europe": ["GB", "IE", "FR", "BE", "NL", "LU", "DE", "CH", "AT", "IT", "ES", "PT", "DK", "NO", "SE", "FI", "IS", "EE", "LV", "LT", "PL", "CZ", "SK", "HU", "SI", "HR", "RS", "BA", "ME", "MK", "AL", "GR", "BG", "RO", "MD", "UA", "CY", "MT"], + "asia": ["TR", "GE", "AM", "IL", "JO", "AE", "QA", "SA", "OM", "KZ", "UZ", "KG", "MN", "IN", "LK", "NP", "BD", "PK", "TH", "VN", "KH", "LA", "MY", "SG", "ID", "PH", "TW", "JP", "KR", "HK"], + "africa": ["ZA", "NA", "BW", "KE", "TZ", "UG", "RW", "ET", "GH", "NG", "SN", "CI", "MA", "TN", "EG", "MG", "MU", "RE"], + "north-america": ["US", "CA", "MX", "GT", "CR", "PA", "CU", "DO", "PR"], + "south-america": ["CO", "EC", "PE", "BO", "CL", "AR", "UY", "PY", "BR"], + "oceania": ["AU", "NZ"] + }, + "seeds": [ + {"cc": "AU", "lat": -37.81, "lon": 144.96, "radius_km": 40, "weight": 3, "name": "Melbourne"}, + {"cc": "AU", "lat": -33.87, "lon": 151.21, "radius_km": 40, "weight": 3, "name": "Sydney"}, + {"cc": "AU", "lat": -27.47, "lon": 153.03, "radius_km": 35, "weight": 2, "name": "Brisbane"}, + {"cc": "AU", "lat": -31.95, "lon": 115.86, "radius_km": 35, "weight": 2, "name": "Perth"}, + {"cc": "AU", "lat": -34.93, "lon": 138.6, "radius_km": 30, "weight": 2, "name": "Adelaide"}, + {"cc": "AU", "lat": -42.88, "lon": 147.33, "radius_km": 25, "weight": 1, "name": "Hobart"}, + {"cc": "AU", "lat": -37.56, "lon": 143.85, "radius_km": 20, "weight": 1, "name": "Ballarat"}, + {"cc": "AU", "lat": -19.26, "lon": 146.82, "radius_km": 20, "weight": 1, "name": "Townsville"}, + {"cc": "AU", "lat": -35.28, "lon": 149.13, "radius_km": 20, "weight": 1, "name": "Canberra"}, + {"cc": "NZ", "lat": -36.85, "lon": 174.76, "radius_km": 30, "weight": 2, "name": "Auckland"}, + {"cc": "NZ", "lat": -41.29, "lon": 174.78, "radius_km": 20, "weight": 1, "name": "Wellington"}, + {"cc": "NZ", "lat": -43.53, "lon": 172.64, "radius_km": 25, "weight": 1, "name": "Christchurch"}, + {"cc": "NZ", "lat": -45.03, "lon": 168.66, "radius_km": 20, "weight": 1, "name": "Queenstown"}, + {"cc": "US", "lat": 40.71, "lon": -74.0, "radius_km": 25, "weight": 2, "name": "New York"}, + {"cc": "US", "lat": 34.05, "lon": -118.24, "radius_km": 40, "weight": 2, "name": "Los Angeles"}, + {"cc": "US", "lat": 41.88, "lon": -87.63, "radius_km": 30, "weight": 2, "name": "Chicago"}, + {"cc": "US", "lat": 29.76, "lon": -95.37, "radius_km": 35, "weight": 1, "name": "Houston"}, + {"cc": "US", "lat": 33.45, "lon": -112.07, "radius_km": 35, "weight": 1, "name": "Phoenix"}, + {"cc": "US", "lat": 47.61, "lon": -122.33, "radius_km": 30, "weight": 2, "name": "Seattle"}, + {"cc": "US", "lat": 37.77, "lon": -122.42, "radius_km": 25, "weight": 2, "name": "San Francisco"}, + {"cc": "US", "lat": 39.74, "lon": -104.99, "radius_km": 30, "weight": 1, "name": "Denver"}, + {"cc": "US", "lat": 25.76, "lon": -80.19, "radius_km": 30, "weight": 1, "name": "Miami"}, + {"cc": "US", "lat": 42.36, "lon": -71.06, "radius_km": 25, "weight": 1, "name": "Boston"}, + {"cc": "US", "lat": 36.17, "lon": -115.14, "radius_km": 25, "weight": 1, "name": "Las Vegas"}, + {"cc": "US", "lat": 45.52, "lon": -122.68, "radius_km": 25, "weight": 1, "name": "Portland"}, + {"cc": "US", "lat": 30.27, "lon": -97.74, "radius_km": 25, "weight": 1, "name": "Austin"}, + {"cc": "US", "lat": 35.23, "lon": -80.84, "radius_km": 25, "weight": 1, "name": "Charlotte"}, + {"cc": "US", "lat": 44.98, "lon": -93.27, "radius_km": 25, "weight": 1, "name": "Minneapolis"}, + {"cc": "US", "lat": 21.31, "lon": -157.86, "radius_km": 20, "weight": 1, "name": "Honolulu"}, + {"cc": "US", "lat": 61.22, "lon": -149.9, "radius_km": 15, "weight": 1, "name": "Anchorage"}, + {"cc": "US", "lat": 35.08, "lon": -106.65, "radius_km": 20, "weight": 1, "name": "Albuquerque"}, + {"cc": "CA", "lat": 43.65, "lon": -79.38, "radius_km": 30, "weight": 2, "name": "Toronto"}, + {"cc": "CA", "lat": 45.5, "lon": -73.57, "radius_km": 25, "weight": 2, "name": "Montreal"}, + {"cc": "CA", "lat": 49.28, "lon": -123.12, "radius_km": 25, "weight": 2, "name": "Vancouver"}, + {"cc": "CA", "lat": 51.05, "lon": -114.07, "radius_km": 25, "weight": 1, "name": "Calgary"}, + {"cc": "CA", "lat": 46.81, "lon": -71.21, "radius_km": 20, "weight": 1, "name": "Quebec City"}, + {"cc": "CA", "lat": 44.65, "lon": -63.57, "radius_km": 20, "weight": 1, "name": "Halifax"}, + {"cc": "MX", "lat": 19.43, "lon": -99.13, "radius_km": 30, "weight": 2, "name": "Mexico City"}, + {"cc": "MX", "lat": 20.67, "lon": -103.35, "radius_km": 25, "weight": 1, "name": "Guadalajara"}, + {"cc": "MX", "lat": 25.69, "lon": -100.32, "radius_km": 25, "weight": 1, "name": "Monterrey"}, + {"cc": "MX", "lat": 21.16, "lon": -86.85, "radius_km": 20, "weight": 1, "name": "Cancun"}, + {"cc": "MX", "lat": 17.07, "lon": -96.72, "radius_km": 15, "weight": 1, "name": "Oaxaca"}, + {"cc": "GT", "lat": 14.63, "lon": -90.51, "radius_km": 15, "weight": 1, "name": "Guatemala City"}, + {"cc": "CR", "lat": 9.93, "lon": -84.08, "radius_km": 20, "weight": 1, "name": "San Jose"}, + {"cc": "PA", "lat": 8.98, "lon": -79.52, "radius_km": 15, "weight": 1, "name": "Panama City"}, + {"cc": "CU", "lat": 23.11, "lon": -82.37, "radius_km": 15, "weight": 1, "name": "Havana"}, + {"cc": "DO", "lat": 18.49, "lon": -69.93, "radius_km": 15, "weight": 1, "name": "Santo Domingo"}, + {"cc": "PR", "lat": 18.47, "lon": -66.11, "radius_km": 20, "weight": 1, "name": "San Juan"}, + {"cc": "CO", "lat": 4.71, "lon": -74.07, "radius_km": 25, "weight": 2, "name": "Bogota"}, + {"cc": "CO", "lat": 6.24, "lon": -75.58, "radius_km": 20, "weight": 1, "name": "Medellin"}, + {"cc": "EC", "lat": -0.18, "lon": -78.47, "radius_km": 15, "weight": 1, "name": "Quito"}, + {"cc": "PE", "lat": -12.05, "lon": -77.04, "radius_km": 25, "weight": 2, "name": "Lima"}, + {"cc": "PE", "lat": -13.53, "lon": -71.97, "radius_km": 15, "weight": 1, "name": "Cusco"}, + {"cc": "BO", "lat": -16.5, "lon": -68.15, "radius_km": 15, "weight": 1, "name": "La Paz"}, + {"cc": "CL", "lat": -33.45, "lon": -70.67, "radius_km": 30, "weight": 2, "name": "Santiago"}, + {"cc": "CL", "lat": -36.83, "lon": -73.05, "radius_km": 20, "weight": 1, "name": "Concepcion"}, + {"cc": "CL", "lat": -41.47, "lon": -72.94, "radius_km": 20, "weight": 1, "name": "Puerto Montt"}, + {"cc": "AR", "lat": -34.6, "lon": -58.38, "radius_km": 30, "weight": 2, "name": "Buenos Aires"}, + {"cc": "AR", "lat": -31.42, "lon": -64.18, "radius_km": 25, "weight": 1, "name": "Cordoba"}, + {"cc": "AR", "lat": -32.89, "lon": -68.84, "radius_km": 20, "weight": 1, "name": "Mendoza"}, + {"cc": "AR", "lat": -41.13, "lon": -71.31, "radius_km": 15, "weight": 1, "name": "Bariloche"}, + {"cc": "UY", "lat": -34.9, "lon": -56.16, "radius_km": 20, "weight": 1, "name": "Montevideo"}, + {"cc": "PY", "lat": -25.26, "lon": -57.58, "radius_km": 15, "weight": 1, "name": "Asuncion"}, + {"cc": "BR", "lat": -23.55, "lon": -46.63, "radius_km": 35, "weight": 3, "name": "Sao Paulo"}, + {"cc": "BR", "lat": -22.91, "lon": -43.17, "radius_km": 30, "weight": 2, "name": "Rio de Janeiro"}, + {"cc": "BR", "lat": -15.79, "lon": -47.88, "radius_km": 25, "weight": 1, "name": "Brasilia"}, + {"cc": "BR", "lat": -30.03, "lon": -51.23, "radius_km": 25, "weight": 1, "name": "Porto Alegre"}, + {"cc": "BR", "lat": -25.43, "lon": -49.27, "radius_km": 25, "weight": 1, "name": "Curitiba"}, + {"cc": "BR", "lat": -12.97, "lon": -38.5, "radius_km": 25, "weight": 1, "name": "Salvador"}, + {"cc": "BR", "lat": -3.73, "lon": -38.52, "radius_km": 20, "weight": 1, "name": "Fortaleza"}, + {"cc": "BR", "lat": -19.92, "lon": -43.94, "radius_km": 25, "weight": 1, "name": "Belo Horizonte"}, + {"cc": "GB", "lat": 51.51, "lon": -0.13, "radius_km": 30, "weight": 3, "name": "London"}, + {"cc": "GB", "lat": 53.48, "lon": -2.24, "radius_km": 25, "weight": 2, "name": "Manchester"}, + {"cc": "GB", "lat": 55.95, "lon": -3.19, "radius_km": 20, "weight": 1, "name": "Edinburgh"}, + {"cc": "GB", "lat": 52.49, "lon": -1.89, "radius_km": 25, "weight": 1, "name": "Birmingham"}, + {"cc": "GB", "lat": 51.45, "lon": -2.59, "radius_km": 20, "weight": 1, "name": "Bristol"}, + {"cc": "GB", "lat": 57.48, "lon": -4.22, "radius_km": 30, "weight": 1, "name": "Inverness"}, + {"cc": "GB", "lat": 54.6, "lon": -5.93, "radius_km": 20, "weight": 1, "name": "Belfast"}, + {"cc": "IE", "lat": 53.35, "lon": -6.26, "radius_km": 25, "weight": 2, "name": "Dublin"}, + {"cc": "IE", "lat": 51.9, "lon": -8.47, "radius_km": 20, "weight": 1, "name": "Cork"}, + {"cc": "IE", "lat": 53.27, "lon": -9.05, "radius_km": 25, "weight": 1, "name": "Galway"}, + {"cc": "FR", "lat": 48.86, "lon": 2.35, "radius_km": 25, "weight": 3, "name": "Paris"}, + {"cc": "FR", "lat": 45.76, "lon": 4.84, "radius_km": 25, "weight": 2, "name": "Lyon"}, + {"cc": "FR", "lat": 43.3, "lon": 5.37, "radius_km": 25, "weight": 2, "name": "Marseille"}, + {"cc": "FR", "lat": 44.84, "lon": -0.58, "radius_km": 25, "weight": 1, "name": "Bordeaux"}, + {"cc": "FR", "lat": 48.11, "lon": -1.68, "radius_km": 25, "weight": 2, "name": "Rennes"}, + {"cc": "FR", "lat": 43.6, "lon": 1.44, "radius_km": 25, "weight": 1, "name": "Toulouse"}, + {"cc": "FR", "lat": 47.22, "lon": -1.55, "radius_km": 25, "weight": 1, "name": "Nantes"}, + {"cc": "FR", "lat": 48.57, "lon": 7.75, "radius_km": 20, "weight": 1, "name": "Strasbourg"}, + {"cc": "FR", "lat": 45.19, "lon": 5.72, "radius_km": 25, "weight": 1, "name": "Grenoble"}, + {"cc": "FR", "lat": 43.7, "lon": 7.27, "radius_km": 20, "weight": 1, "name": "Nice"}, + {"cc": "FR", "lat": 50.63, "lon": 3.06, "radius_km": 20, "weight": 1, "name": "Lille"}, + {"cc": "FR", "lat": 48.39, "lon": -4.49, "radius_km": 30, "weight": 1, "name": "Brest"}, + {"cc": "BE", "lat": 50.85, "lon": 4.35, "radius_km": 20, "weight": 2, "name": "Brussels"}, + {"cc": "BE", "lat": 51.05, "lon": 3.72, "radius_km": 20, "weight": 1, "name": "Ghent"}, + {"cc": "NL", "lat": 52.37, "lon": 4.9, "radius_km": 25, "weight": 2, "name": "Amsterdam"}, + {"cc": "NL", "lat": 51.92, "lon": 4.48, "radius_km": 20, "weight": 1, "name": "Rotterdam"}, + {"cc": "NL", "lat": 52.09, "lon": 5.12, "radius_km": 20, "weight": 1, "name": "Utrecht"}, + {"cc": "NL", "lat": 53.22, "lon": 6.57, "radius_km": 20, "weight": 1, "name": "Groningen"}, + {"cc": "LU", "lat": 49.61, "lon": 6.13, "radius_km": 15, "weight": 1, "name": "Luxembourg"}, + {"cc": "DE", "lat": 52.52, "lon": 13.4, "radius_km": 30, "weight": 3, "name": "Berlin"}, + {"cc": "DE", "lat": 48.14, "lon": 11.58, "radius_km": 30, "weight": 2, "name": "Munich"}, + {"cc": "DE", "lat": 53.55, "lon": 9.99, "radius_km": 25, "weight": 2, "name": "Hamburg"}, + {"cc": "DE", "lat": 50.94, "lon": 6.96, "radius_km": 25, "weight": 2, "name": "Cologne"}, + {"cc": "DE", "lat": 50.11, "lon": 8.68, "radius_km": 25, "weight": 1, "name": "Frankfurt"}, + {"cc": "DE", "lat": 48.78, "lon": 9.18, "radius_km": 25, "weight": 1, "name": "Stuttgart"}, + {"cc": "DE", "lat": 51.34, "lon": 12.37, "radius_km": 20, "weight": 1, "name": "Leipzig"}, + {"cc": "DE", "lat": 51.05, "lon": 13.74, "radius_km": 20, "weight": 1, "name": "Dresden"}, + {"cc": "DE", "lat": 47.99, "lon": 7.84, "radius_km": 20, "weight": 1, "name": "Freiburg"}, + {"cc": "CH", "lat": 47.38, "lon": 8.54, "radius_km": 20, "weight": 2, "name": "Zurich"}, + {"cc": "CH", "lat": 46.2, "lon": 6.14, "radius_km": 20, "weight": 1, "name": "Geneva"}, + {"cc": "CH", "lat": 46.95, "lon": 7.45, "radius_km": 20, "weight": 1, "name": "Bern"}, + {"cc": "AT", "lat": 48.21, "lon": 16.37, "radius_km": 25, "weight": 2, "name": "Vienna"}, + {"cc": "AT", "lat": 47.27, "lon": 11.39, "radius_km": 20, "weight": 1, "name": "Innsbruck"}, + {"cc": "AT", "lat": 47.81, "lon": 13.04, "radius_km": 20, "weight": 1, "name": "Salzburg"}, + {"cc": "IT", "lat": 41.9, "lon": 12.5, "radius_km": 25, "weight": 2, "name": "Rome"}, + {"cc": "IT", "lat": 45.46, "lon": 9.19, "radius_km": 25, "weight": 2, "name": "Milan"}, + {"cc": "IT", "lat": 40.85, "lon": 14.27, "radius_km": 20, "weight": 1, "name": "Naples"}, + {"cc": "IT", "lat": 43.77, "lon": 11.26, "radius_km": 20, "weight": 1, "name": "Florence"}, + {"cc": "IT", "lat": 45.44, "lon": 12.32, "radius_km": 15, "weight": 1, "name": "Venice"}, + {"cc": "IT", "lat": 45.07, "lon": 7.69, "radius_km": 20, "weight": 1, "name": "Turin"}, + {"cc": "IT", "lat": 38.12, "lon": 13.36, "radius_km": 20, "weight": 1, "name": "Palermo"}, + {"cc": "IT", "lat": 44.49, "lon": 11.34, "radius_km": 20, "weight": 1, "name": "Bologna"}, + {"cc": "ES", "lat": 40.42, "lon": -3.7, "radius_km": 30, "weight": 2, "name": "Madrid"}, + {"cc": "ES", "lat": 41.39, "lon": 2.17, "radius_km": 25, "weight": 2, "name": "Barcelona"}, + {"cc": "ES", "lat": 37.39, "lon": -5.98, "radius_km": 20, "weight": 1, "name": "Seville"}, + {"cc": "ES", "lat": 39.47, "lon": -0.38, "radius_km": 20, "weight": 1, "name": "Valencia"}, + {"cc": "ES", "lat": 43.26, "lon": -2.93, "radius_km": 20, "weight": 1, "name": "Bilbao"}, + {"cc": "ES", "lat": 42.88, "lon": -8.54, "radius_km": 20, "weight": 1, "name": "Santiago de Compostela"}, + {"cc": "ES", "lat": 28.12, "lon": -15.43, "radius_km": 20, "weight": 1, "name": "Las Palmas"}, + {"cc": "PT", "lat": 38.72, "lon": -9.14, "radius_km": 25, "weight": 2, "name": "Lisbon"}, + {"cc": "PT", "lat": 41.15, "lon": -8.61, "radius_km": 20, "weight": 1, "name": "Porto"}, + {"cc": "PT", "lat": 37.02, "lon": -7.93, "radius_km": 25, "weight": 1, "name": "Faro"}, + {"cc": "DK", "lat": 55.68, "lon": 12.57, "radius_km": 20, "weight": 2, "name": "Copenhagen"}, + {"cc": "DK", "lat": 56.16, "lon": 10.2, "radius_km": 20, "weight": 1, "name": "Aarhus"}, + {"cc": "NO", "lat": 59.91, "lon": 10.75, "radius_km": 25, "weight": 2, "name": "Oslo"}, + {"cc": "NO", "lat": 60.39, "lon": 5.32, "radius_km": 20, "weight": 1, "name": "Bergen"}, + {"cc": "NO", "lat": 63.43, "lon": 10.4, "radius_km": 20, "weight": 1, "name": "Trondheim"}, + {"cc": "NO", "lat": 69.65, "lon": 18.96, "radius_km": 15, "weight": 1, "name": "Tromso"}, + {"cc": "SE", "lat": 59.33, "lon": 18.07, "radius_km": 25, "weight": 2, "name": "Stockholm"}, + {"cc": "SE", "lat": 57.71, "lon": 11.97, "radius_km": 20, "weight": 1, "name": "Gothenburg"}, + {"cc": "SE", "lat": 55.6, "lon": 13.0, "radius_km": 20, "weight": 1, "name": "Malmo"}, + {"cc": "FI", "lat": 60.17, "lon": 24.94, "radius_km": 25, "weight": 2, "name": "Helsinki"}, + {"cc": "FI", "lat": 61.5, "lon": 23.76, "radius_km": 20, "weight": 1, "name": "Tampere"}, + {"cc": "FI", "lat": 65.01, "lon": 25.47, "radius_km": 20, "weight": 1, "name": "Oulu"}, + {"cc": "IS", "lat": 64.15, "lon": -21.94, "radius_km": 20, "weight": 1, "name": "Reykjavik"}, + {"cc": "EE", "lat": 59.44, "lon": 24.75, "radius_km": 20, "weight": 1, "name": "Tallinn"}, + {"cc": "LV", "lat": 56.95, "lon": 24.11, "radius_km": 20, "weight": 1, "name": "Riga"}, + {"cc": "LT", "lat": 54.69, "lon": 25.28, "radius_km": 20, "weight": 1, "name": "Vilnius"}, + {"cc": "PL", "lat": 52.23, "lon": 21.01, "radius_km": 25, "weight": 2, "name": "Warsaw"}, + {"cc": "PL", "lat": 50.06, "lon": 19.94, "radius_km": 20, "weight": 1, "name": "Krakow"}, + {"cc": "PL", "lat": 51.11, "lon": 17.04, "radius_km": 20, "weight": 1, "name": "Wroclaw"}, + {"cc": "PL", "lat": 54.35, "lon": 18.65, "radius_km": 20, "weight": 1, "name": "Gdansk"}, + {"cc": "CZ", "lat": 50.08, "lon": 14.44, "radius_km": 25, "weight": 2, "name": "Prague"}, + {"cc": "CZ", "lat": 49.2, "lon": 16.61, "radius_km": 20, "weight": 1, "name": "Brno"}, + {"cc": "SK", "lat": 48.15, "lon": 17.11, "radius_km": 20, "weight": 1, "name": "Bratislava"}, + {"cc": "HU", "lat": 47.5, "lon": 19.04, "radius_km": 25, "weight": 2, "name": "Budapest"}, + {"cc": "SI", "lat": 46.06, "lon": 14.51, "radius_km": 20, "weight": 1, "name": "Ljubljana"}, + {"cc": "HR", "lat": 45.81, "lon": 15.98, "radius_km": 20, "weight": 1, "name": "Zagreb"}, + {"cc": "HR", "lat": 43.51, "lon": 16.44, "radius_km": 20, "weight": 1, "name": "Split"}, + {"cc": "RS", "lat": 44.79, "lon": 20.45, "radius_km": 20, "weight": 1, "name": "Belgrade"}, + {"cc": "BA", "lat": 43.86, "lon": 18.41, "radius_km": 15, "weight": 1, "name": "Sarajevo"}, + {"cc": "ME", "lat": 42.43, "lon": 19.26, "radius_km": 15, "weight": 1, "name": "Podgorica"}, + {"cc": "MK", "lat": 41.99, "lon": 21.43, "radius_km": 15, "weight": 1, "name": "Skopje"}, + {"cc": "AL", "lat": 41.33, "lon": 19.82, "radius_km": 15, "weight": 1, "name": "Tirana"}, + {"cc": "GR", "lat": 37.98, "lon": 23.73, "radius_km": 25, "weight": 2, "name": "Athens"}, + {"cc": "GR", "lat": 40.64, "lon": 22.94, "radius_km": 20, "weight": 1, "name": "Thessaloniki"}, + {"cc": "GR", "lat": 35.34, "lon": 25.13, "radius_km": 20, "weight": 1, "name": "Heraklion"}, + {"cc": "BG", "lat": 42.7, "lon": 23.32, "radius_km": 20, "weight": 1, "name": "Sofia"}, + {"cc": "RO", "lat": 44.43, "lon": 26.1, "radius_km": 25, "weight": 1, "name": "Bucharest"}, + {"cc": "RO", "lat": 46.77, "lon": 23.59, "radius_km": 20, "weight": 1, "name": "Cluj-Napoca"}, + {"cc": "MD", "lat": 47.01, "lon": 28.86, "radius_km": 15, "weight": 1, "name": "Chisinau"}, + {"cc": "UA", "lat": 50.45, "lon": 30.52, "radius_km": 25, "weight": 1, "name": "Kyiv"}, + {"cc": "UA", "lat": 49.84, "lon": 24.03, "radius_km": 20, "weight": 1, "name": "Lviv"}, + {"cc": "CY", "lat": 34.68, "lon": 33.04, "radius_km": 20, "weight": 1, "name": "Limassol"}, + {"cc": "MT", "lat": 35.9, "lon": 14.51, "radius_km": 10, "weight": 1, "name": "Valletta"}, + {"cc": "TR", "lat": 41.01, "lon": 28.98, "radius_km": 30, "weight": 2, "name": "Istanbul"}, + {"cc": "TR", "lat": 39.93, "lon": 32.86, "radius_km": 25, "weight": 1, "name": "Ankara"}, + {"cc": "TR", "lat": 38.42, "lon": 27.14, "radius_km": 20, "weight": 1, "name": "Izmir"}, + {"cc": "TR", "lat": 36.9, "lon": 30.7, "radius_km": 20, "weight": 1, "name": "Antalya"}, + {"cc": "GE", "lat": 41.72, "lon": 44.79, "radius_km": 15, "weight": 1, "name": "Tbilisi"}, + {"cc": "AM", "lat": 40.18, "lon": 44.51, "radius_km": 15, "weight": 1, "name": "Yerevan"}, + {"cc": "IL", "lat": 32.08, "lon": 34.78, "radius_km": 20, "weight": 1, "name": "Tel Aviv"}, + {"cc": "JO", "lat": 31.95, "lon": 35.93, "radius_km": 20, "weight": 1, "name": "Amman"}, + {"cc": "AE", "lat": 25.2, "lon": 55.27, "radius_km": 25, "weight": 1, "name": "Dubai"}, + {"cc": "QA", "lat": 25.29, "lon": 51.53, "radius_km": 15, "weight": 1, "name": "Doha"}, + {"cc": "SA", "lat": 24.71, "lon": 46.68, "radius_km": 25, "weight": 1, "name": "Riyadh"}, + {"cc": "OM", "lat": 23.59, "lon": 58.41, "radius_km": 20, "weight": 1, "name": "Muscat"}, + {"cc": "KZ", "lat": 43.24, "lon": 76.89, "radius_km": 20, "weight": 1, "name": "Almaty"}, + {"cc": "UZ", "lat": 41.3, "lon": 69.24, "radius_km": 20, "weight": 1, "name": "Tashkent"}, + {"cc": "KG", "lat": 42.87, "lon": 74.59, "radius_km": 15, "weight": 1, "name": "Bishkek"}, + {"cc": "MN", "lat": 47.89, "lon": 106.91, "radius_km": 15, "weight": 1, "name": "Ulaanbaatar"}, + {"cc": "IN", "lat": 28.61, "lon": 77.21, "radius_km": 30, "weight": 2, "name": "Delhi"}, + {"cc": "IN", "lat": 19.08, "lon": 72.88, "radius_km": 30, "weight": 2, "name": "Mumbai"}, + {"cc": "IN", "lat": 12.97, "lon": 77.59, "radius_km": 30, "weight": 2, "name": "Bengaluru"}, + {"cc": "IN", "lat": 13.08, "lon": 80.27, "radius_km": 25, "weight": 1, "name": "Chennai"}, + {"cc": "IN", "lat": 22.57, "lon": 88.36, "radius_km": 25, "weight": 1, "name": "Kolkata"}, + {"cc": "IN", "lat": 17.39, "lon": 78.49, "radius_km": 25, "weight": 1, "name": "Hyderabad"}, + {"cc": "IN", "lat": 18.52, "lon": 73.86, "radius_km": 25, "weight": 1, "name": "Pune"}, + {"cc": "IN", "lat": 26.91, "lon": 75.79, "radius_km": 20, "weight": 1, "name": "Jaipur"}, + {"cc": "IN", "lat": 9.93, "lon": 76.27, "radius_km": 20, "weight": 1, "name": "Kochi"}, + {"cc": "LK", "lat": 6.93, "lon": 79.86, "radius_km": 20, "weight": 1, "name": "Colombo"}, + {"cc": "NP", "lat": 27.72, "lon": 85.32, "radius_km": 15, "weight": 1, "name": "Kathmandu"}, + {"cc": "BD", "lat": 23.81, "lon": 90.41, "radius_km": 20, "weight": 1, "name": "Dhaka"}, + {"cc": "PK", "lat": 31.52, "lon": 74.36, "radius_km": 20, "weight": 1, "name": "Lahore"}, + {"cc": "TH", "lat": 13.76, "lon": 100.5, "radius_km": 30, "weight": 2, "name": "Bangkok"}, + {"cc": "TH", "lat": 18.79, "lon": 98.99, "radius_km": 20, "weight": 1, "name": "Chiang Mai"}, + {"cc": "TH", "lat": 7.88, "lon": 98.39, "radius_km": 20, "weight": 1, "name": "Phuket"}, + {"cc": "VN", "lat": 21.03, "lon": 105.85, "radius_km": 25, "weight": 1, "name": "Hanoi"}, + {"cc": "VN", "lat": 10.82, "lon": 106.63, "radius_km": 25, "weight": 1, "name": "Ho Chi Minh City"}, + {"cc": "VN", "lat": 16.05, "lon": 108.22, "radius_km": 20, "weight": 1, "name": "Da Nang"}, + {"cc": "KH", "lat": 11.56, "lon": 104.92, "radius_km": 15, "weight": 1, "name": "Phnom Penh"}, + {"cc": "LA", "lat": 17.98, "lon": 102.63, "radius_km": 15, "weight": 1, "name": "Vientiane"}, + {"cc": "MY", "lat": 3.14, "lon": 101.69, "radius_km": 25, "weight": 2, "name": "Kuala Lumpur"}, + {"cc": "MY", "lat": 5.41, "lon": 100.33, "radius_km": 20, "weight": 1, "name": "Penang"}, + {"cc": "SG", "lat": 1.35, "lon": 103.82, "radius_km": 15, "weight": 2, "name": "Singapore"}, + {"cc": "ID", "lat": -6.21, "lon": 106.85, "radius_km": 30, "weight": 2, "name": "Jakarta"}, + {"cc": "ID", "lat": -8.65, "lon": 115.22, "radius_km": 25, "weight": 1, "name": "Bali"}, + {"cc": "ID", "lat": -7.8, "lon": 110.36, "radius_km": 20, "weight": 1, "name": "Yogyakarta"}, + {"cc": "ID", "lat": -7.26, "lon": 112.75, "radius_km": 20, "weight": 1, "name": "Surabaya"}, + {"cc": "PH", "lat": 14.6, "lon": 120.98, "radius_km": 25, "weight": 2, "name": "Manila"}, + {"cc": "PH", "lat": 10.32, "lon": 123.89, "radius_km": 20, "weight": 1, "name": "Cebu"}, + {"cc": "TW", "lat": 25.03, "lon": 121.57, "radius_km": 25, "weight": 2, "name": "Taipei"}, + {"cc": "TW", "lat": 22.63, "lon": 120.3, "radius_km": 20, "weight": 1, "name": "Kaohsiung"}, + {"cc": "JP", "lat": 35.68, "lon": 139.69, "radius_km": 35, "weight": 3, "name": "Tokyo"}, + {"cc": "JP", "lat": 34.69, "lon": 135.5, "radius_km": 30, "weight": 2, "name": "Osaka"}, + {"cc": "JP", "lat": 35.01, "lon": 135.77, "radius_km": 20, "weight": 1, "name": "Kyoto"}, + {"cc": "JP", "lat": 43.06, "lon": 141.35, "radius_km": 25, "weight": 1, "name": "Sapporo"}, + {"cc": "JP", "lat": 33.59, "lon": 130.4, "radius_km": 25, "weight": 1, "name": "Fukuoka"}, + {"cc": "JP", "lat": 35.18, "lon": 136.91, "radius_km": 25, "weight": 1, "name": "Nagoya"}, + {"cc": "JP", "lat": 34.39, "lon": 132.46, "radius_km": 20, "weight": 1, "name": "Hiroshima"}, + {"cc": "JP", "lat": 38.27, "lon": 140.87, "radius_km": 20, "weight": 1, "name": "Sendai"}, + {"cc": "KR", "lat": 37.57, "lon": 126.98, "radius_km": 30, "weight": 2, "name": "Seoul"}, + {"cc": "KR", "lat": 35.18, "lon": 129.08, "radius_km": 25, "weight": 1, "name": "Busan"}, + {"cc": "HK", "lat": 22.32, "lon": 114.17, "radius_km": 15, "weight": 1, "name": "Hong Kong"}, + {"cc": "ZA", "lat": -33.92, "lon": 18.42, "radius_km": 30, "weight": 2, "name": "Cape Town"}, + {"cc": "ZA", "lat": -26.2, "lon": 28.05, "radius_km": 30, "weight": 2, "name": "Johannesburg"}, + {"cc": "ZA", "lat": -29.86, "lon": 31.02, "radius_km": 25, "weight": 1, "name": "Durban"}, + {"cc": "ZA", "lat": -25.75, "lon": 28.19, "radius_km": 20, "weight": 1, "name": "Pretoria"}, + {"cc": "NA", "lat": -22.56, "lon": 17.08, "radius_km": 15, "weight": 1, "name": "Windhoek"}, + {"cc": "BW", "lat": -24.65, "lon": 25.91, "radius_km": 15, "weight": 1, "name": "Gaborone"}, + {"cc": "KE", "lat": -1.29, "lon": 36.82, "radius_km": 25, "weight": 1, "name": "Nairobi"}, + {"cc": "TZ", "lat": -6.79, "lon": 39.21, "radius_km": 20, "weight": 1, "name": "Dar es Salaam"}, + {"cc": "UG", "lat": 0.35, "lon": 32.58, "radius_km": 20, "weight": 1, "name": "Kampala"}, + {"cc": "RW", "lat": -1.95, "lon": 30.06, "radius_km": 15, "weight": 1, "name": "Kigali"}, + {"cc": "ET", "lat": 9.03, "lon": 38.74, "radius_km": 20, "weight": 1, "name": "Addis Ababa"}, + {"cc": "GH", "lat": 5.6, "lon": -0.19, "radius_km": 20, "weight": 1, "name": "Accra"}, + {"cc": "NG", "lat": 6.52, "lon": 3.38, "radius_km": 25, "weight": 1, "name": "Lagos"}, + {"cc": "SN", "lat": 14.72, "lon": -17.47, "radius_km": 15, "weight": 1, "name": "Dakar"}, + {"cc": "CI", "lat": 5.36, "lon": -4.01, "radius_km": 20, "weight": 1, "name": "Abidjan"}, + {"cc": "MA", "lat": 33.57, "lon": -7.59, "radius_km": 25, "weight": 1, "name": "Casablanca"}, + {"cc": "MA", "lat": 31.63, "lon": -8.01, "radius_km": 20, "weight": 1, "name": "Marrakesh"}, + {"cc": "TN", "lat": 36.81, "lon": 10.18, "radius_km": 20, "weight": 1, "name": "Tunis"}, + {"cc": "EG", "lat": 30.04, "lon": 31.24, "radius_km": 25, "weight": 1, "name": "Cairo"}, + {"cc": "MG", "lat": -18.88, "lon": 47.51, "radius_km": 15, "weight": 1, "name": "Antananarivo"}, + {"cc": "MU", "lat": -20.16, "lon": 57.5, "radius_km": 20, "weight": 1, "name": "Port Louis"}, + {"cc": "RE", "lat": -21.12, "lon": 55.53, "radius_km": 20, "weight": 1, "name": "Reunion"} + ] +} diff --git a/cmd/geoguess/geo/seeds_test.go b/cmd/geoguess/geo/seeds_test.go new file mode 100644 index 0000000..bbb4ec8 --- /dev/null +++ b/cmd/geoguess/geo/seeds_test.go @@ -0,0 +1,155 @@ +package geo + +import ( + "encoding/json" + "math" + "math/rand/v2" + "strings" + "testing" +) + +func TestSeedsFile(t *testing.T) { + var f seedFile + if err := json.Unmarshal(seedsJSON, &f); err != nil { + t.Fatal(err) + } + if len(f.Seeds) < 150 || f.CountryCap <= 0 { + t.Errorf("%d seeds, cap %v", len(f.Seeds), f.CountryCap) + } + continent := map[string]string{} + for name, ccs := range f.Continents { + for _, cc := range ccs { + if other, ok := continent[cc]; ok { + t.Errorf("%s is in %s and %s", cc, other, name) + } + continent[cc] = name + } + } + countries := map[string]bool{} + for _, s := range f.Seeds { + countries[s.CC] = true + if _, ok := continent[s.CC]; !ok { + t.Errorf("%s (%s) is in no continent", s.CC, s.Name) + } + if !(Point{s.Lat, s.Lon}).valid() || s.RadiusKm <= 0 || s.RadiusKm > 100 || s.Weight <= 0 || s.Name == "" { + t.Errorf("seed %+v", s) + } + } + if len(countries) < 60 || len(f.Continents) != 6 { + t.Errorf("%d countries in %d continents", len(countries), len(f.Continents)) + } +} + +func TestLoadSeeds(t *testing.T) { + world, err := LoadSeeds("") + if err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + regions string + want func(Seed) bool + err string + }{ + {"europe", func(s Seed) bool { return s.Lon > -30 && s.Lon < 45 && s.Lat > 27 }, ""}, + {"AU,nz, JP", func(s Seed) bool { return s.CC == "AU" || s.CC == "NZ" || s.CC == "JP" }, ""}, + {"South America", func(s Seed) bool { return s.Lat < 13 && s.Lon < -34 && s.Lon > -82 }, ""}, + {"oceania,FR", func(s Seed) bool { return s.CC == "AU" || s.CC == "NZ" || s.CC == "FR" }, ""}, + {"atlantis", nil, "unknown region"}, + {"XX", nil, "no seed regions"}, + } { + s, err := LoadSeeds(tc.regions) + if tc.err != "" { + if err == nil || !strings.Contains(err.Error(), tc.err) { + t.Errorf("%q: %v, want %q", tc.regions, err, tc.err) + } + continue + } + if err != nil || s.Len() == 0 || s.Len() >= world.Len() { + t.Errorf("%q: %d seeds, %v", tc.regions, s.Len(), err) + continue + } + for _, seed := range s.list { + if !tc.want(seed) { + t.Errorf("%q: has %+v", tc.regions, seed) + } + } + } +} + +func TestSeedsCapCountries(t *testing.T) { + list := []Seed{ + {CC: "US", Weight: 6}, {CC: "US", Weight: 6}, // 12, capped at 4 + {CC: "NZ", Weight: 2}, {CC: "AU", Weight: 4}, + } + s := newSeeds(list, 4) + r := rand.New(rand.NewPCG(1, 1)) + got := map[string]int{} + const n = 20000 + for range n { + got[s.Pick(r).CC]++ + } + for cc, share := range map[string]float64{"US": 0.4, "NZ": 0.2, "AU": 0.4} { + if f := float64(got[cc]) / n; math.Abs(f-share) > 0.02 { + t.Errorf("%s picked %.3f of the time, want %.2f", cc, f, share) + } + } + + world, _ := LoadSeeds("") + us := 0 + for range n { + if world.Pick(r).CC == "US" { + us++ + } + } + if f := float64(us) / n; f > 0.05 { + t.Errorf("the US takes %.3f of rounds", f) + } +} + +func TestSeedPoint(t *testing.T) { + r := rand.New(rand.NewPCG(2, 2)) + for _, s := range []Seed{ + {Lat: -37.81, Lon: 144.96, RadiusKm: 40}, + {Lat: 69.65, Lon: 18.96, RadiusKm: 15}, + {Lat: 0, Lon: 179.99, RadiusKm: 30}, // wraps round the antimeridian + } { + far := 0.0 + for range 2000 { + p := s.Point(r) + if !p.valid() { + t.Fatalf("%v is out of range", p) + } + d := Km(p, Point{s.Lat, s.Lon}) + if d > s.RadiusKm*1.001 { + t.Errorf("%v is %.1f km from %+v", p, d, s) + } + far = max(far, d) + } + if far < s.RadiusKm*0.9 { + t.Errorf("points stay within %.1f of %v km", far, s.RadiusKm) + } + } +} + +func TestAround(t *testing.T) { + for _, p := range []Point{{-37.81, 144.96}, {89.99, 0}, {0, -180}} { + b := Around(p) + area := (b.MaxLon - b.MinLon) * (b.MaxLat - b.MinLat) + if area >= 0.01 || area <= 0 || b.MinLon < -180 || b.MaxLat > 90 { + t.Errorf("Around(%v) = %+v, %.4f deg²", p, b, area) + } + } + if got := Around(Point{-37.81, 144.96}).String(); got != "144.940000,-37.830000,144.980000,-37.790000" { + t.Errorf("String %s", got) + } +} + +func TestSeedsHas(t *testing.T) { + europe, err := LoadSeeds("europe") + if err != nil { + t.Fatal(err) + } + if !europe.Has("FR") || europe.Has("AU") || europe.Has("") { + t.Error("europe's countries") + } +} diff --git a/cmd/geoguess/geo/source.go b/cmd/geoguess/geo/source.go new file mode 100644 index 0000000..5d2fbcc --- /dev/null +++ b/cmd/geoguess/geo/source.go @@ -0,0 +1,176 @@ +package geo + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strconv" + "sync" + "time" +) + +// Source is a place to find street-level photos: Mapillary or Panoramax. +type Source interface { + // Name names the source in the credit and the log. + Name() string + // Candidates lists the photos in b. + Candidates(ctx context.Context, b BBox) ([]Candidate, error) + // Fetch downloads a candidate's photo. + Fetch(ctx context.Context, c Candidate) ([]byte, error) +} + +// BBox is an area to search, in decimal degrees. +type BBox struct { + MinLon, MinLat, MaxLon, MaxLat float64 +} + +// String is the bbox as both APIs take it: minLon,minLat,maxLon,maxLat. +func (b BBox) String() string { + return coord(b.MinLon) + "," + coord(b.MinLat) + "," + coord(b.MaxLon) + "," + coord(b.MaxLat) +} + +// Centre is the middle of b. +func (b BBox) Centre() Point { + return Point{Lat: (b.MinLat + b.MaxLat) / 2, Lon: (b.MinLon + b.MaxLon) / 2} +} + +func coord(f float64) string { return strconv.FormatFloat(f, 'f', 6, 64) } + +// Candidate is one photo a source offers, from its metadata alone. +type Candidate struct { + ID string // the source's own ID, which is all the state keeps + Source string // the source's Name + Creator string // the author, for the credit + Licence string // as the credit shows it, e.g. "CC BY-SA 4.0" + Link string // the photo's page, for the credit + At Point // where it was taken: the answer + Raw Point // the raw GPS position, for the drift check; At if there is none + Captured time.Time + Pano bool // an equirectangular 360° panorama + Fisheye bool // a fisheye lens, which is refused + Quality float64 // 0–1; -1 if unknown (Mapillary's quality_score) + Grade int // 1–5 (A is 5); 0 if unknown (Panoramax's grade) + Width int // pixels; 0 if unknown + Height int + Sequence string // the sequence the photo belongs to, if known + + image string // where to download the photo: a URL that may expire +} + +// Key names c across sources, for the list of photos used recently. +func (c Candidate) Key() string { return c.Source + ":" + c.ID } + +// StatusError is an API answering with an HTTP error status. It holds only +// the status, never the URL, so it is safe to log. +type StatusError struct { + Source string + Code int +} + +func (e StatusError) Error() string { return e.Source + ": status " + strconv.Itoa(e.Code) } + +// ErrSlowDown is a source asking to be called less often; the caller should +// wait a while before searching again. +var ErrSlowDown = errors.New("rate limited") + +// maxPhoto caps a downloaded photo. +const maxPhoto = 12 << 20 + +// userAgent names the program, never the person running it. +const userAgent = "geoguess (+https://github.com/robdevops/signalbot)" + +// pacer spaces requests at least every apart. +type pacer struct { + mu sync.Mutex + every time.Duration + next time.Time +} + +// wait blocks until the next request may go, or ctx ends. +func (p *pacer) wait(ctx context.Context) error { + p.mu.Lock() + now := time.Now() + at := now + if p.next.After(now) { + at = p.next + } + p.next = at.Add(p.every) + p.mu.Unlock() + t := time.NewTimer(at.Sub(now)) + defer t.Stop() + select { + case <-t.C: + return nil + case <-ctx.Done(): + return ctx.Err() + } +} + +// request is one GET to an API or an image host. +type request struct { + client *http.Client + source string // names the source in errors + url string + auth string // the Authorization header, if any + limit int64 // the most bytes read +} + +// get does r and returns the body. An error never holds the URL, which may +// carry a signature, nor the server's address. +func (r request) get(ctx context.Context) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, r.url, nil) + if err != nil { + return nil, fmt.Errorf("%s: bad request", r.source) + } + req.Header.Set("User-Agent", userAgent) + if r.auth != "" { + req.Header.Set("Authorization", r.auth) + } + resp, err := r.client.Do(req) + if err != nil { + if ctx.Err() != nil { + return nil, ctx.Err() + } + return nil, fmt.Errorf("%s: request failed", r.source) + } + defer resp.Body.Close() + body, err := io.ReadAll(io.LimitReader(resp.Body, r.limit+1)) + if resp.StatusCode != http.StatusOK { + return body, StatusError{Source: r.source, Code: resp.StatusCode} + } + if err != nil { + return nil, fmt.Errorf("%s: reading the answer failed", r.source) + } + if int64(len(body)) > r.limit { + return nil, fmt.Errorf("%s: answer too large", r.source) + } + return body, nil +} + +// getJSON does r and decodes its JSON body into v. +func (r request) getJSON(ctx context.Context, v any) error { + body, err := r.get(ctx) + if err != nil { + return err + } + if json.Unmarshal(body, v) != nil { + return fmt.Errorf("%s: unreadable answer", r.source) + } + return nil +} + +// geoJSONPoint is a GeoJSON point: [lon, lat]. +type geoJSONPoint struct { + Coordinates []float64 `json:"coordinates"` +} + +func (g *geoJSONPoint) point() (Point, bool) { + if g == nil || len(g.Coordinates) < 2 { + return Point{}, false + } + p := Point{Lat: g.Coordinates[1], Lon: g.Coordinates[0]} + return p, p.valid() +} diff --git a/cmd/geoguess/geo/source_test.go b/cmd/geoguess/geo/source_test.go new file mode 100644 index 0000000..1a711cd --- /dev/null +++ b/cmd/geoguess/geo/source_test.go @@ -0,0 +1,372 @@ +package geo + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync" + "testing" + "time" +) + +// fixture is a recorded API answer from testdata, with {{cdn}} pointing at +// base. The recordings' people are renamed Alice and Bob, and their image +// URLs, which were signed, replaced. +func fixture(t *testing.T, name, base string) []byte { + t.Helper() + data, err := os.ReadFile("testdata/" + name) + if err != nil { + t.Fatal(err) + } + return []byte(strings.ReplaceAll(string(data), "{{cdn}}", base+"/cdn")) +} + +// fakeAPI is an httptest server whose handler the test sets, recording each +// request it gets. +type fakeAPI struct { + *httptest.Server + mu sync.Mutex + handle func(w http.ResponseWriter, r *http.Request) + queries []*http.Request +} + +func newFakeAPI(t *testing.T) *fakeAPI { + f := &fakeAPI{} + f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + f.queries = append(f.queries, r.Clone(context.Background())) + h := f.handle + f.mu.Unlock() + h(w, r) + })) + t.Cleanup(f.Close) + return f +} + +func (f *fakeAPI) requests() []*http.Request { + f.mu.Lock() + defer f.mu.Unlock() + return append([]*http.Request(nil), f.queries...) +} + +var testBox = BBox{MinLon: 143.85, MinLat: -37.57, MaxLon: 143.87, MaxLat: -37.55} + +func TestMapillaryCandidates(t *testing.T) { + api := newFakeAPI(t) + api.handle = func(w http.ResponseWriter, r *http.Request) { w.Write(fixture(t, "mapillary_bbox.json", api.URL)) } + m := NewMapillary(api.URL, "MLY|test", api.Client()) + cands, err := m.Candidates(context.Background(), testBox) + if err != nil { + t.Fatal(err) + } + if len(cands) != 8 { + t.Fatalf("%d candidates, want 8", len(cands)) + } + req := api.requests()[0] + if got := req.Header.Get("Authorization"); got != "OAuth MLY|test" { + t.Errorf("Authorization %q", got) + } + if req.Header.Get("User-Agent") != userAgent { + t.Errorf("User-Agent %q", req.Header.Get("User-Agent")) + } + q := req.URL.Query() + if req.URL.Path != "/images" || q.Get("bbox") != "143.850000,-37.570000,143.870000,-37.550000" || q.Get("limit") != "100" || !strings.Contains(q.Get("fields"), "computed_geometry") { + t.Errorf("query %s %v", req.URL.Path, q) + } + + flat, pano := cands[0], cands[6] + want := Candidate{ + ID: "156004253082834", Source: "Mapillary", Creator: "alice", Licence: "CC BY-SA 4.0", + Link: "https://www.mapillary.com/app/?pKey=156004253082834", + Captured: time.UnixMilli(1566687341409).UTC(), Fisheye: true, Quality: 0.612, + Width: 3840, Height: 2160, Sequence: flat.Sequence, At: flat.At, Raw: flat.Raw, + image: api.URL + "/cdn/156004253082834.jpg", + } + if flat != want { + t.Errorf("candidate\n%+v\nwant\n%+v", flat, want) + } + if flat.At == flat.Raw || Km(flat.At, flat.Raw) > 0.05 || flat.At.Lat > -37.5 { + t.Errorf("positions %v (computed) and %v (raw)", flat.At, flat.Raw) + } + if !pano.Pano || pano.Fisheye || pano.Creator != "bob" || pano.Quality != 0.775 { + t.Errorf("panorama %+v", pano) + } +} + +func TestMapillaryImage(t *testing.T) { + q := 0.5 + for _, tc := range []struct { + name string + im mapillaryImage + ok bool + want func(Candidate) bool + }{ + {"quality null is unknown", mapillaryImage{ID: "1", Geometry: &geoJSONPoint{[]float64{1, 2}}}, true, + func(c Candidate) bool { return c.Quality == -1 && c.At == (Point{2, 1}) && c.Raw == c.At }}, + {"quality kept", mapillaryImage{ID: "1", Geometry: &geoJSONPoint{[]float64{1, 2}}, QualityScore: &q}, true, + func(c Candidate) bool { return c.Quality == 0.5 }}, + {"equirectangular is a panorama", mapillaryImage{ID: "1", Geometry: &geoJSONPoint{[]float64{1, 2}}, CameraType: "equirectangular"}, true, + func(c Candidate) bool { return c.Pano }}, + {"spherical is a panorama", mapillaryImage{ID: "1", Geometry: &geoJSONPoint{[]float64{1, 2}}, CameraType: "spherical"}, true, + func(c Candidate) bool { return c.Pano }}, + {"computed geometry is the answer", mapillaryImage{ID: "1", Geometry: &geoJSONPoint{[]float64{1, 2}}, ComputedGeometry: &geoJSONPoint{[]float64{3, 4}}}, true, + func(c Candidate) bool { return c.At == (Point{4, 3}) && c.Raw == (Point{2, 1}) }}, + {"no capture time", mapillaryImage{ID: "1", ComputedGeometry: &geoJSONPoint{[]float64{3, 4}}}, true, + func(c Candidate) bool { return c.Captured.IsZero() && c.Raw == c.At }}, + {"no position", mapillaryImage{ID: "1"}, false, nil}, + {"out of range", mapillaryImage{ID: "1", Geometry: &geoJSONPoint{[]float64{200, 2}}}, false, nil}, + {"no ID", mapillaryImage{Geometry: &geoJSONPoint{[]float64{1, 2}}}, false, nil}, + } { + c, ok := tc.im.candidate() + if ok != tc.ok || (ok && !tc.want(c)) { + t.Errorf("%s: %+v, %v", tc.name, c, ok) + } + } +} + +func TestMapillaryRetries(t *testing.T) { + for _, tc := range []struct { + name string + answers []string // status and fixture, by request + want int // candidates + calls int + radius bool // the last call was a radius search + err error + }{ + {"empty is asked again", []string{"200 {\"data\":[]}", "200 mapillary_bbox.json"}, 8, 2, false, nil}, + {"empty twice", []string{"200 {\"data\":[]}", "200 {\"data\":[]}"}, 0, 2, false, nil}, + {"too dense falls back to a radius", []string{"500 mapillary_error.json", "200 mapillary_radius.json"}, 5, 2, true, nil}, + {"empty then too dense", []string{"200 {\"data\":[]}", "500 mapillary_error.json", "200 mapillary_radius.json"}, 5, 3, true, nil}, + {"rate limited", []string{`429 {"error":{"code":4,"message":"limit"}}`}, 0, 1, false, ErrSlowDown}, + {"rate limited as a 400", []string{`400 {"error":{"code":4,"message":"limit"}}`}, 0, 1, false, ErrSlowDown}, + {"refused", []string{`401 {"error":{"code":190}}`}, 0, 1, false, StatusError{Source: "Mapillary", Code: 401}}, + {"unreadable", []string{`200 <html>`}, 0, 1, false, errors.New("Mapillary: unreadable answer")}, + } { + api := newFakeAPI(t) + n := 0 + api.handle = func(w http.ResponseWriter, r *http.Request) { + status, body, _ := strings.Cut(tc.answers[min(n, len(tc.answers)-1)], " ") + n++ + if strings.HasSuffix(body, ".json") { + body = string(fixture(t, body, api.URL)) + } + code := map[string]int{"200": 200, "400": 400, "401": 401, "429": 429, "500": 500}[status] + w.WriteHeader(code) + w.Write([]byte(body)) + } + cands, err := NewMapillary(api.URL, "MLY|test", api.Client()).Candidates(context.Background(), testBox) + if (err == nil) != (tc.err == nil) || (err != nil && err.Error() != tc.err.Error()) { + t.Errorf("%s: error %v, want %v", tc.name, err, tc.err) + } + reqs := api.requests() + if len(cands) != tc.want || len(reqs) != tc.calls { + t.Errorf("%s: %d candidates in %d calls, want %d in %d", tc.name, len(cands), len(reqs), tc.want, tc.calls) + continue + } + last := reqs[len(reqs)-1].URL.Query() + if tc.radius && (last.Get("lat") != "-37.560000" || last.Get("lng") != "143.860000" || last.Get("radius") != "50" || last.Has("bbox")) { + t.Errorf("%s: radius search %v", tc.name, last) + } + } +} + +func TestMapillaryFetch(t *testing.T) { + api := newFakeAPI(t) + expired := true + api.handle = func(w http.ResponseWriter, r *http.Request) { + switch { + case r.URL.Path == "/cdn/old.jpg" && expired: + w.WriteHeader(http.StatusForbidden) + case strings.HasPrefix(r.URL.Path, "/cdn/"): + w.Write([]byte("jpeg " + r.URL.Path)) + case r.URL.Path == "/42" && r.URL.Query().Get("fields") == "thumb_2048_url" && r.Header.Get("Authorization") == "OAuth tok": + w.Write([]byte(`{"id":"42","thumb_2048_url":"` + api.URL + `/cdn/fresh.jpg?sig=secret"}`)) + default: + http.NotFound(w, r) + } + } + m := NewMapillary(api.URL, "tok", api.Client()) + ctx := context.Background() + for _, tc := range []struct { + name string + image string + want string + }{ + {"by the search's URL", api.URL + "/cdn/old.jpg", "jpeg /cdn/old.jpg"}, + {"no URL", "", "jpeg /cdn/fresh.jpg"}, + } { + expired = false + data, err := m.Fetch(ctx, Candidate{ID: "42", image: tc.image}) + if err != nil || string(data) != tc.want { + t.Errorf("%s: %q, %v", tc.name, data, err) + } + } + expired = true + data, err := m.Fetch(ctx, Candidate{ID: "42", image: api.URL + "/cdn/old.jpg"}) + if err != nil || string(data) != "jpeg /cdn/fresh.jpg" { + t.Errorf("expired URL: %q, %v", data, err) + } + // An error names neither the URL nor its signature. + _, err = m.Fetch(ctx, Candidate{ID: "43", image: api.URL + "/cdn/old.jpg?sig=secret"}) + if err == nil || strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "127.0.0.1") { + t.Errorf("error %v", err) + } +} + +func TestRequestErrorsHoldNoURL(t *testing.T) { + api := newFakeAPI(t) + api.handle = func(w http.ResponseWriter, r *http.Request) {} + addr := api.URL + api.Close() // nothing listens now + for _, url := range []string{addr + "/x?sig=secret", "://bad?sig=secret"} { + _, err := request{client: http.DefaultClient, source: "Test", url: url, limit: 10}.get(context.Background()) + if err == nil || strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "127.0.0.1") { + t.Errorf("error %v", err) + } + } +} + +func TestPanoramaxCandidates(t *testing.T) { + api := newFakeAPI(t) + api.handle = func(w http.ResponseWriter, r *http.Request) { w.Write(fixture(t, "panoramax_search.json", api.URL)) } + p := NewPanoramax(api.URL, api.Client()) + p.pace.every = 0 + cands, err := p.Candidates(context.Background(), testBox) + if err != nil { + t.Fatal(err) + } + if len(cands) != 5 { + t.Fatalf("%d candidates, want 5", len(cands)) + } + req := api.requests()[0] + if req.URL.Path != "/api/search" || req.URL.Query().Get("bbox") != testBox.String() || req.Header.Get("User-Agent") != userAgent || req.Header.Get("Authorization") != "" { + t.Errorf("request %v %v", req.URL, req.Header) + } + pano := cands[0] + want := Candidate{ + ID: "9a479835-1331-4b8a-adce-f2173f61ffc8", Source: "Panoramax", Creator: "alice", Licence: "Etalab 2.0", + Link: api.URL + "/#focus=pic&pic=9a479835-1331-4b8a-adce-f2173f61ffc8", + At: Point{48.859925491, 2.345090985}, + Raw: Point{48.859925491, 2.345090985}, + Captured: time.Date(2025, 5, 8, 9, 22, 36, 652e6, time.UTC), + Pano: true, Quality: -1, Grade: 5, Width: 12288, Height: 6144, + Sequence: "600d5cee-5328-4dd4-8838-5f27ef85aa59", + image: api.URL + "/cdn/9a479835-1331-4b8a-adce-f2173f61ffc8/sd.jpg", + } + if pano != want { + t.Errorf("candidate\n%+v\nwant\n%+v", pano, want) + } + flat := cands[3] + if flat.Pano || flat.Licence != "CC BY-SA 4.0" || flat.Creator != "bob" || flat.Grade != 3 || flat.Width != 1920 { + t.Errorf("flat %+v", flat) + } + + data, err := p.Fetch(context.Background(), flat) + if err != nil || !strings.Contains(string(data), "FeatureCollection") { // the fake serves the search for any path + t.Errorf("fetch: %v", err) + } + if got := api.requests()[1].URL.Path; got != "/cdn/4ff8d96e-5114-4ed5-b593-daea754a6998/sd.jpg" { + t.Errorf("fetched %s", got) + } +} + +func TestPanoramaxSkips(t *testing.T) { + api := newFakeAPI(t) + api.handle = func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte(`{"features":[ + {"id":"a","geometry":{"coordinates":[2,48]},"assets":{"sd":{"href":"x"}},"properties":{"license":"proprietary"}}, + {"id":"b","geometry":{"coordinates":[2,48]},"assets":{"hd":{"href":"x"}},"properties":{"license":"CC-BY-4.0"}}, + {"id":"c","assets":{"sd":{"href":"x"}},"properties":{"license":"CC-BY-4.0"}}, + {"id":"d","geometry":{"coordinates":[2,48]},"assets":{"sd":{"href":"x"}},"properties":{"license":"CC0-1.0","datetime":"bad"}} + ]}`)) + } + p := NewPanoramax(api.URL, api.Client()) + p.pace.every = 0 + cands, err := p.Candidates(context.Background(), testBox) + if err != nil || len(cands) != 1 || cands[0].ID != "d" || cands[0].Licence != "CC0 1.0" || !cands[0].Captured.IsZero() || cands[0].Grade != 0 { + t.Errorf("%+v, %v", cands, err) + } + api.handle = func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTooManyRequests) } + if _, err := p.Candidates(context.Background(), testBox); err != ErrSlowDown { + t.Errorf("429: %v", err) + } + api.handle = func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadGateway) } + if _, err := p.Candidates(context.Background(), testBox); err != (StatusError{Source: "Panoramax", Code: 502}) { + t.Errorf("502: %v", err) + } +} + +func TestGrade(t *testing.T) { + f := func(v float64) *float64 { return &v } + for _, tc := range []struct { + pano bool + density, accuracy *float64 + want int + }{ + {false, nil, nil, 0}, + {false, f(5), nil, 1}, + {false, f(12), nil, 2}, + {false, f(20), nil, 3}, + {false, f(40), nil, 4}, + {true, f(10), nil, 3}, + {true, f(20), nil, 4}, + {true, f(34), nil, 5}, + {false, nil, f(0.3), 5}, + {false, nil, f(2), 4}, + {false, nil, f(5), 3}, + {false, nil, f(10), 2}, + {false, nil, f(11), 1}, + {true, f(34), f(2), 5}, // 0.8×5 + 0.2×4 = 4.8 + {false, f(20), f(3.6), 3}, // 0.8×3 + 0.2×3 + {false, f(12), f(0.3), 3}, // 0.8×2 + 0.2×5 = 2.6 + {false, f(12), f(11), 2}, // 0.8×2 + 0.2×1 = 1.8 + {false, f(5), f(0.3), 2}, // 0.8 + 1 = 1.8 + {false, f(40), f(11), 3}, // 3.2 + 0.2 = 3.4 + {true, f(10), f(20), 3}, // 2.4 + 0.2 = 2.6 + } { + if got := grade(tc.pano, tc.density, tc.accuracy); got != tc.want { + t.Errorf("grade(%v, %v, %v) = %d, want %d", tc.pano, deref(tc.density), deref(tc.accuracy), got, tc.want) + } + } +} + +func deref(f *float64) any { + if f == nil { + return nil + } + return *f +} + +func TestLicenceName(t *testing.T) { + for spdx, want := range map[string]string{ + "CC-BY-SA-4.0": "CC BY-SA 4.0", "CC-BY-4.0": "CC BY 4.0", "CC0-1.0": "CC0 1.0", + "etalab-2.0": "Etalab 2.0", "": "", "proprietary": "", "CC-4.0": "", "MIT": "", "GPL-3.0": "", + } { + if got := licenceName(spdx); got != want { + t.Errorf("licenceName(%q) = %q, want %q", spdx, got, want) + } + } +} + +func TestPacer(t *testing.T) { + p := &pacer{every: 30 * time.Millisecond} + start := time.Now() + for range 3 { + if err := p.wait(context.Background()); err != nil { + t.Fatal(err) + } + } + if d := time.Since(start); d < 60*time.Millisecond { + t.Errorf("3 requests in %v, want at least 60ms", d) + } + ctx, cancel := context.WithCancel(context.Background()) + cancel() + p.every = time.Hour + p.wait(context.Background()) + if err := p.wait(ctx); err != context.Canceled { + t.Errorf("cancelled wait: %v", err) + } +} diff --git a/cmd/geoguess/geo/testdata/mapillary_bbox.json b/cmd/geoguess/geo/testdata/mapillary_bbox.json new file mode 100644 index 0000000..850c41d --- /dev/null +++ b/cmd/geoguess/geo/testdata/mapillary_bbox.json @@ -0,0 +1,244 @@ +{ + "data": [ + { + "id": "156004253082834", + "computed_geometry": { + "type": "Point", + "coordinates": [ + 143.85993803594, + -37.550111548392 + ] + }, + "geometry": { + "type": "Point", + "coordinates": [ + 143.85993831842, + -37.550110472726 + ] + }, + "captured_at": 1566687341409, + "camera_type": "fisheye", + "is_pano": false, + "quality_score": 0.612, + "width": 3840, + "height": 2160, + "computed_compass_angle": 184.75923939341, + "sequence": "xb2e6e9trvde7vkhc65y3i", + "creator": { + "username": "alice", + "id": "1001" + }, + "thumb_2048_url": "{{cdn}}/156004253082834.jpg" + }, + { + "id": "2880385632236073", + "computed_geometry": { + "type": "Point", + "coordinates": [ + 143.85975441019, + -37.551251776107 + ] + }, + "geometry": { + "type": "Point", + "coordinates": [ + 143.85975375285, + -37.551243574797 + ] + }, + "captured_at": 1566687354881, + "camera_type": "fisheye", + "is_pano": false, + "quality_score": 0.614, + "width": 3840, + "height": 2160, + "computed_compass_angle": 240.63145945093, + "sequence": "xb2e6e9trvde7vkhc65y3i", + "creator": { + "username": "alice", + "id": "1001" + }, + "thumb_2048_url": "{{cdn}}/2880385632236073.jpg" + }, + { + "id": "334718131329412", + "computed_geometry": { + "type": "Point", + "coordinates": [ + 143.85973240176, + -37.551255606257 + ] + }, + "geometry": { + "type": "Point", + "coordinates": [ + 143.85973159017, + -37.551247230787 + ] + }, + "captured_at": 1566687355180, + "camera_type": "fisheye", + "is_pano": false, + "quality_score": 0.618, + "width": 3840, + "height": 2160, + "computed_compass_angle": 250.45092854569, + "sequence": "xb2e6e9trvde7vkhc65y3i", + "creator": { + "username": "alice", + "id": "1001" + }, + "thumb_2048_url": "{{cdn}}/334718131329412.jpg" + }, + { + "id": "178895307446180", + "computed_geometry": { + "type": "Point", + "coordinates": [ + 143.85988012788, + -37.550447115403 + ] + }, + "geometry": { + "type": "Point", + "coordinates": [ + 143.85987935767, + -37.550449615938 + ] + }, + "captured_at": 1566687344327, + "camera_type": "fisheye", + "is_pano": false, + "quality_score": 0.682, + "width": 3840, + "height": 2160, + "computed_compass_angle": 184.78506751006, + "sequence": "xb2e6e9trvde7vkhc65y3i", + "creator": { + "username": "alice", + "id": "1001" + }, + "thumb_2048_url": "{{cdn}}/178895307446180.jpg" + }, + { + "id": "1142062562932199", + "computed_geometry": { + "type": "Point", + "coordinates": [ + 143.85985738968, + -37.550590850425 + ] + }, + "geometry": { + "type": "Point", + "coordinates": [ + 143.85985817455, + -37.550592772934 + ] + }, + "captured_at": 1566687345612, + "camera_type": "fisheye", + "is_pano": false, + "quality_score": 0.587, + "width": 3840, + "height": 2160, + "computed_compass_angle": 183.87523854316, + "sequence": "xb2e6e9trvde7vkhc65y3i", + "creator": { + "username": "alice", + "id": "1001" + }, + "thumb_2048_url": "{{cdn}}/1142062562932199.jpg" + }, + { + "id": "223444442539547", + "computed_geometry": { + "type": "Point", + "coordinates": [ + 143.85983656729, + -37.551193460445 + ] + }, + "geometry": { + "type": "Point", + "coordinates": [ + 143.85984588429, + -37.551196353464 + ] + }, + "captured_at": 1566687353395, + "camera_type": "fisheye", + "is_pano": false, + "quality_score": 0.57, + "width": 3840, + "height": 2160, + "computed_compass_angle": 194.20153045585, + "sequence": "xb2e6e9trvde7vkhc65y3i", + "creator": { + "username": "alice", + "id": "1001" + }, + "thumb_2048_url": "{{cdn}}/223444442539547.jpg" + }, + { + "id": "1197032491288598", + "computed_geometry": { + "type": "Point", + "coordinates": [ + 2.2951849294167, + 48.859976802118 + ] + }, + "geometry": { + "type": "Point", + "coordinates": [ + 2.2951917, + 48.8599845 + ] + }, + "captured_at": 1718006677000, + "camera_type": "spherical", + "is_pano": true, + "quality_score": 0.775, + "width": 5760, + "height": 2880, + "computed_compass_angle": 301.36099357275, + "sequence": "QVKZBMWUjyG9PRXJufv0wA", + "creator": { + "username": "bob", + "id": "1002" + }, + "thumb_2048_url": "{{cdn}}/1197032491288598.jpg" + }, + { + "id": "1011962813864670", + "computed_geometry": { + "type": "Point", + "coordinates": [ + 2.2954610949215, + 48.859805467701 + ] + }, + "geometry": { + "type": "Point", + "coordinates": [ + 2.2954703, + 48.8598093 + ] + }, + "captured_at": 1718006650000, + "camera_type": "spherical", + "is_pano": true, + "quality_score": 0.713, + "width": 5760, + "height": 2880, + "computed_compass_angle": 301.89596100548, + "sequence": "QVKZBMWUjyG9PRXJufv0wA", + "creator": { + "username": "bob", + "id": "1002" + }, + "thumb_2048_url": "{{cdn}}/1011962813864670.jpg" + } + ] +} \ No newline at end of file diff --git a/cmd/geoguess/geo/testdata/mapillary_error.json b/cmd/geoguess/geo/testdata/mapillary_error.json new file mode 100644 index 0000000..95f3f73 --- /dev/null +++ b/cmd/geoguess/geo/testdata/mapillary_error.json @@ -0,0 +1 @@ +{"error":{"code":1,"message":"Please reduce the amount of data you're asking for, then retry your request"}} \ No newline at end of file diff --git a/cmd/geoguess/geo/testdata/mapillary_radius.json b/cmd/geoguess/geo/testdata/mapillary_radius.json new file mode 100644 index 0000000..7aa312b --- /dev/null +++ b/cmd/geoguess/geo/testdata/mapillary_radius.json @@ -0,0 +1,154 @@ +{ + "data": [ + { + "id": "1706189916395244", + "computed_geometry": { + "type": "Point", + "coordinates": [ + 144.96299697336, + -37.813278303317 + ] + }, + "geometry": { + "type": "Point", + "coordinates": [ + 144.96282777778, + -37.813338888889 + ] + }, + "captured_at": 1648397432000, + "camera_type": "perspective", + "is_pano": false, + "quality_score": 0.724, + "width": 4608, + "height": 3456, + "computed_compass_angle": 235.75898108927, + "sequence": "IPZOUkg6evRHs2oXz5nTi1", + "creator": { + "username": "alice", + "id": "1001" + }, + "thumb_2048_url": "{{cdn}}/1706189916395244.jpg" + }, + { + "id": "450966633448484", + "computed_geometry": { + "type": "Point", + "coordinates": [ + 144.96304115907, + -37.813265095945 + ] + }, + "geometry": { + "type": "Point", + "coordinates": [ + 144.96293611111, + -37.813344444444 + ] + }, + "captured_at": 1648397430000, + "camera_type": "perspective", + "is_pano": false, + "quality_score": 0.701, + "width": 4608, + "height": 3456, + "computed_compass_angle": 236.50575771839, + "sequence": "IPZOUkg6evRHs2oXz5nTi1", + "creator": { + "username": "alice", + "id": "1001" + }, + "thumb_2048_url": "{{cdn}}/450966633448484.jpg" + }, + { + "id": "649893549426488", + "computed_geometry": { + "type": "Point", + "coordinates": [ + 144.96308336398, + -37.813246905267 + ] + }, + "geometry": { + "type": "Point", + "coordinates": [ + 144.96304166667, + -37.813333333333 + ] + }, + "captured_at": 1648397428000, + "camera_type": "perspective", + "is_pano": false, + "quality_score": 0.738, + "width": 4608, + "height": 3456, + "computed_compass_angle": 243.79938219267, + "sequence": "IPZOUkg6evRHs2oXz5nTi1", + "creator": { + "username": "alice", + "id": "1001" + }, + "thumb_2048_url": "{{cdn}}/649893549426488.jpg" + }, + { + "id": "518951069663464", + "computed_geometry": { + "type": "Point", + "coordinates": [ + 144.9631266858, + -37.813233251456 + ] + }, + "geometry": { + "type": "Point", + "coordinates": [ + 144.96310277778, + -37.813330555556 + ] + }, + "captured_at": 1648397426000, + "camera_type": "perspective", + "is_pano": false, + "quality_score": 0.633, + "width": 4608, + "height": 3456, + "computed_compass_angle": 250.66612660699, + "sequence": "IPZOUkg6evRHs2oXz5nTi1", + "creator": { + "username": "alice", + "id": "1001" + }, + "thumb_2048_url": "{{cdn}}/518951069663464.jpg" + }, + { + "id": "965287747688046", + "computed_geometry": { + "type": "Point", + "coordinates": [ + 144.96317140375, + -37.813215415651 + ] + }, + "geometry": { + "type": "Point", + "coordinates": [ + 144.96317777778, + -37.813311111111 + ] + }, + "captured_at": 1648397424000, + "camera_type": "perspective", + "is_pano": false, + "quality_score": 0.603, + "width": 4608, + "height": 3456, + "computed_compass_angle": 242.16944133453, + "sequence": "IPZOUkg6evRHs2oXz5nTi1", + "creator": { + "username": "alice", + "id": "1001" + }, + "thumb_2048_url": "{{cdn}}/965287747688046.jpg" + } + ] +} \ No newline at end of file diff --git a/cmd/geoguess/geo/testdata/panoramax_search.json b/cmd/geoguess/geo/testdata/panoramax_search.json new file mode 100644 index 0000000..21ca04e --- /dev/null +++ b/cmd/geoguess/geo/testdata/panoramax_search.json @@ -0,0 +1,614 @@ +{ + "type": "FeatureCollection", + "features": [ + { + "id": "9a479835-1331-4b8a-adce-f2173f61ffc8", + "bbox": [ + 2.345090985, + 48.859925491, + 2.345090985, + 48.859925491 + ], + "type": "Feature", + "links": [ + { + "rel": "license", + "href": "https://alliance.numerique.gouv.fr/licence-ouverte-open-licence/", + "title": "License for this object (etalab-2.0)" + }, + { + "rel": "self", + "href": "https://api.panoramax.xyz/api/collections/600d5cee-5328-4dd4-8838-5f27ef85aa59/items/9a479835-1331-4b8a-adce-f2173f61ffc8", + "type": "application/geo+json" + }, + { + "rel": "via", + "href": "https://panoramax.ign.fr", + "type": "application/json", + "title": "Link to the original instance", + "instance_name": "ign" + } + ], + "assets": { + "hd": { + "href": "{{cdn}}/9a479835-1331-4b8a-adce-f2173f61ffc8/1331-4b8a-adce-f2173f61ffc8.jpg", + "type": "image/jpeg", + "roles": [ + "data" + ], + "title": "HD picture", + "description": "Highest resolution available of this picture" + }, + "sd": { + "href": "{{cdn}}/9a479835-1331-4b8a-adce-f2173f61ffc8/sd.jpg", + "type": "image/jpeg", + "roles": [ + "visual" + ], + "title": "SD picture", + "description": "Picture in standard definition (fixed width of 2048px)" + }, + "thumb": { + "href": "{{cdn}}/9a479835-1331-4b8a-adce-f2173f61ffc8/thumb.jpg", + "type": "image/jpeg", + "roles": [ + "thumbnail" + ], + "title": "Thumbnail", + "description": "Picture in low definition (fixed width of 500px)" + } + }, + "geometry": { + "type": "Point", + "coordinates": [ + 2.345090985, + 48.859925491 + ] + }, + "providers": [ + { + "name": "alice", + "roles": [ + "producer" + ] + }, + { + "name": "Alice for the City", + "roles": [ + "producer" + ] + } + ], + "collection": "600d5cee-5328-4dd4-8838-5f27ef85aa59", + "properties": { + "created": "2025-12-05T19:45:40.220379+00:00", + "license": "etalab-2.0", + "updated": "2025-12-26T15:25:50.228724+00:00", + "datetime": "2025-05-08T09:22:36.652000+00:00", + "collection": { + "semantics": [ + { + "key": "producer", + "value": "Alice" + }, + { + "key": "transport", + "value": "car" + } + ] + }, + "datetimetz": "2025-05-08T11:22:36.652000+02:00", + "view:azimuth": 28, + "geovisio:status": "ready", + "original_file:size": 6521760, + "geovisio:visibility": "anyone", + "pers:interior_orientation": { + "camera_model": "imajbox 360 HD", + "field_of_view": 360, + "camera_manufacturer": "IMAJING", + "sensor_array_dimensions": [ + 12288, + 6144 + ] + }, + "geovisio:rank_in_collection": 5907, + "quality:horizontal_accuracy": 2.0, + "panoramax:horizontal_pixel_density": 34 + }, + "stac_version": "1.0.0", + "asset_templates": { + "tiles": { + "href": "https://panoramax-storage-public-fast.s3.gra.perf.cloud.ovh.net/derivates/9a/47/98/35/1331-4b8a-adce-f2173f61ffc8/tiles/{TileCol}_{TileRow}.jpg", + "type": "image/jpeg", + "roles": [ + "data" + ], + "title": "HD tiled picture", + "description": "Highest resolution available of this picture, as tiles" + } + }, + "stac_extensions": [ + "https://stac-extensions.github.io/view/v1.0.0/schema.json", + "https://stac-extensions.github.io/perspective-imagery/v1.0.0/schema.json", + "https://stac-extensions.github.io/tiled-assets/v1.0.0/schema.json" + ] + }, + { + "id": "ba1508dd-3154-47d2-aa61-250b5bbca547", + "bbox": [ + 2.345074156, + 48.859906028, + 2.345074156, + 48.859906028 + ], + "type": "Feature", + "links": [ + { + "rel": "license", + "href": "https://alliance.numerique.gouv.fr/licence-ouverte-open-licence/", + "title": "License for this object (etalab-2.0)" + }, + { + "rel": "self", + "href": "https://api.panoramax.xyz/api/collections/600d5cee-5328-4dd4-8838-5f27ef85aa59/items/ba1508dd-3154-47d2-aa61-250b5bbca547", + "type": "application/geo+json" + }, + { + "rel": "via", + "href": "https://panoramax.ign.fr", + "type": "application/json", + "title": "Link to the original instance", + "instance_name": "ign" + } + ], + "assets": { + "hd": { + "href": "{{cdn}}/ba1508dd-3154-47d2-aa61-250b5bbca547/3154-47d2-aa61-250b5bbca547.jpg", + "type": "image/jpeg", + "roles": [ + "data" + ], + "title": "HD picture", + "description": "Highest resolution available of this picture" + }, + "sd": { + "href": "{{cdn}}/ba1508dd-3154-47d2-aa61-250b5bbca547/sd.jpg", + "type": "image/jpeg", + "roles": [ + "visual" + ], + "title": "SD picture", + "description": "Picture in standard definition (fixed width of 2048px)" + }, + "thumb": { + "href": "{{cdn}}/ba1508dd-3154-47d2-aa61-250b5bbca547/thumb.jpg", + "type": "image/jpeg", + "roles": [ + "thumbnail" + ], + "title": "Thumbnail", + "description": "Picture in low definition (fixed width of 500px)" + } + }, + "geometry": { + "type": "Point", + "coordinates": [ + 2.345074156, + 48.859906028 + ] + }, + "providers": [ + { + "name": "alice", + "roles": [ + "producer" + ] + }, + { + "name": "Alice for the City", + "roles": [ + "producer" + ] + } + ], + "collection": "600d5cee-5328-4dd4-8838-5f27ef85aa59", + "properties": { + "created": "2025-12-05T19:45:38.673129+00:00", + "license": "etalab-2.0", + "updated": "2025-12-28T19:37:26.880936+00:00", + "datetime": "2025-05-08T09:22:36.251000+00:00", + "collection": { + "semantics": [ + { + "key": "producer", + "value": "Alice" + }, + { + "key": "transport", + "value": "car" + } + ] + }, + "datetimetz": "2025-05-08T11:22:36.251000+02:00", + "view:azimuth": 28, + "geovisio:status": "ready", + "original_file:size": 6561382, + "geovisio:visibility": "anyone", + "pers:interior_orientation": { + "camera_model": "imajbox 360 HD", + "field_of_view": 360, + "camera_manufacturer": "IMAJING", + "sensor_array_dimensions": [ + 12288, + 6144 + ] + }, + "geovisio:rank_in_collection": 5906, + "quality:horizontal_accuracy": 2.0, + "panoramax:horizontal_pixel_density": 34 + }, + "stac_version": "1.0.0", + "asset_templates": { + "tiles": { + "href": "https://panoramax-storage-public-fast.s3.gra.perf.cloud.ovh.net/derivates/ba/15/08/dd/3154-47d2-aa61-250b5bbca547/tiles/{TileCol}_{TileRow}.jpg", + "type": "image/jpeg", + "roles": [ + "data" + ], + "title": "HD tiled picture", + "description": "Highest resolution available of this picture, as tiles" + } + }, + "stac_extensions": [ + "https://stac-extensions.github.io/view/v1.0.0/schema.json", + "https://stac-extensions.github.io/perspective-imagery/v1.0.0/schema.json", + "https://stac-extensions.github.io/tiled-assets/v1.0.0/schema.json" + ] + }, + { + "id": "b79f56d3-4910-437a-ab3d-480dce9ea64a", + "bbox": [ + 2.345106645, + 48.859944271, + 2.345106645, + 48.859944271 + ], + "type": "Feature", + "links": [ + { + "rel": "license", + "href": "https://alliance.numerique.gouv.fr/licence-ouverte-open-licence/", + "title": "License for this object (etalab-2.0)" + }, + { + "rel": "self", + "href": "https://api.panoramax.xyz/api/collections/600d5cee-5328-4dd4-8838-5f27ef85aa59/items/b79f56d3-4910-437a-ab3d-480dce9ea64a", + "type": "application/geo+json" + }, + { + "rel": "via", + "href": "https://panoramax.ign.fr", + "type": "application/json", + "title": "Link to the original instance", + "instance_name": "ign" + } + ], + "assets": { + "hd": { + "href": "{{cdn}}/b79f56d3-4910-437a-ab3d-480dce9ea64a/4910-437a-ab3d-480dce9ea64a.jpg", + "type": "image/jpeg", + "roles": [ + "data" + ], + "title": "HD picture", + "description": "Highest resolution available of this picture" + }, + "sd": { + "href": "{{cdn}}/b79f56d3-4910-437a-ab3d-480dce9ea64a/sd.jpg", + "type": "image/jpeg", + "roles": [ + "visual" + ], + "title": "SD picture", + "description": "Picture in standard definition (fixed width of 2048px)" + }, + "thumb": { + "href": "{{cdn}}/b79f56d3-4910-437a-ab3d-480dce9ea64a/thumb.jpg", + "type": "image/jpeg", + "roles": [ + "thumbnail" + ], + "title": "Thumbnail", + "description": "Picture in low definition (fixed width of 500px)" + } + }, + "geometry": { + "type": "Point", + "coordinates": [ + 2.345106645, + 48.859944271 + ] + }, + "providers": [ + { + "name": "alice", + "roles": [ + "producer" + ] + }, + { + "name": "Alice for the City", + "roles": [ + "producer" + ] + } + ], + "collection": "600d5cee-5328-4dd4-8838-5f27ef85aa59", + "properties": { + "created": "2025-12-05T19:45:40.163540+00:00", + "license": "etalab-2.0", + "updated": "2025-12-28T20:20:31.844006+00:00", + "datetime": "2025-05-08T09:22:37.042000+00:00", + "collection": { + "semantics": [ + { + "key": "producer", + "value": "Alice" + }, + { + "key": "transport", + "value": "car" + } + ] + }, + "datetimetz": "2025-05-08T11:22:37.042000+02:00", + "view:azimuth": 27, + "geovisio:status": "ready", + "original_file:size": 6558079, + "geovisio:visibility": "anyone", + "pers:interior_orientation": { + "camera_model": "imajbox 360 HD", + "field_of_view": 360, + "camera_manufacturer": "IMAJING", + "sensor_array_dimensions": [ + 12288, + 6144 + ] + }, + "geovisio:rank_in_collection": 5908, + "quality:horizontal_accuracy": 2.0, + "panoramax:horizontal_pixel_density": 34 + }, + "stac_version": "1.0.0", + "asset_templates": { + "tiles": { + "href": "https://panoramax-storage-public-fast.s3.gra.perf.cloud.ovh.net/derivates/b7/9f/56/d3/4910-437a-ab3d-480dce9ea64a/tiles/{TileCol}_{TileRow}.jpg", + "type": "image/jpeg", + "roles": [ + "data" + ], + "title": "HD tiled picture", + "description": "Highest resolution available of this picture, as tiles" + } + }, + "stac_extensions": [ + "https://stac-extensions.github.io/view/v1.0.0/schema.json", + "https://stac-extensions.github.io/perspective-imagery/v1.0.0/schema.json", + "https://stac-extensions.github.io/tiled-assets/v1.0.0/schema.json" + ] + }, + { + "id": "4ff8d96e-5114-4ed5-b593-daea754a6998", + "bbox": [ + -1.680981389, + 48.114966389, + -1.680981389, + 48.114966389 + ], + "type": "Feature", + "links": [ + { + "rel": "license", + "href": "https://creativecommons.org/licenses/by-sa/4.0/", + "title": "License for this object (CC-BY-SA-4.0)" + }, + { + "rel": "self", + "href": "https://api.panoramax.xyz/api/collections/912ed747-c21c-4c04-9c9d-f1e75a51072e/items/4ff8d96e-5114-4ed5-b593-daea754a6998", + "type": "application/geo+json" + }, + { + "rel": "via", + "href": "https://panoramax.openstreetmap.fr", + "type": "application/json", + "title": "Link to the original instance", + "instance_name": "osm-fr" + } + ], + "assets": { + "hd": { + "href": "{{cdn}}/4ff8d96e-5114-4ed5-b593-daea754a6998/5114-4ed5-b593-daea754a6998.jpg", + "type": "image/jpeg", + "roles": [ + "data" + ], + "title": "HD picture", + "description": "Highest resolution available of this picture" + }, + "sd": { + "href": "{{cdn}}/4ff8d96e-5114-4ed5-b593-daea754a6998/sd.jpg", + "type": "image/jpeg", + "roles": [ + "visual" + ], + "title": "SD picture", + "description": "Picture in standard definition (fixed width of 2048px)" + }, + "thumb": { + "href": "{{cdn}}/4ff8d96e-5114-4ed5-b593-daea754a6998/thumb.jpg", + "type": "image/jpeg", + "roles": [ + "thumbnail" + ], + "title": "Thumbnail", + "description": "Picture in low definition (fixed width of 500px)" + } + }, + "geometry": { + "type": "Point", + "coordinates": [ + -1.680981389, + 48.114966389 + ] + }, + "providers": [ + { + "name": "bob", + "roles": [ + "producer" + ] + } + ], + "collection": "912ed747-c21c-4c04-9c9d-f1e75a51072e", + "properties": { + "created": "2023-07-30T10:21:28.425345+00:00", + "license": "CC-BY-SA-4.0", + "updated": "2025-06-03T03:02:44.485815+00:00", + "datetime": "2018-03-27T16:55:15+00:00", + "collection": { + "semantics": [] + }, + "datetimetz": "2018-03-27T16:55:15+00:00", + "view:azimuth": 174, + "geovisio:status": "ready", + "original_file:size": 514943, + "geovisio:visibility": "anyone", + "pers:interior_orientation": { + "camera_model": "FDR-X1000V", + "focal_length": 2.8, + "field_of_view": 96, + "camera_manufacturer": "SONY", + "sensor_array_dimensions": [ + 1920, + 1080 + ] + }, + "geovisio:rank_in_collection": 89, + "quality:horizontal_accuracy": 3.6, + "panoramax:horizontal_pixel_density": 20 + }, + "stac_version": "1.0.0", + "stac_extensions": [ + "https://stac-extensions.github.io/view/v1.0.0/schema.json", + "https://stac-extensions.github.io/perspective-imagery/v1.0.0/schema.json" + ] + }, + { + "id": "3f646b4a-caf0-4b2c-a3a6-f3273f9fc332", + "bbox": [ + -1.680981389, + 48.115098056, + -1.680981389, + 48.115098056 + ], + "type": "Feature", + "links": [ + { + "rel": "license", + "href": "https://creativecommons.org/licenses/by-sa/4.0/", + "title": "License for this object (CC-BY-SA-4.0)" + }, + { + "rel": "self", + "href": "https://api.panoramax.xyz/api/collections/912ed747-c21c-4c04-9c9d-f1e75a51072e/items/3f646b4a-caf0-4b2c-a3a6-f3273f9fc332", + "type": "application/geo+json" + }, + { + "rel": "via", + "href": "https://panoramax.openstreetmap.fr", + "type": "application/json", + "title": "Link to the original instance", + "instance_name": "osm-fr" + } + ], + "assets": { + "hd": { + "href": "{{cdn}}/3f646b4a-caf0-4b2c-a3a6-f3273f9fc332/caf0-4b2c-a3a6-f3273f9fc332.jpg", + "type": "image/jpeg", + "roles": [ + "data" + ], + "title": "HD picture", + "description": "Highest resolution available of this picture" + }, + "sd": { + "href": "{{cdn}}/3f646b4a-caf0-4b2c-a3a6-f3273f9fc332/sd.jpg", + "type": "image/jpeg", + "roles": [ + "visual" + ], + "title": "SD picture", + "description": "Picture in standard definition (fixed width of 2048px)" + }, + "thumb": { + "href": "{{cdn}}/3f646b4a-caf0-4b2c-a3a6-f3273f9fc332/thumb.jpg", + "type": "image/jpeg", + "roles": [ + "thumbnail" + ], + "title": "Thumbnail", + "description": "Picture in low definition (fixed width of 500px)" + } + }, + "geometry": { + "type": "Point", + "coordinates": [ + -1.680981389, + 48.115098056 + ] + }, + "providers": [ + { + "name": "bob", + "roles": [ + "producer" + ] + } + ], + "collection": "912ed747-c21c-4c04-9c9d-f1e75a51072e", + "properties": { + "created": "2023-07-30T10:21:34.688826+00:00", + "license": "CC-BY-SA-4.0", + "updated": "2025-06-03T03:02:44.485815+00:00", + "datetime": "2018-03-27T16:55:53+00:00", + "collection": { + "semantics": [] + }, + "datetimetz": "2018-03-27T16:55:53+00:00", + "view:azimuth": 28, + "geovisio:status": "ready", + "original_file:size": 483044, + "geovisio:visibility": "anyone", + "pers:interior_orientation": { + "camera_model": "FDR-X1000V", + "focal_length": 2.8, + "field_of_view": 96, + "camera_manufacturer": "SONY", + "sensor_array_dimensions": [ + 1920, + 1080 + ] + }, + "geovisio:rank_in_collection": 123, + "quality:horizontal_accuracy": 4.2, + "panoramax:horizontal_pixel_density": 20 + }, + "stac_version": "1.0.0", + "stac_extensions": [ + "https://stac-extensions.github.io/view/v1.0.0/schema.json", + "https://stac-extensions.github.io/perspective-imagery/v1.0.0/schema.json" + ] + } + ], + "links": [] +} \ No newline at end of file diff --git a/cmd/geoguess/main.go b/cmd/geoguess/main.go new file mode 100644 index 0000000..17723b3 --- /dev/null +++ b/cmd/geoguess/main.go @@ -0,0 +1,113 @@ +// Command geoguess is GeoGuess, a GeoGuessr-style game for signalbot: the +// bot posts a street-level photo, players answer with a location, and when +// time is up the bot names the place and ranks players by how far off +// they were. +// +// It is an MCP server on stdio (protocol 2025-06-18, newline-delimited +// JSON-RPC) that speaks signalbot's addon extension: signalbot starts it as +// a child process, calls its tools for /geo and for each guess its watch +// catches, and reads its outbox for the results. Stdout carries nothing +// but the protocol. It keeps its state and its own log in GEO_STATE_DIR; +// the log never holds a guess, a coordinate, a name or message text. +// +// Every setting is a GEO_ variable, which signalbot passes to an addon +// server called geo; see README.md. +package main + +import ( + "context" + "fmt" + "log" + "math/rand/v2" + "os" + "os/signal" + "path/filepath" + "runtime/debug" + "syscall" + + "github.com/robdevops/signalbot/cmd/geoguess/geo" + "github.com/robdevops/signalbot/internal/kit/httpx" +) + +// maxLog is the size past which the log is moved aside at start, keeping +// one old log. +const maxLog = 4 << 20 + +func main() { os.Exit(run()) } + +func run() int { + // Stdout is the protocol's: anything else printed by mistake goes to + // stderr, which signalbot counts but never logs. + stdout := os.Stdout + os.Stdout = os.Stderr + cfg, err := loadConfig(os.Getenv) + if err == nil { + err = checkDir(cfg.StateDir) + } + if err != nil { + fmt.Fprintf(os.Stderr, "geoguess: %v\n", err) + return 1 + } + debug.SetMemoryLimit(cfg.MemLimit) + logger, closeLog, err := openLog(cfg.StateDir) + if err != nil { + fmt.Fprintf(os.Stderr, "geoguess: %v\n", err) + return 1 + } + defer closeLog() + if cfg.Token == "" && cfg.Regions == "" { + // Panoramax alone is mostly France: world seeds would mostly search + // empty boxes. + cfg.Regions = "FR" + logger.Printf("GEO_MAPILLARY_TOKEN is not set: Panoramax only, in France unless GEO_REGIONS says otherwise") + } + client := httpx.Client(4) + var sources []geo.Source + if cfg.Token != "" { + sources = append(sources, geo.NewMapillary(cfg.Mapillary, cfg.Token, client)) + } + sources = append(sources, geo.NewPanoramax(cfg.Panoramax, client)) + finder := &search{ + sources: sources, rules: geo.Rules{MinQuality: cfg.MinQuality, MaxAge: cfg.MaxAge}, + places: geo.NewNominatim(cfg.Nominatim, client), rand: rand.New(rand.NewPCG(rand.Uint64(), rand.Uint64())), + log: logger, seeds: map[string]*geo.Seeds{}, regions: cfg.Regions, + } + s, err := newServer(cfg, realClock{}, finder, logger) + if err != nil { + logger.Printf("can't start: %v", err) + fmt.Fprintf(os.Stderr, "geoguess: %v\n", err) + return 1 + } + finder.used = s.isUsed + + ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt) + defer stop() + go s.prefetch(ctx) + done := make(chan error, 1) + go func() { done <- s.serve(ctx, os.Stdin, stdout) }() + select { + case err = <-done: + case <-ctx.Done(): + } + s.save() + if err != nil { + logger.Printf("stopped: %v", err) + return 1 + } + logger.Printf("stopped") + return 0 +} + +// openLog opens GeoGuess's own log, geoguess.log in dir, moving a large one +// aside to geoguess.log.1 first. +func openLog(dir string) (*log.Logger, func(), error) { + path := filepath.Join(dir, "geoguess.log") + if st, err := os.Stat(path); err == nil && st.Size() > maxLog { + os.Rename(path, path+".1") + } + f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o600) + if err != nil { + return nil, nil, fmt.Errorf("can't open its log in GEO_STATE_DIR: %v", err) + } + return log.New(f, "", log.LstdFlags), func() { f.Close() }, nil +} diff --git a/cmd/geoguess/main_test.go b/cmd/geoguess/main_test.go new file mode 100644 index 0000000..291aab0 --- /dev/null +++ b/cmd/geoguess/main_test.go @@ -0,0 +1,803 @@ +package main + +import ( + "bufio" + "bytes" + "context" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "log" + "slices" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/robdevops/signalbot/cmd/geoguess/geo" +) + +// fakeClock is a clock whose time moves only when a test says. +type fakeClock struct { + mu sync.Mutex + now time.Time + timers []*fakeTimer +} + +type fakeTimer struct { + at time.Time + f func() + stopped bool +} + +func (t *fakeTimer) Stop() bool { + was := !t.stopped + t.stopped = true + return was +} + +func (c *fakeClock) Now() time.Time { + c.mu.Lock() + defer c.mu.Unlock() + return c.now +} + +func (c *fakeClock) AfterFunc(d time.Duration, f func()) stopper { + c.mu.Lock() + defer c.mu.Unlock() + t := &fakeTimer{at: c.now.Add(d), f: f} + c.timers = append(c.timers, t) + return t +} + +// Advance moves the time on by d, firing the timers then due in order. +func (c *fakeClock) Advance(d time.Duration) { + c.mu.Lock() + c.now = c.now.Add(d) + var due []*fakeTimer + c.timers = slices.DeleteFunc(c.timers, func(t *fakeTimer) bool { + if !t.at.After(c.now) { + due = append(due, t) + return true + } + return false + }) + c.mu.Unlock() + slices.SortStableFunc(due, func(a, b *fakeTimer) int { return a.at.Compare(b.at) }) + for _, t := range due { + if !t.stopped { + t.f() + } + } +} + +// The photos the fake finder offers: one in Ballarat, and one in Paris for +// a round in Europe. +var ( + ballarat = geo.Point{Lat: -37.5622, Lon: 143.8503} + paris = geo.Point{Lat: 48.8566, Lon: 2.3522} +) + +// syncBuffer is a log a test can read while the server may write it. +type syncBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *syncBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *syncBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +// fakeFinder finds a photo at once, or never if off. +type fakeFinder struct { + mu sync.Mutex + n int + off bool +} + +func (f *fakeFinder) Find(ctx context.Context, regions string) (geo.Photo, error) { + f.mu.Lock() + f.n++ + n, off := f.n, f.off + f.mu.Unlock() + if off { + <-ctx.Done() + return geo.Photo{}, ctx.Err() + } + p := geo.Photo{ + Candidate: geo.Candidate{ + ID: strconv.Itoa(n), Source: "Mapillary", Creator: "alice", Licence: "CC BY-SA 4.0", + Link: "https://www.mapillary.com/app/?pKey=" + strconv.Itoa(n), At: ballarat, + }, + Place: geo.Place{Name: "Ballarat, Victoria, Australia", Country: "Australia", CountryCode: "AU"}, + JPEG: []byte("jpeg " + strconv.Itoa(n)), + } + if strings.Contains(strings.ToLower(regions), "europe") { + p.At, p.Place = paris, geo.Place{Name: "Paris, Île-de-France, France", Country: "France", CountryCode: "FR"} + } + return p, nil +} + +// client drives a server over pipes, as signalbot would, and checks that +// every line the server writes is a valid JSON-RPC message. +type client struct { + t *testing.T + s *server + in *io.PipeWriter + notes chan string + served chan error + done sync.WaitGroup // the reader and the prefetcher + stop context.CancelFunc + + mu sync.Mutex + id int + waiting map[string]chan response + lines int +} + +// rpcIn is a message as the client reads it. +type rpcIn struct { + JSONRPC string `json:"jsonrpc"` + ID json.RawMessage `json:"id"` + Method string `json:"method"` + Result json.RawMessage `json:"result"` + Error *rpcError `json:"error"` +} + +// testServer is a server keeping its state in dir, on clk, with photos from +// the fake finder, and its log in logs. +func testServer(t *testing.T, dir string, clk clock, photos finder, logs io.Writer) *server { + t.Helper() + cfg, err := loadConfig(func(k string) string { return map[string]string{"GEO_STATE_DIR": dir, "GEO_BUFFER": "2"}[k] }) + if err != nil { + t.Fatal(err) + } + s, err := newServer(cfg, clk, photos, log.New(logs, "", 0)) + if err != nil { + t.Fatal(err) + } + s.photoWait = 2 * time.Second + return s +} + +// connect serves s over pipes, with its prefetcher running. +func connect(t *testing.T, s *server) *client { + t.Helper() + inR, inW := io.Pipe() + outR, outW := io.Pipe() + ctx, cancel := context.WithCancel(context.Background()) + c := &client{t: t, s: s, in: inW, notes: make(chan string, 16), served: make(chan error, 1), stop: cancel, waiting: map[string]chan response{}} + c.done.Add(2) + go func() { + defer c.done.Done() + s.prefetch(ctx) + }() + go func() { + err := s.serve(ctx, inR, outW) + outW.Close() + c.served <- err + }() + go func() { + defer c.done.Done() + c.read(outR) + }() + t.Cleanup(c.close) + return c +} + +// read checks and dispatches each line the server writes. +func (c *client) read(r io.Reader) { + sc := bufio.NewScanner(r) + sc.Buffer(nil, 8<<20) + for sc.Scan() { + line := sc.Bytes() + c.mu.Lock() + c.lines++ + c.mu.Unlock() + var m rpcIn + dec := json.NewDecoder(bytes.NewReader(line)) + if err := dec.Decode(&m); err != nil || dec.More() || m.JSONRPC != "2.0" { + c.t.Errorf("stdout has a line that isn't one JSON-RPC message: %.200s", line) + continue + } + switch { + case m.Method != "" && len(m.ID) == 0: + c.notes <- m.Method + case len(m.ID) > 0 && m.Method == "" && (m.Error == nil) != (len(m.Result) == 0): + c.mu.Lock() + ch := c.waiting[string(m.ID)] + delete(c.waiting, string(m.ID)) + c.mu.Unlock() + if ch != nil { + ch <- response{ID: m.ID, Result: m.Result, Error: m.Error} + } + default: + c.t.Errorf("stdout has a message that is neither a response nor a notification: %.200s", line) + } + } +} + +// close ends the session as signalbot does, by closing stdin, and waits for +// the server to finish. +func (c *client) close() { + if c.in == nil { + return + } + c.in.Close() + c.in = nil + select { + case err := <-c.served: + if err != nil { + c.t.Errorf("serve: %v", err) + } + case <-time.After(5 * time.Second): + c.t.Error("the server didn't stop") + } + c.stop() + c.done.Wait() +} + +// send writes one raw line to the server. +func (c *client) send(line string) { + c.t.Helper() + if _, err := io.WriteString(c.in, line+"\n"); err != nil { + c.t.Fatal(err) + } +} + +// request sends a request and waits for its response. +func (c *client) request(method string, params any) response { + c.t.Helper() + c.mu.Lock() + c.id++ + id := strconv.Itoa(c.id) + ch := make(chan response, 1) + c.waiting[id] = ch + c.mu.Unlock() + data, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": c.id, "method": method, "params": params}) + if err != nil { + c.t.Fatal(err) + } + c.send(string(data)) + select { + case r := <-ch: + return r + case <-time.After(10 * time.Second): + c.t.Fatalf("no answer to %s", method) + } + return response{} +} + +// result is a request's result, which must not be an error. +func (c *client) result(method string, params any, v any) { + c.t.Helper() + r := c.request(method, params) + if r.Error != nil { + c.t.Fatalf("%s: error %d %s", method, r.Error.Code, r.Error.Message) + } + if err := json.Unmarshal(r.Result.(json.RawMessage), v); err != nil { + c.t.Fatalf("%s: %v", method, err) + } +} + +// from is the context of a message sent now by user in chat. +func from(clk clock, chat, user string) callContext { + return callContext{Chat: chat, Sender: user, Ref: "r_1", Addressed: true, Group: true, Sent: clk.Now().Unix()} +} + +// tool calls a tool as the bot does, with the message's context in _meta. +func (c *client) tool(name string, args map[string]string, ctx callContext) toolResult { + c.t.Helper() + var r toolResult + c.result("tools/call", map[string]any{ + "name": name, "arguments": args, + "_meta": map[string]any{vendor + "context": ctx}, + }, &r) + return r +} + +func (c *client) geo(args string, ctx callContext) toolResult { + c.t.Helper() + return c.tool("geo", map[string]string{"args": args}, ctx) +} + +func (c *client) guess(text string, ctx callContext) toolResult { + c.t.Helper() + return c.tool("geo_guess", map[string]string{"text": text}, ctx) +} + +// read is the outbox page after cursor. +func (c *client) outbox(cursor string) outboxPage { + c.t.Helper() + var r readResult + c.result("resources/read", uriParams{outboxURI + "/" + cursor}, &r) + if len(r.Contents) != 1 || r.Contents[0].MimeType != "application/json" { + c.t.Fatalf("read %+v", r) + } + var p outboxPage + if err := json.Unmarshal([]byte(r.Contents[0].Text), &p); err != nil { + c.t.Fatal(err) + } + return p +} + +// note waits for a notification. +func (c *client) note() string { + c.t.Helper() + select { + case m := <-c.notes: + return m + case <-time.After(5 * time.Second): + c.t.Fatal("no notification") + } + return "" +} + +// words is a tool result's text. +func words(r toolResult) string { + var parts []string + for _, c := range r.Content { + if c.Type == "text" { + parts = append(parts, c.Text) + } + } + return strings.Join(parts, "\n") +} + +func reacted(r toolResult) bool { return r.Meta != nil && r.Meta.React == pin } + +// start is a fake clock, a server and a client, with the session +// initialized and subscribed to the outbox. +func start(t *testing.T) (*fakeClock, *client, *syncBuffer) { + t.Helper() + clk := &fakeClock{now: time.Date(2026, 11, 20, 14, 0, 0, 0, time.UTC)} + logs := &syncBuffer{} + c := connect(t, testServer(t, t.TempDir(), clk, &fakeFinder{}, logs)) + var init initializeResult + c.result("initialize", map[string]any{ + "protocolVersion": protocolVersion, "clientInfo": map[string]string{"name": "signalbot", "version": "1"}, + "capabilities": map[string]any{"experimental": map[string]any{vendor + "addon": map[string]int{"version": 1}}}, + }, &init) + c.send(`{"jsonrpc":"2.0","method":"notifications/initialized"}`) + var empty struct{} + c.result("resources/subscribe", uriParams{outboxURI}, &empty) + return clk, c, logs +} + +const ( + chat = "c_one" + alice = "u_alice" + bob = "u_bob" +) + +func TestInitializeAndTools(t *testing.T) { + _, c, _ := start(t) + var init initializeResult + c.result("initialize", map[string]any{"protocolVersion": "2099-01-01"}, &init) + if init.ProtocolVersion != protocolVersion || init.Capabilities.Experimental[vendor+"addon"].Version != 1 || + !init.Capabilities.Resources.Subscribe || init.ServerInfo.Name != "geoguess" { + t.Errorf("initialize %+v", init) + } + var list struct { + Tools []tool `json:"tools"` + } + c.result("tools/list", struct{}{}, &list) + var names []string + for _, tl := range list.Tools { + names = append(names, tl.Name) + if !slices.Equal(tl.Meta.Visibility, []string{"bot"}) || tl.InputSchema.Type != "object" { + t.Errorf("tool %+v", tl) + } + } + if !slices.Equal(names, []string{"geo", "geo_guess"}) { + t.Errorf("tools %v", names) + } + var pong struct{} + c.result("ping", nil, &pong) + if r := c.request("tools/call", map[string]any{"name": "nope"}); r.Error == nil || r.Error.Code != codeInvalidParams { + t.Errorf("unknown tool %+v", r) + } + if r := c.request("resources/read", uriParams{"file:///etc/passwd"}); r.Error == nil || r.Error.Code != codeNotFound { + t.Errorf("another resource %+v", r) + } + // Called without a chat, as another MCP client might. + var r toolResult + c.result("tools/call", map[string]any{"name": "geo", "arguments": map[string]string{"args": ""}}, &r) + if !r.IsError || words(r) != noChat { + t.Errorf("no context %+v", r) + } +} + +// A whole round: the photo with its watch, guesses, the timer, and the +// results in the outbox. +func TestRound(t *testing.T) { + clk, c, logs := start(t) + began := clk.Now() + r := c.geo("90s", from(clk, chat, alice)) + if len(r.Content) != 2 || r.Content[0].Type != "image" || r.Content[0].MimeType != "image/jpeg" { + t.Fatalf("content %+v", r.Content) + } + if data, _ := base64.StdEncoding.DecodeString(r.Content[0].Data); !bytes.HasPrefix(data, []byte("jpeg ")) { + t.Errorf("image %q", data) + } + want := caption(began.Add(90*time.Second), 90*time.Second) + if words(r) != want || !strings.Contains(want, "(90 sec)") { + t.Errorf("caption %q", words(r)) + } + if r.Meta == nil || r.Meta.Watch == nil { + t.Fatalf("no watch: %+v", r.Meta) + } + w := *r.Meta.Watch + if w.ID == "" || w.Pattern != geo.Pattern || w.Tool != "geo_guess" || w.Guard != guard || + w.Until != began.Add(95*time.Second).Format(time.RFC3339) { + t.Errorf("watch %+v", w) + } + + if got := words(c.geo("", from(clk, chat, bob))); got != "A round is on: 1m30s left." { + t.Errorf("a second /geo: %q", got) + } + clk.Advance(10 * time.Second) + if r := c.guess("https://maps.google.com/maps?q=-37.6%2C143.9", from(clk, chat, alice)); !reacted(r) { + t.Errorf("Alice's guess: %+v", r) + } + if r := c.guess("I reckon -33.87, 151.21", from(clk, chat, bob)); !reacted(r) { + t.Errorf("Bob's guess: %+v", r) + } + if r := c.guess("see you at 5", from(clk, chat, bob)); reacted(r) { + t.Errorf("no location, but %+v", r) + } + if r := c.guess("-33.87, 151.21", from(clk, "c_two", bob)); reacted(r) || words(r) != noRound { + t.Errorf("a guess in another chat: %+v", r) + } + if p := c.outbox("0"); len(p.Ops) != 0 { + t.Errorf("ops before time is up: %+v", p) + } + + clk.Advance(80*time.Second + settle) + if m := c.note(); m != "notifications/resources/updated" { + t.Errorf("notification %q", m) + } + page := c.outbox("0") + aliceKm, bobKm := geo.Km(geo.Point{Lat: -37.6, Lon: 143.9}, ballarat), geo.Km(geo.Point{Lat: -33.87, Lon: 151.21}, ballarat) + results := "📍 [**Ballarat, Victoria, Australia**](https://www.openstreetmap.org/?mlat=-37.56220&mlon=143.85030#map=12/-37.56220/143.85030)\n" + + "🥇 {u_alice} " + geo.Distance(aliceKm) + " · " + geo.Thousands(geo.Points(aliceKm)) + "\n" + + "🥈 {u_bob} " + geo.Distance(bobKm) + " · " + geo.Thousands(geo.Points(bobKm)) + "\n" + + "Photo: [alice, Mapillary, CC BY-SA 4.0](https://www.mapillary.com/app/?pKey=1)" + if len(page.Ops) != 2 || page.More { + t.Fatalf("page %+v", page) + } + if o := page.Ops[0]; o.Op != "post" || o.Chat != chat || o.Text != results { + t.Errorf("post %+v\nwant %q", o, results) + } + if o := page.Ops[1]; o.Op != "unwatch" || o.Chat != chat || o.Watch != w.ID || o.ID != page.Cursor { + t.Errorf("unwatch %+v, cursor %s", o, page.Cursor) + } + if strings.Contains(page.Ops[0].Text, "151.2") || strings.Contains(page.Ops[0].Text, "-33.8") { + t.Error("the results say where Bob guessed") + } + if again := c.outbox(page.Cursor); len(again.Ops) != 0 || again.Cursor != page.Cursor { + t.Errorf("read past: %+v", again) + } + if r := c.guess("-37.56, 143.85", from(clk, chat, bob)); reacted(r) || words(r) != noRound { + t.Errorf("a guess after the round: %+v", r) + } + scores := c.geo("scores", from(clk, chat, bob)) + wantScores := "🏆 **Scores, last 7 days**\n🥇 {u_alice} " + geo.Thousands(geo.Points(aliceKm)) + " · 1 round\n🥈 {u_bob} " + geo.Thousands(geo.Points(bobKm)) + " · 1 round" + if words(scores) != wantScores { + t.Errorf("scores %q", words(scores)) + } + clk.Advance(8 * 24 * time.Hour) + if got := words(c.geo("scores", from(clk, chat, bob))); !strings.HasPrefix(got, "No scores") { + t.Errorf("scores a week later: %q", got) + } + + c.close() + for _, secret := range []string{"143.9", "151.2", "-33.8", "u_alice", "u_bob", "c_one", "maps.google", "reckon", "Ballarat"} { + if strings.Contains(logs.String(), secret) { + t.Errorf("the log holds %q:\n%s", secret, logs) + } + } + if !strings.Contains(logs.String(), "revealed: 2 guesses") { + t.Errorf("log:\n%s", logs) + } +} + +// An edited guess replaces the first; a late one, or an edit of a message +// from before the round, doesn't count. +func TestEditAndLateGuess(t *testing.T) { + clk, c, _ := start(t) + c.geo("1m", from(clk, chat, alice)) + clk.Advance(10 * time.Second) + first := from(clk, chat, alice) + if !reacted(c.guess("-33.87, 151.21", first)) { + t.Fatal("Alice's first guess") + } + clk.Advance(10 * time.Second) + edit := first + edit.Edited = clk.Now().Unix() + if !reacted(c.guess("geo:-37.57,143.86", edit)) { + t.Fatal("Alice's edit") + } + old := from(clk, chat, bob) + old.Sent, old.Edited = clk.Now().Add(-time.Hour).Unix(), clk.Now().Unix() + if r := c.guess("-37.56, 143.85", old); reacted(r) { + t.Errorf("an edit of an older message counted: %+v", r) + } + clk.Advance(41 * time.Second) // a second past the deadline, before the reveal + if r := c.guess("-37.56, 143.85", from(clk, chat, bob)); reacted(r) || words(r) != "Too late for this round." { + t.Errorf("a late guess: %+v", r) + } + clk.Advance(settle) + c.note() + ops := c.outbox("0").Ops + km := geo.Km(geo.Point{Lat: -37.57, Lon: 143.86}, ballarat) + if len(ops) != 2 || !strings.Contains(ops[0].Text, "\n🥇 {u_alice} "+geo.Distance(km)+" ·") || strings.Contains(ops[0].Text, "u_bob") || strings.Contains(ops[0].Text, "🥈") { + t.Errorf("results %+v", ops) + } +} + +// Only the player who started a round may end or skip it; a skip scores +// nothing, and an end reveals at once. +func TestEndAndSkip(t *testing.T) { + clk, c, _ := start(t) + if got := words(c.geo("end", from(clk, chat, alice))); got != noRound { + t.Errorf("end with no round: %q", got) + } + c.geo("", from(clk, chat, alice)) + if got := words(c.geo("end", from(clk, chat, bob))); got != "Only the player who started this round can end it." { + t.Errorf("Bob ends: %q", got) + } + if got := words(c.geo("SKIP", from(clk, chat, bob))); got != "Only the player who started this round can skip it." { + t.Errorf("Bob skips: %q", got) + } + c.guess("-37.6, 143.9", from(clk, chat, bob)) + skipped := words(c.geo("skip", from(clk, chat, alice))) + if !strings.HasPrefix(skipped, "Round skipped. It was 📍 [**Ballarat, Victoria, Australia**](") || strings.Contains(skipped, "u_bob") { + t.Errorf("skip: %q", skipped) + } + c.note() + page := c.outbox("0") + if len(page.Ops) != 1 || page.Ops[0].Op != "unwatch" { + t.Errorf("after a skip: %+v", page) + } + if got := words(c.geo("scores", from(clk, chat, alice))); !strings.HasPrefix(got, "No scores") { + t.Errorf("a skip scored: %q", got) + } + + c.geo("5m", from(clk, chat, alice)) + clk.Advance(time.Minute) + c.guess("-37.6, 143.9", from(clk, chat, bob)) + ended := words(c.geo("end", from(clk, chat, alice))) + if !strings.Contains(ended, "\n🥇 {u_bob} ") { + t.Errorf("end: %q", ended) + } + c.note() + page = c.outbox(page.Cursor) + if len(page.Ops) != 1 || page.Ops[0].Op != "unwatch" { + t.Errorf("after an end: %+v", page) + } + clk.Advance(5 * time.Minute) // the round's timer, stopped + if p := c.outbox(page.Cursor); len(p.Ops) != 0 { + t.Errorf("the timer of an ended round fired: %+v", p) + } + if got := words(c.geo("scores", from(clk, chat, alice))); !strings.Contains(got, "🥇 {u_bob} ") { + t.Errorf("scores %q", got) + } +} + +// A cursor the server doesn't know, such as one from before a restart, +// gets everything it still holds; one it gave lets go of what was read. +func TestUnknownCursor(t *testing.T) { + clk, c, _ := start(t) + c.geo("30s", from(clk, chat, alice)) + clk.Advance(30*time.Second + settle) + c.note() + for _, cursor := range []string{"0", "k7f2.18", "garbage", c.s.nonce + ".99", c.s.nonce + ".-1"} { + if p := c.outbox(cursor); len(p.Ops) != 2 { + t.Errorf("cursor %q: %+v", cursor, p) + } + } + p := c.outbox(c.s.nonce + ".1") // read the post, not the unwatch + if len(p.Ops) != 1 || p.Ops[0].Op != "unwatch" { + t.Errorf("after the post: %+v", p) + } + p = c.outbox(p.Cursor) + if len(p.Ops) != 0 { + t.Errorf("after all: %+v", p) + } + if again := c.outbox("unknown"); len(again.Ops) != 0 || again.Cursor != p.Cursor { + t.Errorf("nothing held: %+v", again) + } +} + +// A round survives a restart: its guesses are kept, its timer re-armed, and +// one whose time passed while GeoGuess was down is revealed at once. +func TestRestart(t *testing.T) { + clk := &fakeClock{now: time.Date(2026, 11, 20, 14, 0, 0, 0, time.UTC)} + dir := t.TempDir() + var logs syncBuffer + c := connect(t, testServer(t, dir, clk, &fakeFinder{}, &logs)) + c.geo("1m", from(clk, chat, alice)) + c.geo("1m", from(clk, "c_two", bob)) + clk.Advance(10 * time.Second) + c.guess("-37.6, 143.9", from(clk, chat, alice)) + c.guess("-37.6, 143.9", from(clk, "c_two", alice)) + c.close() + + // Back before c_one's deadline, with a new clock: the old timers are gone. + clk = &fakeClock{now: clk.Now().Add(20 * time.Second)} + c = connect(t, testServer(t, dir, clk, &fakeFinder{}, &logs)) + c.result("resources/subscribe", uriParams{outboxURI}, new(struct{})) + if got := words(c.geo("", from(clk, chat, bob))); got != "A round is on: 30s left." { + t.Errorf("after a restart: %q", got) + } + c.guess("-33.87, 151.21", from(clk, chat, bob)) + c.close() + + // Back after both deadlines: both rounds are revealed at once. + clk = &fakeClock{now: clk.Now().Add(time.Hour - 2*time.Minute)} + s := testServer(t, dir, clk, &fakeFinder{}, &logs) + c = connect(t, s) + c.result("resources/subscribe", uriParams{outboxURI}, new(struct{})) + c.note() + page := c.outbox("old.4") + if len(page.Ops) != 4 { + t.Fatalf("ops %+v", page) + } + ids := map[string]bool{} + for _, o := range page.Ops { + ids[o.ID] = true + if o.Op == "post" && o.Chat == chat && (!strings.Contains(o.Text, "🥇 {u_alice}") || !strings.Contains(o.Text, "🥈 {u_bob}")) { + t.Errorf("results %q", o.Text) + } + } + if len(ids) != 4 { + t.Errorf("op IDs %v", ids) + } + c.close() + + // Unread ops outlive another restart, with the same IDs, so the bot can + // tell those it already applied. + c = connect(t, testServer(t, dir, clk, &fakeFinder{}, &logs)) + again := c.outbox("0") + if len(again.Ops) != 4 { + t.Fatalf("after another restart: %+v", again) + } + for _, o := range again.Ops { + if !ids[o.ID] { + t.Errorf("op %s changed its ID", o.ID) + } + } + if got := words(c.geo("", from(clk, chat, bob))); !strings.HasPrefix(got, "🌍") { + t.Errorf("a new round: %q", got) + } + // Ops unread for an hour are let go; only the new round's are left. + clk.Advance(keepOps + time.Second) + if p := c.outbox("0"); len(p.Ops) != 2 || ids[p.Ops[0].ID] || ids[p.Ops[1].ID] { + t.Errorf("an hour on: %+v", p) + } +} + +// Stdout carries only JSON-RPC, whatever arrives on stdin. +func TestStdoutIsProtocol(t *testing.T) { + _, c, _ := start(t) + c.send("not json") + c.send("") + c.send(`{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":1}}`) + c.send(`{"jsonrpc":"2.0","id":99,"result":{}}`) + c.send(`{"id":"x"` + strings.Repeat(" ", maxLine) + `}`) + if r := c.request("nope/nope", nil); r.Error == nil || r.Error.Code != codeNoMethod { + t.Errorf("unknown method %+v", r) + } + if r := c.request("tools/call", "not an object"); r.Error == nil || r.Error.Code != codeInvalidParams { + t.Errorf("bad params %+v", r) + } + c.result("ping", nil, new(struct{})) + c.close() + // initialize, subscribe, the parse error, nope/nope, tools/call and ping. + if c.lines != 6 { + t.Errorf("%d lines on stdout", c.lines) + } +} + +func TestNoPhotoAndRegions(t *testing.T) { + clk := &fakeClock{now: time.Date(2026, 11, 20, 14, 0, 0, 0, time.UTC)} + photos := &fakeFinder{off: true} + s := testServer(t, t.TempDir(), clk, photos, io.Discard) + s.photoWait = 50 * time.Millisecond + c := connect(t, s) + if got := words(c.geo("", from(clk, chat, alice))); got != noPhoto { + t.Errorf("no photo: %q", got) + } + + clk, c, _ = start(t) + r := c.geo("Europe 2m", from(clk, chat, alice)) + if !strings.Contains(words(r), "(2 min)") { + t.Errorf("caption %q", words(r)) + } + if got := words(c.geo("end", from(clk, chat, alice))); !strings.Contains(got, "Paris") { + t.Errorf("a round in Europe: %q", got) + } + for _, args := range []string{"atlantis", "10s", "31m", "2x"} { + if r := c.geo(args, from(clk, chat, alice)); r.Meta != nil { + t.Errorf("/geo %s started a round", args) + } + } + if got := words(c.geo("", from(clk, chat, alice))); !strings.HasPrefix(got, "🌍") { + t.Errorf("a round anywhere: %q", got) + } + if got := words(c.geo("end", from(clk, chat, alice))); !strings.Contains(got, "Ballarat") { + t.Errorf("a world round: %q", got) + } +} + +func TestConfig(t *testing.T) { + env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } } + c, err := loadConfig(env(map[string]string{"GEO_STATE_DIR": "/x"})) + if err != nil || c.Round != 3*time.Minute || c.MemLimit != 200<<20 || c.Buffer != 3 || c.MinQuality != 0.5 || + c.Nominatim != geo.NominatimURL || c.Panoramax != geo.PanoramaxURL || c.Mapillary != geo.MapillaryURL || c.MaxAge < 10*365*24*time.Hour { + t.Errorf("defaults %+v, %v", c, err) + } + c, err = loadConfig(env(map[string]string{"GEO_STATE_DIR": "/x", "GEO_ROUND": "90s", "GEO_MEMLIMIT": "1GiB", "GEO_REGIONS": "europe", "GEO_BUFFER": "5"})) + if err != nil || c.Round != 90*time.Second || c.MemLimit != 1<<30 || c.Regions != "europe" || c.Buffer != 5 { + t.Errorf("set %+v, %v", c, err) + } + _, err = loadConfig(env(map[string]string{"GEO_ROUND": "1h", "GEO_MEMLIMIT": "lots", "GEO_REGIONS": "atlantis", "GEO_BUFFER": "0", + "GEO_MIN_QUALITY": "2", "GEO_MAX_AGE_YEARS": "-1", "GEO_NOMINATIM_URL": "http://x", + "GEO_PANORAMAX_URL": "ftp://x", "GEO_MAPILLARY_URL": "graph.example"})) + for _, name := range []string{"GEO_STATE_DIR", "GEO_ROUND", "GEO_MEMLIMIT", "GEO_REGIONS", "GEO_BUFFER", "GEO_MIN_QUALITY", "GEO_MAX_AGE_YEARS", + "GEO_NOMINATIM_URL", "GEO_PANORAMAX_URL", "GEO_MAPILLARY_URL"} { + if err == nil || !strings.Contains(err.Error(), name) { + t.Errorf("no error for %s: %v", name, err) + } + } + for s, want := range map[string]int64{"200MiB": 200 << 20, "1GiB": 1 << 30, "67108864": 64 << 20, "65536KiB": 64 << 20, "0.5GiB": 512 << 20} { + if got, err := parseSize(s); got != want || err != nil { + t.Errorf("parseSize(%q) = %d, %v", s, got, err) + } + } + for _, s := range []string{"", "1MiB", "-5MiB", "200MB", "MiB"} { + if _, err := parseSize(s); err == nil { + t.Errorf("parseSize(%q) passed", s) + } + } + if err := checkDir(t.TempDir()); err != nil { + t.Error(err) + } + if err := checkDir(t.TempDir() + "/missing"); err == nil || !strings.Contains(err.Error(), "GEO_STATE_DIR") { + t.Errorf("a missing directory: %v", err) + } +} + +func TestLabels(t *testing.T) { + for d, want := range map[time.Duration]string{3 * time.Minute: "3 min", 90 * time.Second: "90 sec", 30 * time.Minute: "30 min"} { + if got := lengthLabel(d); got != want { + t.Errorf("lengthLabel(%s) = %q", d, got) + } + } + r := &round{Deadline: time.Unix(1000, 0)} + for left, want := range map[time.Duration]string{30 * time.Second: "30s", 2 * time.Minute: "2m", 102 * time.Second: "1m42s", -time.Second: "0s"} { + if got := words(busy(r, r.Deadline.Add(-left))); got != fmt.Sprintf("A round is on: %s left.", want) { + t.Errorf("busy %s: %q", left, got) + } + } + if got := (credit{Creator: "[bob](https://evil.example)*", Source: "Panoramax", Licence: "etalab-2.0", Link: "https://x.example/p"}).String(); got != "Photo: [bobhttps://evil.example, Panoramax, etalab-2.0](https://x.example/p)" { + t.Errorf("credit %q", got) + } + if got := (credit{Source: "Mapillary"}).String(); got != "Photo: Mapillary" { + t.Errorf("credit %q", got) + } + if !validID("u_ABC234", "u_") || validID("u_", "u_") || validID("u_a}b", "u_") || validID("c_x", "u_") { + t.Error("validID") + } +} diff --git a/cmd/geoguess/prefetch.go b/cmd/geoguess/prefetch.go new file mode 100644 index 0000000..fcaacb2 --- /dev/null +++ b/cmd/geoguess/prefetch.go @@ -0,0 +1,223 @@ +package main + +import ( + "context" + "errors" + "log" + "maps" + "math/rand/v2" + "slices" + "strings" + "time" + + "github.com/robdevops/signalbot/cmd/geoguess/geo" +) + +// finder finds a photo worth a round in regions ("" is GEO_REGIONS): the +// real search, or a test's. +type finder interface { + Find(ctx context.Context, regions string) (geo.Photo, error) +} + +// The prefetcher's limits: one search's time, and the photos kept beyond +// GEO_BUFFER for rounds in other regions. +const ( + findTimeout = 3 * time.Minute + extraPhotos = 4 +) + +// prefetch keeps GEO_BUFFER checked photos ready, so /geo answers at once, +// and looks for one in each region a /geo asked for. It is the only caller +// of Find. +func (s *server) prefetch(ctx context.Context) { + failures := 0 + for { + region, ok := s.nextSearch() + if !ok { + select { + case <-s.wake: + continue + case <-ctx.Done(): + return + } + } + fctx, cancel := context.WithTimeout(ctx, findTimeout) + p, err := s.photos.Find(fctx, region) + cancel() + if ctx.Err() != nil { + return + } + if err == nil { + failures = 0 + s.add(p, region) + continue + } + s.mu.Lock() + delete(s.wants, region) // asked again by the next /geo for it + s.mu.Unlock() + wait := min(5*time.Second<<failures, 5*time.Minute) + failures = min(failures+1, 10) + if errors.Is(err, geo.ErrSlowDown) { + wait = time.Minute + } + s.log.Printf("no photo found (%v); trying again in %s", err, wait) + t := time.NewTimer(wait) + select { + case <-t.C: + case <-ctx.Done(): + t.Stop() + return + } + } +} + +// nextSearch is the region to look in next: the first a /geo asked for +// that the buffer lacks, else GEO_REGIONS while the buffer isn't full. +func (s *server) nextSearch() (string, bool) { + s.mu.Lock() + defer s.mu.Unlock() + for _, region := range slices.Sorted(maps.Keys(s.wants)) { + if s.match(region) >= 0 { + delete(s.wants, region) + continue + } + return region, true + } + return "", len(s.buffer) < s.cfg.Buffer +} + +// add puts a photo found for region in the buffer, and marks it used so no +// later search finds it again. +func (s *server) add(p geo.Photo, region string) { + s.mu.Lock() + s.buffer = append(s.buffer, p) + if over := len(s.buffer) - s.cfg.Buffer - extraPhotos; over > 0 { + s.buffer = slices.Delete(s.buffer, 0, over) + } + s.markUsed(p.Key()) + delete(s.wants, region) + close(s.changed) + s.changed = make(chan struct{}) + n := len(s.buffer) + s.mu.Unlock() + s.save() + s.log.Printf("a %s photo is ready; %d in all", p.Source, n) +} + +// take is a photo from the buffer for region, waiting up to photoWait for +// the prefetcher to find one. +func (s *server) take(ctx context.Context, region string) (geo.Photo, bool) { + t := time.NewTimer(s.photoWait) + defer t.Stop() + for { + s.mu.Lock() + if i := s.match(region); i >= 0 { + p := s.buffer[i] + s.buffer = slices.Delete(s.buffer, i, i+1) + s.mu.Unlock() + s.wakeUp() + return p, true + } + if region != "" { + s.wants[region] = true + } + changed := s.changed + s.mu.Unlock() + s.wakeUp() + select { + case <-changed: + case <-t.C: + return geo.Photo{}, false + case <-ctx.Done(): + return geo.Photo{}, false + } + } +} + +// match is the index of the oldest photo in the buffer that is in region +// ("" is GEO_REGIONS), or -1. s.mu is held. +func (s *server) match(region string) int { + if region == "" { + region = s.cfg.Regions + } + if region == "" { + if len(s.buffer) == 0 { + return -1 + } + return 0 + } + seeds, err := s.seedsLocked(region) + if err != nil { + return -1 + } + return slices.IndexFunc(s.buffer, func(p geo.Photo) bool { return seeds.Has(p.Place.CountryCode) }) +} + +// regionSeeds is the seeds for region, a /geo argument, or an error if it +// names none. +func (s *server) regionSeeds(region string) (*geo.Seeds, error) { + s.mu.Lock() + defer s.mu.Unlock() + return s.seedsLocked(region) +} + +func (s *server) seedsLocked(region string) (*geo.Seeds, error) { + key := strings.ToUpper(region) + if seeds := s.seeds[key]; seeds != nil { + return seeds, nil + } + seeds, err := geo.LoadSeeds(region) + if err == nil && len(s.seeds) < 64 { + s.seeds[key] = seeds + } + return seeds, err +} + +// wakeUp tells the prefetcher to look at the buffer again, without waiting. +func (s *server) wakeUp() { + select { + case s.wake <- struct{}{}: + default: + } +} + +// search is the real finder: Mapillary and Panoramax, checked by the geo +// package, with places named by Nominatim. +type search struct { + sources []geo.Source + rules geo.Rules + places *geo.Nominatim + rand *rand.Rand + used func(key string) bool + log *log.Logger + seeds map[string]*geo.Seeds + regions string // GEO_REGIONS +} + +// Find looks for one photo. It logs only counts of rejections, by reason, +// and errors, which hold no URL. +func (f *search) Find(ctx context.Context, regions string) (geo.Photo, error) { + if regions == "" { + regions = f.regions + } + seeds := f.seeds[regions] + if seeds == nil { + var err error + if seeds, err = geo.LoadSeeds(regions); err != nil { + return geo.Photo{}, err + } + f.seeds[regions] = seeds + } + rejected := map[string]int{} + finder := geo.Finder{ + Sources: f.sources, Seeds: seeds, Rules: f.rules, Places: f.places, Rand: f.rand, Now: time.Now, + Used: f.used, + Rejected: func(source string, why geo.Reject) { rejected[source+": "+string(why)]++ }, + Failed: func(err error) { f.log.Printf("search failed: %v", err) }, + } + p, err := finder.Find(ctx) + if len(rejected) > 0 { + f.log.Printf("photos rejected: %v", rejected) + } + return p, err +} diff --git a/cmd/geoguess/rpc.go b/cmd/geoguess/rpc.go new file mode 100644 index 0000000..39c46e2 --- /dev/null +++ b/cmd/geoguess/rpc.go @@ -0,0 +1,410 @@ +package main + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "io" + "strings" + "sync" +) + +// The protocol GeoGuess speaks: MCP 2025-06-18, as newline-delimited +// JSON-RPC 2.0 on stdin and stdout, plus signalbot's addon extension. +const ( + protocolVersion = "2025-06-18" + vendor = "io.github.robdevops.signalbot/" + outboxURI = "signalbot://outbox" +) + +// maxLine caps one incoming line. signalbot's requests are small: a +// command's arguments or one chat message. +const maxLine = 1 << 20 + +// JSON-RPC's error codes, and MCP's for a resource that isn't there. +const ( + codeParse = -32700 + codeInvalidRequest = -32600 + codeNoMethod = -32601 + codeInvalidParams = -32602 + codeNotFound = -32002 +) + +// message is one JSON-RPC message read: a request, a notification (no ID) +// or a response to a request of ours (GeoGuess sends none). +type message struct { + JSONRPC string `json:"jsonrpc"` + ID json.RawMessage `json:"id,omitempty"` + Method string `json:"method"` + Params json.RawMessage `json:"params,omitempty"` +} + +// response is the answer to one request: its result or an error. +type response struct { + JSONRPC string `json:"jsonrpc"` + ID json.RawMessage `json:"id"` + Result any `json:"result,omitempty"` + Error *rpcError `json:"error,omitempty"` +} + +// notification is a message to the client that wants no answer. +type notification struct { + JSONRPC string `json:"jsonrpc"` + Method string `json:"method"` + Params any `json:"params,omitempty"` +} + +type rpcError struct { + Code int `json:"code"` + Message string `json:"message"` +} + +func (e *rpcError) Error() string { return e.Message } + +// wire writes whole messages to stdout, one per line, one at a time: it is +// the only writer of stdout, which carries nothing but the protocol. +type wire struct { + mu sync.Mutex + w io.Writer +} + +func (w *wire) send(v any) error { + data, err := json.Marshal(v) + if err != nil { + return err + } + w.mu.Lock() + defer w.mu.Unlock() + _, err = w.w.Write(append(data, '\n')) + return err +} + +// handler answers one request's params with a result, or an *rpcError. +type handler func(ctx context.Context, params json.RawMessage) (any, error) + +// serve reads requests from in until it ends or ctx does, answering each on +// its own goroutine through out, and waits for the answers in flight. +func (s *server) serve(ctx context.Context, in io.Reader, out io.Writer) error { + s.out = &wire{w: out} + ctx, cancel := context.WithCancel(ctx) + defer cancel() + go s.notifier(ctx) + var wg sync.WaitGroup + defer wg.Wait() + r := bufio.NewReaderSize(in, 64<<10) + for { + line, err := readLine(r) + if err != nil { + if errors.Is(err, io.EOF) { + return nil + } + return err + } + if line == nil { // too long, or blank + continue + } + var m message + if json.Unmarshal(line, &m) != nil { + s.out.send(response{JSONRPC: "2.0", ID: json.RawMessage("null"), Error: &rpcError{codeParse, "parse error"}}) + continue + } + if len(m.ID) == 0 || m.Method == "" { // a notification, or a response + continue + } + wg.Add(1) + go func() { + defer wg.Done() + s.out.send(s.answer(ctx, m)) + }() + } +} + +// answer runs one request's handler. +func (s *server) answer(ctx context.Context, m message) response { + resp := response{JSONRPC: "2.0", ID: m.ID} + h, ok := s.methods()[m.Method] + switch { + case m.JSONRPC != "2.0": + resp.Error = &rpcError{codeInvalidRequest, "not JSON-RPC 2.0"} + case !ok: + resp.Error = &rpcError{codeNoMethod, "method not found"} + default: + result, err := h(ctx, m.Params) + var re *rpcError + switch { + case errors.As(err, &re): + resp.Error = re + case err != nil: + resp.Error = &rpcError{-32603, "internal error"} + default: + resp.Result = result + } + } + return resp +} + +// readLine reads one line without its end. A line longer than maxLine is +// skipped whole, and nil returned for it, as for a blank one. +func readLine(r *bufio.Reader) ([]byte, error) { + var line []byte + tooLong := false + for { + part, err := r.ReadSlice('\n') + if !tooLong { + line = append(line, part...) + if len(line) > maxLine { + line, tooLong = nil, true + } + } + switch { + case errors.Is(err, bufio.ErrBufferFull): + continue + case err != nil && (len(line) == 0 || !errors.Is(err, io.EOF)): + return nil, err + } + if tooLong { + return nil, nil + } + line = trimEOL(line) + if len(line) == 0 { + return nil, nil + } + return line, nil + } +} + +func trimEOL(b []byte) []byte { + for len(b) > 0 && (b[len(b)-1] == '\n' || b[len(b)-1] == '\r' || b[len(b)-1] == ' ') { + b = b[:len(b)-1] + } + return b +} + +// params reads a request's params into v, or fails as JSON-RPC's invalid +// params. +func params(raw json.RawMessage, v any) error { + if len(raw) == 0 { + raw = json.RawMessage("{}") + } + if json.Unmarshal(raw, v) != nil { + return &rpcError{codeInvalidParams, "invalid params"} + } + return nil +} + +// The MCP methods' results. +type ( + initializeResult struct { + ProtocolVersion string `json:"protocolVersion"` + Capabilities capabilities `json:"capabilities"` + ServerInfo serverInfo `json:"serverInfo"` + } + capabilities struct { + Experimental map[string]addonCapability `json:"experimental"` + Tools struct{} `json:"tools"` + Resources resourcesCapability `json:"resources"` + } + addonCapability struct { + Version int `json:"version"` + } + resourcesCapability struct { + Subscribe bool `json:"subscribe"` + } + serverInfo struct { + Name string `json:"name"` + Title string `json:"title,omitempty"` + Version string `json:"version"` + } + + tool struct { + Name string `json:"name"` + Description string `json:"description"` + InputSchema schema `json:"inputSchema"` + Meta visibility `json:"_meta"` + } + schema struct { + Type string `json:"type"` + Properties map[string]schema `json:"properties,omitempty"` + Required []string `json:"required,omitempty"` + } + visibility struct { + Visibility []string `json:"io.github.robdevops.signalbot/visibility"` + } + + toolResult struct { + Content []content `json:"content"` + IsError bool `json:"isError,omitempty"` + Meta *resultMeta `json:"_meta,omitempty"` + } + content struct { + Type string `json:"type"` // text or image + Text string `json:"text,omitempty"` + Data string `json:"data,omitempty"` // base64 + MimeType string `json:"mimeType,omitempty"` + } + resultMeta struct { + Watch *watch `json:"io.github.robdevops.signalbot/watch,omitempty"` + React string `json:"io.github.robdevops.signalbot/react,omitempty"` + } + watch struct { + ID string `json:"id"` + Pattern string `json:"pattern"` + Until string `json:"until"` // RFC 3339 + Tool string `json:"tool"` + Guard string `json:"guard,omitempty"` + } + + resourceTemplate struct { + URITemplate string `json:"uriTemplate"` + Name string `json:"name"` + MimeType string `json:"mimeType"` + } + readResult struct { + Contents []resourceContent `json:"contents"` + } + resourceContent struct { + URI string `json:"uri"` + MimeType string `json:"mimeType"` + Text string `json:"text"` + } + uriParams struct { + URI string `json:"uri"` + } +) + +// callParams are tools/call's params, with the context signalbot puts in +// _meta when the bot itself makes the call. +type callParams struct { + Name string `json:"name"` + Arguments json.RawMessage `json:"arguments"` + Meta struct { + Context *callContext `json:"io.github.robdevops.signalbot/context"` + } `json:"_meta"` +} + +// callContext is the message a call came from: pseudonyms for its chat and +// sender, and the bot's receive times in whole seconds. +type callContext struct { + Chat string `json:"chat"` + Sender string `json:"sender"` + Ref string `json:"ref"` + Addressed bool `json:"addressed"` + Group bool `json:"group"` + Sent int64 `json:"sent"` + Edited int64 `json:"edited"` +} + +// methods are the MCP methods GeoGuess answers. +func (s *server) methods() map[string]handler { + return map[string]handler{ + "initialize": func(context.Context, json.RawMessage) (any, error) { + r := initializeResult{ProtocolVersion: protocolVersion, ServerInfo: serverInfo{Name: "geoguess", Title: "GeoGuess", Version: "1"}} + r.Capabilities.Experimental = map[string]addonCapability{vendor + "addon": {Version: 1}} + r.Capabilities.Resources.Subscribe = true + return r, nil + }, + "ping": func(context.Context, json.RawMessage) (any, error) { return struct{}{}, nil }, + "tools/list": func(context.Context, json.RawMessage) (any, error) { + return struct { + Tools []tool `json:"tools"` + }{tools}, nil + }, + "tools/call": func(ctx context.Context, raw json.RawMessage) (any, error) { + var p callParams + if err := params(raw, &p); err != nil { + return nil, err + } + return s.call(ctx, p) + }, + "resources/list": func(context.Context, json.RawMessage) (any, error) { + return struct { + Resources []struct{} `json:"resources"` + }{[]struct{}{}}, nil + }, + "resources/templates/list": func(context.Context, json.RawMessage) (any, error) { + return struct { + Templates []resourceTemplate `json:"resourceTemplates"` + }{[]resourceTemplate{{URITemplate: outboxURI + "/{cursor}", Name: "outbox", MimeType: "application/json"}}}, nil + }, + "resources/subscribe": func(_ context.Context, raw json.RawMessage) (any, error) { return s.subscribe(raw, true) }, + "resources/unsubscribe": func(_ context.Context, raw json.RawMessage) (any, error) { return s.subscribe(raw, false) }, + "resources/read": func(_ context.Context, raw json.RawMessage) (any, error) { + var p uriParams + if err := params(raw, &p); err != nil { + return nil, err + } + cursor, ok := strings.CutPrefix(p.URI, outboxURI+"/") + if !ok { + return nil, &rpcError{codeNotFound, "resource not found"} + } + page, err := json.Marshal(s.readOutbox(cursor)) + if err != nil { + return nil, err + } + return readResult{[]resourceContent{{URI: p.URI, MimeType: "application/json", Text: string(page)}}}, nil + }, + } +} + +// tools are GeoGuess's tools, both for the bot alone: neither is offered to +// the model. +var tools = []tool{ + { + Name: "geo", + Description: "The /geo command: start, end or skip this chat's round, or show its scores.", + InputSchema: schema{Type: "object", Properties: map[string]schema{"args": {Type: "string"}}}, + Meta: visibility{[]string{"bot"}}, + }, + { + Name: "geo_guess", + Description: "Records the location in one chat message as a guess in this chat's round.", + InputSchema: schema{Type: "object", Properties: map[string]schema{"text": {Type: "string"}}, Required: []string{"text"}}, + Meta: visibility{[]string{"bot"}}, + }, +} + +// subscribe records whether the client wants to hear of the outbox. +func (s *server) subscribe(raw json.RawMessage, on bool) (any, error) { + var p uriParams + if err := params(raw, &p); err != nil { + return nil, err + } + if _, ok := strings.CutPrefix(p.URI, outboxURI); !ok { + return nil, &rpcError{codeNotFound, "resource not found"} + } + s.mu.Lock() + s.subscribed = on + pending := len(s.outbox) > 0 + s.mu.Unlock() + if on && pending { + s.poke() + } + return struct{}{}, nil +} + +// notifier tells a subscribed client each time the outbox gains ops, on +// its own goroutine, as a write can wait on a client that is busy. +func (s *server) notifier(ctx context.Context) { + for { + select { + case <-ctx.Done(): + return + case <-s.dirty: + } + s.mu.Lock() + on := s.subscribed + s.mu.Unlock() + if on { + s.out.send(notification{JSONRPC: "2.0", Method: "notifications/resources/updated", Params: uriParams{outboxURI}}) + } + } +} + +// poke marks the outbox changed, without waiting. +func (s *server) poke() { + select { + case s.dirty <- struct{}{}: + default: + } +} diff --git a/cmd/geoguess/server.go b/cmd/geoguess/server.go new file mode 100644 index 0000000..456a0ac --- /dev/null +++ b/cmd/geoguess/server.go @@ -0,0 +1,307 @@ +package main + +import ( + "crypto/rand" + "encoding/hex" + "encoding/json" + "log" + "slices" + "strconv" + "strings" + "sync" + "time" + + "github.com/robdevops/signalbot/cmd/geoguess/geo" + "github.com/robdevops/signalbot/internal/kit/state" +) + +// server is GeoGuess: the chats' rounds, their scores, the outbox the bot +// reads, and the photos kept ready. +type server struct { + cfg config + clock clock + photos finder + log *log.Logger + doc *state.Doc + nonce string // this run's, in each outbox cursor and op ID + photoWait time.Duration // how long /geo waits for a photo when none is ready + + out *wire + dirty chan struct{} // the outbox gained ops: tell the client + wake chan struct{} // the prefetcher has work + + mu sync.Mutex + rounds map[string]*round // by chat + timers map[string]stopper // each round's, by chat + used []string // the last maxUsed photos' keys, oldest first + scores map[string][]score // by chat, the last scoreDays days + outbox []held // ops the bot hasn't read past, oldest first + seq int64 // the last op's sequence number + subscribed bool // the client wants to hear of the outbox + buffer []geo.Photo // photos ready for a round, oldest first + wants map[string]bool // regions a /geo asked for that the buffer lacks + changed chan struct{} // closed when the buffer gains a photo + seeds map[string]*geo.Seeds + + saveMu sync.Mutex // one save at a time, so the last one written is the newest +} + +// round is one chat's round. Its guesses are distances only: where anyone +// guessed is never kept. +type round struct { + ID string `json:"id"` // also the watch's + Chat string `json:"chat"` + Starter string `json:"starter"` // who may end or skip it + Started time.Time `json:"started"` + Deadline time.Time `json:"deadline"` + Answer geo.Point `json:"answer"` + Place string `json:"place"` + Credit credit `json:"credit"` + Guesses map[string]guess `json:"guesses"` // by player +} + +// guess is how far one player's last guess was from the answer, and when +// it was sent. +type guess struct { + Km float64 `json:"km"` + At time.Time `json:"at"` +} + +// credit names a photo's author, source and licence, with a link to it. +type credit struct { + Creator string `json:"creator"` + Source string `json:"source"` + Licence string `json:"licence"` + Link string `json:"link"` +} + +// score is a player's points from one round. +type score struct { + User string `json:"user"` + Points int `json:"points"` + At time.Time `json:"at"` +} + +// saved is geo.json. +type saved struct { + Rounds []*round `json:"rounds"` + Used []string `json:"used"` + Scores map[string][]score `json:"scores"` + Outbox []held `json:"outbox"` +} + +// The state's limits: photos remembered as used, days of scores, and the +// slack on a round's end. +const ( + maxUsed = 1000 + scoreDays = 7 + // settle is how long after its deadline a round is revealed, so a guess + // sent in time that waited in the bot's queue still counts. + settle = 3 * time.Second + // watchSlack is how long after the deadline the bot keeps the watch, so a + // late guess still stays out of the chat's history. + watchSlack = 5 * time.Second +) + +// newServer loads the state saved in cfg.StateDir, re-arms its rounds' +// timers and reveals at once those whose time passed while it was down. +func newServer(cfg config, clk clock, photos finder, logger *log.Logger) (*server, error) { + s := &server{ + cfg: cfg, clock: clk, photos: photos, log: logger, + doc: state.Open(cfg.StateDir, "geo"), + nonce: randomID(4), + photoWait: 10 * time.Second, + dirty: make(chan struct{}, 1), + wake: make(chan struct{}, 1), + rounds: map[string]*round{}, + timers: map[string]stopper{}, + scores: map[string][]score{}, + wants: map[string]bool{}, + changed: make(chan struct{}), + seeds: map[string]*geo.Seeds{}, + } + var st saved + if _, err := s.doc.Load(&st); err != nil { + return nil, err + } + s.used = st.Used + if st.Scores != nil { + s.scores = st.Scores + } + for _, h := range st.Outbox { + s.seq++ + h.seq = s.seq + s.outbox = append(s.outbox, h) + } + s.mu.Lock() + revealed := 0 + for _, r := range st.Rounds { + if r == nil || s.rounds[r.Chat] != nil { + continue + } + if r.Guesses == nil { + r.Guesses = map[string]guess{} + } + s.rounds[r.Chat] = r + if !s.clock.Now().Before(r.Deadline.Add(settle)) { + s.timeUpLocked(r) + revealed++ + } else { + s.arm(r) + } + } + s.mu.Unlock() + s.log.Printf("started: %d rounds open, %d revealed late, %d ops held", len(s.rounds), revealed, len(s.outbox)) + if revealed > 0 { + s.poke() + s.save() + } + return s, nil +} + +// save writes geo.json, logging a failure; the state stays in memory, and +// the next change tries again. +func (s *server) save() { + s.saveMu.Lock() + defer s.saveMu.Unlock() + s.mu.Lock() + st := saved{Used: s.used, Scores: s.scores, Outbox: s.outbox, Rounds: make([]*round, 0, len(s.rounds))} + for _, r := range s.rounds { + st.Rounds = append(st.Rounds, r) + } + slices.SortFunc(st.Rounds, func(a, b *round) int { return strings.Compare(a.Chat, b.Chat) }) + data, err := json.Marshal(st) + s.mu.Unlock() + if err == nil { + err = s.doc.Save(json.RawMessage(data)) + } + if err != nil { + s.log.Printf("saving failed: %v", err) + } +} + +// markUsed remembers a photo's key, forgetting the oldest past maxUsed. +// s.mu is held. +func (s *server) markUsed(key string) { + s.used = append(s.used, key) + if over := len(s.used) - maxUsed; over > 0 { + s.used = slices.Delete(s.used, 0, over) + } +} + +// isUsed reports whether a photo's key is among those used recently. +func (s *server) isUsed(key string) bool { + s.mu.Lock() + defer s.mu.Unlock() + return slices.Contains(s.used, key) +} + +// randomID is n random bytes in hex. +func randomID(n int) string { + b := make([]byte, n) + rand.Read(b) + return hex.EncodeToString(b) +} + +// validID reports whether id is one of signalbot's pseudonyms with prefix +// (c_ or u_), so it can go into a {u_…} placeholder safely. +func validID(id, prefix string) bool { + rest, ok := strings.CutPrefix(id, prefix) + if !ok || rest == "" || len(rest) > 100 { + return false + } + for _, c := range rest { + if !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' || c == '_' || c == '-') { + return false + } + } + return true +} + +// held is an op waiting for the bot to read past it. +type held struct { + Op op `json:"op"` + Queued time.Time `json:"queued"` + seq int64 // this run's, which cursors count in +} + +// op is one thing the bot is asked to do: post in a chat, or end a watch. +type op struct { + ID string `json:"id"` + Op string `json:"op"` // post or unwatch + Chat string `json:"chat"` + Text string `json:"text,omitempty"` + Watch string `json:"watch,omitempty"` +} + +// outboxPage is what reading the outbox returns. +type outboxPage struct { + Cursor string `json:"cursor"` + More bool `json:"more"` + Ops []op `json:"ops"` +} + +// The outbox's limits: how long an op unread is kept, and the most a page +// holds, well under the 4 MiB line signalbot reads. +const ( + keepOps = time.Hour + pageSize = 3 << 20 +) + +// queue adds an op to the outbox. s.mu is held; the caller pokes the +// client and saves once it is released. +func (s *server) queue(o op) { + s.seq++ + o.ID = s.nonce + "." + strconv.FormatInt(s.seq, 10) + s.outbox = append(s.outbox, held{Op: o, Queued: s.clock.Now(), seq: s.seq}) +} + +// readOutbox is the page after cursor. A cursor of this run lets go of the +// ops up to it, which the bot has read; any other, such as one from before +// a restart, gets everything still held. +func (s *server) readOutbox(cursor string) outboxPage { + s.mu.Lock() + after, known := s.cursor(cursor) + now := s.clock.Now() + n := len(s.outbox) + s.outbox = slices.DeleteFunc(s.outbox, func(h held) bool { + return known && h.seq <= after || now.Sub(h.Queued) > keepOps + }) + changed := len(s.outbox) != n + last := s.seq + if known { + last = after + } + page := outboxPage{Ops: []op{}} + size := 0 + for _, h := range s.outbox { + data, _ := json.Marshal(h.Op) + if len(page.Ops) > 0 && size+len(data) > pageSize { + page.More = true + break + } + size += len(data) + page.Ops = append(page.Ops, h.Op) + last = h.seq + } + page.Cursor = s.nonce + "." + strconv.FormatInt(last, 10) + s.mu.Unlock() + if changed { + s.save() + } + return page +} + +// cursor reads a cursor of this run: the sequence number read up to. +// s.mu is held. +func (s *server) cursor(c string) (int64, bool) { + nonce, seq, ok := strings.Cut(c, ".") + if !ok || nonce != s.nonce { + return 0, false + } + n, err := strconv.ParseInt(seq, 10, 64) + if err != nil || n < 0 || n > s.seq { + return 0, false + } + return n, true +} diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 153035b..a022749 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -26,9 +26,10 @@ Every setting, read from the environment (`/etc/signalbot.env` in the install). | `INTRO` | built-in sentence | Overrides the self-introduction; `{name}`, `{model}` (without any OpenRouter `provider/` prefix) and `{tools}` (the names of the tools, or `none`) are substituted | | `MAX_CONCURRENCY` | `32` | Conversations in flight at once; messages beyond this are dropped, with a warning | | `MCP_CONFIG` | empty | Path of an MCP servers file; see [MCP connectors](FILES_LINKS_TOOLS_MCP.md#mcp-connectors) | -| `STATE_DIRECTORY` | working directory | Where features save their state, one file each, such as `/schedule`'s `schedules.json` (and the core its `budget.json`); the bot won't start if a feature that saves can't list and write it. Set by systemd's `StateDirectory=signalbot` (`/var/lib/private/signalbot`) and by the Docker image (`/data`, which must be writable by user 65532) | +| `<SERVER>_…` | none | An [addon's](FILES_LINKS_TOOLS_MCP.md#addons) own settings, read by the addon, not the bot. An addon server gets every variable that starts with its name in capitals, anything but letters and digits as `_`, then `_` (the server `geo` gets `GEO_STATE_DIR` and the rest), plus `PATH`, `HOME` and, if set, `TZ`, `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, `SSL_CERT_FILE` and `SSL_CERT_DIR`, and nothing else, so none of the other settings above reach it. A server whose prefix one of the settings above starts with (such as `model` or `mcp`) is a config error. Each addon documents its own, such as [GeoGuess's](../cmd/geoguess/README.md#settings) | +| `STATE_DIRECTORY` | working directory | Where features save their state, one file each, such as `/schedule`'s `schedules.json`, `mcp.json` when an MCP server is an [addon](FILES_LINKS_TOOLS_MCP.md#addons) (and the core its `budget.json`); the bot won't start if a feature that saves can't list and write it. Set by systemd's `StateDirectory=signalbot` (`/var/lib/private/signalbot`) and by the Docker image (`/data`, which must be writable by user 65532) | | `TOOL_LINGER_ROUNDS` | `2` | Replies a keyword-gated tool group (charts, an MCP server with `keywords`) stays offered after the last one that matched its keywords or used its tools; `0` offers it only on a matching message. Any use or match starts the count again, so a run of follow-ups keeps it. Capped at `HISTORY_MAX`. See [How tools are offered](FILES_LINKS_TOOLS_MCP.md#how-tools-are-offered) | -| `TZ` | `UTC` in Docker, the host's under systemd | Time zone for `/schedule` times without an offset and for `DARKMODE` hours, e.g. `Australia/Sydney` | +| `TZ` | `UTC` in Docker, the host's under systemd | Time zone for `/schedule` times without an offset and for `DARKMODE` hours, e.g. `Australia/Sydney`; addons get it too, for the times they write (GeoGuess's round deadline) | A number that can't be read is warned about at startup, and the default used. `OPENROUTER_API_KEY` is now `MODEL_API_KEY`, and `REASONING` and `SYSTEM_PROMPT` are now `MODEL_REASONING` and `MODEL_SYSTEM_PROMPT`; the old names are ignored, with a warning at startup. `LOG_LEVEL` is gone: every level is always written (see [Logs](../TECHNICAL.md#logs)). diff --git a/docs/FILES_LINKS_TOOLS_MCP.md b/docs/FILES_LINKS_TOOLS_MCP.md index 7cff73c..58cda10 100644 --- a/docs/FILES_LINKS_TOOLS_MCP.md +++ b/docs/FILES_LINKS_TOOLS_MCP.md @@ -5,6 +5,7 @@ - [Images](#images) - [How tools are offered](#how-tools-are-offered) - [MCP connectors](#mcp-connectors) +- [Addons](#addons) ## Files @@ -38,7 +39,7 @@ The default of 2 is meant to cover a short aside ("thanks!", "what's AMD's ticke ## MCP connectors -The model can call tools from [MCP](https://modelcontextprotocol.io) servers, remote (`url`) or local (`command`). Anyone who can address the bot can make it call them, so choose what each server offers: `allowed_tools` offers only the tools listed, `blocked_tools` offers all but those, and without either every tool the server has is offered. Put the servers in a file, for example `/etc/signalbot-mcp.json`. [`examples/signalbot-mcp.json`](../examples/signalbot-mcp.json) is this one, to start from: `sudo install -m 600 examples/signalbot-mcp.json /etc/signalbot-mcp.json`, then `sudoedit /etc/signalbot-mcp.json`. +The model can call tools from [MCP](https://modelcontextprotocol.io) servers, remote (`url`) or local (`command`). Anyone who can address the bot can make it call them (for [addons](#addons), their `chats` and permissions are the gate), so choose what each server offers: `allowed_tools` offers only the tools listed, `blocked_tools` offers all but those, and without either every tool the server has is offered. Put the servers in a file, for example `/etc/signalbot-mcp.json`. [`examples/signalbot-mcp.json`](../examples/signalbot-mcp.json) is this one, to start from: `sudo install -m 600 examples/signalbot-mcp.json /etc/signalbot-mcp.json`, then `sudoedit /etc/signalbot-mcp.json`. ```json {"mcpServers": { @@ -53,6 +54,11 @@ The model can call tools from [MCP](https://modelcontextprotocol.io) servers, re "alerts": {"tool": "get_alerts"} } }, + "geo": { + "command": "/addons/geoguess", + "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m"}}, + "addon": {"chats": ["all"], "dms": false, "post": true, "react": true, "watch": true, "watch_max": "1h"} + }, "files": { "command": "uvx", "args": ["some-mcp-server"], @@ -71,7 +77,8 @@ The model can call tools from [MCP](https://modelcontextprotocol.io) servers, re | `allowed_tools` / `blocked_tools` | offer only these tools, or every tool but these (one or the other, not both) | | `instructions` | a line added to the system prompt while the server's tools are offered (see below) | | `keywords` | offer the server's tools only when a message has one of these words (see below). A server without them is offered with every message, except one whose page or file the model is shown, so what a document says can't call its tools | -| `chat_commands` | optional slash-command shortcuts to a tool (you can always just ask): `tool` names it, `require_arg` makes a bare command get a usage reply, and `example` adds one to it | +| `chat_commands` | optional slash-command shortcuts to a tool (you can always just ask): `tool` names it, `require_arg` makes a bare command get a usage reply, and `example` adds one to it; for an addon, `direct` has the bot call the tool itself, without the model (see [Addons](#addons)) | +| `addon` | makes a local server an addon, and says where it may act and what it may do (see [Addons](#addons)) | | `disabled` | leave the server out without deleting it | **You don't need a command to use the tools: just ask.** For example, `@signalbot what's the weather in Sydney this weekend?` The model sees every tool that's offered and decides when to call one. Without `keywords` a server's tools are always offered; with them, the message needs one of its words, such as `weather` or `forecast` above. Gating tools this way saves tokens. @@ -86,9 +93,55 @@ Two optional fields shape how a server's tools are offered: A server that can't be reached at startup is logged and left out. A config error stops the bot with the file's path and the server's name: a setting it doesn't know (such as `allowedTools` for `allowed_tools`), with the settings it could be; both `allowed_tools` and `blocked_tools`; or a tool named in either list that the server doesn't have, with the list it was in and the server's tools, so a typo can't leave a blocked tool offered. Keys other MCP clients write and the bot has no use for (`type`, `transport`, `timeout`, `alwaysAllow`, `autoApprove`, `description`) are ignored, so an entry pasted from another client starts. A tool call that takes over 30 seconds tells the model it didn't answer in time, so it can try a narrower request. Local servers get only `PATH`, `HOME` and their `env`, never the bot's own environment. - **systemd:** keep the file root-only, uncomment the `LoadCredential=` and `Environment=MCP_CONFIG=` lines in `signalbot.service`, and restart. systemd hands the file to the service alone. -- **Docker:** uncomment the MCP volume and the `environment:` lines in `compose.yaml`, then `sudo docker compose up -d`. The image has no shell or runtimes, so only remote servers (`url`) work. +- **Docker:** uncomment the MCP volume and the `environment:` lines in `compose.yaml`, then `sudo docker compose up -d`. The image has no shell or runtimes, so only remote servers (`url`) and static binaries, such as an addon (below), work. - **Local servers under systemd** usually need the hardening loosened with a drop-in (`sudo systemctl edit signalbot`), for example `MemoryDenyWriteExecute=no` for Node, and `CacheDirectory=signalbot` with `Environment=HOME=/var/cache/signalbot` for npx or uvx caches. +## Addons + +An addon is a local MCP server that does more than offer tools: it answers its own commands without the model, reads the messages it asks for, and posts and reacts when it likes. [GeoGuess](../cmd/geoguess/README.md), a photo-guessing game, is one. It is still an ordinary MCP server (protocol 2025-06-18 over stdio), which also speaks signalbot's small extension, under keys starting `io.github.robdevops.signalbot/`. A server is an addon when it has an `addon` block in the MCP file and says it speaks the extension when the bot connects; one with the block that doesn't runs as a plain server, with a warning. Addons run even with [no model](MODELS.md#no-model). + +**An addon is trusted code.** It runs as the bot's user, inside the same systemd or Docker sandbox, and could read what that user can. The bot gives it as little as it can (below), but that guards against bugs and leaks, not a hostile program: install only addons you would let run as the bot. + +```jsonc +"geo": { + "command": "/addons/geoguess", + "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m"}}, + "addon": { + "chats": ["<group ID>"], + "dms": false, + "post": true, "react": true, "watch": true, + "watch_max": "1h", + "names": false, "global_ids": false, + "rate": {"per_minute": 20, "burst": 5} + } +} +``` + +| Key in `addon` | What it does | +|---|---| +| `chats` | the groups it works in, by ID exactly as Signal or Telegram shows it (a Telegram topic counts as its group), or `["all"]`. A name is an error: names can be changed, IDs can't | +| `dms` | it also works in DMs with people allowed to DM the bot | +| `post` | it may post on its own | +| `react` | it may react to messages | +| `watch` | it may ask to read chosen messages, for a while (below) | +| `watch_max` | the longest a watch may last: 1s to 24h, default 1h | +| `names` | each call it gets carries the sender's display name. Off, it gets none | +| `global_ids` | a person has the same ID in every chat. Off, each chat gives them a different one, so the addon can't follow someone between groups | +| `rate` | its posts and reactions a minute in each chat (`per_minute`, default 20), with bursts of `burst` (default 5) | + +Each permission is off unless set. For an addon, `chats`, `dms` and these permissions are the gate: anyone in an allowed chat can use its commands, and nothing it does reaches another chat. + +**What an addon sees.** Never a phone number, account ID or group ID: chats and people are pseudonyms the bot makes with a secret kept in `mcp.json` in the state directory, different for each addon. It sees a command's text after the command, the messages its watches match, and, with `names`, display names. To name someone in what it says, it writes their pseudonym as `{u_…}`, and the bot puts in the name it last saw them use there, as an @mention, or "someone". + +- **Direct commands.** `"direct": true` on a chat command has the bot call the addon's tool itself, with the text after the command, and send what it answers (text, and up to 2 pictures) without the model. The tool must be marked for the bot, and is then never offered to the model. A call has 15 seconds, and at most 2 run at once per addon; a third is told the addon is busy. When it fails, the chat gets a short line ("GeoGuess couldn't do that just now."), never the addon's own error text. An addon with no tool for the model has its commands named in the prompt's list of what the bot has, so the model can point people to them. +- **Hidden tools.** A tool whose `_meta` says it is for the bot alone (`io.github.robdevops.signalbot/visibility` without `"model"`, or MCP Apps' `ui.visibility` without `"model"`) is never offered to the model or listed as one of its tools, so tools that read chat text stay out of its hands. +- **Watches.** A direct command's answer can ask for a watch on its chat: a pattern, such as map links, until a time at most `watch_max` away. While it lasts, a message there that matches goes to the addon instead: it isn't answered, isn't sent to the model, and isn't kept in history, even as group context; so does an edit of it later. The addon may react to it, so people see it was counted. A pattern that would match ordinary chat ("lol", "see you at 5", a news link, …) is refused, so a watch can't become a feed of everything said; at most 8 run in a chat at once. While a watch lasts, a reply to the command's pictures that asks the bot gets the addon's set answer (GeoGuess's "No hints during a round 😉"), not the model's. +- **Outbox.** An addon posts when it likes by queueing posts, reactions and the end of a watch in its outbox, an MCP resource the bot subscribes to (`signalbot://outbox`), and saying it changed; the bot reads it at once. It may post or react only in a chat where it was used, by a command or a watch, in the last 24 hours, and only within `rate`. Its posts go through the chat's queue like any message, never more than one at a time, and history keeps them as the bot's, labelled with the addon's name (`[GeoGuess] …`), so what an addon writes never poses as a person. +- **Settings.** An addon has no `env` block. It gets `PATH`, `HOME`, the bot's time zone (`TZ`) and proxy settings (`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, and `SSL_CERT_FILE` or `SSL_CERT_DIR` for a custom CA) if set, and every variable in the bot's environment (`/etc/signalbot.env`) that starts with its server's name in capitals, anything but letters and digits as `_`, then `_`: the server `geo` gets `GEO_STATE_DIR`, `GEO_MAPILLARY_TOKEN` and so on, and never the bot's own keys. A name whose prefix starts one of the bot's settings (such as `model`, `signal` or `mcp`) is a config error. If an addon keeps files, give it a directory under its prefix and create it, writable by the bot's user. +- **Logs.** The bot logs an addon's commands, calls and drops by name, outcome, time and size, never what was said. An addon's stderr is counted ("addon geo wrote 3 lines (210 bytes) to stderr", at most once a minute and once more when it exits), never logged, since it may echo a message. To debug an addon, run it on its own with stderr going to your own file. +- **State.** The bot keeps an addon's watches, the messages they took, the chats it may post in and how far it has read its outbox in `mcp.json`, so a restart of either doesn't lose a round. See [PRIVACY.md](../PRIVACY.md#addons). +- **Docker.** The image has no shell or runtimes, so an addon must be a static binary (`CGO_ENABLED=0 go build`), mounted read-only, such as `- /opt/signalbot-addons:/addons:ro` in `compose.yaml`. The state directory must be writable by user 65532 for `mcp.json`, and so must any directory the addon keeps files in. Addons share the container's or unit's memory and process limits, so raise `mem_limit` or `MemoryMax` to suit; `GOMEMLIMIT` isn't passed on, so a Go addon takes its limit from its own setting (GeoGuess: `GEO_MEMLIMIT`). + --- [Back to README.md](../README.md) diff --git a/docs/SCENARIOS.md b/docs/SCENARIOS.md index d3aa8cf..d1cdcfe 100644 --- a/docs/SCENARIOS.md +++ b/docs/SCENARIOS.md @@ -7,7 +7,7 @@ socket, then what the bot sends back, what a fake model API receives, and the lo All of them are at the module root, in package main: - `scenario_test.go`: the scenarios and the two golden prompt tests. They use only the harness. -- `scenario_fakes_test.go`: the fakes and the harness API (fake signal-cli, a fake model API that is OpenRouter's or another provider's, two fake MCP servers plus an optional third whose tools fail, the captured log). It names nothing in the bot's code. +- `scenario_fakes_test.go`: the fakes and the harness API (fake signal-cli, a fake model API that is OpenRouter's or another provider's, two fake MCP servers plus an optional third whose tools fail, an optional addon, "game", that the bot runs as a stdio subprocess of the test binary (`TestScenarioAddonProcess`) speaking signalbot's addon extension, the captured log). It names nothing in the bot's code. - `scenario_start_test.go`: `startBot`, which wires one version of the bot to the fakes. It is the only file that names the bot's code, and the only one rewritten for the new core. - `testdata/prompt_full.txt` and `testdata/prompt_notools.txt`: the scenarios' golden system prompts. `go test . -run Golden -update` rewrites them. `testdata/prompt_nofeatures.txt` is the core's own, checked by `internal/bot` with no features. diff --git a/docs/architecture.svg b/docs/architecture.svg index e2324b3..2c9336c 100644 --- a/docs/architecture.svg +++ b/docs/architecture.svg @@ -1 +1 @@ -<svg id="g1069" width="100%" xmlns="http://www.w3.org/2000/svg" class="flowchart" style="max-width: 3496.15380859375px;" viewBox="4 4 3496.15380859375 1175" role="graphics-document document" aria-roledescription="flowchart-v2"><style>#g1069{font-family:Helvetica,Arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#g1069 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#g1069 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#g1069 .error-icon{fill:#552222;}#g1069 .error-text{fill:#552222;stroke:#552222;}#g1069 .edge-thickness-normal{stroke-width:1px;}#g1069 .edge-thickness-thick{stroke-width:3.5px;}#g1069 .edge-pattern-solid{stroke-dasharray:0;}#g1069 .edge-thickness-invisible{stroke-width:0;fill:none;}#g1069 .edge-pattern-dashed{stroke-dasharray:3;}#g1069 .edge-pattern-dotted{stroke-dasharray:2;}#g1069 .marker{fill:#333333;stroke:#333333;}#g1069 .marker.cross{stroke:#333333;}#g1069 svg{font-family:Helvetica,Arial,sans-serif;font-size:16px;}#g1069 p{margin:0;}#g1069 .label{font-family:Helvetica,Arial,sans-serif;color:#333;}#g1069 .cluster-label text{fill:#333;}#g1069 .cluster-label span{color:#333;}#g1069 .cluster-label span p{background-color:transparent;}#g1069 .label text,#g1069 span{fill:#333;color:#333;}#g1069 .node rect,#g1069 .node circle,#g1069 .node ellipse,#g1069 .node polygon,#g1069 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#g1069 .rough-node .label text,#g1069 .node .label text,#g1069 .image-shape .label,#g1069 .icon-shape .label{text-anchor:middle;}#g1069 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#g1069 .rough-node .label,#g1069 .node .label,#g1069 .image-shape .label,#g1069 .icon-shape .label{text-align:center;}#g1069 .node.clickable{cursor:pointer;}#g1069 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#g1069 .arrowheadPath{fill:#333333;}#g1069 .edgePaths .path{stroke:#333333;stroke-width:1px;}#g1069 .flowchart-link{stroke:#333333;fill:none;}#g1069 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#g1069 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#g1069 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#g1069 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#g1069 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#g1069 .cluster text{fill:#333;}#g1069 .cluster span{color:#333;}#g1069 .node .collapsed-indicator{fill:#aaaa33;stroke:none;opacity:0.6;}#g1069 .node .collapsed-separator{stroke:#aaaa33;stroke-width:0.75px;}#g1069 div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:Helvetica,Arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#g1069 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#g1069 rect.text{fill:none;stroke-width:0;}#g1069 .icon-shape,#g1069 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#g1069 .icon-shape p,#g1069 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#g1069 .icon-shape .label rect,#g1069 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#g1069 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#g1069 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#g1069 .node .neo-node{stroke:#9370DB;}#g1069 [data-look="neo"].node rect,#g1069 [data-look="neo"].cluster rect,#g1069 [data-look="neo"].node polygon{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1069 [data-look="neo"].swimlane.cluster rect{filter:none;}#g1069 [data-look="neo"].node path{stroke:#9370DB;stroke-width:1px;}#g1069 [data-look="neo"].node .outer-path{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1069 [data-look="neo"].node .neo-line path{stroke:#9370DB;filter:none;}#g1069 [data-look="neo"].node circle{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1069 [data-look="neo"].node circle .state-start{fill:#000000;}#g1069 [data-look="neo"].icon-shape .icon{fill:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1069 [data-look="neo"].icon-shape .icon-neo path{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1069 :root{--mermaid-font-family:Helvetica,Arial,sans-serif;}#g1069 .ext rect{fill:rgb(243, 244, 246)!important;stroke:rgb(107, 114, 128)!important;color:rgb(17, 17, 17)!important;}#g1069 .ext polygon{fill:rgb(243, 244, 246)!important;stroke:rgb(107, 114, 128)!important;color:rgb(17, 17, 17)!important;}#g1069 .ext ellipse{fill:rgb(243, 244, 246)!important;stroke:rgb(107, 114, 128)!important;color:rgb(17, 17, 17)!important;}#g1069 .ext circle{fill:rgb(243, 244, 246)!important;stroke:rgb(107, 114, 128)!important;color:rgb(17, 17, 17)!important;}#g1069 .ext path{fill:rgb(243, 244, 246)!important;stroke:rgb(107, 114, 128)!important;color:rgb(17, 17, 17)!important;}#g1069 .ext tspan{fill:rgb(17, 17, 17)!important;}</style><g><marker id="g1069_flowchart-v2-pointEnd" class="marker flowchart-v2" viewBox="0 0 10 10" refX="5" refY="5" markerUnits="userSpaceOnUse" markerWidth="8" markerHeight="8" orient="auto"><path d="M 0 0 L 10 5 L 0 10 z" class="arrowMarkerPath" style="stroke-width: 1; stroke-dasharray: 1, 0;"></path></marker><marker id="g1069_flowchart-v2-pointStart" class="marker flowchart-v2" viewBox="0 0 10 10" refX="4.5" refY="5" markerUnits="userSpaceOnUse" markerWidth="8" markerHeight="8" orient="auto"><path d="M 0 5 L 10 10 L 10 0 z" class="arrowMarkerPath" style="stroke-width: 1; stroke-dasharray: 1, 0;"></path></marker><marker id="g1069_flowchart-v2-pointEnd-margin" class="marker flowchart-v2" viewBox="0 0 11.5 14" refX="11.5" refY="7" markerUnits="userSpaceOnUse" markerWidth="10.5" markerHeight="14" orient="auto"><path d="M 0 0 L 11.5 7 L 0 14 z" class="arrowMarkerPath" style="stroke-width: 0; stroke-dasharray: 1, 0;"></path></marker><marker id="g1069_flowchart-v2-pointStart-margin" class="marker flowchart-v2" viewBox="0 0 11.5 14" refX="1" refY="7" markerUnits="userSpaceOnUse" markerWidth="11.5" markerHeight="14" orient="auto"><polygon points="0,7 11.5,14 11.5,0" class="arrowMarkerPath" style="stroke-width: 0; stroke-dasharray: 1, 0;"></polygon></marker><marker id="g1069_flowchart-v2-circleEnd" class="marker flowchart-v2" viewBox="0 0 10 10" refX="11" refY="5" markerUnits="userSpaceOnUse" markerWidth="11" markerHeight="11" orient="auto"><circle cx="5" cy="5" r="5" class="arrowMarkerPath" style="stroke-width: 1; stroke-dasharray: 1, 0;"></circle></marker><marker id="g1069_flowchart-v2-circleStart" class="marker flowchart-v2" viewBox="0 0 10 10" refX="-1" refY="5" markerUnits="userSpaceOnUse" markerWidth="11" markerHeight="11" orient="auto"><circle cx="5" cy="5" r="5" class="arrowMarkerPath" style="stroke-width: 1; stroke-dasharray: 1, 0;"></circle></marker><marker id="g1069_flowchart-v2-circleEnd-margin" class="marker flowchart-v2" viewBox="0 0 10 10" refY="5" refX="12.25" markerUnits="userSpaceOnUse" markerWidth="14" markerHeight="14" orient="auto"><circle cx="5" cy="5" r="5" class="arrowMarkerPath" style="stroke-width: 0; stroke-dasharray: 1, 0;"></circle></marker><marker id="g1069_flowchart-v2-circleStart-margin" class="marker flowchart-v2" viewBox="0 0 10 10" refX="-2" refY="5" markerUnits="userSpaceOnUse" markerWidth="14" markerHeight="14" orient="auto"><circle cx="5" cy="5" r="5" class="arrowMarkerPath" style="stroke-width: 0; stroke-dasharray: 1, 0;"></circle></marker><marker id="g1069_flowchart-v2-crossEnd" class="marker cross flowchart-v2" viewBox="0 0 11 11" refX="12" refY="5.2" markerUnits="userSpaceOnUse" markerWidth="11" markerHeight="11" orient="auto"><path d="M 1,1 l 9,9 M 10,1 l -9,9" class="arrowMarkerPath" style="stroke-width: 2; stroke-dasharray: 1, 0;"></path></marker><marker id="g1069_flowchart-v2-crossStart" class="marker cross flowchart-v2" viewBox="0 0 11 11" refX="-1" refY="5.2" markerUnits="userSpaceOnUse" markerWidth="11" markerHeight="11" orient="auto"><path d="M 1,1 l 9,9 M 10,1 l -9,9" class="arrowMarkerPath" style="stroke-width: 2; stroke-dasharray: 1, 0;"></path></marker><marker id="g1069_flowchart-v2-crossEnd-margin" class="marker cross flowchart-v2" viewBox="0 0 15 15" refX="17.7" refY="7.5" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto"><path d="M 1,1 L 14,14 M 1,14 L 14,1" class="arrowMarkerPath" style="stroke-width: 2.5;"></path></marker><marker id="g1069_flowchart-v2-crossStart-margin" class="marker cross flowchart-v2" viewBox="0 0 15 15" refX="-3.5" refY="7.5" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto"><path d="M 1,1 L 14,14 M 1,14 L 14,1" class="arrowMarkerPath" style="stroke-width: 2.5; stroke-dasharray: 1, 0;"></path></marker><g class="root"><g class="clusters"><g class="cluster" id="g1069-bin" data-look="classic"><rect style="" x="809.4679412841797" y="12" width="2124.7015686035156" height="1159.0000076293945"></rect><g class="cluster-label" transform="translate(1532.5218505859375, 12)"><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">signalbot</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> binary</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> (main.go</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> wires</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> it:</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> network_*.go</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> picks</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> the</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> network,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> features.go</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> lists</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> the</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> features)</tspan></tspan></text></g></g></g><g class="cluster" id="g1069-feats" data-look="classic"><rect style="" x="924.1554412841797" y="606.0000076293945" width="271.8125" height="553"></rect><g class="cluster-label" transform="translate(961.3351287841797, 606.0000076293945)"><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Features:</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> internal/features/*</tspan></tspan></text></g></g></g><g class="cluster" id="g1069-core" data-look="classic"><rect style="" x="1476.7335662841797" y="389.40000915527344" width="1377.9359436035156" height="342.5666618347168"></rect><g class="cluster-label" transform="translate(2148.3109130859375, 389.40000915527344)"><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Core</tspan></tspan></text></g></g></g><g class="cluster" id="g1069-net" data-look="classic"><rect style="" x="736.5148162841797" y="214.4000015258789" width="611.90625" height="361.6000061035156"></rect><g class="cluster-label" transform="translate(740.5148162841797, 214.4000015258789)"><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Chat</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> networks:</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> outside</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> the</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> core,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> only</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> main</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> imports</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> them;</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> one</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> runs,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> chosen</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> by</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> setting</tspan></tspan></text></g></g></g></g><g class="edges edgePath"><path d="M2260.5445098876953,550.9000091552734L2283.47344207583,550.9000091552734Q2290.5445098876953,550.9000091552734 2290.5445098876953,557.971076967139L2290.5445098876953,685.1289367657712Q2290.5445098876953,692.2000045776367 2297.6155776995606,692.2000045776367L2588.34844207583,692.2000045776367Q2595.4195098876953,692.2000045776367 2595.4195098876953,685.1289367657712L2595.4195098876953,671.9333381652832Q2595.4195098876953,666.4333381652832 2600.9195098876953,666.4333381652832L2606.4195098876953,666.4333381652832" id="g1069-L_bot_chats_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_bot_chats_0" data-points="W3sieCI6MjI2MC41NDQ1MDk4ODc2OTUzLCJ5Ijo1NTAuOTAwMDA5MTU1MjczNH0seyJ4IjoyMjkwLjU0NDUwOTg4NzY5NTMsInkiOjU1MC45MDAwMDkxNTUyNzM0fSx7IngiOjIyOTAuNTQ0NTA5ODg3Njk1MywieSI6NjkyLjIwMDAwNDU3NzYzNjd9LHsieCI6MjU5NS40MTk1MDk4ODc2OTUzLCJ5Ijo2OTIuMjAwMDA0NTc3NjM2N30seyJ4IjoyNTk1LjQxOTUwOTg4NzY5NTMsInkiOjY2Ni40MzMzMzgxNjUyODMyfSx7IngiOjI2MTAuNDE5NTA5ODg3Njk1MywieSI6NjY2LjQzMzMzODE2NTI4MzJ9XQ==" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M2260.5445098876953,513.4750080108643L2328.47344207583,513.4750080108643Q2335.5445098876953,513.4750080108643 2335.5445098876953,520.5460758227298L2335.5445098876953,543.8000068664551Q2335.5445098876953,549.3000068664551 2341.0445098876953,549.3000068664551L2346.5445098876953,549.3000068664551" id="g1069-L_bot_timers_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_bot_timers_0" data-points="W3sieCI6MjI2MC41NDQ1MDk4ODc2OTUzLCJ5Ijo1MTMuNDc1MDA4MDEwODY0M30seyJ4IjoyMzM1LjU0NDUwOTg4NzY5NTMsInkiOjUxMy40NzUwMDgwMTA4NjQzfSx7IngiOjIzMzUuNTQ0NTA5ODg3Njk1MywieSI6NTQ5LjMwMDAwNjg2NjQ1NTF9LHsieCI6MjM1MC41NDQ1MDk4ODc2OTUzLCJ5Ijo1NDkuMzAwMDA2ODY2NDU1MX1d" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M2260.5445098876953,488.5250072479248L2268.47344207583,488.5250072479248Q2275.5445098876953,488.5250072479248 2275.5445098876953,481.45393943605933L2275.5445098876953,476.92107582272973Q2275.5445098876953,469.85000801086426 2282.6155776995606,469.85000801086426L2346.5445098876953,469.85000801086426" id="g1069-L_bot_config_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_bot_config_0" data-points="W3sieCI6MjI2MC41NDQ1MDk4ODc2OTUzLCJ5Ijo0ODguNTI1MDA3MjQ3OTI0OH0seyJ4IjoyMjc1LjU0NDUwOTg4NzY5NTMsInkiOjQ4OC41MjUwMDcyNDc5MjQ4fSx7IngiOjIyNzUuNTQ0NTA5ODg3Njk1MywieSI6NDY5Ljg1MDAwODAxMDg2NDI2fSx7IngiOjIzNTAuNTQ0NTA5ODg3Njk1MywieSI6NDY5Ljg1MDAwODAxMDg2NDI2fV0=" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M2260.5445098876953,538.4250087738037L2298.47344207583,538.4250087738037Q2305.5445098876953,538.4250087738037 2305.5445098876953,545.4960765856692L2305.5445098876953,637.8289375287106Q2305.5445098876953,644.9000053405762 2312.6155776995606,644.9000053405762L2346.5445098876953,644.9000053405762" id="g1069-L_bot_model_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_bot_model_0" data-points="W3sieCI6MjI2MC41NDQ1MDk4ODc2OTUzLCJ5Ijo1MzguNDI1MDA4NzczODAzN30seyJ4IjoyMzA1LjU0NDUwOTg4NzY5NTMsInkiOjUzOC40MjUwMDg3NzM4MDM3fSx7IngiOjIzMDUuNTQ0NTA5ODg3Njk1MywieSI6NjQ0LjkwMDAwNTM0MDU3NjJ9LHsieCI6MjM1MC41NDQ1MDk4ODc2OTUzLCJ5Ijo2NDQuOTAwMDA1MzQwNTc2Mn1d" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M2565.4195098876953,644.9000053405762L2606.4195098876953,644.9000053405762" id="g1069-L_model_chats_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_model_chats_0" data-points="W3sieCI6MjU2NS40MTk1MDk4ODc2OTUzLCJ5Ijo2NDQuOTAwMDA1MzQwNTc2Mn0seyJ4IjoyNjEwLjQxOTUwOTg4NzY5NTMsInkiOjY0NC45MDAwMDUzNDA1NzYyfV0=" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M142.04576367738824,502.4049135664138L143.20997748078395,503.5691267559445Q144.3741912841797,504.7333399454752 146.02063780037582,504.7333399454752L330.2335662841797,504.7333399454752" id="g1069-L_users_scli_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_users_scli_0" data-points="W3sieCI6MTQ0Ljg3NDE5MTU0NzgxOTA3LCJ5Ijo1MDUuMjMzMzM5OTQ1NDc1MTd9LHsieCI6MTQ0LjM3NDE5MTI4NDE3OTcsInkiOjUwNC43MzMzMzk5NDU0NzUyfSx7IngiOjMzNC4yMzM1NjYyODQxNzk3LCJ5Ijo1MDQuNzMzMzM5OTQ1NDc1Mn1d" data-look="classic" marker-start="url(#g1069_flowchart-v2-pointStart)" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M522.7491912841797,504.7333399454752L774.8968734723142,504.7333399454752Q781.9679412841797,504.7333399454752 781.9679412841797,497.66227213360975L781.9679412841797,481.07107544126Q781.9679412841797,474.00000762939453 789.0390090960452,474.00000762939453L801.9679412841797,474.00000762939453L881.4679412841797,474.00000762939453L896.9679412841797,474.00000762939453" id="g1069-L_scli_signal_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_scli_signal_0" data-points="W3sieCI6NTE4Ljc0OTE5MTI4NDE3OTcsInkiOjUwNC43MzMzMzk5NDU0NzUyfSx7IngiOjc4MS45Njc5NDEyODQxNzk3LCJ5Ijo1MDQuNzMzMzM5OTQ1NDc1Mn0seyJ4Ijo3ODEuOTY3OTQxMjg0MTc5NywieSI6NDc0LjAwMDAwNzYyOTM5NDUzfSx7IngiOjgwMS45Njc5NDEyODQxNzk3LCJ5Ijo0NzQuMDAwMDA3NjI5Mzk0NTN9LHsieCI6ODgxLjQ2Nzk0MTI4NDE3OTcsInkiOjQ3NC4wMDAwMDc2MjkzOTQ1M30seyJ4Ijo5MDAuOTY3OTQxMjg0MTc5NywieSI6NDc0LjAwMDAwNzYyOTM5NDUzfV0=" data-look="classic" marker-start="url(#g1069_flowchart-v2-pointStart)" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1153.9679412841797,519.0000076293945L1203.4679412841797,519.0000076293945L1211.3968734723142,519.0000076293945Q1218.4679412841797,519.0000076293945 1218.4679412841797,526.0710754412601L1218.4679412841797,530.928939817529Q1218.4679412841797,538.0000076293945 1225.5390090960452,538.0000076293945L1448.2085666656494,538.0000076293945Q1454.2335662841797,538.0000076293945 1454.2335662841797,531.9750080108643L1454.2335662841797,531.9750080108643Q1454.2335662841797,525.950008392334 1460.25856590271,525.950008392334L1469.2335662841797,525.950008392334L2016.0132598876953,525.950008392334" id="g1069-L_signal_bot_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_signal_bot_0" data-points="W3sieCI6MTE1My45Njc5NDEyODQxNzk3LCJ5Ijo1MTkuMDAwMDA3NjI5Mzk0NX0seyJ4IjoxMjAzLjQ2Nzk0MTI4NDE3OTcsInkiOjUxOS4wMDAwMDc2MjkzOTQ1fSx7IngiOjEyMTguNDY3OTQxMjg0MTc5NywieSI6NTE5LjAwMDAwNzYyOTM5NDV9LHsieCI6MTIxOC40Njc5NDEyODQxNzk3LCJ5Ijo1MzguMDAwMDA3NjI5Mzk0NX0seyJ4IjoxNDU0LjIzMzU2NjI4NDE3OTcsInkiOjUzOC4wMDAwMDc2MjkzOTQ1fSx7IngiOjE0NTQuMjMzNTY2Mjg0MTc5NywieSI6NTI1Ljk1MDAwODM5MjMzNH0seyJ4IjoxNDY5LjIzMzU2NjI4NDE3OTcsInkiOjUyNS45NTAwMDgzOTIzMzR9LHsieCI6MjAyMC4wMTMyNTk4ODc2OTUzLCJ5Ijo1MjUuOTUwMDA4MzkyMzM0fV0=" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M2260.5445098876953,525.950008392334L2313.47344207583,525.950008392334Q2320.5445098876953,525.950008392334 2320.5445098876953,533.0210762041995L2320.5445098876953,589.5289382916501Q2320.5445098876953,596.6000061035156 2327.6155776995606,596.6000061035156L2862.1695098876953,596.6000061035156L2900.09844207583,596.6000061035156Q2907.1695098876953,596.6000061035156 2907.1695098876953,589.5289382916501L2907.1695098876953,123.87107086362329Q2907.1695098876953,116.80000305175781 2900.09844207583,116.80000305175781L843.5390090960452,116.80000305175781Q836.4679412841797,116.80000305175781 836.4679412841797,123.87107086362329L836.4679412841797,511.92893981752906Q836.4679412841797,519.0000076293945 843.5390090960452,519.0000076293945L881.4679412841797,519.0000076293945L896.9679412841797,519.0000076293945" id="g1069-L_bot_signal_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_bot_signal_0" data-points="W3sieCI6MjI2MC41NDQ1MDk4ODc2OTUzLCJ5Ijo1MjUuOTUwMDA4MzkyMzM0fSx7IngiOjIzMjAuNTQ0NTA5ODg3Njk1MywieSI6NTI1Ljk1MDAwODM5MjMzNH0seyJ4IjoyMzIwLjU0NDUwOTg4NzY5NTMsInkiOjU5Ni42MDAwMDYxMDM1MTU2fSx7IngiOjI4NjIuMTY5NTA5ODg3Njk1MywieSI6NTk2LjYwMDAwNjEwMzUxNTZ9LHsieCI6MjkwNy4xNjk1MDk4ODc2OTUzLCJ5Ijo1OTYuNjAwMDA2MTAzNTE1Nn0seyJ4IjoyOTA3LjE2OTUwOTg4NzY5NTMsInkiOjExNi44MDAwMDMwNTE3NTc4MX0seyJ4Ijo4MzYuNDY3OTQxMjg0MTc5NywieSI6MTE2LjgwMDAwMzA1MTc1NzgxfSx7IngiOjgzNi40Njc5NDEyODQxNzk3LCJ5Ijo1MTkuMDAwMDA3NjI5Mzk0NX0seyJ4Ijo4ODEuNDY3OTQxMjg0MTc5NywieSI6NTE5LjAwMDAwNzYyOTM5NDV9LHsieCI6OTAwLjk2Nzk0MTI4NDE3OTcsInkiOjUxOS4wMDAwMDc2MjkzOTQ1fV0=" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M142.04577762741695,363.40489198714016L143.20998445579832,364.56911596630766Q144.3741912841797,365.7333399454752 146.02064049776584,365.7333399454752L330.6710662841797,365.7333399454752" id="g1069-L_tgusers_tgapi_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_tgusers_tgapi_0" data-points="W3sieCI6MTQ0Ljg3NDE4MzkxODQyMDg0LCJ5IjozNjYuMjMzMzM5OTQ1NDc1Mn0seyJ4IjoxNDQuMzc0MTkxMjg0MTc5NywieSI6MzY1LjczMzMzOTk0NTQ3NTJ9LHsieCI6MzM0LjY3MTA2NjI4NDE3OTcsInkiOjM2NS43MzMzMzk5NDU0NzUyfV0=" data-look="classic" marker-start="url(#g1069_flowchart-v2-pointStart)" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M522.3116912841797,365.7333399454752L801.9679412841797,365.7333399454752L881.4679412841797,365.7333399454752L907.6241912841797,365.7333399454752" id="g1069-L_tgapi_telegram_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_tgapi_telegram_0" data-points="W3sieCI6NTE4LjMxMTY5MTI4NDE3OTcsInkiOjM2NS43MzMzMzk5NDU0NzUyfSx7IngiOjgwMS45Njc5NDEyODQxNzk3LCJ5IjozNjUuNzMzMzM5OTQ1NDc1Mn0seyJ4Ijo4ODEuNDY3OTQxMjg0MTc5NywieSI6MzY1LjczMzMzOTk0NTQ3NTJ9LHsieCI6OTExLjYyNDE5MTI4NDE3OTcsInkiOjM2NS43MzMzMzk5NDU0NzUyfV0=" data-look="classic" marker-start="url(#g1069_flowchart-v2-pointStart)" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1143.3116912841797,365.7333399454752L1161.8968734723142,365.7333399454752Q1168.9679412841797,365.7333399454752 1168.9679412841797,372.8044077573407L1168.9679412841797,481.92893981752906Q1168.9679412841797,489.00000762939453 1176.0390090960452,489.00000762939453L1203.4679412841797,489.00000762939453L1212.4679412841797,489.00000762939453Q1218.4679412841797,489.00000762939453 1218.4679412841797,495.00000762939453L1218.4679412841797,495.00000762939453Q1218.4679412841797,501.00000762939453 1224.4679412841797,501.00000762939453L1469.2335662841797,501.00000762939453L2016.0132598876953,501.00000762939453" id="g1069-L_telegram_bot_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_telegram_bot_0" data-points="W3sieCI6MTE0My4zMTE2OTEyODQxNzk3LCJ5IjozNjUuNzMzMzM5OTQ1NDc1Mn0seyJ4IjoxMTY4Ljk2Nzk0MTI4NDE3OTcsInkiOjM2NS43MzMzMzk5NDU0NzUyfSx7IngiOjExNjguOTY3OTQxMjg0MTc5NywieSI6NDg5LjAwMDAwNzYyOTM5NDUzfSx7IngiOjEyMDMuNDY3OTQxMjg0MTc5NywieSI6NDg5LjAwMDAwNzYyOTM5NDUzfSx7IngiOjEyMTguNDY3OTQxMjg0MTc5NywieSI6NDg5LjAwMDAwNzYyOTM5NDUzfSx7IngiOjEyMTguNDY3OTQxMjg0MTc5NywieSI6NTAxLjAwMDAwNzYyOTM5NDUzfSx7IngiOjE0NjkuMjMzNTY2Mjg0MTc5NywieSI6NTAxLjAwMDAwNzYyOTM5NDUzfSx7IngiOjIwMjAuMDEzMjU5ODg3Njk1MywieSI6NTAxLjAwMDAwNzYyOTM5NDUzfV0=" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M2260.5445098876953,501.0000076293946L2862.1695098876953,501.00000762939453L2885.09844207583,501.00000762939453Q2892.1695098876953,501.00000762939453 2892.1695098876953,493.92893981752906L2892.1695098876953,169.47106933774438Q2892.1695098876953,162.4000015258789 2885.09844207583,162.4000015258789L873.5390090960452,162.4000015258789Q866.4679412841797,162.4000015258789 866.4679412841797,169.47106933774438L866.4679412841797,325.3956044496905Q866.4679412841797,332.46667226155597 873.5390090960452,332.46667226155597L881.4679412841797,332.46667226155597L907.6241912841797,332.46667226155597" id="g1069-L_bot_telegram_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_bot_telegram_0" data-points="W3sieCI6MjI2MC41NDQ1MDk4ODc2OTUzLCJ5Ijo1MDEuMDAwMDA3NjI5Mzk0Nn0seyJ4IjoyODYyLjE2OTUwOTg4NzY5NTMsInkiOjUwMS4wMDAwMDc2MjkzOTQ1M30seyJ4IjoyODkyLjE2OTUwOTg4NzY5NTMsInkiOjUwMS4wMDAwMDc2MjkzOTQ1M30seyJ4IjoyODkyLjE2OTUwOTg4NzY5NTMsInkiOjE2Mi40MDAwMDE1MjU4Nzg5fSx7IngiOjg2Ni40Njc5NDEyODQxNzk3LCJ5IjoxNjIuNDAwMDAxNTI1ODc4OX0seyJ4Ijo4NjYuNDY3OTQxMjg0MTc5NywieSI6MzMyLjQ2NjY3MjI2MTU1NTk3fSx7IngiOjg4MS40Njc5NDEyODQxNzk3LCJ5IjozMzIuNDY2NjcyMjYxNTU1OTd9LHsieCI6OTExLjYyNDE5MTI4NDE3OTcsInkiOjMzMi40NjY2NzIyNjE1NTU5N31d" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1195.9679412841797,646.5000076293945L1447.1624984723142,646.5000076293945Q1454.2335662841797,646.5000076293945 1454.2335662841797,639.428939817529L1454.2335662841797,626.6210746783206Q1454.2335662841797,619.5500068664551 1461.3046340960452,619.5500068664551L1461.7335662841797,619.5500068664551Q1469.2335662841797,619.5500068664551 1476.7312236322407,619.7374483001564L1485.2348156985474,619.9500381018139" id="g1069-L_feats_port_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_feats_port_0" data-points="W3sieCI6MTE5NS45Njc5NDEyODQxNzk3LCJ5Ijo2NDYuNTAwMDA3NjI5Mzk0NX0seyJ4IjoxNDU0LjIzMzU2NjI4NDE3OTcsInkiOjY0Ni41MDAwMDc2MjkzOTQ1fSx7IngiOjE0NTQuMjMzNTY2Mjg0MTc5NywieSI6NjE5LjU1MDAwNjg2NjQ1NTF9LHsieCI6MTQ2OS4yMzM1NjYyODQxNzk3LCJ5Ijo2MTkuNTUwMDA2ODY2NDU1MX0seyJ4IjoxNDg5LjIzMzU2NjI4NDE4LCJ5Ijo2MjAuMDUwMDA2ODY2NDU0Nn1d" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1781.646064758301,620.0500068664546L1781.396068572998,619.8000068664549Q1781.1460723876953,619.5500068664551 1781.4996230809004,619.5500068664551L1997.9421920758298,619.5500068664551Q2005.0132598876953,619.5500068664551 2005.0132598876953,612.4789390545895L2005.0132598876953,556.4000091552734Q2005.0132598876953,550.9000091552734 2010.5132598876953,550.9000091552734L2016.0132598876953,550.9000091552734" id="g1069-L_port_bot_0" class="edge-thickness-normal edge-pattern-dotted edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_port_bot_0" data-points="W3sieCI6MTc4MS42NDYwNjQ3NTgzMDEsInkiOjYyMC4wNTAwMDY4NjY0NTQ2fSx7IngiOjE3ODEuMTQ2MDcyMzg3Njk1MywieSI6NjE5LjU1MDAwNjg2NjQ1NTF9LHsieCI6MjAwNS4wMTMyNTk4ODc2OTUzLCJ5Ijo2MTkuNTUwMDA2ODY2NDU1MX0seyJ4IjoyMDA1LjAxMzI1OTg4NzY5NTMsInkiOjU1MC45MDAwMDkxNTUyNzM0fSx7IngiOjIwMjAuMDEzMjU5ODg3Njk1MywieSI6NTUwLjkwMDAwOTE1NTI3MzR9XQ==" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M2569.4195098876953,661.0500049591064L2574.9195098876953,661.0500049591064Q2580.4195098876953,661.0500049591064 2580.4195098876953,666.5500049591064L2580.4195098876953,695.8956031781247Q2580.4195098876953,702.9666709899902 2587.4905776995606,702.9666709899902L2862.1695098876953,702.9666709899902L2941.6695098876953,702.9666709899902L3249.2945098876953,702.9666709899903" id="g1069-L_model_llm_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_model_llm_0" data-points="W3sieCI6MjU2NS40MTk1MDk4ODc2OTUzLCJ5Ijo2NjEuMDUwMDA0OTU5MTA2NH0seyJ4IjoyNTgwLjQxOTUwOTg4NzY5NTMsInkiOjY2MS4wNTAwMDQ5NTkxMDY0fSx7IngiOjI1ODAuNDE5NTA5ODg3Njk1MywieSI6NzAyLjk2NjY3MDk4OTk5MDJ9LHsieCI6Mjg2Mi4xNjk1MDk4ODc2OTUzLCJ5Ijo3MDIuOTY2NjcwOTg5OTkwMn0seyJ4IjoyOTQxLjY2OTUwOTg4NzY5NTMsInkiOjcwMi45NjY2NzA5ODk5OTAyfSx7IngiOjMyNTMuMjk0NTA5ODg3Njk1MywieSI6NzAyLjk2NjY3MDk4OTk5MDN9XQ==" data-look="classic" marker-start="url(#g1069_flowchart-v2-pointStart)" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M2565.4195098876953,628.7500057220459L2573.34844207583,628.7500057220459Q2580.4195098876953,628.7500057220459 2580.4195098876953,621.6789379101804L2580.4195098876953,492.07107544126Q2580.4195098876953,485.00000762939453 2587.4905776995606,485.00000762939453L2862.1695098876953,485.00000762939453L2870.09844207583,485.00000762939453Q2877.1695098876953,485.00000762939453 2877.1695098876953,477.92893981752906L2877.1695098876953,206.47106933774438Q2877.1695098876953,199.4000015258789 2870.09844207583,199.4000015258789L858.5390090960452,199.4000015258789Q851.4679412841797,199.4000015258789 851.4679412841797,206.47106933774438L851.4679412841797,639.428939817529Q851.4679412841797,646.5000076293945 858.5390090960452,646.5000076293945L920.1554412841797,646.5000076293945" id="g1069-L_model_feats_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_model_feats_0" data-points="W3sieCI6MjU2NS40MTk1MDk4ODc2OTUzLCJ5Ijo2MjguNzUwMDA1NzIyMDQ1OX0seyJ4IjoyNTgwLjQxOTUwOTg4NzY5NTMsInkiOjYyOC43NTAwMDU3MjIwNDU5fSx7IngiOjI1ODAuNDE5NTA5ODg3Njk1MywieSI6NDg1LjAwMDAwNzYyOTM5NDUzfSx7IngiOjI4NjIuMTY5NTA5ODg3Njk1MywieSI6NDg1LjAwMDAwNzYyOTM5NDUzfSx7IngiOjI4NzcuMTY5NTA5ODg3Njk1MywieSI6NDg1LjAwMDAwNzYyOTM5NDUzfSx7IngiOjI4NzcuMTY5NTA5ODg3Njk1MywieSI6MTk5LjQwMDAwMTUyNTg3ODl9LHsieCI6ODUxLjQ2Nzk0MTI4NDE3OTcsInkiOjE5OS40MDAwMDE1MjU4Nzg5fSx7IngiOjg1MS40Njc5NDEyODQxNzk3LCJ5Ijo2NDYuNTAwMDA3NjI5Mzk0NX0seyJ4Ijo5MjQuMTU1NDQxMjg0MTc5NywieSI6NjQ2LjUwMDAwNzYyOTM5NDV9XQ==" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1153.9679412841797,474.00000762939453L1203.4679412841797,474.00000762939453L1447.1624984723142,474.00000762939453Q1454.2335662841797,474.00000762939453 1454.2335662841797,466.92893981752906L1454.2335662841797,460.77107620419946Q1454.2335662841797,453.700008392334 1461.3046340960452,453.700008392334L1469.2335662841797,453.700008392334L2346.5445098876953,453.700008392334" id="g1069-L_signal_config_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_signal_config_0" data-points="W3sieCI6MTE1My45Njc5NDEyODQxNzk3LCJ5Ijo0NzQuMDAwMDA3NjI5Mzk0NTN9LHsieCI6MTIwMy40Njc5NDEyODQxNzk3LCJ5Ijo0NzQuMDAwMDA3NjI5Mzk0NTN9LHsieCI6MTQ1NC4yMzM1NjYyODQxNzk3LCJ5Ijo0NzQuMDAwMDA3NjI5Mzk0NTN9LHsieCI6MTQ1NC4yMzM1NjYyODQxNzk3LCJ5Ijo0NTMuNzAwMDA4MzkyMzM0fSx7IngiOjE0NjkuMjMzNTY2Mjg0MTc5NywieSI6NDUzLjcwMDAwODM5MjMzNH0seyJ4IjoyMzUwLjU0NDUwOTg4NzY5NTMsInkiOjQ1My43MDAwMDgzOTIzMzR9XQ==" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1143.3116912841797,332.46667226155597L1203.4679412841797,332.46667226155597L1447.1624984723142,332.46667226155597Q1454.2335662841797,332.46667226155597 1454.2335662841797,339.53774007342145L1454.2335662841797,430.47894096193824Q1454.2335662841797,437.5500087738037 1461.3046340960452,437.5500087738037L1469.2335662841797,437.5500087738037L2346.5445098876953,437.5500087738037" id="g1069-L_telegram_config_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_telegram_config_0" data-points="W3sieCI6MTE0My4zMTE2OTEyODQxNzk3LCJ5IjozMzIuNDY2NjcyMjYxNTU1OTd9LHsieCI6MTIwMy40Njc5NDEyODQxNzk3LCJ5IjozMzIuNDY2NjcyMjYxNTU1OTd9LHsieCI6MTQ1NC4yMzM1NjYyODQxNzk3LCJ5IjozMzIuNDY2NjcyMjYxNTU1OTd9LHsieCI6MTQ1NC4yMzM1NjYyODQxNzk3LCJ5Ijo0MzcuNTUwMDA4NzczODAzN30seyJ4IjoxNDY5LjIzMzU2NjI4NDE3OTcsInkiOjQzNy41NTAwMDg3NzM4MDM3fSx7IngiOjIzNTAuNTQ0NTA5ODg3Njk1MywieSI6NDM3LjU1MDAwODc3MzgwMzd9XQ==" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1183.9679412841797,661.5000076293945L1203.4679412841797,661.5000076293945L1226.3968734723142,661.5000076293945Q1233.4679412841797,661.5000076293945 1233.4679412841797,668.5710754412601L1233.4679412841797,739.8956031781247Q1233.4679412841797,746.9666709899902 1240.5390090960452,746.9666709899902L2941.6695098876953,746.9666709899902L2998.1695098876953,746.9666709899902Q3001.6695098876953,746.9666709899902 3001.6695098876953,750.4666709899902L3001.6695098876953,750.4666709899902Q3001.6695098876953,753.9666709899902 3005.1695098876953,753.9666709899902L3226.22344207583,753.9666709899902Q3233.2945098876953,753.9666709899902 3233.2945098876953,746.8956031781247L3233.2945098876953,737.4377377846031Q3233.2945098876953,730.3666699727377 3240.3655776995606,730.3666699727377L3249.2945098876953,730.3666699727377" id="g1069-L_websearch_llm_0" class="edge-thickness-normal edge-pattern-dotted edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_websearch_llm_0" data-points="W3sieCI6MTE4My45Njc5NDEyODQxNzk3LCJ5Ijo2NjEuNTAwMDA3NjI5Mzk0NX0seyJ4IjoxMjAzLjQ2Nzk0MTI4NDE3OTcsInkiOjY2MS41MDAwMDc2MjkzOTQ1fSx7IngiOjEyMzMuNDY3OTQxMjg0MTc5NywieSI6NjYxLjUwMDAwNzYyOTM5NDV9LHsieCI6MTIzMy40Njc5NDEyODQxNzk3LCJ5Ijo3NDYuOTY2NjcwOTg5OTkwMn0seyJ4IjoyOTQxLjY2OTUwOTg4NzY5NTMsInkiOjc0Ni45NjY2NzA5ODk5OTAyfSx7IngiOjMwMDEuNjY5NTA5ODg3Njk1MywieSI6NzQ2Ljk2NjY3MDk4OTk5MDJ9LHsieCI6MzAwMS42Njk1MDk4ODc2OTUzLCJ5Ijo3NTMuOTY2NjcwOTg5OTkwMn0seyJ4IjozMjMzLjI5NDUwOTg4NzY5NTMsInkiOjc1My45NjY2NzA5ODk5OTAyfSx7IngiOjMyMzMuMjk0NTA5ODg3Njk1MywieSI6NzMwLjM2NjY2OTk3MjczNzd9LHsieCI6MzI1My4yOTQ1MDk4ODc2OTUzLCJ5Ijo3MzAuMzY2NjY5OTcyNzM3N31d" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1183.9679412841797,892.5000076293945L1203.4679412841797,892.5000076293945L2941.6695098876953,892.5000076293945L2954.59844207583,892.5000076293945Q2961.6695098876953,892.5000076293945 2961.6695098876953,899.5710754412601L2961.6695098876953,964.296293892643Q2961.6695098876953,971.3673617045085 2968.7405776995606,971.3673617045085L3249.2945098876953,971.3673617045085" id="g1069-L_links_web_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_links_web_0" data-points="W3sieCI6MTE4My45Njc5NDEyODQxNzk3LCJ5Ijo4OTIuNTAwMDA3NjI5Mzk0NX0seyJ4IjoxMjAzLjQ2Nzk0MTI4NDE3OTcsInkiOjg5Mi41MDAwMDc2MjkzOTQ1fSx7IngiOjI5NDEuNjY5NTA5ODg3Njk1MywieSI6ODkyLjUwMDAwNzYyOTM5NDV9LHsieCI6Mjk2MS42Njk1MDk4ODc2OTUzLCJ5Ijo4OTIuNTAwMDA3NjI5Mzk0NX0seyJ4IjoyOTYxLjY2OTUwOTg4NzY5NTMsInkiOjk3MS4zNjczNjE3MDQ1MDg1fSx7IngiOjMyNTMuMjk0NTA5ODg3Njk1MywieSI6OTcxLjM2NzM2MTcwNDUwODV9XQ==" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1187.9679412841797,1123.5000076293945L1203.4679412841797,1123.5000076293945L2941.6695098876953,1123.5000076293945L3249.2945098876953,1123.5000076293945" id="g1069-L_mcp_mcpsrv_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_mcp_mcpsrv_0" data-points="W3sieCI6MTE4My45Njc5NDEyODQxNzk3LCJ5IjoxMTIzLjUwMDAwNzYyOTM5NDV9LHsieCI6MTIwMy40Njc5NDEyODQxNzk3LCJ5IjoxMTIzLjUwMDAwNzYyOTM5NDV9LHsieCI6Mjk0MS42Njk1MDk4ODc2OTUzLCJ5IjoxMTIzLjUwMDAwNzYyOTM5NDV9LHsieCI6MzI1My4yOTQ1MDk4ODc2OTUzLCJ5IjoxMTIzLjUwMDAwNzYyOTM5NDV9XQ==" data-look="classic" marker-start="url(#g1069_flowchart-v2-pointStart)" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1183.9679412841797,738.5000076293945L1203.4679412841797,738.5000076293945L1211.3968734723142,738.5000076293945Q1218.4679412841797,738.5000076293945 1218.4679412841797,745.5710754412601L1218.4679412841797,769.8956031781247Q1218.4679412841797,776.9666709899902 1225.5390090960452,776.9666709899902L2941.6695098876953,776.9666709899902L2954.59844207583,776.9666709899902Q2961.6695098876953,776.9666709899902 2961.6695098876953,784.0377388018558L2961.6695098876953,869.3958320599609Q2961.6695098876953,876.4668998718263 2968.7405776995606,876.4668998718263L3230.6446253458657,876.4668998718263Q3233.2945098876953,876.4668998718263 3233.2945098876953,873.8170153299968L3233.2945098876953,873.8170153299968Q3233.2945098876953,871.1671307881674 3235.944394429525,871.1671307881674L3249.2945098876953,871.1671307881674" id="g1069-L_schedule_disk_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_schedule_disk_0" data-points="W3sieCI6MTE4My45Njc5NDEyODQxNzk3LCJ5Ijo3MzguNTAwMDA3NjI5Mzk0NX0seyJ4IjoxMjAzLjQ2Nzk0MTI4NDE3OTcsInkiOjczOC41MDAwMDc2MjkzOTQ1fSx7IngiOjEyMTguNDY3OTQxMjg0MTc5NywieSI6NzM4LjUwMDAwNzYyOTM5NDV9LHsieCI6MTIxOC40Njc5NDEyODQxNzk3LCJ5Ijo3NzYuOTY2NjcwOTg5OTkwMn0seyJ4IjoyOTQxLjY2OTUwOTg4NzY5NTMsInkiOjc3Ni45NjY2NzA5ODk5OTAyfSx7IngiOjI5NjEuNjY5NTA5ODg3Njk1MywieSI6Nzc2Ljk2NjY3MDk4OTk5MDJ9LHsieCI6Mjk2MS42Njk1MDk4ODc2OTUzLCJ5Ijo4NzYuNDY2ODk5ODcxODI2M30seyJ4IjozMjMzLjI5NDUwOTg4NzY5NTMsInkiOjg3Ni40NjY4OTk4NzE4MjYzfSx7IngiOjMyMzMuMjk0NTA5ODg3Njk1MywieSI6ODcxLjE2NzEzMDc4ODE2NzR9LHsieCI6MzI1My4yOTQ1MDk4ODc2OTUzLCJ5Ijo4NzEuMTY3MTMwNzg4MTY3NH1d" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M2260.5445098876953,563.3750095367432L2268.47344207583,563.3750095367432Q2275.5445098876953,563.3750095367432 2275.5445098876953,570.4460773486087L2275.5445098876953,711.8956031781247Q2275.5445098876953,718.9666709899902 2282.6155776995606,718.9666709899902L2862.1695098876953,718.9666709899902L2870.09844207583,718.9666709899902Q2877.1695098876953,718.9666709899902 2877.1695098876953,726.0377388018558L2877.1695098876953,754.8956031781247Q2877.1695098876953,761.9666709899902 2884.2405776995606,761.9666709899902L2941.6695098876953,761.9666709899902L2974.59844207583,761.9666709899902Q2981.6695098876953,761.9666709899902 2981.6695098876953,769.0377388018558L2981.6695098876953,827.3958320599609Q2981.6695098876953,834.4668998718263 2988.7405776995606,834.4668998718263L3249.2945098876953,834.4668998718263" id="g1069-L_bot_disk_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_bot_disk_0" data-points="W3sieCI6MjI2MC41NDQ1MDk4ODc2OTUzLCJ5Ijo1NjMuMzc1MDA5NTM2NzQzMn0seyJ4IjoyMjc1LjU0NDUwOTg4NzY5NTMsInkiOjU2My4zNzUwMDk1MzY3NDMyfSx7IngiOjIyNzUuNTQ0NTA5ODg3Njk1MywieSI6NzE4Ljk2NjY3MDk4OTk5MDJ9LHsieCI6Mjg2Mi4xNjk1MDk4ODc2OTUzLCJ5Ijo3MTguOTY2NjcwOTg5OTkwMn0seyJ4IjoyODc3LjE2OTUwOTg4NzY5NTMsInkiOjcxOC45NjY2NzA5ODk5OTAyfSx7IngiOjI4NzcuMTY5NTA5ODg3Njk1MywieSI6NzYxLjk2NjY3MDk4OTk5MDJ9LHsieCI6Mjk0MS42Njk1MDk4ODc2OTUzLCJ5Ijo3NjEuOTY2NjcwOTg5OTkwMn0seyJ4IjoyOTgxLjY2OTUwOTg4NzY5NTMsInkiOjc2MS45NjY2NzA5ODk5OTAyfSx7IngiOjI5ODEuNjY5NTA5ODg3Njk1MywieSI6ODM0LjQ2Njg5OTg3MTgyNjN9LHsieCI6MzI1My4yOTQ1MDk4ODc2OTUzLCJ5Ijo4MzQuNDY2ODk5ODcxODI2M31d" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path></g><g class="edgeLabels"><g class="edgeLabel" transform="translate(239.3038787841797, 504.2333399454752)"><g class="label" data-id="L_users_scli_0" transform="translate(0, -11.5)"><g><rect class="background" style="" x="-54.9296875" y="1" width="109.859375" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Signal</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> protocol</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(660.3585662841797, 504.03333918253577)"><g class="label" data-id="L_scli_signal_0" transform="translate(0, -64.29999923706055)"><g><rect class="background" style="" x="-101.609375" y="1" width="203.21875" height="126.5999984741211"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">JSON-RPC</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> over</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> TCP</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> or</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> a</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Unix</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> socket:</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="2.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">receive,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> send,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="3.2em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">sendReaction,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> sendTyping,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="4.300000000000001em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">getAttachment,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> listContacts,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="5.4em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">listAccounts,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="6.500000000000001em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">listGroups</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> and</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> more</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(1343.8507537841797, 537.5000076293945)"><g class="label" data-id="L_signal_bot_0" transform="translate(0, -11.5)"><g><rect class="background" style="" x="-48.6953125" y="1" width="97.390625" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">bot.Received</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(1343.8507537841797, 116.10000228881836)"><g class="label" data-id="L_bot_signal_0" transform="translate(0, -20.299999237060547)"><g><rect class="background" style="" x="-95.3828125" y="1" width="190.765625" height="38.599998474121094"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">bot.Network:</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Send,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> React,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Typing,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Media,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Groups</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(239.3038787841797, 365.2333399454752)"><g class="label" data-id="L_tgusers_tgapi_0" transform="translate(-0.05078125, -11.5)"><g><rect class="background" style="" x="-32.671875" y="1" width="65.4453125" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">MTProto</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(660.3585662841797, 365.2333399454752)"><g class="label" data-id="L_tgapi_telegram_0" transform="translate(0, -55.5)"><g><rect class="background" style="" x="-96.734375" y="1" width="193.46875" height="109"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">HTTPS,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> TLS</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> 1.3:</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">getUpdates,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="2.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">sendMessage,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> sendPhoto,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="3.2em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">getFile,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="4.300000000000001em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">setMessageReaction</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> and</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="5.4em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">more</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(1343.8507537841797, 500.50000762939453)"><g class="label" data-id="L_telegram_bot_0" transform="translate(0, -11.5)"><g><rect class="background" style="" x="-48.6953125" y="1" width="97.390625" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">bot.Received</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(1343.8507537841797, 161.9000015258789)"><g class="label" data-id="L_bot_telegram_0" transform="translate(-0.49609375, -11.5)"><g><rect class="background" style="" x="-44.6875" y="1" width="90.3671875" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">bot.Network</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(1343.8507537841797, 646.0000076293945)"><g class="label" data-id="L_feats_port_0" transform="translate(0, -11.5)"><g><rect class="background" style="" x="-86.9453125" y="1" width="173.890625" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">register</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> hooks</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> and</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> tools</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(1900.5796661376953, 619.0500068664551)"><g class="label" data-id="L_port_bot_0" transform="translate(-0.27734375, -11.5)"><g><rect class="background" style="" x="-89.15625" y="1" width="178.8671875" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">the</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Bot</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> implements</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Host</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(3117.4820098876953, 702.4666709899902)"><g class="label" data-id="L_model_llm_0" transform="translate(-0.05078125, -11.5)"><g><rect class="background" style="" x="-60.5390625" y="1" width="121.1796875" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">HTTPS,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> TLS</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> 1.3</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(1343.8507537841797, 198.9000015258789)"><g class="label" data-id="L_model_feats_0" transform="translate(-0.05078125, -11.5)"><g><rect class="background" style="" x="-79.3671875" y="1" width="158.8359375" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Tool.Run:</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> charts,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> mcp</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(3117.4820098876953, 753.2666702270508)"><g class="label" data-id="L_websearch_llm_0" transform="translate(0, -20.299999237060547)"><g><rect class="background" style="" x="-66.03125" y="1" width="132.0625" height="38.599998474121094"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">server</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> tool,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> run</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> by</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">OpenRouter</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(3117.4820098876953, 970.6673609415691)"><g class="label" data-id="L_links_web_0" transform="translate(0, -20.299999237060547)"><g><rect class="background" style="" x="-95.8125" y="1" width="191.625" height="38.599998474121094"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">HTTPS,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> private</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> addresses</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">refused</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(3117.4820098876953, 1123.0000076293945)"><g class="label" data-id="L_mcp_mcpsrv_0" transform="translate(0, -11.5)"><g><rect class="background" style="" x="-82.921875" y="1" width="165.84375" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">MCP:</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> list</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> and</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> call</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> tools</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(3117.4820098876953, 875.9668998718263)"><g class="label" data-id="L_schedule_disk_0" transform="translate(-0.046875, -11.5)"><g><rect class="background" style="" x="-21.125" y="1" width="42.34375" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Store</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(3117.4820098876953, 833.9668998718263)"><g class="label" data-id="L_bot_disk_0" transform="translate(0, -11.5)"><g><rect class="background" style="" x="-43.3671875" y="1" width="86.734375" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">budget.json</tspan></tspan></text></g></g></g></g><g class="nodes"><g class="node default ext" id="g1069-flowchart-users-0" data-look="classic" transform="translate(88.85116195678711, 504.7333399454752)"><g class="basic label-container outer-path"><path d="M-39.53125 -16 C-8.853541698567344 -16, 21.82416660286531 -16, 39.53125 -16 C39.53125 -16, 39.53125 -16, 39.53125 -16 C39.8287459544915 -15.990459883780204, 40.126241908983 -15.98091976756041, 40.556373519691405 -15.967126284005381 C40.76626545318403 -15.94687826161333, 40.976157386676654 -15.926630239221279, 41.577284586952096 -15.868640221171939 C41.84800821062784 -15.824871725189102, 42.11873183430358 -15.781103229206266, 42.58978805922195 -15.704946511857047 C42.824150316251114 -15.651454856046794, 43.058512573280275 -15.59796320023654, 43.58972334255211 -15.476717808624471 C43.809712437376376 -15.411426200026952, 44.02970153220064 -15.346134591429434, 44.572981488377934 -15.184891952170698 C44.89416367042614 -15.066693940201414, 45.215345852474336 -14.948495928232132, 45.53552207806999 -14.830668117536348 C45.80614352002659 -14.710872032882012, 46.07676496198319 -14.591075948227676, 46.47338982588093 -14.415501886438706 C46.701260070682146 -14.296622125683768, 46.92913031548337 -14.17774236492883, 47.382730832063004 -13.941099265974232 C47.635725200440504 -13.787732593103858, 47.888719568818 -13.634365920233483, 48.25980841936878 -13.409409678269451 C48.49908213312966 -13.242502693541988, 48.73835584689054 -13.075595708814525, 49.101018487859456 -12.822617949887306 C49.29450853131015 -12.668314789221679, 49.48799857476084 -12.514011628556053, 49.90290432492461 -12.183135333906153 C50.180000311981196 -11.931484090019422, 50.45709629903779 -11.679832846132694, 50.662170809655784 -11.493589601563642 C50.94731782276734 -11.199151899520801, 51.232464835878886 -10.904714197477963, 51.37569795320505 -10.756814244181072 C51.61699386792725 -10.473374332621871, 51.85828978264945 -10.18993442106267, 52.04055371948848 -9.975836829739738 C52.26405092003508 -9.676370942021121, 52.487548120581685 -9.376905054302505, 52.65400607355129 -9.153866561954718 C52.818627151513596 -8.900964379255617, 52.98324822947591 -8.648062196556518, 53.213534208085534 -8.294281092968403 C53.38986672023664 -7.981184862041069, 53.566199232387746 -7.668088631113735, 53.716838901968 -7.400612643853364 C53.83770035461109 -7.149641251419186, 53.95856180725417 -6.8986698589850075, 54.161851968252996 -6.476533489958305 C54.26026928895161 -6.2334408050632675, 54.358686609650235 -5.990348120168231, 54.546744752796165 -5.52584087074093 C54.65169125654768 -5.209758722395985, 54.7566377602992 -4.893676574051041, 54.86993564858657 -4.552441386096524 C54.927842003528916 -4.331619357928371, 54.98574835847126 -4.110797329760218, 55.130096594909176 -3.560334943301032 C55.206008937285176 -3.1705411092795206, 55.28192127966118 -2.780747275258009, 55.326158534631205 -2.5535983205340735 C55.37158972974992 -2.2012429425975317, 55.41702092486863 -1.84888756466099, 55.45731580718717 -1.536368414522911 C55.48290123627834 -1.13785470424133, 55.5084866653695 -0.7393409939597488, 55.523029459211 -0.5128252411464826 C55.523029459211 -0.11984368198501999, 55.523029459211 0.27313787717644267, 55.523029459211 0.5128252411464788 C55.49701520373653 0.9180182684904905, 55.47100094826206 1.3232112958345024, 55.45731580718717 1.5363684145229002 C55.4118953675383 1.8886403751592669, 55.36647492788943 2.2409123357956338, 55.326158534631205 2.5535983205340624 C55.26627797808663 2.8610723226303443, 55.20639742154206 3.168546324726626, 55.130096594909176 3.5603349433010285 C55.027775747255184 3.950528681541589, 54.92545489960119 4.34072241978215, 54.86993564858657 4.552441386096513 C54.79456442870599 4.779447491603757, 54.71919320882541 5.006453597111, 54.546744752796165 5.525840870740919 C54.40478353353902 5.876487826939538, 54.26282231428187 6.227134783138157, 54.161851968253 6.4765334899583005 C54.03956974323592 6.730455146626734, 53.91728751821885 6.984376803295167, 53.716838901968 7.400612643853361 C53.533382616808105 7.726357855118047, 53.34992633164821 8.052103066382733, 53.21353420808554 8.294281092968399 C53.03855042043867 8.563103180520168, 52.86356663279179 8.831925268071936, 52.6540060735513 9.15386656195471 C52.47511432334086 9.393565209862988, 52.296222573130414 9.633263857771265, 52.04055371948848 9.975836829739734 C51.90538279677529 10.134616287002036, 51.770211874062106 10.29339574426434, 51.375697953205055 10.756814244181063 C51.19631595397437 10.942040885922774, 51.01693395474369 11.127267527664484, 50.662170809655784 11.493589601563638 C50.43744669987826 11.697678092189465, 50.21272259010074 11.901766582815291, 49.90290432492463 12.183135333906142 C49.652436226655034 12.382876977040125, 49.40196812838544 12.582618620174108, 49.10101848785946 12.822617949887304 C48.86836915691236 12.984904051928785, 48.63571982596526 13.147190153970266, 48.25980841936879 13.409409678269446 C48.044203975582334 13.540110359125142, 47.82859953179589 13.67081103998084, 47.382730832063004 13.94109926597423 C47.183554689950014 14.045009331736168, 46.98437854783703 14.148919397498103, 46.47338982588093 14.415501886438705 C46.22176662250305 14.526888014436969, 45.97014341912516 14.63827414243523, 45.535522078069995 14.830668117536346 C45.31648268328429 14.911276639595453, 45.097443288498596 14.99188516165456, 44.57298148837794 15.184891952170695 C44.29490153865001 15.267424621578504, 44.01682158892207 15.349957290986312, 43.58972334255213 15.476717808624468 C43.30672443126736 15.541310463384734, 43.02372551998259 15.605903118145, 42.58978805922196 15.704946511857045 C42.363876412727905 15.74147015489122, 42.13796476623385 15.777993797925394, 41.5772845869521 15.868640221171937 C41.24688443129441 15.90051352682391, 40.91648427563672 15.932386832475885, 40.556373519691405 15.967126284005381 C40.276475039404914 15.976102083478828, 39.996576559118424 15.985077882952273, 39.53125 16 C39.53125 16, 39.53125 16, 39.53125 16 C11.419256779070754 16, -16.692736441858493 16, -39.53125 16 C-39.93079212830454 15.98718746160685, -40.33033425660907 15.974374923213697, -40.5563735196914 15.967126284005381 C-40.89594947831425 15.934367799676876, -41.2355254369371 15.90160931534837, -41.577284586952096 15.868640221171937 C-41.94438831461072 15.809289737416018, -42.31149204226935 15.749939253660099, -42.58978805922196 15.704946511857045 C-42.86604586813568 15.641892469723167, -43.14230367704939 15.578838427589291, -43.58972334255211 15.476717808624471 C-43.88198414719161 15.389976335915737, -44.17424495183111 15.303234863207003, -44.57298148837792 15.184891952170702 C-44.782874807684294 15.107649270433381, -44.99276812699067 15.030406588696062, -45.53552207806999 14.830668117536348 C-45.843029357819084 14.694543766670776, -46.15053663756818 14.558419415805206, -46.47338982588093 14.415501886438708 C-46.73357923898204 14.279761236283132, -46.99376865208315 14.144020586127555, -47.382730832063 13.941099265974234 C-47.66328036857541 13.771028488248334, -47.94382990508781 13.600957710522435, -48.25980841936877 13.409409678269457 C-48.528860299858145 13.221730733508258, -48.79791218034752 13.034051788747059, -49.101018487859456 12.822617949887308 C-49.30773462369481 12.65776733250601, -49.51445075953017 12.492916715124714, -49.90290432492461 12.183135333906154 C-50.111860948057256 11.993366457466376, -50.32081757118989 11.803597581026597, -50.66217080965578 11.493589601563649 C-50.91430982943568 11.233235362642391, -51.16644884921558 10.972881123721132, -51.37569795320505 10.756814244181069 C-51.60113499285663 10.492003069675372, -51.82657203250821 10.227191895169673, -52.04055371948847 9.97583682973974 C-52.218440106229224 9.737485277290347, -52.396326492969976 9.499133724840954, -52.65400607355129 9.15386656195472 C-52.82823728003461 8.886200641166521, -53.00246848651792 8.618534720378321, -53.213534208085534 8.29428109296841 C-53.40156866198752 7.960406879512298, -53.589603115889496 7.626532666056187, -53.716838901968 7.400612643853366 C-53.85727937879155 7.108984988784448, -53.997719855615095 6.817357333715528, -54.161851968252996 6.476533489958307 C-54.304788333828 6.123477903501422, -54.447724699403004 5.770422317044538, -54.546744752796165 5.525840870740931 C-54.6679506316291 5.160788075230372, -54.78915651046203 4.795735279719812, -54.86993564858657 4.552441386096519 C-54.95328426750965 4.23459697862285, -55.03663288643274 3.91675257114918, -55.130096594909176 3.5603349433010343 C-55.17729384534498 3.3179870374556204, -55.22449109578078 3.0756391316102065, -55.326158534631205 2.5535983205340753 C-55.3698508562782 2.2147293018647796, -55.41354317792519 1.8758602831954838, -55.45731580718717 1.5363684145229202 C-55.481635984610776 1.1575620202563535, -55.50595616203438 0.778755625989787, -55.523029459211 0.5128252411464846 C-55.523029459211 0.22428975267455936, -55.523029459211 -0.06424573579736592, -55.523029459211 -0.5128252411464769 C-55.502056542060686 -0.8394953547967459, -55.48108362491036 -1.1661654684470149, -55.45731580718717 -1.5363684145228982 C-55.42159272720871 -1.8134295685158057, -55.38586964723025 -2.0904907225087133, -55.326158534631205 -2.5535983205340678 C-55.25144490948211 -2.937236994944395, -55.176731284333016 -3.320875669354722, -55.130096594909176 -3.5603349433010267 C-55.07458881012505 -3.772010183909013, -55.019081025340924 -3.9836854245169997, -54.869935648586576 -4.552441386096511 C-54.74736185143608 -4.921614133631368, -54.624788054285595 -5.290786881166226, -54.54674475279617 -5.525840870740911 C-54.45603718223133 -5.749890323747645, -54.36532961166649 -5.97393977675438, -54.161851968253 -6.476533489958299 C-53.99386017408023 -6.8253720450066275, -53.82586837990747 -7.1742106000549555, -53.716838901968 -7.400612643853359 C-53.597108229136914 -7.613206577510267, -53.477377556305825 -7.8258005111671745, -53.213534208085534 -8.294281092968404 C-53.090477594070656 -8.483329097422905, -52.96742098005578 -8.672377101877403, -52.654006073551294 -9.153866561954715 C-52.427961940207155 -9.456745107591674, -52.201917806863015 -9.759623653228633, -52.04055371948848 -9.975836829739734 C-51.87503915969803 -10.170259649714852, -51.709524599907574 -10.364682469689972, -51.375697953205055 -10.756814244181063 C-51.11383577968841 -11.02720843762128, -50.85197360617176 -11.297602631061498, -50.66217080965579 -11.493589601563633 C-50.3969350035715 -11.734469742894518, -50.13169919748721 -11.975349884225405, -49.90290432492463 -12.18313533390614 C-49.737995502146426 -12.314645731663681, -49.573086679368224 -12.446156129421222, -49.10101848785946 -12.822617949887302 C-48.86848662193326 -12.984822113415188, -48.635954756007045 -13.147026276943071, -48.25980841936879 -13.409409678269444 C-48.024064564740755 -13.55231898832962, -47.78832071011273 -13.695228298389798, -47.382730832063004 -13.941099265974229 C-47.026308517811685 -14.127044559019755, -46.66988620356037 -14.31298985206528, -46.473389825880936 -14.415501886438705 C-46.20561432454231 -14.534038157603293, -45.93783882320368 -14.652574428767881, -45.535522078069995 -14.830668117536344 C-45.32410369860372 -14.908472035510009, -45.11268531913745 -14.986275953483675, -44.57298148837794 -15.184891952170695 C-44.25212031535246 -15.280121864089994, -43.931259142326965 -15.37535177600929, -43.58972334255213 -15.476717808624466 C-43.340165335008074 -15.533677795328206, -43.09060732746401 -15.590637782031946, -42.589788059221966 -15.704946511857043 C-42.190249223842486 -15.769540852291254, -41.79071038846301 -15.834135192725464, -41.5772845869521 -15.868640221171937 C-41.23558073913608 -15.901603980411746, -40.89387689132006 -15.934567739651555, -40.556373519691405 -15.967126284005381 C-40.267134908103756 -15.976401603310194, -39.97789629651611 -15.985676922615005, -39.53125000000001 -16 C-39.53125000000001 -16, -39.53125 -16, -39.53125 -16" stroke="none" stroke-width="0" fill="#f3f4f6" style="fill:#f3f4f6 !important;stroke:#6b7280 !important"></path><path d="M-39.53125 -16 C-14.285494672522574 -16, 10.960260654954851 -16, 39.53125 -16 M-39.53125 -16 C-17.39374383940747 -16, 4.743762321185059 -16, 39.53125 -16 M39.53125 -16 C39.53125 -16, 39.53125 -16, 39.53125 -16 M39.53125 -16 C39.53125 -16, 39.53125 -16, 39.53125 -16 M39.53125 -16 C39.78122673938669 -15.991983732518076, 40.03120347877337 -15.98396746503615, 40.556373519691405 -15.967126284005381 M39.53125 -16 C39.79226914170174 -15.991629624168564, 40.053288283403475 -15.983259248337127, 40.556373519691405 -15.967126284005381 M40.556373519691405 -15.967126284005381 C40.913635529543676 -15.932661647585363, 41.270897539395946 -15.898197011165344, 41.577284586952096 -15.868640221171939 M40.556373519691405 -15.967126284005381 C40.83173823383019 -15.940562181206934, 41.107102947968976 -15.913998078408488, 41.577284586952096 -15.868640221171939 M41.577284586952096 -15.868640221171939 C41.96447173777732 -15.806042805307715, 42.35165888860256 -15.743445389443492, 42.58978805922195 -15.704946511857047 M41.577284586952096 -15.868640221171939 C41.85226219145586 -15.824183974558942, 42.12723979595962 -15.779727727945946, 42.58978805922195 -15.704946511857047 M42.58978805922195 -15.704946511857047 C42.92470115390306 -15.628504783508275, 43.25961424858416 -15.552063055159502, 43.58972334255211 -15.476717808624471 M42.58978805922195 -15.704946511857047 C42.98484292704056 -15.614777816251387, 43.37989779485917 -15.524609120645726, 43.58972334255211 -15.476717808624471 M43.58972334255211 -15.476717808624471 C43.82997231482707 -15.405413174745854, 44.07022128710203 -15.334108540867236, 44.572981488377934 -15.184891952170698 M43.58972334255211 -15.476717808624471 C43.899129386198645 -15.384887718975646, 44.20853542984518 -15.293057629326821, 44.572981488377934 -15.184891952170698 M44.572981488377934 -15.184891952170698 C44.83236995999847 -15.089434596853593, 45.091758431619006 -14.99397724153649, 45.53552207806999 -14.830668117536348 M44.572981488377934 -15.184891952170698 C44.89583617338073 -15.066078443653677, 45.21869085838353 -14.947264935136655, 45.53552207806999 -14.830668117536348 M45.53552207806999 -14.830668117536348 C45.849200732386564 -14.691811882217074, 46.16287938670314 -14.552955646897802, 46.47338982588093 -14.415501886438706 M45.53552207806999 -14.830668117536348 C45.78208539749038 -14.721521850069944, 46.02864871691076 -14.612375582603542, 46.47338982588093 -14.415501886438706 M46.47338982588093 -14.415501886438706 C46.71292852267583 -14.290534701752666, 46.952467219470726 -14.165567517066625, 47.382730832063004 -13.941099265974232 M46.47338982588093 -14.415501886438706 C46.81767758457956 -14.235887183252466, 47.16196534327819 -14.056272480066223, 47.382730832063004 -13.941099265974232 M47.382730832063004 -13.941099265974232 C47.6582763062706 -13.774061980224644, 47.9338217804782 -13.607024694475056, 48.25980841936878 -13.409409678269451 M47.382730832063004 -13.941099265974232 C47.67434641797654 -13.764320184070044, 47.96596200389007 -13.587541102165858, 48.25980841936878 -13.409409678269451 M48.25980841936878 -13.409409678269451 C48.42879207856109 -13.291533992801602, 48.597775737753395 -13.173658307333755, 49.101018487859456 -12.822617949887306 M48.25980841936878 -13.409409678269451 C48.510985123126105 -13.2341996829926, 48.76216182688343 -13.05898968771575, 49.101018487859456 -12.822617949887306 M49.101018487859456 -12.822617949887306 C49.31736036886612 -12.650091056883728, 49.53370224987279 -12.477564163880148, 49.90290432492461 -12.183135333906153 M49.101018487859456 -12.822617949887306 C49.32300258101944 -12.645591542837028, 49.54498667417942 -12.46856513578675, 49.90290432492461 -12.183135333906153 M49.90290432492461 -12.183135333906153 C50.07864955695188 -12.023528164143015, 50.254394788979155 -11.863920994379876, 50.662170809655784 -11.493589601563642 M49.90290432492461 -12.183135333906153 C50.1474935527081 -11.961005868709535, 50.39208278049158 -11.738876403512917, 50.662170809655784 -11.493589601563642 M50.662170809655784 -11.493589601563642 C50.91983261443204 -11.227532633704564, 51.1774944192083 -10.961475665845487, 51.37569795320505 -10.756814244181072 M50.662170809655784 -11.493589601563642 C50.92805551406738 -11.219041814718464, 51.19394021847897 -10.944494027873288, 51.37569795320505 -10.756814244181072 M51.37569795320505 -10.756814244181072 C51.56778986898836 -10.531172149562337, 51.75988178477168 -10.305530054943604, 52.04055371948848 -9.975836829739738 M51.37569795320505 -10.756814244181072 C51.560432312079435 -10.539814754564418, 51.745166670953815 -10.322815264947764, 52.04055371948848 -9.975836829739738 M52.04055371948848 -9.975836829739738 C52.27059487626515 -9.66760263683951, 52.500636033041815 -9.359368443939283, 52.65400607355129 -9.153866561954718 M52.04055371948848 -9.975836829739738 C52.23873356387037 -9.710293892823245, 52.43691340825225 -9.444750955906752, 52.65400607355129 -9.153866561954718 M52.65400607355129 -9.153866561954718 C52.79584831030727 -8.935958796323863, 52.93769054706325 -8.71805103069301, 53.213534208085534 -8.294281092968403 M52.65400607355129 -9.153866561954718 C52.836188393148724 -8.873985596250403, 53.01837071274616 -8.59410463054609, 53.213534208085534 -8.294281092968403 M53.213534208085534 -8.294281092968403 C53.340218477135295 -8.06934034509728, 53.46690274618505 -7.844399597226157, 53.716838901968 -7.400612643853364 M53.213534208085534 -8.294281092968403 C53.36959130490037 -8.017185915079049, 53.52564840171521 -7.740090737189694, 53.716838901968 -7.400612643853364 M53.716838901968 -7.400612643853364 C53.84952991744219 -7.12507691108831, 53.98222093291637 -6.849541178323254, 54.161851968252996 -6.476533489958305 M53.716838901968 -7.400612643853364 C53.80613831319459 -7.215180505740051, 53.89543772442117 -7.0297483676267385, 54.161851968252996 -6.476533489958305 M54.161851968252996 -6.476533489958305 C54.292089549680014 -6.154844145861236, 54.42232713110703 -5.8331548017641675, 54.546744752796165 -5.52584087074093 M54.161851968252996 -6.476533489958305 C54.275056759659094 -6.196915466519504, 54.388261551065185 -5.917297443080702, 54.546744752796165 -5.52584087074093 M54.546744752796165 -5.52584087074093 C54.63995928160424 -5.2450935616892655, 54.73317381041232 -4.964346252637601, 54.86993564858657 -4.552441386096524 M54.546744752796165 -5.52584087074093 C54.63367947785674 -5.264007330025889, 54.72061420291732 -5.002173789310848, 54.86993564858657 -4.552441386096524 M54.86993564858657 -4.552441386096524 C54.9587784565668 -4.213645254551373, 55.04762126454702 -3.8748491230062223, 55.130096594909176 -3.560334943301032 M54.86993564858657 -4.552441386096524 C54.96170025915473 -4.202503154966317, 55.053464869722895 -3.85256492383611, 55.130096594909176 -3.560334943301032 M55.130096594909176 -3.560334943301032 C55.181446563644 -3.2966637066674425, 55.23279653237883 -3.032992470033853, 55.326158534631205 -2.5535983205340735 M55.130096594909176 -3.560334943301032 C55.185170027738394 -3.2775445054971506, 55.24024346056761 -2.9947540676932687, 55.326158534631205 -2.5535983205340735 M55.326158534631205 -2.5535983205340735 C55.35900104656108 -2.298878283493447, 55.39184355849097 -2.0441582464528203, 55.45731580718717 -1.536368414522911 M55.326158534631205 -2.5535983205340735 C55.35818219746586 -2.305229115375974, 55.39020586030052 -2.056859910217874, 55.45731580718717 -1.536368414522911 M55.45731580718717 -1.536368414522911 C55.47269666233285 -1.296799180426115, 55.48807751747853 -1.0572299463293189, 55.523029459211 -0.5128252411464826 M55.45731580718717 -1.536368414522911 C55.48233476613253 -1.1466779340087412, 55.50735372507789 -0.7569874534945714, 55.523029459211 -0.5128252411464826 M55.523029459211 -0.5128252411464826 C55.523029459211 -0.27199889649583253, 55.523029459211 -0.031172551845182417, 55.523029459211 0.5128252411464788 M55.523029459211 -0.5128252411464826 C55.523029459211 -0.11613608119258917, 55.523029459211 0.2805530787613043, 55.523029459211 0.5128252411464788 M55.523029459211 0.5128252411464788 C55.50360798015233 0.8153304542210676, 55.48418650109365 1.1178356672956564, 55.45731580718717 1.5363684145229002 M55.523029459211 0.5128252411464788 C55.50246943987737 0.8330641380166743, 55.481909420543744 1.15330303488687, 55.45731580718717 1.5363684145229002 M55.45731580718717 1.5363684145229002 C55.41100191839049 1.8955697903181614, 55.364688029593815 2.2547711661134224, 55.326158534631205 2.5535983205340624 M55.45731580718717 1.5363684145229002 C55.42164836686328 1.8129980383422426, 55.385980926539396 2.089627662161585, 55.326158534631205 2.5535983205340624 M55.326158534631205 2.5535983205340624 C55.272550521827725 2.8288641362224016, 55.218942509024245 3.104129951910741, 55.130096594909176 3.5603349433010285 M55.326158534631205 2.5535983205340624 C55.28255932417931 2.7774710515081376, 55.238960113727416 3.0013437824822127, 55.130096594909176 3.5603349433010285 M55.130096594909176 3.5603349433010285 C55.03848334274558 3.909695979235468, 54.94687009058199 4.259057015169907, 54.86993564858657 4.552441386096513 M55.130096594909176 3.5603349433010285 C55.04084820192759 3.9006777462380264, 54.951599808946 4.241020549175024, 54.86993564858657 4.552441386096513 M54.86993564858657 4.552441386096513 C54.800224039297625 4.762401646238235, 54.73051243000868 4.972361906379957, 54.546744752796165 5.525840870740919 M54.86993564858657 4.552441386096513 C54.74686160661175 4.92312079133905, 54.623787564636935 5.2938001965815875, 54.546744752796165 5.525840870740919 M54.546744752796165 5.525840870740919 C54.46457976959589 5.72878996779748, 54.38241478639562 5.9317390648540425, 54.161851968253 6.4765334899583005 M54.546744752796165 5.525840870740919 C54.40905137208789 5.865946183210787, 54.27135799137961 6.206051495680655, 54.161851968253 6.4765334899583005 M54.161851968253 6.4765334899583005 C53.985823469686316 6.842060433638529, 53.80979497111963 7.207587377318756, 53.716838901968 7.400612643853361 M54.161851968253 6.4765334899583005 C53.99228418056564 6.8286446292605385, 53.822716392878284 7.1807557685627765, 53.716838901968 7.400612643853361 M53.716838901968 7.400612643853361 C53.57216745829893 7.657491441660026, 53.427496014629845 7.914370239466692, 53.21353420808554 8.294281092968399 M53.716838901968 7.400612643853361 C53.53402902868326 7.72521008537742, 53.35121915539851 8.04980752690148, 53.21353420808554 8.294281092968399 M53.21353420808554 8.294281092968399 C53.070420418263 8.514142305569298, 52.92730662844046 8.734003518170194, 52.6540060735513 9.15386656195471 M53.21353420808554 8.294281092968399 C53.05639396478906 8.535690704735408, 52.89925372149258 8.777100316502416, 52.6540060735513 9.15386656195471 M52.6540060735513 9.15386656195471 C52.45532663015897 9.420078916030786, 52.256647186766635 9.686291270106862, 52.04055371948848 9.975836829739734 M52.6540060735513 9.15386656195471 C52.43911354430838 9.441802974028068, 52.22422101506546 9.729739386101429, 52.04055371948848 9.975836829739734 M52.04055371948848 9.975836829739734 C51.87661829001979 10.168404713383845, 51.71268286055111 10.360972597027954, 51.375697953205055 10.756814244181063 M52.04055371948848 9.975836829739734 C51.78809745841248 10.272386319167804, 51.53564119733648 10.568935808595874, 51.375697953205055 10.756814244181063 M51.375697953205055 10.756814244181063 C51.1779587925007 10.960996162295332, 50.98021963179634 11.1651780804096, 50.662170809655784 11.493589601563638 M51.375697953205055 10.756814244181063 C51.16013082260237 10.979405004918904, 50.94456369199968 11.201995765656745, 50.662170809655784 11.493589601563638 M50.662170809655784 11.493589601563638 C50.442949520219 11.692680576352652, 50.22372823078222 11.891771551141664, 49.90290432492463 12.183135333906142 M50.662170809655784 11.493589601563638 C50.44126277369752 11.694212434914599, 50.22035473773924 11.89483526826556, 49.90290432492463 12.183135333906142 M49.90290432492463 12.183135333906142 C49.649770359497985 12.38500293515617, 49.396636394071336 12.586870536406199, 49.10101848785946 12.822617949887304 M49.90290432492463 12.183135333906142 C49.6071385006172 12.419000708132184, 49.31137267630977 12.654866082358229, 49.10101848785946 12.822617949887304 M49.10101848785946 12.822617949887304 C48.85275941180182 12.995792734382924, 48.60450033574418 13.168967518878544, 48.25980841936879 13.409409678269446 M49.10101848785946 12.822617949887304 C48.86912276306894 12.984378368897044, 48.637227038278404 13.146138787906784, 48.25980841936879 13.409409678269446 M48.25980841936879 13.409409678269446 C48.025191144933366 13.551636048796345, 47.79057387049794 13.693862419323246, 47.382730832063004 13.94109926597423 M48.25980841936879 13.409409678269446 C47.95071246839683 13.596785460198076, 47.64161651742487 13.784161242126707, 47.382730832063004 13.94109926597423 M47.382730832063004 13.94109926597423 C47.19032713874031 14.041476149540234, 46.99792344541761 14.141853033106235, 46.47338982588093 14.415501886438705 M47.382730832063004 13.94109926597423 C47.126417980571354 14.074817516421207, 46.870105129079704 14.208535766868184, 46.47338982588093 14.415501886438705 M46.47338982588093 14.415501886438705 C46.163147475141535 14.552836972098685, 45.852905124402135 14.690172057758666, 45.535522078069995 14.830668117536346 M46.47338982588093 14.415501886438705 C46.26181809069744 14.5091584175519, 46.050246355513956 14.602814948665095, 45.535522078069995 14.830668117536346 M45.535522078069995 14.830668117536346 C45.27315290627601 14.927222398070569, 45.010783734482025 15.023776678604793, 44.57298148837794 15.184891952170695 M45.535522078069995 14.830668117536346 C45.28247435274312 14.923792019604166, 45.02942662741625 15.016915921671988, 44.57298148837794 15.184891952170695 M44.57298148837794 15.184891952170695 C44.276406055709366 15.272913983830515, 43.97983062304078 15.360936015490337, 43.58972334255213 15.476717808624468 M44.57298148837794 15.184891952170695 C44.28085766094578 15.2715927707633, 43.98873383351362 15.358293589355906, 43.58972334255213 15.476717808624468 M43.58972334255213 15.476717808624468 C43.38570165463467 15.523284427525692, 43.18167996671722 15.569851046426914, 42.58978805922196 15.704946511857045 M43.58972334255213 15.476717808624468 C43.272520579574206 15.549117269332704, 42.95531781659628 15.621516730040943, 42.58978805922196 15.704946511857045 M42.58978805922196 15.704946511857045 C42.22644493243745 15.763689010827532, 41.863101805652946 15.82243150979802, 41.5772845869521 15.868640221171937 M42.58978805922196 15.704946511857045 C42.24643482050046 15.760457200749402, 41.90308158177897 15.815967889641758, 41.5772845869521 15.868640221171937 M41.5772845869521 15.868640221171937 C41.28361592331781 15.896970083964495, 40.98994725968351 15.925299946757056, 40.556373519691405 15.967126284005381 M41.5772845869521 15.868640221171937 C41.21682596203106 15.903413231203148, 40.85636733711001 15.93818624123436, 40.556373519691405 15.967126284005381 M40.556373519691405 15.967126284005381 C40.21298666384262 15.978138032110484, 39.869599807993836 15.989149780215588, 39.53125 16 M40.556373519691405 15.967126284005381 C40.24218553773662 15.977201681056863, 39.927997555781836 15.987277078108345, 39.53125 16 M39.53125 16 C39.53125 16, 39.53125 16, 39.53125 16 M39.53125 16 C39.53125 16, 39.53125 16, 39.53125 16 M39.53125 16 C12.151233391834303 16, -15.228783216331394 16, -39.53125 16 M39.53125 16 C9.273116365290598 16, -20.985017269418805 16, -39.53125 16 M-39.53125 16 C-39.82358186257768 15.990625486156585, -40.115913725155366 15.981250972313171, -40.5563735196914 15.967126284005381 M-39.53125 16 C-39.90203561234326 15.988109627102563, -40.272821224686524 15.976219254205127, -40.5563735196914 15.967126284005381 M-40.5563735196914 15.967126284005381 C-40.83043495022994 15.940687907408421, -41.104496380768495 15.91424953081146, -41.577284586952096 15.868640221171937 M-40.5563735196914 15.967126284005381 C-40.7735487032709 15.94617565523684, -40.99072388685039 15.925225026468297, -41.577284586952096 15.868640221171937 M-41.577284586952096 15.868640221171937 C-41.85855050062964 15.82316732949829, -42.139816414307184 15.777694437824643, -42.58978805922196 15.704946511857045 M-41.577284586952096 15.868640221171937 C-41.84907891072642 15.824698622700565, -42.12087323450074 15.780757024229194, -42.58978805922196 15.704946511857045 M-42.58978805922196 15.704946511857045 C-42.93232053846506 15.626765708703127, -43.27485301770816 15.54858490554921, -43.58972334255211 15.476717808624471 M-42.58978805922196 15.704946511857045 C-42.97776174500112 15.616394049842857, -43.36573543078028 15.527841587828668, -43.58972334255211 15.476717808624471 M-43.58972334255211 15.476717808624471 C-43.86709261863751 15.394396063423368, -44.144461894722895 15.312074318222265, -44.57298148837792 15.184891952170702 M-43.58972334255211 15.476717808624471 C-43.87269326607156 15.39273382066334, -44.155663189591 15.308749832702206, -44.57298148837792 15.184891952170702 M-44.57298148837792 15.184891952170702 C-44.8131795414124 15.09649684828755, -45.053377594446886 15.008101744404398, -45.53552207806999 14.830668117536348 M-44.57298148837792 15.184891952170702 C-44.77931947083822 15.108957667257911, -44.985657453298515 15.033023382345121, -45.53552207806999 14.830668117536348 M-45.53552207806999 14.830668117536348 C-45.819481225865985 14.704967826155897, -46.10344037366199 14.579267534775445, -46.47338982588093 14.415501886438708 M-45.53552207806999 14.830668117536348 C-45.86332535195582 14.685559332125717, -46.191128625841664 14.540450546715086, -46.47338982588093 14.415501886438708 M-46.47338982588093 14.415501886438708 C-46.80267947483156 14.243711687501252, -47.131969123782184 14.071921488563794, -47.382730832063 13.941099265974234 M-46.47338982588093 14.415501886438708 C-46.820276856212516 14.234531144906466, -47.1671638865441 14.053560403374224, -47.382730832063 13.941099265974234 M-47.382730832063 13.941099265974234 C-47.71112093824837 13.742027253770189, -48.03951104443374 13.542955241566144, -48.25980841936877 13.409409678269457 M-47.382730832063 13.941099265974234 C-47.68395560129354 13.758495040673445, -47.98518037052409 13.575890815372654, -48.25980841936877 13.409409678269457 M-48.25980841936877 13.409409678269457 C-48.436792941119506 13.285952937432606, -48.613777462870246 13.162496196595756, -49.101018487859456 12.822617949887308 M-48.25980841936877 13.409409678269457 C-48.45285239574785 13.27475055708646, -48.645896372126934 13.140091435903463, -49.101018487859456 12.822617949887308 M-49.101018487859456 12.822617949887308 C-49.35765500799691 12.617957154462307, -49.61429152813436 12.413296359037306, -49.90290432492461 12.183135333906154 M-49.101018487859456 12.822617949887308 C-49.33568056423975 12.635481188594133, -49.57034264062005 12.448344427300956, -49.90290432492461 12.183135333906154 M-49.90290432492461 12.183135333906154 C-50.11290927276863 11.992414396700651, -50.32291422061266 11.801693459495146, -50.66217080965578 11.493589601563649 M-49.90290432492461 12.183135333906154 C-50.102540317768955 12.001831207283843, -50.3021763106133 11.820527080661531, -50.66217080965578 11.493589601563649 M-50.66217080965578 11.493589601563649 C-50.807705400711036 11.34331318768695, -50.9532399917663 11.193036773810253, -51.37569795320505 10.756814244181069 M-50.66217080965578 11.493589601563649 C-50.908114975102514 11.239632058348384, -51.15405914054924 10.985674515133121, -51.37569795320505 10.756814244181069 M-51.37569795320505 10.756814244181069 C-51.550543321055535 10.551430926120611, -51.72538868890602 10.346047608060152, -52.04055371948847 9.97583682973974 M-51.37569795320505 10.756814244181069 C-51.59107305980151 10.503822388782122, -51.80644816639797 10.250830533383178, -52.04055371948847 9.97583682973974 M-52.04055371948847 9.97583682973974 C-52.260946693336564 9.680530322996265, -52.48133966718465 9.385223816252791, -52.65400607355129 9.15386656195472 M-52.04055371948847 9.97583682973974 C-52.2529426613996 9.691254996609478, -52.46533160331074 9.406673163479217, -52.65400607355129 9.15386656195472 M-52.65400607355129 9.15386656195472 C-52.79762982894551 8.93322190529079, -52.941253584339734 8.712577248626861, -53.213534208085534 8.29428109296841 M-52.65400607355129 9.15386656195472 C-52.79559422272951 8.936349143075368, -52.93718237190774 8.718831724196018, -53.213534208085534 8.29428109296841 M-53.213534208085534 8.29428109296841 C-53.37632061518061 8.005237343259934, -53.53910702227569 7.7161935935514565, -53.716838901968 7.400612643853366 M-53.213534208085534 8.29428109296841 C-53.41166757826104 7.942475231042498, -53.60980094843654 7.590669369116586, -53.716838901968 7.400612643853366 M-53.716838901968 7.400612643853366 C-53.86284592648424 7.09742593339554, -54.00885295100047 6.794239222937713, -54.161851968252996 6.476533489958307 M-53.716838901968 7.400612643853366 C-53.87966523471341 7.06250027998212, -54.04249156745882 6.724387916110874, -54.161851968252996 6.476533489958307 M-54.161851968252996 6.476533489958307 C-54.28976359916383 6.160589288605411, -54.41767523007466 5.844645087252516, -54.546744752796165 5.525840870740931 M-54.161851968252996 6.476533489958307 C-54.27842380451375 6.18859880063112, -54.3949956407745 5.900664111303933, -54.546744752796165 5.525840870740931 M-54.546744752796165 5.525840870740931 C-54.64381478968793 5.233481385632982, -54.740884826579695 4.941121900525033, -54.86993564858657 4.552441386096519 M-54.546744752796165 5.525840870740931 C-54.63729770062848 5.253109819522927, -54.72785064846079 4.980378768304922, -54.86993564858657 4.552441386096519 M-54.86993564858657 4.552441386096519 C-54.9560843117245 4.223919196484801, -55.04223297486243 3.8953970068730834, -55.130096594909176 3.5603349433010343 M-54.86993564858657 4.552441386096519 C-54.962547979435975 4.199270430129638, -55.05516031028538 3.8460994741627568, -55.130096594909176 3.5603349433010343 M-55.130096594909176 3.5603349433010343 C-55.2084217704773 3.158151720790441, -55.286746946045426 2.755968498279848, -55.326158534631205 2.5535983205340753 M-55.130096594909176 3.5603349433010343 C-55.20549330941526 3.1731887494135727, -55.28089002392134 2.786042555526111, -55.326158534631205 2.5535983205340753 M-55.326158534631205 2.5535983205340753 C-55.378330829857845 2.1489603013412317, -55.430503125084485 1.7443222821483886, -55.45731580718717 1.5363684145229202 M-55.326158534631205 2.5535983205340753 C-55.35610076217804 2.3213723164424382, -55.38604298972487 2.089146312350801, -55.45731580718717 1.5363684145229202 M-55.45731580718717 1.5363684145229202 C-55.481165681624105 1.1648873688955366, -55.50501555606103 0.793406323268153, -55.523029459211 0.5128252411464846 M-55.45731580718717 1.5363684145229202 C-55.47510256873979 1.2593252461253055, -55.492889330292414 0.9822820777276907, -55.523029459211 0.5128252411464846 M-55.523029459211 0.5128252411464846 C-55.523029459211 0.2897090881257104, -55.523029459211 0.06659293510493608, -55.523029459211 -0.5128252411464769 M-55.523029459211 0.5128252411464846 C-55.523029459211 0.1757125646307685, -55.523029459211 -0.16140011188494763, -55.523029459211 -0.5128252411464769 M-55.523029459211 -0.5128252411464769 C-55.497631321483524 -0.9084217372597736, -55.472233183756046 -1.3040182333730703, -55.45731580718717 -1.5363684145228982 M-55.523029459211 -0.5128252411464769 C-55.497077191336714 -0.9170527615821402, -55.471124923462426 -1.3212802820178036, -55.45731580718717 -1.5363684145228982 M-55.45731580718717 -1.5363684145228982 C-55.41145053147598 -1.8920904358158062, -55.365585255764785 -2.247812457108714, -55.326158534631205 -2.5535983205340678 M-55.45731580718717 -1.5363684145228982 C-55.42724015032773 -1.7696292700145597, -55.39716449346828 -2.0028901255062213, -55.326158534631205 -2.5535983205340678 M-55.326158534631205 -2.5535983205340678 C-55.25647457717217 -2.9114107143765846, -55.186790619713136 -3.2692231082191014, -55.130096594909176 -3.5603349433010267 M-55.326158534631205 -2.5535983205340678 C-55.26073800812885 -2.889518897490496, -55.19531748162649 -3.225439474446924, -55.130096594909176 -3.5603349433010267 M-55.130096594909176 -3.5603349433010267 C-55.02652795953321 -3.9552870369200916, -54.922959324157254 -4.350239130539157, -54.869935648586576 -4.552441386096511 M-55.130096594909176 -3.5603349433010267 C-55.03301738743268 -3.9305400358035927, -54.93593817995618 -4.300745128306159, -54.869935648586576 -4.552441386096511 M-54.869935648586576 -4.552441386096511 C-54.769532791453685 -4.854838794757937, -54.66912993432079 -5.157236203419362, -54.54674475279617 -5.525840870740911 M-54.869935648586576 -4.552441386096511 C-54.76795804519213 -4.859581679595993, -54.665980441797686 -5.166721973095475, -54.54674475279617 -5.525840870740911 M-54.54674475279617 -5.525840870740911 C-54.42501570417721 -5.826513974300796, -54.30328665555825 -6.127187077860682, -54.161851968253 -6.476533489958299 M-54.54674475279617 -5.525840870740911 C-54.46045325705742 -5.738982533548221, -54.37416176131865 -5.95212419635553, -54.161851968253 -6.476533489958299 M-54.161851968253 -6.476533489958299 C-53.99962768892751 -6.813395677021211, -53.83740340960202 -7.150257864084125, -53.716838901968 -7.400612643853359 M-54.161851968253 -6.476533489958299 C-54.0237197952077 -6.763367902841911, -53.88558762216239 -7.050202315725523, -53.716838901968 -7.400612643853359 M-53.716838901968 -7.400612643853359 C-53.57982228156306 -7.643899527819645, -53.44280566115812 -7.8871864117859305, -53.213534208085534 -8.294281092968404 M-53.716838901968 -7.400612643853359 C-53.563603975475246 -7.67269677256013, -53.41036904898249 -7.944780901266902, -53.213534208085534 -8.294281092968404 M-53.213534208085534 -8.294281092968404 C-53.074624679726355 -8.507683430959299, -52.93571515136718 -8.721085768950193, -52.654006073551294 -9.153866561954715 M-53.213534208085534 -8.294281092968404 C-53.03484762970024 -8.568791661432925, -52.856161051314935 -8.843302229897445, -52.654006073551294 -9.153866561954715 M-52.654006073551294 -9.153866561954715 C-52.44385845676507 -9.435445223606518, -52.23371083997885 -9.717023885258321, -52.04055371948848 -9.975836829739734 M-52.654006073551294 -9.153866561954715 C-52.48286534148441 -9.383179551682906, -52.311724609417524 -9.612492541411095, -52.04055371948848 -9.975836829739734 M-52.04055371948848 -9.975836829739734 C-51.788799843050796 -10.27156125820482, -51.537045966613114 -10.567285686669907, -51.375697953205055 -10.756814244181063 M-52.04055371948848 -9.975836829739734 C-51.88561971874809 -10.157831123003788, -51.73068571800769 -10.339825416267841, -51.375697953205055 -10.756814244181063 M-51.375697953205055 -10.756814244181063 C-51.17417873733565 -10.964899379601542, -50.97265952146625 -11.17298451502202, -50.66217080965579 -11.493589601563633 M-51.375697953205055 -10.756814244181063 C-51.17624292513624 -10.962767936224461, -50.976787897067425 -11.168721628267859, -50.66217080965579 -11.493589601563633 M-50.66217080965579 -11.493589601563633 C-50.37795031380478 -11.751711135833288, -50.09372981795377 -12.009832670102943, -49.90290432492463 -12.18313533390614 M-50.66217080965579 -11.493589601563633 C-50.39866433986851 -11.732899205425303, -50.13515787008124 -11.972208809286974, -49.90290432492463 -12.18313533390614 M-49.90290432492463 -12.18313533390614 C-49.71496974561956 -12.333008159752739, -49.5270351663145 -12.482880985599335, -49.10101848785946 -12.822617949887302 M-49.90290432492463 -12.18313533390614 C-49.639238918008935 -12.393401479490253, -49.37557351109325 -12.603667625074367, -49.10101848785946 -12.822617949887302 M-49.10101848785946 -12.822617949887302 C-48.77576855814515 -13.049498221013472, -48.45051862843085 -13.276378492139642, -48.25980841936879 -13.409409678269444 M-49.10101848785946 -12.822617949887302 C-48.824671976049665 -13.015385313678129, -48.548325464239866 -13.208152677468954, -48.25980841936879 -13.409409678269444 M-48.25980841936879 -13.409409678269444 C-47.91346831634812 -13.619363084040934, -47.56712821332746 -13.829316489812422, -47.382730832063004 -13.941099265974229 M-48.25980841936879 -13.409409678269444 C-48.07808712645132 -13.519570193948864, -47.896365833533864 -13.629730709628284, -47.382730832063004 -13.941099265974229 M-47.382730832063004 -13.941099265974229 C-47.14819616501878 -14.063455851544578, -46.91366149797456 -14.185812437114926, -46.473389825880936 -14.415501886438705 M-47.382730832063004 -13.941099265974229 C-47.1802837684803 -14.046715769371794, -46.97783670489759 -14.15233227276936, -46.473389825880936 -14.415501886438705 M-46.473389825880936 -14.415501886438705 C-46.106146594486916 -14.578069571093438, -45.738903363092895 -14.74063725574817, -45.535522078069995 -14.830668117536344 M-46.473389825880936 -14.415501886438705 C-46.24040709969826 -14.518636428132757, -46.00742437351558 -14.62177096982681, -45.535522078069995 -14.830668117536344 M-45.535522078069995 -14.830668117536344 C-45.19513137485972 -14.955935042854893, -44.85474067164945 -15.08120196817344, -44.57298148837794 -15.184891952170695 M-45.535522078069995 -14.830668117536344 C-45.20691450711965 -14.951598741261158, -44.87830693616931 -15.072529364985972, -44.57298148837794 -15.184891952170695 M-44.57298148837794 -15.184891952170695 C-44.26658819614051 -15.275827873015553, -43.96019490390308 -15.366763793860413, -43.58972334255213 -15.476717808624466 M-44.57298148837794 -15.184891952170695 C-44.21734153475591 -15.290444023613501, -43.861701581133886 -15.39599609505631, -43.58972334255213 -15.476717808624466 M-43.58972334255213 -15.476717808624466 C-43.223340274801174 -15.560342352965668, -42.856957207050215 -15.643966897306868, -42.589788059221966 -15.704946511857043 M-43.58972334255213 -15.476717808624466 C-43.331240597311236 -15.535714808468152, -43.072757852070346 -15.594711808311837, -42.589788059221966 -15.704946511857043 M-42.589788059221966 -15.704946511857043 C-42.29181561915397 -15.753120385156452, -41.99384317908597 -15.801294258455862, -41.5772845869521 -15.868640221171937 M-42.589788059221966 -15.704946511857043 C-42.20279805981602 -15.76751205380873, -41.81580806041007 -15.830077595760416, -41.5772845869521 -15.868640221171937 M-41.5772845869521 -15.868640221171937 C-41.25679209967208 -15.899557745971231, -40.936299612392055 -15.930475270770527, -40.556373519691405 -15.967126284005381 M-41.5772845869521 -15.868640221171937 C-41.35446004174257 -15.890135837062578, -41.13163549653303 -15.911631452953218, -40.556373519691405 -15.967126284005381 M-40.556373519691405 -15.967126284005381 C-40.228123660454656 -15.977652618091513, -39.89987380121791 -15.988178952177645, -39.53125000000001 -16 M-40.556373519691405 -15.967126284005381 C-40.23202489677309 -15.977527513036076, -39.907676273854776 -15.98792874206677, -39.53125000000001 -16 M-39.53125000000001 -16 C-39.53125000000001 -16, -39.53125 -16, -39.53125 -16 M-39.53125000000001 -16 C-39.53125000000001 -16, -39.53125 -16, -39.53125 -16" stroke="#6b7280" stroke-width="1.3" fill="none" stroke-dasharray="0 0" style="fill:#f3f4f6 !important;stroke:#6b7280 !important"></path></g><g class="label" style="color:#111 !important" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style="fill:#111 !important"><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Signal</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> users</tspan></tspan></text></g></g></g><g class="node default ext" id="g1069-flowchart-tgusers-1" data-look="classic" transform="translate(78.18709564208984, 365.7333399454752)"><g class="basic label-container outer-path"><path d="M-50.1953125 -16 C-13.779073118692743 -16, 22.637166262614514 -16, 50.1953125 -16 C50.1953125 -16, 50.1953125 -16, 50.1953125 -16 C50.51537949691282 -15.989736074381621, 50.835446493825636 -15.979472148763245, 51.220436019691405 -15.967126284005381 C51.493602135727684 -15.940774277321681, 51.76676825176396 -15.914422270637981, 52.241347086952096 -15.868640221171939 C52.58673238579796 -15.812801004557535, 52.93211768464382 -15.756961787943133, 53.25385055922195 -15.704946511857047 C53.48913548637211 -15.65124426261266, 53.72442041352227 -15.597542013368276, 54.25378584255211 -15.476717808624471 C54.459794280862376 -15.415575585494345, 54.66580271917264 -15.354433362364219, 55.237043988377934 -15.184891952170698 C55.55181312181775 -15.069054001370871, 55.866582255257576 -14.953216050571044, 56.19958457806999 -14.830668117536348 C56.40075711102136 -14.741615004769935, 56.601929643972746 -14.65256189200352, 57.13745232588093 -14.415501886438706 C57.352735153008126 -14.303188973421681, 57.568017980135316 -14.190876060404657, 58.046793332063004 -13.941099265974232 C58.31281501922462 -13.7798353558999, 58.57883670638624 -13.618571445825568, 58.92387091936878 -13.409409678269451 C59.21025686732906 -13.20963923842024, 59.49664281528933 -13.009868798571027, 59.765080987859456 -12.822617949887306 C59.94494137531096 -12.679184077180654, 60.12480176276246 -12.535750204474002, 60.56696682492461 -12.183135333906153 C60.82010644692749 -11.953240626910516, 61.07324606893037 -11.72334591991488, 61.326233309655784 -11.493589601563642 C61.562339352705635 -11.249790727448032, 61.798445395755486 -11.005991853332421, 62.03976045320505 -10.756814244181072 C62.23932859565072 -10.522390148315388, 62.43889673809639 -10.287966052449706, 62.70461621948848 -9.975836829739738 C62.87507295069422 -9.747440338851723, 63.04552968189995 -9.519043847963706, 63.31806857355129 -9.153866561954718 C63.541051562250175 -8.811304811996864, 63.76403455094906 -8.46874306203901, 63.877596708085534 -8.294281092968403 C64.0597868297115 -7.970784083271172, 64.24197695133746 -7.647287073573942, 64.380901401968 -7.400612643853364 C64.52568703252328 -7.09996218408911, 64.67047266307857 -6.799311724324855, 64.825914468253 -6.476533489958305 C64.93809028274173 -6.199457059399335, 65.05026609723043 -5.922380628840365, 65.21080725279616 -5.52584087074093 C65.29929320927364 -5.259335268153313, 65.38777916575113 -4.992829665565695, 65.53399814858656 -4.552441386096524 C65.61129820192946 -4.257662780645052, 65.68859825527234 -3.9628841751935813, 65.79415909490918 -3.560334943301032 C65.8397749143428 -3.326107351416257, 65.88539073377642 -3.091879759531482, 65.9902210346312 -2.5535983205340735 C66.0194289529132 -2.327067474094685, 66.04863687119521 -2.1005366276552966, 66.12137830718717 -1.536368414522911 C66.14325439948188 -1.195630618969103, 66.16513049177657 -0.854892823415295, 66.187091959211 -0.5128252411464826 C66.187091959211 -0.19393656417055394, 66.187091959211 0.12495211280537477, 66.187091959211 0.5128252411464788 C66.1706215049775 0.7693658605446669, 66.15415105074399 1.0259064799428552, 66.12137830718717 1.5363684145229002 C66.08689537741469 1.803811208413542, 66.05241244764223 2.071254002304184, 65.9902210346312 2.5535983205340624 C65.93981295872025 2.8124331365861504, 65.88940488280932 3.0712679526382387, 65.79415909490918 3.5603349433010285 C65.72632163791893 3.8190285677446973, 65.65848418092868 4.077722192188366, 65.53399814858658 4.552441386096513 C65.43125183549165 4.861896910736589, 65.32850552239672 5.171352435376665, 65.21080725279617 5.525840870740919 C65.12674969614007 5.733464660823814, 65.04269213948395 5.941088450906709, 64.825914468253 6.4765334899583005 C64.65112269956755 6.83949233757837, 64.4763309308821 7.202451185198438, 64.380901401968 7.400612643853361 C64.2466784690256 7.638939052838379, 64.11245553608319 7.877265461823397, 63.87759670808554 8.294281092968399 C63.670837455432974 8.611918827675979, 63.464078202780414 8.929556562383558, 63.3180685735513 9.15386656195471 C63.17861164096585 9.340726146831292, 63.0391547083804 9.527585731707875, 62.70461621948848 9.975836829739734 C62.52379436438093 10.18824046980409, 62.34297250927339 10.400644109868445, 62.039760453205055 10.756814244181063 C61.82188889218045 10.981784518526784, 61.60401733115586 11.206754792872506, 61.326233309655784 11.493589601563638 C61.11565516320848 11.684831102574638, 60.90507701676118 11.876072603585635, 60.56696682492463 12.183135333906142 C60.39666203591388 12.318948871141448, 60.22635724690313 12.454762408376753, 59.76508098785946 12.822617949887304 C59.45618040735887 13.038093622753907, 59.14727982685828 13.25356929562051, 58.92387091936879 13.409409678269446 C58.714873075311125 13.536105399544862, 58.50587523125346 13.66280112082028, 58.046793332063004 13.94109926597423 C57.83234577924679 14.052976416918234, 57.61789822643058 14.164853567862238, 57.13745232588093 14.415501886438705 C56.83559290022206 14.549126099836174, 56.533733474563185 14.682750313233644, 56.199584578069995 14.830668117536346 C55.974452278552526 14.91351888485894, 55.74931997903505 14.996369652181532, 55.23704398837794 15.184891952170695 C54.94234536606762 15.272356956367762, 54.647646743757306 15.35982196056483, 54.25378584255213 15.476717808624468 C53.92831889302147 15.55100351598451, 53.602851943490805 15.625289223344552, 53.25385055922196 15.704946511857045 C52.9891129314784 15.747747238439658, 52.724375303734845 15.79054796502227, 52.2413470869521 15.868640221171937 C51.87794903044688 15.90369679463289, 51.51455097394166 15.938753368093844, 51.220436019691405 15.967126284005381 C50.87509278000934 15.978200769532148, 50.52974954032727 15.989275255058914, 50.1953125 16 C50.1953125 16, 50.1953125 16, 50.1953125 16 C28.372116867123385 16, 6.5489212342467695 16, -50.1953125 16 C-50.54346550242734 15.988835410850864, -50.89161850485468 15.977670821701729, -51.2204360196914 15.967126284005381 C-51.479726677855744 15.942112826054908, -51.7390173360201 15.917099368104433, -52.241347086952096 15.868640221171937 C-52.4629251431155 15.832817199414928, -52.68450319927889 15.796994177657918, -53.25385055922196 15.704946511857045 C-53.498366374794955 15.649137372567322, -53.74288219036795 15.593328233277601, -54.25378584255211 15.476717808624471 C-54.51970695067662 15.397793819581498, -54.78562805880113 15.318869830538524, -55.23704398837792 15.184891952170702 C-55.52647738562722 15.078377786489964, -55.81591078287652 14.971863620809227, -56.19958457806999 14.830668117536348 C-56.49377450734926 14.700438962678602, -56.787964436628535 14.570209807820856, -57.13745232588093 14.415501886438708 C-57.425368731226584 14.26529608218914, -57.71328513657224 14.11509027793957, -58.046793332063 13.941099265974234 C-58.23990830314005 13.824031835637788, -58.43302327421709 13.706964405301342, -58.92387091936877 13.409409678269457 C-59.244953839315585 13.18543613277014, -59.56603675926241 12.961462587270823, -59.765080987859456 12.822617949887308 C-60.00275381773034 12.633080192804908, -60.24042664760121 12.443542435722506, -60.56696682492461 12.183135333906154 C-60.749049266364054 12.017772878228259, -60.93113170780349 11.852410422550363, -61.32623330965578 11.493589601563649 C-61.519913880570506 11.293598510623594, -61.71359445148523 11.09360741968354, -62.03976045320505 10.756814244181069 C-62.27540636104848 10.480011152196163, -62.511052268891916 10.203208060211256, -62.70461621948847 9.97583682973974 C-62.86195357500558 9.765019107074773, -63.01929093052269 9.554201384409804, -63.31806857355129 9.15386656195472 C-63.48630851506828 8.895404833034698, -63.654548456585275 8.636943104114678, -63.877596708085534 8.29428109296841 C-64.03075670218348 8.022330014316344, -64.18391669628144 7.750378935664278, -64.380901401968 7.400612643853366 C-64.55427533159583 7.040597969373366, -64.72764926122365 6.680583294893364, -64.825914468253 6.476533489958307 C-64.91311616867422 6.261143603987696, -65.00031786909545 6.045753718017085, -65.21080725279616 5.525840870740931 C-65.30507635234761 5.241917362633255, -65.39934545189905 4.957993854525578, -65.53399814858656 4.552441386096519 C-65.60615287834955 4.277284129452562, -65.67830760811253 4.0021268728086055, -65.79415909490918 3.5603349433010343 C-65.83721893672296 3.3392317562880067, -65.88027877853676 3.118128569274979, -65.9902210346312 2.5535983205340753 C-66.03665510600271 2.1934648324212334, -66.0830891773742 1.8333313443083914, -66.12137830718717 1.5363684145229202 C-66.1403165323608 1.2413902707833735, -66.15925475753444 0.9464121270438268, -66.187091959211 0.5128252411464846 C-66.187091959211 0.13727991295822167, -66.187091959211 -0.2382654152300413, -66.187091959211 -0.5128252411464769 C-66.16654646429932 -0.8328379084211248, -66.14600096938761 -1.1528505756957728, -66.12137830718717 -1.5363684145228982 C-66.08917362617836 -1.7861415608936524, -66.05696894516956 -2.0359147072644066, -65.9902210346312 -2.5535983205340678 C-65.92238683182191 -2.901912615195955, -65.85455262901262 -3.250226909857842, -65.79415909490918 -3.5603349433010267 C-65.70957296831055 -3.8828985038807655, -65.62498684171192 -4.205462064460503, -65.53399814858658 -4.552441386096511 C-65.40548297882478 -4.939508601307458, -65.27696780906298 -5.326575816518406, -65.21080725279617 -5.525840870740911 C-65.12170981990162 -5.74591325257212, -65.03261238700708 -5.965985634403331, -64.825914468253 -6.476533489958299 C-64.6703553504286 -6.799555326552612, -64.51479623260417 -7.122577163146927, -64.380901401968 -7.400612643853359 C-64.22554624264744 -7.676461460642746, -64.07019108332689 -7.952310277432134, -63.877596708085534 -8.294281092968404 C-63.728881455297945 -8.522747656887036, -63.58016620251035 -8.751214220805668, -63.318068573551294 -9.153866561954715 C-63.188169115398786 -9.327920001794986, -63.05826965724628 -9.501973441635258, -62.70461621948848 -9.975836829739734 C-62.47107100782921 -10.250172324453722, -62.23752579616994 -10.524507819167708, -62.039760453205055 -10.756814244181063 C-61.756105987556126 -11.049710768428321, -61.47245152190719 -11.342607292675579, -61.32623330965579 -11.493589601563633 C-61.10902316442086 -11.690854108400481, -60.89181301918594 -11.88811861523733, -60.56696682492463 -12.18313533390614 C-60.39361191815737 -12.321381258885218, -60.22025701139012 -12.459627183864296, -59.76508098785946 -12.822617949887302 C-59.472906439537795 -13.026426266764153, -59.18073189121612 -13.230234583641005, -58.92387091936879 -13.409409678269444 C-58.57916591475379 -13.618371877778515, -58.234460910138786 -13.827334077287585, -58.046793332063004 -13.941099265974229 C-57.731519257727335 -14.105577548612468, -57.416245183391666 -14.270055831250705, -57.137452325880936 -14.415501886438705 C-56.79601170380683 -14.56664752135472, -56.45457108173273 -14.717793156270735, -56.199584578069995 -14.830668117536344 C-55.866238722881825 -14.953342473660898, -55.532892867693654 -15.07601682978545, -55.23704398837794 -15.184891952170695 C-55.003699693634765 -15.254147314001273, -54.77035539889158 -15.32340267583185, -54.25378584255213 -15.476717808624466 C-54.048147923692035 -15.523653321691455, -53.84251000483194 -15.570588834758444, -53.253850559221966 -15.704946511857043 C-53.04315287977748 -15.73901047868472, -52.832455200333 -15.773074445512396, -52.2413470869521 -15.868640221171937 C-51.94572706334077 -15.897158329314628, -51.650107039729434 -15.925676437457318, -51.220436019691405 -15.967126284005381 C-50.9355845910625 -15.97626091489184, -50.6507331624336 -15.985395545778298, -50.19531250000001 -16 C-50.19531250000001 -16, -50.1953125 -16, -50.1953125 -16" stroke="none" stroke-width="0" fill="#f3f4f6" style="fill:#f3f4f6 !important;stroke:#6b7280 !important"></path><path d="M-50.1953125 -16 C-17.22995829966105 -16, 15.7353959006779 -16, 50.1953125 -16 M-50.1953125 -16 C-17.672874107829543 -16, 14.849564284340914 -16, 50.1953125 -16 M50.1953125 -16 C50.1953125 -16, 50.1953125 -16, 50.1953125 -16 M50.1953125 -16 C50.1953125 -16, 50.1953125 -16, 50.1953125 -16 M50.1953125 -16 C50.58137195703254 -15.987619824632114, 50.96743141406507 -15.975239649264228, 51.220436019691405 -15.967126284005381 M50.1953125 -16 C50.47011443623712 -15.991187636774397, 50.74491637247423 -15.982375273548792, 51.220436019691405 -15.967126284005381 M51.220436019691405 -15.967126284005381 C51.47529047337059 -15.942540781366274, 51.73014492704977 -15.917955278727169, 52.241347086952096 -15.868640221171939 M51.220436019691405 -15.967126284005381 C51.59759723722451 -15.93074199495269, 51.97475845475762 -15.894357705900001, 52.241347086952096 -15.868640221171939 M52.241347086952096 -15.868640221171939 C52.60357349354615 -15.810078264861549, 52.96579990014021 -15.751516308551158, 53.25385055922195 -15.704946511857047 M52.241347086952096 -15.868640221171939 C52.48383051294768 -15.829437381344027, 52.72631393894326 -15.790234541516115, 53.25385055922195 -15.704946511857047 M53.25385055922195 -15.704946511857047 C53.49142077837638 -15.650722659625611, 53.7289909975308 -15.596498807394175, 54.25378584255211 -15.476717808624471 M53.25385055922195 -15.704946511857047 C53.51079608618664 -15.646300372053618, 53.76774161315132 -15.587654232250191, 54.25378584255211 -15.476717808624471 M54.25378584255211 -15.476717808624471 C54.63648410507421 -15.363134973132086, 55.01918236759631 -15.249552137639702, 55.237043988377934 -15.184891952170698 M54.25378584255211 -15.476717808624471 C54.50990935121747 -15.400701695672325, 54.766032859882834 -15.324685582720178, 55.237043988377934 -15.184891952170698 M55.237043988377934 -15.184891952170698 C55.51567454072421 -15.082353333274677, 55.79430509307049 -14.979814714378655, 56.19958457806999 -14.830668117536348 M55.237043988377934 -15.184891952170698 C55.43569446351299 -15.111786741016136, 55.63434493864804 -15.038681529861574, 56.19958457806999 -14.830668117536348 M56.19958457806999 -14.830668117536348 C56.52333729047669 -14.687352395536891, 56.8470900028834 -14.544036673537434, 57.13745232588093 -14.415501886438706 M56.19958457806999 -14.830668117536348 C56.5323933438851 -14.68334354933127, 56.865202109700206 -14.536018981126192, 57.13745232588093 -14.415501886438706 M57.13745232588093 -14.415501886438706 C57.48143362512878 -14.23604706295164, 57.82541492437663 -14.056592239464575, 58.046793332063004 -13.941099265974232 M57.13745232588093 -14.415501886438706 C57.41207616676104 -14.272230804556516, 57.68670000764116 -14.128959722674328, 58.046793332063004 -13.941099265974232 M58.046793332063004 -13.941099265974232 C58.269411781696405 -13.806146653555242, 58.49203023132981 -13.671194041136252, 58.92387091936878 -13.409409678269451 M58.046793332063004 -13.941099265974232 C58.28436229266242 -13.797083565948688, 58.52193125326183 -13.653067865923145, 58.92387091936878 -13.409409678269451 M58.92387091936878 -13.409409678269451 C59.19569215787875 -13.21979894923666, 59.467513396388725 -13.030188220203867, 59.765080987859456 -12.822617949887306 M58.92387091936878 -13.409409678269451 C59.183364491089364 -13.228398195932844, 59.44285806280995 -13.047386713596236, 59.765080987859456 -12.822617949887306 M59.765080987859456 -12.822617949887306 C59.97033876932824 -12.658930331304914, 60.17559655079702 -12.495242712722522, 60.56696682492461 -12.183135333906153 M59.765080987859456 -12.822617949887306 C60.05608513634649 -12.59054988541451, 60.34708928483353 -12.358481820941716, 60.56696682492461 -12.183135333906153 M60.56696682492461 -12.183135333906153 C60.79257469697603 -11.97824423376624, 61.01818256902746 -11.773353133626328, 61.326233309655784 -11.493589601563642 M60.56696682492461 -12.183135333906153 C60.816079250360886 -11.956898020278526, 61.06519167579715 -11.730660706650898, 61.326233309655784 -11.493589601563642 M61.326233309655784 -11.493589601563642 C61.56792706164976 -11.244020959203782, 61.80962081364374 -10.994452316843924, 62.03976045320505 -10.756814244181072 M61.326233309655784 -11.493589601563642 C61.55242775844855 -11.260025262275493, 61.77862220724132 -11.026460922987344, 62.03976045320505 -10.756814244181072 M62.03976045320505 -10.756814244181072 C62.2029416422823 -10.565132334218232, 62.366122831359554 -10.373450424255392, 62.70461621948848 -9.975836829739738 M62.03976045320505 -10.756814244181072 C62.196283777168176 -10.572953041424542, 62.352807101131305 -10.38909183866801, 62.70461621948848 -9.975836829739738 M62.70461621948848 -9.975836829739738 C62.82771785655243 -9.810891850863884, 62.950819493616386 -9.645946871988032, 63.31806857355129 -9.153866561954718 M62.70461621948848 -9.975836829739738 C62.94250355291698 -9.657089474927453, 63.18039088634548 -9.338342120115168, 63.31806857355129 -9.153866561954718 M63.31806857355129 -9.153866561954718 C63.514843013618936 -8.851568180675166, 63.711617453686586 -8.549269799395613, 63.877596708085534 -8.294281092968403 M63.31806857355129 -9.153866561954718 C63.43733568753553 -8.970640247170515, 63.55660280151977 -8.787413932386313, 63.877596708085534 -8.294281092968403 M63.877596708085534 -8.294281092968403 C64.00380097930822 -8.0701926298443, 64.1300052505309 -7.846104166720199, 64.380901401968 -7.400612643853364 M63.877596708085534 -8.294281092968403 C64.00216195290744 -8.073102887188295, 64.12672719772935 -7.851924681408186, 64.380901401968 -7.400612643853364 M64.380901401968 -7.400612643853364 C64.5448972182735 -7.06007182234665, 64.708893034579 -6.719531000839935, 64.825914468253 -6.476533489958305 M64.380901401968 -7.400612643853364 C64.47677467869117 -7.201529733378218, 64.57264795541433 -7.002446822903071, 64.825914468253 -6.476533489958305 M64.825914468253 -6.476533489958305 C64.94309176858495 -6.187103292669402, 65.0602690689169 -5.897673095380499, 65.21080725279616 -5.52584087074093 M64.825914468253 -6.476533489958305 C64.95305131002678 -6.162503032753456, 65.08018815180056 -5.848472575548607, 65.21080725279616 -5.52584087074093 M65.21080725279616 -5.52584087074093 C65.33238859613033 -5.159657235974797, 65.45396993946449 -4.793473601208666, 65.53399814858656 -4.552441386096524 M65.21080725279616 -5.52584087074093 C65.33038990039132 -5.165676989091728, 65.4499725479865 -4.805513107442526, 65.53399814858656 -4.552441386096524 M65.53399814858656 -4.552441386096524 C65.60276447545361 -4.2902055782378765, 65.67153080232066 -4.0279697703792285, 65.79415909490918 -3.560334943301032 M65.53399814858656 -4.552441386096524 C65.60422772318543 -4.284625580460894, 65.67445729778429 -4.016809774825265, 65.79415909490918 -3.560334943301032 M65.79415909490918 -3.560334943301032 C65.85981910091795 -3.2231846896932024, 65.92547910692672 -2.8860344360853727, 65.9902210346312 -2.5535983205340735 M65.79415909490918 -3.560334943301032 C65.8385611638318 -3.332339703763936, 65.88296323275443 -3.1043444642268407, 65.9902210346312 -2.5535983205340735 M65.9902210346312 -2.5535983205340735 C66.04079203039873 -2.1613796637338063, 66.09136302616625 -1.769161006933539, 66.12137830718717 -1.536368414522911 M65.9902210346312 -2.5535983205340735 C66.04078732315031 -2.161416172222973, 66.09135361166942 -1.769234023911873, 66.12137830718717 -1.536368414522911 M66.12137830718717 -1.536368414522911 C66.14388783938118 -1.185764281233892, 66.16639737157519 -0.835160147944873, 66.187091959211 -0.5128252411464826 M66.12137830718717 -1.536368414522911 C66.13495453005122 -1.3249077848855695, 66.14853075291526 -1.1134471552482281, 66.187091959211 -0.5128252411464826 M66.187091959211 -0.5128252411464826 C66.187091959211 -0.23099716001236942, 66.187091959211 0.05083092112174381, 66.187091959211 0.5128252411464788 M66.187091959211 -0.5128252411464826 C66.187091959211 -0.22107926515201903, 66.187091959211 0.07066671084244458, 66.187091959211 0.5128252411464788 M66.187091959211 0.5128252411464788 C66.16464250947953 0.8624935415838437, 66.14219305974805 1.2121618420212086, 66.12137830718717 1.5363684145229002 M66.187091959211 0.5128252411464788 C66.16516293386036 0.8543875117735551, 66.1432339085097 1.1959497824006313, 66.12137830718717 1.5363684145229002 M66.12137830718717 1.5363684145229002 C66.09011345929521 1.7788524008304754, 66.05884861140323 2.0213363871380503, 65.9902210346312 2.5535983205340624 M66.12137830718717 1.5363684145229002 C66.09465894050437 1.7435985461788932, 66.06793957382159 1.950828677834886, 65.9902210346312 2.5535983205340624 M65.9902210346312 2.5535983205340624 C65.93962546245344 2.813395890288904, 65.88902989027568 3.073193460043745, 65.79415909490918 3.5603349433010285 M65.9902210346312 2.5535983205340624 C65.9361598422822 2.8311911174091504, 65.8820986499332 3.1087839142842384, 65.79415909490918 3.5603349433010285 M65.79415909490918 3.5603349433010285 C65.72143887876419 3.837648644602903, 65.6487186626192 4.114962345904777, 65.53399814858658 4.552441386096513 M65.79415909490918 3.5603349433010285 C65.70321711615969 3.907136122775737, 65.61227513741021 4.253937302250446, 65.53399814858658 4.552441386096513 M65.53399814858658 4.552441386096513 C65.42676250892936 4.875418047065166, 65.31952686927214 5.198394708033819, 65.21080725279617 5.525840870740919 M65.53399814858658 4.552441386096513 C65.42574136739358 4.878493562674083, 65.3174845862006 5.204545739251654, 65.21080725279617 5.525840870740919 M65.21080725279617 5.525840870740919 C65.08850245504138 5.827936085797678, 64.96619765728657 6.130031300854437, 64.825914468253 6.4765334899583005 M65.21080725279617 5.525840870740919 C65.07047190911548 5.872471882831497, 64.93013656543481 6.2191028949220755, 64.825914468253 6.4765334899583005 M64.825914468253 6.4765334899583005 C64.66659310507876 6.8073677095207, 64.5072717419045 7.1382019290831, 64.380901401968 7.400612643853361 M64.825914468253 6.4765334899583005 C64.69707178972074 6.744078068722237, 64.56822911118847 7.011622647486172, 64.380901401968 7.400612643853361 M64.380901401968 7.400612643853361 C64.2043851678126 7.714035091803204, 64.02786893365719 8.027457539753048, 63.87759670808554 8.294281092968399 M64.380901401968 7.400612643853361 C64.20529320204723 7.71242278507117, 64.02968500212647 8.02423292628898, 63.87759670808554 8.294281092968399 M63.87759670808554 8.294281092968399 C63.753827825573595 8.484423333105271, 63.63005894306164 8.674565573242145, 63.3180685735513 9.15386656195471 M63.87759670808554 8.294281092968399 C63.7259809339884 8.527203636517527, 63.57436515989126 8.760126180066655, 63.3180685735513 9.15386656195471 M63.3180685735513 9.15386656195471 C63.11764076282997 9.422421568972107, 62.917212952108635 9.690976575989504, 62.70461621948848 9.975836829739734 M63.3180685735513 9.15386656195471 C63.083920751597574 9.467603312067299, 62.84977292964384 9.78134006217989, 62.70461621948848 9.975836829739734 M62.70461621948848 9.975836829739734 C62.46621591251068 10.255875395677622, 62.22781560553287 10.535913961615508, 62.039760453205055 10.756814244181063 M62.70461621948848 9.975836829739734 C62.565340285885895 10.139438266374457, 62.42606435228331 10.30303970300918, 62.039760453205055 10.756814244181063 M62.039760453205055 10.756814244181063 C61.80953019685301 10.99454588612013, 61.57929994050096 11.2322775280592, 61.326233309655784 11.493589601563638 M62.039760453205055 10.756814244181063 C61.84058327702176 10.962481031340602, 61.64140610083846 11.168147818500138, 61.326233309655784 11.493589601563638 M61.326233309655784 11.493589601563638 C61.03505061766376 11.75803401815895, 60.74386792567173 12.022478434754264, 60.56696682492463 12.183135333906142 M61.326233309655784 11.493589601563638 C61.16937525014768 11.636043940972067, 61.012517190639585 11.778498280380498, 60.56696682492463 12.183135333906142 M60.56696682492463 12.183135333906142 C60.39073811027136 12.323673044199076, 60.21450939561809 12.46421075449201, 59.76508098785946 12.822617949887304 M60.56696682492463 12.183135333906142 C60.32747330267199 12.374125044712338, 60.087979780419346 12.565114755518534, 59.76508098785946 12.822617949887304 M59.76508098785946 12.822617949887304 C59.55665631507975 12.968005979059766, 59.348231642300036 13.113394008232229, 58.92387091936879 13.409409678269446 M59.76508098785946 12.822617949887304 C59.57902052648005 12.95240567331802, 59.392960065100645 13.082193396748739, 58.92387091936879 13.409409678269446 M58.92387091936879 13.409409678269446 C58.702735709266705 13.54346314216807, 58.48160049916462 13.677516606066693, 58.046793332063004 13.94109926597423 M58.92387091936879 13.409409678269446 C58.65165746635337 13.574427073191206, 58.37944401333795 13.739444468112964, 58.046793332063004 13.94109926597423 M58.046793332063004 13.94109926597423 C57.838680712555984 14.049671486268549, 57.63056809304896 14.15824370656287, 57.13745232588093 14.415501886438705 M58.046793332063004 13.94109926597423 C57.81276119321273 14.06319368290768, 57.578729054362455 14.185288099841129, 57.13745232588093 14.415501886438705 M57.13745232588093 14.415501886438705 C56.94181227200117 14.50210593483527, 56.74617221812142 14.588709983231839, 56.199584578069995 14.830668117536346 M57.13745232588093 14.415501886438705 C56.91105488377427 14.515721318217816, 56.68465744166762 14.615940749996929, 56.199584578069995 14.830668117536346 M56.199584578069995 14.830668117536346 C55.9971336453999 14.905171932194847, 55.79468271272981 14.979675746853347, 55.23704398837794 15.184891952170695 M56.199584578069995 14.830668117536346 C55.93056551213361 14.929669620585921, 55.66154644619723 15.028671123635494, 55.23704398837794 15.184891952170695 M55.23704398837794 15.184891952170695 C54.99330966466762 15.257231020060345, 54.74957534095731 15.329570087949994, 54.25378584255213 15.476717808624468 M55.23704398837794 15.184891952170695 C54.93778056264833 15.273711766061467, 54.638517136918715 15.36253157995224, 54.25378584255213 15.476717808624468 M54.25378584255213 15.476717808624468 C53.88914192679285 15.559945402872595, 53.52449801103358 15.64317299712072, 53.25385055922196 15.704946511857045 M54.25378584255213 15.476717808624468 C53.9906475812395 15.536777399631447, 53.72750931992687 15.596836990638424, 53.25385055922196 15.704946511857045 M53.25385055922196 15.704946511857045 C52.993782653952266 15.746992273924322, 52.73371474868258 15.789038035991597, 52.2413470869521 15.868640221171937 M53.25385055922196 15.704946511857045 C52.94438807670643 15.754978006112761, 52.63492559419091 15.805009500368476, 52.2413470869521 15.868640221171937 M52.2413470869521 15.868640221171937 C51.913443933280064 15.90027264404544, 51.58554077960802 15.931905066918942, 51.220436019691405 15.967126284005381 M52.2413470869521 15.868640221171937 C51.83666297701598 15.907679610553625, 51.431978867079856 15.946718999935314, 51.220436019691405 15.967126284005381 M51.220436019691405 15.967126284005381 C50.87382161202933 15.978241533415087, 50.52720720436726 15.989356782824794, 50.1953125 16 M51.220436019691405 15.967126284005381 C50.91360456886574 15.976965771422172, 50.60677311804009 15.986805258838963, 50.1953125 16 M50.1953125 16 C50.1953125 16, 50.1953125 16, 50.1953125 16 M50.1953125 16 C50.1953125 16, 50.1953125 16, 50.1953125 16 M50.1953125 16 C28.14324886950841 16, 6.0911852390168235 16, -50.1953125 16 M50.1953125 16 C17.664259753101383 16, -14.866792993797233 16, -50.1953125 16 M-50.1953125 16 C-50.442730219944245 15.992065795290765, -50.69014793988849 15.98413159058153, -51.2204360196914 15.967126284005381 M-50.1953125 16 C-50.457136360076916 15.99160381841656, -50.71896022015383 15.983207636833122, -51.2204360196914 15.967126284005381 M-51.2204360196914 15.967126284005381 C-51.60826165739686 15.929713211164506, -51.99608729510231 15.89230013832363, -52.241347086952096 15.868640221171937 M-51.2204360196914 15.967126284005381 C-51.523816321667006 15.93785955114199, -51.827196623642614 15.908592818278597, -52.241347086952096 15.868640221171937 M-52.241347086952096 15.868640221171937 C-52.55691837520368 15.817621102579313, -52.872489663455255 15.766601983986687, -53.25385055922196 15.704946511857045 M-52.241347086952096 15.868640221171937 C-52.55323952524278 15.818215870511082, -52.865131963533464 15.76779151985023, -53.25385055922196 15.704946511857045 M-53.25385055922196 15.704946511857045 C-53.58213793547146 15.630017060503434, -53.91042531172096 15.55508760914982, -54.25378584255211 15.476717808624471 M-53.25385055922196 15.704946511857045 C-53.55109412073784 15.63710260863656, -53.84833768225371 15.569258705416074, -54.25378584255211 15.476717808624471 M-54.25378584255211 15.476717808624471 C-54.49159523938659 15.406137227930994, -54.729404636221076 15.335556647237517, -55.23704398837792 15.184891952170702 M-54.25378584255211 15.476717808624471 C-54.54961243655994 15.388918028348426, -54.845439030567775 15.301118248072383, -55.23704398837792 15.184891952170702 M-55.23704398837792 15.184891952170702 C-55.60074990886157 15.051044811372044, -55.964455829345226 14.917197670573387, -56.19958457806999 14.830668117536348 M-55.23704398837792 15.184891952170702 C-55.61068131195361 15.047389963229291, -55.9843186355293 14.90988797428788, -56.19958457806999 14.830668117536348 M-56.19958457806999 14.830668117536348 C-56.46580676937782 14.712819450645087, -56.73202896068566 14.594970783753826, -57.13745232588093 14.415501886438708 M-56.19958457806999 14.830668117536348 C-56.54358879531572 14.6783876550842, -56.88759301256145 14.526107192632052, -57.13745232588093 14.415501886438708 M-57.13745232588093 14.415501886438708 C-57.45272925901403 14.251022112367684, -57.768006192147126 14.08654233829666, -58.046793332063 13.941099265974234 M-57.13745232588093 14.415501886438708 C-57.494322624743084 14.229322880108658, -57.85119292360523 14.043143873778607, -58.046793332063 13.941099265974234 M-58.046793332063 13.941099265974234 C-58.39280163835406 13.731346997330084, -58.738809944645126 13.521594728685931, -58.92387091936877 13.409409678269457 M-58.046793332063 13.941099265974234 C-58.26764353127464 13.807218577352305, -58.48849373048628 13.673337888730376, -58.92387091936877 13.409409678269457 M-58.92387091936877 13.409409678269457 C-59.09950706616293 13.286893505432104, -59.27514321295709 13.164377332594752, -59.765080987859456 12.822617949887308 M-58.92387091936877 13.409409678269457 C-59.13355968494301 13.263139872685228, -59.34324845051725 13.116870067101, -59.765080987859456 12.822617949887308 M-59.765080987859456 12.822617949887308 C-60.071661874547864 12.578127851213331, -60.37824276123627 12.333637752539355, -60.56696682492461 12.183135333906154 M-59.765080987859456 12.822617949887308 C-60.036381727618554 12.606262829545319, -60.307682467377646 12.389907709203328, -60.56696682492461 12.183135333906154 M-60.56696682492461 12.183135333906154 C-60.744928010098604 12.021515694126071, -60.922889195272596 11.859896054345988, -61.32623330965578 11.493589601563649 M-60.56696682492461 12.183135333906154 C-60.817966990559654 11.955183624576874, -61.068967156194695 11.727231915247591, -61.32623330965578 11.493589601563649 M-61.32623330965578 11.493589601563649 C-61.47036375540861 11.34476308299418, -61.61449420116145 11.195936564424713, -62.03976045320505 10.756814244181069 M-61.32623330965578 11.493589601563649 C-61.59790118520502 11.213070215711667, -61.869569060754266 10.932550829859684, -62.03976045320505 10.756814244181069 M-62.03976045320505 10.756814244181069 C-62.29646154241571 10.455278538088452, -62.553162631626385 10.153742831995835, -62.70461621948847 9.97583682973974 M-62.03976045320505 10.756814244181069 C-62.184026011486964 10.587351710480318, -62.32829156976887 10.417889176779568, -62.70461621948847 9.97583682973974 M-62.70461621948847 9.97583682973974 C-62.83148804653665 9.805840139756405, -62.95835987358482 9.635843449773073, -63.31806857355129 9.15386656195472 M-62.70461621948847 9.97583682973974 C-62.924417504161276 9.681323132587151, -63.14421878883409 9.386809435434563, -63.31806857355129 9.15386656195472 M-63.31806857355129 9.15386656195472 C-63.521812847245464 8.840860644562436, -63.72555712093964 8.527854727170153, -63.877596708085534 8.29428109296841 M-63.31806857355129 9.15386656195472 C-63.47434111667654 8.913789970660845, -63.63061365980179 8.67371337936697, -63.877596708085534 8.29428109296841 M-63.877596708085534 8.29428109296841 C-63.98361711986846 8.106031116116984, -64.08963753165139 7.917781139265557, -64.380901401968 7.400612643853366 M-63.877596708085534 8.29428109296841 C-64.03539370326973 8.014096549340422, -64.19319069845395 7.733912005712437, -64.380901401968 7.400612643853366 M-64.380901401968 7.400612643853366 C-64.51420366226044 7.123807648144677, -64.64750592255287 6.847002652435988, -64.825914468253 6.476533489958307 M-64.380901401968 7.400612643853366 C-64.52514339090962 7.101091067531951, -64.66938537985124 6.801569491210536, -64.825914468253 6.476533489958307 M-64.825914468253 6.476533489958307 C-64.94478822402867 6.1829130149246785, -65.06366197980434 5.88929253989105, -65.21080725279616 5.525840870740931 M-64.825914468253 6.476533489958307 C-64.95492609772391 6.157872270894978, -65.08393772719482 5.839211051831649, -65.21080725279616 5.525840870740931 M-65.21080725279616 5.525840870740931 C-65.27712690582325 5.32609664242508, -65.34344655885033 5.1263524141092285, -65.53399814858656 4.552441386096519 M-65.21080725279616 5.525840870740931 C-65.33581529388582 5.149336568305399, -65.46082333497547 4.772832265869866, -65.53399814858656 4.552441386096519 M-65.53399814858656 4.552441386096519 C-65.62723506912995 4.196888598927588, -65.72047198967336 3.8413358117586576, -65.79415909490918 3.5603349433010343 M-65.53399814858656 4.552441386096519 C-65.62326648969284 4.212022512314529, -65.71253483079911 3.871603638532538, -65.79415909490918 3.5603349433010343 M-65.79415909490918 3.5603349433010343 C-65.86060525036693 3.2191479784254025, -65.92705140582468 2.87796101354977, -65.9902210346312 2.5535983205340753 M-65.79415909490918 3.5603349433010343 C-65.84442492565297 3.302230526118745, -65.89469075639677 3.044126108936455, -65.9902210346312 2.5535983205340753 M-65.9902210346312 2.5535983205340753 C-66.02315165758762 2.2981949117711067, -66.05608228054405 2.0427915030081385, -66.12137830718717 1.5363684145229202 M-65.9902210346312 2.5535983205340753 C-66.03996849289076 2.1677668580196414, -66.08971595115034 1.7819353955052075, -66.12137830718717 1.5363684145229202 M-66.12137830718717 1.5363684145229202 C-66.13943668440474 1.2550946128995846, -66.1574950616223 0.9738208112762491, -66.187091959211 0.5128252411464846 M-66.12137830718717 1.5363684145229202 C-66.1460463887776 1.152143132034874, -66.17071447036803 0.7679178495468281, -66.187091959211 0.5128252411464846 M-66.187091959211 0.5128252411464846 C-66.187091959211 0.11895029747643021, -66.187091959211 -0.2749246461936242, -66.187091959211 -0.5128252411464769 M-66.187091959211 0.5128252411464846 C-66.187091959211 0.24106015787710017, -66.187091959211 -0.03070492539228431, -66.187091959211 -0.5128252411464769 M-66.187091959211 -0.5128252411464769 C-66.16920935401427 -0.7913612516647894, -66.15132674881752 -1.069897262183102, -66.12137830718717 -1.5363684145228982 M-66.187091959211 -0.5128252411464769 C-66.1706894933986 -0.7683068860068625, -66.15428702758618 -1.023788530867248, -66.12137830718717 -1.5363684145228982 M-66.12137830718717 -1.5363684145228982 C-66.08178915383614 -1.8434140701509607, -66.0422000004851 -2.1504597257790232, -65.9902210346312 -2.5535983205340678 M-66.12137830718717 -1.5363684145228982 C-66.07087942807554 -1.9280277487810649, -66.02038054896393 -2.3196870830392315, -65.9902210346312 -2.5535983205340678 M-65.9902210346312 -2.5535983205340678 C-65.9404286726464 -2.809271575706593, -65.8906363106616 -3.064944830879118, -65.79415909490918 -3.5603349433010267 M-65.9902210346312 -2.5535983205340678 C-65.92899711525185 -2.8679702068671, -65.8677731958725 -3.1823420932001323, -65.79415909490918 -3.5603349433010267 M-65.79415909490918 -3.5603349433010267 C-65.7153963830074 -3.8606912997577503, -65.63663367110564 -4.161047656214474, -65.53399814858658 -4.552441386096511 M-65.79415909490918 -3.5603349433010267 C-65.69845428437348 -3.925298864600897, -65.60274947383779 -4.290262785900767, -65.53399814858658 -4.552441386096511 M-65.53399814858658 -4.552441386096511 C-65.42095170914641 -4.892919250186187, -65.30790526970624 -5.2333971142758635, -65.21080725279617 -5.525840870740911 M-65.53399814858658 -4.552441386096511 C-65.41488159238475 -4.911201474730564, -65.2957650361829 -5.2699615633646175, -65.21080725279617 -5.525840870740911 M-65.21080725279617 -5.525840870740911 C-65.06123646754031 -5.895283602077283, -64.91166568228446 -6.264726333413655, -64.825914468253 -6.476533489958299 M-65.21080725279617 -5.525840870740911 C-65.08630171005414 -5.833371968464651, -64.9617961673121 -6.1409030661883905, -64.825914468253 -6.476533489958299 M-64.825914468253 -6.476533489958299 C-64.67928870405129 -6.781005026611939, -64.53266293984956 -7.08547656326558, -64.380901401968 -7.400612643853359 M-64.825914468253 -6.476533489958299 C-64.66471810052049 -6.811261196604612, -64.50352173278797 -7.145988903250924, -64.380901401968 -7.400612643853359 M-64.380901401968 -7.400612643853359 C-64.18935929975699 -7.740715042070066, -63.99781719754597 -8.080817440286774, -63.877596708085534 -8.294281092968404 M-64.380901401968 -7.400612643853359 C-64.27136014188333 -7.59511424338907, -64.16181888179867 -7.789615842924782, -63.877596708085534 -8.294281092968404 M-63.877596708085534 -8.294281092968404 C-63.7368310753641 -8.510534905693529, -63.596065442642676 -8.726788718418653, -63.318068573551294 -9.153866561954715 M-63.877596708085534 -8.294281092968404 C-63.66395959209059 -8.62248507273478, -63.45032247609566 -8.950689052501154, -63.318068573551294 -9.153866561954715 M-63.318068573551294 -9.153866561954715 C-63.12776435612441 -9.408856876235872, -62.93746013869753 -9.663847190517028, -62.70461621948848 -9.975836829739734 M-63.318068573551294 -9.153866561954715 C-63.130924024807385 -9.404623208052422, -62.94377947606348 -9.65537985415013, -62.70461621948848 -9.975836829739734 M-62.70461621948848 -9.975836829739734 C-62.53843826328515 -10.17103891288974, -62.372260307081824 -10.366240996039746, -62.039760453205055 -10.756814244181063 M-62.70461621948848 -9.975836829739734 C-62.460383235551426 -10.262726789922672, -62.21615025161438 -10.54961675010561, -62.039760453205055 -10.756814244181063 M-62.039760453205055 -10.756814244181063 C-61.83328387128559 -10.970018267055556, -61.62680728936611 -11.183222289930049, -61.32623330965579 -11.493589601563633 M-62.039760453205055 -10.756814244181063 C-61.78613135068278 -11.01870711587189, -61.532502248160505 -11.280599987562718, -61.32623330965579 -11.493589601563633 M-61.32623330965579 -11.493589601563633 C-61.11131773438572 -11.688770240669394, -60.896402159115645 -11.883950879775156, -60.56696682492463 -12.18313533390614 M-61.32623330965579 -11.493589601563633 C-61.149052050848056 -11.654500932853603, -60.97187079204032 -11.815412264143575, -60.56696682492463 -12.18313533390614 M-60.56696682492463 -12.18313533390614 C-60.25633019117695 -12.430859782931925, -59.945693557429266 -12.67858423195771, -59.76508098785946 -12.822617949887302 M-60.56696682492463 -12.18313533390614 C-60.36546601905114 -12.343826864428607, -60.163965213177654 -12.504518394951074, -59.76508098785946 -12.822617949887302 M-59.76508098785946 -12.822617949887302 C-59.57017842221198 -12.958573542486903, -59.3752758565645 -13.094529135086503, -58.92387091936879 -13.409409678269444 M-59.76508098785946 -12.822617949887302 C-59.54654768291126 -12.975057323264869, -59.32801437796306 -13.127496696642435, -58.92387091936879 -13.409409678269444 M-58.92387091936879 -13.409409678269444 C-58.588145512946554 -13.612928392584083, -58.25242010652432 -13.816447106898721, -58.046793332063004 -13.941099265974229 M-58.92387091936879 -13.409409678269444 C-58.748308147998905 -13.515836861995231, -58.57274537662902 -13.622264045721018, -58.046793332063004 -13.941099265974229 M-58.046793332063004 -13.941099265974229 C-57.77403614942479 -14.083396513447275, -57.501278966786565 -14.225693760920322, -57.137452325880936 -14.415501886438705 M-58.046793332063004 -13.941099265974229 C-57.74078185447426 -14.100745257822572, -57.43477037688552 -14.260391249670915, -57.137452325880936 -14.415501886438705 M-57.137452325880936 -14.415501886438705 C-56.94253973964398 -14.501783906489361, -56.74762715340703 -14.58806592654002, -56.199584578069995 -14.830668117536344 M-57.137452325880936 -14.415501886438705 C-56.799259508094444 -14.565209814739287, -56.46106669030795 -14.714917743039868, -56.199584578069995 -14.830668117536344 M-56.199584578069995 -14.830668117536344 C-55.90369196110276 -14.939559335781656, -55.60779934413552 -15.048450554026967, -55.23704398837794 -15.184891952170695 M-56.199584578069995 -14.830668117536344 C-55.892181968831224 -14.943795119334782, -55.58477935959245 -15.05692212113322, -55.23704398837794 -15.184891952170695 M-55.23704398837794 -15.184891952170695 C-54.990208709489295 -15.258151367280027, -54.74337343060065 -15.331410782389359, -54.25378584255213 -15.476717808624466 M-55.23704398837794 -15.184891952170695 C-54.913169925395366 -15.281016074014275, -54.58929586241279 -15.377140195857855, -54.25378584255213 -15.476717808624466 M-54.25378584255213 -15.476717808624466 C-54.04178057515946 -15.525106627443183, -53.82977530776678 -15.573495446261902, -53.253850559221966 -15.704946511857043 M-54.25378584255213 -15.476717808624466 C-53.923969060050084 -15.551996336974915, -53.594152277548034 -15.627274865325363, -53.253850559221966 -15.704946511857043 M-53.253850559221966 -15.704946511857043 C-52.85777855560553 -15.768980361817487, -52.46170655198909 -15.83301421177793, -52.2413470869521 -15.868640221171937 M-53.253850559221966 -15.704946511857043 C-52.91320735799086 -15.76001906290461, -52.57256415675976 -15.815091613952173, -52.2413470869521 -15.868640221171937 M-52.2413470869521 -15.868640221171937 C-52.02607089930829 -15.88940765608644, -51.81079471166447 -15.910175091000944, -51.220436019691405 -15.967126284005381 M-52.2413470869521 -15.868640221171937 C-51.869730326817894 -15.904489643087542, -51.498113566683685 -15.940339065003146, -51.220436019691405 -15.967126284005381 M-51.220436019691405 -15.967126284005381 C-50.98904533890346 -15.974546532763613, -50.75765465811551 -15.981966781521844, -50.19531250000001 -16 M-51.220436019691405 -15.967126284005381 C-50.971431073215804 -15.975111387980128, -50.722426126740196 -15.983096491954875, -50.19531250000001 -16 M-50.19531250000001 -16 C-50.19531250000001 -16, -50.19531250000001 -16, -50.1953125 -16 M-50.19531250000001 -16 C-50.19531250000001 -16, -50.1953125 -16, -50.1953125 -16" stroke="#6b7280" stroke-width="1.3" fill="none" stroke-dasharray="0 0" style="fill:#f3f4f6 !important;stroke:#6b7280 !important"></path></g><g class="label" style="color:#111 !important" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style="fill:#111 !important"><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Telegram</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> users</tspan></tspan></text></g></g></g><g class="node default ext" id="g1069-flowchart-tgapi-2" data-look="classic" transform="translate(426.4913787841797, 365.7333399454752)"><rect class="basic label-container" style="fill:#f3f4f6 !important;stroke:#6b7280 !important" x="-91.8203125" y="-32.29999923706055" width="183.640625" height="64.5999984741211"></rect><g class="label" style="color:#111 !important" transform="translate(0, -17.299999237060547)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style="fill:#111 !important"><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Telegram</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Bot</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> API</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">api.telegram.org</tspan></tspan></text></g></g></g><g class="node default ext" id="g1069-flowchart-scli-3" data-look="classic" transform="translate(426.4913787841797, 504.7333399454752)"><rect class="basic label-container" style="fill:#f3f4f6 !important;stroke:#6b7280 !important" x="-92.2578125" y="-23.5" width="184.515625" height="47"></rect><g class="label" style="color:#111 !important" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style="fill:#111 !important"><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">signal-cli</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> daemon</tspan></tspan></text></g></g></g><g class="node default ext" id="g1069-flowchart-llm-4" data-look="classic" transform="translate(3365.9077911376953, 716.666670481364)"><rect class="basic label-container" style="fill:#f3f4f6 !important;stroke:#6b7280 !important" x="-112.61328125" y="-41.099998474121094" width="225.2265625" height="82.19999694824219"></rect><g class="label" style="color:#111 !important" transform="translate(0, -26.099998474121094)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style="fill:#111 !important"><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Model</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> API</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">OpenRouter</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> or</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> another</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="2.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">chat</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> completions</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> API</tspan></tspan></text></g></g></g><g class="node default ext" id="g1069-flowchart-web-5" data-look="classic" transform="translate(3323.6226348876953, 971.3673617045085)"><rect class="basic label-container" style="fill:#f3f4f6 !important;stroke:#6b7280 !important" x="-70.328125" y="-23.5" width="140.65625" height="47"></rect><g class="label" style="color:#111 !important" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style="fill:#111 !important"><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Web</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> pages</tspan></tspan></text></g></g></g><g class="node default ext" id="g1069-flowchart-mcpsrv-6" data-look="classic" transform="translate(3372.7241973876953, 1123.5000076293945)"><rect class="basic label-container" style="fill:#f3f4f6 !important;stroke:#6b7280 !important" x="-119.4296875" y="-41.099998474121094" width="238.859375" height="82.19999694824219"></rect><g class="label" style="color:#111 !important" transform="translate(0, -26.099998474121094)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style="fill:#111 !important"><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">MCP</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> servers</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">remote</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> over</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> HTTP,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> or</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="2.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">local</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> programs</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> over</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> stdio</tspan></tspan></text></g></g></g><g class="node default ext" id="g1069-flowchart-disk-7" data-look="classic" transform="translate(3336.8257598876953, 852.8170153299968)"><path d="M0,14.300235394821312 a83.53125,14.300235394821312 0,0,0 167.0625,0 a83.53125,14.300235394821312 0,0,0 -167.0625,0 l0,81.5002323430635 a83.53125,14.300235394821312 0,0,0 167.0625,0 l0,-81.5002323430635" class="basic label-container outer-path" style="fill:#f3f4f6 !important;stroke:#6b7280 !important" transform="translate(-83.53125, -55.050351566353065)"></path><g class="label" style="color:#111 !important" transform="translate(-0.1640625, -19.099998474121094)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style="fill:#111 !important"><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">STATE_DIRECTORY</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">budget.json</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="2.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">schedules.json</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-telegram-8" data-look="classic" transform="translate(1027.4679412841797, 349.1000061035156)"><rect class="basic label-container" style="" x="-115.84375" y="-49.900001525878906" width="231.6875" height="99.80000305175781"></rect><g class="label" style="" transform="translate(0, -34.900001525878906)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">internal/telegram</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">long</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> polling,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> decoding,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="2.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">sending</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> with</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> entities,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="3.2em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">names</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> and</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> groups</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> seen</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-signal-9" data-look="classic" transform="translate(1027.4679412841797, 496.50000762939453)"><rect class="basic label-container" style="" x="-126.5" y="-67.5" width="253" height="135"></rect><g class="label" style="" transform="translate(0, -52.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">internal/signal</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">JSON-RPC</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> client,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="2.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">decoding,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="3.2em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">sending,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Markdown</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> to</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> text</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="4.300000000000001em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">styles,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="5.4em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">names,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> recent</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> attachments</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-bot-10" data-look="classic" transform="translate(2140.2788848876953, 525.950008392334)"><rect class="basic label-container" style="" x="-120.265625" y="-49.900001525878906" width="240.53125" height="99.80000305175781"></rect><g class="label" style="" transform="translate(0, -34.900001525878906)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">internal/bot</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">addressed</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> or</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> not,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> hooks,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="2.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">prompt,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="3.2em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">daily</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> budget,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> worker</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> slots</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-chats-11" data-look="classic" transform="translate(2726.5445098876953, 655.6666717529297)"><rect class="basic label-container" style="" x="-116.125" y="-32.29999923706055" width="232.25" height="64.5999984741211"></rect><g class="label" style="" transform="translate(0, -17.299999237060547)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">internal/chats</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">history,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> dedupe,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> mailbox</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-timers-12" data-look="classic" transform="translate(2435.6773223876953, 549.3000068664551)"><rect class="basic label-container" style="" x="-85.1328125" y="-32.29999923706055" width="170.265625" height="64.5999984741211"></rect><g class="label" style="" transform="translate(0, -17.299999237060547)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">internal/timers</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">one-shot</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> timers</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-config-13" data-look="classic" transform="translate(2430.3570098876953, 453.700008392334)"><rect class="basic label-container" style="" x="-79.8125" y="-32.29999923706055" width="159.625" height="64.5999984741211"></rect><g class="label" style="" transform="translate(0, -17.299999237060547)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">internal/config</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">settings</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-model-14" data-look="classic" transform="translate(2457.9820098876953, 644.9000053405762)"><rect class="basic label-container" style="" x="-107.4375" y="-32.29999923706055" width="214.875" height="64.5999984741211"></rect><g class="label" style="" transform="translate(0, -17.299999237060547)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">internal/model</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">model</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> client,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> tool</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> loop</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-port-25" data-look="classic" transform="translate(1634.9398193359375, 619.5500068664551)"><polygon points="38.79999923706055,0 253.61249923706055,0 292.4124984741211,-77.5999984741211 253.61249923706055,-155.1999969482422 38.79999923706055,-155.1999969482422 0,-77.5999984741211" class="label-container" transform="translate(-146.20624923706055,77.5999984741211)"></polygon><g class="label" style="" transform="translate(0, -70.0999984741211)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">internal/feature:</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> the</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Host</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">ports,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="2.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">the</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> only</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> part</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> of</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> the</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> core</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="3.2em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">features</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> use</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="4.300000000000001em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">OnMessage,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> OnTurn,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="5.4em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">OnEvent,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Command,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="6.500000000000001em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">OfferTools,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> At,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Store,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Media,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="7.600000000000001em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Deliver,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Tell</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-f1-26" data-look="classic" transform="translate(1060.0616912841797, 1046.5000076293945)"><rect class="basic label-container" style="" x="-105.6015625" y="-23.5" width="211.203125" height="47"></rect><g class="label" style="" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">intro,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> groupctx,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> vision</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-files-27" data-look="classic" transform="translate(1060.0616912841797, 815.5000076293945)"><rect class="basic label-container" style="" x="-123.90625" y="-23.5" width="247.8125" height="47"></rect><g class="label" style="" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">files</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> (FILES=off</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> to</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> disable)</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-charts-28" data-look="classic" transform="translate(1060.0616912841797, 969.5000076293945)"><rect class="basic label-container" style="" x="-122.4921875" y="-23.5" width="244.984375" height="47"></rect><g class="label" style="" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">charts</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> (build</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> tag</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> nocharts)</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-schedule-29" data-look="classic" transform="translate(1121.8937225341797, 738.5000076293945)"><rect class="basic label-container" style="" x="-62.07421875" y="-23.5" width="124.1484375" height="47"></rect><g class="label" style="" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">schedule</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-websearch-30" data-look="classic" transform="translate(1114.7804412841797, 661.5000076293945)"><rect class="basic label-container" style="" x="-69.1875" y="-23.5" width="138.375" height="47"></rect><g class="label" style="" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">websearch</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-links-31" data-look="classic" transform="translate(1137.9601287841797, 892.5000076293945)"><rect class="basic label-container" style="" x="-46.0078125" y="-23.5" width="92.015625" height="47"></rect><g class="label" style="" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">links</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-mcp-32" data-look="classic" transform="translate(1138.8038787841797, 1123.5000076293945)"><rect class="basic label-container" style="" x="-45.1640625" y="-23.5" width="90.328125" height="47"></rect><g class="label" style="" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">mcp</tspan></tspan></text></g></g></g></g></g></g><defs><filter id="g1069-drop-shadow" height="130%" width="130%"><feDropShadow dx="4" dy="4" stdDeviation="0" flood-opacity="0.06" flood-color="#000000"></feDropShadow></filter></defs><defs><filter id="g1069-drop-shadow-small" height="150%" width="150%"><feDropShadow dx="2" dy="2" stdDeviation="0" flood-opacity="0.06" flood-color="#000000"></feDropShadow></filter></defs></svg> \ No newline at end of file +<svg id="g1069" width="100%" xmlns="http://www.w3.org/2000/svg" class="flowchart" style="max-width: 3496.15380859375px;" viewBox="4 4 3496.15380859375 1175" role="graphics-document document" aria-roledescription="flowchart-v2"><style>#g1069{font-family:Helvetica,Arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#g1069 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#g1069 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#g1069 .error-icon{fill:#552222;}#g1069 .error-text{fill:#552222;stroke:#552222;}#g1069 .edge-thickness-normal{stroke-width:1px;}#g1069 .edge-thickness-thick{stroke-width:3.5px;}#g1069 .edge-pattern-solid{stroke-dasharray:0;}#g1069 .edge-thickness-invisible{stroke-width:0;fill:none;}#g1069 .edge-pattern-dashed{stroke-dasharray:3;}#g1069 .edge-pattern-dotted{stroke-dasharray:2;}#g1069 .marker{fill:#333333;stroke:#333333;}#g1069 .marker.cross{stroke:#333333;}#g1069 svg{font-family:Helvetica,Arial,sans-serif;font-size:16px;}#g1069 p{margin:0;}#g1069 .label{font-family:Helvetica,Arial,sans-serif;color:#333;}#g1069 .cluster-label text{fill:#333;}#g1069 .cluster-label span{color:#333;}#g1069 .cluster-label span p{background-color:transparent;}#g1069 .label text,#g1069 span{fill:#333;color:#333;}#g1069 .node rect,#g1069 .node circle,#g1069 .node ellipse,#g1069 .node polygon,#g1069 .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#g1069 .rough-node .label text,#g1069 .node .label text,#g1069 .image-shape .label,#g1069 .icon-shape .label{text-anchor:middle;}#g1069 .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#g1069 .rough-node .label,#g1069 .node .label,#g1069 .image-shape .label,#g1069 .icon-shape .label{text-align:center;}#g1069 .node.clickable{cursor:pointer;}#g1069 .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#g1069 .arrowheadPath{fill:#333333;}#g1069 .edgePaths .path{stroke:#333333;stroke-width:1px;}#g1069 .flowchart-link{stroke:#333333;fill:none;}#g1069 .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#g1069 .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#g1069 .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#g1069 .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#g1069 .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#g1069 .cluster text{fill:#333;}#g1069 .cluster span{color:#333;}#g1069 .node .collapsed-indicator{fill:#aaaa33;stroke:none;opacity:0.6;}#g1069 .node .collapsed-separator{stroke:#aaaa33;stroke-width:0.75px;}#g1069 div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:Helvetica,Arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#g1069 .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#g1069 rect.text{fill:none;stroke-width:0;}#g1069 .icon-shape,#g1069 .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#g1069 .icon-shape p,#g1069 .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#g1069 .icon-shape .label rect,#g1069 .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#g1069 .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#g1069 .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#g1069 .node .neo-node{stroke:#9370DB;}#g1069 [data-look="neo"].node rect,#g1069 [data-look="neo"].cluster rect,#g1069 [data-look="neo"].node polygon{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1069 [data-look="neo"].swimlane.cluster rect{filter:none;}#g1069 [data-look="neo"].node path{stroke:#9370DB;stroke-width:1px;}#g1069 [data-look="neo"].node .outer-path{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1069 [data-look="neo"].node .neo-line path{stroke:#9370DB;filter:none;}#g1069 [data-look="neo"].node circle{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1069 [data-look="neo"].node circle .state-start{fill:#000000;}#g1069 [data-look="neo"].icon-shape .icon{fill:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1069 [data-look="neo"].icon-shape .icon-neo path{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1069 :root{--mermaid-font-family:Helvetica,Arial,sans-serif;}#g1069 .ext rect{fill:rgb(243, 244, 246)!important;stroke:rgb(107, 114, 128)!important;color:rgb(17, 17, 17)!important;}#g1069 .ext polygon{fill:rgb(243, 244, 246)!important;stroke:rgb(107, 114, 128)!important;color:rgb(17, 17, 17)!important;}#g1069 .ext ellipse{fill:rgb(243, 244, 246)!important;stroke:rgb(107, 114, 128)!important;color:rgb(17, 17, 17)!important;}#g1069 .ext circle{fill:rgb(243, 244, 246)!important;stroke:rgb(107, 114, 128)!important;color:rgb(17, 17, 17)!important;}#g1069 .ext path{fill:rgb(243, 244, 246)!important;stroke:rgb(107, 114, 128)!important;color:rgb(17, 17, 17)!important;}#g1069 .ext tspan{fill:rgb(17, 17, 17)!important;}</style><g><marker id="g1069_flowchart-v2-pointEnd" class="marker flowchart-v2" viewBox="0 0 10 10" refX="5" refY="5" markerUnits="userSpaceOnUse" markerWidth="8" markerHeight="8" orient="auto"><path d="M 0 0 L 10 5 L 0 10 z" class="arrowMarkerPath" style="stroke-width: 1; stroke-dasharray: 1, 0;"></path></marker><marker id="g1069_flowchart-v2-pointStart" class="marker flowchart-v2" viewBox="0 0 10 10" refX="4.5" refY="5" markerUnits="userSpaceOnUse" markerWidth="8" markerHeight="8" orient="auto"><path d="M 0 5 L 10 10 L 10 0 z" class="arrowMarkerPath" style="stroke-width: 1; stroke-dasharray: 1, 0;"></path></marker><marker id="g1069_flowchart-v2-pointEnd-margin" class="marker flowchart-v2" viewBox="0 0 11.5 14" refX="11.5" refY="7" markerUnits="userSpaceOnUse" markerWidth="10.5" markerHeight="14" orient="auto"><path d="M 0 0 L 11.5 7 L 0 14 z" class="arrowMarkerPath" style="stroke-width: 0; stroke-dasharray: 1, 0;"></path></marker><marker id="g1069_flowchart-v2-pointStart-margin" class="marker flowchart-v2" viewBox="0 0 11.5 14" refX="1" refY="7" markerUnits="userSpaceOnUse" markerWidth="11.5" markerHeight="14" orient="auto"><polygon points="0,7 11.5,14 11.5,0" class="arrowMarkerPath" style="stroke-width: 0; stroke-dasharray: 1, 0;"></polygon></marker><marker id="g1069_flowchart-v2-circleEnd" class="marker flowchart-v2" viewBox="0 0 10 10" refX="11" refY="5" markerUnits="userSpaceOnUse" markerWidth="11" markerHeight="11" orient="auto"><circle cx="5" cy="5" r="5" class="arrowMarkerPath" style="stroke-width: 1; stroke-dasharray: 1, 0;"></circle></marker><marker id="g1069_flowchart-v2-circleStart" class="marker flowchart-v2" viewBox="0 0 10 10" refX="-1" refY="5" markerUnits="userSpaceOnUse" markerWidth="11" markerHeight="11" orient="auto"><circle cx="5" cy="5" r="5" class="arrowMarkerPath" style="stroke-width: 1; stroke-dasharray: 1, 0;"></circle></marker><marker id="g1069_flowchart-v2-circleEnd-margin" class="marker flowchart-v2" viewBox="0 0 10 10" refY="5" refX="12.25" markerUnits="userSpaceOnUse" markerWidth="14" markerHeight="14" orient="auto"><circle cx="5" cy="5" r="5" class="arrowMarkerPath" style="stroke-width: 0; stroke-dasharray: 1, 0;"></circle></marker><marker id="g1069_flowchart-v2-circleStart-margin" class="marker flowchart-v2" viewBox="0 0 10 10" refX="-2" refY="5" markerUnits="userSpaceOnUse" markerWidth="14" markerHeight="14" orient="auto"><circle cx="5" cy="5" r="5" class="arrowMarkerPath" style="stroke-width: 0; stroke-dasharray: 1, 0;"></circle></marker><marker id="g1069_flowchart-v2-crossEnd" class="marker cross flowchart-v2" viewBox="0 0 11 11" refX="12" refY="5.2" markerUnits="userSpaceOnUse" markerWidth="11" markerHeight="11" orient="auto"><path d="M 1,1 l 9,9 M 10,1 l -9,9" class="arrowMarkerPath" style="stroke-width: 2; stroke-dasharray: 1, 0;"></path></marker><marker id="g1069_flowchart-v2-crossStart" class="marker cross flowchart-v2" viewBox="0 0 11 11" refX="-1" refY="5.2" markerUnits="userSpaceOnUse" markerWidth="11" markerHeight="11" orient="auto"><path d="M 1,1 l 9,9 M 10,1 l -9,9" class="arrowMarkerPath" style="stroke-width: 2; stroke-dasharray: 1, 0;"></path></marker><marker id="g1069_flowchart-v2-crossEnd-margin" class="marker cross flowchart-v2" viewBox="0 0 15 15" refX="17.7" refY="7.5" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto"><path d="M 1,1 L 14,14 M 1,14 L 14,1" class="arrowMarkerPath" style="stroke-width: 2.5;"></path></marker><marker id="g1069_flowchart-v2-crossStart-margin" class="marker cross flowchart-v2" viewBox="0 0 15 15" refX="-3.5" refY="7.5" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto"><path d="M 1,1 L 14,14 M 1,14 L 14,1" class="arrowMarkerPath" style="stroke-width: 2.5; stroke-dasharray: 1, 0;"></path></marker><g class="root"><g class="clusters"><g class="cluster" id="g1069-bin" data-look="classic"><rect style="" x="809.4679412841797" y="12" width="2124.7015686035156" height="1159.0000076293945"></rect><g class="cluster-label" transform="translate(1532.5218505859375, 12)"><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">signalbot</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> binary</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> (main.go</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> wires</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> it:</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> network_*.go</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> picks</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> the</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> network,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> features.go</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> lists</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> the</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> features)</tspan></tspan></text></g></g></g><g class="cluster" id="g1069-feats" data-look="classic"><rect style="" x="924.1554412841797" y="606.0000076293945" width="271.8125" height="553"></rect><g class="cluster-label" transform="translate(961.3351287841797, 606.0000076293945)"><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Features:</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> internal/features/*</tspan></tspan></text></g></g></g><g class="cluster" id="g1069-core" data-look="classic"><rect style="" x="1476.7335662841797" y="389.40000915527344" width="1377.9359436035156" height="342.5666618347168"></rect><g class="cluster-label" transform="translate(2148.3109130859375, 389.40000915527344)"><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Core</tspan></tspan></text></g></g></g><g class="cluster" id="g1069-net" data-look="classic"><rect style="" x="736.5148162841797" y="214.4000015258789" width="611.90625" height="361.6000061035156"></rect><g class="cluster-label" transform="translate(740.5148162841797, 214.4000015258789)"><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Chat</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> networks:</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> outside</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> the</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> core,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> only</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> main</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> imports</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> them;</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> one</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> runs,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> chosen</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> by</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> setting</tspan></tspan></text></g></g></g></g><g class="edges edgePath"><path d="M2260.5445098876953,550.9000091552734L2283.47344207583,550.9000091552734Q2290.5445098876953,550.9000091552734 2290.5445098876953,557.971076967139L2290.5445098876953,685.1289367657712Q2290.5445098876953,692.2000045776367 2297.6155776995606,692.2000045776367L2588.34844207583,692.2000045776367Q2595.4195098876953,692.2000045776367 2595.4195098876953,685.1289367657712L2595.4195098876953,671.9333381652832Q2595.4195098876953,666.4333381652832 2600.9195098876953,666.4333381652832L2606.4195098876953,666.4333381652832" id="g1069-L_bot_chats_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_bot_chats_0" data-points="W3sieCI6MjI2MC41NDQ1MDk4ODc2OTUzLCJ5Ijo1NTAuOTAwMDA5MTU1MjczNH0seyJ4IjoyMjkwLjU0NDUwOTg4NzY5NTMsInkiOjU1MC45MDAwMDkxNTUyNzM0fSx7IngiOjIyOTAuNTQ0NTA5ODg3Njk1MywieSI6NjkyLjIwMDAwNDU3NzYzNjd9LHsieCI6MjU5NS40MTk1MDk4ODc2OTUzLCJ5Ijo2OTIuMjAwMDA0NTc3NjM2N30seyJ4IjoyNTk1LjQxOTUwOTg4NzY5NTMsInkiOjY2Ni40MzMzMzgxNjUyODMyfSx7IngiOjI2MTAuNDE5NTA5ODg3Njk1MywieSI6NjY2LjQzMzMzODE2NTI4MzJ9XQ==" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M2260.5445098876953,513.4750080108643L2328.47344207583,513.4750080108643Q2335.5445098876953,513.4750080108643 2335.5445098876953,520.5460758227298L2335.5445098876953,543.8000068664551Q2335.5445098876953,549.3000068664551 2341.0445098876953,549.3000068664551L2346.5445098876953,549.3000068664551" id="g1069-L_bot_timers_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_bot_timers_0" data-points="W3sieCI6MjI2MC41NDQ1MDk4ODc2OTUzLCJ5Ijo1MTMuNDc1MDA4MDEwODY0M30seyJ4IjoyMzM1LjU0NDUwOTg4NzY5NTMsInkiOjUxMy40NzUwMDgwMTA4NjQzfSx7IngiOjIzMzUuNTQ0NTA5ODg3Njk1MywieSI6NTQ5LjMwMDAwNjg2NjQ1NTF9LHsieCI6MjM1MC41NDQ1MDk4ODc2OTUzLCJ5Ijo1NDkuMzAwMDA2ODY2NDU1MX1d" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M2260.5445098876953,488.5250072479248L2268.47344207583,488.5250072479248Q2275.5445098876953,488.5250072479248 2275.5445098876953,481.45393943605933L2275.5445098876953,476.92107582272973Q2275.5445098876953,469.85000801086426 2282.6155776995606,469.85000801086426L2346.5445098876953,469.85000801086426" id="g1069-L_bot_config_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_bot_config_0" data-points="W3sieCI6MjI2MC41NDQ1MDk4ODc2OTUzLCJ5Ijo0ODguNTI1MDA3MjQ3OTI0OH0seyJ4IjoyMjc1LjU0NDUwOTg4NzY5NTMsInkiOjQ4OC41MjUwMDcyNDc5MjQ4fSx7IngiOjIyNzUuNTQ0NTA5ODg3Njk1MywieSI6NDY5Ljg1MDAwODAxMDg2NDI2fSx7IngiOjIzNTAuNTQ0NTA5ODg3Njk1MywieSI6NDY5Ljg1MDAwODAxMDg2NDI2fV0=" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M2260.5445098876953,538.4250087738037L2298.47344207583,538.4250087738037Q2305.5445098876953,538.4250087738037 2305.5445098876953,545.4960765856692L2305.5445098876953,637.8289375287106Q2305.5445098876953,644.9000053405762 2312.6155776995606,644.9000053405762L2346.5445098876953,644.9000053405762" id="g1069-L_bot_model_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_bot_model_0" data-points="W3sieCI6MjI2MC41NDQ1MDk4ODc2OTUzLCJ5Ijo1MzguNDI1MDA4NzczODAzN30seyJ4IjoyMzA1LjU0NDUwOTg4NzY5NTMsInkiOjUzOC40MjUwMDg3NzM4MDM3fSx7IngiOjIzMDUuNTQ0NTA5ODg3Njk1MywieSI6NjQ0LjkwMDAwNTM0MDU3NjJ9LHsieCI6MjM1MC41NDQ1MDk4ODc2OTUzLCJ5Ijo2NDQuOTAwMDA1MzQwNTc2Mn1d" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M2565.4195098876953,644.9000053405762L2606.4195098876953,644.9000053405762" id="g1069-L_model_chats_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_model_chats_0" data-points="W3sieCI6MjU2NS40MTk1MDk4ODc2OTUzLCJ5Ijo2NDQuOTAwMDA1MzQwNTc2Mn0seyJ4IjoyNjEwLjQxOTUwOTg4NzY5NTMsInkiOjY0NC45MDAwMDUzNDA1NzYyfV0=" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M142.04576367738824,502.4049135664138L143.20997748078395,503.5691267559445Q144.3741912841797,504.7333399454752 146.02063780037582,504.7333399454752L330.2335662841797,504.7333399454752" id="g1069-L_users_scli_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_users_scli_0" data-points="W3sieCI6MTQ0Ljg3NDE5MTU0NzgxOTA3LCJ5Ijo1MDUuMjMzMzM5OTQ1NDc1MTd9LHsieCI6MTQ0LjM3NDE5MTI4NDE3OTcsInkiOjUwNC43MzMzMzk5NDU0NzUyfSx7IngiOjMzNC4yMzM1NjYyODQxNzk3LCJ5Ijo1MDQuNzMzMzM5OTQ1NDc1Mn1d" data-look="classic" marker-start="url(#g1069_flowchart-v2-pointStart)" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M522.7491912841797,504.7333399454752L774.8968734723142,504.7333399454752Q781.9679412841797,504.7333399454752 781.9679412841797,497.66227213360975L781.9679412841797,481.07107544126Q781.9679412841797,474.00000762939453 789.0390090960452,474.00000762939453L801.9679412841797,474.00000762939453L881.4679412841797,474.00000762939453L896.9679412841797,474.00000762939453" id="g1069-L_scli_signal_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_scli_signal_0" data-points="W3sieCI6NTE4Ljc0OTE5MTI4NDE3OTcsInkiOjUwNC43MzMzMzk5NDU0NzUyfSx7IngiOjc4MS45Njc5NDEyODQxNzk3LCJ5Ijo1MDQuNzMzMzM5OTQ1NDc1Mn0seyJ4Ijo3ODEuOTY3OTQxMjg0MTc5NywieSI6NDc0LjAwMDAwNzYyOTM5NDUzfSx7IngiOjgwMS45Njc5NDEyODQxNzk3LCJ5Ijo0NzQuMDAwMDA3NjI5Mzk0NTN9LHsieCI6ODgxLjQ2Nzk0MTI4NDE3OTcsInkiOjQ3NC4wMDAwMDc2MjkzOTQ1M30seyJ4Ijo5MDAuOTY3OTQxMjg0MTc5NywieSI6NDc0LjAwMDAwNzYyOTM5NDUzfV0=" data-look="classic" marker-start="url(#g1069_flowchart-v2-pointStart)" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1153.9679412841797,519.0000076293945L1203.4679412841797,519.0000076293945L1211.3968734723142,519.0000076293945Q1218.4679412841797,519.0000076293945 1218.4679412841797,526.0710754412601L1218.4679412841797,530.928939817529Q1218.4679412841797,538.0000076293945 1225.5390090960452,538.0000076293945L1448.2085666656494,538.0000076293945Q1454.2335662841797,538.0000076293945 1454.2335662841797,531.9750080108643L1454.2335662841797,531.9750080108643Q1454.2335662841797,525.950008392334 1460.25856590271,525.950008392334L1469.2335662841797,525.950008392334L2016.0132598876953,525.950008392334" id="g1069-L_signal_bot_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_signal_bot_0" data-points="W3sieCI6MTE1My45Njc5NDEyODQxNzk3LCJ5Ijo1MTkuMDAwMDA3NjI5Mzk0NX0seyJ4IjoxMjAzLjQ2Nzk0MTI4NDE3OTcsInkiOjUxOS4wMDAwMDc2MjkzOTQ1fSx7IngiOjEyMTguNDY3OTQxMjg0MTc5NywieSI6NTE5LjAwMDAwNzYyOTM5NDV9LHsieCI6MTIxOC40Njc5NDEyODQxNzk3LCJ5Ijo1MzguMDAwMDA3NjI5Mzk0NX0seyJ4IjoxNDU0LjIzMzU2NjI4NDE3OTcsInkiOjUzOC4wMDAwMDc2MjkzOTQ1fSx7IngiOjE0NTQuMjMzNTY2Mjg0MTc5NywieSI6NTI1Ljk1MDAwODM5MjMzNH0seyJ4IjoxNDY5LjIzMzU2NjI4NDE3OTcsInkiOjUyNS45NTAwMDgzOTIzMzR9LHsieCI6MjAyMC4wMTMyNTk4ODc2OTUzLCJ5Ijo1MjUuOTUwMDA4MzkyMzM0fV0=" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M2260.5445098876953,525.950008392334L2313.47344207583,525.950008392334Q2320.5445098876953,525.950008392334 2320.5445098876953,533.0210762041995L2320.5445098876953,589.5289382916501Q2320.5445098876953,596.6000061035156 2327.6155776995606,596.6000061035156L2862.1695098876953,596.6000061035156L2900.09844207583,596.6000061035156Q2907.1695098876953,596.6000061035156 2907.1695098876953,589.5289382916501L2907.1695098876953,123.87107086362329Q2907.1695098876953,116.80000305175781 2900.09844207583,116.80000305175781L843.5390090960452,116.80000305175781Q836.4679412841797,116.80000305175781 836.4679412841797,123.87107086362329L836.4679412841797,511.92893981752906Q836.4679412841797,519.0000076293945 843.5390090960452,519.0000076293945L881.4679412841797,519.0000076293945L896.9679412841797,519.0000076293945" id="g1069-L_bot_signal_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_bot_signal_0" data-points="W3sieCI6MjI2MC41NDQ1MDk4ODc2OTUzLCJ5Ijo1MjUuOTUwMDA4MzkyMzM0fSx7IngiOjIzMjAuNTQ0NTA5ODg3Njk1MywieSI6NTI1Ljk1MDAwODM5MjMzNH0seyJ4IjoyMzIwLjU0NDUwOTg4NzY5NTMsInkiOjU5Ni42MDAwMDYxMDM1MTU2fSx7IngiOjI4NjIuMTY5NTA5ODg3Njk1MywieSI6NTk2LjYwMDAwNjEwMzUxNTZ9LHsieCI6MjkwNy4xNjk1MDk4ODc2OTUzLCJ5Ijo1OTYuNjAwMDA2MTAzNTE1Nn0seyJ4IjoyOTA3LjE2OTUwOTg4NzY5NTMsInkiOjExNi44MDAwMDMwNTE3NTc4MX0seyJ4Ijo4MzYuNDY3OTQxMjg0MTc5NywieSI6MTE2LjgwMDAwMzA1MTc1NzgxfSx7IngiOjgzNi40Njc5NDEyODQxNzk3LCJ5Ijo1MTkuMDAwMDA3NjI5Mzk0NX0seyJ4Ijo4ODEuNDY3OTQxMjg0MTc5NywieSI6NTE5LjAwMDAwNzYyOTM5NDV9LHsieCI6OTAwLjk2Nzk0MTI4NDE3OTcsInkiOjUxOS4wMDAwMDc2MjkzOTQ1fV0=" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M142.04577762741695,363.40489198714016L143.20998445579832,364.56911596630766Q144.3741912841797,365.7333399454752 146.02064049776584,365.7333399454752L330.6710662841797,365.7333399454752" id="g1069-L_tgusers_tgapi_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_tgusers_tgapi_0" data-points="W3sieCI6MTQ0Ljg3NDE4MzkxODQyMDg0LCJ5IjozNjYuMjMzMzM5OTQ1NDc1Mn0seyJ4IjoxNDQuMzc0MTkxMjg0MTc5NywieSI6MzY1LjczMzMzOTk0NTQ3NTJ9LHsieCI6MzM0LjY3MTA2NjI4NDE3OTcsInkiOjM2NS43MzMzMzk5NDU0NzUyfV0=" data-look="classic" marker-start="url(#g1069_flowchart-v2-pointStart)" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M522.3116912841797,365.7333399454752L801.9679412841797,365.7333399454752L881.4679412841797,365.7333399454752L907.6241912841797,365.7333399454752" id="g1069-L_tgapi_telegram_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_tgapi_telegram_0" data-points="W3sieCI6NTE4LjMxMTY5MTI4NDE3OTcsInkiOjM2NS43MzMzMzk5NDU0NzUyfSx7IngiOjgwMS45Njc5NDEyODQxNzk3LCJ5IjozNjUuNzMzMzM5OTQ1NDc1Mn0seyJ4Ijo4ODEuNDY3OTQxMjg0MTc5NywieSI6MzY1LjczMzMzOTk0NTQ3NTJ9LHsieCI6OTExLjYyNDE5MTI4NDE3OTcsInkiOjM2NS43MzMzMzk5NDU0NzUyfV0=" data-look="classic" marker-start="url(#g1069_flowchart-v2-pointStart)" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1143.3116912841797,365.7333399454752L1161.8968734723142,365.7333399454752Q1168.9679412841797,365.7333399454752 1168.9679412841797,372.8044077573407L1168.9679412841797,481.92893981752906Q1168.9679412841797,489.00000762939453 1176.0390090960452,489.00000762939453L1203.4679412841797,489.00000762939453L1212.4679412841797,489.00000762939453Q1218.4679412841797,489.00000762939453 1218.4679412841797,495.00000762939453L1218.4679412841797,495.00000762939453Q1218.4679412841797,501.00000762939453 1224.4679412841797,501.00000762939453L1469.2335662841797,501.00000762939453L2016.0132598876953,501.00000762939453" id="g1069-L_telegram_bot_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_telegram_bot_0" data-points="W3sieCI6MTE0My4zMTE2OTEyODQxNzk3LCJ5IjozNjUuNzMzMzM5OTQ1NDc1Mn0seyJ4IjoxMTY4Ljk2Nzk0MTI4NDE3OTcsInkiOjM2NS43MzMzMzk5NDU0NzUyfSx7IngiOjExNjguOTY3OTQxMjg0MTc5NywieSI6NDg5LjAwMDAwNzYyOTM5NDUzfSx7IngiOjEyMDMuNDY3OTQxMjg0MTc5NywieSI6NDg5LjAwMDAwNzYyOTM5NDUzfSx7IngiOjEyMTguNDY3OTQxMjg0MTc5NywieSI6NDg5LjAwMDAwNzYyOTM5NDUzfSx7IngiOjEyMTguNDY3OTQxMjg0MTc5NywieSI6NTAxLjAwMDAwNzYyOTM5NDUzfSx7IngiOjE0NjkuMjMzNTY2Mjg0MTc5NywieSI6NTAxLjAwMDAwNzYyOTM5NDUzfSx7IngiOjIwMjAuMDEzMjU5ODg3Njk1MywieSI6NTAxLjAwMDAwNzYyOTM5NDUzfV0=" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M2260.5445098876953,501.0000076293946L2862.1695098876953,501.00000762939453L2885.09844207583,501.00000762939453Q2892.1695098876953,501.00000762939453 2892.1695098876953,493.92893981752906L2892.1695098876953,169.47106933774438Q2892.1695098876953,162.4000015258789 2885.09844207583,162.4000015258789L873.5390090960452,162.4000015258789Q866.4679412841797,162.4000015258789 866.4679412841797,169.47106933774438L866.4679412841797,325.3956044496905Q866.4679412841797,332.46667226155597 873.5390090960452,332.46667226155597L881.4679412841797,332.46667226155597L907.6241912841797,332.46667226155597" id="g1069-L_bot_telegram_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_bot_telegram_0" data-points="W3sieCI6MjI2MC41NDQ1MDk4ODc2OTUzLCJ5Ijo1MDEuMDAwMDA3NjI5Mzk0Nn0seyJ4IjoyODYyLjE2OTUwOTg4NzY5NTMsInkiOjUwMS4wMDAwMDc2MjkzOTQ1M30seyJ4IjoyODkyLjE2OTUwOTg4NzY5NTMsInkiOjUwMS4wMDAwMDc2MjkzOTQ1M30seyJ4IjoyODkyLjE2OTUwOTg4NzY5NTMsInkiOjE2Mi40MDAwMDE1MjU4Nzg5fSx7IngiOjg2Ni40Njc5NDEyODQxNzk3LCJ5IjoxNjIuNDAwMDAxNTI1ODc4OX0seyJ4Ijo4NjYuNDY3OTQxMjg0MTc5NywieSI6MzMyLjQ2NjY3MjI2MTU1NTk3fSx7IngiOjg4MS40Njc5NDEyODQxNzk3LCJ5IjozMzIuNDY2NjcyMjYxNTU1OTd9LHsieCI6OTExLjYyNDE5MTI4NDE3OTcsInkiOjMzMi40NjY2NzIyNjE1NTU5N31d" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1195.9679412841797,646.5000076293945L1447.1624984723142,646.5000076293945Q1454.2335662841797,646.5000076293945 1454.2335662841797,639.428939817529L1454.2335662841797,626.6210746783206Q1454.2335662841797,619.5500068664551 1461.3046340960452,619.5500068664551L1461.7335662841797,619.5500068664551Q1469.2335662841797,619.5500068664551 1476.7312236322407,619.7374483001564L1485.2348156985474,619.9500381018139" id="g1069-L_feats_port_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_feats_port_0" data-points="W3sieCI6MTE5NS45Njc5NDEyODQxNzk3LCJ5Ijo2NDYuNTAwMDA3NjI5Mzk0NX0seyJ4IjoxNDU0LjIzMzU2NjI4NDE3OTcsInkiOjY0Ni41MDAwMDc2MjkzOTQ1fSx7IngiOjE0NTQuMjMzNTY2Mjg0MTc5NywieSI6NjE5LjU1MDAwNjg2NjQ1NTF9LHsieCI6MTQ2OS4yMzM1NjYyODQxNzk3LCJ5Ijo2MTkuNTUwMDA2ODY2NDU1MX0seyJ4IjoxNDg5LjIzMzU2NjI4NDE4LCJ5Ijo2MjAuMDUwMDA2ODY2NDU0Nn1d" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1781.646064758301,620.0500068664546L1781.396068572998,619.8000068664549Q1781.1460723876953,619.5500068664551 1781.4996230809004,619.5500068664551L1997.9421920758298,619.5500068664551Q2005.0132598876953,619.5500068664551 2005.0132598876953,612.4789390545895L2005.0132598876953,556.4000091552734Q2005.0132598876953,550.9000091552734 2010.5132598876953,550.9000091552734L2016.0132598876953,550.9000091552734" id="g1069-L_port_bot_0" class="edge-thickness-normal edge-pattern-dotted edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_port_bot_0" data-points="W3sieCI6MTc4MS42NDYwNjQ3NTgzMDEsInkiOjYyMC4wNTAwMDY4NjY0NTQ2fSx7IngiOjE3ODEuMTQ2MDcyMzg3Njk1MywieSI6NjE5LjU1MDAwNjg2NjQ1NTF9LHsieCI6MjAwNS4wMTMyNTk4ODc2OTUzLCJ5Ijo2MTkuNTUwMDA2ODY2NDU1MX0seyJ4IjoyMDA1LjAxMzI1OTg4NzY5NTMsInkiOjU1MC45MDAwMDkxNTUyNzM0fSx7IngiOjIwMjAuMDEzMjU5ODg3Njk1MywieSI6NTUwLjkwMDAwOTE1NTI3MzR9XQ==" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M2569.4195098876953,661.0500049591064L2574.9195098876953,661.0500049591064Q2580.4195098876953,661.0500049591064 2580.4195098876953,666.5500049591064L2580.4195098876953,695.8956031781247Q2580.4195098876953,702.9666709899902 2587.4905776995606,702.9666709899902L2862.1695098876953,702.9666709899902L2941.6695098876953,702.9666709899902L3249.2945098876953,702.9666709899903" id="g1069-L_model_llm_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_model_llm_0" data-points="W3sieCI6MjU2NS40MTk1MDk4ODc2OTUzLCJ5Ijo2NjEuMDUwMDA0OTU5MTA2NH0seyJ4IjoyNTgwLjQxOTUwOTg4NzY5NTMsInkiOjY2MS4wNTAwMDQ5NTkxMDY0fSx7IngiOjI1ODAuNDE5NTA5ODg3Njk1MywieSI6NzAyLjk2NjY3MDk4OTk5MDJ9LHsieCI6Mjg2Mi4xNjk1MDk4ODc2OTUzLCJ5Ijo3MDIuOTY2NjcwOTg5OTkwMn0seyJ4IjoyOTQxLjY2OTUwOTg4NzY5NTMsInkiOjcwMi45NjY2NzA5ODk5OTAyfSx7IngiOjMyNTMuMjk0NTA5ODg3Njk1MywieSI6NzAyLjk2NjY3MDk4OTk5MDN9XQ==" data-look="classic" marker-start="url(#g1069_flowchart-v2-pointStart)" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M2565.4195098876953,628.7500057220459L2573.34844207583,628.7500057220459Q2580.4195098876953,628.7500057220459 2580.4195098876953,621.6789379101804L2580.4195098876953,492.07107544126Q2580.4195098876953,485.00000762939453 2587.4905776995606,485.00000762939453L2862.1695098876953,485.00000762939453L2870.09844207583,485.00000762939453Q2877.1695098876953,485.00000762939453 2877.1695098876953,477.92893981752906L2877.1695098876953,206.47106933774438Q2877.1695098876953,199.4000015258789 2870.09844207583,199.4000015258789L858.5390090960452,199.4000015258789Q851.4679412841797,199.4000015258789 851.4679412841797,206.47106933774438L851.4679412841797,639.428939817529Q851.4679412841797,646.5000076293945 858.5390090960452,646.5000076293945L920.1554412841797,646.5000076293945" id="g1069-L_model_feats_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_model_feats_0" data-points="W3sieCI6MjU2NS40MTk1MDk4ODc2OTUzLCJ5Ijo2MjguNzUwMDA1NzIyMDQ1OX0seyJ4IjoyNTgwLjQxOTUwOTg4NzY5NTMsInkiOjYyOC43NTAwMDU3MjIwNDU5fSx7IngiOjI1ODAuNDE5NTA5ODg3Njk1MywieSI6NDg1LjAwMDAwNzYyOTM5NDUzfSx7IngiOjI4NjIuMTY5NTA5ODg3Njk1MywieSI6NDg1LjAwMDAwNzYyOTM5NDUzfSx7IngiOjI4NzcuMTY5NTA5ODg3Njk1MywieSI6NDg1LjAwMDAwNzYyOTM5NDUzfSx7IngiOjI4NzcuMTY5NTA5ODg3Njk1MywieSI6MTk5LjQwMDAwMTUyNTg3ODl9LHsieCI6ODUxLjQ2Nzk0MTI4NDE3OTcsInkiOjE5OS40MDAwMDE1MjU4Nzg5fSx7IngiOjg1MS40Njc5NDEyODQxNzk3LCJ5Ijo2NDYuNTAwMDA3NjI5Mzk0NX0seyJ4Ijo5MjQuMTU1NDQxMjg0MTc5NywieSI6NjQ2LjUwMDAwNzYyOTM5NDV9XQ==" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1153.9679412841797,474.00000762939453L1203.4679412841797,474.00000762939453L1447.1624984723142,474.00000762939453Q1454.2335662841797,474.00000762939453 1454.2335662841797,466.92893981752906L1454.2335662841797,460.77107620419946Q1454.2335662841797,453.700008392334 1461.3046340960452,453.700008392334L1469.2335662841797,453.700008392334L2346.5445098876953,453.700008392334" id="g1069-L_signal_config_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_signal_config_0" data-points="W3sieCI6MTE1My45Njc5NDEyODQxNzk3LCJ5Ijo0NzQuMDAwMDA3NjI5Mzk0NTN9LHsieCI6MTIwMy40Njc5NDEyODQxNzk3LCJ5Ijo0NzQuMDAwMDA3NjI5Mzk0NTN9LHsieCI6MTQ1NC4yMzM1NjYyODQxNzk3LCJ5Ijo0NzQuMDAwMDA3NjI5Mzk0NTN9LHsieCI6MTQ1NC4yMzM1NjYyODQxNzk3LCJ5Ijo0NTMuNzAwMDA4MzkyMzM0fSx7IngiOjE0NjkuMjMzNTY2Mjg0MTc5NywieSI6NDUzLjcwMDAwODM5MjMzNH0seyJ4IjoyMzUwLjU0NDUwOTg4NzY5NTMsInkiOjQ1My43MDAwMDgzOTIzMzR9XQ==" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1143.3116912841797,332.46667226155597L1203.4679412841797,332.46667226155597L1447.1624984723142,332.46667226155597Q1454.2335662841797,332.46667226155597 1454.2335662841797,339.53774007342145L1454.2335662841797,430.47894096193824Q1454.2335662841797,437.5500087738037 1461.3046340960452,437.5500087738037L1469.2335662841797,437.5500087738037L2346.5445098876953,437.5500087738037" id="g1069-L_telegram_config_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_telegram_config_0" data-points="W3sieCI6MTE0My4zMTE2OTEyODQxNzk3LCJ5IjozMzIuNDY2NjcyMjYxNTU1OTd9LHsieCI6MTIwMy40Njc5NDEyODQxNzk3LCJ5IjozMzIuNDY2NjcyMjYxNTU1OTd9LHsieCI6MTQ1NC4yMzM1NjYyODQxNzk3LCJ5IjozMzIuNDY2NjcyMjYxNTU1OTd9LHsieCI6MTQ1NC4yMzM1NjYyODQxNzk3LCJ5Ijo0MzcuNTUwMDA4NzczODAzN30seyJ4IjoxNDY5LjIzMzU2NjI4NDE3OTcsInkiOjQzNy41NTAwMDg3NzM4MDM3fSx7IngiOjIzNTAuNTQ0NTA5ODg3Njk1MywieSI6NDM3LjU1MDAwODc3MzgwMzd9XQ==" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1183.9679412841797,661.5000076293945L1203.4679412841797,661.5000076293945L1226.3968734723142,661.5000076293945Q1233.4679412841797,661.5000076293945 1233.4679412841797,668.5710754412601L1233.4679412841797,739.8956031781247Q1233.4679412841797,746.9666709899902 1240.5390090960452,746.9666709899902L2941.6695098876953,746.9666709899902L2998.1695098876953,746.9666709899902Q3001.6695098876953,746.9666709899902 3001.6695098876953,750.4666709899902L3001.6695098876953,750.4666709899902Q3001.6695098876953,753.9666709899902 3005.1695098876953,753.9666709899902L3226.22344207583,753.9666709899902Q3233.2945098876953,753.9666709899902 3233.2945098876953,746.8956031781247L3233.2945098876953,737.4377377846031Q3233.2945098876953,730.3666699727377 3240.3655776995606,730.3666699727377L3249.2945098876953,730.3666699727377" id="g1069-L_websearch_llm_0" class="edge-thickness-normal edge-pattern-dotted edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_websearch_llm_0" data-points="W3sieCI6MTE4My45Njc5NDEyODQxNzk3LCJ5Ijo2NjEuNTAwMDA3NjI5Mzk0NX0seyJ4IjoxMjAzLjQ2Nzk0MTI4NDE3OTcsInkiOjY2MS41MDAwMDc2MjkzOTQ1fSx7IngiOjEyMzMuNDY3OTQxMjg0MTc5NywieSI6NjYxLjUwMDAwNzYyOTM5NDV9LHsieCI6MTIzMy40Njc5NDEyODQxNzk3LCJ5Ijo3NDYuOTY2NjcwOTg5OTkwMn0seyJ4IjoyOTQxLjY2OTUwOTg4NzY5NTMsInkiOjc0Ni45NjY2NzA5ODk5OTAyfSx7IngiOjMwMDEuNjY5NTA5ODg3Njk1MywieSI6NzQ2Ljk2NjY3MDk4OTk5MDJ9LHsieCI6MzAwMS42Njk1MDk4ODc2OTUzLCJ5Ijo3NTMuOTY2NjcwOTg5OTkwMn0seyJ4IjozMjMzLjI5NDUwOTg4NzY5NTMsInkiOjc1My45NjY2NzA5ODk5OTAyfSx7IngiOjMyMzMuMjk0NTA5ODg3Njk1MywieSI6NzMwLjM2NjY2OTk3MjczNzd9LHsieCI6MzI1My4yOTQ1MDk4ODc2OTUzLCJ5Ijo3MzAuMzY2NjY5OTcyNzM3N31d" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1183.9679412841797,892.5000076293945L1203.4679412841797,892.5000076293945L2941.6695098876953,892.5000076293945L2954.59844207583,892.5000076293945Q2961.6695098876953,892.5000076293945 2961.6695098876953,899.5710754412601L2961.6695098876953,964.296293892643Q2961.6695098876953,971.3673617045085 2968.7405776995606,971.3673617045085L3249.2945098876953,971.3673617045085" id="g1069-L_links_web_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_links_web_0" data-points="W3sieCI6MTE4My45Njc5NDEyODQxNzk3LCJ5Ijo4OTIuNTAwMDA3NjI5Mzk0NX0seyJ4IjoxMjAzLjQ2Nzk0MTI4NDE3OTcsInkiOjg5Mi41MDAwMDc2MjkzOTQ1fSx7IngiOjI5NDEuNjY5NTA5ODg3Njk1MywieSI6ODkyLjUwMDAwNzYyOTM5NDV9LHsieCI6Mjk2MS42Njk1MDk4ODc2OTUzLCJ5Ijo4OTIuNTAwMDA3NjI5Mzk0NX0seyJ4IjoyOTYxLjY2OTUwOTg4NzY5NTMsInkiOjk3MS4zNjczNjE3MDQ1MDg1fSx7IngiOjMyNTMuMjk0NTA5ODg3Njk1MywieSI6OTcxLjM2NzM2MTcwNDUwODV9XQ==" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1187.9679412841797,1123.5000076293945L1203.4679412841797,1123.5000076293945L2941.6695098876953,1123.5000076293945L3249.2945098876953,1123.5000076293945" id="g1069-L_mcp_mcpsrv_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_mcp_mcpsrv_0" data-points="W3sieCI6MTE4My45Njc5NDEyODQxNzk3LCJ5IjoxMTIzLjUwMDAwNzYyOTM5NDV9LHsieCI6MTIwMy40Njc5NDEyODQxNzk3LCJ5IjoxMTIzLjUwMDAwNzYyOTM5NDV9LHsieCI6Mjk0MS42Njk1MDk4ODc2OTUzLCJ5IjoxMTIzLjUwMDAwNzYyOTM5NDV9LHsieCI6MzI1My4yOTQ1MDk4ODc2OTUzLCJ5IjoxMTIzLjUwMDAwNzYyOTM5NDV9XQ==" data-look="classic" marker-start="url(#g1069_flowchart-v2-pointStart)" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M1183.9679412841797,738.5000076293945L1203.4679412841797,738.5000076293945L1211.3968734723142,738.5000076293945Q1218.4679412841797,738.5000076293945 1218.4679412841797,745.5710754412601L1218.4679412841797,769.8956031781247Q1218.4679412841797,776.9666709899902 1225.5390090960452,776.9666709899902L2941.6695098876953,776.9666709899902L2954.59844207583,776.9666709899902Q2961.6695098876953,776.9666709899902 2961.6695098876953,784.0377388018558L2961.6695098876953,869.3958320599609Q2961.6695098876953,876.4668998718263 2968.7405776995606,876.4668998718263L3230.6446253458657,876.4668998718263Q3233.2945098876953,876.4668998718263 3233.2945098876953,873.8170153299968L3233.2945098876953,873.8170153299968Q3233.2945098876953,871.1671307881674 3235.944394429525,871.1671307881674L3249.2945098876953,871.1671307881674" id="g1069-L_schedule_disk_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_schedule_disk_0" data-points="W3sieCI6MTE4My45Njc5NDEyODQxNzk3LCJ5Ijo3MzguNTAwMDA3NjI5Mzk0NX0seyJ4IjoxMjAzLjQ2Nzk0MTI4NDE3OTcsInkiOjczOC41MDAwMDc2MjkzOTQ1fSx7IngiOjEyMTguNDY3OTQxMjg0MTc5NywieSI6NzM4LjUwMDAwNzYyOTM5NDV9LHsieCI6MTIxOC40Njc5NDEyODQxNzk3LCJ5Ijo3NzYuOTY2NjcwOTg5OTkwMn0seyJ4IjoyOTQxLjY2OTUwOTg4NzY5NTMsInkiOjc3Ni45NjY2NzA5ODk5OTAyfSx7IngiOjI5NjEuNjY5NTA5ODg3Njk1MywieSI6Nzc2Ljk2NjY3MDk4OTk5MDJ9LHsieCI6Mjk2MS42Njk1MDk4ODc2OTUzLCJ5Ijo4NzYuNDY2ODk5ODcxODI2M30seyJ4IjozMjMzLjI5NDUwOTg4NzY5NTMsInkiOjg3Ni40NjY4OTk4NzE4MjYzfSx7IngiOjMyMzMuMjk0NTA5ODg3Njk1MywieSI6ODcxLjE2NzEzMDc4ODE2NzR9LHsieCI6MzI1My4yOTQ1MDk4ODc2OTUzLCJ5Ijo4NzEuMTY3MTMwNzg4MTY3NH1d" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path><path d="M2260.5445098876953,563.3750095367432L2268.47344207583,563.3750095367432Q2275.5445098876953,563.3750095367432 2275.5445098876953,570.4460773486087L2275.5445098876953,711.8956031781247Q2275.5445098876953,718.9666709899902 2282.6155776995606,718.9666709899902L2862.1695098876953,718.9666709899902L2870.09844207583,718.9666709899902Q2877.1695098876953,718.9666709899902 2877.1695098876953,726.0377388018558L2877.1695098876953,754.8956031781247Q2877.1695098876953,761.9666709899902 2884.2405776995606,761.9666709899902L2941.6695098876953,761.9666709899902L2974.59844207583,761.9666709899902Q2981.6695098876953,761.9666709899902 2981.6695098876953,769.0377388018558L2981.6695098876953,827.3958320599609Q2981.6695098876953,834.4668998718263 2988.7405776995606,834.4668998718263L3249.2945098876953,834.4668998718263" id="g1069-L_bot_disk_0" class="edge-thickness-normal edge-pattern-solid edge-thickness-normal edge-pattern-solid flowchart-link" style=";" data-edge="true" data-et="edge" data-id="L_bot_disk_0" data-points="W3sieCI6MjI2MC41NDQ1MDk4ODc2OTUzLCJ5Ijo1NjMuMzc1MDA5NTM2NzQzMn0seyJ4IjoyMjc1LjU0NDUwOTg4NzY5NTMsInkiOjU2My4zNzUwMDk1MzY3NDMyfSx7IngiOjIyNzUuNTQ0NTA5ODg3Njk1MywieSI6NzE4Ljk2NjY3MDk4OTk5MDJ9LHsieCI6Mjg2Mi4xNjk1MDk4ODc2OTUzLCJ5Ijo3MTguOTY2NjcwOTg5OTkwMn0seyJ4IjoyODc3LjE2OTUwOTg4NzY5NTMsInkiOjcxOC45NjY2NzA5ODk5OTAyfSx7IngiOjI4NzcuMTY5NTA5ODg3Njk1MywieSI6NzYxLjk2NjY3MDk4OTk5MDJ9LHsieCI6Mjk0MS42Njk1MDk4ODc2OTUzLCJ5Ijo3NjEuOTY2NjcwOTg5OTkwMn0seyJ4IjoyOTgxLjY2OTUwOTg4NzY5NTMsInkiOjc2MS45NjY2NzA5ODk5OTAyfSx7IngiOjI5ODEuNjY5NTA5ODg3Njk1MywieSI6ODM0LjQ2Njg5OTg3MTgyNjN9LHsieCI6MzI1My4yOTQ1MDk4ODc2OTUzLCJ5Ijo4MzQuNDY2ODk5ODcxODI2M31d" data-look="classic" marker-end="url(#g1069_flowchart-v2-pointEnd)"></path></g><g class="edgeLabels"><g class="edgeLabel" transform="translate(239.3038787841797, 504.2333399454752)"><g class="label" data-id="L_users_scli_0" transform="translate(0, -11.5)"><g><rect class="background" style="" x="-54.9296875" y="1" width="109.859375" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Signal</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> protocol</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(660.3585662841797, 504.03333918253577)"><g class="label" data-id="L_scli_signal_0" transform="translate(0, -64.29999923706055)"><g><rect class="background" style="" x="-101.609375" y="1" width="203.21875" height="126.5999984741211"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">JSON-RPC</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> over</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> TCP</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> or</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> a</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Unix</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> socket:</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="2.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">receive,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> send,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="3.2em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">sendReaction,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> sendTyping,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="4.300000000000001em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">getAttachment,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> listContacts,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="5.4em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">listAccounts,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="6.500000000000001em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">listGroups</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> and</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> more</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(1343.8507537841797, 537.5000076293945)"><g class="label" data-id="L_signal_bot_0" transform="translate(0, -11.5)"><g><rect class="background" style="" x="-48.6953125" y="1" width="97.390625" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">bot.Received</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(1343.8507537841797, 116.10000228881836)"><g class="label" data-id="L_bot_signal_0" transform="translate(0, -20.299999237060547)"><g><rect class="background" style="" x="-95.3828125" y="1" width="190.765625" height="38.599998474121094"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">bot.Network:</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Send,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> React,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Typing,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Media,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Groups</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(239.3038787841797, 365.2333399454752)"><g class="label" data-id="L_tgusers_tgapi_0" transform="translate(-0.05078125, -11.5)"><g><rect class="background" style="" x="-32.671875" y="1" width="65.4453125" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">MTProto</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(660.3585662841797, 365.2333399454752)"><g class="label" data-id="L_tgapi_telegram_0" transform="translate(0, -55.5)"><g><rect class="background" style="" x="-96.734375" y="1" width="193.46875" height="109"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">HTTPS,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> TLS</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> 1.3:</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">getUpdates,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="2.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">sendMessage,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> sendPhoto,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="3.2em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">getFile,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="4.300000000000001em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">setMessageReaction</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> and</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="5.4em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">more</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(1343.8507537841797, 500.50000762939453)"><g class="label" data-id="L_telegram_bot_0" transform="translate(0, -11.5)"><g><rect class="background" style="" x="-48.6953125" y="1" width="97.390625" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">bot.Received</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(1343.8507537841797, 161.9000015258789)"><g class="label" data-id="L_bot_telegram_0" transform="translate(-0.49609375, -11.5)"><g><rect class="background" style="" x="-44.6875" y="1" width="90.3671875" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">bot.Network</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(1343.8507537841797, 646.0000076293945)"><g class="label" data-id="L_feats_port_0" transform="translate(0, -11.5)"><g><rect class="background" style="" x="-86.9453125" y="1" width="173.890625" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">register</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> hooks</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> and</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> tools</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(1900.5796661376953, 619.0500068664551)"><g class="label" data-id="L_port_bot_0" transform="translate(-0.27734375, -11.5)"><g><rect class="background" style="" x="-89.15625" y="1" width="178.8671875" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">the</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Bot</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> implements</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Host</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(3117.4820098876953, 702.4666709899902)"><g class="label" data-id="L_model_llm_0" transform="translate(-0.05078125, -11.5)"><g><rect class="background" style="" x="-60.5390625" y="1" width="121.1796875" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">HTTPS,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> TLS</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> 1.3</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(1343.8507537841797, 198.9000015258789)"><g class="label" data-id="L_model_feats_0" transform="translate(-0.05078125, -11.5)"><g><rect class="background" style="" x="-79.3671875" y="1" width="158.8359375" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Tool.Run:</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> charts,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> mcp</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(3117.4820098876953, 753.2666702270508)"><g class="label" data-id="L_websearch_llm_0" transform="translate(0, -20.299999237060547)"><g><rect class="background" style="" x="-66.03125" y="1" width="132.0625" height="38.599998474121094"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">server</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> tool,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> run</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> by</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">OpenRouter</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(3117.4820098876953, 970.6673609415691)"><g class="label" data-id="L_links_web_0" transform="translate(0, -20.299999237060547)"><g><rect class="background" style="" x="-95.8125" y="1" width="191.625" height="38.599998474121094"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">HTTPS,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> private</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> addresses</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">refused</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(3117.4820098876953, 1123.0000076293945)"><g class="label" data-id="L_mcp_mcpsrv_0" transform="translate(0, -11.5)"><g><rect class="background" style="" x="-82.921875" y="1" width="165.84375" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">MCP:</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> list</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> and</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> call</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> tools</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(3117.4820098876953, 875.9668998718263)"><g class="label" data-id="L_schedule_disk_0" transform="translate(-0.046875, -11.5)"><g><rect class="background" style="" x="-21.125" y="1" width="42.34375" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Store</tspan></tspan></text></g></g></g><g class="edgeLabel" transform="translate(3117.4820098876953, 833.9668998718263)"><g class="label" data-id="L_bot_disk_0" transform="translate(0, -11.5)"><g><rect class="background" style="" x="-43.3671875" y="1" width="86.734375" height="21"></rect><text y="-10.1" text-anchor="middle" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em" text-anchor="middle"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">budget.json</tspan></tspan></text></g></g></g></g><g class="nodes"><g class="node default ext" id="g1069-flowchart-users-0" data-look="classic" transform="translate(88.85116195678711, 504.7333399454752)"><g class="basic label-container outer-path"><path d="M-39.53125 -16 C-8.853541698567344 -16, 21.82416660286531 -16, 39.53125 -16 C39.53125 -16, 39.53125 -16, 39.53125 -16 C39.8287459544915 -15.990459883780204, 40.126241908983 -15.98091976756041, 40.556373519691405 -15.967126284005381 C40.76626545318403 -15.94687826161333, 40.976157386676654 -15.926630239221279, 41.577284586952096 -15.868640221171939 C41.84800821062784 -15.824871725189102, 42.11873183430358 -15.781103229206266, 42.58978805922195 -15.704946511857047 C42.824150316251114 -15.651454856046794, 43.058512573280275 -15.59796320023654, 43.58972334255211 -15.476717808624471 C43.809712437376376 -15.411426200026952, 44.02970153220064 -15.346134591429434, 44.572981488377934 -15.184891952170698 C44.89416367042614 -15.066693940201414, 45.215345852474336 -14.948495928232132, 45.53552207806999 -14.830668117536348 C45.80614352002659 -14.710872032882012, 46.07676496198319 -14.591075948227676, 46.47338982588093 -14.415501886438706 C46.701260070682146 -14.296622125683768, 46.92913031548337 -14.17774236492883, 47.382730832063004 -13.941099265974232 C47.635725200440504 -13.787732593103858, 47.888719568818 -13.634365920233483, 48.25980841936878 -13.409409678269451 C48.49908213312966 -13.242502693541988, 48.73835584689054 -13.075595708814525, 49.101018487859456 -12.822617949887306 C49.29450853131015 -12.668314789221679, 49.48799857476084 -12.514011628556053, 49.90290432492461 -12.183135333906153 C50.180000311981196 -11.931484090019422, 50.45709629903779 -11.679832846132694, 50.662170809655784 -11.493589601563642 C50.94731782276734 -11.199151899520801, 51.232464835878886 -10.904714197477963, 51.37569795320505 -10.756814244181072 C51.61699386792725 -10.473374332621871, 51.85828978264945 -10.18993442106267, 52.04055371948848 -9.975836829739738 C52.26405092003508 -9.676370942021121, 52.487548120581685 -9.376905054302505, 52.65400607355129 -9.153866561954718 C52.818627151513596 -8.900964379255617, 52.98324822947591 -8.648062196556518, 53.213534208085534 -8.294281092968403 C53.38986672023664 -7.981184862041069, 53.566199232387746 -7.668088631113735, 53.716838901968 -7.400612643853364 C53.83770035461109 -7.149641251419186, 53.95856180725417 -6.8986698589850075, 54.161851968252996 -6.476533489958305 C54.26026928895161 -6.2334408050632675, 54.358686609650235 -5.990348120168231, 54.546744752796165 -5.52584087074093 C54.65169125654768 -5.209758722395985, 54.7566377602992 -4.893676574051041, 54.86993564858657 -4.552441386096524 C54.927842003528916 -4.331619357928371, 54.98574835847126 -4.110797329760218, 55.130096594909176 -3.560334943301032 C55.206008937285176 -3.1705411092795206, 55.28192127966118 -2.780747275258009, 55.326158534631205 -2.5535983205340735 C55.37158972974992 -2.2012429425975317, 55.41702092486863 -1.84888756466099, 55.45731580718717 -1.536368414522911 C55.48290123627834 -1.13785470424133, 55.5084866653695 -0.7393409939597488, 55.523029459211 -0.5128252411464826 C55.523029459211 -0.11984368198501999, 55.523029459211 0.27313787717644267, 55.523029459211 0.5128252411464788 C55.49701520373653 0.9180182684904905, 55.47100094826206 1.3232112958345024, 55.45731580718717 1.5363684145229002 C55.4118953675383 1.8886403751592669, 55.36647492788943 2.2409123357956338, 55.326158534631205 2.5535983205340624 C55.26627797808663 2.8610723226303443, 55.20639742154206 3.168546324726626, 55.130096594909176 3.5603349433010285 C55.027775747255184 3.950528681541589, 54.92545489960119 4.34072241978215, 54.86993564858657 4.552441386096513 C54.79456442870599 4.779447491603757, 54.71919320882541 5.006453597111, 54.546744752796165 5.525840870740919 C54.40478353353902 5.876487826939538, 54.26282231428187 6.227134783138157, 54.161851968253 6.4765334899583005 C54.03956974323592 6.730455146626734, 53.91728751821885 6.984376803295167, 53.716838901968 7.400612643853361 C53.533382616808105 7.726357855118047, 53.34992633164821 8.052103066382733, 53.21353420808554 8.294281092968399 C53.03855042043867 8.563103180520168, 52.86356663279179 8.831925268071936, 52.6540060735513 9.15386656195471 C52.47511432334086 9.393565209862988, 52.296222573130414 9.633263857771265, 52.04055371948848 9.975836829739734 C51.90538279677529 10.134616287002036, 51.770211874062106 10.29339574426434, 51.375697953205055 10.756814244181063 C51.19631595397437 10.942040885922774, 51.01693395474369 11.127267527664484, 50.662170809655784 11.493589601563638 C50.43744669987826 11.697678092189465, 50.21272259010074 11.901766582815291, 49.90290432492463 12.183135333906142 C49.652436226655034 12.382876977040125, 49.40196812838544 12.582618620174108, 49.10101848785946 12.822617949887304 C48.86836915691236 12.984904051928785, 48.63571982596526 13.147190153970266, 48.25980841936879 13.409409678269446 C48.044203975582334 13.540110359125142, 47.82859953179589 13.67081103998084, 47.382730832063004 13.94109926597423 C47.183554689950014 14.045009331736168, 46.98437854783703 14.148919397498103, 46.47338982588093 14.415501886438705 C46.22176662250305 14.526888014436969, 45.97014341912516 14.63827414243523, 45.535522078069995 14.830668117536346 C45.31648268328429 14.911276639595453, 45.097443288498596 14.99188516165456, 44.57298148837794 15.184891952170695 C44.29490153865001 15.267424621578504, 44.01682158892207 15.349957290986312, 43.58972334255213 15.476717808624468 C43.30672443126736 15.541310463384734, 43.02372551998259 15.605903118145, 42.58978805922196 15.704946511857045 C42.363876412727905 15.74147015489122, 42.13796476623385 15.777993797925394, 41.5772845869521 15.868640221171937 C41.24688443129441 15.90051352682391, 40.91648427563672 15.932386832475885, 40.556373519691405 15.967126284005381 C40.276475039404914 15.976102083478828, 39.996576559118424 15.985077882952273, 39.53125 16 C39.53125 16, 39.53125 16, 39.53125 16 C11.419256779070754 16, -16.692736441858493 16, -39.53125 16 C-39.93079212830454 15.98718746160685, -40.33033425660907 15.974374923213697, -40.5563735196914 15.967126284005381 C-40.89594947831425 15.934367799676876, -41.2355254369371 15.90160931534837, -41.577284586952096 15.868640221171937 C-41.94438831461072 15.809289737416018, -42.31149204226935 15.749939253660099, -42.58978805922196 15.704946511857045 C-42.86604586813568 15.641892469723167, -43.14230367704939 15.578838427589291, -43.58972334255211 15.476717808624471 C-43.88198414719161 15.389976335915737, -44.17424495183111 15.303234863207003, -44.57298148837792 15.184891952170702 C-44.782874807684294 15.107649270433381, -44.99276812699067 15.030406588696062, -45.53552207806999 14.830668117536348 C-45.843029357819084 14.694543766670776, -46.15053663756818 14.558419415805206, -46.47338982588093 14.415501886438708 C-46.73357923898204 14.279761236283132, -46.99376865208315 14.144020586127555, -47.382730832063 13.941099265974234 C-47.66328036857541 13.771028488248334, -47.94382990508781 13.600957710522435, -48.25980841936877 13.409409678269457 C-48.528860299858145 13.221730733508258, -48.79791218034752 13.034051788747059, -49.101018487859456 12.822617949887308 C-49.30773462369481 12.65776733250601, -49.51445075953017 12.492916715124714, -49.90290432492461 12.183135333906154 C-50.111860948057256 11.993366457466376, -50.32081757118989 11.803597581026597, -50.66217080965578 11.493589601563649 C-50.91430982943568 11.233235362642391, -51.16644884921558 10.972881123721132, -51.37569795320505 10.756814244181069 C-51.60113499285663 10.492003069675372, -51.82657203250821 10.227191895169673, -52.04055371948847 9.97583682973974 C-52.218440106229224 9.737485277290347, -52.396326492969976 9.499133724840954, -52.65400607355129 9.15386656195472 C-52.82823728003461 8.886200641166521, -53.00246848651792 8.618534720378321, -53.213534208085534 8.29428109296841 C-53.40156866198752 7.960406879512298, -53.589603115889496 7.626532666056187, -53.716838901968 7.400612643853366 C-53.85727937879155 7.108984988784448, -53.997719855615095 6.817357333715528, -54.161851968252996 6.476533489958307 C-54.304788333828 6.123477903501422, -54.447724699403004 5.770422317044538, -54.546744752796165 5.525840870740931 C-54.6679506316291 5.160788075230372, -54.78915651046203 4.795735279719812, -54.86993564858657 4.552441386096519 C-54.95328426750965 4.23459697862285, -55.03663288643274 3.91675257114918, -55.130096594909176 3.5603349433010343 C-55.17729384534498 3.3179870374556204, -55.22449109578078 3.0756391316102065, -55.326158534631205 2.5535983205340753 C-55.3698508562782 2.2147293018647796, -55.41354317792519 1.8758602831954838, -55.45731580718717 1.5363684145229202 C-55.481635984610776 1.1575620202563535, -55.50595616203438 0.778755625989787, -55.523029459211 0.5128252411464846 C-55.523029459211 0.22428975267455936, -55.523029459211 -0.06424573579736592, -55.523029459211 -0.5128252411464769 C-55.502056542060686 -0.8394953547967459, -55.48108362491036 -1.1661654684470149, -55.45731580718717 -1.5363684145228982 C-55.42159272720871 -1.8134295685158057, -55.38586964723025 -2.0904907225087133, -55.326158534631205 -2.5535983205340678 C-55.25144490948211 -2.937236994944395, -55.176731284333016 -3.320875669354722, -55.130096594909176 -3.5603349433010267 C-55.07458881012505 -3.772010183909013, -55.019081025340924 -3.9836854245169997, -54.869935648586576 -4.552441386096511 C-54.74736185143608 -4.921614133631368, -54.624788054285595 -5.290786881166226, -54.54674475279617 -5.525840870740911 C-54.45603718223133 -5.749890323747645, -54.36532961166649 -5.97393977675438, -54.161851968253 -6.476533489958299 C-53.99386017408023 -6.8253720450066275, -53.82586837990747 -7.1742106000549555, -53.716838901968 -7.400612643853359 C-53.597108229136914 -7.613206577510267, -53.477377556305825 -7.8258005111671745, -53.213534208085534 -8.294281092968404 C-53.090477594070656 -8.483329097422905, -52.96742098005578 -8.672377101877403, -52.654006073551294 -9.153866561954715 C-52.427961940207155 -9.456745107591674, -52.201917806863015 -9.759623653228633, -52.04055371948848 -9.975836829739734 C-51.87503915969803 -10.170259649714852, -51.709524599907574 -10.364682469689972, -51.375697953205055 -10.756814244181063 C-51.11383577968841 -11.02720843762128, -50.85197360617176 -11.297602631061498, -50.66217080965579 -11.493589601563633 C-50.3969350035715 -11.734469742894518, -50.13169919748721 -11.975349884225405, -49.90290432492463 -12.18313533390614 C-49.737995502146426 -12.314645731663681, -49.573086679368224 -12.446156129421222, -49.10101848785946 -12.822617949887302 C-48.86848662193326 -12.984822113415188, -48.635954756007045 -13.147026276943071, -48.25980841936879 -13.409409678269444 C-48.024064564740755 -13.55231898832962, -47.78832071011273 -13.695228298389798, -47.382730832063004 -13.941099265974229 C-47.026308517811685 -14.127044559019755, -46.66988620356037 -14.31298985206528, -46.473389825880936 -14.415501886438705 C-46.20561432454231 -14.534038157603293, -45.93783882320368 -14.652574428767881, -45.535522078069995 -14.830668117536344 C-45.32410369860372 -14.908472035510009, -45.11268531913745 -14.986275953483675, -44.57298148837794 -15.184891952170695 C-44.25212031535246 -15.280121864089994, -43.931259142326965 -15.37535177600929, -43.58972334255213 -15.476717808624466 C-43.340165335008074 -15.533677795328206, -43.09060732746401 -15.590637782031946, -42.589788059221966 -15.704946511857043 C-42.190249223842486 -15.769540852291254, -41.79071038846301 -15.834135192725464, -41.5772845869521 -15.868640221171937 C-41.23558073913608 -15.901603980411746, -40.89387689132006 -15.934567739651555, -40.556373519691405 -15.967126284005381 C-40.267134908103756 -15.976401603310194, -39.97789629651611 -15.985676922615005, -39.53125000000001 -16 C-39.53125000000001 -16, -39.53125 -16, -39.53125 -16" stroke="none" stroke-width="0" fill="#f3f4f6" style="fill:#f3f4f6 !important;stroke:#6b7280 !important"></path><path d="M-39.53125 -16 C-14.285494672522574 -16, 10.960260654954851 -16, 39.53125 -16 M-39.53125 -16 C-17.39374383940747 -16, 4.743762321185059 -16, 39.53125 -16 M39.53125 -16 C39.53125 -16, 39.53125 -16, 39.53125 -16 M39.53125 -16 C39.53125 -16, 39.53125 -16, 39.53125 -16 M39.53125 -16 C39.78122673938669 -15.991983732518076, 40.03120347877337 -15.98396746503615, 40.556373519691405 -15.967126284005381 M39.53125 -16 C39.79226914170174 -15.991629624168564, 40.053288283403475 -15.983259248337127, 40.556373519691405 -15.967126284005381 M40.556373519691405 -15.967126284005381 C40.913635529543676 -15.932661647585363, 41.270897539395946 -15.898197011165344, 41.577284586952096 -15.868640221171939 M40.556373519691405 -15.967126284005381 C40.83173823383019 -15.940562181206934, 41.107102947968976 -15.913998078408488, 41.577284586952096 -15.868640221171939 M41.577284586952096 -15.868640221171939 C41.96447173777732 -15.806042805307715, 42.35165888860256 -15.743445389443492, 42.58978805922195 -15.704946511857047 M41.577284586952096 -15.868640221171939 C41.85226219145586 -15.824183974558942, 42.12723979595962 -15.779727727945946, 42.58978805922195 -15.704946511857047 M42.58978805922195 -15.704946511857047 C42.92470115390306 -15.628504783508275, 43.25961424858416 -15.552063055159502, 43.58972334255211 -15.476717808624471 M42.58978805922195 -15.704946511857047 C42.98484292704056 -15.614777816251387, 43.37989779485917 -15.524609120645726, 43.58972334255211 -15.476717808624471 M43.58972334255211 -15.476717808624471 C43.82997231482707 -15.405413174745854, 44.07022128710203 -15.334108540867236, 44.572981488377934 -15.184891952170698 M43.58972334255211 -15.476717808624471 C43.899129386198645 -15.384887718975646, 44.20853542984518 -15.293057629326821, 44.572981488377934 -15.184891952170698 M44.572981488377934 -15.184891952170698 C44.83236995999847 -15.089434596853593, 45.091758431619006 -14.99397724153649, 45.53552207806999 -14.830668117536348 M44.572981488377934 -15.184891952170698 C44.89583617338073 -15.066078443653677, 45.21869085838353 -14.947264935136655, 45.53552207806999 -14.830668117536348 M45.53552207806999 -14.830668117536348 C45.849200732386564 -14.691811882217074, 46.16287938670314 -14.552955646897802, 46.47338982588093 -14.415501886438706 M45.53552207806999 -14.830668117536348 C45.78208539749038 -14.721521850069944, 46.02864871691076 -14.612375582603542, 46.47338982588093 -14.415501886438706 M46.47338982588093 -14.415501886438706 C46.71292852267583 -14.290534701752666, 46.952467219470726 -14.165567517066625, 47.382730832063004 -13.941099265974232 M46.47338982588093 -14.415501886438706 C46.81767758457956 -14.235887183252466, 47.16196534327819 -14.056272480066223, 47.382730832063004 -13.941099265974232 M47.382730832063004 -13.941099265974232 C47.6582763062706 -13.774061980224644, 47.9338217804782 -13.607024694475056, 48.25980841936878 -13.409409678269451 M47.382730832063004 -13.941099265974232 C47.67434641797654 -13.764320184070044, 47.96596200389007 -13.587541102165858, 48.25980841936878 -13.409409678269451 M48.25980841936878 -13.409409678269451 C48.42879207856109 -13.291533992801602, 48.597775737753395 -13.173658307333755, 49.101018487859456 -12.822617949887306 M48.25980841936878 -13.409409678269451 C48.510985123126105 -13.2341996829926, 48.76216182688343 -13.05898968771575, 49.101018487859456 -12.822617949887306 M49.101018487859456 -12.822617949887306 C49.31736036886612 -12.650091056883728, 49.53370224987279 -12.477564163880148, 49.90290432492461 -12.183135333906153 M49.101018487859456 -12.822617949887306 C49.32300258101944 -12.645591542837028, 49.54498667417942 -12.46856513578675, 49.90290432492461 -12.183135333906153 M49.90290432492461 -12.183135333906153 C50.07864955695188 -12.023528164143015, 50.254394788979155 -11.863920994379876, 50.662170809655784 -11.493589601563642 M49.90290432492461 -12.183135333906153 C50.1474935527081 -11.961005868709535, 50.39208278049158 -11.738876403512917, 50.662170809655784 -11.493589601563642 M50.662170809655784 -11.493589601563642 C50.91983261443204 -11.227532633704564, 51.1774944192083 -10.961475665845487, 51.37569795320505 -10.756814244181072 M50.662170809655784 -11.493589601563642 C50.92805551406738 -11.219041814718464, 51.19394021847897 -10.944494027873288, 51.37569795320505 -10.756814244181072 M51.37569795320505 -10.756814244181072 C51.56778986898836 -10.531172149562337, 51.75988178477168 -10.305530054943604, 52.04055371948848 -9.975836829739738 M51.37569795320505 -10.756814244181072 C51.560432312079435 -10.539814754564418, 51.745166670953815 -10.322815264947764, 52.04055371948848 -9.975836829739738 M52.04055371948848 -9.975836829739738 C52.27059487626515 -9.66760263683951, 52.500636033041815 -9.359368443939283, 52.65400607355129 -9.153866561954718 M52.04055371948848 -9.975836829739738 C52.23873356387037 -9.710293892823245, 52.43691340825225 -9.444750955906752, 52.65400607355129 -9.153866561954718 M52.65400607355129 -9.153866561954718 C52.79584831030727 -8.935958796323863, 52.93769054706325 -8.71805103069301, 53.213534208085534 -8.294281092968403 M52.65400607355129 -9.153866561954718 C52.836188393148724 -8.873985596250403, 53.01837071274616 -8.59410463054609, 53.213534208085534 -8.294281092968403 M53.213534208085534 -8.294281092968403 C53.340218477135295 -8.06934034509728, 53.46690274618505 -7.844399597226157, 53.716838901968 -7.400612643853364 M53.213534208085534 -8.294281092968403 C53.36959130490037 -8.017185915079049, 53.52564840171521 -7.740090737189694, 53.716838901968 -7.400612643853364 M53.716838901968 -7.400612643853364 C53.84952991744219 -7.12507691108831, 53.98222093291637 -6.849541178323254, 54.161851968252996 -6.476533489958305 M53.716838901968 -7.400612643853364 C53.80613831319459 -7.215180505740051, 53.89543772442117 -7.0297483676267385, 54.161851968252996 -6.476533489958305 M54.161851968252996 -6.476533489958305 C54.292089549680014 -6.154844145861236, 54.42232713110703 -5.8331548017641675, 54.546744752796165 -5.52584087074093 M54.161851968252996 -6.476533489958305 C54.275056759659094 -6.196915466519504, 54.388261551065185 -5.917297443080702, 54.546744752796165 -5.52584087074093 M54.546744752796165 -5.52584087074093 C54.63995928160424 -5.2450935616892655, 54.73317381041232 -4.964346252637601, 54.86993564858657 -4.552441386096524 M54.546744752796165 -5.52584087074093 C54.63367947785674 -5.264007330025889, 54.72061420291732 -5.002173789310848, 54.86993564858657 -4.552441386096524 M54.86993564858657 -4.552441386096524 C54.9587784565668 -4.213645254551373, 55.04762126454702 -3.8748491230062223, 55.130096594909176 -3.560334943301032 M54.86993564858657 -4.552441386096524 C54.96170025915473 -4.202503154966317, 55.053464869722895 -3.85256492383611, 55.130096594909176 -3.560334943301032 M55.130096594909176 -3.560334943301032 C55.181446563644 -3.2966637066674425, 55.23279653237883 -3.032992470033853, 55.326158534631205 -2.5535983205340735 M55.130096594909176 -3.560334943301032 C55.185170027738394 -3.2775445054971506, 55.24024346056761 -2.9947540676932687, 55.326158534631205 -2.5535983205340735 M55.326158534631205 -2.5535983205340735 C55.35900104656108 -2.298878283493447, 55.39184355849097 -2.0441582464528203, 55.45731580718717 -1.536368414522911 M55.326158534631205 -2.5535983205340735 C55.35818219746586 -2.305229115375974, 55.39020586030052 -2.056859910217874, 55.45731580718717 -1.536368414522911 M55.45731580718717 -1.536368414522911 C55.47269666233285 -1.296799180426115, 55.48807751747853 -1.0572299463293189, 55.523029459211 -0.5128252411464826 M55.45731580718717 -1.536368414522911 C55.48233476613253 -1.1466779340087412, 55.50735372507789 -0.7569874534945714, 55.523029459211 -0.5128252411464826 M55.523029459211 -0.5128252411464826 C55.523029459211 -0.27199889649583253, 55.523029459211 -0.031172551845182417, 55.523029459211 0.5128252411464788 M55.523029459211 -0.5128252411464826 C55.523029459211 -0.11613608119258917, 55.523029459211 0.2805530787613043, 55.523029459211 0.5128252411464788 M55.523029459211 0.5128252411464788 C55.50360798015233 0.8153304542210676, 55.48418650109365 1.1178356672956564, 55.45731580718717 1.5363684145229002 M55.523029459211 0.5128252411464788 C55.50246943987737 0.8330641380166743, 55.481909420543744 1.15330303488687, 55.45731580718717 1.5363684145229002 M55.45731580718717 1.5363684145229002 C55.41100191839049 1.8955697903181614, 55.364688029593815 2.2547711661134224, 55.326158534631205 2.5535983205340624 M55.45731580718717 1.5363684145229002 C55.42164836686328 1.8129980383422426, 55.385980926539396 2.089627662161585, 55.326158534631205 2.5535983205340624 M55.326158534631205 2.5535983205340624 C55.272550521827725 2.8288641362224016, 55.218942509024245 3.104129951910741, 55.130096594909176 3.5603349433010285 M55.326158534631205 2.5535983205340624 C55.28255932417931 2.7774710515081376, 55.238960113727416 3.0013437824822127, 55.130096594909176 3.5603349433010285 M55.130096594909176 3.5603349433010285 C55.03848334274558 3.909695979235468, 54.94687009058199 4.259057015169907, 54.86993564858657 4.552441386096513 M55.130096594909176 3.5603349433010285 C55.04084820192759 3.9006777462380264, 54.951599808946 4.241020549175024, 54.86993564858657 4.552441386096513 M54.86993564858657 4.552441386096513 C54.800224039297625 4.762401646238235, 54.73051243000868 4.972361906379957, 54.546744752796165 5.525840870740919 M54.86993564858657 4.552441386096513 C54.74686160661175 4.92312079133905, 54.623787564636935 5.2938001965815875, 54.546744752796165 5.525840870740919 M54.546744752796165 5.525840870740919 C54.46457976959589 5.72878996779748, 54.38241478639562 5.9317390648540425, 54.161851968253 6.4765334899583005 M54.546744752796165 5.525840870740919 C54.40905137208789 5.865946183210787, 54.27135799137961 6.206051495680655, 54.161851968253 6.4765334899583005 M54.161851968253 6.4765334899583005 C53.985823469686316 6.842060433638529, 53.80979497111963 7.207587377318756, 53.716838901968 7.400612643853361 M54.161851968253 6.4765334899583005 C53.99228418056564 6.8286446292605385, 53.822716392878284 7.1807557685627765, 53.716838901968 7.400612643853361 M53.716838901968 7.400612643853361 C53.57216745829893 7.657491441660026, 53.427496014629845 7.914370239466692, 53.21353420808554 8.294281092968399 M53.716838901968 7.400612643853361 C53.53402902868326 7.72521008537742, 53.35121915539851 8.04980752690148, 53.21353420808554 8.294281092968399 M53.21353420808554 8.294281092968399 C53.070420418263 8.514142305569298, 52.92730662844046 8.734003518170194, 52.6540060735513 9.15386656195471 M53.21353420808554 8.294281092968399 C53.05639396478906 8.535690704735408, 52.89925372149258 8.777100316502416, 52.6540060735513 9.15386656195471 M52.6540060735513 9.15386656195471 C52.45532663015897 9.420078916030786, 52.256647186766635 9.686291270106862, 52.04055371948848 9.975836829739734 M52.6540060735513 9.15386656195471 C52.43911354430838 9.441802974028068, 52.22422101506546 9.729739386101429, 52.04055371948848 9.975836829739734 M52.04055371948848 9.975836829739734 C51.87661829001979 10.168404713383845, 51.71268286055111 10.360972597027954, 51.375697953205055 10.756814244181063 M52.04055371948848 9.975836829739734 C51.78809745841248 10.272386319167804, 51.53564119733648 10.568935808595874, 51.375697953205055 10.756814244181063 M51.375697953205055 10.756814244181063 C51.1779587925007 10.960996162295332, 50.98021963179634 11.1651780804096, 50.662170809655784 11.493589601563638 M51.375697953205055 10.756814244181063 C51.16013082260237 10.979405004918904, 50.94456369199968 11.201995765656745, 50.662170809655784 11.493589601563638 M50.662170809655784 11.493589601563638 C50.442949520219 11.692680576352652, 50.22372823078222 11.891771551141664, 49.90290432492463 12.183135333906142 M50.662170809655784 11.493589601563638 C50.44126277369752 11.694212434914599, 50.22035473773924 11.89483526826556, 49.90290432492463 12.183135333906142 M49.90290432492463 12.183135333906142 C49.649770359497985 12.38500293515617, 49.396636394071336 12.586870536406199, 49.10101848785946 12.822617949887304 M49.90290432492463 12.183135333906142 C49.6071385006172 12.419000708132184, 49.31137267630977 12.654866082358229, 49.10101848785946 12.822617949887304 M49.10101848785946 12.822617949887304 C48.85275941180182 12.995792734382924, 48.60450033574418 13.168967518878544, 48.25980841936879 13.409409678269446 M49.10101848785946 12.822617949887304 C48.86912276306894 12.984378368897044, 48.637227038278404 13.146138787906784, 48.25980841936879 13.409409678269446 M48.25980841936879 13.409409678269446 C48.025191144933366 13.551636048796345, 47.79057387049794 13.693862419323246, 47.382730832063004 13.94109926597423 M48.25980841936879 13.409409678269446 C47.95071246839683 13.596785460198076, 47.64161651742487 13.784161242126707, 47.382730832063004 13.94109926597423 M47.382730832063004 13.94109926597423 C47.19032713874031 14.041476149540234, 46.99792344541761 14.141853033106235, 46.47338982588093 14.415501886438705 M47.382730832063004 13.94109926597423 C47.126417980571354 14.074817516421207, 46.870105129079704 14.208535766868184, 46.47338982588093 14.415501886438705 M46.47338982588093 14.415501886438705 C46.163147475141535 14.552836972098685, 45.852905124402135 14.690172057758666, 45.535522078069995 14.830668117536346 M46.47338982588093 14.415501886438705 C46.26181809069744 14.5091584175519, 46.050246355513956 14.602814948665095, 45.535522078069995 14.830668117536346 M45.535522078069995 14.830668117536346 C45.27315290627601 14.927222398070569, 45.010783734482025 15.023776678604793, 44.57298148837794 15.184891952170695 M45.535522078069995 14.830668117536346 C45.28247435274312 14.923792019604166, 45.02942662741625 15.016915921671988, 44.57298148837794 15.184891952170695 M44.57298148837794 15.184891952170695 C44.276406055709366 15.272913983830515, 43.97983062304078 15.360936015490337, 43.58972334255213 15.476717808624468 M44.57298148837794 15.184891952170695 C44.28085766094578 15.2715927707633, 43.98873383351362 15.358293589355906, 43.58972334255213 15.476717808624468 M43.58972334255213 15.476717808624468 C43.38570165463467 15.523284427525692, 43.18167996671722 15.569851046426914, 42.58978805922196 15.704946511857045 M43.58972334255213 15.476717808624468 C43.272520579574206 15.549117269332704, 42.95531781659628 15.621516730040943, 42.58978805922196 15.704946511857045 M42.58978805922196 15.704946511857045 C42.22644493243745 15.763689010827532, 41.863101805652946 15.82243150979802, 41.5772845869521 15.868640221171937 M42.58978805922196 15.704946511857045 C42.24643482050046 15.760457200749402, 41.90308158177897 15.815967889641758, 41.5772845869521 15.868640221171937 M41.5772845869521 15.868640221171937 C41.28361592331781 15.896970083964495, 40.98994725968351 15.925299946757056, 40.556373519691405 15.967126284005381 M41.5772845869521 15.868640221171937 C41.21682596203106 15.903413231203148, 40.85636733711001 15.93818624123436, 40.556373519691405 15.967126284005381 M40.556373519691405 15.967126284005381 C40.21298666384262 15.978138032110484, 39.869599807993836 15.989149780215588, 39.53125 16 M40.556373519691405 15.967126284005381 C40.24218553773662 15.977201681056863, 39.927997555781836 15.987277078108345, 39.53125 16 M39.53125 16 C39.53125 16, 39.53125 16, 39.53125 16 M39.53125 16 C39.53125 16, 39.53125 16, 39.53125 16 M39.53125 16 C12.151233391834303 16, -15.228783216331394 16, -39.53125 16 M39.53125 16 C9.273116365290598 16, -20.985017269418805 16, -39.53125 16 M-39.53125 16 C-39.82358186257768 15.990625486156585, -40.115913725155366 15.981250972313171, -40.5563735196914 15.967126284005381 M-39.53125 16 C-39.90203561234326 15.988109627102563, -40.272821224686524 15.976219254205127, -40.5563735196914 15.967126284005381 M-40.5563735196914 15.967126284005381 C-40.83043495022994 15.940687907408421, -41.104496380768495 15.91424953081146, -41.577284586952096 15.868640221171937 M-40.5563735196914 15.967126284005381 C-40.7735487032709 15.94617565523684, -40.99072388685039 15.925225026468297, -41.577284586952096 15.868640221171937 M-41.577284586952096 15.868640221171937 C-41.85855050062964 15.82316732949829, -42.139816414307184 15.777694437824643, -42.58978805922196 15.704946511857045 M-41.577284586952096 15.868640221171937 C-41.84907891072642 15.824698622700565, -42.12087323450074 15.780757024229194, -42.58978805922196 15.704946511857045 M-42.58978805922196 15.704946511857045 C-42.93232053846506 15.626765708703127, -43.27485301770816 15.54858490554921, -43.58972334255211 15.476717808624471 M-42.58978805922196 15.704946511857045 C-42.97776174500112 15.616394049842857, -43.36573543078028 15.527841587828668, -43.58972334255211 15.476717808624471 M-43.58972334255211 15.476717808624471 C-43.86709261863751 15.394396063423368, -44.144461894722895 15.312074318222265, -44.57298148837792 15.184891952170702 M-43.58972334255211 15.476717808624471 C-43.87269326607156 15.39273382066334, -44.155663189591 15.308749832702206, -44.57298148837792 15.184891952170702 M-44.57298148837792 15.184891952170702 C-44.8131795414124 15.09649684828755, -45.053377594446886 15.008101744404398, -45.53552207806999 14.830668117536348 M-44.57298148837792 15.184891952170702 C-44.77931947083822 15.108957667257911, -44.985657453298515 15.033023382345121, -45.53552207806999 14.830668117536348 M-45.53552207806999 14.830668117536348 C-45.819481225865985 14.704967826155897, -46.10344037366199 14.579267534775445, -46.47338982588093 14.415501886438708 M-45.53552207806999 14.830668117536348 C-45.86332535195582 14.685559332125717, -46.191128625841664 14.540450546715086, -46.47338982588093 14.415501886438708 M-46.47338982588093 14.415501886438708 C-46.80267947483156 14.243711687501252, -47.131969123782184 14.071921488563794, -47.382730832063 13.941099265974234 M-46.47338982588093 14.415501886438708 C-46.820276856212516 14.234531144906466, -47.1671638865441 14.053560403374224, -47.382730832063 13.941099265974234 M-47.382730832063 13.941099265974234 C-47.71112093824837 13.742027253770189, -48.03951104443374 13.542955241566144, -48.25980841936877 13.409409678269457 M-47.382730832063 13.941099265974234 C-47.68395560129354 13.758495040673445, -47.98518037052409 13.575890815372654, -48.25980841936877 13.409409678269457 M-48.25980841936877 13.409409678269457 C-48.436792941119506 13.285952937432606, -48.613777462870246 13.162496196595756, -49.101018487859456 12.822617949887308 M-48.25980841936877 13.409409678269457 C-48.45285239574785 13.27475055708646, -48.645896372126934 13.140091435903463, -49.101018487859456 12.822617949887308 M-49.101018487859456 12.822617949887308 C-49.35765500799691 12.617957154462307, -49.61429152813436 12.413296359037306, -49.90290432492461 12.183135333906154 M-49.101018487859456 12.822617949887308 C-49.33568056423975 12.635481188594133, -49.57034264062005 12.448344427300956, -49.90290432492461 12.183135333906154 M-49.90290432492461 12.183135333906154 C-50.11290927276863 11.992414396700651, -50.32291422061266 11.801693459495146, -50.66217080965578 11.493589601563649 M-49.90290432492461 12.183135333906154 C-50.102540317768955 12.001831207283843, -50.3021763106133 11.820527080661531, -50.66217080965578 11.493589601563649 M-50.66217080965578 11.493589601563649 C-50.807705400711036 11.34331318768695, -50.9532399917663 11.193036773810253, -51.37569795320505 10.756814244181069 M-50.66217080965578 11.493589601563649 C-50.908114975102514 11.239632058348384, -51.15405914054924 10.985674515133121, -51.37569795320505 10.756814244181069 M-51.37569795320505 10.756814244181069 C-51.550543321055535 10.551430926120611, -51.72538868890602 10.346047608060152, -52.04055371948847 9.97583682973974 M-51.37569795320505 10.756814244181069 C-51.59107305980151 10.503822388782122, -51.80644816639797 10.250830533383178, -52.04055371948847 9.97583682973974 M-52.04055371948847 9.97583682973974 C-52.260946693336564 9.680530322996265, -52.48133966718465 9.385223816252791, -52.65400607355129 9.15386656195472 M-52.04055371948847 9.97583682973974 C-52.2529426613996 9.691254996609478, -52.46533160331074 9.406673163479217, -52.65400607355129 9.15386656195472 M-52.65400607355129 9.15386656195472 C-52.79762982894551 8.93322190529079, -52.941253584339734 8.712577248626861, -53.213534208085534 8.29428109296841 M-52.65400607355129 9.15386656195472 C-52.79559422272951 8.936349143075368, -52.93718237190774 8.718831724196018, -53.213534208085534 8.29428109296841 M-53.213534208085534 8.29428109296841 C-53.37632061518061 8.005237343259934, -53.53910702227569 7.7161935935514565, -53.716838901968 7.400612643853366 M-53.213534208085534 8.29428109296841 C-53.41166757826104 7.942475231042498, -53.60980094843654 7.590669369116586, -53.716838901968 7.400612643853366 M-53.716838901968 7.400612643853366 C-53.86284592648424 7.09742593339554, -54.00885295100047 6.794239222937713, -54.161851968252996 6.476533489958307 M-53.716838901968 7.400612643853366 C-53.87966523471341 7.06250027998212, -54.04249156745882 6.724387916110874, -54.161851968252996 6.476533489958307 M-54.161851968252996 6.476533489958307 C-54.28976359916383 6.160589288605411, -54.41767523007466 5.844645087252516, -54.546744752796165 5.525840870740931 M-54.161851968252996 6.476533489958307 C-54.27842380451375 6.18859880063112, -54.3949956407745 5.900664111303933, -54.546744752796165 5.525840870740931 M-54.546744752796165 5.525840870740931 C-54.64381478968793 5.233481385632982, -54.740884826579695 4.941121900525033, -54.86993564858657 4.552441386096519 M-54.546744752796165 5.525840870740931 C-54.63729770062848 5.253109819522927, -54.72785064846079 4.980378768304922, -54.86993564858657 4.552441386096519 M-54.86993564858657 4.552441386096519 C-54.9560843117245 4.223919196484801, -55.04223297486243 3.8953970068730834, -55.130096594909176 3.5603349433010343 M-54.86993564858657 4.552441386096519 C-54.962547979435975 4.199270430129638, -55.05516031028538 3.8460994741627568, -55.130096594909176 3.5603349433010343 M-55.130096594909176 3.5603349433010343 C-55.2084217704773 3.158151720790441, -55.286746946045426 2.755968498279848, -55.326158534631205 2.5535983205340753 M-55.130096594909176 3.5603349433010343 C-55.20549330941526 3.1731887494135727, -55.28089002392134 2.786042555526111, -55.326158534631205 2.5535983205340753 M-55.326158534631205 2.5535983205340753 C-55.378330829857845 2.1489603013412317, -55.430503125084485 1.7443222821483886, -55.45731580718717 1.5363684145229202 M-55.326158534631205 2.5535983205340753 C-55.35610076217804 2.3213723164424382, -55.38604298972487 2.089146312350801, -55.45731580718717 1.5363684145229202 M-55.45731580718717 1.5363684145229202 C-55.481165681624105 1.1648873688955366, -55.50501555606103 0.793406323268153, -55.523029459211 0.5128252411464846 M-55.45731580718717 1.5363684145229202 C-55.47510256873979 1.2593252461253055, -55.492889330292414 0.9822820777276907, -55.523029459211 0.5128252411464846 M-55.523029459211 0.5128252411464846 C-55.523029459211 0.2897090881257104, -55.523029459211 0.06659293510493608, -55.523029459211 -0.5128252411464769 M-55.523029459211 0.5128252411464846 C-55.523029459211 0.1757125646307685, -55.523029459211 -0.16140011188494763, -55.523029459211 -0.5128252411464769 M-55.523029459211 -0.5128252411464769 C-55.497631321483524 -0.9084217372597736, -55.472233183756046 -1.3040182333730703, -55.45731580718717 -1.5363684145228982 M-55.523029459211 -0.5128252411464769 C-55.497077191336714 -0.9170527615821402, -55.471124923462426 -1.3212802820178036, -55.45731580718717 -1.5363684145228982 M-55.45731580718717 -1.5363684145228982 C-55.41145053147598 -1.8920904358158062, -55.365585255764785 -2.247812457108714, -55.326158534631205 -2.5535983205340678 M-55.45731580718717 -1.5363684145228982 C-55.42724015032773 -1.7696292700145597, -55.39716449346828 -2.0028901255062213, -55.326158534631205 -2.5535983205340678 M-55.326158534631205 -2.5535983205340678 C-55.25647457717217 -2.9114107143765846, -55.186790619713136 -3.2692231082191014, -55.130096594909176 -3.5603349433010267 M-55.326158534631205 -2.5535983205340678 C-55.26073800812885 -2.889518897490496, -55.19531748162649 -3.225439474446924, -55.130096594909176 -3.5603349433010267 M-55.130096594909176 -3.5603349433010267 C-55.02652795953321 -3.9552870369200916, -54.922959324157254 -4.350239130539157, -54.869935648586576 -4.552441386096511 M-55.130096594909176 -3.5603349433010267 C-55.03301738743268 -3.9305400358035927, -54.93593817995618 -4.300745128306159, -54.869935648586576 -4.552441386096511 M-54.869935648586576 -4.552441386096511 C-54.769532791453685 -4.854838794757937, -54.66912993432079 -5.157236203419362, -54.54674475279617 -5.525840870740911 M-54.869935648586576 -4.552441386096511 C-54.76795804519213 -4.859581679595993, -54.665980441797686 -5.166721973095475, -54.54674475279617 -5.525840870740911 M-54.54674475279617 -5.525840870740911 C-54.42501570417721 -5.826513974300796, -54.30328665555825 -6.127187077860682, -54.161851968253 -6.476533489958299 M-54.54674475279617 -5.525840870740911 C-54.46045325705742 -5.738982533548221, -54.37416176131865 -5.95212419635553, -54.161851968253 -6.476533489958299 M-54.161851968253 -6.476533489958299 C-53.99962768892751 -6.813395677021211, -53.83740340960202 -7.150257864084125, -53.716838901968 -7.400612643853359 M-54.161851968253 -6.476533489958299 C-54.0237197952077 -6.763367902841911, -53.88558762216239 -7.050202315725523, -53.716838901968 -7.400612643853359 M-53.716838901968 -7.400612643853359 C-53.57982228156306 -7.643899527819645, -53.44280566115812 -7.8871864117859305, -53.213534208085534 -8.294281092968404 M-53.716838901968 -7.400612643853359 C-53.563603975475246 -7.67269677256013, -53.41036904898249 -7.944780901266902, -53.213534208085534 -8.294281092968404 M-53.213534208085534 -8.294281092968404 C-53.074624679726355 -8.507683430959299, -52.93571515136718 -8.721085768950193, -52.654006073551294 -9.153866561954715 M-53.213534208085534 -8.294281092968404 C-53.03484762970024 -8.568791661432925, -52.856161051314935 -8.843302229897445, -52.654006073551294 -9.153866561954715 M-52.654006073551294 -9.153866561954715 C-52.44385845676507 -9.435445223606518, -52.23371083997885 -9.717023885258321, -52.04055371948848 -9.975836829739734 M-52.654006073551294 -9.153866561954715 C-52.48286534148441 -9.383179551682906, -52.311724609417524 -9.612492541411095, -52.04055371948848 -9.975836829739734 M-52.04055371948848 -9.975836829739734 C-51.788799843050796 -10.27156125820482, -51.537045966613114 -10.567285686669907, -51.375697953205055 -10.756814244181063 M-52.04055371948848 -9.975836829739734 C-51.88561971874809 -10.157831123003788, -51.73068571800769 -10.339825416267841, -51.375697953205055 -10.756814244181063 M-51.375697953205055 -10.756814244181063 C-51.17417873733565 -10.964899379601542, -50.97265952146625 -11.17298451502202, -50.66217080965579 -11.493589601563633 M-51.375697953205055 -10.756814244181063 C-51.17624292513624 -10.962767936224461, -50.976787897067425 -11.168721628267859, -50.66217080965579 -11.493589601563633 M-50.66217080965579 -11.493589601563633 C-50.37795031380478 -11.751711135833288, -50.09372981795377 -12.009832670102943, -49.90290432492463 -12.18313533390614 M-50.66217080965579 -11.493589601563633 C-50.39866433986851 -11.732899205425303, -50.13515787008124 -11.972208809286974, -49.90290432492463 -12.18313533390614 M-49.90290432492463 -12.18313533390614 C-49.71496974561956 -12.333008159752739, -49.5270351663145 -12.482880985599335, -49.10101848785946 -12.822617949887302 M-49.90290432492463 -12.18313533390614 C-49.639238918008935 -12.393401479490253, -49.37557351109325 -12.603667625074367, -49.10101848785946 -12.822617949887302 M-49.10101848785946 -12.822617949887302 C-48.77576855814515 -13.049498221013472, -48.45051862843085 -13.276378492139642, -48.25980841936879 -13.409409678269444 M-49.10101848785946 -12.822617949887302 C-48.824671976049665 -13.015385313678129, -48.548325464239866 -13.208152677468954, -48.25980841936879 -13.409409678269444 M-48.25980841936879 -13.409409678269444 C-47.91346831634812 -13.619363084040934, -47.56712821332746 -13.829316489812422, -47.382730832063004 -13.941099265974229 M-48.25980841936879 -13.409409678269444 C-48.07808712645132 -13.519570193948864, -47.896365833533864 -13.629730709628284, -47.382730832063004 -13.941099265974229 M-47.382730832063004 -13.941099265974229 C-47.14819616501878 -14.063455851544578, -46.91366149797456 -14.185812437114926, -46.473389825880936 -14.415501886438705 M-47.382730832063004 -13.941099265974229 C-47.1802837684803 -14.046715769371794, -46.97783670489759 -14.15233227276936, -46.473389825880936 -14.415501886438705 M-46.473389825880936 -14.415501886438705 C-46.106146594486916 -14.578069571093438, -45.738903363092895 -14.74063725574817, -45.535522078069995 -14.830668117536344 M-46.473389825880936 -14.415501886438705 C-46.24040709969826 -14.518636428132757, -46.00742437351558 -14.62177096982681, -45.535522078069995 -14.830668117536344 M-45.535522078069995 -14.830668117536344 C-45.19513137485972 -14.955935042854893, -44.85474067164945 -15.08120196817344, -44.57298148837794 -15.184891952170695 M-45.535522078069995 -14.830668117536344 C-45.20691450711965 -14.951598741261158, -44.87830693616931 -15.072529364985972, -44.57298148837794 -15.184891952170695 M-44.57298148837794 -15.184891952170695 C-44.26658819614051 -15.275827873015553, -43.96019490390308 -15.366763793860413, -43.58972334255213 -15.476717808624466 M-44.57298148837794 -15.184891952170695 C-44.21734153475591 -15.290444023613501, -43.861701581133886 -15.39599609505631, -43.58972334255213 -15.476717808624466 M-43.58972334255213 -15.476717808624466 C-43.223340274801174 -15.560342352965668, -42.856957207050215 -15.643966897306868, -42.589788059221966 -15.704946511857043 M-43.58972334255213 -15.476717808624466 C-43.331240597311236 -15.535714808468152, -43.072757852070346 -15.594711808311837, -42.589788059221966 -15.704946511857043 M-42.589788059221966 -15.704946511857043 C-42.29181561915397 -15.753120385156452, -41.99384317908597 -15.801294258455862, -41.5772845869521 -15.868640221171937 M-42.589788059221966 -15.704946511857043 C-42.20279805981602 -15.76751205380873, -41.81580806041007 -15.830077595760416, -41.5772845869521 -15.868640221171937 M-41.5772845869521 -15.868640221171937 C-41.25679209967208 -15.899557745971231, -40.936299612392055 -15.930475270770527, -40.556373519691405 -15.967126284005381 M-41.5772845869521 -15.868640221171937 C-41.35446004174257 -15.890135837062578, -41.13163549653303 -15.911631452953218, -40.556373519691405 -15.967126284005381 M-40.556373519691405 -15.967126284005381 C-40.228123660454656 -15.977652618091513, -39.89987380121791 -15.988178952177645, -39.53125000000001 -16 M-40.556373519691405 -15.967126284005381 C-40.23202489677309 -15.977527513036076, -39.907676273854776 -15.98792874206677, -39.53125000000001 -16 M-39.53125000000001 -16 C-39.53125000000001 -16, -39.53125 -16, -39.53125 -16 M-39.53125000000001 -16 C-39.53125000000001 -16, -39.53125 -16, -39.53125 -16" stroke="#6b7280" stroke-width="1.3" fill="none" stroke-dasharray="0 0" style="fill:#f3f4f6 !important;stroke:#6b7280 !important"></path></g><g class="label" style="color:#111 !important" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style="fill:#111 !important"><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Signal</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> users</tspan></tspan></text></g></g></g><g class="node default ext" id="g1069-flowchart-tgusers-1" data-look="classic" transform="translate(78.18709564208984, 365.7333399454752)"><g class="basic label-container outer-path"><path d="M-50.1953125 -16 C-13.779073118692743 -16, 22.637166262614514 -16, 50.1953125 -16 C50.1953125 -16, 50.1953125 -16, 50.1953125 -16 C50.51537949691282 -15.989736074381621, 50.835446493825636 -15.979472148763245, 51.220436019691405 -15.967126284005381 C51.493602135727684 -15.940774277321681, 51.76676825176396 -15.914422270637981, 52.241347086952096 -15.868640221171939 C52.58673238579796 -15.812801004557535, 52.93211768464382 -15.756961787943133, 53.25385055922195 -15.704946511857047 C53.48913548637211 -15.65124426261266, 53.72442041352227 -15.597542013368276, 54.25378584255211 -15.476717808624471 C54.459794280862376 -15.415575585494345, 54.66580271917264 -15.354433362364219, 55.237043988377934 -15.184891952170698 C55.55181312181775 -15.069054001370871, 55.866582255257576 -14.953216050571044, 56.19958457806999 -14.830668117536348 C56.40075711102136 -14.741615004769935, 56.601929643972746 -14.65256189200352, 57.13745232588093 -14.415501886438706 C57.352735153008126 -14.303188973421681, 57.568017980135316 -14.190876060404657, 58.046793332063004 -13.941099265974232 C58.31281501922462 -13.7798353558999, 58.57883670638624 -13.618571445825568, 58.92387091936878 -13.409409678269451 C59.21025686732906 -13.20963923842024, 59.49664281528933 -13.009868798571027, 59.765080987859456 -12.822617949887306 C59.94494137531096 -12.679184077180654, 60.12480176276246 -12.535750204474002, 60.56696682492461 -12.183135333906153 C60.82010644692749 -11.953240626910516, 61.07324606893037 -11.72334591991488, 61.326233309655784 -11.493589601563642 C61.562339352705635 -11.249790727448032, 61.798445395755486 -11.005991853332421, 62.03976045320505 -10.756814244181072 C62.23932859565072 -10.522390148315388, 62.43889673809639 -10.287966052449706, 62.70461621948848 -9.975836829739738 C62.87507295069422 -9.747440338851723, 63.04552968189995 -9.519043847963706, 63.31806857355129 -9.153866561954718 C63.541051562250175 -8.811304811996864, 63.76403455094906 -8.46874306203901, 63.877596708085534 -8.294281092968403 C64.0597868297115 -7.970784083271172, 64.24197695133746 -7.647287073573942, 64.380901401968 -7.400612643853364 C64.52568703252328 -7.09996218408911, 64.67047266307857 -6.799311724324855, 64.825914468253 -6.476533489958305 C64.93809028274173 -6.199457059399335, 65.05026609723043 -5.922380628840365, 65.21080725279616 -5.52584087074093 C65.29929320927364 -5.259335268153313, 65.38777916575113 -4.992829665565695, 65.53399814858656 -4.552441386096524 C65.61129820192946 -4.257662780645052, 65.68859825527234 -3.9628841751935813, 65.79415909490918 -3.560334943301032 C65.8397749143428 -3.326107351416257, 65.88539073377642 -3.091879759531482, 65.9902210346312 -2.5535983205340735 C66.0194289529132 -2.327067474094685, 66.04863687119521 -2.1005366276552966, 66.12137830718717 -1.536368414522911 C66.14325439948188 -1.195630618969103, 66.16513049177657 -0.854892823415295, 66.187091959211 -0.5128252411464826 C66.187091959211 -0.19393656417055394, 66.187091959211 0.12495211280537477, 66.187091959211 0.5128252411464788 C66.1706215049775 0.7693658605446669, 66.15415105074399 1.0259064799428552, 66.12137830718717 1.5363684145229002 C66.08689537741469 1.803811208413542, 66.05241244764223 2.071254002304184, 65.9902210346312 2.5535983205340624 C65.93981295872025 2.8124331365861504, 65.88940488280932 3.0712679526382387, 65.79415909490918 3.5603349433010285 C65.72632163791893 3.8190285677446973, 65.65848418092868 4.077722192188366, 65.53399814858658 4.552441386096513 C65.43125183549165 4.861896910736589, 65.32850552239672 5.171352435376665, 65.21080725279617 5.525840870740919 C65.12674969614007 5.733464660823814, 65.04269213948395 5.941088450906709, 64.825914468253 6.4765334899583005 C64.65112269956755 6.83949233757837, 64.4763309308821 7.202451185198438, 64.380901401968 7.400612643853361 C64.2466784690256 7.638939052838379, 64.11245553608319 7.877265461823397, 63.87759670808554 8.294281092968399 C63.670837455432974 8.611918827675979, 63.464078202780414 8.929556562383558, 63.3180685735513 9.15386656195471 C63.17861164096585 9.340726146831292, 63.0391547083804 9.527585731707875, 62.70461621948848 9.975836829739734 C62.52379436438093 10.18824046980409, 62.34297250927339 10.400644109868445, 62.039760453205055 10.756814244181063 C61.82188889218045 10.981784518526784, 61.60401733115586 11.206754792872506, 61.326233309655784 11.493589601563638 C61.11565516320848 11.684831102574638, 60.90507701676118 11.876072603585635, 60.56696682492463 12.183135333906142 C60.39666203591388 12.318948871141448, 60.22635724690313 12.454762408376753, 59.76508098785946 12.822617949887304 C59.45618040735887 13.038093622753907, 59.14727982685828 13.25356929562051, 58.92387091936879 13.409409678269446 C58.714873075311125 13.536105399544862, 58.50587523125346 13.66280112082028, 58.046793332063004 13.94109926597423 C57.83234577924679 14.052976416918234, 57.61789822643058 14.164853567862238, 57.13745232588093 14.415501886438705 C56.83559290022206 14.549126099836174, 56.533733474563185 14.682750313233644, 56.199584578069995 14.830668117536346 C55.974452278552526 14.91351888485894, 55.74931997903505 14.996369652181532, 55.23704398837794 15.184891952170695 C54.94234536606762 15.272356956367762, 54.647646743757306 15.35982196056483, 54.25378584255213 15.476717808624468 C53.92831889302147 15.55100351598451, 53.602851943490805 15.625289223344552, 53.25385055922196 15.704946511857045 C52.9891129314784 15.747747238439658, 52.724375303734845 15.79054796502227, 52.2413470869521 15.868640221171937 C51.87794903044688 15.90369679463289, 51.51455097394166 15.938753368093844, 51.220436019691405 15.967126284005381 C50.87509278000934 15.978200769532148, 50.52974954032727 15.989275255058914, 50.1953125 16 C50.1953125 16, 50.1953125 16, 50.1953125 16 C28.372116867123385 16, 6.5489212342467695 16, -50.1953125 16 C-50.54346550242734 15.988835410850864, -50.89161850485468 15.977670821701729, -51.2204360196914 15.967126284005381 C-51.479726677855744 15.942112826054908, -51.7390173360201 15.917099368104433, -52.241347086952096 15.868640221171937 C-52.4629251431155 15.832817199414928, -52.68450319927889 15.796994177657918, -53.25385055922196 15.704946511857045 C-53.498366374794955 15.649137372567322, -53.74288219036795 15.593328233277601, -54.25378584255211 15.476717808624471 C-54.51970695067662 15.397793819581498, -54.78562805880113 15.318869830538524, -55.23704398837792 15.184891952170702 C-55.52647738562722 15.078377786489964, -55.81591078287652 14.971863620809227, -56.19958457806999 14.830668117536348 C-56.49377450734926 14.700438962678602, -56.787964436628535 14.570209807820856, -57.13745232588093 14.415501886438708 C-57.425368731226584 14.26529608218914, -57.71328513657224 14.11509027793957, -58.046793332063 13.941099265974234 C-58.23990830314005 13.824031835637788, -58.43302327421709 13.706964405301342, -58.92387091936877 13.409409678269457 C-59.244953839315585 13.18543613277014, -59.56603675926241 12.961462587270823, -59.765080987859456 12.822617949887308 C-60.00275381773034 12.633080192804908, -60.24042664760121 12.443542435722506, -60.56696682492461 12.183135333906154 C-60.749049266364054 12.017772878228259, -60.93113170780349 11.852410422550363, -61.32623330965578 11.493589601563649 C-61.519913880570506 11.293598510623594, -61.71359445148523 11.09360741968354, -62.03976045320505 10.756814244181069 C-62.27540636104848 10.480011152196163, -62.511052268891916 10.203208060211256, -62.70461621948847 9.97583682973974 C-62.86195357500558 9.765019107074773, -63.01929093052269 9.554201384409804, -63.31806857355129 9.15386656195472 C-63.48630851506828 8.895404833034698, -63.654548456585275 8.636943104114678, -63.877596708085534 8.29428109296841 C-64.03075670218348 8.022330014316344, -64.18391669628144 7.750378935664278, -64.380901401968 7.400612643853366 C-64.55427533159583 7.040597969373366, -64.72764926122365 6.680583294893364, -64.825914468253 6.476533489958307 C-64.91311616867422 6.261143603987696, -65.00031786909545 6.045753718017085, -65.21080725279616 5.525840870740931 C-65.30507635234761 5.241917362633255, -65.39934545189905 4.957993854525578, -65.53399814858656 4.552441386096519 C-65.60615287834955 4.277284129452562, -65.67830760811253 4.0021268728086055, -65.79415909490918 3.5603349433010343 C-65.83721893672296 3.3392317562880067, -65.88027877853676 3.118128569274979, -65.9902210346312 2.5535983205340753 C-66.03665510600271 2.1934648324212334, -66.0830891773742 1.8333313443083914, -66.12137830718717 1.5363684145229202 C-66.1403165323608 1.2413902707833735, -66.15925475753444 0.9464121270438268, -66.187091959211 0.5128252411464846 C-66.187091959211 0.13727991295822167, -66.187091959211 -0.2382654152300413, -66.187091959211 -0.5128252411464769 C-66.16654646429932 -0.8328379084211248, -66.14600096938761 -1.1528505756957728, -66.12137830718717 -1.5363684145228982 C-66.08917362617836 -1.7861415608936524, -66.05696894516956 -2.0359147072644066, -65.9902210346312 -2.5535983205340678 C-65.92238683182191 -2.901912615195955, -65.85455262901262 -3.250226909857842, -65.79415909490918 -3.5603349433010267 C-65.70957296831055 -3.8828985038807655, -65.62498684171192 -4.205462064460503, -65.53399814858658 -4.552441386096511 C-65.40548297882478 -4.939508601307458, -65.27696780906298 -5.326575816518406, -65.21080725279617 -5.525840870740911 C-65.12170981990162 -5.74591325257212, -65.03261238700708 -5.965985634403331, -64.825914468253 -6.476533489958299 C-64.6703553504286 -6.799555326552612, -64.51479623260417 -7.122577163146927, -64.380901401968 -7.400612643853359 C-64.22554624264744 -7.676461460642746, -64.07019108332689 -7.952310277432134, -63.877596708085534 -8.294281092968404 C-63.728881455297945 -8.522747656887036, -63.58016620251035 -8.751214220805668, -63.318068573551294 -9.153866561954715 C-63.188169115398786 -9.327920001794986, -63.05826965724628 -9.501973441635258, -62.70461621948848 -9.975836829739734 C-62.47107100782921 -10.250172324453722, -62.23752579616994 -10.524507819167708, -62.039760453205055 -10.756814244181063 C-61.756105987556126 -11.049710768428321, -61.47245152190719 -11.342607292675579, -61.32623330965579 -11.493589601563633 C-61.10902316442086 -11.690854108400481, -60.89181301918594 -11.88811861523733, -60.56696682492463 -12.18313533390614 C-60.39361191815737 -12.321381258885218, -60.22025701139012 -12.459627183864296, -59.76508098785946 -12.822617949887302 C-59.472906439537795 -13.026426266764153, -59.18073189121612 -13.230234583641005, -58.92387091936879 -13.409409678269444 C-58.57916591475379 -13.618371877778515, -58.234460910138786 -13.827334077287585, -58.046793332063004 -13.941099265974229 C-57.731519257727335 -14.105577548612468, -57.416245183391666 -14.270055831250705, -57.137452325880936 -14.415501886438705 C-56.79601170380683 -14.56664752135472, -56.45457108173273 -14.717793156270735, -56.199584578069995 -14.830668117536344 C-55.866238722881825 -14.953342473660898, -55.532892867693654 -15.07601682978545, -55.23704398837794 -15.184891952170695 C-55.003699693634765 -15.254147314001273, -54.77035539889158 -15.32340267583185, -54.25378584255213 -15.476717808624466 C-54.048147923692035 -15.523653321691455, -53.84251000483194 -15.570588834758444, -53.253850559221966 -15.704946511857043 C-53.04315287977748 -15.73901047868472, -52.832455200333 -15.773074445512396, -52.2413470869521 -15.868640221171937 C-51.94572706334077 -15.897158329314628, -51.650107039729434 -15.925676437457318, -51.220436019691405 -15.967126284005381 C-50.9355845910625 -15.97626091489184, -50.6507331624336 -15.985395545778298, -50.19531250000001 -16 C-50.19531250000001 -16, -50.1953125 -16, -50.1953125 -16" stroke="none" stroke-width="0" fill="#f3f4f6" style="fill:#f3f4f6 !important;stroke:#6b7280 !important"></path><path d="M-50.1953125 -16 C-17.22995829966105 -16, 15.7353959006779 -16, 50.1953125 -16 M-50.1953125 -16 C-17.672874107829543 -16, 14.849564284340914 -16, 50.1953125 -16 M50.1953125 -16 C50.1953125 -16, 50.1953125 -16, 50.1953125 -16 M50.1953125 -16 C50.1953125 -16, 50.1953125 -16, 50.1953125 -16 M50.1953125 -16 C50.58137195703254 -15.987619824632114, 50.96743141406507 -15.975239649264228, 51.220436019691405 -15.967126284005381 M50.1953125 -16 C50.47011443623712 -15.991187636774397, 50.74491637247423 -15.982375273548792, 51.220436019691405 -15.967126284005381 M51.220436019691405 -15.967126284005381 C51.47529047337059 -15.942540781366274, 51.73014492704977 -15.917955278727169, 52.241347086952096 -15.868640221171939 M51.220436019691405 -15.967126284005381 C51.59759723722451 -15.93074199495269, 51.97475845475762 -15.894357705900001, 52.241347086952096 -15.868640221171939 M52.241347086952096 -15.868640221171939 C52.60357349354615 -15.810078264861549, 52.96579990014021 -15.751516308551158, 53.25385055922195 -15.704946511857047 M52.241347086952096 -15.868640221171939 C52.48383051294768 -15.829437381344027, 52.72631393894326 -15.790234541516115, 53.25385055922195 -15.704946511857047 M53.25385055922195 -15.704946511857047 C53.49142077837638 -15.650722659625611, 53.7289909975308 -15.596498807394175, 54.25378584255211 -15.476717808624471 M53.25385055922195 -15.704946511857047 C53.51079608618664 -15.646300372053618, 53.76774161315132 -15.587654232250191, 54.25378584255211 -15.476717808624471 M54.25378584255211 -15.476717808624471 C54.63648410507421 -15.363134973132086, 55.01918236759631 -15.249552137639702, 55.237043988377934 -15.184891952170698 M54.25378584255211 -15.476717808624471 C54.50990935121747 -15.400701695672325, 54.766032859882834 -15.324685582720178, 55.237043988377934 -15.184891952170698 M55.237043988377934 -15.184891952170698 C55.51567454072421 -15.082353333274677, 55.79430509307049 -14.979814714378655, 56.19958457806999 -14.830668117536348 M55.237043988377934 -15.184891952170698 C55.43569446351299 -15.111786741016136, 55.63434493864804 -15.038681529861574, 56.19958457806999 -14.830668117536348 M56.19958457806999 -14.830668117536348 C56.52333729047669 -14.687352395536891, 56.8470900028834 -14.544036673537434, 57.13745232588093 -14.415501886438706 M56.19958457806999 -14.830668117536348 C56.5323933438851 -14.68334354933127, 56.865202109700206 -14.536018981126192, 57.13745232588093 -14.415501886438706 M57.13745232588093 -14.415501886438706 C57.48143362512878 -14.23604706295164, 57.82541492437663 -14.056592239464575, 58.046793332063004 -13.941099265974232 M57.13745232588093 -14.415501886438706 C57.41207616676104 -14.272230804556516, 57.68670000764116 -14.128959722674328, 58.046793332063004 -13.941099265974232 M58.046793332063004 -13.941099265974232 C58.269411781696405 -13.806146653555242, 58.49203023132981 -13.671194041136252, 58.92387091936878 -13.409409678269451 M58.046793332063004 -13.941099265974232 C58.28436229266242 -13.797083565948688, 58.52193125326183 -13.653067865923145, 58.92387091936878 -13.409409678269451 M58.92387091936878 -13.409409678269451 C59.19569215787875 -13.21979894923666, 59.467513396388725 -13.030188220203867, 59.765080987859456 -12.822617949887306 M58.92387091936878 -13.409409678269451 C59.183364491089364 -13.228398195932844, 59.44285806280995 -13.047386713596236, 59.765080987859456 -12.822617949887306 M59.765080987859456 -12.822617949887306 C59.97033876932824 -12.658930331304914, 60.17559655079702 -12.495242712722522, 60.56696682492461 -12.183135333906153 M59.765080987859456 -12.822617949887306 C60.05608513634649 -12.59054988541451, 60.34708928483353 -12.358481820941716, 60.56696682492461 -12.183135333906153 M60.56696682492461 -12.183135333906153 C60.79257469697603 -11.97824423376624, 61.01818256902746 -11.773353133626328, 61.326233309655784 -11.493589601563642 M60.56696682492461 -12.183135333906153 C60.816079250360886 -11.956898020278526, 61.06519167579715 -11.730660706650898, 61.326233309655784 -11.493589601563642 M61.326233309655784 -11.493589601563642 C61.56792706164976 -11.244020959203782, 61.80962081364374 -10.994452316843924, 62.03976045320505 -10.756814244181072 M61.326233309655784 -11.493589601563642 C61.55242775844855 -11.260025262275493, 61.77862220724132 -11.026460922987344, 62.03976045320505 -10.756814244181072 M62.03976045320505 -10.756814244181072 C62.2029416422823 -10.565132334218232, 62.366122831359554 -10.373450424255392, 62.70461621948848 -9.975836829739738 M62.03976045320505 -10.756814244181072 C62.196283777168176 -10.572953041424542, 62.352807101131305 -10.38909183866801, 62.70461621948848 -9.975836829739738 M62.70461621948848 -9.975836829739738 C62.82771785655243 -9.810891850863884, 62.950819493616386 -9.645946871988032, 63.31806857355129 -9.153866561954718 M62.70461621948848 -9.975836829739738 C62.94250355291698 -9.657089474927453, 63.18039088634548 -9.338342120115168, 63.31806857355129 -9.153866561954718 M63.31806857355129 -9.153866561954718 C63.514843013618936 -8.851568180675166, 63.711617453686586 -8.549269799395613, 63.877596708085534 -8.294281092968403 M63.31806857355129 -9.153866561954718 C63.43733568753553 -8.970640247170515, 63.55660280151977 -8.787413932386313, 63.877596708085534 -8.294281092968403 M63.877596708085534 -8.294281092968403 C64.00380097930822 -8.0701926298443, 64.1300052505309 -7.846104166720199, 64.380901401968 -7.400612643853364 M63.877596708085534 -8.294281092968403 C64.00216195290744 -8.073102887188295, 64.12672719772935 -7.851924681408186, 64.380901401968 -7.400612643853364 M64.380901401968 -7.400612643853364 C64.5448972182735 -7.06007182234665, 64.708893034579 -6.719531000839935, 64.825914468253 -6.476533489958305 M64.380901401968 -7.400612643853364 C64.47677467869117 -7.201529733378218, 64.57264795541433 -7.002446822903071, 64.825914468253 -6.476533489958305 M64.825914468253 -6.476533489958305 C64.94309176858495 -6.187103292669402, 65.0602690689169 -5.897673095380499, 65.21080725279616 -5.52584087074093 M64.825914468253 -6.476533489958305 C64.95305131002678 -6.162503032753456, 65.08018815180056 -5.848472575548607, 65.21080725279616 -5.52584087074093 M65.21080725279616 -5.52584087074093 C65.33238859613033 -5.159657235974797, 65.45396993946449 -4.793473601208666, 65.53399814858656 -4.552441386096524 M65.21080725279616 -5.52584087074093 C65.33038990039132 -5.165676989091728, 65.4499725479865 -4.805513107442526, 65.53399814858656 -4.552441386096524 M65.53399814858656 -4.552441386096524 C65.60276447545361 -4.2902055782378765, 65.67153080232066 -4.0279697703792285, 65.79415909490918 -3.560334943301032 M65.53399814858656 -4.552441386096524 C65.60422772318543 -4.284625580460894, 65.67445729778429 -4.016809774825265, 65.79415909490918 -3.560334943301032 M65.79415909490918 -3.560334943301032 C65.85981910091795 -3.2231846896932024, 65.92547910692672 -2.8860344360853727, 65.9902210346312 -2.5535983205340735 M65.79415909490918 -3.560334943301032 C65.8385611638318 -3.332339703763936, 65.88296323275443 -3.1043444642268407, 65.9902210346312 -2.5535983205340735 M65.9902210346312 -2.5535983205340735 C66.04079203039873 -2.1613796637338063, 66.09136302616625 -1.769161006933539, 66.12137830718717 -1.536368414522911 M65.9902210346312 -2.5535983205340735 C66.04078732315031 -2.161416172222973, 66.09135361166942 -1.769234023911873, 66.12137830718717 -1.536368414522911 M66.12137830718717 -1.536368414522911 C66.14388783938118 -1.185764281233892, 66.16639737157519 -0.835160147944873, 66.187091959211 -0.5128252411464826 M66.12137830718717 -1.536368414522911 C66.13495453005122 -1.3249077848855695, 66.14853075291526 -1.1134471552482281, 66.187091959211 -0.5128252411464826 M66.187091959211 -0.5128252411464826 C66.187091959211 -0.23099716001236942, 66.187091959211 0.05083092112174381, 66.187091959211 0.5128252411464788 M66.187091959211 -0.5128252411464826 C66.187091959211 -0.22107926515201903, 66.187091959211 0.07066671084244458, 66.187091959211 0.5128252411464788 M66.187091959211 0.5128252411464788 C66.16464250947953 0.8624935415838437, 66.14219305974805 1.2121618420212086, 66.12137830718717 1.5363684145229002 M66.187091959211 0.5128252411464788 C66.16516293386036 0.8543875117735551, 66.1432339085097 1.1959497824006313, 66.12137830718717 1.5363684145229002 M66.12137830718717 1.5363684145229002 C66.09011345929521 1.7788524008304754, 66.05884861140323 2.0213363871380503, 65.9902210346312 2.5535983205340624 M66.12137830718717 1.5363684145229002 C66.09465894050437 1.7435985461788932, 66.06793957382159 1.950828677834886, 65.9902210346312 2.5535983205340624 M65.9902210346312 2.5535983205340624 C65.93962546245344 2.813395890288904, 65.88902989027568 3.073193460043745, 65.79415909490918 3.5603349433010285 M65.9902210346312 2.5535983205340624 C65.9361598422822 2.8311911174091504, 65.8820986499332 3.1087839142842384, 65.79415909490918 3.5603349433010285 M65.79415909490918 3.5603349433010285 C65.72143887876419 3.837648644602903, 65.6487186626192 4.114962345904777, 65.53399814858658 4.552441386096513 M65.79415909490918 3.5603349433010285 C65.70321711615969 3.907136122775737, 65.61227513741021 4.253937302250446, 65.53399814858658 4.552441386096513 M65.53399814858658 4.552441386096513 C65.42676250892936 4.875418047065166, 65.31952686927214 5.198394708033819, 65.21080725279617 5.525840870740919 M65.53399814858658 4.552441386096513 C65.42574136739358 4.878493562674083, 65.3174845862006 5.204545739251654, 65.21080725279617 5.525840870740919 M65.21080725279617 5.525840870740919 C65.08850245504138 5.827936085797678, 64.96619765728657 6.130031300854437, 64.825914468253 6.4765334899583005 M65.21080725279617 5.525840870740919 C65.07047190911548 5.872471882831497, 64.93013656543481 6.2191028949220755, 64.825914468253 6.4765334899583005 M64.825914468253 6.4765334899583005 C64.66659310507876 6.8073677095207, 64.5072717419045 7.1382019290831, 64.380901401968 7.400612643853361 M64.825914468253 6.4765334899583005 C64.69707178972074 6.744078068722237, 64.56822911118847 7.011622647486172, 64.380901401968 7.400612643853361 M64.380901401968 7.400612643853361 C64.2043851678126 7.714035091803204, 64.02786893365719 8.027457539753048, 63.87759670808554 8.294281092968399 M64.380901401968 7.400612643853361 C64.20529320204723 7.71242278507117, 64.02968500212647 8.02423292628898, 63.87759670808554 8.294281092968399 M63.87759670808554 8.294281092968399 C63.753827825573595 8.484423333105271, 63.63005894306164 8.674565573242145, 63.3180685735513 9.15386656195471 M63.87759670808554 8.294281092968399 C63.7259809339884 8.527203636517527, 63.57436515989126 8.760126180066655, 63.3180685735513 9.15386656195471 M63.3180685735513 9.15386656195471 C63.11764076282997 9.422421568972107, 62.917212952108635 9.690976575989504, 62.70461621948848 9.975836829739734 M63.3180685735513 9.15386656195471 C63.083920751597574 9.467603312067299, 62.84977292964384 9.78134006217989, 62.70461621948848 9.975836829739734 M62.70461621948848 9.975836829739734 C62.46621591251068 10.255875395677622, 62.22781560553287 10.535913961615508, 62.039760453205055 10.756814244181063 M62.70461621948848 9.975836829739734 C62.565340285885895 10.139438266374457, 62.42606435228331 10.30303970300918, 62.039760453205055 10.756814244181063 M62.039760453205055 10.756814244181063 C61.80953019685301 10.99454588612013, 61.57929994050096 11.2322775280592, 61.326233309655784 11.493589601563638 M62.039760453205055 10.756814244181063 C61.84058327702176 10.962481031340602, 61.64140610083846 11.168147818500138, 61.326233309655784 11.493589601563638 M61.326233309655784 11.493589601563638 C61.03505061766376 11.75803401815895, 60.74386792567173 12.022478434754264, 60.56696682492463 12.183135333906142 M61.326233309655784 11.493589601563638 C61.16937525014768 11.636043940972067, 61.012517190639585 11.778498280380498, 60.56696682492463 12.183135333906142 M60.56696682492463 12.183135333906142 C60.39073811027136 12.323673044199076, 60.21450939561809 12.46421075449201, 59.76508098785946 12.822617949887304 M60.56696682492463 12.183135333906142 C60.32747330267199 12.374125044712338, 60.087979780419346 12.565114755518534, 59.76508098785946 12.822617949887304 M59.76508098785946 12.822617949887304 C59.55665631507975 12.968005979059766, 59.348231642300036 13.113394008232229, 58.92387091936879 13.409409678269446 M59.76508098785946 12.822617949887304 C59.57902052648005 12.95240567331802, 59.392960065100645 13.082193396748739, 58.92387091936879 13.409409678269446 M58.92387091936879 13.409409678269446 C58.702735709266705 13.54346314216807, 58.48160049916462 13.677516606066693, 58.046793332063004 13.94109926597423 M58.92387091936879 13.409409678269446 C58.65165746635337 13.574427073191206, 58.37944401333795 13.739444468112964, 58.046793332063004 13.94109926597423 M58.046793332063004 13.94109926597423 C57.838680712555984 14.049671486268549, 57.63056809304896 14.15824370656287, 57.13745232588093 14.415501886438705 M58.046793332063004 13.94109926597423 C57.81276119321273 14.06319368290768, 57.578729054362455 14.185288099841129, 57.13745232588093 14.415501886438705 M57.13745232588093 14.415501886438705 C56.94181227200117 14.50210593483527, 56.74617221812142 14.588709983231839, 56.199584578069995 14.830668117536346 M57.13745232588093 14.415501886438705 C56.91105488377427 14.515721318217816, 56.68465744166762 14.615940749996929, 56.199584578069995 14.830668117536346 M56.199584578069995 14.830668117536346 C55.9971336453999 14.905171932194847, 55.79468271272981 14.979675746853347, 55.23704398837794 15.184891952170695 M56.199584578069995 14.830668117536346 C55.93056551213361 14.929669620585921, 55.66154644619723 15.028671123635494, 55.23704398837794 15.184891952170695 M55.23704398837794 15.184891952170695 C54.99330966466762 15.257231020060345, 54.74957534095731 15.329570087949994, 54.25378584255213 15.476717808624468 M55.23704398837794 15.184891952170695 C54.93778056264833 15.273711766061467, 54.638517136918715 15.36253157995224, 54.25378584255213 15.476717808624468 M54.25378584255213 15.476717808624468 C53.88914192679285 15.559945402872595, 53.52449801103358 15.64317299712072, 53.25385055922196 15.704946511857045 M54.25378584255213 15.476717808624468 C53.9906475812395 15.536777399631447, 53.72750931992687 15.596836990638424, 53.25385055922196 15.704946511857045 M53.25385055922196 15.704946511857045 C52.993782653952266 15.746992273924322, 52.73371474868258 15.789038035991597, 52.2413470869521 15.868640221171937 M53.25385055922196 15.704946511857045 C52.94438807670643 15.754978006112761, 52.63492559419091 15.805009500368476, 52.2413470869521 15.868640221171937 M52.2413470869521 15.868640221171937 C51.913443933280064 15.90027264404544, 51.58554077960802 15.931905066918942, 51.220436019691405 15.967126284005381 M52.2413470869521 15.868640221171937 C51.83666297701598 15.907679610553625, 51.431978867079856 15.946718999935314, 51.220436019691405 15.967126284005381 M51.220436019691405 15.967126284005381 C50.87382161202933 15.978241533415087, 50.52720720436726 15.989356782824794, 50.1953125 16 M51.220436019691405 15.967126284005381 C50.91360456886574 15.976965771422172, 50.60677311804009 15.986805258838963, 50.1953125 16 M50.1953125 16 C50.1953125 16, 50.1953125 16, 50.1953125 16 M50.1953125 16 C50.1953125 16, 50.1953125 16, 50.1953125 16 M50.1953125 16 C28.14324886950841 16, 6.0911852390168235 16, -50.1953125 16 M50.1953125 16 C17.664259753101383 16, -14.866792993797233 16, -50.1953125 16 M-50.1953125 16 C-50.442730219944245 15.992065795290765, -50.69014793988849 15.98413159058153, -51.2204360196914 15.967126284005381 M-50.1953125 16 C-50.457136360076916 15.99160381841656, -50.71896022015383 15.983207636833122, -51.2204360196914 15.967126284005381 M-51.2204360196914 15.967126284005381 C-51.60826165739686 15.929713211164506, -51.99608729510231 15.89230013832363, -52.241347086952096 15.868640221171937 M-51.2204360196914 15.967126284005381 C-51.523816321667006 15.93785955114199, -51.827196623642614 15.908592818278597, -52.241347086952096 15.868640221171937 M-52.241347086952096 15.868640221171937 C-52.55691837520368 15.817621102579313, -52.872489663455255 15.766601983986687, -53.25385055922196 15.704946511857045 M-52.241347086952096 15.868640221171937 C-52.55323952524278 15.818215870511082, -52.865131963533464 15.76779151985023, -53.25385055922196 15.704946511857045 M-53.25385055922196 15.704946511857045 C-53.58213793547146 15.630017060503434, -53.91042531172096 15.55508760914982, -54.25378584255211 15.476717808624471 M-53.25385055922196 15.704946511857045 C-53.55109412073784 15.63710260863656, -53.84833768225371 15.569258705416074, -54.25378584255211 15.476717808624471 M-54.25378584255211 15.476717808624471 C-54.49159523938659 15.406137227930994, -54.729404636221076 15.335556647237517, -55.23704398837792 15.184891952170702 M-54.25378584255211 15.476717808624471 C-54.54961243655994 15.388918028348426, -54.845439030567775 15.301118248072383, -55.23704398837792 15.184891952170702 M-55.23704398837792 15.184891952170702 C-55.60074990886157 15.051044811372044, -55.964455829345226 14.917197670573387, -56.19958457806999 14.830668117536348 M-55.23704398837792 15.184891952170702 C-55.61068131195361 15.047389963229291, -55.9843186355293 14.90988797428788, -56.19958457806999 14.830668117536348 M-56.19958457806999 14.830668117536348 C-56.46580676937782 14.712819450645087, -56.73202896068566 14.594970783753826, -57.13745232588093 14.415501886438708 M-56.19958457806999 14.830668117536348 C-56.54358879531572 14.6783876550842, -56.88759301256145 14.526107192632052, -57.13745232588093 14.415501886438708 M-57.13745232588093 14.415501886438708 C-57.45272925901403 14.251022112367684, -57.768006192147126 14.08654233829666, -58.046793332063 13.941099265974234 M-57.13745232588093 14.415501886438708 C-57.494322624743084 14.229322880108658, -57.85119292360523 14.043143873778607, -58.046793332063 13.941099265974234 M-58.046793332063 13.941099265974234 C-58.39280163835406 13.731346997330084, -58.738809944645126 13.521594728685931, -58.92387091936877 13.409409678269457 M-58.046793332063 13.941099265974234 C-58.26764353127464 13.807218577352305, -58.48849373048628 13.673337888730376, -58.92387091936877 13.409409678269457 M-58.92387091936877 13.409409678269457 C-59.09950706616293 13.286893505432104, -59.27514321295709 13.164377332594752, -59.765080987859456 12.822617949887308 M-58.92387091936877 13.409409678269457 C-59.13355968494301 13.263139872685228, -59.34324845051725 13.116870067101, -59.765080987859456 12.822617949887308 M-59.765080987859456 12.822617949887308 C-60.071661874547864 12.578127851213331, -60.37824276123627 12.333637752539355, -60.56696682492461 12.183135333906154 M-59.765080987859456 12.822617949887308 C-60.036381727618554 12.606262829545319, -60.307682467377646 12.389907709203328, -60.56696682492461 12.183135333906154 M-60.56696682492461 12.183135333906154 C-60.744928010098604 12.021515694126071, -60.922889195272596 11.859896054345988, -61.32623330965578 11.493589601563649 M-60.56696682492461 12.183135333906154 C-60.817966990559654 11.955183624576874, -61.068967156194695 11.727231915247591, -61.32623330965578 11.493589601563649 M-61.32623330965578 11.493589601563649 C-61.47036375540861 11.34476308299418, -61.61449420116145 11.195936564424713, -62.03976045320505 10.756814244181069 M-61.32623330965578 11.493589601563649 C-61.59790118520502 11.213070215711667, -61.869569060754266 10.932550829859684, -62.03976045320505 10.756814244181069 M-62.03976045320505 10.756814244181069 C-62.29646154241571 10.455278538088452, -62.553162631626385 10.153742831995835, -62.70461621948847 9.97583682973974 M-62.03976045320505 10.756814244181069 C-62.184026011486964 10.587351710480318, -62.32829156976887 10.417889176779568, -62.70461621948847 9.97583682973974 M-62.70461621948847 9.97583682973974 C-62.83148804653665 9.805840139756405, -62.95835987358482 9.635843449773073, -63.31806857355129 9.15386656195472 M-62.70461621948847 9.97583682973974 C-62.924417504161276 9.681323132587151, -63.14421878883409 9.386809435434563, -63.31806857355129 9.15386656195472 M-63.31806857355129 9.15386656195472 C-63.521812847245464 8.840860644562436, -63.72555712093964 8.527854727170153, -63.877596708085534 8.29428109296841 M-63.31806857355129 9.15386656195472 C-63.47434111667654 8.913789970660845, -63.63061365980179 8.67371337936697, -63.877596708085534 8.29428109296841 M-63.877596708085534 8.29428109296841 C-63.98361711986846 8.106031116116984, -64.08963753165139 7.917781139265557, -64.380901401968 7.400612643853366 M-63.877596708085534 8.29428109296841 C-64.03539370326973 8.014096549340422, -64.19319069845395 7.733912005712437, -64.380901401968 7.400612643853366 M-64.380901401968 7.400612643853366 C-64.51420366226044 7.123807648144677, -64.64750592255287 6.847002652435988, -64.825914468253 6.476533489958307 M-64.380901401968 7.400612643853366 C-64.52514339090962 7.101091067531951, -64.66938537985124 6.801569491210536, -64.825914468253 6.476533489958307 M-64.825914468253 6.476533489958307 C-64.94478822402867 6.1829130149246785, -65.06366197980434 5.88929253989105, -65.21080725279616 5.525840870740931 M-64.825914468253 6.476533489958307 C-64.95492609772391 6.157872270894978, -65.08393772719482 5.839211051831649, -65.21080725279616 5.525840870740931 M-65.21080725279616 5.525840870740931 C-65.27712690582325 5.32609664242508, -65.34344655885033 5.1263524141092285, -65.53399814858656 4.552441386096519 M-65.21080725279616 5.525840870740931 C-65.33581529388582 5.149336568305399, -65.46082333497547 4.772832265869866, -65.53399814858656 4.552441386096519 M-65.53399814858656 4.552441386096519 C-65.62723506912995 4.196888598927588, -65.72047198967336 3.8413358117586576, -65.79415909490918 3.5603349433010343 M-65.53399814858656 4.552441386096519 C-65.62326648969284 4.212022512314529, -65.71253483079911 3.871603638532538, -65.79415909490918 3.5603349433010343 M-65.79415909490918 3.5603349433010343 C-65.86060525036693 3.2191479784254025, -65.92705140582468 2.87796101354977, -65.9902210346312 2.5535983205340753 M-65.79415909490918 3.5603349433010343 C-65.84442492565297 3.302230526118745, -65.89469075639677 3.044126108936455, -65.9902210346312 2.5535983205340753 M-65.9902210346312 2.5535983205340753 C-66.02315165758762 2.2981949117711067, -66.05608228054405 2.0427915030081385, -66.12137830718717 1.5363684145229202 M-65.9902210346312 2.5535983205340753 C-66.03996849289076 2.1677668580196414, -66.08971595115034 1.7819353955052075, -66.12137830718717 1.5363684145229202 M-66.12137830718717 1.5363684145229202 C-66.13943668440474 1.2550946128995846, -66.1574950616223 0.9738208112762491, -66.187091959211 0.5128252411464846 M-66.12137830718717 1.5363684145229202 C-66.1460463887776 1.152143132034874, -66.17071447036803 0.7679178495468281, -66.187091959211 0.5128252411464846 M-66.187091959211 0.5128252411464846 C-66.187091959211 0.11895029747643021, -66.187091959211 -0.2749246461936242, -66.187091959211 -0.5128252411464769 M-66.187091959211 0.5128252411464846 C-66.187091959211 0.24106015787710017, -66.187091959211 -0.03070492539228431, -66.187091959211 -0.5128252411464769 M-66.187091959211 -0.5128252411464769 C-66.16920935401427 -0.7913612516647894, -66.15132674881752 -1.069897262183102, -66.12137830718717 -1.5363684145228982 M-66.187091959211 -0.5128252411464769 C-66.1706894933986 -0.7683068860068625, -66.15428702758618 -1.023788530867248, -66.12137830718717 -1.5363684145228982 M-66.12137830718717 -1.5363684145228982 C-66.08178915383614 -1.8434140701509607, -66.0422000004851 -2.1504597257790232, -65.9902210346312 -2.5535983205340678 M-66.12137830718717 -1.5363684145228982 C-66.07087942807554 -1.9280277487810649, -66.02038054896393 -2.3196870830392315, -65.9902210346312 -2.5535983205340678 M-65.9902210346312 -2.5535983205340678 C-65.9404286726464 -2.809271575706593, -65.8906363106616 -3.064944830879118, -65.79415909490918 -3.5603349433010267 M-65.9902210346312 -2.5535983205340678 C-65.92899711525185 -2.8679702068671, -65.8677731958725 -3.1823420932001323, -65.79415909490918 -3.5603349433010267 M-65.79415909490918 -3.5603349433010267 C-65.7153963830074 -3.8606912997577503, -65.63663367110564 -4.161047656214474, -65.53399814858658 -4.552441386096511 M-65.79415909490918 -3.5603349433010267 C-65.69845428437348 -3.925298864600897, -65.60274947383779 -4.290262785900767, -65.53399814858658 -4.552441386096511 M-65.53399814858658 -4.552441386096511 C-65.42095170914641 -4.892919250186187, -65.30790526970624 -5.2333971142758635, -65.21080725279617 -5.525840870740911 M-65.53399814858658 -4.552441386096511 C-65.41488159238475 -4.911201474730564, -65.2957650361829 -5.2699615633646175, -65.21080725279617 -5.525840870740911 M-65.21080725279617 -5.525840870740911 C-65.06123646754031 -5.895283602077283, -64.91166568228446 -6.264726333413655, -64.825914468253 -6.476533489958299 M-65.21080725279617 -5.525840870740911 C-65.08630171005414 -5.833371968464651, -64.9617961673121 -6.1409030661883905, -64.825914468253 -6.476533489958299 M-64.825914468253 -6.476533489958299 C-64.67928870405129 -6.781005026611939, -64.53266293984956 -7.08547656326558, -64.380901401968 -7.400612643853359 M-64.825914468253 -6.476533489958299 C-64.66471810052049 -6.811261196604612, -64.50352173278797 -7.145988903250924, -64.380901401968 -7.400612643853359 M-64.380901401968 -7.400612643853359 C-64.18935929975699 -7.740715042070066, -63.99781719754597 -8.080817440286774, -63.877596708085534 -8.294281092968404 M-64.380901401968 -7.400612643853359 C-64.27136014188333 -7.59511424338907, -64.16181888179867 -7.789615842924782, -63.877596708085534 -8.294281092968404 M-63.877596708085534 -8.294281092968404 C-63.7368310753641 -8.510534905693529, -63.596065442642676 -8.726788718418653, -63.318068573551294 -9.153866561954715 M-63.877596708085534 -8.294281092968404 C-63.66395959209059 -8.62248507273478, -63.45032247609566 -8.950689052501154, -63.318068573551294 -9.153866561954715 M-63.318068573551294 -9.153866561954715 C-63.12776435612441 -9.408856876235872, -62.93746013869753 -9.663847190517028, -62.70461621948848 -9.975836829739734 M-63.318068573551294 -9.153866561954715 C-63.130924024807385 -9.404623208052422, -62.94377947606348 -9.65537985415013, -62.70461621948848 -9.975836829739734 M-62.70461621948848 -9.975836829739734 C-62.53843826328515 -10.17103891288974, -62.372260307081824 -10.366240996039746, -62.039760453205055 -10.756814244181063 M-62.70461621948848 -9.975836829739734 C-62.460383235551426 -10.262726789922672, -62.21615025161438 -10.54961675010561, -62.039760453205055 -10.756814244181063 M-62.039760453205055 -10.756814244181063 C-61.83328387128559 -10.970018267055556, -61.62680728936611 -11.183222289930049, -61.32623330965579 -11.493589601563633 M-62.039760453205055 -10.756814244181063 C-61.78613135068278 -11.01870711587189, -61.532502248160505 -11.280599987562718, -61.32623330965579 -11.493589601563633 M-61.32623330965579 -11.493589601563633 C-61.11131773438572 -11.688770240669394, -60.896402159115645 -11.883950879775156, -60.56696682492463 -12.18313533390614 M-61.32623330965579 -11.493589601563633 C-61.149052050848056 -11.654500932853603, -60.97187079204032 -11.815412264143575, -60.56696682492463 -12.18313533390614 M-60.56696682492463 -12.18313533390614 C-60.25633019117695 -12.430859782931925, -59.945693557429266 -12.67858423195771, -59.76508098785946 -12.822617949887302 M-60.56696682492463 -12.18313533390614 C-60.36546601905114 -12.343826864428607, -60.163965213177654 -12.504518394951074, -59.76508098785946 -12.822617949887302 M-59.76508098785946 -12.822617949887302 C-59.57017842221198 -12.958573542486903, -59.3752758565645 -13.094529135086503, -58.92387091936879 -13.409409678269444 M-59.76508098785946 -12.822617949887302 C-59.54654768291126 -12.975057323264869, -59.32801437796306 -13.127496696642435, -58.92387091936879 -13.409409678269444 M-58.92387091936879 -13.409409678269444 C-58.588145512946554 -13.612928392584083, -58.25242010652432 -13.816447106898721, -58.046793332063004 -13.941099265974229 M-58.92387091936879 -13.409409678269444 C-58.748308147998905 -13.515836861995231, -58.57274537662902 -13.622264045721018, -58.046793332063004 -13.941099265974229 M-58.046793332063004 -13.941099265974229 C-57.77403614942479 -14.083396513447275, -57.501278966786565 -14.225693760920322, -57.137452325880936 -14.415501886438705 M-58.046793332063004 -13.941099265974229 C-57.74078185447426 -14.100745257822572, -57.43477037688552 -14.260391249670915, -57.137452325880936 -14.415501886438705 M-57.137452325880936 -14.415501886438705 C-56.94253973964398 -14.501783906489361, -56.74762715340703 -14.58806592654002, -56.199584578069995 -14.830668117536344 M-57.137452325880936 -14.415501886438705 C-56.799259508094444 -14.565209814739287, -56.46106669030795 -14.714917743039868, -56.199584578069995 -14.830668117536344 M-56.199584578069995 -14.830668117536344 C-55.90369196110276 -14.939559335781656, -55.60779934413552 -15.048450554026967, -55.23704398837794 -15.184891952170695 M-56.199584578069995 -14.830668117536344 C-55.892181968831224 -14.943795119334782, -55.58477935959245 -15.05692212113322, -55.23704398837794 -15.184891952170695 M-55.23704398837794 -15.184891952170695 C-54.990208709489295 -15.258151367280027, -54.74337343060065 -15.331410782389359, -54.25378584255213 -15.476717808624466 M-55.23704398837794 -15.184891952170695 C-54.913169925395366 -15.281016074014275, -54.58929586241279 -15.377140195857855, -54.25378584255213 -15.476717808624466 M-54.25378584255213 -15.476717808624466 C-54.04178057515946 -15.525106627443183, -53.82977530776678 -15.573495446261902, -53.253850559221966 -15.704946511857043 M-54.25378584255213 -15.476717808624466 C-53.923969060050084 -15.551996336974915, -53.594152277548034 -15.627274865325363, -53.253850559221966 -15.704946511857043 M-53.253850559221966 -15.704946511857043 C-52.85777855560553 -15.768980361817487, -52.46170655198909 -15.83301421177793, -52.2413470869521 -15.868640221171937 M-53.253850559221966 -15.704946511857043 C-52.91320735799086 -15.76001906290461, -52.57256415675976 -15.815091613952173, -52.2413470869521 -15.868640221171937 M-52.2413470869521 -15.868640221171937 C-52.02607089930829 -15.88940765608644, -51.81079471166447 -15.910175091000944, -51.220436019691405 -15.967126284005381 M-52.2413470869521 -15.868640221171937 C-51.869730326817894 -15.904489643087542, -51.498113566683685 -15.940339065003146, -51.220436019691405 -15.967126284005381 M-51.220436019691405 -15.967126284005381 C-50.98904533890346 -15.974546532763613, -50.75765465811551 -15.981966781521844, -50.19531250000001 -16 M-51.220436019691405 -15.967126284005381 C-50.971431073215804 -15.975111387980128, -50.722426126740196 -15.983096491954875, -50.19531250000001 -16 M-50.19531250000001 -16 C-50.19531250000001 -16, -50.19531250000001 -16, -50.1953125 -16 M-50.19531250000001 -16 C-50.19531250000001 -16, -50.1953125 -16, -50.1953125 -16" stroke="#6b7280" stroke-width="1.3" fill="none" stroke-dasharray="0 0" style="fill:#f3f4f6 !important;stroke:#6b7280 !important"></path></g><g class="label" style="color:#111 !important" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style="fill:#111 !important"><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Telegram</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> users</tspan></tspan></text></g></g></g><g class="node default ext" id="g1069-flowchart-tgapi-2" data-look="classic" transform="translate(426.4913787841797, 365.7333399454752)"><rect class="basic label-container" style="fill:#f3f4f6 !important;stroke:#6b7280 !important" x="-91.8203125" y="-32.29999923706055" width="183.640625" height="64.5999984741211"></rect><g class="label" style="color:#111 !important" transform="translate(0, -17.299999237060547)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style="fill:#111 !important"><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Telegram</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Bot</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> API</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">api.telegram.org</tspan></tspan></text></g></g></g><g class="node default ext" id="g1069-flowchart-scli-3" data-look="classic" transform="translate(426.4913787841797, 504.7333399454752)"><rect class="basic label-container" style="fill:#f3f4f6 !important;stroke:#6b7280 !important" x="-92.2578125" y="-23.5" width="184.515625" height="47"></rect><g class="label" style="color:#111 !important" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style="fill:#111 !important"><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">signal-cli</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> daemon</tspan></tspan></text></g></g></g><g class="node default ext" id="g1069-flowchart-llm-4" data-look="classic" transform="translate(3365.9077911376953, 716.666670481364)"><rect class="basic label-container" style="fill:#f3f4f6 !important;stroke:#6b7280 !important" x="-112.61328125" y="-41.099998474121094" width="225.2265625" height="82.19999694824219"></rect><g class="label" style="color:#111 !important" transform="translate(0, -26.099998474121094)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style="fill:#111 !important"><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Model</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> API</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">OpenRouter</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> or</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> another</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="2.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">chat</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> completions</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> API</tspan></tspan></text></g></g></g><g class="node default ext" id="g1069-flowchart-web-5" data-look="classic" transform="translate(3323.6226348876953, 971.3673617045085)"><rect class="basic label-container" style="fill:#f3f4f6 !important;stroke:#6b7280 !important" x="-70.328125" y="-23.5" width="140.65625" height="47"></rect><g class="label" style="color:#111 !important" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style="fill:#111 !important"><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Web</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> pages</tspan></tspan></text></g></g></g><g class="node default ext" id="g1069-flowchart-mcpsrv-6" data-look="classic" transform="translate(3372.7241973876953, 1123.5000076293945)"><rect class="basic label-container" style="fill:#f3f4f6 !important;stroke:#6b7280 !important" x="-119.4296875" y="-41.099998474121094" width="238.859375" height="82.19999694824219"></rect><g class="label" style="color:#111 !important" transform="translate(0, -26.099998474121094)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style="fill:#111 !important"><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">MCP</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> servers</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">remote</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> over</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> HTTP,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> or</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="2.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">local</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> programs</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> over</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> stdio</tspan></tspan></text></g></g></g><g class="node default ext" id="g1069-flowchart-disk-7" data-look="classic" transform="translate(3336.8257598876953, 852.8170153299968)"><path d="M0,14.300235394821312 a83.53125,14.300235394821312 0,0,0 167.0625,0 a83.53125,14.300235394821312 0,0,0 -167.0625,0 l0,81.5002323430635 a83.53125,14.300235394821312 0,0,0 167.0625,0 l0,-81.5002323430635" class="basic label-container outer-path" style="fill:#f3f4f6 !important;stroke:#6b7280 !important" transform="translate(-83.53125, -55.050351566353065)"></path><g class="label" style="color:#111 !important" transform="translate(-0.1640625, -19.099998474121094)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style="fill:#111 !important"><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">STATE_DIRECTORY</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">budget.json</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="2.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">schedules.json</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-telegram-8" data-look="classic" transform="translate(1027.4679412841797, 349.1000061035156)"><rect class="basic label-container" style="" x="-115.84375" y="-49.900001525878906" width="231.6875" height="99.80000305175781"></rect><g class="label" style="" transform="translate(0, -34.900001525878906)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">internal/telegram</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">long</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> polling,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> decoding,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="2.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">sending</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> with</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> entities,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="3.2em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">names</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> and</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> groups</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> seen</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-signal-9" data-look="classic" transform="translate(1027.4679412841797, 496.50000762939453)"><rect class="basic label-container" style="" x="-126.5" y="-67.5" width="253" height="135"></rect><g class="label" style="" transform="translate(0, -52.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">internal/signal</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">JSON-RPC</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> client,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="2.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">decoding,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="3.2em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">sending,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Markdown</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> to</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> text</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="4.300000000000001em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">styles,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="5.4em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">names,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> recent</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> attachments</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-bot-10" data-look="classic" transform="translate(2140.2788848876953, 525.950008392334)"><rect class="basic label-container" style="" x="-120.265625" y="-49.900001525878906" width="240.53125" height="99.80000305175781"></rect><g class="label" style="" transform="translate(0, -34.900001525878906)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">internal/bot</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">addressed</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> or</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> not,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> hooks,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="2.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">prompt,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="3.2em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">daily</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> budget,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> worker</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> slots</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-chats-11" data-look="classic" transform="translate(2726.5445098876953, 655.6666717529297)"><rect class="basic label-container" style="" x="-116.125" y="-32.29999923706055" width="232.25" height="64.5999984741211"></rect><g class="label" style="" transform="translate(0, -17.299999237060547)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">internal/chats</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">history,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> dedupe,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> mailbox</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-timers-12" data-look="classic" transform="translate(2435.6773223876953, 549.3000068664551)"><rect class="basic label-container" style="" x="-85.1328125" y="-32.29999923706055" width="170.265625" height="64.5999984741211"></rect><g class="label" style="" transform="translate(0, -17.299999237060547)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">internal/timers</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">one-shot</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> timers</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-config-13" data-look="classic" transform="translate(2430.3570098876953, 453.700008392334)"><rect class="basic label-container" style="" x="-79.8125" y="-32.29999923706055" width="159.625" height="64.5999984741211"></rect><g class="label" style="" transform="translate(0, -17.299999237060547)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">internal/config</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">settings</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-model-14" data-look="classic" transform="translate(2457.9820098876953, 644.9000053405762)"><rect class="basic label-container" style="" x="-107.4375" y="-32.29999923706055" width="214.875" height="64.5999984741211"></rect><g class="label" style="" transform="translate(0, -17.299999237060547)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">internal/model</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">model</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> client,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> tool</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> loop</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-port-25" data-look="classic" transform="translate(1634.9398193359375, 619.5500068664551)"><polygon points="38.79999923706055,0 253.61249923706055,0 292.4124984741211,-77.5999984741211 253.61249923706055,-155.1999969482422 38.79999923706055,-155.1999969482422 0,-77.5999984741211" class="label-container" transform="translate(-146.20624923706055,77.5999984741211)"></polygon><g class="label" style="" transform="translate(0, -70.0999984741211)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">internal/feature:</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> the</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Host</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">ports,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="2.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">the</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> only</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> part</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> of</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> the</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> core</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="3.2em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">features</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> use</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="4.300000000000001em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">OnMessage,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> OnTurn,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="5.4em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">OnEvent,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Command,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="6.500000000000001em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">OfferTools,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> At,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Store,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Media,</tspan></tspan><tspan class="text-outer-tspan row" x="0" y="7.600000000000001em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">Deliver,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> Post,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> React</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-f1-26" data-look="classic" transform="translate(1060.0616912841797, 1046.5000076293945)"><rect class="basic label-container" style="" x="-105.6015625" y="-23.5" width="211.203125" height="47"></rect><g class="label" style="" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">intro,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> vision</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-files-27" data-look="classic" transform="translate(1060.0616912841797, 815.5000076293945)"><rect class="basic label-container" style="" x="-123.90625" y="-23.5" width="247.8125" height="47"></rect><g class="label" style="" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">files</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> (FILES=off</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> to</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> disable)</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-charts-28" data-look="classic" transform="translate(1060.0616912841797, 969.5000076293945)"><rect class="basic label-container" style="" x="-122.4921875" y="-23.5" width="244.984375" height="47"></rect><g class="label" style="" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">charts</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> (build</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> tag</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> nocharts)</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-schedule-29" data-look="classic" transform="translate(1121.8937225341797, 738.5000076293945)"><rect class="basic label-container" style="" x="-62.07421875" y="-23.5" width="124.1484375" height="47"></rect><g class="label" style="" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">schedule</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-websearch-30" data-look="classic" transform="translate(1114.7804412841797, 661.5000076293945)"><rect class="basic label-container" style="" x="-69.1875" y="-23.5" width="138.375" height="47"></rect><g class="label" style="" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">websearch</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-links-31" data-look="classic" transform="translate(1137.9601287841797, 892.5000076293945)"><rect class="basic label-container" style="" x="-46.0078125" y="-23.5" width="92.015625" height="47"></rect><g class="label" style="" transform="translate(0, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">links</tspan></tspan></text></g></g></g><g class="node default" id="g1069-flowchart-mcp-32" data-look="classic" transform="translate(1138.8038787841797, 1123.5000076293945)"><rect class="basic label-container" style="" x="-45.1640625" y="-23.5" width="160" height="47"></rect><g class="label" style="" transform="translate(34.8359375, -8.5)"><rect></rect><g><rect class="background" style="stroke: none"></rect><text y="-10.1" style=""><tspan class="text-outer-tspan row" x="0" y="-0.1em" dy="1.1em"><tspan font-style="normal" class="text-inner-tspan" font-weight="normal">mcp,</tspan><tspan font-style="normal" class="text-inner-tspan" font-weight="normal"> then groupctx</tspan></tspan></text></g></g></g></g></g></g><defs><filter id="g1069-drop-shadow" height="130%" width="130%"><feDropShadow dx="4" dy="4" stdDeviation="0" flood-opacity="0.06" flood-color="#000000"></feDropShadow></filter></defs><defs><filter id="g1069-drop-shadow-small" height="150%" width="150%"><feDropShadow dx="2" dy="2" stdDeviation="0" flood-opacity="0.06" flood-color="#000000"></feDropShadow></filter></defs></svg> \ No newline at end of file diff --git a/docs/message-flow.svg b/docs/message-flow.svg index cb9cf2d..4e0403e 100644 --- a/docs/message-flow.svg +++ b/docs/message-flow.svg @@ -1 +1 @@ -<svg id="g1415" width="100%" xmlns="http://www.w3.org/2000/svg" style="max-width: 1912px;" viewBox="-50 -10 1912 1556" role="graphics-document document" aria-roledescription="sequence"><g><rect x="1662" y="1470" fill="#eaeaea" stroke="#666" width="150" height="65" name="L" rx="3" ry="3" class="actor actor-bottom"></rect><text x="1737" y="1502.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="1737" dy="0">Model API</tspan></text></g><g><rect x="1462" y="1470" fill="#eaeaea" stroke="#666" width="150" height="65" name="M" rx="3" ry="3" class="actor actor-bottom"></rect><text x="1537" y="1502.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="1537" dy="0">internal/model</tspan></text></g><g><rect x="1231" y="1470" fill="#eaeaea" stroke="#666" width="150" height="65" name="F" rx="3" ry="3" class="actor actor-bottom"></rect><text x="1306" y="1502.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="1306" dy="0">Features</tspan></text></g><g><rect x="886" y="1470" fill="#eaeaea" stroke="#666" width="150" height="65" name="B" rx="3" ry="3" class="actor actor-bottom"></rect><text x="961" y="1502.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="961" dy="0">internal/bot</tspan></text></g><g><rect x="563" y="1470" fill="#eaeaea" stroke="#666" width="150" height="65" name="N" rx="3" ry="3" class="actor actor-bottom"></rect><text x="638" y="1502.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="638" dy="0">internal/signal</tspan></text></g><g><rect x="274" y="1470" fill="#eaeaea" stroke="#666" width="150" height="65" name="S" rx="3" ry="3" class="actor actor-bottom"></rect><text x="349" y="1502.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="349" dy="0">signal-cli</tspan></text></g><g><rect x="0" y="1470" fill="#eaeaea" stroke="#666" width="150" height="65" name="U" rx="3" ry="3" class="actor actor-bottom"></rect><text x="75" y="1502.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="75" dy="0">Signal user</tspan></text></g><g><line id="actor6" x1="1737" y1="65" x2="1737" y2="1470" class="actor-line 200" stroke-width="0.5px" stroke="#999" name="L" data-et="life-line" data-id="L"></line><g id="root-6" data-et="participant" data-type="participant" data-id="L"><rect x="1662" y="0" fill="#eaeaea" stroke="#666" width="150" height="65" name="L" rx="3" ry="3" class="actor actor-top"></rect><text x="1737" y="32.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="1737" dy="0">Model API</tspan></text></g></g><g><line id="actor5" x1="1537" y1="65" x2="1537" y2="1470" class="actor-line 200" stroke-width="0.5px" stroke="#999" name="M" data-et="life-line" data-id="M"></line><g id="root-5" data-et="participant" data-type="participant" data-id="M"><rect x="1462" y="0" fill="#eaeaea" stroke="#666" width="150" height="65" name="M" rx="3" ry="3" class="actor actor-top"></rect><text x="1537" y="32.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="1537" dy="0">internal/model</tspan></text></g></g><g><line id="actor4" x1="1306" y1="65" x2="1306" y2="1470" class="actor-line 200" stroke-width="0.5px" stroke="#999" name="F" data-et="life-line" data-id="F"></line><g id="root-4" data-et="participant" data-type="participant" data-id="F"><rect x="1231" y="0" fill="#eaeaea" stroke="#666" width="150" height="65" name="F" rx="3" ry="3" class="actor actor-top"></rect><text x="1306" y="32.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="1306" dy="0">Features</tspan></text></g></g><g><line id="actor3" x1="961" y1="65" x2="961" y2="1470" class="actor-line 200" stroke-width="0.5px" stroke="#999" name="B" data-et="life-line" data-id="B"></line><g id="root-3" data-et="participant" data-type="participant" data-id="B"><rect x="886" y="0" fill="#eaeaea" stroke="#666" width="150" height="65" name="B" rx="3" ry="3" class="actor actor-top"></rect><text x="961" y="32.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="961" dy="0">internal/bot</tspan></text></g></g><g><line id="actor2" x1="638" y1="65" x2="638" y2="1470" class="actor-line 200" stroke-width="0.5px" stroke="#999" name="N" data-et="life-line" data-id="N"></line><g id="root-2" data-et="participant" data-type="participant" data-id="N"><rect x="563" y="0" fill="#eaeaea" stroke="#666" width="150" height="65" name="N" rx="3" ry="3" class="actor actor-top"></rect><text x="638" y="32.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="638" dy="0">internal/signal</tspan></text></g></g><g><line id="actor1" x1="349" y1="65" x2="349" y2="1470" class="actor-line 200" stroke-width="0.5px" stroke="#999" name="S" data-et="life-line" data-id="S"></line><g id="root-1" data-et="participant" data-type="participant" data-id="S"><rect x="274" y="0" fill="#eaeaea" stroke="#666" width="150" height="65" name="S" rx="3" ry="3" class="actor actor-top"></rect><text x="349" y="32.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="349" dy="0">signal-cli</tspan></text></g></g><g><line id="actor0" x1="75" y1="65" x2="75" y2="1470" class="actor-line 200" stroke-width="0.5px" stroke="#999" name="U" data-et="life-line" data-id="U"></line><g id="root-0" data-et="participant" data-type="participant" data-id="U"><rect x="0" y="0" fill="#eaeaea" stroke="#666" width="150" height="65" name="U" rx="3" ry="3" class="actor actor-top"></rect><text x="75" y="32.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="75" dy="0">Signal user</tspan></text></g></g><style>#g1415{font-family:Helvetica,Arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#g1415 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#g1415 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#g1415 .error-icon{fill:#552222;}#g1415 .error-text{fill:#552222;stroke:#552222;}#g1415 .edge-thickness-normal{stroke-width:1px;}#g1415 .edge-thickness-thick{stroke-width:3.5px;}#g1415 .edge-pattern-solid{stroke-dasharray:0;}#g1415 .edge-thickness-invisible{stroke-width:0;fill:none;}#g1415 .edge-pattern-dashed{stroke-dasharray:3;}#g1415 .edge-pattern-dotted{stroke-dasharray:2;}#g1415 .marker{fill:#333333;stroke:#333333;}#g1415 .marker.cross{stroke:#333333;}#g1415 svg{font-family:Helvetica,Arial,sans-serif;font-size:16px;}#g1415 p{margin:0;}#g1415 .actor{stroke:#9370DB;fill:#ECECFF;stroke-width:1;}#g1415 rect.actor.outer-path[data-look="neo"]{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1415 rect.note[data-look="neo"]{stroke:#aaaa33;fill:#fff5ad;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1415 text.actor>tspan{fill:black;stroke:none;}#g1415 .actor-line{stroke:#9370DB;}#g1415 .innerArc{stroke-width:1.5;stroke-dasharray:none;}#g1415 .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333;}#g1415 .messageLine1{stroke-width:1.5;stroke-dasharray:2,2;stroke:#333;}#g1415 [id$="-arrowhead"] path{fill:#333;stroke:#333;}#g1415 .sequenceNumber{fill:white;}#g1415 [id$="-sequencenumber"]{fill:#333;}#g1415 [id$="-crosshead"] path{fill:#333;stroke:#333;}#g1415 .messageText{fill:#333;stroke:none;}#g1415 .labelBox{stroke:#9370DB;fill:#ECECFF;filter:none;}#g1415 .labelText,#g1415 .labelText>tspan{fill:black;stroke:none;}#g1415 .loopText,#g1415 .loopText>tspan{fill:black;stroke:none;}#g1415 .sectionTitle,#g1415 .sectionTitle>tspan{fill:black;stroke:none;}#g1415 .loopLine{stroke-width:2px;stroke-dasharray:2,2;stroke:#9370DB;fill:#9370DB;}#g1415 .note{stroke:#aaaa33;fill:#fff5ad;}#g1415 .noteText,#g1415 .noteText>tspan{fill:black;stroke:none;font-weight:normal;}#g1415 .activation0{fill:#f4f4f4;stroke:#666;}#g1415 .activation1{fill:#f4f4f4;stroke:#666;}#g1415 .activation2{fill:#f4f4f4;stroke:#666;}#g1415 .actorPopupMenu{position:absolute;}#g1415 .actorPopupMenuPanel{position:absolute;fill:#ECECFF;box-shadow:0px 8px 16px 0px rgba(0,0,0,0.2);filter:drop-shadow(3px 5px 2px rgb(0 0 0 / 0.4));}#g1415 .actor-man circle,#g1415 line{fill:#ECECFF;stroke-width:2px;}#g1415 g rect.rect{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));stroke:#9370DB;}#g1415 .node .neo-node{stroke:#9370DB;}#g1415 [data-look="neo"].node rect,#g1415 [data-look="neo"].cluster rect,#g1415 [data-look="neo"].node polygon{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1415 [data-look="neo"].swimlane.cluster rect{filter:none;}#g1415 [data-look="neo"].node path{stroke:#9370DB;stroke-width:1px;}#g1415 [data-look="neo"].node .outer-path{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1415 [data-look="neo"].node .neo-line path{stroke:#9370DB;filter:none;}#g1415 [data-look="neo"].node circle{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1415 [data-look="neo"].node circle .state-start{fill:#000000;}#g1415 [data-look="neo"].icon-shape .icon{fill:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1415 [data-look="neo"].icon-shape .icon-neo path{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1415 :root{--mermaid-font-family:Helvetica,Arial,sans-serif;}</style><g></g><defs><symbol id="g1415-computer" width="24" height="24"><path transform="scale(.5)" d="M2 2v13h20v-13h-20zm18 11h-16v-9h16v9zm-10.228 6l.466-1h3.524l.467 1h-4.457zm14.228 3h-24l2-6h2.104l-1.33 4h18.45l-1.297-4h2.073l2 6zm-5-10h-14v-7h14v7z"></path></symbol></defs><defs><symbol id="g1415-database" fill-rule="evenodd" clip-rule="evenodd"><path transform="scale(.5)" d="M12.258.001l.256.004.255.005.253.008.251.01.249.012.247.015.246.016.242.019.241.02.239.023.236.024.233.027.231.028.229.031.225.032.223.034.22.036.217.038.214.04.211.041.208.043.205.045.201.046.198.048.194.05.191.051.187.053.183.054.18.056.175.057.172.059.168.06.163.061.16.063.155.064.15.066.074.033.073.033.071.034.07.034.069.035.068.035.067.035.066.035.064.036.064.036.062.036.06.036.06.037.058.037.058.037.055.038.055.038.053.038.052.038.051.039.05.039.048.039.047.039.045.04.044.04.043.04.041.04.04.041.039.041.037.041.036.041.034.041.033.042.032.042.03.042.029.042.027.042.026.043.024.043.023.043.021.043.02.043.018.044.017.043.015.044.013.044.012.044.011.045.009.044.007.045.006.045.004.045.002.045.001.045v17l-.001.045-.002.045-.004.045-.006.045-.007.045-.009.044-.011.045-.012.044-.013.044-.015.044-.017.043-.018.044-.02.043-.021.043-.023.043-.024.043-.026.043-.027.042-.029.042-.03.042-.032.042-.033.042-.034.041-.036.041-.037.041-.039.041-.04.041-.041.04-.043.04-.044.04-.045.04-.047.039-.048.039-.05.039-.051.039-.052.038-.053.038-.055.038-.055.038-.058.037-.058.037-.06.037-.06.036-.062.036-.064.036-.064.036-.066.035-.067.035-.068.035-.069.035-.07.034-.071.034-.073.033-.074.033-.15.066-.155.064-.16.063-.163.061-.168.06-.172.059-.175.057-.18.056-.183.054-.187.053-.191.051-.194.05-.198.048-.201.046-.205.045-.208.043-.211.041-.214.04-.217.038-.22.036-.223.034-.225.032-.229.031-.231.028-.233.027-.236.024-.239.023-.241.02-.242.019-.246.016-.247.015-.249.012-.251.01-.253.008-.255.005-.256.004-.258.001-.258-.001-.256-.004-.255-.005-.253-.008-.251-.01-.249-.012-.247-.015-.245-.016-.243-.019-.241-.02-.238-.023-.236-.024-.234-.027-.231-.028-.228-.031-.226-.032-.223-.034-.22-.036-.217-.038-.214-.04-.211-.041-.208-.043-.204-.045-.201-.046-.198-.048-.195-.05-.19-.051-.187-.053-.184-.054-.179-.056-.176-.057-.172-.059-.167-.06-.164-.061-.159-.063-.155-.064-.151-.066-.074-.033-.072-.033-.072-.034-.07-.034-.069-.035-.068-.035-.067-.035-.066-.035-.064-.036-.063-.036-.062-.036-.061-.036-.06-.037-.058-.037-.057-.037-.056-.038-.055-.038-.053-.038-.052-.038-.051-.039-.049-.039-.049-.039-.046-.039-.046-.04-.044-.04-.043-.04-.041-.04-.04-.041-.039-.041-.037-.041-.036-.041-.034-.041-.033-.042-.032-.042-.03-.042-.029-.042-.027-.042-.026-.043-.024-.043-.023-.043-.021-.043-.02-.043-.018-.044-.017-.043-.015-.044-.013-.044-.012-.044-.011-.045-.009-.044-.007-.045-.006-.045-.004-.045-.002-.045-.001-.045v-17l.001-.045.002-.045.004-.045.006-.045.007-.045.009-.044.011-.045.012-.044.013-.044.015-.044.017-.043.018-.044.02-.043.021-.043.023-.043.024-.043.026-.043.027-.042.029-.042.03-.042.032-.042.033-.042.034-.041.036-.041.037-.041.039-.041.04-.041.041-.04.043-.04.044-.04.046-.04.046-.039.049-.039.049-.039.051-.039.052-.038.053-.038.055-.038.056-.038.057-.037.058-.037.06-.037.061-.036.062-.036.063-.036.064-.036.066-.035.067-.035.068-.035.069-.035.07-.034.072-.034.072-.033.074-.033.151-.066.155-.064.159-.063.164-.061.167-.06.172-.059.176-.057.179-.056.184-.054.187-.053.19-.051.195-.05.198-.048.201-.046.204-.045.208-.043.211-.041.214-.04.217-.038.22-.036.223-.034.226-.032.228-.031.231-.028.234-.027.236-.024.238-.023.241-.02.243-.019.245-.016.247-.015.249-.012.251-.01.253-.008.255-.005.256-.004.258-.001.258.001zm-9.258 20.499v.01l.001.021.003.021.004.022.005.021.006.022.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.023.018.024.019.024.021.024.022.025.023.024.024.025.052.049.056.05.061.051.066.051.07.051.075.051.079.052.084.052.088.052.092.052.097.052.102.051.105.052.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.048.144.049.147.047.152.047.155.047.16.045.163.045.167.043.171.043.176.041.178.041.183.039.187.039.19.037.194.035.197.035.202.033.204.031.209.03.212.029.216.027.219.025.222.024.226.021.23.02.233.018.236.016.24.015.243.012.246.01.249.008.253.005.256.004.259.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.021.224-.024.22-.026.216-.027.212-.028.21-.031.205-.031.202-.034.198-.034.194-.036.191-.037.187-.039.183-.04.179-.04.175-.042.172-.043.168-.044.163-.045.16-.046.155-.046.152-.047.148-.048.143-.049.139-.049.136-.05.131-.05.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.053.083-.051.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.05.023-.024.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.023.01-.022.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.127l-.077.055-.08.053-.083.054-.085.053-.087.052-.09.052-.093.051-.095.05-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.045-.118.044-.12.043-.122.042-.124.042-.126.041-.128.04-.13.04-.132.038-.134.038-.135.037-.138.037-.139.035-.142.035-.143.034-.144.033-.147.032-.148.031-.15.03-.151.03-.153.029-.154.027-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.01-.179.008-.179.008-.181.006-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.006-.179-.008-.179-.008-.178-.01-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.027-.153-.029-.151-.03-.15-.03-.148-.031-.146-.032-.145-.033-.143-.034-.141-.035-.14-.035-.137-.037-.136-.037-.134-.038-.132-.038-.13-.04-.128-.04-.126-.041-.124-.042-.122-.042-.12-.044-.117-.043-.116-.045-.113-.045-.112-.046-.109-.047-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.05-.093-.052-.09-.051-.087-.052-.085-.053-.083-.054-.08-.054-.077-.054v4.127zm0-5.654v.011l.001.021.003.021.004.021.005.022.006.022.007.022.009.022.01.022.011.023.012.023.013.023.015.024.016.023.017.024.018.024.019.024.021.024.022.024.023.025.024.024.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.052.11.051.114.051.119.052.123.05.127.051.131.05.135.049.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.044.171.042.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.022.23.02.233.018.236.016.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.012.241-.015.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.048.139-.05.136-.049.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.051.051-.049.023-.025.023-.024.021-.025.02-.024.019-.024.018-.024.017-.024.015-.023.014-.023.013-.024.012-.022.01-.023.01-.023.008-.022.006-.022.006-.022.004-.021.004-.022.001-.021.001-.021v-4.139l-.077.054-.08.054-.083.054-.085.052-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.044-.118.044-.12.044-.122.042-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.035-.143.033-.144.033-.147.033-.148.031-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.009-.179.009-.179.007-.181.007-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.007-.179-.007-.179-.009-.178-.009-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.031-.146-.033-.145-.033-.143-.033-.141-.035-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.04-.126-.041-.124-.042-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.051-.093-.051-.09-.051-.087-.053-.085-.052-.083-.054-.08-.054-.077-.054v4.139zm0-5.666v.011l.001.02.003.022.004.021.005.022.006.021.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.024.018.023.019.024.021.025.022.024.023.024.024.025.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.051.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.043.171.043.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.021.23.02.233.018.236.017.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.013.241-.014.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.049.139-.049.136-.049.131-.051.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.049.023-.025.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.022.01-.023.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.153l-.077.054-.08.054-.083.053-.085.053-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.048-.105.048-.106.048-.109.046-.111.046-.114.046-.115.044-.118.044-.12.043-.122.043-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.034-.143.034-.144.033-.147.032-.148.032-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.024-.161.024-.162.023-.163.023-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.01-.178.01-.179.009-.179.007-.181.006-.182.006-.182.004-.184.003-.184.001-.185.001-.185-.001-.184-.001-.184-.003-.182-.004-.182-.006-.181-.006-.179-.007-.179-.009-.178-.01-.176-.01-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.023-.162-.023-.161-.024-.159-.024-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.032-.146-.032-.145-.033-.143-.034-.141-.034-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.041-.126-.041-.124-.041-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.048-.105-.048-.102-.048-.1-.05-.097-.049-.095-.051-.093-.051-.09-.052-.087-.052-.085-.053-.083-.053-.08-.054-.077-.054v4.153zm8.74-8.179l-.257.004-.254.005-.25.008-.247.011-.244.012-.241.014-.237.016-.233.018-.231.021-.226.022-.224.023-.22.026-.216.027-.212.028-.21.031-.205.032-.202.033-.198.034-.194.036-.191.038-.187.038-.183.04-.179.041-.175.042-.172.043-.168.043-.163.045-.16.046-.155.046-.152.048-.148.048-.143.048-.139.049-.136.05-.131.05-.126.051-.123.051-.118.051-.114.052-.11.052-.106.052-.101.052-.096.052-.092.052-.088.052-.083.052-.079.052-.074.051-.07.052-.065.051-.06.05-.056.05-.051.05-.023.025-.023.024-.021.024-.02.025-.019.024-.018.024-.017.023-.015.024-.014.023-.013.023-.012.023-.01.023-.01.022-.008.022-.006.023-.006.021-.004.022-.004.021-.001.021-.001.021.001.021.001.021.004.021.004.022.006.021.006.023.008.022.01.022.01.023.012.023.013.023.014.023.015.024.017.023.018.024.019.024.02.025.021.024.023.024.023.025.051.05.056.05.06.05.065.051.07.052.074.051.079.052.083.052.088.052.092.052.096.052.101.052.106.052.11.052.114.052.118.051.123.051.126.051.131.05.136.05.139.049.143.048.148.048.152.048.155.046.16.046.163.045.168.043.172.043.175.042.179.041.183.04.187.038.191.038.194.036.198.034.202.033.205.032.21.031.212.028.216.027.22.026.224.023.226.022.231.021.233.018.237.016.241.014.244.012.247.011.25.008.254.005.257.004.26.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.022.224-.023.22-.026.216-.027.212-.028.21-.031.205-.032.202-.033.198-.034.194-.036.191-.038.187-.038.183-.04.179-.041.175-.042.172-.043.168-.043.163-.045.16-.046.155-.046.152-.048.148-.048.143-.048.139-.049.136-.05.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.05.051-.05.023-.025.023-.024.021-.024.02-.025.019-.024.018-.024.017-.023.015-.024.014-.023.013-.023.012-.023.01-.023.01-.022.008-.022.006-.023.006-.021.004-.022.004-.021.001-.021.001-.021-.001-.021-.001-.021-.004-.021-.004-.022-.006-.021-.006-.023-.008-.022-.01-.022-.01-.023-.012-.023-.013-.023-.014-.023-.015-.024-.017-.023-.018-.024-.019-.024-.02-.025-.021-.024-.023-.024-.023-.025-.051-.05-.056-.05-.06-.05-.065-.051-.07-.052-.074-.051-.079-.052-.083-.052-.088-.052-.092-.052-.096-.052-.101-.052-.106-.052-.11-.052-.114-.052-.118-.051-.123-.051-.126-.051-.131-.05-.136-.05-.139-.049-.143-.048-.148-.048-.152-.048-.155-.046-.16-.046-.163-.045-.168-.043-.172-.043-.175-.042-.179-.041-.183-.04-.187-.038-.191-.038-.194-.036-.198-.034-.202-.033-.205-.032-.21-.031-.212-.028-.216-.027-.22-.026-.224-.023-.226-.022-.231-.021-.233-.018-.237-.016-.241-.014-.244-.012-.247-.011-.25-.008-.254-.005-.257-.004-.26-.001-.26.001z"></path></symbol></defs><defs><symbol id="g1415-clock" width="24" height="24"><path transform="scale(.5)" d="M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm5.848 12.459c.202.038.202.333.001.372-1.907.361-6.045 1.111-6.547 1.111-.719 0-1.301-.582-1.301-1.301 0-.512.77-5.447 1.125-7.445.034-.192.312-.181.343.014l.985 6.238 5.394 1.011z"></path></symbol></defs><defs><marker id="g1415-arrowhead" refX="7.9" refY="5" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto-start-reverse"><path d="M -1 0 L 10 5 L 0 10 z"></path></marker></defs><defs><marker id="g1415-crosshead" markerWidth="15" markerHeight="8" orient="auto" refX="4" refY="4.5"><path fill="none" stroke="#000000" stroke-width="1pt" d="M 1,2 L 6,7 M 6,2 L 1,7" style="stroke-dasharray: 0, 0;"></path></marker></defs><defs><marker id="g1415-filled-head" refX="15.5" refY="7" markerWidth="20" markerHeight="28" orient="auto"><path d="M 18,7 L9,13 L14,7 L9,1 Z"></path></marker></defs><defs><marker id="g1415-sequencenumber" refX="15" refY="15" markerWidth="60" markerHeight="40" orient="auto"><circle cx="15" cy="15" r="6"></circle></marker></defs><defs><marker id="g1415-solidTopArrowHead" refX="7.9" refY="7.25" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto-start-reverse"><path d="M 0 0 L 10 8 L 0 8 z"></path></marker></defs><defs><marker id="g1415-solidBottomArrowHead" refX="7.9" refY="0.75" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto-start-reverse"><path d="M 0 0 L 10 0 L 0 8 z"></path></marker></defs><defs><marker id="g1415-stickTopArrowHead" refX="7.5" refY="7" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto-start-reverse"><path d="M 0 0 L 7 7" stroke="black" stroke-width="1.5" fill="none"></path></marker></defs><defs><marker id="g1415-stickBottomArrowHead" refX="7.5" refY="0" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto-start-reverse"><path d="M 0 7 L 7 0" stroke="black" stroke-width="1.5" fill="none"></path></marker></defs><g data-et="note" data-id="i3"><rect x="764" y="207" fill="#EDF2AE" stroke="#666" width="394" height="71" class="note"></rect><text x="961" y="212" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">an unaddressed group message only runs</tspan></text><text x="961" y="229" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">the OnMessage hooks (groupctx keeps it as context)</tspan></text><text x="961" y="246" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">and goes no further, never logged</tspan></text></g><g data-et="note" data-id="i4"><rect x="793.5" y="288" fill="#EDF2AE" stroke="#666" width="335" height="71" class="note"></rect><text x="961" y="293" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">an edit is handled as a new message</tspan></text><text x="961" y="310" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">in place of the original, a delete for everyone</tspan></text><text x="961" y="327" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">drops the message from history</tspan></text></g><g data-et="note" data-id="i5"><rect x="795" y="369" fill="#EDF2AE" stroke="#666" width="332" height="54" class="note"></rect><text x="961" y="374" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">an addressed one waits in its chat's mailbox</tspan></text><text x="961" y="391" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">for a worker slot</tspan></text></g><g data-et="note" data-id="i12"><rect x="806" y="699" fill="#EDF2AE" stroke="#666" width="310" height="56" class="note"></rect><text x="961" y="704" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">daily budget checked: over it, one notice,</tspan></text><text x="961" y="721" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">then a ⏳ reaction instead of an answer</tspan></text></g><g data-et="control-structure" data-id="i24"><line x1="1295" y1="1073" x2="1748" y2="1073" class="loopLine"></line><line x1="1748" y1="1073" x2="1748" y2="1264" class="loopLine"></line><line x1="1295" y1="1264" x2="1748" y2="1264" class="loopLine"></line><line x1="1295" y1="1073" x2="1295" y2="1264" class="loopLine"></line><polygon points="1295,1073 1345,1073 1345,1086 1336.6,1093 1295,1093" class="labelBox"></polygon><text x="1320" y="1086" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="labelText" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">loop</text><text x="1546.5" y="1091" text-anchor="middle" class="loopText" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="1546.5">[at most 5 requests per</tspan></text><text x="1546.5" y="1108" text-anchor="middle" class="loopText" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="1546.5">reply]</tspan></text></g><g data-et="control-structure" data-id="i27"><line x1="338" y1="521" x2="1758" y2="521" class="loopLine"></line><line x1="1758" y1="521" x2="1758" y2="1362" class="loopLine"></line><line x1="338" y1="1362" x2="1758" y2="1362" class="loopLine"></line><line x1="338" y1="521" x2="338" y2="1362" class="loopLine"></line><line x1="338" y1="659" x2="1758" y2="659" class="loopLine" style="stroke-dasharray: 3, 3;"></line><polygon points="338,521 388,521 388,534 379.6,541 338,541" class="labelBox"></polygon><text x="363" y="534" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="labelText" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">alt</text><text x="1073" y="539" text-anchor="middle" class="loopText" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="1073">[a hook answers itself, e.g. /schedule, /intro]</tspan></text><text x="1048" y="677" text-anchor="middle" class="sectionTitle" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">[ask the model (an MCP chat command forces its tool here)]</text></g><text x="211" y="80" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">message (text, images, files)</text><line x1="76" y1="109" x2="345" y2="109" class="messageLine0" data-et="message" data-id="i0" data-from="U" data-to="S" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="492" y="124" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">JSON-RPC receive notification</text><line x1="350" y1="153" x2="634" y2="153" class="messageLine0" data-et="message" data-id="i1" data-from="S" data-to="N" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="798" y="168" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">bot.Received</text><line x1="639" y1="197" x2="957" y2="197" class="messageLine0" data-et="message" data-id="i2" data-from="N" data-to="B" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="801" y="438" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">Delivered (sender's name, mention)</text><line x1="960" y1="467" x2="642" y2="467" class="messageLine0" data-et="message" data-id="i6" data-from="B" data-to="N" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="1132" y="482" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">OnMessage</text><line x1="962" y1="511" x2="1302" y2="511" class="messageLine0" data-et="message" data-id="i7" data-from="B" data-to="F" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="1135" y="571" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">Action{Answer}</text><line x1="1305" y1="600" x2="965" y2="600" class="messageLine1" data-et="message" data-id="i9" data-from="F" data-to="B" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="stroke-dasharray: 3, 3; fill: none;"></line><text x="801" y="615" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">Send</text><line x1="960" y1="644" x2="642" y2="644" class="messageLine0" data-et="message" data-id="i10" data-from="B" data-to="N" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="801" y="770" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">Typing (sendTyping)</text><line x1="960" y1="799" x2="642" y2="799" class="messageLine0" data-et="message" data-id="i13" data-from="B" data-to="N" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="1132" y="814" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">OnTurn (files, links, vision)</text><line x1="962" y1="843" x2="1302" y2="843" class="messageLine0" data-et="message" data-id="i14" data-from="B" data-to="F" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="1135" y="858" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">Media, where a file or image is needed</text><line x1="1305" y1="887" x2="965" y2="887" class="messageLine0" data-et="message" data-id="i15" data-from="F" data-to="B" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="801" y="902" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">Media</text><line x1="960" y1="931" x2="642" y2="931" class="messageLine0" data-et="message" data-id="i16" data-from="B" data-to="N" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="495" y="946" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">getAttachment</text><line x1="637" y1="975" x2="353" y2="975" class="messageLine0" data-et="message" data-id="i17" data-from="N" data-to="S" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="1135" y="990" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">Additions (note, images, files)</text><line x1="1305" y1="1019" x2="965" y2="1019" class="messageLine1" data-et="message" data-id="i18" data-from="F" data-to="B" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="stroke-dasharray: 3, 3; fill: none;"></line><text x="1248" y="1034" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">prompt, history and offered tools</text><line x1="962" y1="1063" x2="1533" y2="1063" class="messageLine0" data-et="message" data-id="i19" data-from="B" data-to="M" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="1636" y="1137" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">chat completion</text><line x1="1538" y1="1166" x2="1733" y2="1166" class="messageLine0" data-et="message" data-id="i21" data-from="M" data-to="L" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="1639" y="1181" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">text or tool calls</text><line x1="1736" y1="1210" x2="1541" y2="1210" class="messageLine1" data-et="message" data-id="i22" data-from="L" data-to="M" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="stroke-dasharray: 3, 3; fill: none;"></line><text x="1423" y="1225" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">Tool.Run (charts, mcp)</text><line x1="1536" y1="1254" x2="1310" y2="1254" class="messageLine0" data-et="message" data-id="i23" data-from="M" data-to="F" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="1251" y="1279" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">reply text and pictures</text><line x1="1536" y1="1308" x2="965" y2="1308" class="messageLine1" data-et="message" data-id="i25" data-from="M" data-to="B" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="stroke-dasharray: 3, 3; fill: none;"></line><text x="801" y="1323" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">Send, or React for a single emoji</text><line x1="960" y1="1352" x2="642" y2="1352" class="messageLine0" data-et="message" data-id="i26" data-from="B" data-to="N" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="495" y="1377" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">send or sendReaction</text><line x1="637" y1="1406" x2="353" y2="1406" class="messageLine0" data-et="message" data-id="i28" data-from="N" data-to="S" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="214" y="1421" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">reply</text><line x1="348" y1="1450" x2="79" y2="1450" class="messageLine0" data-et="message" data-id="i29" data-from="S" data-to="U" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line></svg> \ No newline at end of file +<svg id="g1415" width="100%" xmlns="http://www.w3.org/2000/svg" style="max-width: 1912px;" viewBox="-50 -10 1912 1556" role="graphics-document document" aria-roledescription="sequence"><g><rect x="1662" y="1470" fill="#eaeaea" stroke="#666" width="150" height="65" name="L" rx="3" ry="3" class="actor actor-bottom"></rect><text x="1737" y="1502.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="1737" dy="0">Model API</tspan></text></g><g><rect x="1462" y="1470" fill="#eaeaea" stroke="#666" width="150" height="65" name="M" rx="3" ry="3" class="actor actor-bottom"></rect><text x="1537" y="1502.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="1537" dy="0">internal/model</tspan></text></g><g><rect x="1231" y="1470" fill="#eaeaea" stroke="#666" width="150" height="65" name="F" rx="3" ry="3" class="actor actor-bottom"></rect><text x="1306" y="1502.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="1306" dy="0">Features</tspan></text></g><g><rect x="886" y="1470" fill="#eaeaea" stroke="#666" width="150" height="65" name="B" rx="3" ry="3" class="actor actor-bottom"></rect><text x="961" y="1502.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="961" dy="0">internal/bot</tspan></text></g><g><rect x="563" y="1470" fill="#eaeaea" stroke="#666" width="150" height="65" name="N" rx="3" ry="3" class="actor actor-bottom"></rect><text x="638" y="1502.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="638" dy="0">internal/signal</tspan></text></g><g><rect x="274" y="1470" fill="#eaeaea" stroke="#666" width="150" height="65" name="S" rx="3" ry="3" class="actor actor-bottom"></rect><text x="349" y="1502.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="349" dy="0">signal-cli</tspan></text></g><g><rect x="0" y="1470" fill="#eaeaea" stroke="#666" width="150" height="65" name="U" rx="3" ry="3" class="actor actor-bottom"></rect><text x="75" y="1502.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="75" dy="0">Signal user</tspan></text></g><g><line id="actor6" x1="1737" y1="65" x2="1737" y2="1470" class="actor-line 200" stroke-width="0.5px" stroke="#999" name="L" data-et="life-line" data-id="L"></line><g id="root-6" data-et="participant" data-type="participant" data-id="L"><rect x="1662" y="0" fill="#eaeaea" stroke="#666" width="150" height="65" name="L" rx="3" ry="3" class="actor actor-top"></rect><text x="1737" y="32.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="1737" dy="0">Model API</tspan></text></g></g><g><line id="actor5" x1="1537" y1="65" x2="1537" y2="1470" class="actor-line 200" stroke-width="0.5px" stroke="#999" name="M" data-et="life-line" data-id="M"></line><g id="root-5" data-et="participant" data-type="participant" data-id="M"><rect x="1462" y="0" fill="#eaeaea" stroke="#666" width="150" height="65" name="M" rx="3" ry="3" class="actor actor-top"></rect><text x="1537" y="32.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="1537" dy="0">internal/model</tspan></text></g></g><g><line id="actor4" x1="1306" y1="65" x2="1306" y2="1470" class="actor-line 200" stroke-width="0.5px" stroke="#999" name="F" data-et="life-line" data-id="F"></line><g id="root-4" data-et="participant" data-type="participant" data-id="F"><rect x="1231" y="0" fill="#eaeaea" stroke="#666" width="150" height="65" name="F" rx="3" ry="3" class="actor actor-top"></rect><text x="1306" y="32.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="1306" dy="0">Features</tspan></text></g></g><g><line id="actor3" x1="961" y1="65" x2="961" y2="1470" class="actor-line 200" stroke-width="0.5px" stroke="#999" name="B" data-et="life-line" data-id="B"></line><g id="root-3" data-et="participant" data-type="participant" data-id="B"><rect x="886" y="0" fill="#eaeaea" stroke="#666" width="150" height="65" name="B" rx="3" ry="3" class="actor actor-top"></rect><text x="961" y="32.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="961" dy="0">internal/bot</tspan></text></g></g><g><line id="actor2" x1="638" y1="65" x2="638" y2="1470" class="actor-line 200" stroke-width="0.5px" stroke="#999" name="N" data-et="life-line" data-id="N"></line><g id="root-2" data-et="participant" data-type="participant" data-id="N"><rect x="563" y="0" fill="#eaeaea" stroke="#666" width="150" height="65" name="N" rx="3" ry="3" class="actor actor-top"></rect><text x="638" y="32.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="638" dy="0">internal/signal</tspan></text></g></g><g><line id="actor1" x1="349" y1="65" x2="349" y2="1470" class="actor-line 200" stroke-width="0.5px" stroke="#999" name="S" data-et="life-line" data-id="S"></line><g id="root-1" data-et="participant" data-type="participant" data-id="S"><rect x="274" y="0" fill="#eaeaea" stroke="#666" width="150" height="65" name="S" rx="3" ry="3" class="actor actor-top"></rect><text x="349" y="32.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="349" dy="0">signal-cli</tspan></text></g></g><g><line id="actor0" x1="75" y1="65" x2="75" y2="1470" class="actor-line 200" stroke-width="0.5px" stroke="#999" name="U" data-et="life-line" data-id="U"></line><g id="root-0" data-et="participant" data-type="participant" data-id="U"><rect x="0" y="0" fill="#eaeaea" stroke="#666" width="150" height="65" name="U" rx="3" ry="3" class="actor actor-top"></rect><text x="75" y="32.5" dominant-baseline="central" alignment-baseline="central" class="actor actor-box" style="text-anchor: middle; font-size: 16px; font-weight: 400; font-family: Helvetica, Arial, sans-serif;"><tspan x="75" dy="0">Signal user</tspan></text></g></g><style>#g1415{font-family:Helvetica,Arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#g1415 .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#g1415 .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#g1415 .error-icon{fill:#552222;}#g1415 .error-text{fill:#552222;stroke:#552222;}#g1415 .edge-thickness-normal{stroke-width:1px;}#g1415 .edge-thickness-thick{stroke-width:3.5px;}#g1415 .edge-pattern-solid{stroke-dasharray:0;}#g1415 .edge-thickness-invisible{stroke-width:0;fill:none;}#g1415 .edge-pattern-dashed{stroke-dasharray:3;}#g1415 .edge-pattern-dotted{stroke-dasharray:2;}#g1415 .marker{fill:#333333;stroke:#333333;}#g1415 .marker.cross{stroke:#333333;}#g1415 svg{font-family:Helvetica,Arial,sans-serif;font-size:16px;}#g1415 p{margin:0;}#g1415 .actor{stroke:#9370DB;fill:#ECECFF;stroke-width:1;}#g1415 rect.actor.outer-path[data-look="neo"]{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1415 rect.note[data-look="neo"]{stroke:#aaaa33;fill:#fff5ad;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1415 text.actor>tspan{fill:black;stroke:none;}#g1415 .actor-line{stroke:#9370DB;}#g1415 .innerArc{stroke-width:1.5;stroke-dasharray:none;}#g1415 .messageLine0{stroke-width:1.5;stroke-dasharray:none;stroke:#333;}#g1415 .messageLine1{stroke-width:1.5;stroke-dasharray:2,2;stroke:#333;}#g1415 [id$="-arrowhead"] path{fill:#333;stroke:#333;}#g1415 .sequenceNumber{fill:white;}#g1415 [id$="-sequencenumber"]{fill:#333;}#g1415 [id$="-crosshead"] path{fill:#333;stroke:#333;}#g1415 .messageText{fill:#333;stroke:none;}#g1415 .labelBox{stroke:#9370DB;fill:#ECECFF;filter:none;}#g1415 .labelText,#g1415 .labelText>tspan{fill:black;stroke:none;}#g1415 .loopText,#g1415 .loopText>tspan{fill:black;stroke:none;}#g1415 .sectionTitle,#g1415 .sectionTitle>tspan{fill:black;stroke:none;}#g1415 .loopLine{stroke-width:2px;stroke-dasharray:2,2;stroke:#9370DB;fill:#9370DB;}#g1415 .note{stroke:#aaaa33;fill:#fff5ad;}#g1415 .noteText,#g1415 .noteText>tspan{fill:black;stroke:none;font-weight:normal;}#g1415 .activation0{fill:#f4f4f4;stroke:#666;}#g1415 .activation1{fill:#f4f4f4;stroke:#666;}#g1415 .activation2{fill:#f4f4f4;stroke:#666;}#g1415 .actorPopupMenu{position:absolute;}#g1415 .actorPopupMenuPanel{position:absolute;fill:#ECECFF;box-shadow:0px 8px 16px 0px rgba(0,0,0,0.2);filter:drop-shadow(3px 5px 2px rgb(0 0 0 / 0.4));}#g1415 .actor-man circle,#g1415 line{fill:#ECECFF;stroke-width:2px;}#g1415 g rect.rect{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));stroke:#9370DB;}#g1415 .node .neo-node{stroke:#9370DB;}#g1415 [data-look="neo"].node rect,#g1415 [data-look="neo"].cluster rect,#g1415 [data-look="neo"].node polygon{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1415 [data-look="neo"].swimlane.cluster rect{filter:none;}#g1415 [data-look="neo"].node path{stroke:#9370DB;stroke-width:1px;}#g1415 [data-look="neo"].node .outer-path{filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1415 [data-look="neo"].node .neo-line path{stroke:#9370DB;filter:none;}#g1415 [data-look="neo"].node circle{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1415 [data-look="neo"].node circle .state-start{fill:#000000;}#g1415 [data-look="neo"].icon-shape .icon{fill:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1415 [data-look="neo"].icon-shape .icon-neo path{stroke:#9370DB;filter:drop-shadow(1px 2px 2px rgba(185, 185, 185, 1));}#g1415 :root{--mermaid-font-family:Helvetica,Arial,sans-serif;}</style><g></g><defs><symbol id="g1415-computer" width="24" height="24"><path transform="scale(.5)" d="M2 2v13h20v-13h-20zm18 11h-16v-9h16v9zm-10.228 6l.466-1h3.524l.467 1h-4.457zm14.228 3h-24l2-6h2.104l-1.33 4h18.45l-1.297-4h2.073l2 6zm-5-10h-14v-7h14v7z"></path></symbol></defs><defs><symbol id="g1415-database" fill-rule="evenodd" clip-rule="evenodd"><path transform="scale(.5)" d="M12.258.001l.256.004.255.005.253.008.251.01.249.012.247.015.246.016.242.019.241.02.239.023.236.024.233.027.231.028.229.031.225.032.223.034.22.036.217.038.214.04.211.041.208.043.205.045.201.046.198.048.194.05.191.051.187.053.183.054.18.056.175.057.172.059.168.06.163.061.16.063.155.064.15.066.074.033.073.033.071.034.07.034.069.035.068.035.067.035.066.035.064.036.064.036.062.036.06.036.06.037.058.037.058.037.055.038.055.038.053.038.052.038.051.039.05.039.048.039.047.039.045.04.044.04.043.04.041.04.04.041.039.041.037.041.036.041.034.041.033.042.032.042.03.042.029.042.027.042.026.043.024.043.023.043.021.043.02.043.018.044.017.043.015.044.013.044.012.044.011.045.009.044.007.045.006.045.004.045.002.045.001.045v17l-.001.045-.002.045-.004.045-.006.045-.007.045-.009.044-.011.045-.012.044-.013.044-.015.044-.017.043-.018.044-.02.043-.021.043-.023.043-.024.043-.026.043-.027.042-.029.042-.03.042-.032.042-.033.042-.034.041-.036.041-.037.041-.039.041-.04.041-.041.04-.043.04-.044.04-.045.04-.047.039-.048.039-.05.039-.051.039-.052.038-.053.038-.055.038-.055.038-.058.037-.058.037-.06.037-.06.036-.062.036-.064.036-.064.036-.066.035-.067.035-.068.035-.069.035-.07.034-.071.034-.073.033-.074.033-.15.066-.155.064-.16.063-.163.061-.168.06-.172.059-.175.057-.18.056-.183.054-.187.053-.191.051-.194.05-.198.048-.201.046-.205.045-.208.043-.211.041-.214.04-.217.038-.22.036-.223.034-.225.032-.229.031-.231.028-.233.027-.236.024-.239.023-.241.02-.242.019-.246.016-.247.015-.249.012-.251.01-.253.008-.255.005-.256.004-.258.001-.258-.001-.256-.004-.255-.005-.253-.008-.251-.01-.249-.012-.247-.015-.245-.016-.243-.019-.241-.02-.238-.023-.236-.024-.234-.027-.231-.028-.228-.031-.226-.032-.223-.034-.22-.036-.217-.038-.214-.04-.211-.041-.208-.043-.204-.045-.201-.046-.198-.048-.195-.05-.19-.051-.187-.053-.184-.054-.179-.056-.176-.057-.172-.059-.167-.06-.164-.061-.159-.063-.155-.064-.151-.066-.074-.033-.072-.033-.072-.034-.07-.034-.069-.035-.068-.035-.067-.035-.066-.035-.064-.036-.063-.036-.062-.036-.061-.036-.06-.037-.058-.037-.057-.037-.056-.038-.055-.038-.053-.038-.052-.038-.051-.039-.049-.039-.049-.039-.046-.039-.046-.04-.044-.04-.043-.04-.041-.04-.04-.041-.039-.041-.037-.041-.036-.041-.034-.041-.033-.042-.032-.042-.03-.042-.029-.042-.027-.042-.026-.043-.024-.043-.023-.043-.021-.043-.02-.043-.018-.044-.017-.043-.015-.044-.013-.044-.012-.044-.011-.045-.009-.044-.007-.045-.006-.045-.004-.045-.002-.045-.001-.045v-17l.001-.045.002-.045.004-.045.006-.045.007-.045.009-.044.011-.045.012-.044.013-.044.015-.044.017-.043.018-.044.02-.043.021-.043.023-.043.024-.043.026-.043.027-.042.029-.042.03-.042.032-.042.033-.042.034-.041.036-.041.037-.041.039-.041.04-.041.041-.04.043-.04.044-.04.046-.04.046-.039.049-.039.049-.039.051-.039.052-.038.053-.038.055-.038.056-.038.057-.037.058-.037.06-.037.061-.036.062-.036.063-.036.064-.036.066-.035.067-.035.068-.035.069-.035.07-.034.072-.034.072-.033.074-.033.151-.066.155-.064.159-.063.164-.061.167-.06.172-.059.176-.057.179-.056.184-.054.187-.053.19-.051.195-.05.198-.048.201-.046.204-.045.208-.043.211-.041.214-.04.217-.038.22-.036.223-.034.226-.032.228-.031.231-.028.234-.027.236-.024.238-.023.241-.02.243-.019.245-.016.247-.015.249-.012.251-.01.253-.008.255-.005.256-.004.258-.001.258.001zm-9.258 20.499v.01l.001.021.003.021.004.022.005.021.006.022.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.023.018.024.019.024.021.024.022.025.023.024.024.025.052.049.056.05.061.051.066.051.07.051.075.051.079.052.084.052.088.052.092.052.097.052.102.051.105.052.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.048.144.049.147.047.152.047.155.047.16.045.163.045.167.043.171.043.176.041.178.041.183.039.187.039.19.037.194.035.197.035.202.033.204.031.209.03.212.029.216.027.219.025.222.024.226.021.23.02.233.018.236.016.24.015.243.012.246.01.249.008.253.005.256.004.259.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.021.224-.024.22-.026.216-.027.212-.028.21-.031.205-.031.202-.034.198-.034.194-.036.191-.037.187-.039.183-.04.179-.04.175-.042.172-.043.168-.044.163-.045.16-.046.155-.046.152-.047.148-.048.143-.049.139-.049.136-.05.131-.05.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.053.083-.051.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.05.023-.024.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.023.01-.022.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.127l-.077.055-.08.053-.083.054-.085.053-.087.052-.09.052-.093.051-.095.05-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.045-.118.044-.12.043-.122.042-.124.042-.126.041-.128.04-.13.04-.132.038-.134.038-.135.037-.138.037-.139.035-.142.035-.143.034-.144.033-.147.032-.148.031-.15.03-.151.03-.153.029-.154.027-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.01-.179.008-.179.008-.181.006-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.006-.179-.008-.179-.008-.178-.01-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.027-.153-.029-.151-.03-.15-.03-.148-.031-.146-.032-.145-.033-.143-.034-.141-.035-.14-.035-.137-.037-.136-.037-.134-.038-.132-.038-.13-.04-.128-.04-.126-.041-.124-.042-.122-.042-.12-.044-.117-.043-.116-.045-.113-.045-.112-.046-.109-.047-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.05-.093-.052-.09-.051-.087-.052-.085-.053-.083-.054-.08-.054-.077-.054v4.127zm0-5.654v.011l.001.021.003.021.004.021.005.022.006.022.007.022.009.022.01.022.011.023.012.023.013.023.015.024.016.023.017.024.018.024.019.024.021.024.022.024.023.025.024.024.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.052.11.051.114.051.119.052.123.05.127.051.131.05.135.049.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.044.171.042.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.022.23.02.233.018.236.016.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.012.241-.015.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.048.139-.05.136-.049.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.051.051-.049.023-.025.023-.024.021-.025.02-.024.019-.024.018-.024.017-.024.015-.023.014-.023.013-.024.012-.022.01-.023.01-.023.008-.022.006-.022.006-.022.004-.021.004-.022.001-.021.001-.021v-4.139l-.077.054-.08.054-.083.054-.085.052-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.049-.105.048-.106.047-.109.047-.111.046-.114.045-.115.044-.118.044-.12.044-.122.042-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.035-.143.033-.144.033-.147.033-.148.031-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.025-.161.024-.162.023-.163.022-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.011-.178.009-.179.009-.179.007-.181.007-.182.005-.182.004-.184.003-.184.002h-.37l-.184-.002-.184-.003-.182-.004-.182-.005-.181-.007-.179-.007-.179-.009-.178-.009-.176-.011-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.022-.162-.023-.161-.024-.159-.025-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.031-.146-.033-.145-.033-.143-.033-.141-.035-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.04-.126-.041-.124-.042-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.047-.105-.048-.102-.049-.1-.049-.097-.05-.095-.051-.093-.051-.09-.051-.087-.053-.085-.052-.083-.054-.08-.054-.077-.054v4.139zm0-5.666v.011l.001.02.003.022.004.021.005.022.006.021.007.022.009.023.01.022.011.023.012.023.013.023.015.023.016.024.017.024.018.023.019.024.021.025.022.024.023.024.024.025.052.05.056.05.061.05.066.051.07.051.075.052.079.051.084.052.088.052.092.052.097.052.102.052.105.051.11.052.114.051.119.051.123.051.127.05.131.05.135.05.139.049.144.048.147.048.152.047.155.046.16.045.163.045.167.043.171.043.176.042.178.04.183.04.187.038.19.037.194.036.197.034.202.033.204.032.209.03.212.028.216.027.219.025.222.024.226.021.23.02.233.018.236.017.24.014.243.012.246.01.249.008.253.006.256.003.259.001.26-.001.257-.003.254-.006.25-.008.247-.01.244-.013.241-.014.237-.016.233-.018.231-.02.226-.022.224-.024.22-.025.216-.027.212-.029.21-.03.205-.032.202-.033.198-.035.194-.036.191-.037.187-.039.183-.039.179-.041.175-.042.172-.043.168-.044.163-.045.16-.045.155-.047.152-.047.148-.048.143-.049.139-.049.136-.049.131-.051.126-.05.123-.051.118-.052.114-.051.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.052.07-.051.065-.051.06-.051.056-.05.051-.049.023-.025.023-.025.021-.024.02-.024.019-.024.018-.024.017-.024.015-.023.014-.024.013-.023.012-.023.01-.022.01-.023.008-.022.006-.022.006-.022.004-.022.004-.021.001-.021.001-.021v-4.153l-.077.054-.08.054-.083.053-.085.053-.087.053-.09.051-.093.051-.095.051-.097.05-.1.049-.102.048-.105.048-.106.048-.109.046-.111.046-.114.046-.115.044-.118.044-.12.043-.122.043-.124.042-.126.041-.128.04-.13.039-.132.039-.134.038-.135.037-.138.036-.139.036-.142.034-.143.034-.144.033-.147.032-.148.032-.15.03-.151.03-.153.028-.154.028-.156.027-.158.026-.159.024-.161.024-.162.023-.163.023-.165.021-.166.02-.167.019-.169.018-.169.017-.171.016-.173.015-.173.014-.175.013-.175.012-.177.01-.178.01-.179.009-.179.007-.181.006-.182.006-.182.004-.184.003-.184.001-.185.001-.185-.001-.184-.001-.184-.003-.182-.004-.182-.006-.181-.006-.179-.007-.179-.009-.178-.01-.176-.01-.176-.012-.175-.013-.173-.014-.172-.015-.171-.016-.17-.017-.169-.018-.167-.019-.166-.02-.165-.021-.163-.023-.162-.023-.161-.024-.159-.024-.157-.026-.156-.027-.155-.028-.153-.028-.151-.03-.15-.03-.148-.032-.146-.032-.145-.033-.143-.034-.141-.034-.14-.036-.137-.036-.136-.037-.134-.038-.132-.039-.13-.039-.128-.041-.126-.041-.124-.041-.122-.043-.12-.043-.117-.044-.116-.044-.113-.046-.112-.046-.109-.046-.106-.048-.105-.048-.102-.048-.1-.05-.097-.049-.095-.051-.093-.051-.09-.052-.087-.052-.085-.053-.083-.053-.08-.054-.077-.054v4.153zm8.74-8.179l-.257.004-.254.005-.25.008-.247.011-.244.012-.241.014-.237.016-.233.018-.231.021-.226.022-.224.023-.22.026-.216.027-.212.028-.21.031-.205.032-.202.033-.198.034-.194.036-.191.038-.187.038-.183.04-.179.041-.175.042-.172.043-.168.043-.163.045-.16.046-.155.046-.152.048-.148.048-.143.048-.139.049-.136.05-.131.05-.126.051-.123.051-.118.051-.114.052-.11.052-.106.052-.101.052-.096.052-.092.052-.088.052-.083.052-.079.052-.074.051-.07.052-.065.051-.06.05-.056.05-.051.05-.023.025-.023.024-.021.024-.02.025-.019.024-.018.024-.017.023-.015.024-.014.023-.013.023-.012.023-.01.023-.01.022-.008.022-.006.023-.006.021-.004.022-.004.021-.001.021-.001.021.001.021.001.021.004.021.004.022.006.021.006.023.008.022.01.022.01.023.012.023.013.023.014.023.015.024.017.023.018.024.019.024.02.025.021.024.023.024.023.025.051.05.056.05.06.05.065.051.07.052.074.051.079.052.083.052.088.052.092.052.096.052.101.052.106.052.11.052.114.052.118.051.123.051.126.051.131.05.136.05.139.049.143.048.148.048.152.048.155.046.16.046.163.045.168.043.172.043.175.042.179.041.183.04.187.038.191.038.194.036.198.034.202.033.205.032.21.031.212.028.216.027.22.026.224.023.226.022.231.021.233.018.237.016.241.014.244.012.247.011.25.008.254.005.257.004.26.001.26-.001.257-.004.254-.005.25-.008.247-.011.244-.012.241-.014.237-.016.233-.018.231-.021.226-.022.224-.023.22-.026.216-.027.212-.028.21-.031.205-.032.202-.033.198-.034.194-.036.191-.038.187-.038.183-.04.179-.041.175-.042.172-.043.168-.043.163-.045.16-.046.155-.046.152-.048.148-.048.143-.048.139-.049.136-.05.131-.05.126-.051.123-.051.118-.051.114-.052.11-.052.106-.052.101-.052.096-.052.092-.052.088-.052.083-.052.079-.052.074-.051.07-.052.065-.051.06-.05.056-.05.051-.05.023-.025.023-.024.021-.024.02-.025.019-.024.018-.024.017-.023.015-.024.014-.023.013-.023.012-.023.01-.023.01-.022.008-.022.006-.023.006-.021.004-.022.004-.021.001-.021.001-.021-.001-.021-.001-.021-.004-.021-.004-.022-.006-.021-.006-.023-.008-.022-.01-.022-.01-.023-.012-.023-.013-.023-.014-.023-.015-.024-.017-.023-.018-.024-.019-.024-.02-.025-.021-.024-.023-.024-.023-.025-.051-.05-.056-.05-.06-.05-.065-.051-.07-.052-.074-.051-.079-.052-.083-.052-.088-.052-.092-.052-.096-.052-.101-.052-.106-.052-.11-.052-.114-.052-.118-.051-.123-.051-.126-.051-.131-.05-.136-.05-.139-.049-.143-.048-.148-.048-.152-.048-.155-.046-.16-.046-.163-.045-.168-.043-.172-.043-.175-.042-.179-.041-.183-.04-.187-.038-.191-.038-.194-.036-.198-.034-.202-.033-.205-.032-.21-.031-.212-.028-.216-.027-.22-.026-.224-.023-.226-.022-.231-.021-.233-.018-.237-.016-.241-.014-.244-.012-.247-.011-.25-.008-.254-.005-.257-.004-.26-.001-.26.001z"></path></symbol></defs><defs><symbol id="g1415-clock" width="24" height="24"><path transform="scale(.5)" d="M12 2c5.514 0 10 4.486 10 10s-4.486 10-10 10-10-4.486-10-10 4.486-10 10-10zm0-2c-6.627 0-12 5.373-12 12s5.373 12 12 12 12-5.373 12-12-5.373-12-12-12zm5.848 12.459c.202.038.202.333.001.372-1.907.361-6.045 1.111-6.547 1.111-.719 0-1.301-.582-1.301-1.301 0-.512.77-5.447 1.125-7.445.034-.192.312-.181.343.014l.985 6.238 5.394 1.011z"></path></symbol></defs><defs><marker id="g1415-arrowhead" refX="7.9" refY="5" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto-start-reverse"><path d="M -1 0 L 10 5 L 0 10 z"></path></marker></defs><defs><marker id="g1415-crosshead" markerWidth="15" markerHeight="8" orient="auto" refX="4" refY="4.5"><path fill="none" stroke="#000000" stroke-width="1pt" d="M 1,2 L 6,7 M 6,2 L 1,7" style="stroke-dasharray: 0, 0;"></path></marker></defs><defs><marker id="g1415-filled-head" refX="15.5" refY="7" markerWidth="20" markerHeight="28" orient="auto"><path d="M 18,7 L9,13 L14,7 L9,1 Z"></path></marker></defs><defs><marker id="g1415-sequencenumber" refX="15" refY="15" markerWidth="60" markerHeight="40" orient="auto"><circle cx="15" cy="15" r="6"></circle></marker></defs><defs><marker id="g1415-solidTopArrowHead" refX="7.9" refY="7.25" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto-start-reverse"><path d="M 0 0 L 10 8 L 0 8 z"></path></marker></defs><defs><marker id="g1415-solidBottomArrowHead" refX="7.9" refY="0.75" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto-start-reverse"><path d="M 0 0 L 10 0 L 0 8 z"></path></marker></defs><defs><marker id="g1415-stickTopArrowHead" refX="7.5" refY="7" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto-start-reverse"><path d="M 0 0 L 7 7" stroke="black" stroke-width="1.5" fill="none"></path></marker></defs><defs><marker id="g1415-stickBottomArrowHead" refX="7.5" refY="0" markerUnits="userSpaceOnUse" markerWidth="12" markerHeight="12" orient="auto-start-reverse"><path d="M 0 7 L 7 0" stroke="black" stroke-width="1.5" fill="none"></path></marker></defs><g data-et="note" data-id="i3"><rect x="764" y="207" fill="#EDF2AE" stroke="#666" width="394" height="71" class="note"></rect><text x="961" y="212" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">an unaddressed group message only runs the</tspan></text><text x="961" y="229" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">OnMessage hooks (groupctx keeps it as context</tspan></text><text x="961" y="246" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">unless an earlier one took it); never logged</tspan></text></g><g data-et="note" data-id="i4"><rect x="793.5" y="288" fill="#EDF2AE" stroke="#666" width="335" height="71" class="note"></rect><text x="961" y="293" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">an edit is handled as a new message</tspan></text><text x="961" y="310" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">in place of the original, a delete for everyone</tspan></text><text x="961" y="327" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">drops the message from history</tspan></text></g><g data-et="note" data-id="i5"><rect x="795" y="369" fill="#EDF2AE" stroke="#666" width="332" height="54" class="note"></rect><text x="961" y="374" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">an addressed one waits in its chat's mailbox</tspan></text><text x="961" y="391" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">for a worker slot</tspan></text></g><g data-et="note" data-id="i12"><rect x="806" y="699" fill="#EDF2AE" stroke="#666" width="310" height="56" class="note"></rect><text x="961" y="704" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">daily budget checked: over it, one notice,</tspan></text><text x="961" y="721" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="noteText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="961">then a ⏳ reaction instead of an answer</tspan></text></g><g data-et="control-structure" data-id="i24"><line x1="1295" y1="1073" x2="1748" y2="1073" class="loopLine"></line><line x1="1748" y1="1073" x2="1748" y2="1264" class="loopLine"></line><line x1="1295" y1="1264" x2="1748" y2="1264" class="loopLine"></line><line x1="1295" y1="1073" x2="1295" y2="1264" class="loopLine"></line><polygon points="1295,1073 1345,1073 1345,1086 1336.6,1093 1295,1093" class="labelBox"></polygon><text x="1320" y="1086" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="labelText" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">loop</text><text x="1546.5" y="1091" text-anchor="middle" class="loopText" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="1546.5">[at most 5 requests per</tspan></text><text x="1546.5" y="1108" text-anchor="middle" class="loopText" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="1546.5">reply]</tspan></text></g><g data-et="control-structure" data-id="i27"><line x1="338" y1="521" x2="1758" y2="521" class="loopLine"></line><line x1="1758" y1="521" x2="1758" y2="1362" class="loopLine"></line><line x1="338" y1="1362" x2="1758" y2="1362" class="loopLine"></line><line x1="338" y1="521" x2="338" y2="1362" class="loopLine"></line><line x1="338" y1="659" x2="1758" y2="659" class="loopLine" style="stroke-dasharray: 3, 3;"></line><polygon points="338,521 388,521 388,534 379.6,541 338,541" class="labelBox"></polygon><text x="363" y="534" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="labelText" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">alt</text><text x="1073" y="539" text-anchor="middle" class="loopText" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;"><tspan x="1073">[a hook answers itself, e.g. /schedule, /intro]</tspan></text><text x="1048" y="677" text-anchor="middle" class="sectionTitle" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">[ask the model (an MCP chat command forces its tool here)]</text></g><text x="211" y="80" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">message (text, images, files)</text><line x1="76" y1="109" x2="345" y2="109" class="messageLine0" data-et="message" data-id="i0" data-from="U" data-to="S" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="492" y="124" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">JSON-RPC receive notification</text><line x1="350" y1="153" x2="634" y2="153" class="messageLine0" data-et="message" data-id="i1" data-from="S" data-to="N" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="798" y="168" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">bot.Received</text><line x1="639" y1="197" x2="957" y2="197" class="messageLine0" data-et="message" data-id="i2" data-from="N" data-to="B" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="801" y="438" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">Delivered (sender's name, mention)</text><line x1="960" y1="467" x2="642" y2="467" class="messageLine0" data-et="message" data-id="i6" data-from="B" data-to="N" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="1132" y="482" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">OnMessage</text><line x1="962" y1="511" x2="1302" y2="511" class="messageLine0" data-et="message" data-id="i7" data-from="B" data-to="F" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="1135" y="571" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">Action{Answer}</text><line x1="1305" y1="600" x2="965" y2="600" class="messageLine1" data-et="message" data-id="i9" data-from="F" data-to="B" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="stroke-dasharray: 3, 3; fill: none;"></line><text x="801" y="615" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">Send</text><line x1="960" y1="644" x2="642" y2="644" class="messageLine0" data-et="message" data-id="i10" data-from="B" data-to="N" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="801" y="770" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">Typing (sendTyping)</text><line x1="960" y1="799" x2="642" y2="799" class="messageLine0" data-et="message" data-id="i13" data-from="B" data-to="N" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="1132" y="814" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">OnTurn (files, links, vision)</text><line x1="962" y1="843" x2="1302" y2="843" class="messageLine0" data-et="message" data-id="i14" data-from="B" data-to="F" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="1135" y="858" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">Media, where a file or image is needed</text><line x1="1305" y1="887" x2="965" y2="887" class="messageLine0" data-et="message" data-id="i15" data-from="F" data-to="B" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="801" y="902" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">Media</text><line x1="960" y1="931" x2="642" y2="931" class="messageLine0" data-et="message" data-id="i16" data-from="B" data-to="N" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="495" y="946" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">getAttachment</text><line x1="637" y1="975" x2="353" y2="975" class="messageLine0" data-et="message" data-id="i17" data-from="N" data-to="S" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="1135" y="990" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">Additions (note, images, files)</text><line x1="1305" y1="1019" x2="965" y2="1019" class="messageLine1" data-et="message" data-id="i18" data-from="F" data-to="B" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="stroke-dasharray: 3, 3; fill: none;"></line><text x="1248" y="1034" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">prompt, history and offered tools</text><line x1="962" y1="1063" x2="1533" y2="1063" class="messageLine0" data-et="message" data-id="i19" data-from="B" data-to="M" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="1636" y="1137" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">chat completion</text><line x1="1538" y1="1166" x2="1733" y2="1166" class="messageLine0" data-et="message" data-id="i21" data-from="M" data-to="L" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="1639" y="1181" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">text or tool calls</text><line x1="1736" y1="1210" x2="1541" y2="1210" class="messageLine1" data-et="message" data-id="i22" data-from="L" data-to="M" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="stroke-dasharray: 3, 3; fill: none;"></line><text x="1423" y="1225" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">Tool.Run (charts, mcp)</text><line x1="1536" y1="1254" x2="1310" y2="1254" class="messageLine0" data-et="message" data-id="i23" data-from="M" data-to="F" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="1251" y="1279" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">reply text and pictures</text><line x1="1536" y1="1308" x2="965" y2="1308" class="messageLine1" data-et="message" data-id="i25" data-from="M" data-to="B" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="stroke-dasharray: 3, 3; fill: none;"></line><text x="801" y="1323" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">Send, or React for a single emoji</text><line x1="960" y1="1352" x2="642" y2="1352" class="messageLine0" data-et="message" data-id="i26" data-from="B" data-to="N" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="495" y="1377" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">send or sendReaction</text><line x1="637" y1="1406" x2="353" y2="1406" class="messageLine0" data-et="message" data-id="i28" data-from="N" data-to="S" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line><text x="214" y="1421" text-anchor="middle" dominant-baseline="middle" alignment-baseline="middle" class="messageText" dy="1em" style="font-family: Helvetica, Arial, sans-serif; font-size: 16px; font-weight: 400;">reply</text><line x1="348" y1="1450" x2="79" y2="1450" class="messageLine0" data-et="message" data-id="i29" data-from="S" data-to="U" stroke-width="2" stroke="none" marker-end="url(#g1415-arrowhead)" style="fill: none;"></line></svg> \ No newline at end of file diff --git a/examples/signalbot-mcp.json b/examples/signalbot-mcp.json index da81436..3c5cfdf 100644 --- a/examples/signalbot-mcp.json +++ b/examples/signalbot-mcp.json @@ -10,6 +10,11 @@ "alerts": {"tool": "get_alerts"} } }, + "geo": { + "command": "/addons/geoguess", + "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m"}}, + "addon": {"chats": ["all"], "dms": false, "post": true, "react": true, "watch": true, "watch_max": "1h"} + }, "files": { "command": "uvx", "args": ["some-mcp-server"], diff --git a/features.go b/features.go index 5d0be6b..5c9cc17 100644 --- a/features.go +++ b/features.go @@ -21,13 +21,13 @@ import ( var features = []func(feature.Host) error{ intro.Register, websearch.Register, - groupctx.Register, vision.Register, files.Register, links.Register, chartsFeature, // after websearch, for the tools line; build tag nocharts imagegen.Register, // after charts, for the tools line mcp.Register, // after websearch and charts, for the tools line + groupctx.Register, // after mcp, whose hook must see group chatter first: groupctx keeps all of it schedule.Register, } diff --git a/internal/arch/arch_test.go b/internal/arch/arch_test.go index 75c1bfd..13e56fe 100644 --- a/internal/arch/arch_test.go +++ b/internal/arch/arch_test.go @@ -43,7 +43,8 @@ func under(p, dir string) bool { return p == dir || strings.HasPrefix(p, dir+"/" // its own packages and kit; internal/signal imports only those, // internal/config and internal/bot (for Received: the network depends on // the core, never the reverse); internal/config and kit import no other -// internal package. +// internal package; GeoGuess, an addon the bot runs as a separate program, +// imports only kit and its own packages. func TestImports(t *testing.T) { for _, p := range goFiles(t) { f, err := parser.ParseFile(token.NewFileSet(), root+"/"+p, nil, parser.ImportsOnly) @@ -71,6 +72,8 @@ func TestImports(t *testing.T) { ok = under(imp, "internal/feature") || under(imp, "internal/kit") || imp == "internal/config" || imp == "internal/bot" case under(dir, "internal/kit"), dir == "internal/config": ok = under(imp, "internal/kit") + case under(dir, "cmd/geoguess"): + ok = under(imp, "internal/kit") || under(imp, "cmd/geoguess") default: ok = dir == "." || !under(imp, "internal/features") && !under(imp, "internal/signal") && !under(imp, "internal/telegram") } diff --git a/internal/bot/answer.go b/internal/bot/answer.go index bad01a2..9868e7e 100644 --- a/internal/bot/answer.go +++ b/internal/bot/answer.go @@ -56,18 +56,25 @@ const ( waiting = "⏳" ) -// respond acts on an addressed message: as act says, else by asking the -// model and sending its reply (asking again if the API rejects its images -// or tools; see fallBack); with no model, only an Answer is sent, and with -// tools off a chat command gets noTools rather than an answer made up -// without its tool's data. text +// respond acts on an addressed message: as act says (nothing if Done; its +// Answer and Pictures sent, with OnSent told of what went out), else by +// asking the model and sending its reply (asking again if the API rejects +// its images or tools; see fallBack); with no model, only an Answer and +// Pictures are sent, and with tools off a chat command gets noTools rather +// than an answer made up without its tool's data. text // is the message as the model sees it, prompt(msg) for one message; tools // are offered by msg.Text alone, what was typed, never a sender's name or a // quote. refs names the messages answered, for history (see Forget). func (b *Bot) respond(msg feature.Message, act feature.Action, text string, refs []chats.Ref) { switch { - case act.Answer != "": - b.net.Send(msg.Chat, act.Answer, nil, b.chats.Names(msg.Chat.Key())) + case act.Done: + return + case act.Answer != "" || len(act.Pictures) > 0: + text, _ := captioned(act.Answer, act.Pictures) + sent := b.net.Send(msg.Chat, text, act.Pictures, b.chats.Names(msg.Chat.Key())) + if act.OnSent != nil { + act.OnSent(sent) + } return case b.ai == nil: return // no model: no typing, no reply @@ -142,17 +149,6 @@ func (b *Bot) respond(msg feature.Message, act feature.Action, text string, refs return } b.followUp(key, offered, msg.Text, reply.ToolsUsed) - // History notes the pictures sent, which the model would otherwise not - // know it did. Pictures with captions are sent with those in place of - // the text, which neither goes out nor is kept. - var notes string - var captions []string - for _, p := range reply.Pictures { - notes += cmp.Or(p.HistoryNote, "[sent an image]") + "\n" - if p.Caption != "" { - captions = append(captions, p.Caption) - } - } // A reply that is one emoji, and nothing else, is a reaction to the // message, unless the bot made the message (a scheduled post), which // can't be reacted to. @@ -164,16 +160,31 @@ func (b *Bot) respond(msg feature.Message, act feature.Action, text string, refs b.net.React(msg.Chat, msg, emoji) return } - sent := reply.Text - if len(captions) > 0 { - reply.Text, sent = "", strings.Join(captions, "\n") - } + sent, kept := captioned(reply.Text, reply.Pictures) p := b.pending() b.chats.Add(key, start, msg.Expires, chats.Entry{Role: "user", Content: strings.TrimSpace(t.kept), Refs: refs}, - chats.Entry{Role: "assistant", Content: notes + reply.Text, Refs: []chats.Ref{p}}) + chats.Entry{Role: "assistant", Content: kept, Refs: []chats.Ref{p}}) b.sendKept(key, p, msg.Chat, sent, reply.Pictures, b.chats.Names(key)) } +// captioned is the caption rule, for text sent with pics: what is sent, and +// what history keeps of it. History notes each picture, which the model +// would otherwise not know the bot sent. Pictures with captions are sent +// with those in place of the text, which then neither goes out nor is kept. +func captioned(text string, pics []feature.Picture) (sent, kept string) { + var captions []string + for _, p := range pics { + kept += cmp.Or(p.HistoryNote, "[sent an image]") + "\n" + if p.Caption != "" { + captions = append(captions, p.Caption) + } + } + if len(captions) > 0 { + return strings.Join(captions, "\n"), kept + } + return text, kept + text +} + // askedForMore is added to a message asked again after the model answered // it with a lone emoji though its words offered a tool. const askedForMore = "[This message asks you for something: answer it in words, or with a tool if one fits, not with an emoji alone.]" diff --git a/internal/bot/bot.go b/internal/bot/bot.go index b0ac499..4554ade 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -43,6 +43,10 @@ type Network interface { // Delivered readies a posted message in its slot. ok is false, logged, // if msg is dropped. Delivered(ctx context.Context, msg feature.Message) (r Ready, ok bool) + // Reachable reports, in the chat's slot, whether the bot may still post + // in chat on its own: a group it is still in and answers in, or the DM + // of a user still allowed to DM it. + Reachable(ctx context.Context, chat feature.Chat) bool // BotName never blocks. BotName() string // Prompt is the network's own line in the system prompt, such as its @@ -97,6 +101,7 @@ type Bot struct { func New(ctx context.Context, cfg *config.Config, net Network) *Bot { b := &Bot{cfg: cfg, net: net, timers: timers.New(), slots: make(chan struct{}, cfg.MaxConcurrency), ctx: ctx, now: time.Now} b.chats = chats.New(cfg.HistoryMax, b.work, b.spawn) + b.chats.SetEvicted(func(r Received) { b.dropped(r, errMadeRoom) }) b.timerCtx, b.stopTimers = context.WithCancel(ctx) if cfg.NoModel { logx.Warnf("no model: set MODEL_API_KEY (or MODEL_API_URL for a provider that needs no key); until then only commands are answered") @@ -166,8 +171,8 @@ func (b *Bot) Shutdown(d time.Duration) { // member change comes from another of its goroutines), so it never blocks // or calls the network. An Incoming message and, with a hook for them, a // Happened event go to their chat's mailbox; Chatter goes to the OnMessage -// hooks here, and is never logged. (A Posted message comes from Deliver, -// never from the network.) +// hooks here, and is never logged. (Posted, Outgoing and Reacted come from +// Deliver, Post and React, never from the network.) func (b *Bot) handle(r Received) { if b.closing.Load() { return @@ -193,10 +198,10 @@ func (b *Bot) handle(r Received) { } // overhear runs the OnMessage hooks for an unaddressed group message, and keeps -// the Context one returns in history. +// the Context one returns in history, unless it is Done, which keeps nothing. func (b *Bot) overhear(msg feature.Message) { b.replaced(msg) - if a := b.onMessage(b.ctx, msg); a.Context != "" && b.ai != nil { // with no model, nothing would read it + if a := b.onMessage(b.ctx, msg); a.Context != "" && !a.Done && b.ai != nil { // with no model, nothing would read it b.chats.Add(msg.Chat.Key(), b.now(), msg.Expires, chats.Entry{Role: "user", Content: a.Context, Context: true, Refs: refs(msg)}) } } @@ -221,11 +226,13 @@ func (b *Bot) pending() chats.Ref { } // sendKept sends text to chat, after entries were kept holding ref p, then -// names them by what was sent, so a delete from a linked device finds them. -// History is kept first so a message arriving while the send is out lands -// after the turn, not before it. -func (b *Bot) sendKept(key string, p chats.Ref, chat feature.Chat, text string, pics []feature.Picture, known map[string]string) { - b.chats.Retag(key, p.ID, botRefs(b.net.Send(chat, text, pics, known))) +// names them by what was sent, so a delete from a linked device finds them, +// and returns Send's timestamps. History is kept first so a message +// arriving while the send is out lands after the turn, not before it. +func (b *Bot) sendKept(key string, p chats.Ref, chat feature.Chat, text string, pics []feature.Picture, known map[string]string) []int64 { + sent := b.net.Send(chat, text, pics, known) + b.chats.Retag(key, p.ID, botRefs(sent)) + return sent } // botRefs names the messages the bot sent, by Send's timestamps. @@ -288,11 +295,43 @@ func (b *Bot) spawn(worker func()) bool { // post adds r to its chat's mailbox. func (b *Bot) post(r Received) { - switch err := b.chats.Post(r.chat().Key(), r); { - case errors.Is(err, chats.ErrNoSlot): - logx.Warnf("dropped a message: all %d worker slots are busy (raise MAX_CONCURRENCY)", b.cfg.MaxConcurrency) - case err != nil: - logx.Warnf("dropped a message: %v", err) + if err := b.chats.Post(r.chat().Key(), r); err != nil { + b.dropped(r, err) + } +} + +// errMadeRoom drops the bot's waiting reactions to make room in their +// chat's mailbox. +var errMadeRoom = errors.New("made room in its chat for a message") + +// dropped logs that r was dropped for err, saying what it was, and tells a +// post's feature. +func (b *Bot) dropped(r Received, err error) { + what := "a message" + switch r := r.(type) { + case Outgoing: + what = "a post" + r.Post.Done(nil, true) + case Reacted: + what = "a reaction" + if n := len(r.Reactions); n > 1 { + what = fmt.Sprintf("%d reactions", n) + } + } + if errors.Is(err, chats.ErrNoSlot) { + logx.Warnf("dropped %s: all %d worker slots are busy (raise MAX_CONCURRENCY)", what, b.cfg.MaxConcurrency) + } else { + logx.Warnf("dropped %s: %v", what, err) + } +} + +// abandon tells the posts among rs, left waiting when shutdown began, that +// they were dropped. +func abandon(rs []Received) { + for _, r := range rs { + if o, ok := r.(Outgoing); ok { + o.Post.Done(nil, true) + } } } @@ -300,9 +339,10 @@ func (b *Bot) post(r Received) { // messages are answered together, as one turn, so "actually" and "forget // it" get one reply that sees both; each run stays within one message's // picture limits. On its own goes a message a hook acts on (a command or -// an answer), a delivered one, and one that waited for the bot's -// ID and was not addressed after all. A panic loses only the message or -// turn that caused it, and nothing new starts once shutdown begins. +// an answer), a delivered one, a post, the bot's reactions, and one that +// waited for the bot's ID and was not addressed after all. A panic loses +// only the message or turn that caused it, and nothing new starts once +// shutdown begins; a post left waiting then is told it was dropped. func (b *Bot) work(rs []Received) { var batch []feature.Message flush := func() { @@ -320,8 +360,9 @@ func (b *Bot) work(rs []Received) { fn() } } - for _, r := range rs { + for i, r := range rs { if b.closing.Load() { + abandon(rs[i:]) return } safely(func() { @@ -333,8 +374,12 @@ func (b *Bot) work(rs []Received) { case Posted: alone(func() { b.delivered(r.Message) }) return - case Told: - alone(func() { b.told(r) }) + case Outgoing: + alone(func() { b.say(r.Post) }) + r.Post.Done(nil, true) // if shutdown began first + return + case Reacted: + alone(func() { b.react(r) }) return case Incoming: p = r @@ -347,7 +392,7 @@ func (b *Bot) work(rs []Received) { case !msg.Addressed: alone(func() { b.overhear(msg) }) default: - if act := b.onMessage(b.ctx, msg); act != (feature.Action{}) { + if act := b.onMessage(b.ctx, msg); !act.IsZero() { alone(func() { b.respond(msg, act, prompt(msg), refs(msg)) }) return } @@ -478,7 +523,7 @@ func (b *Bot) load(r Incoming) (feature.Message, bool) { // non-zero, counting only what applies to the message, wins. func (b *Bot) onMessage(ctx context.Context, msg feature.Message) feature.Action { for _, fn := range b.messages { - if a := fn(ctx, msg).For(msg); a != (feature.Action{}) { + if a := fn(ctx, msg).For(msg); !a.IsZero() { return a } } diff --git a/internal/bot/fakes_test.go b/internal/bot/fakes_test.go index a5142be..823718d 100644 --- a/internal/bot/fakes_test.go +++ b/internal/bot/fakes_test.go @@ -113,6 +113,14 @@ func (n *fakeNet) Delivered(ctx context.Context, msg feature.Message) (Ready, bo return r, true } +// Reachable is the group, and the DMs of Alice and Bob. +func (n *fakeNet) Reachable(_ context.Context, chat feature.Chat) bool { + if chat.GroupID != "" { + return chat.GroupID == groupID + } + return chat.User == aliceID || chat.User == bobID +} + func (n *fakeNet) BotName() string { return "Botty" } // Prompt is Signal's, so the golden prompt holds with no features. diff --git a/internal/bot/host.go b/internal/bot/host.go index 08f9d35..2dfc0e2 100644 --- a/internal/bot/host.go +++ b/internal/bot/host.go @@ -8,12 +8,15 @@ import ( "fmt" "slices" "strings" + "sync" "time" "github.com/robdevops/signalbot/internal/chats" "github.com/robdevops/signalbot/internal/config" "github.com/robdevops/signalbot/internal/feature" + "github.com/robdevops/signalbot/internal/kit/logx" "github.com/robdevops/signalbot/internal/kit/state" + "github.com/robdevops/signalbot/internal/kit/txt" ) // The ports. Features call them while they register, before Run. @@ -128,19 +131,91 @@ func (b *Bot) Deliver(msg feature.Message) { } } -// Tell sends text to user, in their DM's mailbox. -func (b *Bot) Tell(user, text string) { - if !b.closing.Load() && user != "" && text != "" { - b.post(Told{User: user, Text: text}) +// Post sends p from the bot, in its chat's mailbox. Its Done is called +// once, whatever happens to it. +func (b *Bot) Post(p feature.Post) { + p.Done = once(p.Done) + switch { + case b.closing.Load(), p.Text == "" && len(p.Pictures) == 0: + p.Done(nil, true) + default: + b.post(Outgoing{Post: p}) } } -// told sends a Told in its chat's slot, if its user may still DM the bot, -// which the network checks as it does for a delivered DM. -func (b *Bot) told(t Told) { - chat := feature.Chat{User: t.User} - if _, ok := b.net.Delivered(b.ctx, feature.Message{Chat: chat, Sender: t.User}); ok { - b.net.Send(chat, t.Text, nil, nil) +// once is done made safe to call more than once, the calls after the first +// doing nothing; nil does nothing. +func once(done func(sent []int64, dropped bool)) func(sent []int64, dropped bool) { + var o sync.Once + return func(sent []int64, dropped bool) { + o.Do(func() { + if done != nil { + done(sent, dropped) + } + }) + } +} + +// say sends a post in its chat's slot, if the bot may still post there, +// with @Name linked to the chat's known names. With a label, history keeps +// it as the bot's own entry, "[Label] text", clamped; without one, nothing. +func (b *Bot) say(p feature.Post) { + defer p.Done(nil, true) // if it is never sent + if !b.net.Reachable(b.ctx, p.Chat) { + logx.Infof("dropped a post: the bot can no longer post in its chat") + return + } + key := p.Chat.Key() + text, kept := captioned(p.Text, p.Pictures) + if p.Label == "" || b.ai == nil { // with no model, nothing would read it + p.Done(b.net.Send(p.Chat, text, p.Pictures, b.chats.Names(key)), false) + return + } + ref := b.pending() + b.chats.Add(key, b.now(), 0, chats.Entry{Role: "assistant", Content: txt.Clamp("["+p.Label+"] "+kept, maxPostKept), Refs: []chats.Ref{ref}}) + p.Done(b.sendKept(key, ref, p.Chat, text, p.Pictures, b.chats.Names(key)), false) +} + +// maxPostKept caps what history keeps of a post. +const maxPostKept = 500 + +// React puts emoji on msg, in chat's mailbox at low priority, merged with +// the reactions already waiting there: a later one on the same message +// replaces the earlier, and past maxReactions the oldest is dropped. +func (b *Bot) React(chat feature.Chat, msg feature.Message, emoji string) { + if b.closing.Load() || emoji == "" || msg.Timestamp == 0 { // a message the bot made can't be reacted to + return + } + msg.Chat = chat + r := Reaction{Message: msg, Emoji: emoji} + add := Reacted{Chat: chat, Reactions: []Reaction{r}} + merge := func(waiting Received) Received { + w := waiting.(Reacted) + w.Reactions = slices.DeleteFunc(slices.Clone(w.Reactions), func(x Reaction) bool { + return x.Message.Sender == msg.Sender && x.Message.Timestamp == msg.Timestamp + }) + if len(w.Reactions) >= maxReactions { + logx.Warnf("dropped a reaction: %d already wait in its chat", maxReactions) + w.Reactions = w.Reactions[1:] + } + w.Reactions = append(w.Reactions, r) + return w + } + if err := b.chats.PostLow(chat.Key(), add, merge); err != nil { + b.dropped(add, err) + } +} + +// maxReactions caps the reactions waiting in one chat. +const maxReactions = 16 + +// react puts the waiting reactions on their messages in their chat's slot, +// skipping any message deleted or replaced by an edit since. +func (b *Bot) react(r Reacted) { + for _, x := range r.Reactions { + if !b.gone(x.Message) { + b.net.React(r.Chat, x.Message, x.Emoji) + } } } @@ -184,7 +259,7 @@ func (b *Bot) delivered(msg feature.Message) { b.chats.Learn(key, msg.Name, msg.Sender) } msg.Addressed = true - if act := b.onMessage(b.ctx, msg); act != (feature.Action{}) || r.Mentioned { + if act := b.onMessage(b.ctx, msg); !act.IsZero() || r.Mentioned { b.respond(msg, act, prompt(msg), nil) return } diff --git a/internal/bot/host_test.go b/internal/bot/host_test.go index aed44ff..18f4fd5 100644 --- a/internal/bot/host_test.go +++ b/internal/bot/host_test.go @@ -614,3 +614,254 @@ func TestReceivedKinds(t *testing.T) { h.settle() h.noSend() } + +// A Done Action handles the message: an addressed one gets no answer and +// no model; an unaddressed one is kept nowhere, even with a Context, and +// later hooks never see it. +func TestDone(t *testing.T) { + var later []string + h := start(t, options{features: func(b *Bot) { + b.OnMessage(func(_ context.Context, m feature.Message) feature.Action { + if strings.HasPrefix(m.Text, "claimed") { + return feature.Action{Done: true, Context: "never kept", Answer: "never sent"} + } + return feature.Action{} + }) + b.OnMessage(func(_ context.Context, m feature.Message) feature.Action { + later = append(later, m.Text) + if !m.Addressed { + return feature.Action{Context: m.Name + ": " + m.Text} + } + return feature.Action{} + }) + }}) + h.receive(dm("claimed in a DM")) + h.receive(atBot("claimed in the group")) + h.receive(chatter("claimed chatter")) + h.receive(chatter("kept chatter")) + h.settle() + h.noSend() + if len(h.requests()) != 0 || h.typing() != 0 { + t.Fatalf("the model was asked, or typing shown") + } + h.eventually("the chatter", func() bool { return len(later) == 1 }) + r, _ := h.ask(atBot("what's new?")) + equal(t, "model got", contents(r), []string{"user: [Messages not addressed to you, for context only:]\nBob: kept chatter", "user: Alice: what's new?"}) + equal(t, "later hooks saw", later, []string{"kept chatter", "what's new?"}) +} + +// A command's pictures are sent with its Answer, without the model, by the +// caption rule; OnSent gets the timestamps Send returned. +func TestActionPictures(t *testing.T) { + var sentAt [][]int64 + onSent := func(ts []int64) { sentAt = append(sentAt, ts) } + h := start(t, options{features: func(b *Bot) { + b.Command("plain", func(context.Context, feature.Message, string) feature.Action { + return feature.Action{Answer: "here", Pictures: []feature.Picture{{Data: png}}, OnSent: onSent} + }) + b.Command("captioned", func(context.Context, feature.Message, string) feature.Action { + return feature.Action{Answer: "never sent", Pictures: []feature.Picture{{Data: png, Caption: "a caption"}, {Data: png}}, OnSent: onSent} + }) + b.Command("alone", func(context.Context, feature.Message, string) feature.Action { + return feature.Action{Pictures: []feature.Picture{{Data: png}}} + }) + }}) + h.receive(dm("/plain")) + if s := h.nextSend(); s.text != "here" || len(s.images) != 1 || string(s.images[0].Data) != string(png) { + t.Fatalf("sent %+v", s) + } + h.receive(atBot("/captioned")) + if s := h.nextSend(); s.text != "a caption" || len(s.images) != 2 || s.chat.GroupID != groupID { + t.Fatalf("sent %+v", s) + } + h.receive(dm("/alone")) + if s := h.nextSend(); s.text != "" || len(s.images) != 1 { + t.Fatalf("sent %+v", s) + } + h.settle() + if len(h.requests()) != 0 { + t.Fatal("the model was asked") + } + if fmt.Sprint(sentAt) != "[[5001] [5002]]" { + t.Fatalf("OnSent got %v", sentAt) + } +} + +// strangerID can't be reached: the fake network allows only Alice's and +// Bob's DMs. +const strangerID = "33333333-3333-4333-8333-333333333333" + +// A post goes to a group or a DM, with @Name linked to the chat's known +// names, unless the network says the bot can no longer post there. History +// keeps a labelled one as the bot's own, clamped, and nothing of one with +// no label. Done is called once: when it is sent, or dropped. +func TestPost(t *testing.T) { + h := start(t, options{}) + type done struct { + sent []int64 + dropped bool + } + dones := make(chan done, 16) + post := func(p feature.Post) { + p.Done = func(sent []int64, dropped bool) { dones <- done{sent, dropped} } + h.b.Post(p) + } + next := func() done { + t.Helper() + select { + case d := <-dones: + return d + case <-time.After(5 * time.Second): + t.Fatal("Done never called") + return done{} + } + } + group := feature.Chat{GroupID: groupID} + h.ask(atBot("hello")) // learns Alice's name + + post(feature.Post{Chat: group, Label: "Label", Text: "well done @Alice"}) + if s := h.nextSend(); s.text != "well done @Alice" || s.chat != group || s.known["alice"] != aliceID { + t.Fatalf("sent %+v", s) + } + if d := next(); d.dropped || fmt.Sprint(d.sent) != "[5002]" { + t.Fatalf("done %+v", d) + } + post(feature.Post{Chat: group, Label: "Label", Text: "never sent", Pictures: []feature.Picture{{Data: png, Caption: "a caption", HistoryNote: "[a picture]"}}}) + if s := h.nextSend(); s.text != "a caption" || len(s.images) != 1 { + t.Fatalf("sent %+v", s) + } + next() + post(feature.Post{Chat: group, Label: "Label", Text: strings.Repeat("x", 600)}) + h.nextSend() + next() + r, _ := h.ask(atBot("and?")) + equal(t, "history", contents(r)[2:5], []string{"assistant: [Label] well done @Alice", "assistant: [Label] [a picture]\n", "assistant: [Label] " + strings.Repeat("x", 500-len("[Label] ")) + "…"}) + + // In a DM, with no label, as a timer tells a user something: nothing + // is kept. + post(feature.Post{Chat: feature.Chat{User: aliceID}, Text: "your reminder didn't post"}) + if s := h.nextSend(); s.text != "your reminder didn't post" || s.chat.User != aliceID { + t.Fatalf("sent %+v", s) + } + next() + r, _ = h.ask(dm("anything else?")) + equal(t, "DM history", contents(r), []string{"user: anything else?"}) + + for _, chat := range []feature.Chat{{User: strangerID}, {GroupID: "other"}} { + post(feature.Post{Chat: chat, Label: "Label", Text: "never sent"}) + if d := next(); !d.dropped || d.sent != nil { + t.Fatalf("done %+v", d) + } + } + post(feature.Post{Chat: group}) // nothing to send + if d := next(); !d.dropped { + t.Fatalf("done %+v", d) + } + h.settle() + h.noSend() + if len(dones) != 0 { + t.Fatalf("Done called again: %+v", <-dones) + } + if n := strings.Count(h.logs.String(), "<6>dropped a post: the bot can no longer post in its chat\n"); n != 2 { + t.Fatalf("%d drops logged:\n%s", n, h.logs) + } + if strings.Contains(h.logs.String(), "never sent") { + t.Fatalf("text logged:\n%s", h.logs) + } +} + +// A post that doesn't fit in its chat's mailbox is dropped, with a warning +// of its own, and Done says so. +func TestPostDropped(t *testing.T) { + h := start(t, options{}) + h.holdModel() + h.receive(dm("first")) + h.eventually("the first request", func() bool { return len(h.requests()) == 1 }) + for _, s := range []string{"b", "c", "d", "e"} { + h.receive(dm(s)) + } + dropped := make(chan bool, 1) + h.b.Post(feature.Post{Chat: feature.Chat{User: aliceID}, Text: "never sent", Done: func(_ []int64, d bool) { dropped <- d }}) + if !<-dropped { + t.Fatal("Done said it was sent") + } + if !strings.Contains(h.logs.String(), "<4>dropped a post: 4 messages are already waiting in this chat\n") { + t.Fatalf("logs:\n%s", h.logs) + } + h.release() + for range 2 { + if s := h.nextSend(); s.text != "ok" { + t.Fatalf("sent %+v", s) + } + } + h.settle() + h.noSend() +} + +// The bot's reactions wait at low priority: merged into one item, a later +// one on the same message replacing the earlier, sent after what waited +// with them, dropped first to make room, and skipped for a message deleted +// since. +func TestReact(t *testing.T) { + h := start(t, options{}) + group := feature.Chat{GroupID: groupID} + msg := func(ts int64) feature.Message { + return feature.Message{Chat: group, Sender: aliceID, Timestamp: ts} + } + h.b.React(group, msg(1), "👍") + if s := h.nextSend(); s.text != "react 👍 to "+aliceID+"@1" { + t.Fatalf("sent %+v", s) + } + + h.holdModel() + h.receive(atBot("zero")) // holds the chat's worker, so the rest wait + h.eventually("the first request", func() bool { return len(h.requests()) == 1 }) + h.b.React(group, msg(2), "👍") + h.b.React(group, msg(3), "📍") + h.b.React(group, msg(2), "🎉") + h.receive(atBot("one")) + h.release() + for _, want := range []string{"ok", "ok", "react 📍 to " + aliceID + "@3", "react 🎉 to " + aliceID + "@2"} { + if s := h.nextSend(); s.text != want { + t.Fatalf("sent %q, want %q", s.text, want) + } + } + h.settle() + + // Four messages fill the mailbox, so the reactions waiting there go. + h.holdModel() + h.receive(atBot("zero again")) + h.eventually("the request", func() bool { return len(h.requests()) == 3 }) + h.b.React(group, msg(4), "👍") + h.b.React(group, msg(5), "👍") + for _, s := range []string{"a", "b", "c", "d"} { + h.receive(atBot(s)) + } + if !strings.Contains(h.logs.String(), "<4>dropped 2 reactions: made room in its chat for a message\n") { + t.Fatalf("logs:\n%s", h.logs) + } + h.release() + for range 2 { + if s := h.nextSend(); s.text != "ok" { + t.Fatalf("sent %+v", s) + } + } + h.settle() + h.noSend() + + // A reaction to a message deleted while it waited is skipped. + h.holdModel() + h.receive(atBot("zero once more")) + h.eventually("the request", func() bool { return len(h.requests()) == 5 }) + h.b.React(group, msg(6), "👍") + h.net.handle(Deleted{Chat: group, Sender: aliceID, Sent: 6, At: 7}) + h.release() + if s := h.nextSend(); s.text != "ok" { + t.Fatalf("sent %+v", s) + } + h.settle() + h.noSend() + if strings.Contains(h.logs.String(), "dropped a message") { + t.Fatalf("logs:\n%s", h.logs) + } +} diff --git a/internal/bot/received.go b/internal/bot/received.go index 4da4625..8093c97 100644 --- a/internal/bot/received.go +++ b/internal/bot/received.go @@ -44,12 +44,26 @@ type Happened struct{ Event feature.Event } // in its chat's mailbox for the network to ready it. type Posted struct{ Message feature.Message } -// Told is a text the bot sends a user in their DM (Tell), waiting in that -// chat's mailbox. -type Told struct{ User, Text string } +// Outgoing is a post the bot makes on its own (Post), waiting in its chat's +// mailbox. +type Outgoing struct{ Post feature.Post } + +// Reacted is the bot's reactions (React) waiting in a chat's mailbox at low +// priority, merged into one item, oldest first. +type Reacted struct { + Chat feature.Chat + Reactions []Reaction +} + +// Reaction is an emoji the bot puts on a message. +type Reaction struct { + Message feature.Message + Emoji string +} func (r Incoming) chat() feature.Chat { return r.Chat } -func (r Told) chat() feature.Chat { return feature.Chat{User: r.User} } +func (r Outgoing) chat() feature.Chat { return r.Post.Chat } +func (r Reacted) chat() feature.Chat { return r.Chat } func (r Chatter) chat() feature.Chat { return r.Message.Chat } func (r GroupChanged) chat() feature.Chat { return r.Chat } func (r Deleted) chat() feature.Chat { return r.Chat } diff --git a/internal/chats/chats.go b/internal/chats/chats.go index 7a0e083..693b50e 100644 --- a/internal/chats/chats.go +++ b/internal/chats/chats.go @@ -61,6 +61,7 @@ type Store[M any] struct { handle func([]M) // a chat's worker hands it what waits spawn func(worker func()) bool // starts a chat's worker on a free slot now func() time.Time // the clock entries expire by + evicted func(M) // told of a low-priority item dropped to make room; nil if none is } type chat[M any] struct { @@ -71,6 +72,7 @@ type chat[M any] struct { followUps map[int]int // tool group -> replies left gone map[string]int64 // message ID -> versions before this are deleted or replaced queue []M // waiting for the worker + low []M // waiting at low priority, after queue: none or one, which merges the rest busy bool // a worker is running } @@ -101,6 +103,11 @@ func New[M any](messages int, handle func([]M), spawn func(worker func()) bool) // the real one, for tests that can't wait. Call it before the store is used. func (s *Store[M]) SetClock(now func() time.Time) { s.now = now } +// SetEvicted has fn told of each low-priority item dropped to make room +// (see PostLow), without the store's lock held. Call it before the store is +// used. +func (s *Store[M]) SetEvicted(fn func(M)) { s.evicted = fn } + // get returns the chat, creating it if create is set. When the map is full, // an idle chat is dropped to make room; with none idle it returns nil. // Caller holds s.mu. @@ -181,8 +188,17 @@ func (s *Store[M]) tidy(key string, c *chat[M]) { } // Post adds m to the chat's mailbox, starting the chat's worker if it has -// none. It returns ErrNoSlot when no slot is free for the worker. +// none. A low-priority item waiting there is dropped to make room (see +// PostLow). It returns ErrNoSlot when no slot is free for the worker. func (s *Store[M]) Post(key string, m M) error { + var evicted []M + defer func() { + for _, e := range evicted { + if s.evicted != nil { + s.evicted(e) + } + } + }() s.mu.Lock() defer s.mu.Unlock() c := s.get(key, true) @@ -192,9 +208,40 @@ func (s *Store[M]) Post(key string, m M) error { case c.busy && len(c.queue) >= maxQueue: return errQueueFull case c.busy: + if len(c.queue)+len(c.low) >= maxQueue { + evicted, c.low = c.low, nil + } c.queue = append(c.queue, m) return nil } + return s.start(key, c, m) +} + +// PostLow adds m to the chat's mailbox at low priority: it waits after +// everything else, and is the first dropped, by Post, to make room, so it +// never takes the place of a message. A low-priority item already waiting +// is replaced by merge(waiting), so at most one waits. +func (s *Store[M]) PostLow(key string, m M, merge func(waiting M) M) error { + s.mu.Lock() + defer s.mu.Unlock() + c := s.get(key, true) + switch { + case c == nil: + return errFull + case c.busy && len(c.low) > 0: + c.low[0] = merge(c.low[0]) + return nil + case c.busy && len(c.queue) >= maxQueue: + return errQueueFull + case c.busy: + c.low = []M{m} + return nil + } + return s.start(key, c, m) +} + +// start starts the idle chat's worker with m. Caller holds s.mu. +func (s *Store[M]) start(key string, c *chat[M], m M) error { c.busy = true if !s.spawn(func() { s.work(key, c, []M{m}) }) { c.busy = false @@ -208,7 +255,7 @@ func (s *Store[M]) work(key string, c *chat[M], ms []M) { for len(ms) > 0 { s.handle(ms) s.mu.Lock() - ms, c.queue = c.queue, nil + ms, c.queue, c.low = append(c.queue, c.low...), nil, nil if len(ms) == 0 { c.busy = false s.tidy(key, c) diff --git a/internal/chats/chats_test.go b/internal/chats/chats_test.go index c60efc0..e2c17fc 100644 --- a/internal/chats/chats_test.go +++ b/internal/chats/chats_test.go @@ -65,6 +65,58 @@ func TestMailboxInOrder(t *testing.T) { } } +// Low-priority items merge into one, wait after everything else, take no +// message's place, and are dropped first to make room. +func TestLowPriority(t *testing.T) { + release := make(chan struct{}) + var got []string + pool := newSlots(8) + s := New(10, func(rs []string) { + if rs[0] == "0" { + <-release + } + got = append(got, fmt.Sprint(rs)) + }, pool.spawn) + var evicted []string + s.SetEvicted(func(m string) { evicted = append(evicted, m) }) + merge := func(m string) func(string) string { return func(w string) string { return w + "+" + m } } + s.Post("g:1", "0") + for _, m := range []string{"a", "b", "c"} { + if err := s.PostLow("g:1", m, merge(m)); err != nil { + t.Fatal(err) + } + } + for i := 1; i <= 3; i++ { + s.Post("g:1", fmt.Sprint(i)) + } + if len(evicted) != 0 { + t.Fatalf("evicted %v with room left", evicted) + } + s.Post("g:1", "4") // a full mailbox: the merged item goes + if fmt.Sprint(evicted) != "[a+b+c]" { + t.Fatalf("evicted %v", evicted) + } + if err := s.PostLow("g:1", "d", merge("d")); err != errQueueFull { + t.Errorf("a low-priority item took a message's place: err %v", err) + } + close(release) + pool.wg.Wait() + if fmt.Sprint(got) != "[[0] [1 2 3 4]]" { + t.Errorf("handled %v", got) + } + + release = make(chan struct{}) + got = nil + s.Post("g:1", "0") + s.PostLow("g:1", "a", merge("a")) + s.Post("g:1", "1") + close(release) + pool.wg.Wait() + if fmt.Sprint(got) != "[[0] [1 a]]" { + t.Errorf("handled %v", got) + } +} + // Different chats run in parallel, each on its own slot, and a full pool // drops new work. func TestChatsInParallel(t *testing.T) { diff --git a/internal/feature/command_test.go b/internal/feature/command_test.go index 06a929f..a4e15f5 100644 --- a/internal/feature/command_test.go +++ b/internal/feature/command_test.go @@ -39,10 +39,10 @@ func TestCommand(t *testing.T) { if a := h.Message(ctx, feature.Message{Text: "/PING now", Addressed: true}); a.Answer != "pong now" { t.Errorf("got %+v", a) } - if a := h.Message(ctx, feature.Message{Text: "/ping"}); a != (feature.Action{}) { + if a := h.Message(ctx, feature.Message{Text: "/ping"}); !a.IsZero() { t.Errorf("an unaddressed message ran the command: %+v", a) } - if a := h.Message(ctx, feature.Message{Text: "/pinger", Addressed: true}); a != (feature.Action{}) { + if a := h.Message(ctx, feature.Message{Text: "/pinger", Addressed: true}); !a.IsZero() { t.Errorf("another name ran the command: %+v", a) } } diff --git a/internal/feature/feature.go b/internal/feature/feature.go index 17df3c7..597e6e9 100644 --- a/internal/feature/feature.go +++ b/internal/feature/feature.go @@ -104,18 +104,27 @@ type File struct { // Action is what an OnMessage hook decides. The zero value carries on. type Action struct { - Answer string // reply with this text, without the model (addressed messages only) - ToolChoice string // make the model call this tool before answering (addressed messages only) - Context string // keep this text in the chat's history (unaddressed messages only) + Answer string // reply with this text, without the model (addressed messages only) + Pictures []Picture // send these with Answer, or alone, without the model; captions as for a tool's pictures (addressed messages only) + OnSent func(sent []int64) // called with the timestamps of the messages Answer and Pictures went out in (addressed messages only) + ToolChoice string // make the model call this tool before answering (addressed messages only) + Context string // keep this text in the chat's history (unaddressed messages only) + Done bool // the hook handled the message: no answer, no model, and for an unaddressed one nothing kept and no later hook +} + +// IsZero reports whether a carries on: no field is set. +func (a Action) IsZero() bool { + return a.Answer == "" && len(a.Pictures) == 0 && a.OnSent == nil && a.ToolChoice == "" && a.Context == "" && !a.Done } // For returns a copy of the action keeping only the fields that apply to -// m: Answer and ToolChoice if m is addressed, Context if not. +// m: Answer, Pictures, OnSent and ToolChoice if m is addressed, Context if +// not, and Done either way. func (a Action) For(m Message) Action { if m.Addressed { a.Context = "" } else { - a.Answer, a.ToolChoice = "", "" + a.Answer, a.Pictures, a.OnSent, a.ToolChoice = "", nil, nil, "" } return a } @@ -188,6 +197,15 @@ type Store interface { Save(v any) error } +// Post is what the bot posts on its own, from a timer or a worker. +type Post struct { + Chat Chat + Label string // history keeps the post as the bot's, as "[Label] text"; "" keeps nothing + Text string // Markdown, as written; @Name is linked to the chat's known names + Pictures []Picture // sent with Text; captions as for a tool's pictures + Done func(sent []int64, dropped bool) // if set, called once: with the timestamps sent, or dropped +} + // Group is a group chat. type Group struct { ID, Name string @@ -197,7 +215,8 @@ type Group struct { type Host interface { // OnMessage sees every message. For an unaddressed one it runs on the // reader goroutine, so it must not block or call the network. The first - // non-zero Action wins. + // Action that isn't zero, counting only what applies to the message, + // wins. OnMessage(func(context.Context, Message) Action) // OnTurn adds to the model's request for the addressed message being // answered. @@ -243,9 +262,14 @@ type Host interface { Media(ctx context.Context, msg Message, i int) ([]byte, error) // Deliver acts on msg as if its sender had just posted it in its chat. Deliver(msg Message) - // Tell sends text from the bot to user in their DM, as written, never - // through the model, if they may still DM the bot. - Tell(user, text string) + // Post sends a post from the bot to its chat, as written, never through + // the model, through the chat's mailbox, if the bot may still post + // there. + Post(p Post) + // React puts emoji on msg in chat, as a reaction from the bot, through + // the chat's mailbox at low priority: unless msg was deleted or edited + // since, and unless the reaction is dropped to make room. + React(chat Chat, msg Message, emoji string) // Groups lists the groups the bot shares with user. Groups(ctx context.Context, user string) ([]Group, error) // CallAPI posts body as JSON to path (such as "/images") at the model's diff --git a/internal/feature/feature_test.go b/internal/feature/feature_test.go new file mode 100644 index 0000000..951b101 --- /dev/null +++ b/internal/feature/feature_test.go @@ -0,0 +1,40 @@ +package feature_test + +import ( + "testing" + + "github.com/robdevops/signalbot/internal/feature" +) + +// The zero Action carries on; any one field set makes it act. +func TestActionIsZero(t *testing.T) { + if !(feature.Action{}).IsZero() { + t.Error("the zero Action isn't zero") + } + for name, a := range map[string]feature.Action{ + "Answer": {Answer: "a"}, + "Pictures": {Pictures: []feature.Picture{{}}}, + "OnSent": {OnSent: func([]int64) {}}, + "ToolChoice": {ToolChoice: "t"}, + "Context": {Context: "c"}, + "Done": {Done: true}, + } { + if a.IsZero() { + t.Errorf("an Action with only %s set is zero", name) + } + } +} + +// For keeps what applies to the message, and Done on both. +func TestActionFor(t *testing.T) { + a := feature.Action{Answer: "a", Pictures: []feature.Picture{{}}, OnSent: func([]int64) {}, ToolChoice: "t", Context: "c", Done: true} + if got := a.For(feature.Message{Addressed: true}); got.Answer != "a" || len(got.Pictures) != 1 || got.OnSent == nil || got.ToolChoice != "t" || got.Context != "" || !got.Done { + t.Errorf("addressed: %+v", got) + } + if got := a.For(feature.Message{}); got.Answer != "" || got.Pictures != nil || got.OnSent != nil || got.ToolChoice != "" || got.Context != "c" || !got.Done { + t.Errorf("unaddressed: %+v", got) + } + if got := (feature.Action{Answer: "a"}).For(feature.Message{}); !got.IsZero() { + t.Errorf("an Answer counted on an unaddressed message: %+v", got) + } +} diff --git a/internal/feature/featuretest/featuretest.go b/internal/feature/featuretest/featuretest.go index 63116b8..9348d38 100644 --- a/internal/feature/featuretest/featuretest.go +++ b/internal/feature/featuretest/featuretest.go @@ -37,7 +37,8 @@ type Host struct { more []string timers []*Timer delivered []feature.Message - told []Told + posts []feature.Post + reactions []Reaction stores []string commands feature.Commands life context.Context // what Go passes; ended by Stop @@ -200,20 +201,38 @@ func (h *Host) Deliver(m feature.Message) { h.delivered = append(h.delivered, m) } -func (h *Host) Tell(user, text string) { +// Post records p; Posts returns what was posted. Done is never called. +func (h *Host) Post(p feature.Post) { h.mu.Lock() defer h.mu.Unlock() - h.told = append(h.told, Told{user, text}) + h.posts = append(h.posts, p) } -// Told is a text passed to Tell. -type Told struct{ User, Text string } +// Posts is the posts passed to Post, in order. +func (h *Host) Posts() []feature.Post { + h.mu.Lock() + defer h.mu.Unlock() + return slices.Clone(h.posts) +} + +// Reaction is a reaction passed to React. +type Reaction struct { + Chat feature.Chat + Message feature.Message + Emoji string +} + +func (h *Host) React(chat feature.Chat, msg feature.Message, emoji string) { + h.mu.Lock() + defer h.mu.Unlock() + h.reactions = append(h.reactions, Reaction{chat, msg, emoji}) +} -// TellsSent is the texts passed to Tell, in order. -func (h *Host) TellsSent() []Told { +// Reactions is the reactions passed to React, in order. +func (h *Host) Reactions() []Reaction { h.mu.Lock() defer h.mu.Unlock() - return slices.Clone(h.told) + return slices.Clone(h.reactions) } func (h *Host) Groups(context.Context, string) ([]feature.Group, error) { return h.Shared, nil } @@ -256,7 +275,7 @@ func (h *Host) Message(ctx context.Context, m feature.Message) feature.Action { hooks := slices.Clone(h.messages) h.mu.Unlock() for _, fn := range hooks { - if a := fn(ctx, m).For(m); a != (feature.Action{}) { + if a := fn(ctx, m).For(m); !a.IsZero() { return a } } diff --git a/internal/feature/featuretest/featuretest_test.go b/internal/feature/featuretest/featuretest_test.go index 597d06d..5353c7d 100644 --- a/internal/feature/featuretest/featuretest_test.go +++ b/internal/feature/featuretest/featuretest_test.go @@ -31,10 +31,10 @@ func TestActionsCountAsInTheCore(t *testing.T) { return feature.Action{Context: "ctx", Answer: "early"} }) h.OnMessage(func(context.Context, feature.Message) feature.Action { return feature.Action{Answer: "late"} }) - if a := h.Message(context.Background(), feature.Message{Addressed: true}); a != (feature.Action{Answer: "early"}) { + if a := h.Message(context.Background(), feature.Message{Addressed: true}); a.Answer != "early" || a.Context != "" { t.Errorf("addressed: got %+v", a) } - if a := h.Message(context.Background(), feature.Message{}); a != (feature.Action{Context: "ctx"}) { + if a := h.Message(context.Background(), feature.Message{}); a.Context != "ctx" || a.Answer != "" { t.Errorf("unaddressed: got %+v", a) } h = New() @@ -45,6 +45,20 @@ func TestActionsCountAsInTheCore(t *testing.T) { } } +// Post and React are recorded in order. +func TestPostsAndReactions(t *testing.T) { + h := New() + alice := feature.Chat{User: "alice"} + h.Post(feature.Post{Chat: alice, Label: "Label", Text: "hello"}) + h.React(alice, feature.Message{Chat: alice, Sender: "alice", Timestamp: 1}, "👍") + if p := h.Posts(); len(p) != 1 || p[0].Chat != alice || p[0].Text != "hello" || p[0].Label != "Label" { + t.Errorf("posts %+v", p) + } + if r := h.Reactions(); len(r) != 1 || r[0].Chat != alice || r[0].Message.Timestamp != 1 || r[0].Emoji != "👍" { + t.Errorf("reactions %+v", r) + } +} + func TestTimers(t *testing.T) { h := New() now := time.Now() diff --git a/internal/features/groupctx/groupctx_test.go b/internal/features/groupctx/groupctx_test.go index 843086f..80d03f2 100644 --- a/internal/features/groupctx/groupctx_test.go +++ b/internal/features/groupctx/groupctx_test.go @@ -28,7 +28,7 @@ func chatterFrom(name, text string, media ...feature.Media) feature.Message { func TestGroupChatterIsContext(t *testing.T) { h := host(t, "") // on by default ctx := context.Background() - if a := h.Message(ctx, chatterFrom("Alice", "the moon is made of cheese")); a != (feature.Action{Context: "Alice: the moon is made of cheese"}) { + if a := h.Message(ctx, chatterFrom("Alice", "the moon is made of cheese")); a.Context != "Alice: the moon is made of cheese" || a.Answer != "" || a.Done { t.Fatalf("got %+v", a) } if a := h.Message(ctx, chatterFrom("", "hello")); a.Context != "someone: hello" { @@ -75,7 +75,7 @@ func TestAddressedIsNotContext(t *testing.T) { h := host(t, "") addressed := chatterFrom("Alice", "what do you think?") addressed.Addressed = true - if a := h.Message(context.Background(), addressed); a != (feature.Action{}) { + if a := h.Message(context.Background(), addressed); !a.IsZero() { t.Errorf("got %+v", a) } } @@ -84,7 +84,7 @@ func TestAddressedIsNotContext(t *testing.T) { func TestGroupContextOff(t *testing.T) { for _, v := range []string{"false", "off", "0"} { h := host(t, v) - if a := h.Message(context.Background(), chatterFrom("Alice", "hello")); a != (feature.Action{}) { + if a := h.Message(context.Background(), chatterFrom("Alice", "hello")); !a.IsZero() { t.Errorf("GROUP_CONTEXT=%s: got %+v", v, a) } } diff --git a/internal/features/intro/intro_test.go b/internal/features/intro/intro_test.go index 88a4e8b..d46a821 100644 --- a/internal/features/intro/intro_test.go +++ b/internal/features/intro/intro_test.go @@ -21,7 +21,7 @@ func TestIntro(t *testing.T) { for _, text := range []string{"/intro", "/INTRO", "/help", "/Help"} { for chat, want := range map[feature.Chat]string{dm: "hi, I'm Botty. DM me.", group: "hi, I'm Botty (tools: **charts**)."} { m := feature.Message{Chat: chat, Sender: "u-alice", Name: "Alice", Text: text, Addressed: true} - if a := h.Message(context.Background(), m); a != (feature.Action{Answer: want + "\n\nThis message did not use the model."}) { + if a := h.Message(context.Background(), m); a.Answer != want+"\n\nThis message did not use the model." || a.ToolChoice != "" || len(a.Pictures) != 0 || a.Done { t.Fatalf("%s in %+v: got %+v", text, chat, a) } } @@ -33,7 +33,7 @@ func TestIntro(t *testing.T) { } for _, text := range []string{"/intro yourself", "/help me"} { m := feature.Message{Chat: dm, Sender: "u-alice", Text: text, Addressed: true} - if a := h.Message(context.Background(), m); a != (feature.Action{}) { + if a := h.Message(context.Background(), m); !a.IsZero() { t.Fatalf("%s got %+v", text, a) } } diff --git a/internal/features/mcp/addon.go b/internal/features/mcp/addon.go new file mode 100644 index 0000000..62a1d52 --- /dev/null +++ b/internal/features/mcp/addon.go @@ -0,0 +1,356 @@ +package mcp + +import ( + "cmp" + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "encoding/base32" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "os" + "regexp" + "slices" + "strings" + "sync" + "time" + + "github.com/robdevops/signalbot/internal/feature" + "github.com/robdevops/signalbot/internal/kit/txt" +) + +// vendor prefixes the keys of signalbot's MCP extension: the capability, +// tool visibility and the context of the bot's own calls. +const vendor = "io.github.robdevops.signalbot/" + +// addonVersion is the version of the extension the bot speaks. +const addonVersion = 1 + +// addonConfig is a server's "addon" block: what an addon may do, and where. +type addonConfig struct { + Chats []string `json:"chats"` // group IDs, or "all" + DMs bool `json:"dms"` + Post bool `json:"post"` + React bool `json:"react"` + Watch bool `json:"watch"` + WatchMax string `json:"watch_max"` // how long a watch may last: 1h by default, 24h at most + Names bool `json:"names"` // the context carries the sender's display name + GlobalIDs bool `json:"global_ids"` + Rate rateConfig `json:"rate"` + + watchMax time.Duration // WatchMax, read +} + +// rateConfig caps an addon's posts and reactions in each chat. +type rateConfig struct { + PerMinute int `json:"per_minute"` + Burst int `json:"burst"` +} + +// addonSettings are the keys an addon block may have, and rateSettings its +// rate's. +var ( + addonSettings = []string{"chats", "dms", "post", "react", "watch", "watch_max", "names", "global_ids", "rate"} + rateSettings = []string{"per_minute", "burst"} +) + +// coreSettings are signalbot's own settings, docs/CONFIGURATION.md's table +// (a test keeps them in step): an addon is given the variables that start +// with its prefix, so no prefix may start one of these. +var coreSettings = []string{ + "SIGNALCLI_SOCKET", "SIGNAL_DM_USER_IDS", "TELEGRAM_BOT_TOKEN", "TELEGRAM_DM_USER_IDS", "TELEGRAM_API_URL", + "MODEL", "MODEL_API_KEY", "MODEL_API_URL", "MODEL_REASONING", "MODEL_SEARCH", "MODEL_SYSTEM_PROMPT", + "CHARTS", "IMAGE_MODEL", "IMAGE_QUALITY", "DAILY_BUDGET", "DARKMODE", "FILES", "GROUP_CONTEXT", "HISTORY_MAX", + "INTRO", "MAX_CONCURRENCY", "MCP_CONFIG", "STATE_DIRECTORY", "TOOL_LINGER_ROUNDS", "TZ", +} + +// envPrefix is what an addon server's settings start with: its name in +// capitals, anything but letters and digits as _, then _. +func envPrefix(server string) string { + return strings.Map(func(r rune) rune { + switch { + case r >= 'a' && r <= 'z': + return r - 'a' + 'A' + case r >= 'A' && r <= 'Z', r >= '0' && r <= '9': + return r + } + return '_' + }, server) + "_" +} + +// telegramGroup is a Telegram group's ID, as the bot names it. +var telegramGroup = regexp.MustCompile(`^-[0-9]{1,20}$`) + +// isGroupID reports whether id is a group's ID: Signal's, 32 bytes in +// base64, or Telegram's, a negative number. +func isGroupID(id string) bool { + b, err := base64.StdEncoding.DecodeString(id) + return err == nil && len(b) == 32 || telegramGroup.MatchString(id) +} + +// check checks an addon block, whose raw keys are entry, and fills in its +// defaults. +func (a *addonConfig) check(entry map[string]json.RawMessage) error { + if err := unknown(entry, addonSettings); err != nil { + return fmt.Errorf("addon: %v", err) + } + var rate map[string]json.RawMessage + json.Unmarshal(entry["rate"], &rate) + if err := unknown(rate, rateSettings); err != nil { + return fmt.Errorf("addon rate: %v", err) + } + for _, c := range a.Chats { + switch { + case c == "all" && len(a.Chats) > 1: + return errors.New(`addon chats: "all" goes alone`) + case c != "all" && !isGroupID(c): + return fmt.Errorf(`addon chats: %q isn't a group ID; copy the group's ID as Signal or Telegram shows it, or use "all"`, txt.Clamp(c, 60)) + } + } + a.watchMax = time.Hour + if a.WatchMax != "" { + d, err := time.ParseDuration(a.WatchMax) + if err != nil || d <= 0 || d > 24*time.Hour { + return fmt.Errorf("addon watch_max: %q isn't a time from 1s to 24h, such as 1h or 30m", txt.Clamp(a.WatchMax, 40)) + } + a.watchMax = d + } + if a.Rate.PerMinute < 0 || a.Rate.Burst < 0 { + return errors.New("addon rate: per_minute and burst can't be below 0") + } + a.Rate.PerMinute, a.Rate.Burst = cmp.Or(a.Rate.PerMinute, 20), cmp.Or(a.Rate.Burst, 5) + return nil +} + +// checkAddonServer checks what an addon server may not have: a url, an env +// block, or a prefix one of the bot's own settings starts with. +func checkAddonServer(name string, s server) error { + prefix := envPrefix(name) + switch { + case s.Command == "": + return errors.New("an addon needs a command: addons run only as local servers") + case s.Env != nil: + return fmt.Errorf("an addon server takes no env block: put its settings in the bot's environment, starting with %s, and it gets them", prefix) + } + if i := slices.IndexFunc(coreSettings, func(s string) bool { return strings.HasPrefix(s, prefix) }); i >= 0 { + return fmt.Errorf("an addon's settings start with %s, as the bot's own %s does; rename the server", prefix, coreSettings[i]) + } + return nil +} + +// shared are the bot's variables every addon gets, if set: the time zone, +// and how to reach the internet (a proxy, and certificates to trust). None +// holds a key of the bot's. +var shared = []string{"TZ", "HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "NO_PROXY", "no_proxy", "SSL_CERT_FILE", "SSL_CERT_DIR"} + +// addonEnv is an addon's whole environment: PATH, HOME, the shared +// variables that are set, and the bot's variables that start with prefix. +func addonEnv(prefix string) []string { + env := []string{"PATH=" + os.Getenv("PATH"), "HOME=" + os.Getenv("HOME")} + for _, name := range shared { + if v, ok := os.LookupEnv(name); ok { + env = append(env, name+"="+v) + } + } + for _, kv := range os.Environ() { + if strings.HasPrefix(kv, prefix) { + env = append(env, kv) + } + } + return env +} + +// saved is the mcp store's document. +type saved struct { + Secret []byte `json:"secret"` // the key every pseudonym is made from + Addons map[string]addonState `json:"addons,omitempty"` // each addon's state, by server name +} + +// secretSize is the pseudonym secret's size, in bytes. +const secretSize = 32 + +// loadSaved is the mcp store's document, with the pseudonym secret made and +// saved the first time. One that can't be read or saved is an error: never +// a new secret, which would change every pseudonym. +func loadSaved(store feature.Store) (saved, error) { + var s saved + found, err := store.Load(&s) + switch { + case err != nil: + return saved{}, err + case found && len(s.Secret) == secretSize: + return s, nil + case found: + return saved{}, errors.New("the saved secret is damaged") + } + s.Secret = make([]byte, secretSize) + rand.Read(s.Secret) + if err := store.Save(s); err != nil { + return saved{}, err + } + return s, nil +} + +// encoding writes pseudonyms and refs: lowercase base32, no padding. +var encoding = base32.NewEncoding("abcdefghijklmnopqrstuvwxyz234567").WithPadding(base32.NoPadding) + +// placeholder is a {u_…} an addon writes for a person's name. +var placeholder = regexp.MustCompile(`\{u_[a-z2-7]{26}\}`) + +// Kept for: a ref, and a sender's last-seen name. +const ( + refLife = 24 * time.Hour + nameLife = 24 * time.Hour +) + +// addon is a server that speaks signalbot's extension, and what the bot +// keeps for it. Its watches, claims, leases and outbox cursor are saved, +// by the keeper; the rest is in memory only. +type addon struct { + server string // its name in MCP_CONFIG + title string // its name for people, as it gave it + cfg addonConfig + key []byte // HMAC(secret, server): its pseudonyms' key + conn conn // where to call it + bot map[string]bool // the tools the bot may call itself + busy chan struct{} // a place for each direct call in flight + now func() time.Time + host feature.Host // where it posts and reacts; set before it runs + changed func() // its saved state changed: save it soon, without waiting + dirty chan struct{} // its outbox has news: read it + up chan struct{} // it has started again + settled chan struct{} // its posts read from the outbox have all been sent or dropped + matches chan match // matched messages, for the watch worker + posts *limiter // its posts and reactions, per chat + calls *limiter // the watch worker's calls, per chat + + mu sync.Mutex + refs map[string]ref // by ref + names map[string]seen // by chat key, "\x00", sender's pseudonym + watches map[string][]*watch // live, by chat key + claims map[claimKey]claim // messages its watches took + leases map[string]lease // the chats it may post in, by pseudonym + tombs map[string]time.Time // unwatches before their watch, by chat pseudonym, "\x00", watch ID: until when + cursor string // where its outbox was read and delivered up to; "" for the start + next string // where the last read of its outbox ended: the cursor once its posts are sent + missed bool // a post read from the outbox wasn't sent: read it again before the cursor moves + applied []string // the IDs of its last ops applied, oldest first + done map[string]bool // applied, as a set + sending map[string]bool // the IDs of post ops held or in a mailbox + failed map[string]failure // post ops dropped before they were sent, by ID + waiting map[string][]*outgoing // by chat pseudonym, while a post of its waits in the chat's mailbox: those held to send after it, in turn +} + +// ref is the message a ref stands for: who sent it, where and when. +type ref struct { + msg feature.Message // without its text + expires time.Time +} + +// seen is the name a sender last had in a chat. +type seen struct { + name string + expires time.Time +} + +func newAddon(server, title string, cfg addonConfig, secret []byte, c conn, bot map[string]bool) *addon { + mac := hmac.New(sha256.New, secret) + mac.Write([]byte(server)) + return &addon{server: server, title: title, cfg: cfg, key: mac.Sum(nil), conn: c, bot: bot, + busy: make(chan struct{}, maxDirect), now: time.Now, changed: func() {}, dirty: make(chan struct{}, 1), + up: make(chan struct{}, 1), settled: make(chan struct{}, 1), + matches: make(chan match, maxMatches), posts: newLimiter(cfg.Rate), calls: newLimiter(watchRate), + refs: map[string]ref{}, names: map[string]seen{}, watches: map[string][]*watch{}, claims: map[claimKey]claim{}, + leases: map[string]lease{}, tombs: map[string]time.Time{}, done: map[string]bool{}, + sending: map[string]bool{}, failed: map[string]failure{}, waiting: map[string][]*outgoing{}} +} + +// allows reports whether the addon may be used in chat. +func (a *addon) allows(chat feature.Chat) bool { + if chat.GroupID == "" { + return a.cfg.DMs + } + group, _, _ := strings.Cut(chat.GroupID, "/") // a Telegram topic is in its group + return slices.Contains(a.cfg.Chats, "all") || slices.Contains(a.cfg.Chats, chat.GroupID) || slices.Contains(a.cfg.Chats, group) +} + +// pseudonym is prefix and HMAC(key, data), cut to 128 bits. +func (a *addon) pseudonym(prefix, data string) string { + mac := hmac.New(sha256.New, a.key) + mac.Write([]byte(data)) + return prefix + encoding.EncodeToString(mac.Sum(nil)[:16]) +} + +// chatID is the addon's name for chat. +func (a *addon) chatID(chat feature.Chat) string { return a.pseudonym("c_", "chat\x00"+chat.Key()) } + +// userID is the addon's name for sender: in chat only, unless global_ids. +func (a *addon) userID(chat feature.Chat, sender string) string { + if a.cfg.GlobalIDs { + return a.pseudonym("u_", "user\x00"+sender) + } + return a.pseudonym("u_", "user\x00"+chat.Key()+"\x00"+sender) +} + +// callContext is the context of a call the bot starts, in its _meta. +type callContext struct { + Chat string `json:"chat"` + Sender string `json:"sender"` + Ref string `json:"ref"` + Addressed bool `json:"addressed"` + Group bool `json:"group"` + Sent int64 `json:"sent"` // when the bot got it, in Unix seconds + Edited int64 `json:"edited"` // when the bot got the edit; 0 for an original + Name string `json:"name,omitempty"` +} + +// context is m's context for the addon, which the bot got at at. It keeps +// the sender's name, for placeholders, and a ref for m. sent and edited are +// when the bot got it, never the sender's clock. +func (a *addon) context(m feature.Message, at time.Time) callContext { + now := a.now() + user := a.userID(m.Chat, m.Sender) + r := make([]byte, 16) + rand.Read(r) + id := "r_" + encoding.EncodeToString(r) + a.mu.Lock() + for k, v := range a.refs { + if now.After(v.expires) { + delete(a.refs, k) + } + } + for k, v := range a.names { + if now.After(v.expires) { + delete(a.names, k) + } + } + a.refs[id] = ref{feature.Message{Chat: m.Chat, Sender: m.Sender, Timestamp: m.Timestamp, Edited: m.Edited}, now.Add(refLife)} + if m.Name != "" { + a.names[m.Chat.Key()+"\x00"+user] = seen{m.Name, now.Add(nameLife)} + } + a.mu.Unlock() + c := callContext{Chat: a.chatID(m.Chat), Sender: user, Ref: id, Addressed: m.Addressed, Group: m.Chat.GroupID != "", Sent: at.Unix()} + if m.Edited != 0 { + c.Edited = c.Sent + } + if a.cfg.Names { + c.Name = m.Name + } + return c +} + +// fill replaces each {u_…} in text with @Name, the name the addon last saw +// that sender use in chat, or "someone". +func (a *addon) fill(chat feature.Chat, text string) string { + now := a.now() + a.mu.Lock() + defer a.mu.Unlock() + return placeholder.ReplaceAllStringFunc(text, func(p string) string { + if s, ok := a.names[chat.Key()+"\x00"+p[1:len(p)-1]]; ok && now.Before(s.expires) { + return "@" + s.name + } + return "someone" + }) +} diff --git a/internal/features/mcp/addon_test.go b/internal/features/mcp/addon_test.go new file mode 100644 index 0000000..8657658 --- /dev/null +++ b/internal/features/mcp/addon_test.go @@ -0,0 +1,631 @@ +package mcp + +import ( + "bufio" + "bytes" + "context" + "encoding/base64" + "encoding/json" + "flag" + "fmt" + "image" + "image/png" + "io" + "maps" + "math/rand/v2" + "os" + "os/exec" + "path/filepath" + "regexp" + "slices" + "strconv" + "strings" + "sync" + "syscall" + "testing" + "time" + + "github.com/robdevops/signalbot/internal/feature" + "github.com/robdevops/signalbot/internal/feature/featuretest" + "github.com/robdevops/signalbot/internal/kit/logx" +) + +// Group IDs as Signal names them, and a Telegram one. +var ( + groupA = base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{1}, 32)) + groupB = base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{2}, 32)) + telegram = "-1001234567890" +) + +// addonTools is what the fake addon lists: who each tool is for, by its +// _meta. +var addonTools = map[string]string{ + "play": `{"io.github.robdevops.signalbot/visibility":["bot"]}`, + "both": `{"io.github.robdevops.signalbot/visibility":["model","bot"]}`, + "plain": ``, + "app": `{"ui":{"visibility":["app"]}}`, + "app_too": `{"ui":{"visibility":["model","app"]},"io.github.robdevops.signalbot/visibility":["model","bot"]}`, + "context": `{"io.github.robdevops.signalbot/visibility":["bot"]}`, + "pics": `{"io.github.robdevops.signalbot/visibility":["bot"]}`, + "big": `{"io.github.robdevops.signalbot/visibility":["bot"]}`, + "fail": `{"io.github.robdevops.signalbot/visibility":["bot"]}`, + "rpcfail": `{"io.github.robdevops.signalbot/visibility":["bot"]}`, + "hang": `{"io.github.robdevops.signalbot/visibility":["bot"]}`, + "huge": `{"io.github.robdevops.signalbot/visibility":["bot"]}`, + "env": `{"io.github.robdevops.signalbot/visibility":["bot"]}`, + "empty": `{"io.github.robdevops.signalbot/visibility":["bot"]}`, + "spawn": `{"io.github.robdevops.signalbot/visibility":["bot"]}`, + "round": `{"io.github.robdevops.signalbot/visibility":["bot"]}`, + "guess": `{"io.github.robdevops.signalbot/visibility":["bot"]}`, + "queue": `{"io.github.robdevops.signalbot/visibility":["bot"]}`, + "epoch": `{"io.github.robdevops.signalbot/visibility":["bot"]}`, + "crash": `{"io.github.robdevops.signalbot/visibility":["bot"]}`, +} + +// TestAddonProcess is not a real test: run as a subprocess with the +// argument "addon" (or "plain", which doesn't speak the extension, or +// "sleep", a process it starts that only sleeps), it is a stdio MCP server +// with addonTools and an outbox (see fakeOutbox). It answers calls at +// once, each on its own, echoes every line it gets to stderr, and exits +// when its stdin closes. +func TestAddonProcess(t *testing.T) { + mode := flag.Arg(0) + switch mode { + case "addon", "plain": + case "sleep": + time.Sleep(time.Hour) + os.Exit(0) + default: + return + } + var out sync.Mutex + reply := func(id int64, result string) { + out.Lock() + defer out.Unlock() + fmt.Printf(`{"jsonrpc":"2.0","id":%d,%s}`+"\n", id, result) + } + box := &fakeOutbox{nonce: "a", notify: func() { + out.Lock() + defer out.Unlock() + fmt.Println(`{"jsonrpc":"2.0","method":"notifications/resources/updated","params":{"uri":"signalbot://outbox/x"}}`) + }} + text := func(s string) string { + b, _ := json.Marshal(s) + return `"result":{"content":[{"type":"text","text":` + string(b) + `}]}` + } + sc := bufio.NewScanner(os.Stdin) + sc.Buffer(nil, 8<<20) + for sc.Scan() { + fmt.Fprintln(os.Stderr, sc.Text()) + var req struct { + ID *int64 `json:"id"` + Method string `json:"method"` + Params struct { + Name string `json:"name"` + Arguments map[string]string `json:"arguments"` + Meta json.RawMessage `json:"_meta"` + URI string `json:"uri"` + Caps struct { + Experimental map[string]struct{ Version int } `json:"experimental"` + } `json:"capabilities"` + } `json:"params"` + } + json.Unmarshal(sc.Bytes(), &req) + if req.ID == nil { + continue + } + id, p := *req.ID, req.Params + switch req.Method { + case "initialize": + caps := `{"tools":{}}` + if mode == "addon" && p.Caps.Experimental[vendor+"addon"].Version == 1 { // only if offered + caps = `{"tools":{},"resources":{"subscribe":true},"experimental":{"io.github.robdevops.signalbot/addon":{"version":1}}}` + } + reply(id, `"result":{"protocolVersion":"`+protocol+`","capabilities":`+caps+`,"serverInfo":{"name":"game","title":"Game","version":"1"}}`) + case "tools/list": + var list []string + for _, n := range slices.Sorted(maps.Keys(addonTools)) { + t := `{"name":"` + n + `","inputSchema":{"type":"object"}` + if m := addonTools[n]; m != "" { + t += `,"_meta":` + m + } + list = append(list, t+"}") + } + reply(id, `"result":{"tools":[`+strings.Join(list, ",")+`]}`) + case "tools/call": + go func() { + switch p.Name { + case "play": + var meta map[string]callContext + json.Unmarshal(p.Meta, &meta) + reply(id, text("you said "+p.Arguments["args"]+"\n{"+meta[vendor+"context"].Sender+"} plays")) + case "context": + reply(id, text(string(p.Meta))) + case "pics": + pic := `{"type":"image","mimeType":"image/png","data":"` + tinyPNG() + `"}` + reply(id, `"result":{"content":[`+pic+`,{"type":"image","data":"eA=="},`+pic+`,`+pic+`]}`) + case "big": + reply(id, `"result":{"content":[{"type":"image","data":"`+tinyPNG()+`"},{"type":"image","data":"`+noisePNG()+`"},{"type":"text","text":"two"}]}`) + case "fail": + reply(id, `"result":{"content":[{"type":"text","text":"Alice's secret broke"}],"isError":true}`) + case "rpcfail": + reply(id, `"error":{"code":-32000,"message":"Bob's secret broke"}`) + case "hang": + case "huge": + out.Lock() + fmt.Println(strings.Repeat("x", 5<<20)) + out.Unlock() + case "env": + var names []string + for _, kv := range os.Environ() { + k, _, _ := strings.Cut(kv, "=") + names = append(names, k) + } + slices.Sort(names) + reply(id, text(strings.Join(names, ","))) + case "empty": + reply(id, `"result":{"content":[]}`) + case "round", "guess", "queue", "epoch", "crash": + reply(id, box.call(p.Name, p.Arguments, p.Meta)) + case "spawn": + cmd := exec.Command(os.Args[0], "-test.run=^TestAddonProcess$", "sleep") + cmd.Start() + reply(id, text(strconv.Itoa(cmd.Process.Pid))) + default: + reply(id, text("called "+p.Name)) + } + }() + case "resources/subscribe": + fakeLog("subscribed") + reply(id, `"result":{}`) + case "resources/read": + go func() { reply(id, box.read(p.URI)) }() + default: + reply(id, `"result":{}`) + } + } + os.Exit(0) +} + +// noisePNG is a PNG of noise, over 2 MB. +func noisePNG() string { + im := image.NewRGBA(image.Rect(0, 0, 800, 800)) + r := rand.New(rand.NewPCG(1, 2)) + for i := range im.Pix { + im.Pix[i] = uint8(r.Uint32()) + } + var buf bytes.Buffer + png.Encode(&buf, im) + return base64.StdEncoding.EncodeToString(buf.Bytes()) +} + +// addonServer is a config entry for the fake addon, in mode, with addon +// as its addon block and more settings after it. +func addonServer(mode, addon, more string) string { + self, _ := json.Marshal(os.Args[0]) + return `{"command":` + string(self) + `,"args":["-test.run=^TestAddonProcess$","` + mode + `"],"addon":` + addon + more + `}` +} + +// direct is the chat_commands setting for /play, and /ctx, /pics and the +// rest, each calling the tool of its name directly. +const direct = `,"chat_commands":{"play":{"tool":"play","direct":true,"example":"/play 3m"},"ctx":{"tool":"context","direct":true},` + + `"pics":{"tool":"pics","direct":true},"big":{"tool":"big","direct":true},"fail":{"tool":"fail","direct":true},` + + `"rpcfail":{"tool":"rpcfail","direct":true},"hang":{"tool":"hang","direct":true},"huge":{"tool":"huge","direct":true},` + + `"env":{"tool":"env","direct":true},"empty":{"tool":"empty","direct":true},"spawn":{"tool":"spawn","direct":true},` + + `"app":{"tool":"app","direct":true},"plain":{"tool":"plain","direct":true},"both":{"tool":"both"}}` + +// startAddon registers config on a host with a model that calls tools and +// a state directory of its own, waits until the servers are up, and stops +// them when the test ends. +func startAddon(t *testing.T, config string, before ...func(*featuretest.Host)) (*featuretest.Host, *logx.Buffer) { + t.Helper() + dir := t.TempDir() + h, log, err := register(t, config, append([]func(*featuretest.Host){func(h *featuretest.Host) { h.Settings["STATE_DIRECTORY"] = dir }}, before...)...) + if err != nil { + t.Fatal(err) + } + return h, log +} + +// in is an addressed message from Alice, in chat. +func in(chat feature.Chat, text string) feature.Message { + return feature.Message{Chat: chat, Sender: "alice-id", Name: "Alice", Text: text, Timestamp: 1700000000000, Addressed: true} +} + +var ( + inA = feature.Chat{GroupID: groupA} + inB = feature.Chat{GroupID: groupB} + inDM = feature.Chat{User: "alice-id"} +) + +func TestEnvPrefix(t *testing.T) { + for name, want := range map[string]string{"geo": "GEO_", "my-addon.v2": "MY_ADDON_V2_", "Ünï": "_N__"} { + if got := envPrefix(name); got != want { + t.Errorf("envPrefix(%q) = %q, want %q", name, got, want) + } + } +} + +// coreSettings is docs/CONFIGURATION.md's table, so no addon's prefix +// starts one of the bot's own settings. +func TestCoreSettingsAreTheDocs(t *testing.T) { + doc, err := os.ReadFile("../../../docs/CONFIGURATION.md") + if err != nil { + t.Fatal(err) + } + var documented []string + for _, m := range regexp.MustCompile("(?m)^\\| `([A-Z0-9_]+)` \\|").FindAllStringSubmatch(string(doc), -1) { + documented = append(documented, m[1]) + } + want := slices.Sorted(slices.Values(append(documented, "STATE_DIRECTORY"))) + if got := slices.Sorted(slices.Values(coreSettings)); !slices.Equal(slices.Compact(want), got) { + t.Fatalf("coreSettings %v,\ndocs %v", got, slices.Compact(want)) + } +} + +func TestAddonLoad(t *testing.T) { + s, err := load(writeConfig(t, `{"mcpServers":{"game":`+addonServer("addon", `{"chats":["`+groupA+`","`+telegram+`"],"dms":true}`, direct)+`,`+ + `"all":`+addonServer("addon", `{"chats":["all"],"watch_max":"30m","rate":{"per_minute":6}}`, "")+`}}`)) + if err != nil { + t.Fatal(err) + } + if a := s["game"].Addon; a == nil || !a.DMs || len(a.Chats) != 2 || a.watchMax != time.Hour || a.Rate != (rateConfig{20, 5}) || !s["game"].ChatCommands["play"].Direct { + t.Fatalf("game: %+v", s["game"]) + } + if a := s["all"].Addon; a.watchMax != 30*time.Minute || a.Rate != (rateConfig{6, 5}) { + t.Fatalf("all: %+v", a) + } + for bad, want := range map[string]string{ + `{"mcpServers":{"geo":{"url":"https://x","addon":{}}}}`: `: MCP server "geo": an addon needs a command: addons run only as local servers`, + `{"mcpServers":{"geo":{"command":"x","env":{"A":"b"},"addon":{}}}}`: `: MCP server "geo": an addon server takes no env block: put its settings in the bot's environment, starting with GEO_, and it gets them`, + `{"mcpServers":{"model":{"command":"x","addon":{}}}}`: `: MCP server "model": an addon's settings start with MODEL_, as the bot's own MODEL_API_KEY does; rename the server`, + `{"mcpServers":{"Daily":{"command":"x","addon":{}}}}`: `: MCP server "Daily": an addon's settings start with DAILY_, as the bot's own DAILY_BUDGET does; rename the server`, + `{"mcpServers":{"geo":{"command":"x","chat_commands":{"geo":{"tool":"geo","direct":true}}}}}`: `: MCP server "geo": chat command "geo" is direct, which needs an addon block`, + `{"mcpServers":{"geo":{"command":"x","addon":{"chat":["all"]}}}}`: `: MCP server "geo": addon: unknown setting "chat" (settings are chats, dms, post, react, watch, watch_max, names, global_ids, rate)`, + `{"mcpServers":{"geo":{"command":"x","addon":{"rate":{"perMinute":1}}}}}`: `: MCP server "geo": addon rate: unknown setting "perMinute" (settings are per_minute, burst)`, + `{"mcpServers":{"geo":{"command":"x","addon":{"chats":["Family"]}}}}`: `: MCP server "geo": addon chats: "Family" isn't a group ID; copy the group's ID as Signal or Telegram shows it, or use "all"`, + `{"mcpServers":{"geo":{"command":"x","addon":{"chats":["all","` + groupA + `"]}}}}`: `: MCP server "geo": addon chats: "all" goes alone`, + `{"mcpServers":{"geo":{"command":"x","addon":{"watch_max":"25h"}}}}`: `: MCP server "geo": addon watch_max: "25h" isn't a time from 1s to 24h, such as 1h or 30m`, + `{"mcpServers":{"geo":{"command":"x","addon":{"rate":{"burst":-1}}}}}`: `: MCP server "geo": addon rate: per_minute and burst can't be below 0`, + `{"mcpServers":{"geo":{"command":"x","chat_commands":{"g":{"tool":"g","drect":true}},"addon":{}}}}`: `: MCP server "geo": chat command "g": unknown setting "drect" (settings are tool, require_arg, example, direct)`, + } { + p := writeConfig(t, bad) + if _, err := load(p); err == nil || err.Error() != p+want { + t.Errorf("%s:\n got %v\nwant %s", bad, err, want) + } + } +} + +// An addon gets PATH, HOME, the time zone and proxy settings, and the +// bot's variables with its prefix, never the bot's own; it is offered +// signalbot's extension in the handshake. +func TestAddonEnv(t *testing.T) { + t.Setenv("MODEL_API_KEY", "secret-key") + t.Setenv("GAME_TOKEN", "t") + t.Setenv("GAMES_X", "x") + for _, name := range shared { + t.Setenv(name, "x") + } + h, _ := startAddon(t, `{"mcpServers":{"game":`+addonServer("addon", `{"dms":true}`, direct)+`}}`) + want := strings.Join(slices.Sorted(slices.Values(append([]string{"GAME_TOKEN", "HOME", "PATH"}, shared...))), ",") + if got := h.Message(context.Background(), in(inDM, "/env")); got.Answer != want { + t.Fatalf("env %+v", got) + } +} + +// What an addon writes to stderr is counted, and what was counted since the +// last count logged is logged when it exits. +func TestAddonStderr(t *testing.T) { + var log logx.Buffer + t.Cleanup(logx.SetOutput(&log, &log, true)) + c := &stdioConn{name: "game", prefix: "GAME_"} + c.readStderr(io.NopCloser(strings.NewReader("started\npanic: Alice\ngoroutine 1\n"))) + if got, want := log.String(), "<6>addon game wrote 1 line (7 bytes) to stderr\n<6>addon game wrote 2 lines (23 bytes) to stderr\n"; got != want { + t.Fatalf("log %q", got) + } +} + +// Tools that aren't for the model are never offered to it; a direct +// command calls a tool for the bot, with the message's context, and its +// placeholders filled in; only in the chats the addon is allowed. +func TestDirect(t *testing.T) { + h, log := startAddon(t, `{"mcpServers":{"game":`+addonServer("addon", `{"chats":["`+groupA+`"]}`, direct)+`}}`) + if gs := h.ToolGroups(); len(gs) != 1 || gs[0].Listing != "game: app_too, both, plain, /big, /both, /ctx, /empty, /env, /fail, /hang, /huge, /pics, /play, /rpcfail, /spawn" { + t.Fatalf("groups %+v", gs) + } + if got := strings.Join(slices.Sorted(maps.Keys(tools(h))), ","); got != "game__app_too,game__both,game__plain" { + t.Fatalf("offered %s", got) + } + for _, want := range []string{ + "<5>game MCP: app_too, both, plain\n", + "<5>game MCP: an addon, with tools for the bot: app_too, big, both, context, crash, empty, env, epoch, fail, guess, hang, huge, pics, play, queue, round, rpcfail, spawn\n", + `<4>MCP server game: chat command /app names tool "app", which the bot may not call; skipped`, + `<4>MCP server game: chat command /plain names tool "plain", which the bot may not call; skipped`, + } { + if !strings.Contains(log.String(), want) { + t.Errorf("log %q, want %q", log.String(), want) + } + } + ctx := context.Background() + if got := h.Message(ctx, in(inA, "/play 3m")); got.Answer != "you said 3m\n@Alice plays" || got.Done || len(got.Pictures) != 0 { + t.Fatalf("play: %+v", got) + } + if got := h.Message(ctx, in(inA, "/both")); got.ToolChoice != "game__both" { + t.Fatalf("a command for the model: %+v", got) + } + for _, chat := range []feature.Chat{inB, inDM} { + if got := h.Message(ctx, in(chat, "/play")); got.Answer != "/play isn't available in this chat." { + t.Errorf("%v: %+v", chat, got) + } + } + got := h.Message(ctx, in(inA, "/ctx")) + var meta map[string]callContext + if err := json.Unmarshal([]byte(got.Answer), &meta); err != nil { + t.Fatalf("ctx %q: %v", got.Answer, err) + } + c := meta[vendor+"context"] + id := regexp.MustCompile(`^[cur]_[a-z2-7]{26}$`) + if !id.MatchString(c.Chat) || !id.MatchString(c.Sender) || !id.MatchString(c.Ref) || c.Chat[0] != 'c' || c.Sender[0] != 'u' || c.Ref[0] != 'r' || + !c.Addressed || !c.Group || c.Edited != 0 || c.Name != "" || time.Since(time.Unix(c.Sent, 0)) > time.Minute { + t.Fatalf("context %+v", c) + } + if strings.Contains(got.Answer, "alice-id") || strings.Contains(got.Answer, groupA) || strings.Contains(got.Answer, "Alice") { + t.Fatalf("a real name or ID reached the addon: %s", got.Answer) + } + // Each call is logged by tool, outcome and size only. + if !regexp.MustCompile(`<6>MCP server game: /play called play: ok in \d+ms, \d+ bytes\n`).MatchString(log.String()) { + t.Errorf("log %q", log.String()) + } +} + +// With no model, only addons start: no tools are offered, and direct +// commands, listed by themselves, still work. +func TestDirectNoModel(t *testing.T) { + gone := writeConfig(t, "") + h, log := startAddon(t, `{"mcpServers":{"game":`+addonServer("addon", `{"dms":true}`, + `,"chat_commands":{"play":{"tool":"play","direct":true},"both":{"tool":"both"}}`)+`,"other":{"command":"`+gone+`"}}}`, + func(h *featuretest.Host) { h.Bot = feature.Info{} }) + if gs := h.ToolGroups(); len(gs) != 1 || len(gs[0].Tools) != 0 || !slices.Equal(gs[0].Names, []string{"**game MCP**: /play"}) { + t.Fatalf("groups %+v", gs) + } + if got := h.Message(context.Background(), in(inDM, "/play")); got.Answer != "you said \n@Alice plays" { + t.Fatalf("play: %+v", got) + } + if l := log.String(); !strings.HasPrefix(l, "<4>MCP_CONFIG is set but no model is configured, so only addon servers were started\n") || strings.Contains(l, "other") { + t.Fatalf("log %q", l) + } +} + +// A direct command's images are made safe and capped; a result with +// nothing is done with, not sent to the model; a failure is told in a +// line for people, its text never shown or logged; a call that takes too +// long is given up; past two at once, the addon is busy. +func TestDirectResults(t *testing.T) { + defer func(d time.Duration) { directTimeout = d }(directTimeout) + directTimeout = 3 * time.Second + h, log := startAddon(t, `{"mcpServers":{"game":`+addonServer("addon", `{"dms":true}`, direct)+`}}`) + ctx := context.Background() + if got := h.Message(ctx, in(inDM, "/pics")); got.Answer != "" || len(got.Pictures) != 2 || got.Done { + t.Fatalf("pics: %+v", got) + } + if got := h.Message(ctx, in(inDM, "/big")); got.Answer != "two" || len(got.Pictures) != 1 { + t.Fatalf("big: %d pictures, %q", len(got.Pictures), got.Answer) + } + if !strings.Contains(log.String(), "<4>MCP server game: 1 images left out: not images, or past 2 images or 2 MB\n") || + !strings.Contains(log.String(), "<4>MCP server game: 2 images left out") { + t.Errorf("log %q", log.String()) + } + if got := h.Message(ctx, in(inDM, "/empty")); !got.Done || got.Answer != "" { + t.Fatalf("empty: %+v", got) + } + for _, cmd := range []string{"/fail", "/rpcfail"} { + if got := h.Message(ctx, in(inDM, cmd)); got.Answer != "Game couldn't do that just now." { + t.Errorf("%s: %+v", cmd, got) + } + } + answers := make(chan string, 3) + for range 3 { + go func() { answers <- h.Message(ctx, in(inDM, "/hang")).Answer }() + } + var got []string + for range 3 { + got = append(got, <-answers) + } + slices.Sort(got) + if want := []string{"Game couldn't do that just now.", "Game couldn't do that just now.", "Game is busy, try again in a moment."}; !slices.Equal(got, want) { + t.Errorf("hangs: %q", got) + } + l := log.String() + for _, want := range []string{"/fail called fail: an error result", "/rpcfail called rpcfail: rpc error -32000", "/hang called hang: no answer in time", + "<4>MCP server game: /hang refused: 2 calls already in flight\n"} { + if !strings.Contains(l, want) { + t.Errorf("log %q, want %q", l, want) + } + } + if strings.Contains(l, "secret") { + t.Fatalf("the server's error text was logged: %q", l) + } +} + +// A require_arg direct command answers a bare one with its example, not +// pointing to the model. +func TestDirectRequireArg(t *testing.T) { + h, _ := startAddon(t, `{"mcpServers":{"game":`+addonServer("addon", `{"dms":true}`, + `,"chat_commands":{"play":{"tool":"play","direct":true,"require_arg":true,"example":"/play 3m"}}`)+`}}`) + if got := h.Message(context.Background(), in(inDM, "/play")); got.Answer != "Put what you want after it, like /play <your request>. Try: /play 3m." { + t.Fatalf("bare: %+v", got) + } +} + +// A server with an addon block that doesn't speak the extension runs as a +// plain server: its direct commands are skipped, and its tools for the +// model are offered. +func TestNotAnAddon(t *testing.T) { + h, log := startAddon(t, `{"mcpServers":{"game":`+addonServer("plain", `{"dms":true}`, direct)+`}}`) + for _, want := range []string{ + "<4>MCP server game has an addon block but doesn't speak signalbot's addon extension (version 1), so it runs as a plain server\n", + "<4>MCP server game: chat command /play is direct, but the server's addon features are off; skipped\n", + "<5>chat commands: /both\n", + } { + if !strings.Contains(log.String(), want) { + t.Errorf("log %q, want %q", log.String(), want) + } + } + if got := h.Message(context.Background(), in(inDM, "/play")); !got.IsZero() { + t.Fatalf("play: %+v", got) + } +} + +// Pseudonyms are per chat unless global_ids, differ between servers, and +// are made from a secret kept in the "mcp" store, so they survive a +// restart. A secret that can't be kept turns addons off. +func TestPseudonyms(t *testing.T) { + secret := bytes.Repeat([]byte{7}, secretSize) + a := newAddon("game", "Game", addonConfig{}, secret, nil, nil) + g := newAddon("game", "Game", addonConfig{GlobalIDs: true}, secret, nil, nil) + other := newAddon("game2", "Game", addonConfig{}, secret, nil, nil) + if a.userID(inA, "alice-id") == a.userID(inB, "alice-id") || a.userID(inA, "alice-id") == a.userID(inA, "bob-id") || + g.userID(inA, "alice-id") != g.userID(inB, "alice-id") || a.chatID(inA) == other.chatID(inA) || a.chatID(inA) == a.chatID(inB) || + a.chatID(inA) != newAddon("game", "", addonConfig{}, secret, nil, nil).chatID(inA) { + t.Fatal("pseudonyms don't keep apart what they should") + } + + dir := t.TempDir() + cfg := `{"mcpServers":{"game":` + addonServer("addon", `{"dms":true}`, direct) + `}}` + chatIDs := func() string { + h, _, err := register(t, cfg, func(h *featuretest.Host) { h.Settings["STATE_DIRECTORY"] = dir }) + if err != nil { + t.Fatal(err) + } + defer h.Stop() + var meta map[string]callContext + json.Unmarshal([]byte(h.Message(context.Background(), in(inDM, "/ctx")).Answer), &meta) + return meta[vendor+"context"].Chat + } + first := chatIDs() + if first == "" || chatIDs() != first { + t.Fatal("pseudonyms changed with a restart") + } + var s saved + data, err := os.ReadFile(filepath.Join(dir, "mcp.json")) + if err != nil || json.Unmarshal(data, &s) != nil || len(s.Secret) != secretSize { + t.Fatalf("saved %s, %v", data, err) + } + + // mcp.json can't be read: addons fail closed. + broken := t.TempDir() + os.Mkdir(filepath.Join(broken, "mcp.json"), 0o700) + h, log, err := register(t, cfg, func(h *featuretest.Host) { h.Settings["STATE_DIRECTORY"] = broken }) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(log.String(), "<3>addon features are off: the pseudonyms' secret can't be kept: ") || + !strings.Contains(log.String(), "/play is direct, but the server's addon features are off; skipped") { + t.Fatalf("log %q", log.String()) + } + if got := h.Message(context.Background(), in(inDM, "/play")); !got.IsZero() { + t.Fatalf("play with addons off: %+v", got) + } + // So does a state directory the host can't open. + _, log, err = register(t, cfg, func(h *featuretest.Host) { h.StoreErr = fmt.Errorf("no state directory") }) + if err != nil || !strings.Contains(log.String(), "<3>addon features are off: the pseudonyms' secret can't be kept: no state directory\n") { + t.Fatalf("log %q, %v", log.String(), err) + } +} + +// A placeholder becomes the name its sender last had in that chat, as the +// addon saw them, else "someone"; names expire. +func TestFill(t *testing.T) { + a := newAddon("game", "Game", addonConfig{}, bytes.Repeat([]byte{7}, secretSize), nil, nil) + now := time.Now() + a.now = func() time.Time { return now } + alice, bob := a.userID(inA, "alice-id"), a.userID(inA, "bob-id") + a.context(in(inA, "/play"), now) + bobs := in(inA, "/play") + bobs.Sender, bobs.Name = "bob-id", "Bob" + a.context(bobs, now) + if got := a.fill(inA, "{"+alice+"} beat {"+bob+"} and {"+a.userID(inA, "x")+"}; {u_x}"); got != "@Alice beat @Bob and someone; {u_x}" { + t.Fatalf("filled %q", got) + } + if got := a.fill(inB, "{"+alice+"}"); got != "someone" { + t.Fatalf("another chat: %q", got) + } + now = now.Add(nameLife + time.Second) + if got := a.fill(inA, "{"+alice+"}"); got != "someone" { + t.Fatalf("expired: %q", got) + } + n := a.context(feature.Message{Chat: inA, Sender: "alice-id", Name: "Alice", Edited: 5}, now) + if n.Edited != n.Sent || n.Name != "" { + t.Fatalf("edit %+v", n) + } + a.cfg.Names = true + if n := a.context(in(inA, "/play"), now); n.Name != "Alice" || n.Edited != 0 { + t.Fatalf("names %+v", n) + } + a.mu.Lock() + defer a.mu.Unlock() + if len(a.refs) != 2 { // the first two expired + t.Fatalf("%d refs", len(a.refs)) + } +} + +// An addon's stderr is only counted, never logged: it may echo chat text. +// A line over 4 MiB on stdout gets it restarted. +func TestAddonOutput(t *testing.T) { + defer func(d time.Duration) { restartDelay = d }(restartDelay) + restartDelay = 10 * time.Millisecond + h, log := startAddon(t, `{"mcpServers":{"game":`+addonServer("addon", `{"dms":true}`, direct)+`}}`) + ctx := context.Background() + if got := h.Message(ctx, in(inDM, "/play my address is 1 Long Rd")); got.Answer != "you said my address is 1 Long Rd\n@Alice plays" { + t.Fatalf("play: %+v", got) + } + if got := h.Message(ctx, in(inDM, "/huge")); got.Answer != "Game couldn't do that just now." { + t.Fatalf("huge: %+v", got) + } + deadline := time.Now().Add(10 * time.Second) + for h.Message(ctx, in(inDM, "/play")).Answer != "you said \n@Alice plays" { + if time.Now().After(deadline) { + t.Fatalf("not restarted: %s", log.String()) + } + time.Sleep(50 * time.Millisecond) + } + l := log.String() + if !strings.Contains(l, "<4>MCP server game wrote a line over 4 MiB, so it is stopped and restarted\n") || !strings.Contains(l, "<4>MCP server game exited; restarting in") || + !regexp.MustCompile(`<6>addon game wrote \d+ lines? \(\d+ bytes\) to stderr\n`).MatchString(l) { + t.Fatalf("log %q", l) + } + if strings.Contains(l, "Long Rd") || strings.Contains(l, "initialize") { + t.Fatalf("stderr was logged: %q", l) + } +} + +// When the bot stops, so does everything the addon started. +func TestAddonStops(t *testing.T) { + h, _ := startAddon(t, `{"mcpServers":{"game":`+addonServer("addon", `{"dms":true}`, direct)+`}}`) + pid, err := strconv.Atoi(h.Message(context.Background(), in(inDM, "/spawn")).Answer) + if err != nil { + t.Fatal(err) + } + if !alive(pid) { + t.Fatal("not started") + } + h.Stop() + for deadline := time.Now().Add(10 * time.Second); alive(pid); time.Sleep(20 * time.Millisecond) { + if time.Now().After(deadline) { + t.Fatal("what the addon started outlived the bot") + } + } +} + +// alive reports whether process pid runs: it exists and isn't a zombie. +func alive(pid int) bool { + if syscall.Kill(pid, 0) != nil { + return false + } + stat, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid)) + if err != nil { + return true // no /proc: as signal 0 says + } + _, after, _ := strings.Cut(string(stat), ") ") + return !strings.HasPrefix(after, "Z") +} diff --git a/internal/features/mcp/conn.go b/internal/features/mcp/conn.go index 3784b48..6f1f113 100644 --- a/internal/features/mcp/conn.go +++ b/internal/features/mcp/conn.go @@ -34,6 +34,13 @@ type rpcError struct { func (e *rpcError) Error() string { return fmt.Sprintf("rpc error %d: %s", e.Code, e.Message) } +// A local server's call fails with errNotRunning while it is down, and +// errExited if it exits before answering. +var ( + errNotRunning = errors.New("not running") + errExited = errors.New("server exited") +) + type rpcMsg struct { JSONRPC string `json:"jsonrpc"` ID *int64 `json:"id,omitempty"` @@ -50,58 +57,112 @@ type rpcMsg struct { type stdioConn struct { name, version string cfg server - redact func(string) string // scrubs names and IDs from its output before it is logged + redact func(string) string // scrubs names and IDs from its output before it is logged + prefix string // an addon's: it gets the bot's variables that start with this, and its stderr is only counted + updated chan struct{} // an addon's: marked, without waiting, when it says a resource was updated + ready func(context.Context, handshake) // an addon's: called each time it has started again and initialized nextID atomic.Int64 - mu sync.Mutex // guards stdin, pending and done + mu sync.Mutex // guards stdin, pending, done and the stderr counts stdin io.WriteCloser pending map[int64]chan rpcMsg done chan struct{} // closed when the current process exits + + errLines, errBytes int // an addon's stderr, since it was last logged + errLogged time.Time // when it was } +const ( + // maxLine caps a line from a server; a longer one gets it restarted. + maxLine = 4 << 20 + // maxStderrLine caps what is logged of a line on a server's stderr. + maxStderrLine = 4 << 10 + // stopWait is how long a server has to exit after its stdin closes, + // and again after SIGTERM, before SIGKILL. + stopWait = 2 * time.Second +) + +// start starts the server, in a process group of its own, stopped when ctx +// ends: its stdin is closed, then the group gets SIGTERM, then SIGKILL. The +// group is killed when the server exits, so what it started stops too. func (c *stdioConn) start(ctx context.Context) error { - cmd := exec.CommandContext(ctx, c.cfg.Command, c.cfg.Args...) - // Its whole environment: PATH, HOME and its configured env, never the - // bot's own, which holds the API key. - cmd.Env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + os.Getenv("HOME")} - for k, v := range c.cfg.Env { - cmd.Env = append(cmd.Env, k+"="+v) - } - cmd.Cancel = func() error { return cmd.Process.Signal(syscall.SIGTERM) } - cmd.WaitDelay = 5 * time.Second + cmd := exec.Command(c.cfg.Command, c.cfg.Args...) + // Its whole environment: PATH, HOME and its configured env, or an + // addon's prefixed variables, never the bot's own, which hold the API + // key. + if c.prefix != "" { + cmd.Env = addonEnv(c.prefix) + } else { + cmd.Env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + os.Getenv("HOME")} + for k, v := range c.cfg.Env { + cmd.Env = append(cmd.Env, k+"="+v) + } + } + setGroup(cmd) stdin, err := cmd.StdinPipe() if err != nil { return err } - stdout, err := cmd.StdoutPipe() + // Its own pipes, not exec's, so Wait never closes them under a read: + // they end when every process writing to them has. + outR, outW, err := os.Pipe() if err != nil { return err } - stderr, err := cmd.StderrPipe() + errR, errW, err := os.Pipe() if err != nil { + outR.Close() + outW.Close() return err } - if err := cmd.Start(); err != nil { + cmd.Stdout, cmd.Stderr = outW, errW + err = cmd.Start() + outW.Close() + errW.Close() + if err != nil { + outR.Close() + errR.Close() return err } - done := make(chan struct{}) + done, exited := make(chan struct{}), make(chan struct{}) c.mu.Lock() c.stdin, c.pending, c.done = stdin, map[int64]chan rpcMsg{}, done c.mu.Unlock() + go c.readStderr(errR) go func() { - sc := bufio.NewScanner(stderr) - for sc.Scan() { - logx.Debugf("MCP server %s: %s", c.name, c.redact(sc.Text())) + cmd.Wait() + signalGroup(cmd.Process, syscall.SIGKILL) // anything it left running + close(exited) + }() + go func() { + select { + case <-exited: + return + case <-ctx.Done(): + } + stdin.Close() + for _, sig := range []syscall.Signal{syscall.SIGTERM, syscall.SIGKILL} { + select { + case <-exited: + return + case <-time.After(stopWait): + signalGroup(cmd.Process, sig) + } } }() go func() { - sc := bufio.NewScanner(stdout) - sc.Buffer(make([]byte, 64<<10), 4<<20) + sc := bufio.NewScanner(outR) + sc.Buffer(make([]byte, 64<<10), maxLine) for sc.Scan() { c.dispatch(sc.Bytes()) } - cmd.Wait() + if errors.Is(sc.Err(), bufio.ErrTooLong) { + logx.Warnf("MCP server %s wrote a line over %d MiB, so it is stopped and restarted", c.name, maxLine>>20) + signalGroup(cmd.Process, syscall.SIGKILL) + } + outR.Close() + <-exited c.mu.Lock() for id, ch := range c.pending { close(ch) @@ -114,11 +175,83 @@ func (c *stdioConn) start(ctx context.Context) error { return nil } +// readStderr reads the server's stderr in pieces, so no line is too long +// for it. A plain server's lines are logged at debug, scrubbed and cut; an +// addon's are only counted, since it may write what it was sent, and what +// was counted since the last count logged is logged once it exits. +func (c *stdioConn) readStderr(r io.ReadCloser) { + defer r.Close() + br := bufio.NewReaderSize(r, maxStderrLine) + var line []byte + for { + piece, more, err := br.ReadLine() + if err != nil { + if c.prefix != "" { + c.flushStderr() + } + return + } + if c.prefix != "" { + c.countStderr(len(piece), !more) + continue + } + line = append(line, piece[:min(len(piece), maxStderrLine-len(line))]...) + if !more { + logx.Debugf("MCP server %s: %s", c.name, c.redact(string(line))) + line = line[:0] + } + } +} + +// countStderr counts n bytes of an addon's stderr, and a line if end, and +// logs the counts at most once a minute. +func (c *stdioConn) countStderr(n int, end bool) { + c.mu.Lock() + c.errBytes += n + if end { + c.errLines++ + } + lines, bytes := c.errLines, c.errBytes + due := lines > 0 && time.Since(c.errLogged) >= time.Minute + if due { + c.errLines, c.errBytes, c.errLogged = 0, 0, time.Now() + } + c.mu.Unlock() + if due { + c.logStderr(lines, bytes) + } +} + +// flushStderr logs what was counted of an addon's stderr since the count +// was last logged, if anything. +func (c *stdioConn) flushStderr() { + c.mu.Lock() + lines, bytes := c.errLines, c.errBytes + pending := lines > 0 || bytes > 0 + if pending { + c.errLines, c.errBytes, c.errLogged = 0, 0, time.Now() + } + c.mu.Unlock() + if pending { + c.logStderr(max(lines, 1), bytes) // a last line without a line break is still a line + } +} + +// logStderr logs a count of an addon's stderr. +func (c *stdioConn) logStderr(lines, bytes int) { + unit := "lines" + if lines == 1 { + unit = "line" + } + logx.Infof("addon %s wrote %d %s (%d bytes) to stderr", c.name, lines, unit, bytes) +} + // restartDelay is the first wait before restarting a local server that // exited, doubling to 32s while it keeps failing; tests shorten it. var restartDelay = time.Second -// supervise restarts the server whenever it exits, until ctx ends. +// supervise restarts the server whenever it exits, until ctx ends, and +// calls ready, if set, each time one has initialized. func (c *stdioConn) supervise(ctx context.Context) { backoff := restartDelay for { @@ -139,16 +272,20 @@ func (c *stdioConn) supervise(ctx context.Context) { } backoff = min(backoff*2, 32*time.Second) if err := c.start(ctx); err != nil { - logx.Warnf("MCP server %s failed to start: %v", c.name, err) + logx.Warnf("MCP server %s failed to start: %s", c.name, describe(err, c.prefix != "")) continue // c.done is still the exited process's, so it retries } ictx, cancel := context.WithTimeout(ctx, callTimeout) - if _, err := initialize(ictx, c, c.version); err != nil { - logx.Warnf("MCP server %s failed to initialize: %v", c.name, err) - } else { - backoff = restartDelay - } + hs, err := initialize(ictx, c, c.version) cancel() + if err != nil { + logx.Warnf("MCP server %s failed to initialize: %s", c.name, describe(err, c.prefix != "")) + continue + } + backoff = restartDelay + if c.ready != nil { + c.ready(ctx, hs) + } } } @@ -174,6 +311,12 @@ func (c *stdioConn) dispatch(line []byte) { if ch != nil { ch <- m } + case m.Method == "notifications/resources/updated" && c.updated != nil: + // Any resource: the spec lets it be one under the one subscribed. + select { + case c.updated <- struct{}{}: + default: + } } } @@ -185,7 +328,7 @@ func (c *stdioConn) write(m rpcMsg) error { c.mu.Lock() defer c.mu.Unlock() if c.stdin == nil { - return errors.New("not running") + return errNotRunning } _, err = c.stdin.Write(append(data, '\n')) return err @@ -197,7 +340,7 @@ func (c *stdioConn) call(ctx context.Context, method string, params any) (json.R c.mu.Lock() if c.stdin == nil { c.mu.Unlock() - return nil, errors.New("not running") + return nil, errNotRunning } c.pending[id] = ch c.mu.Unlock() @@ -208,7 +351,7 @@ func (c *stdioConn) call(ctx context.Context, method string, params any) (json.R select { case m, ok := <-ch: if !ok { - return nil, errors.New("server exited") + return nil, errExited } if m.Error != nil { return nil, m.Error diff --git a/internal/features/mcp/corpus.go b/internal/features/mcp/corpus.go new file mode 100644 index 0000000..50be42b --- /dev/null +++ b/internal/features/mcp/corpus.go @@ -0,0 +1,239 @@ +package mcp + +import "regexp" + +// ordinary reports whether re matches nothing at all, or any of a list of +// ordinary chat lines: a pattern that does would turn a watch into a feed +// of the chat, so it is refused. +func ordinary(re *regexp.Regexp) bool { + if re.MatchString("") { + return true + } + for _, line := range chatter { + if re.MatchString(line) { + return true + } + } + return false +} + +// chatter is ordinary things people write in a group chat: short and long, +// questions, plans, times, prices, numbers, emoji and links to everyday +// sites. A watch is for something specific, such as a map link, so it +// matches none of these. +var chatter = []string{ + "lol", + "haha", + "hahaha that's great", + "ok", + "OK!", + "k", + "yes", + "no", + "nope", + "yep", + "sure", + "thanks", + "thank you so much!", + "ty", + "np", + "👍", + "😂😂😂", + "❤️", + "🎉🎉", + "good morning", + "morning all", + "good night everyone", + "night", + "hi", + "hey", + "hello!", + "hey, how's it going?", + "what's up", + "not much, you?", + "see you at 5", + "see you at 5pm", + "see you tomorrow", + "see you soon", + "I'll be there in 10 minutes", + "running 5 min late, sorry", + "on my way", + "omw", + "just got home", + "leaving now", + "where are you?", + "I'm at the station", + "at the shops, need anything?", + "can you grab milk on the way home?", + "we're out of bread", + "what's for dinner?", + "pasta tonight", + "pizza?", + "let's get takeaway", + "dinner's ready", + "lunch at 12:30?", + "meet at 1pm", + "the meeting moved to 3:15", + "it starts at 19:00", + "train leaves at 7.45", + "back by 6", + "is anyone free on Saturday?", + "I'm free Sunday afternoon", + "can't make it, sorry", + "count me in", + "I'm in", + "maybe next week", + "let's do Friday", + "how about the 14th?", + "my birthday is on 3/4", + "party on 12/05/2026", + "happy birthday!! 🎂", + "happy new year!", + "congrats!", + "well done", + "that's amazing", + "wow", + "no way", + "seriously?", + "really?", + "I know right", + "same", + "me too", + "agreed", + "fair enough", + "good point", + "I don't think so", + "not sure tbh", + "idk", + "brb", + "gtg", + "ttyl", + "call me when you can", + "can I call you later?", + "missed your call", + "sorry, was in a meeting", + "busy day", + "so tired today", + "long week", + "finally Friday", + "Monday again 😩", + "it's raining again", + "so hot today, 34 degrees", + "it's freezing, -2 this morning", + "nice weather for a walk", + "anyone up for a walk?", + "going for a run", + "did 5km this morning", + "gym later?", + "I'm sick, staying home", + "feel better soon!", + "hope you're ok", + "how's the new job?", + "how was the trip?", + "we just landed", + "flight is delayed by 2 hours", + "gate 23", + "seat 14C", + "the bus is late", + "traffic is terrible", + "parking is a nightmare", + "it costs $12.50", + "that's €4,99", + "only £3.20 at the market", + "I paid 45.00 for it", + "it was 1,250 dollars", + "split it 3 ways: 18.40 each", + "I owe you 20", + "sent you the money", + "price went up 2.5%", + "version 1.2.3 is out", + "update to 17.4 fixed it", + "my phone is at 3%", + "the score was 2-1", + "we won 3 to 0", + "what a game!", + "did you see the match last night?", + "who's watching tonight?", + "new episode is out", + "have you seen it yet?", + "no spoilers please", + "just finished the book", + "any recommendations?", + "check this out https://www.bbc.co.uk/news/articles/world-12345678", + "https://www.nytimes.com/2026/11/19/technology/phones.html", + "https://www.youtube.com/watch?v=dQw4w9WgXcQ", + "https://en.wikipedia.org/wiki/Melbourne", + "look at this https://www.reddit.com/r/aww/comments/abc123/cute_dog/", + "https://github.com/robdevops/signalbot/pull/42", + "www.example.com/recipes/lasagne", + "read this: theguardian.com/world/2026/nov/19/story", + "the recipe is on page 42", + "room 101", + "call 0412 345 678", + "my number is +61 400 000 000", + "the code is 4821", + "order #55123 has shipped", + "tracking number AB123456789AU", + "the wifi password is on the fridge", + "did you lock the door?", + "I left my keys at yours", + "can you feed the cat?", + "the dog needs a walk", + "kids are asleep", + "school pickup at 3", + "homework done?", + "who's driving?", + "I can drive", + "need a lift?", + "thanks for the lift!", + "it's at 12 Main Street", + "meet at the corner of 5th and Pine", + "the cafe on the left", + "near the park", + "we're in the back room", + "photos from today", + "great photo!", + "you look great", + "love this", + "so cute", + "that's hilarious", + "I can't stop laughing", + "ugh", + "oh no", + "oops", + "my bad", + "no worries", + "all good", + "sounds good", + "sounds like a plan", + "perfect", + "great, see you then", + "don't forget the tickets", + "tickets are 2 for 1 this week", + "half price on Tuesday", + "I'll bring dessert", + "bring a jacket", + "what time works for everyone?", + "10 or 11?", + "either works", + "let me check and get back to you", + "will do", + "done", + "noted", + "good luck tomorrow!", + "fingers crossed 🤞", + "how did it go?", + "it went well", + "nailed it", + "@Alice what do you think?", + "@Bob are you coming?", + "Alice said she'd be late", + "Bob is bringing chips", + "ask Bob", + "can someone add Alice to the group?", + "welcome to the group!", + "who changed the group name? 😂", + "muting this chat for a bit", + "sorry for the spam", + "wrong chat, ignore", +} diff --git a/internal/features/mcp/direct.go b/internal/features/mcp/direct.go new file mode 100644 index 0000000..b1fe02c --- /dev/null +++ b/internal/features/mcp/direct.go @@ -0,0 +1,134 @@ +package mcp + +import ( + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "strings" + "time" + + "github.com/robdevops/signalbot/internal/feature" + "github.com/robdevops/signalbot/internal/kit/img" + "github.com/robdevops/signalbot/internal/kit/logx" + "github.com/robdevops/signalbot/internal/kit/txt" +) + +const ( + // maxDirect is how many direct calls may be in flight on one server; a + // command past them is told the addon is busy, so a slow addon can't + // take every slot. + maxDirect = 2 + // maxAnswer caps a direct command's answer, in runes. + maxAnswer = 4000 + // An addon's answer or post has at most maxAddonPictures pictures, of + // at most maxPictureBytes in all. + maxAddonPictures = 2 + maxPictureBytes = 2 << 20 +) + +// directTimeout is how long a direct call may take, short of callTimeout so +// a hung addon can't hold a message's slot long; tests shorten it. +var directTimeout = 15 * time.Second + +// direct answers /name in m by calling the addon's tool itself, with args +// and m's context: the result's text and pictures, sent without the model. +// A failure is told in words for people; the server's own text is never +// shown or logged. +func (a *addon) direct(ctx context.Context, m feature.Message, name, tool, args string) feature.Action { + if !a.allows(m.Chat) { + return feature.Action{Answer: "/" + name + " isn't available in this chat."} + } + select { + case a.busy <- struct{}{}: + defer func() { <-a.busy }() + default: + logx.Warnf("MCP server %s: /%s refused: %d calls already in flight", a.server, name, maxDirect) + return feature.Action{Answer: a.title + " is busy, try again in a moment."} + } + a.lease(m.Chat) + ctx, cancel := context.WithTimeout(ctx, directTimeout) + defer cancel() + start := time.Now() + res, err := a.conn.call(ctx, "tools/call", map[string]any{ + "name": tool, + "arguments": map[string]string{"args": args}, + "_meta": map[string]any{vendor + "context": a.context(m, a.now())}, + }) + var r toolResult + outcome := "ok" + switch { + case err != nil: + outcome = errCode(err) + case json.Unmarshal(res, &r) != nil: + outcome = "a malformed result" + case r.IsError: + outcome = "an error result" + } + logx.Infof("MCP server %s: /%s called %s: %s in %dms, %d bytes", a.server, name, tool, outcome, time.Since(start).Milliseconds(), len(res)) + if outcome != "ok" { + return feature.Action{Answer: a.title + " couldn't do that just now."} + } + act := a.action(m.Chat, r) + if r.Meta.Watch != nil { + if w := a.watch(m, *r.Meta.Watch); w != nil && len(act.Pictures) > 0 { + act.OnSent = func(sent []int64) { a.guarding(w, sent) } + } + } + if act.IsZero() { + act.Done = true // nothing to say: still the addon's, not the model's + } + return act +} + +// action is what a direct call's result says in chat: its text, with +// placeholders filled in, and its images made safe. +func (a *addon) action(chat feature.Chat, r toolResult) feature.Action { + var parts, images []string + for _, p := range r.Content { + switch p.Type { + case "text": + parts = append(parts, p.Text) + case "image": + images = append(images, p.Data) + } + } + text := strings.TrimSpace(strings.Join(parts, "\n")) + return feature.Action{Answer: txt.Clamp(a.fill(chat, text), maxAnswer), Pictures: a.pictures(images)} +} + +// pictures are images, in base64, made safe: at most maxAddonPictures, of +// at most maxPictureBytes in all. Those left out are counted in the log. +func (a *addon) pictures(images []string) []feature.Picture { + var pics []feature.Picture + total, left := 0, 0 + for _, b64 := range images { + data, err := base64.StdEncoding.DecodeString(b64) + if err == nil { + data, err = img.Safe(data) + } + if err != nil || len(pics) == maxAddonPictures || total+len(data) > maxPictureBytes { + left++ + continue + } + total += len(data) + pics = append(pics, feature.Picture{Data: data}) + } + if left > 0 { + logx.Warnf("MCP server %s: %d images left out: not images, or past %d images or %d MB", a.server, left, maxAddonPictures, maxPictureBytes>>20) + } + return pics +} + +// errCode says what went wrong with a call for the log: an error's code, +// never a server's text. +func errCode(err error) string { + if re, ok := errors.AsType[*rpcError](err); ok { + return fmt.Sprintf("rpc error %d", re.Code) + } + if errors.Is(err, context.DeadlineExceeded) { + return "no answer in time" + } + return err.Error() +} diff --git a/internal/features/mcp/keep.go b/internal/features/mcp/keep.go new file mode 100644 index 0000000..948aa7c --- /dev/null +++ b/internal/features/mcp/keep.go @@ -0,0 +1,179 @@ +package mcp + +import ( + "cmp" + "context" + "maps" + "regexp" + "slices" + "strings" + + "github.com/robdevops/signalbot/internal/feature" + "github.com/robdevops/signalbot/internal/kit/logx" +) + +// maxApplied is how many of an addon's last op IDs are kept, so an op read +// again is never applied twice. +const maxApplied = 1000 + +// addonState is what is saved of an addon: its live watches, the messages +// they took, the chats it may post in, and how far its outbox was read. +type addonState struct { + Watches []watch `json:"watches,omitempty"` + Claims []claim `json:"claims,omitempty"` + Leases map[string]lease `json:"leases,omitempty"` // by chat pseudonym + Cursor string `json:"cursor,omitempty"` + Applied []string `json:"applied,omitempty"` // oldest first +} + +// keeper keeps the mcp store's document: the pseudonyms' secret and each +// addon's state. One goroutine saves it, whenever told something changed, +// so a message's hook never waits on the disk, and a burst of changes is +// one write. +type keeper struct { + store feature.Store + doc saved // as loaded; an addon not running this time keeps its state here + addons []*addon // running, set before run starts + dirty chan struct{} // something changed +} + +// newKeeper keeps doc, as loaded from store, for the addon servers named +// in servers; the state of any other is dropped at the first save. +func newKeeper(store feature.Store, doc saved, servers map[string]server) *keeper { + maps.DeleteFunc(doc.Addons, func(name string, _ addonState) bool { return servers[name].Addon == nil }) + return &keeper{store: store, doc: doc, dirty: make(chan struct{}, 1)} +} + +// changed marks the document changed, without waiting. +func (k *keeper) changed() { + select { + case k.dirty <- struct{}{}: + default: + } +} + +// run saves the document each time it changes, and once more when ctx +// ends. A failed save is logged once, until one succeeds; the state stays +// in memory, and the next change tries again. +func (k *keeper) run(ctx context.Context) { + failing := false + for { + var end bool + select { + case <-ctx.Done(): + end = true + case <-k.dirty: + } + doc := saved{Secret: k.doc.Secret, Addons: maps.Clone(k.doc.Addons)} + if doc.Addons == nil { + doc.Addons = map[string]addonState{} + } + for _, a := range k.addons { + doc.Addons[a.server] = a.state() + } + switch err := k.store.Save(doc); { + case err != nil && !failing: + logx.Warnf("addon state not saved, kept in memory until a save works: %v", err) + failing = true + case err == nil: + failing = false + } + if end { + return + } + } +} + +// state is what is saved of the addon, without anything expired, which it +// forgets. +func (a *addon) state() addonState { + now := a.now() + a.mu.Lock() + defer a.mu.Unlock() + s := addonState{Leases: map[string]lease{}, Cursor: a.cursor, Applied: slices.Clone(a.applied)} + for key, ws := range a.watches { + ws = slices.DeleteFunc(ws, func(w *watch) bool { return !now.Before(w.Until) }) + if len(ws) == 0 { + delete(a.watches, key) + continue + } + a.watches[key] = ws + for _, w := range ws { + c := *w + c.Pictures = slices.Clone(w.Pictures) + s.Watches = append(s.Watches, c) + } + } + for k, c := range a.claims { + if !now.Before(c.Expires) { + delete(a.claims, k) + continue + } + s.Claims = append(s.Claims, c) + } + for id, l := range a.leases { + if !now.Before(l.Expires) { + delete(a.leases, id) + continue + } + s.Leases[id] = l + } + for id, t := range a.tombs { + if !now.Before(t) { + delete(a.tombs, id) + } + } + // In a fixed order, so an unchanged state saves the same. + slices.SortFunc(s.Watches, func(x, y watch) int { + return cmp.Or(x.Until.Compare(y.Until), strings.Compare(x.Chat, y.Chat), strings.Compare(x.ID, y.ID)) + }) + slices.SortFunc(s.Claims, func(x, y claim) int { return x.Expires.Compare(y.Expires) }) + return s +} + +// restore takes up s, as saved, leaving out what has expired, and a watch +// in a chat the addon is no longer allowed in or whose pattern no longer +// passes. +func (a *addon) restore(s addonState) { + now := a.now() + a.mu.Lock() + defer a.mu.Unlock() + for id, l := range s.Leases { + if now.Before(l.Expires) { + a.leases[id] = l + } + } + for _, c := range s.Claims { + if now.Before(c.Expires) { + a.claims[c.claimKey] = c + } + } + for _, w := range s.Watches { + l, ok := a.leases[w.Chat] + re, err := regexp.Compile(w.Pattern) + if !ok || !now.Before(w.Until) || !a.allows(l.Chat) || err != nil || len(w.Pattern) > maxPattern || ordinary(re) || + len(a.watches[l.Chat.Key()]) >= maxWatches { + continue + } + w.key, w.re = l.Chat.Key(), re + a.watches[w.key] = append(a.watches[w.key], &w) + } + a.cursor = s.Cursor + for _, id := range s.Applied[max(len(s.Applied)-maxApplied, 0):] { + a.remember(id) + } +} + +// remember records that the op with id was applied, forgetting the oldest +// past maxApplied. a.mu is held. +func (a *addon) remember(id string) { + if a.done[id] { + return + } + a.done[id] = true + a.applied = append(a.applied, id) + if len(a.applied) > maxApplied { + delete(a.done, a.applied[0]) + a.applied = slices.Delete(a.applied, 0, 1) + } +} diff --git a/internal/features/mcp/mcp.go b/internal/features/mcp/mcp.go index 43c0c65..9228ca8 100644 --- a/internal/features/mcp/mcp.go +++ b/internal/features/mcp/mcp.go @@ -1,5 +1,8 @@ // Package mcp offers the model the tools of the MCP servers in MCP_CONFIG, -// one tool group per server, and turns them into chat commands. +// one tool group per server, and turns them into chat commands. A local +// server with an "addon" block that speaks signalbot's extension is an +// addon: the bot calls its tools itself, for direct commands, and it never +// learns who anyone is, only pseudonyms. package mcp import ( @@ -47,15 +50,18 @@ type server struct { ChatCommands map[string]chatCommand `json:"chat_commands"` Instructions *string `json:"instructions"` // a system-prompt line while its tools are offered; unset: the server's own, "": none Keywords []string `json:"keywords"` // if set, its tools are offered only when a message has one of these words + Addon *addonConfig `json:"addon"` // set for an addon } -// chatCommand makes "/name ..." a turn in which the model must call tool. +// chatCommand makes "/name ..." a turn in which the model must call tool, +// or, if direct, an addon's tool the bot calls itself, without the model. // With require_arg, a bare "/name" is answered by the bot, not the model, // showing example if set. type chatCommand struct { Tool string `json:"tool"` RequireArg bool `json:"require_arg"` Example string `json:"example"` + Direct bool `json:"direct"` } // settings are the keys a server may have, and commandSettings a chat @@ -63,8 +69,8 @@ type chatCommand struct { // MCP clients write that the bot has no use for, so a pasted entry starts. var ( settings = []string{"url", "headers", "command", "args", "env", "allowed_tools", "blocked_tools", - "instructions", "keywords", "chat_commands", "disabled"} - commandSettings = []string{"tool", "require_arg", "example"} + "instructions", "keywords", "chat_commands", "disabled", "addon"} + commandSettings = []string{"tool", "require_arg", "example", "direct"} ignored = []string{"type", "transport", "timeout", "alwaysAllow", "autoApprove", "description"} ) @@ -75,24 +81,60 @@ var unsafeToolChars = regexp.MustCompile(`[^A-Za-z0-9_-]`) var envPattern = regexp.MustCompile(`\$\{([A-Za-z_][A-Za-z0-9_]*)\}`) // Register starts the servers in MCP_CONFIG, if set, and offers their tools -// on h. They run as long as the bot: when it stops, local servers get -// SIGTERM and the bot waits for them. With no model, none is started. +// on h. They run as long as the bot: when it stops, local servers have +// their stdin closed, then get SIGTERM, then SIGKILL, and the bot waits for +// them. With no model, only addons are started. With an addon, the +// pseudonyms' secret and each addon's watches, claims, leases and outbox +// cursor are kept in the "mcp" store; if it can't be opened, addons run as +// plain servers. func Register(h feature.Host) error { path := h.Env("MCP_CONFIG", "") if path == "" { return nil } - if h.Info().Model == "" { - logx.Warnf("MCP_CONFIG is set but no model is configured, so MCP servers were not started") - return nil - } servers, err := load(path) if err != nil { return err } + if h.Info().Model == "" { + logx.Warnf("MCP_CONFIG is set but no model is configured, so only addon servers were started") + maps.DeleteFunc(servers, func(_ string, s server) bool { return s.Addon == nil }) + } + addons := false + for _, s := range servers { + addons = addons || s.Addon != nil + } + var k *keeper + if addons { // so MCP without addons needs no state directory + store, err := h.Store("mcp") + var doc saved + if err == nil { + doc, err = loadSaved(store) + } + if err != nil { + logx.Errorf("addon features are off: the pseudonyms' secret can't be kept: %v", err) + } else { + k = newKeeper(store, doc, servers) + } + } ctx, cancel := context.WithCancel(context.Background()) h.Go(func(life context.Context) { <-life.Done(); cancel() }) - return start(ctx, h, path, servers) + if err := start(ctx, h, path, servers, k); err != nil { + return err + } + if k != nil && len(k.addons) > 0 { + // After the chat commands, so a command is never a watch's. + h.OnMessage(func(_ context.Context, m feature.Message) feature.Action { + for _, a := range k.addons { + if act := a.claim(m); !act.IsZero() { + return act + } + } + return feature.Action{} + }) + h.Go(k.run) + } + return nil } func load(path string) (map[string]server, error) { @@ -140,6 +182,9 @@ func load(path string) (map[string]server, error) { if err := unknown(c, commandSettings); err != nil { return nil, bad("chat command %q: %v", txt.Clamp(n, 40), err) } + if s.ChatCommands[n].Direct && s.Addon == nil { + return nil, bad("chat command %q is direct, which needs an addon block", txt.Clamp(n, 40)) + } } switch { case (s.URL == "") == (s.Command == ""): @@ -147,6 +192,16 @@ func load(path string) (map[string]server, error) { case s.AllowedTools != nil && s.BlockedTools != nil: return nil, bad("has both allowed_tools and blocked_tools; use one") } + if s.Addon != nil { + var entry map[string]json.RawMessage + json.Unmarshal(raw.Servers[name]["addon"], &entry) + if err := s.Addon.check(entry); err != nil { + return nil, bad("%v", err) + } + if err := checkAddonServer(name, s); err != nil { + return nil, bad("%v", err) + } + } if err := s.expand(); err != nil { return nil, bad("%v", err) } @@ -198,22 +253,49 @@ func (s *server) expand() (err error) { // maxInstructions caps a server's own instructions in the system prompt. const maxInstructions = 1000 -// initialize performs the MCP handshake, as the bot's version, and returns -// the instructions the server sent, if any. -func initialize(ctx context.Context, c conn, version string) (string, error) { +// handshake is what a server says of itself in the MCP handshake. +type handshake struct { + instructions string + title string // its name for people, its title or else its name; "" if neither + addon bool // it speaks signalbot's extension, at the bot's version + subscribe bool // it takes resource subscriptions +} + +// initialize performs the MCP handshake, as the bot's version, offering +// signalbot's extension, and returns what the server said of itself. +func initialize(ctx context.Context, c conn, version string) (handshake, error) { res, err := c.call(ctx, "initialize", map[string]any{ "protocolVersion": protocol, - "capabilities": map[string]any{}, + "capabilities": map[string]any{"experimental": map[string]any{vendor + "addon": map[string]int{"version": addonVersion}}}, "clientInfo": map[string]string{"name": "signalbot", "version": version}, }) if err != nil { - return "", err + return handshake{}, err } var r struct { Instructions string `json:"instructions"` - } - json.Unmarshal(res, &r) // instructions are optional; a bad result shows up in tools/list - return strings.TrimSpace(r.Instructions), c.notify(ctx, "notifications/initialized", nil) + ServerInfo struct { + Name string `json:"name"` + Title string `json:"title"` + } `json:"serverInfo"` + Capabilities struct { + Experimental map[string]json.RawMessage `json:"experimental"` + Resources struct { + Subscribe bool `json:"subscribe"` + } `json:"resources"` + } `json:"capabilities"` + } + json.Unmarshal(res, &r) // all optional; a bad result shows up in tools/list + var ext struct { + Version int `json:"version"` + } + addon := json.Unmarshal(r.Capabilities.Experimental[vendor+"addon"], &ext) == nil && ext.Version == addonVersion + return handshake{ + instructions: strings.TrimSpace(r.Instructions), + title: txt.SafeName(cmp.Or(r.ServerInfo.Title, r.ServerInfo.Name)), + addon: addon, + subscribe: r.Capabilities.Resources.Subscribe, + }, c.notify(ctx, "notifications/initialized", nil) } // tool is a tool as a server lists it. @@ -221,8 +303,25 @@ type tool struct { Name string `json:"name"` Description string `json:"description"` Schema json.RawMessage `json:"inputSchema"` + Meta struct { + Visibility []string `json:"io.github.robdevops.signalbot/visibility"` // nil: ["model"] + UI struct { + Visibility []string `json:"visibility"` // MCP Apps'; nil: ["model", "app"] + } `json:"ui"` + } `json:"_meta"` +} + +// forModel reports whether the tool may be offered to the model: neither +// signalbot's visibility nor MCP Apps' leaves the model out. +func (t tool) forModel() bool { + return (t.Meta.Visibility == nil || slices.Contains(t.Meta.Visibility, "model")) && + (t.Meta.UI.Visibility == nil || slices.Contains(t.Meta.UI.Visibility, "model")) } +// forBot reports whether the bot may call the tool itself: only if +// signalbot's visibility says so (MCP Apps' "app" is a UI's, not the bot's). +func (t tool) forBot() bool { return slices.Contains(t.Meta.Visibility, "bot") } + // modelName is the name the model sees for a server's tool. func modelName(server, tool string) string { n := unsafeToolChars.ReplaceAllString(server, "_") + "__" + unsafeToolChars.ReplaceAllString(tool, "_") @@ -230,15 +329,17 @@ func modelName(server, tool string) string { } // start connects to every server, in name order, and offers each one's -// tools that its allowed_tools and blocked_tools let through as a tool -// group, named by those tools and then its chat commands. A server that -// cannot be reached is logged and left out. A tool named in either list -// that a reachable server does not have, or two tools that end up with the -// same name, is an error starting with the file's path: a typo in -// blocked_tools would otherwise leave the tool offered. Local servers are -// stopped when ctx ends, and the bot waits for them. While the model can't -// call tools, no command is registered. -func start(ctx context.Context, h feature.Host, path string, servers map[string]server) error { +// tools that its allowed_tools and blocked_tools let through, and that are +// for the model, as a tool group, named by those tools and then its chat +// commands. A server that cannot be reached is logged and left out. A tool +// named in either list that a reachable server does not have, or two tools +// that end up with the same name, is an error starting with the file's +// path: a typo in blocked_tools would otherwise leave the tool offered. +// Local servers are stopped when ctx ends, and the bot waits for them. +// While the model can't call tools, only direct commands are registered; +// with no model, no tools are offered. k keeps the addons' state, nil to +// run addons as plain servers; each addon started joins it. +func start(ctx context.Context, h feature.Host, path string, servers map[string]server, k *keeper) error { info := h.Info() version := cmp.Or(info.Version, "dev") type owner struct{ server, tool string } @@ -248,11 +349,15 @@ func start(ctx context.Context, h feature.Host, path string, servers map[string] cfg := servers[name] var c conn = &httpConn{url: cfg.URL, headers: cfg.Headers, client: httpx.Client(2), version: version} if cfg.Command != "" { - c = &stdioConn{name: name, cfg: cfg, version: version, redact: h.Redact} + s := &stdioConn{name: name, cfg: cfg, version: version, redact: h.Redact} + if cfg.Addon != nil { + s.prefix, s.updated = envPrefix(name), make(chan struct{}, 1) + } + c = s } - listed, sent, err := connect(ctx, c, version) + listed, hs, err := connect(ctx, c, version) if err != nil { - logx.Errorf("MCP server %s unavailable, its tools are left out: %v", name, err) + logx.Errorf("MCP server %s unavailable, its tools are left out: %s", name, describe(err, cfg.Addon != nil)) continue } for list, names := range map[string][]string{"allowed_tools": cfg.AllowedTools, "blocked_tools": cfg.BlockedTools} { @@ -263,13 +368,31 @@ func start(ctx context.Context, h feature.Host, path string, servers map[string] } } } + var a *addon + switch { + case cfg.Addon == nil: + case !hs.addon: + logx.Warnf("MCP server %s has an addon block but doesn't speak signalbot's addon extension (version %d), so it runs as a plain server", name, addonVersion) + case k != nil: + bot := map[string]bool{} + for _, t := range listed { + if t.forBot() { + bot[t.Name] = true + } + } + a = newAddon(name, cmp.Or(hs.title, name), *cfg.Addon, k.doc.Secret, c, bot) + a.host, a.changed, a.dirty = h, k.changed, c.(*stdioConn).updated + a.restore(k.doc.Addons[name]) + k.addons = append(k.addons, a) + } g := feature.ToolGroup{ - System: instructions(cfg.Instructions, sent), + System: instructions(cfg.Instructions, hs.instructions), Keywords: keywords(cfg.Keywords), } models := map[string]string{} // the model's name for each offered tool, by the server's for _, t := range listed { - if cfg.AllowedTools != nil && !slices.Contains(cfg.AllowedTools, t.Name) || slices.Contains(cfg.BlockedTools, t.Name) { + if info.Model == "" || !t.forModel() || + cfg.AllowedTools != nil && !slices.Contains(cfg.AllowedTools, t.Name) || slices.Contains(cfg.BlockedTools, t.Name) { continue } model := modelName(name, t.Name) @@ -294,22 +417,39 @@ func start(ctx context.Context, h feature.Host, path string, servers map[string] if len(g.Names) > 0 { // before its commands join them: one line per server logx.Noticef("%s: %s", label, strings.Join(g.Names, ", ")) } - if !info.CallsTools { - cfg.ChatCommands = nil // a command would force a tool the model can't call + if a != nil { + logx.Noticef("%s: an addon, with tools for the bot: %s", label, cmp.Or(strings.Join(slices.Sorted(maps.Keys(a.bot)), ", "), "none")) } var own []string // its chat commands, as "/name" for _, n := range slices.Sorted(maps.Keys(cfg.ChatCommands)) { - if cmd := command(h, name, n, cfg.ChatCommands[n], models); cmd != "" { + cc := cfg.ChatCommands[n] + if !cc.Direct && !info.CallsTools { + continue // a command would force a tool the model can't call + } + if cmd := command(h, name, n, cc, models, a); cmd != "" { own = append(own, cmd) } } slices.Sort(own) cmds = append(cmds, own...) - if len(g.Tools) > 0 { + switch { + case len(g.Tools) > 0: all := strings.Join(append(g.Names, own...), ", ") g.Listing = name + ": " + all g.Names = []string{"**" + label + "**: " + all} // grouped by server in {tools}, in Markdown h.OfferTools(g) + case len(own) > 0: // no group to list them in + var bare []string + for _, cmd := range own { + bare = append(bare, strings.TrimPrefix(cmd, "/")) + } + h.ListCommands(label, bare...) + } + if a != nil { + c.(*stdioConn).ready = a.ready + a.ready(ctx, hs) + h.Go(a.work) + h.Go(a.readOutbox) } if s, ok := c.(*stdioConn); ok { h.Go(func(context.Context) { s.supervise(ctx) }) @@ -321,6 +461,15 @@ func start(ctx context.Context, h feature.Host, path string, servers map[string] return nil } +// describe is err for the log: for an addon, only its code, never the +// server's own text. +func describe(err error, addon bool) string { + if addon { + return errCode(err) + } + return err.Error() +} + // toolList names a server's tools, the first 20 and then "…". func toolList(tools []tool) string { var names []string @@ -358,12 +507,21 @@ func keywords(words []string) *regexp.Regexp { } // command registers chat command n of a server on h and returns it as -// "/name". One that can't be used (a tool the model isn't offered, or a bad -// or taken name) is logged and skipped, returning "". -func command(h feature.Host, server, n string, c chatCommand, models map[string]string) string { +// "/name". A direct one calls a tool of a, the server as an addon, that the +// bot may call; any other has the model call a tool it is offered. One that +// can't be used (such a tool missing, or a bad or taken name) is logged and +// skipped, returning "". +func command(h feature.Host, server, n string, c chatCommand, models map[string]string, a *addon) string { name := strings.ToLower(strings.TrimPrefix(n, "/")) model, offered := models[c.Tool] - if !offered { + switch { + case c.Direct && a == nil: + logx.Warnf("MCP server %s: chat command /%s is direct, but the server's addon features are off; skipped", server, txt.Clamp(name, 40)) + return "" + case c.Direct && !a.bot[c.Tool]: + logx.Warnf("MCP server %s: chat command /%s names tool %q, which the bot may not call; skipped", server, txt.Clamp(name, 40), txt.Clamp(c.Tool, 64)) + return "" + case !c.Direct && !offered: logx.Warnf("MCP server %s: chat command /%s names tool %q, which isn't offered; skipped", server, txt.Clamp(name, 40), txt.Clamp(c.Tool, 64)) return "" } @@ -371,10 +529,15 @@ func command(h feature.Host, server, n string, c chatCommand, models map[string] if ex := strings.TrimRight(strings.TrimSpace(c.Example), "."); ex != "" { bare += " Try: " + ex + "." } - bare += " Or just ask me in plain words." - err := h.Command(name, func(_ context.Context, m feature.Message, args string) feature.Action { - if c.RequireArg && args == "" { + if !c.Direct { + bare += " Or just ask me in plain words." + } + err := h.Command(name, func(ctx context.Context, m feature.Message, args string) feature.Action { + switch { + case c.RequireArg && args == "": return feature.Action{Answer: bare} + case c.Direct: + return a.direct(ctx, m, name, c.Tool, args) } return feature.Action{ToolChoice: model} }) @@ -385,18 +548,19 @@ func command(h feature.Host, server, n string, c chatCommand, models map[string] return "/" + name } -// connect starts the server, initializes it, and lists its tools by name. -func connect(ctx context.Context, c conn, version string) ([]tool, string, error) { +// connect starts the server, initializes it, and lists its tools by name, +// all of them, whoever they are for. +func connect(ctx context.Context, c conn, version string) ([]tool, handshake, error) { ctx2, cancel := context.WithTimeout(ctx, callTimeout) defer cancel() if s, ok := c.(*stdioConn); ok { if err := s.start(ctx); err != nil { - return nil, "", err + return nil, handshake{}, err } } - own, err := initialize(ctx2, c, version) + hs, err := initialize(ctx2, c, version) if err != nil { - return nil, "", err + return nil, handshake{}, err } var tools []tool cursor := "" @@ -407,19 +571,19 @@ func connect(ctx context.Context, c conn, version string) ([]tool, string, error } res, err := c.call(ctx2, "tools/list", params) if err != nil { - return nil, "", err + return nil, handshake{}, err } var page struct { Tools []tool `json:"tools"` NextCursor string `json:"nextCursor"` } if err := json.Unmarshal(res, &page); err != nil { - return nil, "", fmt.Errorf("tools/list: %v", err) + return nil, handshake{}, fmt.Errorf("tools/list: %v", err) } tools = append(tools, page.Tools...) if cursor = page.NextCursor; cursor == "" { slices.SortFunc(tools, func(a, b tool) int { return strings.Compare(a.Name, b.Name) }) - return slices.CompactFunc(tools, func(a, b tool) bool { return a.Name == b.Name }), own, nil + return slices.CompactFunc(tools, func(a, b tool) bool { return a.Name == b.Name }), hs, nil } } } @@ -447,28 +611,25 @@ func call(ctx context.Context, c conn, name, arguments string) (string, []featur } return "error: the tool could not be reached", nil, err } - var r struct { - Content []struct { - Type string `json:"type"` - Text string `json:"text"` - Data string `json:"data"` // base64, for an image - MimeType string `json:"mimeType"` - } `json:"content"` - IsError bool `json:"isError"` - } + var r toolResult if json.Unmarshal(res, &r) != nil { return "error: the tool sent a malformed result", nil, errors.New("malformed result") } var parts []string var pics []feature.Picture for _, p := range r.Content { - switch data, err := base64.StdEncoding.DecodeString(p.Data); { - case p.Type == "text": + if p.Type == "text" { parts = append(parts, p.Text) - case p.Type == "image" && err == nil && img.Sendable(data) && len(pics) < feature.MaxPictures: + continue + } + data, err := base64.StdEncoding.DecodeString(p.Data) + if err == nil { + data, err = img.Safe(data) // its metadata, such as where a photo was taken, never sent + } + if p.Type == "image" && err == nil && img.Sendable(data) && len(pics) < feature.MaxPictures { pics = append(pics, feature.Picture{Data: data}) parts = append(parts, "[image sent to the chat]") - default: + } else { parts = append(parts, "[non-text content omitted]") } } @@ -478,3 +639,19 @@ func call(ctx context.Context, c conn, name, arguments string) (string, []featur } return out, pics, nil } + +// toolResult is a tools/call result. An addon's _meta may make a watch, +// for a direct command, or ask for a reaction, for a watch's call. +type toolResult struct { + Content []struct { + Type string `json:"type"` + Text string `json:"text"` + Data string `json:"data"` // base64, for an image + MimeType string `json:"mimeType"` + } `json:"content"` + IsError bool `json:"isError"` + Meta struct { + Watch *watchSpec `json:"io.github.robdevops.signalbot/watch"` + React string `json:"io.github.robdevops.signalbot/react"` // an emoji to put on the message + } `json:"_meta"` +} diff --git a/internal/features/mcp/mcp_test.go b/internal/features/mcp/mcp_test.go index 70f1dec..a7b0bad 100644 --- a/internal/features/mcp/mcp_test.go +++ b/internal/features/mcp/mcp_test.go @@ -177,7 +177,7 @@ func TestNoConfig(t *testing.T) { } } -// With no model, no server is started, and the log says so. +// With no model, no server but an addon is started, and the log says so. func TestNoModel(t *testing.T) { var started atomic.Bool srv := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { started.Store(true) })) @@ -186,7 +186,7 @@ func TestNoModel(t *testing.T) { if err != nil || len(h.ToolGroups()) != 0 || started.Load() { t.Fatalf("groups %+v, %v, started %v", h.ToolGroups(), err, started.Load()) } - if l := log.String(); l != "<4>MCP_CONFIG is set but no model is configured, so MCP servers were not started\n" { + if l := log.String(); l != "<4>MCP_CONFIG is set but no model is configured, so only addon servers were started\n" { t.Fatalf("log %q", l) } } @@ -248,8 +248,8 @@ func TestLoad(t *testing.T) { // settings it could be, and both lists at once too; keys other clients // write are ignored, so a pasted entry starts. for bad, want := range map[string]string{ - `{"mcpServers":{"w":{"url":"u","allowedTools":["t"]}}}`: `: MCP server "w": unknown setting "allowedTools" (settings are url, headers, command, args, env, allowed_tools, blocked_tools, instructions, keywords, chat_commands, disabled)`, - `{"mcpServers":{"w":{"url":"u","chat_commands":{"x":{"tool":"t","requireArg":true}}}}}`: `: MCP server "w": chat command "x": unknown setting "requireArg" (settings are tool, require_arg, example)`, + `{"mcpServers":{"w":{"url":"u","allowedTools":["t"]}}}`: `: MCP server "w": unknown setting "allowedTools" (settings are url, headers, command, args, env, allowed_tools, blocked_tools, instructions, keywords, chat_commands, disabled, addon)`, + `{"mcpServers":{"w":{"url":"u","chat_commands":{"x":{"tool":"t","requireArg":true}}}}}`: `: MCP server "w": chat command "x": unknown setting "requireArg" (settings are tool, require_arg, example, direct)`, `{"mcpServers":{"w":{"url":"u","allowed_tools":[],"blocked_tools":["t"]}}}`: `: MCP server "w": has both allowed_tools and blocked_tools; use one`, } { p := writeConfig(t, bad) @@ -479,12 +479,12 @@ func TestChatCommands(t *testing.T) { "echo what's up": {}, "/echoes whatever": {}, } { - if got := h.Message(ctx, dm(text)); got != want { + if got := h.Message(ctx, dm(text)); got.Answer != want.Answer || got.ToolChoice != want.ToolChoice || got.IsZero() != want.IsZero() { t.Errorf("%q: %+v, want %+v", text, got, want) } } group := feature.Message{Chat: feature.Chat{GroupID: "g"}, Sender: "bob", Name: "Bob", Text: "/echo hi"} - if got := h.Message(ctx, group); got != (feature.Action{}) { + if got := h.Message(ctx, group); !got.IsZero() { t.Errorf("unaddressed: %+v", got) } } @@ -501,7 +501,7 @@ func TestChatCommandsToolsOff(t *testing.T) { t.Fatalf("names %q, log %q", got, log.String()) } m := feature.Message{Chat: feature.Chat{User: "alice"}, Sender: "alice", Name: "Alice", Text: "/echo hi", Addressed: true} - if got := h.Message(context.Background(), m); got != (feature.Action{}) { + if got := h.Message(context.Background(), m); !got.IsZero() { t.Errorf("tools off: %+v", got) } } @@ -563,7 +563,7 @@ func TestStdio(t *testing.T) { if err := Register(h); err != nil { t.Fatal(err) } - defer h.Stop() // its stdin stays open, so this returns only once SIGTERM stops it + defer h.Stop() // its stdin is closed, and it exits if gs := h.ToolGroups(); len(gs) != 1 || gs[0].System != "Local files." { // the server's own instructions t.Fatalf("groups %+v", gs) } @@ -652,7 +652,7 @@ func TestCallFailures(t *testing.T) { } // examples/signalbot-mcp.json is the docs' example, as written there, and -// it loads: the disabled server is dropped, the other kept. +// it loads: the disabled server is dropped, the others kept, one an addon. func TestExampleFile(t *testing.T) { example, err := os.ReadFile("../../../examples/signalbot-mcp.json") if err != nil { @@ -667,7 +667,8 @@ func TestExampleFile(t *testing.T) { } t.Setenv("WEATHER_TOKEN", "x") s, err := load("../../../examples/signalbot-mcp.json") - if err != nil || len(s) != 1 || s["weather"].Headers["Authorization"] != "Bearer x" || s["weather"].ChatCommands["forecast"].Example == "" { + if err != nil || len(s) != 2 || s["weather"].Headers["Authorization"] != "Bearer x" || s["weather"].ChatCommands["forecast"].Example == "" || + s["geo"].Addon == nil || !s["geo"].Addon.Watch || !s["geo"].ChatCommands["geo"].Direct { t.Fatalf("loaded %+v, %v", s, err) } } diff --git a/internal/features/mcp/outbox.go b/internal/features/mcp/outbox.go new file mode 100644 index 0000000..bdfb6c7 --- /dev/null +++ b/internal/features/mcp/outbox.go @@ -0,0 +1,440 @@ +package mcp + +import ( + "cmp" + "context" + "encoding/json" + "errors" + "fmt" + "maps" + "slices" + "strings" + "time" + + "github.com/robdevops/signalbot/internal/feature" + "github.com/robdevops/signalbot/internal/kit/logx" + "github.com/robdevops/signalbot/internal/kit/txt" +) + +// outboxURI is the resource an addon queues its posts and other ops in. +// The bot subscribes to it, and reads outboxURI/<cursor> for the ops past +// cursor. +const outboxURI = "signalbot://outbox" + +// maxPages caps the pages of one outbox read, so an addon that always has +// more can't keep the reader. +const maxPages = 100 + +// Reading the outbox again: after a failed read, from retryDelay, doubling +// to maxRetryDelay while reads keep failing; a post dropped before it was +// sent is posted again after retryDelay, doubling, and given up after +// maxPostTries. Tests shorten retryDelay. +var retryDelay = 10 * time.Second + +const ( + maxRetryDelay = 5 * time.Minute + maxPostTries = 6 +) + +// ready subscribes to the addon's outbox, once it has started (again), if +// it takes subscriptions, then reads the outbox, for anything sent while +// the bot wasn't listening. +func (a *addon) ready(ctx context.Context, hs handshake) { + select { + case a.up <- struct{}{}: + default: + } + if !hs.subscribe { + logx.Warnf("MCP server %s takes no resource subscriptions, so its outbox is off", a.server) + return + } + ctx, cancel := context.WithTimeout(ctx, callTimeout) + defer cancel() + if _, err := a.conn.call(ctx, "resources/subscribe", map[string]string{"uri": outboxURI}); err != nil { + logx.Warnf("MCP server %s: subscribing to its outbox failed: %s", a.server, errCode(err)) + return + } + a.poke() +} + +// poke marks the outbox as having news, without waiting. +func (a *addon) poke() { + select { + case a.dirty <- struct{}{}: + default: + } +} + +// readOutbox reads the outbox each time it has news, and again a while +// after a read fails, until ctx ends. It is the addon's one reader, so two +// reads never race, and news that comes during a read is read after it. +func (a *addon) readOutbox(ctx context.Context) { + wait := retryDelay + var again <-chan time.Time + for { + select { + case <-ctx.Done(): + return + case <-a.dirty: + case <-again: + } + if a.drain(ctx) { + wait, again = retryDelay, nil + } else { + again = time.After(wait) + wait = min(wait*2, maxRetryDelay) + } + } +} + +// page is a page of an addon's outbox. +type page struct { + Cursor string `json:"cursor"` + More bool `json:"more"` + Ops []op `json:"ops"` +} + +// op is one thing an addon asks the bot to do. +type op struct { + ID string `json:"id"` + Op string `json:"op"` // post, react or unwatch + Chat string `json:"chat"` // a post's or unwatch's chat pseudonym + Text string `json:"text"` + Images []postImage `json:"images"` + Ref string `json:"ref"` // a reaction's message + Emoji string `json:"emoji"` + Watch string `json:"watch"` // the ID of the watch to end +} + +// postImage is an image in a post. +type postImage struct { + Data string `json:"data"` // base64 + MimeType string `json:"mimeType"` + Name string `json:"name"` +} + +// errNotFound is a resource the server doesn't have: -32002 in the +// 2025-06-18 spec and older SDKs, -32602 in the Go SDK. +func errNotFound(err error) bool { + re, ok := errors.AsType[*rpcError](err) + return ok && (re.Code == -32002 || re.Code == -32602) +} + +// drain reads the outbox page by page from the cursor until it has no +// more, applying each op not applied before, and reports whether it read +// it all. What is dropped is counted in one warning. +// +// Delivery is at least once: the cursor, which lets the addon forget the +// ops before it, moves past a post only once the post is sent. Until then +// a read starts from before it, and skips it while it waits; one dropped +// before it was sent, such as while the bot stops or before the network is +// up, is posted again by a later read. A page with more after it waits for +// its posts, since reading the next lets the addon forget them. +func (a *addon) drain(ctx context.Context) bool { + dropped := map[string]int{} + defer func() { + if len(dropped) == 0 { + return + } + var parts []string + n := 0 + for _, why := range slices.Sorted(maps.Keys(dropped)) { + parts = append(parts, fmt.Sprintf("%d %s", dropped[why], why)) + n += dropped[why] + } + unit := "ops" + if n == 1 { + unit = "op" + } + logx.Warnf("addon %s: dropped %d %s: %s", a.server, n, unit, strings.Join(parts, ", ")) + }() + a.mu.Lock() + a.next = "" // only this read's end may become the cursor + a.mu.Unlock() + for range maxPages { + a.mu.Lock() + cursor := cmp.Or(a.cursor, "0") + a.mu.Unlock() + rctx, cancel := context.WithTimeout(ctx, callTimeout) + res, err := a.conn.call(rctx, "resources/read", map[string]string{"uri": outboxURI + "/" + cursor}) + cancel() + var r struct { + Contents []struct { + Text string `json:"text"` + } `json:"contents"` + } + var p page + switch { + case errNotFound(err): + logx.Warnf("MCP server %s has no outbox to read", a.server) + return true + case err != nil: + logx.Warnf("MCP server %s: reading its outbox failed: %s", a.server, errCode(err)) + return false + case json.Unmarshal(res, &r) != nil || len(r.Contents) != 1 || json.Unmarshal([]byte(r.Contents[0].Text), &p) != nil: + logx.Warnf("MCP server %s: its outbox was malformed (%d bytes)", a.server, len(res)) + return false + } + a.mu.Lock() + a.missed = false // what was missed is read again now + a.mu.Unlock() + for _, o := range p.Ops { + if why := a.apply(o); why != "" { + dropped[why]++ + } + } + a.mu.Lock() + a.next = cmp.Or(p.Cursor, cursor) + a.settle() + a.mu.Unlock() + a.changed() + if !p.More { + return true + } + if !a.wait(ctx) { + return false + } + } + return false +} + +// wait waits until every post read from the outbox has been sent or +// dropped, and reports whether the cursor then moved past them. +func (a *addon) wait(ctx context.Context) bool { + for { + a.mu.Lock() + n, moved := len(a.sending), a.next == "" + a.mu.Unlock() + if n == 0 { + return moved + } + select { + case <-ctx.Done(): + return false + case <-a.settled: + } + } +} + +// settle moves the cursor to where the last read ended, once every post it +// read has been sent and none was missed. a.mu is held. +func (a *addon) settle() { + if len(a.sending) == 0 && !a.missed && a.next != "" { + a.cursor, a.next = a.next, "" + } +} + +// failure is a post op dropped before it was sent: how often, and when it +// may be posted again. +type failure struct { + tries int + retry time.Time +} + +// apply does what o asks, once, and returns why it was dropped, if it was. +// A post counts as applied only once it is sent. +func (a *addon) apply(o op) (why string) { + if o.ID == "" { + return "without an id" + } + now := a.now() + a.mu.Lock() + f, failed := a.failed[o.ID] + again := a.done[o.ID] || a.sending[o.ID] + switch { + case again: + case o.Op == "post" && failed && now.Before(f.retry): + again, a.missed = true, true // not yet: a later read posts it + case o.Op != "post": + a.remember(o.ID) + } + a.mu.Unlock() + if again { + return "" + } + switch o.Op { + case "post": + why = a.post(o, failed) + if why != "" { + a.mu.Lock() + a.remember(o.ID) + delete(a.failed, o.ID) + a.mu.Unlock() + } + return why + case "react": + if !a.cfg.React { + return "reactions not allowed" + } + a.mu.Lock() + r, ok := a.refs[o.Ref] + l, leased := a.leases[a.chatID(r.msg.Chat)] + a.mu.Unlock() + switch { + case !ok || !now.Before(r.expires): + return "reactions to an unknown message" + case !leased || !now.Before(l.Expires) || !a.allows(r.msg.Chat): + return "for a chat without a lease" + } + if why := a.react(r.msg, o.Emoji); why != "" { + return "reactions " + why + } + case "unwatch": + a.unwatch(o.Chat, o.Watch) + default: + return "of an unknown kind" + } + return "" +} + +// post posts o in its chat, if the addon may. One posted again, after it +// was dropped, isn't counted against the rate again. +func (a *addon) post(o op, again bool) (why string) { + now := a.now() + a.mu.Lock() + l, ok := a.leases[o.Chat] + a.mu.Unlock() + switch { + case !a.cfg.Post: + return "posts not allowed" + case !ok || !now.Before(l.Expires) || !a.allows(l.Chat): + return "for a chat without a lease" + } + var b64 []string + for _, im := range o.Images { + b64 = append(b64, im.Data) + } + out := &outgoing{Post: feature.Post{Chat: l.Chat, Label: a.title, Text: txt.Clamp(a.fill(l.Chat, strings.TrimSpace(o.Text)), maxAnswer), Pictures: a.pictures(b64)}, + ops: []string{o.ID}} + switch { + case out.Text == "" && len(out.Pictures) == 0: + return "empty posts" + case !again && !a.posts.allow(l.Chat.Key(), now): + return "posts over the rate limit" + } + a.send(o.Chat, out) + return "" +} + +// outgoing is a post of the addon's, and the ops it carries. +type outgoing struct { + feature.Post + ops []string +} + +// fits reports whether p's pictures can join o's in one post. +func (o *outgoing) fits(p *outgoing) bool { + size := 0 + for _, pic := range append(slices.Clone(o.Pictures), p.Pictures...) { + size += len(pic.Data) + } + return len(o.Pictures)+len(p.Pictures) <= maxAddonPictures && size <= maxPictureBytes +} + +// send posts out in the chat whose pseudonym is id, unless a post of the +// addon's still waits in that chat's mailbox: then out is held, merged with +// the last one held if their pictures fit in one post, and posted once +// those before it have gone. So an addon never takes more than one place in +// a chat's mailbox. +func (a *addon) send(id string, out *outgoing) { + a.mu.Lock() + for _, op := range out.ops { + a.sending[op] = true + } + if held, waiting := a.waiting[id]; waiting { + if n := len(held); n > 0 && held[n-1].fits(out) { + last := held[n-1] + last.Text = txt.Clamp(strings.TrimSpace(last.Text+"\n\n"+out.Text), maxAnswer) + last.Pictures = append(last.Pictures, out.Pictures...) + last.ops = append(last.ops, out.ops...) + } else { + a.waiting[id] = append(held, out) + } + a.mu.Unlock() + return + } + a.waiting[id] = nil + a.mu.Unlock() + a.mail(id, out) +} + +// mail puts out in its chat's mailbox. +func (a *addon) mail(id string, out *outgoing) { + p := out.Post + p.Done = func(_ []int64, dropped bool) { + a.sent(out.ops, !dropped) + a.mu.Lock() + held := a.waiting[id] + if len(held) == 0 { + delete(a.waiting, id) + } else { + a.waiting[id] = held[1:] + } + a.mu.Unlock() + if len(held) > 0 { + a.mail(id, held[0]) + } + } + a.host.Post(p) +} + +// sent records that the post carrying ops was sent, or dropped before it +// was: a dropped one is read and posted again later, until it has been +// tried maxPostTries times. +func (a *addon) sent(ops []string, ok bool) { + now := a.now() + given, retries := 0, map[time.Duration]bool{} + a.mu.Lock() + for _, id := range ops { + delete(a.sending, id) + f := a.failed[id] + switch { + case ok: + a.remember(id) + delete(a.failed, id) + case f.tries+1 >= maxPostTries: + a.remember(id) + delete(a.failed, id) + given++ + default: + retry := min(retryDelay<<f.tries, maxRetryDelay) + a.failed[id] = failure{f.tries + 1, now.Add(retry)} + a.missed, retries[retry] = true, true + } + } + a.settle() + settled := len(a.sending) == 0 + a.mu.Unlock() + a.changed() + if given > 0 { + logx.Warnf("addon %s: %d posts dropped: not sent after %d tries", a.server, given, maxPostTries) + } + for retry := range retries { + time.AfterFunc(retry, a.poke) + } + if settled { + select { + case a.settled <- struct{}{}: + default: + } + } +} + +// unwatch ends the watch called id in the chat whose pseudonym is chat; +// if it hasn't begun, it is ended before it does, for tombLife. +func (a *addon) unwatch(chat, id string) { + a.mu.Lock() + found := false + for key, ws := range a.watches { + a.watches[key] = slices.DeleteFunc(ws, func(w *watch) bool { + gone := w.Chat == chat && w.ID == id + found = found || gone + return gone + }) + } + if !found { + a.tombs[chat+"\x00"+id] = a.now().Add(tombLife) + } + a.mu.Unlock() + a.changed() +} diff --git a/internal/features/mcp/proc_other.go b/internal/features/mcp/proc_other.go new file mode 100644 index 0000000..d959d7b --- /dev/null +++ b/internal/features/mcp/proc_other.go @@ -0,0 +1,15 @@ +//go:build !unix + +package mcp + +import ( + "os" + "os/exec" + "syscall" +) + +// setGroup does nothing where there are no process groups. +func setGroup(*exec.Cmd) {} + +// signalGroup kills p, whatever sig is, where there are no process groups. +func signalGroup(p *os.Process, _ syscall.Signal) { p.Kill() } diff --git a/internal/features/mcp/proc_unix.go b/internal/features/mcp/proc_unix.go new file mode 100644 index 0000000..79b4d08 --- /dev/null +++ b/internal/features/mcp/proc_unix.go @@ -0,0 +1,15 @@ +//go:build unix + +package mcp + +import ( + "os" + "os/exec" + "syscall" +) + +// setGroup makes cmd's process lead a process group of its own. +func setGroup(cmd *exec.Cmd) { cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} } + +// signalGroup sends sig to p's process group. +func signalGroup(p *os.Process, sig syscall.Signal) { syscall.Kill(-p.Pid, sig) } diff --git a/internal/features/mcp/watch.go b/internal/features/mcp/watch.go new file mode 100644 index 0000000..9ff23ca --- /dev/null +++ b/internal/features/mcp/watch.go @@ -0,0 +1,411 @@ +package mcp + +import ( + "context" + "encoding/json" + "errors" + "regexp" + "slices" + "strings" + "sync" + "time" + + "github.com/robdevops/signalbot/internal/feature" + "github.com/robdevops/signalbot/internal/kit/logx" + "github.com/robdevops/signalbot/internal/kit/txt" +) + +// A watch's limits. +const ( + maxWatches = 8 // live in one chat, per addon + maxPattern = 1 << 10 // a pattern's size, in bytes + maxWatchID = 64 // an ID's size, in bytes + maxGuard = 500 // a guard's size, in runes + maxMatches = 256 // matched messages waiting for the watch worker, per addon + claimLife = 48 * time.Hour + leaseLife = 24 * time.Hour + tombLife = 10 * time.Minute +) + +// watchRate caps the watch worker's calls in each chat; a match past it +// waits its turn. Tests change it. +var watchRate = rateConfig{PerMinute: 120, Burst: 20} + +// watchSpec is the watch a direct command's result asks for, in its _meta. +type watchSpec struct { + ID string `json:"id"` + Pattern string `json:"pattern"` // RE2 + Until string `json:"until"` // RFC 3339 + Tool string `json:"tool"` // called with each message it matches + Guard string `json:"guard"` // optional: the answer, while it lasts, to a message addressed to the bot that quotes its pictures +} + +// watch is a live watch: an addon's claim, until Until, on the messages +// matching Pattern in one chat that the bot gets while it lasts, and the +// edits of those sent from Since on. +type watch struct { + ID string `json:"id"` + Chat string `json:"chat"` // the chat's pseudonym; its lease names the chat + Pattern string `json:"pattern"` + Tool string `json:"tool"` + Guard string `json:"guard,omitempty"` + Since int64 `json:"since"` // the Timestamp of the command that made it, by its sender's clock: only for edits + Until time.Time `json:"until"` + Pictures []int64 `json:"pictures,omitempty"` // when the bot's messages with the command's pictures were sent, as Quote.Sent names them + + key string // the chat's key + re *regexp.Regexp // Pattern +} + +// claimKey names a message a watch took: its chat's key, its sender's +// pseudonym and when it was sent. +type claimKey struct { + Chat string `json:"chat"` + Sender string `json:"sender"` + Sent int64 `json:"sent"` +} + +// claim is a message a watch took, whose edits go to the same tool. +type claim struct { + claimKey + Tool string `json:"tool"` + Got int64 `json:"got"` // when the bot got it, in Unix seconds + Expires time.Time `json:"expires"` +} + +// lease is a chat an addon may post and react in, until it expires. +type lease struct { + Chat feature.Chat `json:"chat"` + Expires time.Time `json:"expires"` +} + +// match is a message a watch took, for the watch worker. +type match struct { + msg feature.Message + tool string + at time.Time // when the bot got it + first int64 // for an edit, when the bot got the original, in Unix seconds; 0 if unknown + due time.Time // when the worker may call its tool, within its chat's rate + tries int // calls that failed with the server down +} + +// A match whose call finds the server down waits for it to start again, up +// to downWait, and is dropped after maxTries such calls. +const ( + downWait = time.Minute + maxTries = 3 +) + +// lease lets the addon post in chat for the next leaseLife. +func (a *addon) lease(chat feature.Chat) { + id := a.chatID(chat) + a.mu.Lock() + a.leases[id] = lease{chat, a.now().Add(leaseLife)} + a.mu.Unlock() + a.changed() +} + +// watch makes the watch spec asks for in m's chat, after the command m, +// and returns it, or nil if it is refused, which is logged without the +// pattern. +func (a *addon) watch(m feature.Message, spec watchSpec) *watch { + refuse := func(why string) *watch { + logx.Warnf("MCP server %s: a watch refused: %s", a.server, why) + return nil + } + now := a.now() + until, err := time.Parse(time.RFC3339, spec.Until) + var re *regexp.Regexp + switch { + case !a.cfg.Watch: + return refuse("the addon block doesn't allow watch") + case spec.ID == "" || len(spec.ID) > maxWatchID: + return refuse("its id is empty or too long") + case !a.bot[spec.Tool]: + return refuse("its tool isn't one the bot may call") + case len(spec.Pattern) > maxPattern: + return refuse("its pattern is over 1 KB") + case err != nil: + return refuse("its until isn't an RFC 3339 time") + case !until.After(now): + return refuse("its until has passed") + } + if re, err = regexp.Compile(spec.Pattern); err != nil { + return refuse("its pattern isn't RE2") + } + if ordinary(re) { + return refuse("its pattern matches ordinary chat") + } + if latest := now.Add(a.cfg.watchMax); until.After(latest) { + until = latest + } + w := &watch{ID: spec.ID, Chat: a.chatID(m.Chat), Pattern: spec.Pattern, Tool: spec.Tool, Guard: txt.Clamp(strings.TrimSpace(spec.Guard), maxGuard), + Since: m.Timestamp, Until: until, key: m.Chat.Key(), re: re} + a.mu.Lock() + tomb := w.Chat + "\x00" + w.ID + if t, ok := a.tombs[tomb]; ok && now.Before(t) { + delete(a.tombs, tomb) + a.mu.Unlock() + return refuse("the addon ended it before it began") + } + live := slices.DeleteFunc(a.watches[w.key], func(o *watch) bool { return o.ID == w.ID || !now.Before(o.Until) }) + if len(live) >= maxWatches { + a.watches[w.key] = live + a.mu.Unlock() + return refuse("8 watches are already live in the chat") + } + a.watches[w.key] = append(live, w) + a.mu.Unlock() + a.changed() + logx.Infof("MCP server %s: watching a chat for %s", a.server, until.Sub(now).Round(time.Second)) + return w +} + +// guarding records that w's command's pictures went out in the messages +// sent at sent, so its guard knows a reply to them. +func (a *addon) guarding(w *watch, sent []int64) { + a.mu.Lock() + w.Pictures = append(w.Pictures, sent...) + a.mu.Unlock() + a.changed() +} + +// claim is the Action for m if one of the addon's watches takes it: Done, +// with m sent to the watch worker. So is an edit of a message one took. An +// addressed message that quotes the pictures of a watch with a guard, even +// with no text, gets the guard. It runs on the network's reader goroutine +// for an unaddressed message, so it changes only what is in memory, and +// never waits. +// +// An original is taken whenever the bot gets it while a watch lasts, not by +// its Timestamp: on Signal that is its sender's clock, which may be behind. +// An edit's original must be from Since on, so an older message's edit is +// never taken. +func (a *addon) claim(m feature.Message) feature.Action { + if !a.allows(m.Chat) { + return feature.Action{} + } + now := a.now() + key := m.Chat.Key() + a.mu.Lock() + live := slices.Clone(a.watches[key]) // their patterns never change + a.mu.Unlock() + if m.Text == "" || len(live) == 0 && m.Edited == 0 { + return a.guard(m, live, now) + } + c := claimKey{key, a.userID(m.Chat, m.Sender), m.Timestamp} + got := match{msg: m, at: now} + if m.Edited != 0 { + a.mu.Lock() + if old, ok := a.claims[c]; ok && now.Before(old.Expires) { + got.tool, got.first = old.Tool, old.Got + } + a.mu.Unlock() + } + for _, w := range live { + if got.tool == "" && now.Before(w.Until) && (m.Edited == 0 || m.Timestamp >= w.Since) && w.re.MatchString(m.Text) { + got.tool = w.Tool + } + } + if got.tool == "" { + return a.guard(m, live, now) + } + a.mu.Lock() + if _, ok := a.claims[c]; !ok { + a.claims[c] = claim{c, got.tool, now.Unix(), now.Add(claimLife)} + } + a.leases[a.chatID(m.Chat)] = lease{m.Chat, now.Add(leaseLife)} + a.mu.Unlock() + a.changed() + select { + case a.matches <- got: + default: + logx.Warnf("addon %s: watch queue full, a matched message dropped", a.server) + } + return feature.Action{Done: true} +} + +// guard is the guard of a watch in live, live at now, if m is addressed to +// the bot and quotes its pictures. +func (a *addon) guard(m feature.Message, live []*watch, now time.Time) feature.Action { + if !m.Addressed || m.Quote == nil || !m.Quote.Bot || m.Quote.Sent == 0 { + return feature.Action{} + } + a.mu.Lock() + defer a.mu.Unlock() + for _, w := range live { + if w.Guard != "" && now.Before(w.Until) && slices.Contains(w.Pictures, m.Quote.Sent) { + return feature.Action{Answer: w.Guard} + } + } + return feature.Action{} +} + +// work passes each matched message to its watch's tool, until ctx ends: in +// each chat in turn and within the chat's rate, a match past the rate +// waiting its turn without holding up other chats'. A match whose call finds +// the server down is kept, and goes first once it has started again. +func (a *addon) work(ctx context.Context) { + var queue []match // oldest first; a chat's are due in order + var down <-chan struct{} + for ctx.Err() == nil { + in := a.matches + if len(queue) >= maxMatches { + in = nil // claim drops what can't wait + } + var wake <-chan time.Time + switch { + case down != nil: + wake = time.After(downWait) + case len(queue) > 0: + i := 0 + for j, m := range queue { + if m.due.Before(queue[i].due) { + i = j + } + } + if d := time.Until(queue[i].due); d > 0 { + wake = time.After(d) + break + } + m := queue[i] + queue = slices.Delete(queue, i, i+1) + select { + case <-a.up: // a start before this call + default: + } + if a.forward(ctx, m) { + if m.tries++; m.tries < maxTries { + queue, down = slices.Insert(queue, 0, m), a.up + } else { + logx.Warnf("addon %s: a matched message dropped: the server was down for %d calls", a.server, maxTries) + } + } + continue + } + select { + case <-ctx.Done(): + return + case m := <-in: + m.due = time.Now().Add(a.calls.take(m.msg.Chat.Key(), a.now())) + queue = append(queue, m) + case <-down: + down = nil + case <-wake: + down = nil + } + } +} + +// forward calls m's tool with its text and context, and puts the reaction +// the result asks for on it, and reports whether the call found the server +// down. Only the call's outcome, time and size are logged. +func (a *addon) forward(ctx context.Context, m match) (down bool) { + c := a.context(m.msg, m.at) + if m.first != 0 { + c.Sent = m.first + } + ctx, cancel := context.WithTimeout(ctx, directTimeout) + defer cancel() + start := time.Now() + res, err := a.conn.call(ctx, "tools/call", map[string]any{ + "name": m.tool, + "arguments": map[string]string{"text": m.msg.Text}, + "_meta": map[string]any{vendor + "context": c}, + }) + var r toolResult + outcome := "ok" + switch { + case err != nil: + outcome = errCode(err) + case json.Unmarshal(res, &r) != nil: + outcome = "a malformed result" + case r.IsError: + outcome = "an error result" + } + logx.Infof("MCP server %s: a watch called %s: %s in %dms, %d bytes", a.server, m.tool, outcome, time.Since(start).Milliseconds(), len(res)) + if outcome == "ok" && r.Meta.React != "" { + msg := feature.Message{Chat: m.msg.Chat, Sender: m.msg.Sender, Timestamp: m.msg.Timestamp, Edited: m.msg.Edited} // without its text + if why := a.react(msg, r.Meta.React); why != "" { + logx.Warnf("addon %s: a reaction dropped: %s", a.server, why) + } + } + return errors.Is(err, errNotRunning) || errors.Is(err, errExited) +} + +// react puts emoji on msg, if the addon may, and returns why not if not. +func (a *addon) react(msg feature.Message, emoji string) (why string) { + switch { + case !a.cfg.React: + return "the addon block doesn't allow react" + case !txt.SingleEmoji(emoji): + return "not one emoji" + case !a.posts.allow(msg.Chat.Key(), a.now()): + return "over the rate limit" + } + a.host.React(msg.Chat, msg, emoji) + return "" +} + +// limiter is a token bucket for each chat: rate.PerMinute tokens a minute, +// up to rate.Burst. +type limiter struct { + every time.Duration // a token comes back each + burst float64 + + mu sync.Mutex + buckets map[string]*bucket // by chat key +} + +type bucket struct { + tokens float64 + at time.Time // when tokens was counted +} + +func newLimiter(rate rateConfig) *limiter { + return &limiter{every: time.Minute / time.Duration(max(rate.PerMinute, 1)), burst: float64(max(rate.Burst, 1)), buckets: map[string]*bucket{}} +} + +// fill is chat's bucket at now, with what came back since. l.mu is held. +func (l *limiter) fill(chat string, now time.Time) *bucket { + if len(l.buckets) > 1000 { + for k, b := range l.buckets { + if b.tokens+float64(now.Sub(b.at))/float64(l.every) >= l.burst { + delete(l.buckets, k) // full: the same as none + } + } + } + b := l.buckets[chat] + if b == nil { + b = &bucket{l.burst, now} + l.buckets[chat] = b + } + b.tokens = min(l.burst, b.tokens+float64(now.Sub(b.at))/float64(l.every)) + b.at = now + return b +} + +// allow takes a token for chat, if there is one. +func (l *limiter) allow(chat string, now time.Time) bool { + l.mu.Lock() + defer l.mu.Unlock() + b := l.fill(chat, now) + if b.tokens < 1 { + return false + } + b.tokens-- + return true +} + +// take takes a token for chat, owing it if there is none, and returns how +// long to wait until it is due. +func (l *limiter) take(chat string, now time.Time) time.Duration { + l.mu.Lock() + defer l.mu.Unlock() + b := l.fill(chat, now) + b.tokens-- + if b.tokens >= 0 { + return 0 + } + return time.Duration(-b.tokens * float64(l.every)) +} diff --git a/internal/features/mcp/watch_test.go b/internal/features/mcp/watch_test.go new file mode 100644 index 0000000..76bd8fe --- /dev/null +++ b/internal/features/mcp/watch_test.go @@ -0,0 +1,935 @@ +package mcp + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "regexp" + "slices" + "strconv" + "strings" + "sync" + "testing" + "time" + + "github.com/robdevops/signalbot/internal/feature" + "github.com/robdevops/signalbot/internal/feature/featuretest" + "github.com/robdevops/signalbot/internal/kit/logx" +) + +// --- the fake addon's game and outbox ------------------------------------- + +// fakeOutbox is the fake addon's outbox, and its game's tools: round +// answers with a picture and the watch its args spell out in JSON; guess +// records what it was sent, in GAME_LOG, and asks for a 📍 unless the text +// says nopin; queue adds the ops in its args ({"ops": […], "notify": n}) and +// says so n times (once if unset); epoch makes every earlier cursor +// unknown, as a restart would; crash exits. A read returns at most three +// ops a page, from the cursor if it knows it, else from the start, and logs +// how many reads were in flight, then how many ops it returned. +type fakeOutbox struct { + notify func() + + mu sync.Mutex + nonce string + ops []json.RawMessage + reading int +} + +func (b *fakeOutbox) call(name string, args map[string]string, meta json.RawMessage) string { + text := func(s string) string { return `"result":{"content":[{"type":"text","text":"` + s + `"}]}` } + switch name { + case "round": + return `"result":{"content":[{"type":"text","text":"Round on"},{"type":"image","mimeType":"image/png","data":"` + tinyPNG() + `"}],` + + `"_meta":{"io.github.robdevops.signalbot/watch":` + args["args"] + `}}` + case "guess": + var m map[string]callContext + json.Unmarshal(meta, &m) + line, _ := json.Marshal(guessed{args["text"], m[vendor+"context"]}) + fakeLog("guess " + string(line)) + if strings.Contains(args["text"], "nopin") { + return text("Recorded") + } + return `"result":{"content":[{"type":"text","text":"Recorded"}],"_meta":{"io.github.robdevops.signalbot/react":"📍"}}` + case "queue": + var q struct { + Ops []json.RawMessage `json:"ops"` + Notify *int `json:"notify"` + } + json.Unmarshal([]byte(args["args"]), &q) + b.mu.Lock() + b.ops = append(b.ops, q.Ops...) + b.mu.Unlock() + n := 1 + if q.Notify != nil { + n = *q.Notify + } + for range n { + b.notify() + } + return text("queued") + case "epoch": + b.mu.Lock() + b.nonce += "a" + b.mu.Unlock() + return text("new epoch") + case "crash": + os.Exit(3) + } + return text("?") +} + +func (b *fakeOutbox) read(uri string) string { + b.mu.Lock() + b.reading++ + fakeLog("reading " + strconv.Itoa(b.reading)) + b.mu.Unlock() + time.Sleep(20 * time.Millisecond) // so a read that raced it would show + b.mu.Lock() + defer b.mu.Unlock() + b.reading-- + from := 0 + if n, ok := strings.CutPrefix(strings.TrimPrefix(uri, outboxURI+"/"), b.nonce+"."); ok { + if i, err := strconv.Atoi(n); err == nil && i <= len(b.ops) { + from = i + } + } + to := min(from+3, len(b.ops)) + p, _ := json.Marshal(map[string]any{"cursor": fmt.Sprintf("%s.%d", b.nonce, to), "more": to < len(b.ops), "ops": b.ops[from:to]}) + res, _ := json.Marshal(map[string]any{"contents": []any{map[string]string{"uri": uri, "mimeType": "application/json", "text": string(p)}}}) + fakeLog("read " + strconv.Itoa(to-from)) + return `"result":` + string(res) +} + +// guessed is what the fake addon's guess tool was sent. +type guessed struct { + Text string + Context callContext +} + +var fakeLogMu sync.Mutex + +// fakeLog appends line to the file GAME_LOG names, if set: the fake addon +// gets it, as its name starts with GAME_. +func fakeLog(line string) { + path := os.Getenv("GAME_LOG") + if path == "" { + return + } + fakeLogMu.Lock() + defer fakeLogMu.Unlock() + f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600) + if err != nil { + return + } + defer f.Close() + fmt.Fprintln(f, line) +} + +// gameLog is the lines the fake addon logged that start with prefix, +// without it. +func gameLog(t *testing.T, prefix string) []string { + t.Helper() + f, err := os.Open(os.Getenv("GAME_LOG")) + if err != nil { + return nil + } + defer f.Close() + var out []string + sc := bufio.NewScanner(f) + for sc.Scan() { + if rest, ok := strings.CutPrefix(sc.Text(), prefix); ok { + out = append(out, rest) + } + } + return out +} + +// guesses is what the fake addon's guess tool was sent, in order. +func guesses(t *testing.T) []guessed { + var out []guessed + for _, l := range gameLog(t, "guess ") { + var g guessed + json.Unmarshal([]byte(l), &g) + out = append(out, g) + } + return out +} + +// eventually waits up to 10s for ok. +func eventually(t *testing.T, what string, ok func() bool) { + t.Helper() + for deadline := time.Now().Add(10 * time.Second); !ok(); time.Sleep(5 * time.Millisecond) { + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for %s", what) + } + } +} + +// --- helpers ------------------------------------------------------------------ + +// gameCommands are /round, /ctx, /queue, /epoch and /crash, each calling its +// tool directly. +const gameCommands = `,"chat_commands":{"round":{"tool":"round","direct":true},"ctx":{"tool":"context","direct":true},` + + `"queue":{"tool":"queue","direct":true},"epoch":{"tool":"epoch","direct":true},"crash":{"tool":"crash","direct":true}}` + +// gameConfig is MCP_CONFIG for the fake addon "game", allowed everything in +// group A and DMs, with more settings in its addon block. +func gameConfig(more string) string { + return `{"mcpServers":{"game":` + addonServer("addon", `{"chats":["`+groupA+`"],"dms":true,"post":true,"react":true,"watch":true`+more+`}`, gameCommands) + `}}` +} + +// startGame starts the fake addon "game" with config in the state +// directory dir, with GAME_LOG in a fresh file. +func startGame(t *testing.T, config, dir string) (*featuretest.Host, *logx.Buffer) { + t.Helper() + if os.Getenv("GAME_LOG") == "" { + t.Setenv("GAME_LOG", filepath.Join(t.TempDir(), "game.log")) + } + h, log, err := register(t, config, func(h *featuretest.Host) { h.Settings["STATE_DIRECTORY"] = dir }) + if err != nil { + t.Fatal(err) + } + eventually(t, "the first read", func() bool { return len(gameLog(t, "read ")) > 0 }) + return h, log +} + +// said is a message from who ("alice-id" or "bob-id") in chat, sent at ts. +func said(chat feature.Chat, who string, ts int64, text string) feature.Message { + name := map[string]string{"alice-id": "Alice", "bob-id": "Bob"}[who] + return feature.Message{Chat: chat, Sender: who, Name: name, Text: text, Timestamp: ts} +} + +// to is m addressed to the bot. +func to(m feature.Message) feature.Message { m.Addressed = true; return m } + +// replyTo is m addressed to the bot, quoting its message sent at sent. +func replyTo(m feature.Message, sent int64) feature.Message { + m.Addressed, m.Quote = true, &feature.Quote{Bot: true, Sent: sent} + return m +} + +// edit is m edited at at to say text. +func edit(m feature.Message, at int64, text string) feature.Message { + m.Edited, m.Text = at, text + return m +} + +// spec is a watch called id, for "guess <number>", lasting d, with guard. +func spec(id string, d time.Duration, guard string) string { + b, _ := json.Marshal(watchSpec{ID: id, Pattern: `\bguess \d+`, Until: time.Now().Add(d).Format(time.RFC3339), Tool: "guess", Guard: guard}) + return string(b) +} + +// round starts a round, watch spec, by Alice in chat at ts, and says its +// picture went out at 5000. +func round(t *testing.T, h *featuretest.Host, chat feature.Chat, ts int64, spec string) feature.Action { + t.Helper() + act := h.Message(context.Background(), to(said(chat, "alice-id", ts, "/round "+spec))) + if act.Answer != "Round on" || len(act.Pictures) != 1 { + t.Fatalf("round: %+v", act) + } + if act.OnSent != nil { + act.OnSent([]int64{5000}) + } + return act +} + +// chatID is the fake addon's pseudonym for chat, from /ctx there. +func chatID(t *testing.T, h *featuretest.Host, chat feature.Chat) callContext { + t.Helper() + var meta map[string]callContext + if err := json.Unmarshal([]byte(h.Message(context.Background(), in(chat, "/ctx")).Answer), &meta); err != nil { + t.Fatal(err) + } + return meta[vendor+"context"] +} + +// queue has the fake addon queue ops, telling the bot notify times. +func queue(t *testing.T, h *featuretest.Host, notify int, ops ...map[string]any) { + t.Helper() + b, _ := json.Marshal(map[string]any{"ops": ops, "notify": notify}) + if got := h.Message(context.Background(), in(inA, "/queue "+string(b))); got.Answer != "queued" { + t.Fatalf("queue: %+v", got) + } +} + +// --- watches, through the fake addon -------------------------------------- + +// A watch takes the matching messages in its chat sent after it, addressed +// or not, and their edits: each is Done, and goes to the watch's tool, +// which has the bot react. A reply to its picture that doesn't match gets +// the guard; nothing else is touched, and no text reaches the log. +func TestWatch(t *testing.T) { + h, log := startGame(t, gameConfig(""), t.TempDir()) + ctx := context.Background() + act := round(t, h, inA, 1000, spec("r1", time.Hour, "No hints during a round")) + if act.OnSent == nil { + t.Fatal("no OnSent, so no guard") + } + bobs := said(inA, "bob-id", 1001, "guess 42") + for _, m := range []feature.Message{ + bobs, // unaddressed: on the reader goroutine + replyTo(said(inA, "alice-id", 1002, "my guess 7"), 5000), + to(said(inA, "alice-id", 1003, "@bot guess 8")), + edit(bobs, 1004, "guess 43"), // a claimed message's edit + edit(bobs, 1005, "oops, not that"), // still claimed, though it no longer matches + } { + if got := h.Message(ctx, m); !got.Done || got.Answer != "" || len(got.Pictures) != 0 { + t.Fatalf("%q: %+v", m.Text, got) + } + } + for _, m := range []feature.Message{ + edit(said(inA, "bob-id", 999, "hello"), 1006, "guess 2"), // an older message's edit + said(inA, "bob-id", 1007, "lol"), + to(said(inA, "bob-id", 1008, "where is it?")), + said(inB, "bob-id", 1009, "guess 3"), // another group + said(inDM, "bob-id", 1010, "guess 4"), // a DM, with no round + } { + if got := h.Message(ctx, m); !got.IsZero() { + t.Fatalf("%q: %+v", m.Text, got) + } + } + for _, text := range []string{"@bot where is this?", ""} { // with no text, such as a bare mention + if got := h.Message(ctx, replyTo(said(inA, "bob-id", 1011, text), 5000)); got.Answer != "No hints during a round" || got.Done { + t.Fatalf("guard for %q: %+v", text, got) + } + } + + eventually(t, "the guesses", func() bool { return len(guesses(t)) == 5 }) + g := guesses(t) + var texts []string + for _, x := range g { + texts = append(texts, x.Text) + } + if want := []string{"guess 42", "my guess 7", "@bot guess 8", "guess 43", "oops, not that"}; !slices.Equal(texts, want) { + t.Fatalf("the addon got %q", texts) + } + first := g[0].Context + if first.Edited != 0 || first.Addressed || !first.Group || g[1].Context.Sender == first.Sender || !g[1].Context.Addressed { + t.Fatalf("contexts %+v", g) + } + for _, e := range g[3:] { + if e.Context.Sent != first.Sent || e.Context.Edited == 0 || e.Context.Sender != first.Sender || e.Context.Chat != first.Chat { + t.Fatalf("an edit's context %+v, the original's %+v", e.Context, first) + } + } + eventually(t, "the pins", func() bool { return len(h.Reactions()) == 5 }) + for i, r := range h.Reactions() { + if r.Emoji != "📍" || r.Chat != inA || r.Message.Text != "" || r.Message.Timestamp < 1001 || r.Message.Sender == "" { + t.Fatalf("reaction %d: %+v", i, r) + } + } + l := log.String() + if !regexp.MustCompile(`<6>MCP server game: watching a chat for (59m59s|1h0m0s)\n`).MatchString(l) || + !regexp.MustCompile(`<6>MCP server game: a watch called guess: ok in \d+ms, \d+ bytes\n`).MatchString(l) { + t.Fatalf("log %q", l) + } + for _, s := range []string{"guess 4", "guess 1", "oops", "hints", "lol"} { + if strings.Contains(l, s) { + t.Fatalf("%q reached the log: %q", s, l) + } + } +} + +// A watch must be allowed, and its pattern specific; it lasts at most +// watch_max. +func TestWatchRefused(t *testing.T) { + h, log := startGame(t, gameConfig(`,"watch_max":"2s"`), t.TempDir()) + ctx := context.Background() + for _, s := range []string{ + `{"id":"a","pattern":".*","until":"` + time.Now().Add(time.Hour).Format(time.RFC3339) + `","tool":"guess"}`, + `{"id":"b","pattern":"(?i)\\b(see|you)\\b","until":"` + time.Now().Add(time.Hour).Format(time.RFC3339) + `","tool":"guess"}`, + `{"id":"c","pattern":"guess (?=\\d)","until":"` + time.Now().Add(time.Hour).Format(time.RFC3339) + `","tool":"guess"}`, + `{"id":"d","pattern":"guess \\d+","until":"` + time.Now().Add(time.Hour).Format(time.RFC3339) + `","tool":"plain"}`, + `{"id":"e","pattern":"guess \\d+","until":"yesterday","tool":"guess"}`, + `{"id":"f","pattern":"guess \\d+` + strings.Repeat("x", 1024) + `","until":"` + time.Now().Add(time.Hour).Format(time.RFC3339) + `","tool":"guess"}`, + } { + round(t, h, inA, 1000, s) + } + if got := h.Message(ctx, said(inA, "bob-id", 1001, "see you at guess 5")); !got.IsZero() { + t.Fatalf("a refused watch took a message: %+v", got) + } + for _, want := range []string{"its pattern matches ordinary chat", "its pattern isn't RE2", "its tool isn't one the bot may call", + "its until isn't an RFC 3339 time", "its pattern is over 1 KB"} { + if !strings.Contains(log.String(), "<4>MCP server game: a watch refused: "+want+"\n") { + t.Errorf("log %q, want %q", log.String(), want) + } + } + + // Asked for an hour, it lasts watch_max. + round(t, h, inA, 2000, spec("r1", time.Hour, "")) + if got := h.Message(ctx, said(inA, "bob-id", 2001, "guess 5")); !got.Done { + t.Fatalf("a live watch: %+v", got) + } + time.Sleep(2100 * time.Millisecond) + if got := h.Message(ctx, said(inA, "bob-id", 2002, "guess 6")); !got.IsZero() { + t.Fatalf("an ended watch: %+v", got) + } + + // Without the watch permission, none. + h2, log2 := startGame(t, `{"mcpServers":{"game":`+addonServer("addon", `{"dms":true}`, gameCommands)+`}}`, t.TempDir()) + round(t, h2, inDM, 1000, spec("r1", time.Hour, "")) + if got := h2.Message(ctx, said(inDM, "alice-id", 1001, "guess 5")); !got.IsZero() || !strings.Contains(log2.String(), "a watch refused: the addon block doesn't allow watch") { + t.Fatalf("%+v, log %q", got, log2.String()) + } +} + +// gatedStore is a Store whose saves wait while hold is locked. +type gatedStore struct { + feature.Store + hold sync.Mutex + saves chan struct{} +} + +func (s *gatedStore) Save(v any) error { + s.hold.Lock() + defer s.hold.Unlock() + err := s.Store.Save(v) + select { + case s.saves <- struct{}{}: + default: + } + return err +} + +// gatedHost is a featuretest.Host whose "mcp" store is a gatedStore. +type gatedHost struct { + *featuretest.Host + store *gatedStore +} + +func (g gatedHost) Store(name string) (feature.Store, error) { + s, err := g.Host.Store(name) + if err != nil { + return nil, err + } + g.store.Store = s + return g.store, nil +} + +// A match changes only memory: it never waits for a save, which happens on +// the saver goroutine, even while the disk is stuck. +func TestWatchNeverSavesOnTheReader(t *testing.T) { + t.Setenv("GAME_LOG", filepath.Join(t.TempDir(), "game.log")) + var log logx.Buffer + t.Cleanup(logx.SetOutput(&log, &log, true)) + dir := t.TempDir() + host := featuretest.New() + host.Bot.Model, host.Bot.CallsTools = "x/test-model", true + host.Settings["MCP_CONFIG"], host.Settings["STATE_DIRECTORY"] = writeConfig(t, gameConfig("")), dir + t.Cleanup(host.Stop) + g := gatedHost{host, &gatedStore{saves: make(chan struct{}, 1)}} + if err := Register(g); err != nil { + t.Fatal(err) + } + round(t, host, inA, 1000, spec("r1", time.Hour, "")) + eventually(t, "a save", func() bool { + select { + case <-g.store.saves: + return true + default: + return false + } + }) + + g.store.hold.Lock() // the disk is stuck + done := make(chan feature.Action) + go func() { done <- host.Message(context.Background(), said(inA, "bob-id", 1001, "guess 42")) }() + select { + case got := <-done: + if !got.Done { + t.Fatalf("%+v", got) + } + case <-time.After(5 * time.Second): + t.Fatal("a match waited for a save") + } + g.store.hold.Unlock() + eventually(t, "the claim saved", func() bool { + data, _ := os.ReadFile(filepath.Join(dir, "mcp.json")) + var s saved + json.Unmarshal(data, &s) + return len(s.Addons["game"].Claims) == 1 + }) +} + +// Watches, claims and leases outlive a restart of the bot, and of the +// addon, which the bot subscribes to again. +func TestWatchRestarts(t *testing.T) { + defer func(d time.Duration) { restartDelay = d }(restartDelay) + restartDelay = 10 * time.Millisecond + dir := t.TempDir() + h, _ := startGame(t, gameConfig(""), dir) + ctx := context.Background() + round(t, h, inA, 1000, spec("r1", time.Hour, "No hints")) + bobs := said(inA, "bob-id", 1001, "guess 42") + if !h.Message(ctx, bobs).Done { + t.Fatal("not taken") + } + chat := chatID(t, h, inA).Chat + h.Stop() + + h, log := startGame(t, gameConfig(""), dir) + for _, m := range []feature.Message{said(inA, "alice-id", 1002, "guess 5"), edit(bobs, 1003, "never mind")} { + if got := h.Message(ctx, m); !got.Done { + t.Fatalf("after a restart, %q: %+v", m.Text, got) + } + } + if got := h.Message(ctx, replyTo(said(inA, "bob-id", 1004, "@bot where?"), 5000)); got.Answer != "No hints" { + t.Fatalf("after a restart, the guard: %+v", got) + } + queue(t, h, 1, map[string]any{"id": "1", "op": "post", "chat": chat, "text": "after a restart"}) + eventually(t, "the post", func() bool { return len(h.Posts()) == 1 }) + + // The addon restarts: the bot subscribes again, and its watches stand. + h.Message(ctx, in(inA, "/crash")) + eventually(t, "a second subscription", func() bool { return len(gameLog(t, "subscribed")) == 3 }) + if got := h.Message(ctx, said(inA, "alice-id", 1005, "guess 6")); !got.Done { + t.Fatalf("after the addon's restart: %+v", got) + } + eventually(t, "the guesses", func() bool { return len(guesses(t)) >= 3 }) + if !strings.Contains(log.String(), "<4>MCP server game exited; restarting in") { + t.Fatalf("log %q", log.String()) + } +} + +// --- the outbox, through the fake addon ------------------------------------ + +// Posts go to a chat the addon has a lease in, one waiting at a time, the +// rest held and merged; one dropped before it was sent is posted again; an +// op read again is applied once, even from the start of an unknown cursor; +// reactions go to known messages. +func TestOutbox(t *testing.T) { + d := retryDelay + t.Cleanup(func() { retryDelay = d }) // after the addon stops + retryDelay = 50 * time.Millisecond + h, log := startGame(t, gameConfig(""), t.TempDir()) + ctx := context.Background() + c := chatID(t, h, inA) // a lease, and a ref + post := func(id, text string) map[string]any { + return map[string]any{"id": id, "op": "post", "chat": c.Chat, "text": text} + } + queue(t, h, 1, post("1", "hello {"+c.Sender+"}")) + eventually(t, "the post", func() bool { return len(h.Posts()) == 1 }) + if p := h.Posts()[0]; p.Chat != inA || p.Label != "Game" || p.Text != "hello @Alice" || p.Done == nil { + t.Fatalf("post %+v", p) + } + + // Held while the first waits, and merged. + queue(t, h, 1, post("2", "two"), post("3", "three")) + time.Sleep(100 * time.Millisecond) + if n := len(h.Posts()); n != 1 { + t.Fatalf("%d posts while one waits", n) + } + h.Posts()[0].Done([]int64{1}, false) + eventually(t, "the held posts", func() bool { return len(h.Posts()) == 2 }) + if p := h.Posts()[1]; p.Text != "two\n\nthree" { + t.Fatalf("held %q", p.Text) + } + + // Dropped before it was sent, as while the bot stops: posted again, + // one by one, as nothing waits. + h.Posts()[1].Done(nil, true) + eventually(t, "the post again", func() bool { return len(h.Posts()) == 3 }) + h.Posts()[2].Done([]int64{2}, false) + eventually(t, "the next post again", func() bool { return len(h.Posts()) == 4 }) + h.Posts()[3].Done([]int64{3}, false) + if p := h.Posts(); p[2].Text != "two" || p[3].Text != "three" { + t.Fatalf("again %q, %q", p[2].Text, p[3].Text) + } + + // Read again, from the start, after the addon's cursor is unknown: only + // the new op is applied. + h.Message(ctx, in(inA, "/epoch")) + queue(t, h, 1, post("3", "three again"), post("4", "four")) + eventually(t, "the new post", func() bool { return len(h.Posts()) == 5 }) + time.Sleep(100 * time.Millisecond) + if p := h.Posts(); len(p) != 5 || p[4].Text != "four" { + t.Fatalf("posts %+v", p) + } + h.Posts()[4].Done(nil, false) + + // A reaction, to a message the addon has a ref for; ops it may not do, + // or for a chat it has no lease in, are dropped and counted. + queue(t, h, 1, map[string]any{"id": "5", "op": "react", "ref": c.Ref, "emoji": "👀"}, + map[string]any{"id": "6", "op": "react", "ref": "r_unknown", "emoji": "👀"}, + post("", "no id"), map[string]any{"id": "7", "op": "post", "chat": "c_elsewhere", "text": "x"}, + map[string]any{"id": "8", "op": "dance"}) + eventually(t, "the reaction", func() bool { return len(h.Reactions()) == 1 }) + if r := h.Reactions()[0]; r.Emoji != "👀" || r.Chat != inA || r.Message.Sender != "alice-id" || r.Message.Timestamp != 1700000000000 { + t.Fatalf("reaction %+v", r) + } + eventually(t, "the drops", func() bool { + return strings.Contains(log.String(), "<4>addon game: dropped 4 ops: 1 for a chat without a lease, 1 of an unknown kind, 1 reactions to an unknown message, 1 without an id\n") + }) + if len(h.Posts()) != 5 || strings.Contains(log.String(), "hello") { + t.Fatalf("posts %d, log %q", len(h.Posts()), log.String()) + } +} + +// A post goes as a merged post only while their pictures fit in one; the +// cursor moves past a post only once it is sent; one never sent is given up +// after maxPostTries. +func TestOutboxDelivery(t *testing.T) { + defer func(d time.Duration) { retryDelay = d }(retryDelay) + retryDelay = time.Hour // retried only when the test says + var log logx.Buffer + t.Cleanup(logx.SetOutput(&log, &log, true)) + cfg := everything + cfg.Rate = rateConfig{600, 100} + a, now := unitAddon(cfg) + h := featuretest.New() + a.host = h + a.lease(inA) + id := a.chatID(inA) + pic := []postImage{{Data: tinyPNG(), MimeType: "image/png"}} + postOp := func(n string, images []postImage) op { + return op{ID: n, Op: "post", Chat: id, Text: "post " + n, Images: images} + } + for _, o := range []op{postOp("1", nil), postOp("2", pic), postOp("3", pic), postOp("4", pic), postOp("5", nil)} { + if why := a.apply(o); why != "" { + t.Fatalf("%s: %s", o.ID, why) + } + } + a.next = "c.5" + a.settle() + if a.cursor != "" { + t.Fatalf("the cursor moved to %q before the posts were sent", a.cursor) + } + var texts []string + for i := 0; i < len(h.Posts()); i++ { + texts = append(texts, h.Posts()[i].Text) + h.Posts()[i].Done([]int64{int64(i)}, false) + } + if want := []string{"post 1", "post 2\n\npost 3", "post 4\n\npost 5"}; !slices.Equal(texts, want) { + t.Fatalf("posts %q", texts) + } + if a.cursor != "c.5" || len(a.applied) != 5 { + t.Fatalf("cursor %q, applied %q", a.cursor, a.applied) + } + + // Never sent: posted again on each read once due, then given up. + for try := range maxPostTries { + a.next = "c.6" + if why := a.apply(postOp("6", nil)); why != "" { + t.Fatal(why) + } + p := h.Posts()[len(h.Posts())-1] + if p.Text != "post 6" { + t.Fatalf("try %d: %q", try, p.Text) + } + p.Done(nil, true) + if a.apply(postOp("6", nil)); len(h.Posts()) != 4+try { + t.Fatalf("try %d: posted again before it was due", try) + } + *now = now.Add(maxRetryDelay) + } + if !a.done["6"] || a.cursor != "c.5" || !strings.Contains(log.String(), "<4>addon game: 1 posts dropped: not sent after 6 tries\n") { + t.Fatalf("cursor %q, log %q", a.cursor, log.String()) + } +} + +// One reader per addon: a burst of news never makes two reads at once, a +// read misses nothing that came during it, and news the addon never sent is +// read with the next. +func TestOutboxReader(t *testing.T) { + h, _ := startGame(t, gameConfig(`,"rate":{"per_minute":600,"burst":50}`), t.TempDir()) + c := chatID(t, h, inA) + react := func(id string) map[string]any { + return map[string]any{"id": id, "op": "react", "ref": c.Ref, "emoji": "👍"} + } + queue(t, h, 0, react("1")) // its news lost + time.Sleep(100 * time.Millisecond) + if n := len(h.Reactions()); n != 0 { + t.Fatalf("%d reactions without news", n) + } + queue(t, h, 1, react("2")) + eventually(t, "both reactions", func() bool { return len(h.Reactions()) == 2 }) + + var ops []map[string]any + for i := range 7 { + ops = append(ops, react(strconv.Itoa(10+i))) + } + queue(t, h, 20, ops...) + eventually(t, "every reaction", func() bool { return len(h.Reactions()) == 9 }) + time.Sleep(100 * time.Millisecond) + if n := len(h.Reactions()); n != 9 { + t.Fatalf("%d reactions", n) + } + for _, l := range gameLog(t, "reading ") { + if l != "1" { + t.Fatalf("%s reads at once", l) + } + } +} + +// Posts and reactions are rate limited per chat: past the burst, dropped +// and counted. +func TestOutboxRate(t *testing.T) { + h, log := startGame(t, gameConfig(`,"rate":{"per_minute":1,"burst":2}`), t.TempDir()) + c := chatID(t, h, inA) + var ops []map[string]any + for i := range 3 { + ops = append(ops, map[string]any{"id": strconv.Itoa(i), "op": "react", "ref": c.Ref, "emoji": "👍"}) + } + queue(t, h, 1, ops...) + eventually(t, "the drop", func() bool { return strings.Contains(log.String(), "dropped 1 op: 1 reactions over the rate limit") }) + if n := len(h.Reactions()); n != 2 { + t.Fatalf("%d reactions", n) + } +} + +// An unwatch ends a watch; one that comes first ends it before it begins. +func TestOutboxUnwatch(t *testing.T) { + h, log := startGame(t, gameConfig(""), t.TempDir()) + ctx := context.Background() + c := chatID(t, h, inA) + round(t, h, inA, 1000, spec("r1", time.Hour, "")) + queue(t, h, 1, map[string]any{"id": "1", "op": "unwatch", "chat": c.Chat, "watch": "r1"}, + map[string]any{"id": "2", "op": "unwatch", "chat": c.Chat, "watch": "r2"}) + eventually(t, "the unwatch", func() bool { return h.Message(ctx, said(inA, "bob-id", 1001, "guess 5")).IsZero() }) + round(t, h, inA, 1002, spec("r2", time.Hour, "")) + if got := h.Message(ctx, said(inA, "bob-id", 1003, "guess 5")); !got.IsZero() { + t.Fatalf("a watch ended before it began: %+v", got) + } + if !strings.Contains(log.String(), "a watch refused: the addon ended it before it began") { + t.Fatalf("log %q", log.String()) + } +} + +// --- in memory ------------------------------------------------------------------ + +// unitAddon is an addon with no server, allowed everywhere, on a clock the +// test moves. +func unitAddon(cfg addonConfig) (*addon, *time.Time) { + a := newAddon("game", "Game", cfg, bytes.Repeat([]byte{7}, secretSize), nil, map[string]bool{"guess": true}) + now := time.Unix(1800000000, 0) + a.now = func() time.Time { return now } + return a, &now +} + +var everything = addonConfig{Chats: []string{"all"}, DMs: true, Watch: true, Post: true, React: true, watchMax: time.Hour, Rate: rateConfig{20, 5}} + +// specAt is a watch spec ending at until. +func specAt(id string, until time.Time) watchSpec { + return watchSpec{ID: id, Pattern: `\bguess \d+`, Until: until.Format(time.RFC3339), Tool: "guess"} +} + +// A chat has at most maxWatches; a claim lasts claimLife, a watch until its +// end, a tombstone tombLife. +func TestWatchLimits(t *testing.T) { + var log logx.Buffer + t.Cleanup(logx.SetOutput(&log, &log, true)) + a, now := unitAddon(everything) + cmd := said(inA, "alice-id", 1000, "/round") + for i := range maxWatches { + if a.watch(cmd, specAt(strconv.Itoa(i), now.Add(time.Minute))) == nil { + t.Fatalf("watch %d refused", i) + } + } + if a.watch(cmd, specAt("9", now.Add(time.Minute))) != nil || !strings.Contains(log.String(), "8 watches are already live in the chat") { + t.Fatalf("a 9th: %q", log.String()) + } + if a.watch(cmd, specAt("0", now.Add(time.Minute))) == nil { + t.Fatal("one replacing another of its ID was refused") + } + if a.watch(said(inB, "alice-id", 1000, "/round"), specAt("0", now.Add(time.Minute))) == nil { + t.Fatal("refused in another chat") + } + + bobs := said(inA, "bob-id", 1001, "guess 1") + if !a.claim(bobs).Done { + t.Fatal("not claimed") + } + *now = now.Add(time.Minute) + if !a.claim(said(inA, "bob-id", 1002, "guess 2")).IsZero() { + t.Fatal("claimed after the watch ended") + } + if !a.claim(edit(bobs, 1003, "guess 3")).Done { + t.Fatal("an edit not claimed after the watch ended") + } + *now = now.Add(claimLife) + if !a.claim(edit(bobs, 1004, "guess 4")).IsZero() { + t.Fatal("an edit claimed after its claim ended") + } + if s := a.state(); len(s.Watches) != 0 || len(s.Claims) != 0 || len(s.Leases) != 0 { + t.Fatalf("kept %+v", s) + } + + a.unwatch(a.chatID(inA), "late") + *now = now.Add(tombLife + time.Second) + if a.watch(cmd, specAt("late", now.Add(time.Minute))) == nil { + t.Fatal("a tombstone outlived tombLife") + } +} + +// An original is taken whenever the bot gets it, even by a clock behind the +// command's; an edit only of an original from the command on. +func TestWatchClock(t *testing.T) { + a, now := unitAddon(everything) + a.watch(said(inA, "alice-id", 1000, "/round"), specAt("r", now.Add(time.Minute))) + if !a.claim(said(inA, "bob-id", 900, "guess 1")).Done { + t.Fatal("an original by a slow clock not taken") + } + if !a.claim(edit(said(inA, "bob-id", 999, "hello"), 1100, "guess 2")).IsZero() { + t.Fatal("an older message's edit taken") + } +} + +// fakeConn is a server for the watch worker: it records the texts it is +// sent, or fails as down while down is set. +type fakeConn struct { + mu sync.Mutex + down bool + texts []string + fails int +} + +func (c *fakeConn) call(_ context.Context, _ string, params any) (json.RawMessage, error) { + c.mu.Lock() + defer c.mu.Unlock() + if c.down { + c.fails++ + return nil, errNotRunning + } + c.texts = append(c.texts, params.(map[string]any)["arguments"].(map[string]string)["text"]) + return json.RawMessage(`{"content":[]}`), nil +} + +func (c *fakeConn) notify(context.Context, string, any) error { return nil } + +func (c *fakeConn) state() ([]string, int) { + c.mu.Lock() + defer c.mu.Unlock() + return slices.Clone(c.texts), c.fails +} + +// A chat past its rate doesn't hold up another's matches; a match the +// server was down for is called again once it has started. +func TestWatchWorker(t *testing.T) { + defer func(r rateConfig) { watchRate = r }(watchRate) + watchRate = rateConfig{PerMinute: 1, Burst: 1} + a, now := unitAddon(everything) + c := &fakeConn{} + a.conn = c + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { a.work(ctx); close(done) }() + defer func() { cancel(); <-done }() + for _, chat := range []feature.Chat{inA, inB, inDM} { + a.watch(said(chat, "alice-id", 1000, "/round"), specAt("r", now.Add(time.Minute))) + } + a.claim(said(inA, "bob-id", 1001, "guess 1")) + a.claim(said(inA, "bob-id", 1002, "guess 2")) // due in a minute + a.claim(said(inB, "bob-id", 1003, "guess 3")) + eventually(t, "the calls", func() bool { texts, _ := c.state(); return len(texts) == 2 }) + if texts, _ := c.state(); !slices.Equal(texts, []string{"guess 1", "guess 3"}) { + t.Fatalf("called with %q", texts) + } + + c.mu.Lock() + c.down = true + c.mu.Unlock() + a.claim(said(inDM, "bob-id", 1004, "guess 4")) + eventually(t, "the failed call", func() bool { _, fails := c.state(); return fails == 1 }) + c.mu.Lock() + c.down = false + c.mu.Unlock() + time.Sleep(50 * time.Millisecond) + if texts, _ := c.state(); len(texts) != 2 { + t.Fatalf("called again before the server started: %q", texts) + } + a.up <- struct{}{} + eventually(t, "the call again", func() bool { texts, _ := c.state(); return len(texts) == 3 }) + if texts, _ := c.state(); texts[2] != "guess 4" { + t.Fatalf("called with %q", texts) + } +} + +// A match never waits for the watch worker: past maxMatches waiting, it is +// dropped with a warning, though still taken. +func TestWatchQueueFull(t *testing.T) { + var log logx.Buffer + t.Cleanup(logx.SetOutput(&log, &log, true)) + a, now := unitAddon(everything) + a.watch(said(inA, "alice-id", 1000, "/round"), specAt("r", now.Add(time.Minute))) + for i := range maxMatches + 1 { + if !a.claim(said(inA, "bob-id", int64(1001+i), "guess 1")).Done { + t.Fatal("not claimed") + } + } + if strings.Count(log.String(), "<4>addon game: watch queue full, a matched message dropped\n") != 1 { + t.Fatalf("log %q", log.String()) + } + if s := a.state(); len(s.Claims) != maxMatches+1 { + t.Fatalf("%d claims", len(s.Claims)) + } +} + +// Past the watch rate, a call waits its turn rather than being dropped. +func TestWatchRate(t *testing.T) { + defer func(r rateConfig) { watchRate = r }(watchRate) + watchRate = rateConfig{PerMinute: 600, Burst: 1} // one each 100ms + h, _ := startGame(t, gameConfig(""), t.TempDir()) + ctx := context.Background() + round(t, h, inA, 1000, spec("r1", time.Hour, "")) + start := time.Now() + for i := range 4 { + h.Message(ctx, said(inA, "bob-id", int64(1001+i), "guess "+strconv.Itoa(i)+" nopin")) + } + eventually(t, "every guess", func() bool { return len(guesses(t)) == 4 }) + if d := time.Since(start); d < 250*time.Millisecond { + t.Fatalf("4 calls in %s", d) + } +} + +func TestLimiter(t *testing.T) { + l := newLimiter(rateConfig{PerMinute: 60, Burst: 2}) + now := time.Unix(0, 0) + if !l.allow("a", now) || !l.allow("a", now) || l.allow("a", now) || !l.allow("b", now) { + t.Fatal("burst") + } + if !l.allow("a", now.Add(time.Second)) || l.allow("a", now.Add(time.Second)) { + t.Fatal("refill") + } + if w := l.take("c", now); w != 0 { + t.Fatalf("waits %s", w) + } + l.take("c", now) + if w := l.take("c", now); w != time.Second { + t.Fatalf("waits %s", w) + } +} + +// Catch-alls and patterns for ordinary chat are refused; a game's are not. +func TestOrdinary(t *testing.T) { + for _, p := range []string{`.*`, `.`, `^`, `x*`, `(?i)lol`, `\d`, `\w+`, `(?i)the`, `https?://`, `\?$`, `[a-z]{3}`} { + if !ordinary(regexp.MustCompile(p)) { + t.Errorf("%s passed", p) + } + } + geo := `(?i)(?:\bmaps\.google\.[a-z.]+/|\bgoogle\.[a-z.]+/maps|\bmaps\.apple\.com\b|\bgeo:[+-]?\d|\bopenstreetmap\.org/|(?:^|[^\w.])-?\d{1,3}\.\d+°?\s*,\s*-?\d{1,3}\.\d+)` + for _, p := range []string{geo, `\bguess \d+`, `^/vote [a-d]$`} { + if ordinary(regexp.MustCompile(p)) { + t.Errorf("%s refused", p) + } + } + if n := len(chatter); n < 200 { + t.Errorf("%d lines of chatter", n) + } +} + +func TestNotFound(t *testing.T) { + for code, want := range map[int]bool{-32002: true, -32602: true, -32601: false} { + if got := errNotFound(fmt.Errorf("x: %w", &rpcError{Code: code})); got != want { + t.Errorf("%d: %v", code, got) + } + } + if errNotFound(context.DeadlineExceeded) { + t.Error("a timeout") + } +} diff --git a/internal/features/schedule/schedule.go b/internal/features/schedule/schedule.go index 1ce27fd..528503c 100644 --- a/internal/features/schedule/schedule.go +++ b/internal/features/schedule/schedule.go @@ -229,8 +229,8 @@ func (s *scheduler) settle(e *entry, dueAt time.Time) (deliver bool) { } if late >= grace { logx.Warnf("a one-off schedule was dropped: it was due %s ago", late.Round(time.Minute)) - s.h.Tell(e.User, "I was offline at "+dueAt.In(s.loc).Format(whenLayout)+", so your reminder \""+ - txt.Clamp(strings.Join(strings.Fields(e.Text), " "), 80)+"\" didn't post.") + s.h.Post(feature.Post{Chat: feature.Chat{User: e.User}, Text: "I was offline at " + dueAt.In(s.loc).Format(whenLayout) + ", so your reminder \"" + + txt.Clamp(strings.Join(strings.Fields(e.Text), " "), 80) + "\" didn't post."}) return false } return true diff --git a/internal/features/schedule/schedule_test.go b/internal/features/schedule/schedule_test.go index d3d79b9..ce96bb0 100644 --- a/internal/features/schedule/schedule_test.go +++ b/internal/features/schedule/schedule_test.go @@ -292,7 +292,7 @@ func TestRefusals(t *testing.T) { t.Fatalf("logs:\n%s", w.logs) } // Not commands of its own: carried on. - if a := w.h.Message(context.Background(), feature.Message{Chat: feature.Chat{User: alice}, Sender: alice, Text: "/schedules", Addressed: true}); a != (feature.Action{}) { + if a := w.h.Message(context.Background(), feature.Message{Chat: feature.Chat{User: alice}, Sender: alice, Text: "/schedules", Addressed: true}); !a.IsZero() { t.Fatalf("got %+v", a) } } @@ -416,8 +416,9 @@ func TestLoad(t *testing.T) { t.Fatalf("saved %+v", s) } logs := w.logs.String() - if told := w.h.TellsSent(); len(told) != 1 || told[0] != (featuretest.Told{User: alice, Text: `I was offline at Tue 15 Jan 2030 10:59 UTC, so your reminder "stale one" didn't post.`}) { - t.Fatalf("told %+v", told) + if p := w.h.Posts(); len(p) != 1 || p[0].Chat != (feature.Chat{User: alice}) || p[0].Label != "" || len(p[0].Pictures) != 0 || + p[0].Text != `I was offline at Tue 15 Jan 2030 10:59 UTC, so your reminder "stale one" didn't post.` { + t.Fatalf("posted %+v", p) } for _, want := range []string{"<3>schedules.json: entry 4 skipped: no text; it will be removed at the next save\n", "<4>a one-off schedule was dropped: it was due 1h1m0s ago\n", "<5>loaded 3 schedules\n"} { if !strings.Contains(logs, want) { @@ -508,7 +509,7 @@ func TestAliases(t *testing.T) { if got := w.dm("/timer help"); !strings.Contains(got, "/timer and /reminder work the same as /schedule.") { t.Fatalf("help: %q", got) } - if a := w.h.Message(context.Background(), feature.Message{Chat: feature.Chat{User: alice}, Sender: alice, Text: "/job list", Addressed: true}); a != (feature.Action{}) { + if a := w.h.Message(context.Background(), feature.Message{Chat: feature.Chat{User: alice}, Sender: alice, Text: "/job list", Addressed: true}); !a.IsZero() { t.Fatalf("/job is still a command: %+v", a) } } diff --git a/internal/kit/img/safe.go b/internal/kit/img/safe.go new file mode 100644 index 0000000..628edda --- /dev/null +++ b/internal/kit/img/safe.go @@ -0,0 +1,119 @@ +package img + +import ( + "bytes" + "encoding/binary" + "errors" + "image" +) + +// The largest image Safe passes: phones decode what they are sent, so a +// small file claiming a huge canvas must never reach them. +const ( + safePixels = 40_000_000 + safeSide = 8192 +) + +// Safe is data, an image from a source the bot doesn't trust, made safe to +// send to a chat: it fails for anything but a PNG, JPEG, GIF or WebP whose +// header gives at most safePixels pixels and safeSide a side, and a JPEG +// loses its metadata (EXIF, which can hold where a photo was taken, XMP, +// Photoshop's IPTC, comments, and anything after the image) but keeps its +// EXIF orientation. Only headers and segments are read, never pixels; data +// is not checked for size, which is Sendable's job. +func Safe(data []byte) ([]byte, error) { + cfg, format, err := image.DecodeConfig(bytes.NewReader(data)) + if err != nil { + return nil, errors.New("not an image") + } + switch format { + case "png", "jpeg", "gif", "webp": + default: + return nil, errors.New("not an image") + } + if cfg.Width <= 0 || cfg.Height <= 0 || cfg.Width > safeSide || cfg.Height > safeSide || int64(cfg.Width)*int64(cfg.Height) > safePixels { + return nil, errors.New("image too large") + } + if format != "jpeg" { + return data, nil + } + return stripJPEG(data) +} + +// stripJPEG is a JPEG without its metadata segments, walking its markers +// and copying its scans as they are. An EXIF orientation other than upright +// is kept, in a new EXIF segment that holds nothing else. +func stripJPEG(data []byte) ([]byte, error) { + bad := errors.New("malformed JPEG") + if len(data) < 2 || data[0] != 0xff || data[1] != 0xd8 { + return nil, bad + } + out := append(make([]byte, 0, len(data)), 0xff, 0xd8) + oriented := false + for i := 2; ; { + if i >= len(data) || data[i] != 0xff { + return nil, bad + } + for i < len(data) && data[i] == 0xff { // fill bytes may come before a marker + i++ + } + if i >= len(data) { + return nil, bad + } + marker := data[i] + i++ + switch { + case marker == 0xd9: // EOI: what follows, such as another image, is dropped + return append(out, 0xff, 0xd9), nil + case marker == 0x01 || marker >= 0xd0 && marker <= 0xd7: // no length + out = append(out, 0xff, marker) + continue + } + if i+2 > len(data) { + return nil, bad + } + size := int(binary.BigEndian.Uint16(data[i:])) + if size < 2 || i+size > len(data) { + return nil, bad + } + payload := data[i+2 : i+size] + i += size + switch { + case marker == 0xe1: // EXIF or XMP + if !oriented && bytes.HasPrefix(payload, []byte("Exif\x00\x00")) { + if o := exifOrientation(payload[6:]); o > 1 { + out = append(out, orientationSegment(o)...) + oriented = true + } + } + continue + case marker == 0xed, marker == 0xfe: // Photoshop's IPTC, a comment + continue + case marker == 0xe2 && bytes.HasPrefix(payload, []byte("MPF\x00")): // points at images after EOI + continue + } + out = append(out, 0xff, marker) + out = append(out, data[i-size:i]...) + if marker == 0xda { // a scan: its data runs to the next marker but a restart + j := i + for ; j+1 < len(data); j++ { + if next := data[j+1]; data[j] == 0xff && next != 0 && (next < 0xd0 || next > 0xd7) { + break + } + } + if j+1 >= len(data) { + return nil, bad + } + out = append(out, data[i:j]...) + i = j + } + } +} + +// orientationSegment is an APP1 segment whose EXIF holds only orientation o. +func orientationSegment(o int) []byte { + seg := []byte("\xff\xe1\x00\x00Exif\x00\x00MM\x00\x2a\x00\x00\x00\x08\x00\x01\x01\x12\x00\x03\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00") + binary.BigEndian.PutUint16(seg[2:], uint16(len(seg)-2)) + binary.BigEndian.PutUint16(seg[4+6+8+2+8:], uint16(o)) + return seg +} diff --git a/internal/kit/img/safe_test.go b/internal/kit/img/safe_test.go new file mode 100644 index 0000000..eac81df --- /dev/null +++ b/internal/kit/img/safe_test.go @@ -0,0 +1,183 @@ +package img + +import ( + "bytes" + "encoding/binary" + "hash/crc32" + "image" + "image/color" + "image/gif" + "image/jpeg" + "slices" + "testing" +) + +// segment is a JPEG marker segment holding payload. +func segment(marker byte, payload []byte) []byte { + return append([]byte{0xff, marker, byte((len(payload) + 2) >> 8), byte(len(payload) + 2)}, payload...) +} + +// withSegments is a JPEG with segs put just after its start. +func withSegments(jpg []byte, segs ...[]byte) []byte { + out := slices.Clone(jpg[:2]) + for _, s := range segs { + out = append(out, s...) + } + return append(out, jpg[2:]...) +} + +func jpegBytes(t *testing.T, w, h int) []byte { + t.Helper() + var b bytes.Buffer + if err := jpeg.Encode(&b, noise(w, h), &jpeg.Options{Quality: 90}); err != nil { + t.Fatal(err) + } + return b.Bytes() +} + +// pngClaiming is a 2 by 2 PNG whose header claims w by h, with the header's +// checksum right, so only the pixels give it away. +func pngClaiming(t *testing.T, w, h int) []byte { + data := pngBytes(t) + binary.BigEndian.PutUint32(data[16:], uint32(w)) + binary.BigEndian.PutUint32(data[20:], uint32(h)) + binary.BigEndian.PutUint32(data[29:], crc32.ChecksumIEEE(data[12:29])) + return data +} + +// jpegClaiming is a small JPEG whose frame header claims w by h. +func jpegClaiming(t *testing.T, w, h int) []byte { + data := jpegBytes(t, 8, 8) + i := bytes.Index(data, []byte{0xff, 0xc0}) + if i < 0 { + t.Fatal("no frame header") + } + binary.BigEndian.PutUint16(data[i+5:], uint16(h)) + binary.BigEndian.PutUint16(data[i+7:], uint16(w)) + return data +} + +// gpsExif is an EXIF segment's payload with orientation 6 and a GPS +// latitude of 37° 48′ S. +func gpsExif() []byte { + var t bytes.Buffer + be := binary.BigEndian + t.WriteString("MM\x00\x2a\x00\x00\x00\x08") + binary.Write(&t, be, uint16(2)) // IFD0 at 8 + binary.Write(&t, be, [6]uint16{0x0112, 3, 0, 1, 6, 0}) + binary.Write(&t, be, []uint16{0x8825, 4, 0, 1}) + binary.Write(&t, be, uint32(38)) // the GPS IFD + binary.Write(&t, be, uint32(0)) + binary.Write(&t, be, uint16(2)) // the GPS IFD at 38 + binary.Write(&t, be, []uint16{0x0001, 2, 0, 2}) + t.WriteString("S\x00\x00\x00") + binary.Write(&t, be, []uint16{0x0002, 5, 0, 3}) + binary.Write(&t, be, uint32(68)) // the rationals + binary.Write(&t, be, uint32(0)) + binary.Write(&t, be, []uint32{37, 1, 48, 1, 0, 1}) + return append([]byte("Exif\x00\x00"), t.Bytes()...) +} + +// markers lists a JPEG's markers up to its first scan. +func markers(data []byte) []byte { + var ms []byte + for i := 2; i+4 <= len(data) && data[i] == 0xff && data[i+1] != 0xda; i += 2 + int(binary.BigEndian.Uint16(data[i+2:])) { + ms = append(ms, data[i+1]) + } + return ms +} + +func TestSafe(t *testing.T) { + photo := jpegBytes(t, 64, 48) + gps := gpsExif() + xmp := append([]byte("http://ns.adobe.com/xap/1.0/\x00"), "<x:xmpmeta>Alice</x:xmpmeta>"...) + iptc := []byte("Photoshop 3.0\x008BIM\x04\x04\x00\x00\x00\x00\x00\x08\x1c\x02\x5a\x00\x03Bob") + // A comment between the scan and the end, and a second image after it. + late := slices.Concat(photo[:len(photo)-2], segment(0xfe, []byte("Bob was here")), []byte{0xff, 0xd9}, photo) + var g bytes.Buffer + gif.Encode(&g, image.NewPaletted(image.Rect(0, 0, 3, 3), color.Palette{color.White, color.Black}), nil) + + for _, c := range []struct { + name string + data []byte + wantErr string + same bool // comes out as it went in + strip bool // a JPEG that comes out without its metadata + orient int // the orientation it comes out with + gone [][]byte + }{ + {name: "png", data: pngBytes(t), same: true}, + {name: "gif", data: g.Bytes(), same: true}, + {name: "png at the limits", data: pngClaiming(t, safeSide, safePixels/safeSide), same: true}, + {name: "png bomb", data: pngClaiming(t, 100_000, 100_000), wantErr: "image too large"}, + {name: "png too many pixels", data: pngClaiming(t, safeSide, safePixels/safeSide+1), wantErr: "image too large"}, + {name: "png too wide", data: pngClaiming(t, safeSide+1, 10), wantErr: "image too large"}, + {name: "png too tall", data: pngClaiming(t, 10, safeSide+1), wantErr: "image too large"}, + {name: "jpeg bomb", data: jpegClaiming(t, 8000, 8000), wantErr: "image too large"}, + {name: "text", data: []byte("hello"), wantErr: "not an image"}, + {name: "empty", data: nil, wantErr: "not an image"}, + {name: "bmp", data: []byte("BM\x3a\x00\x00\x00\x00\x00\x00\x00\x36\x00\x00\x00\x28\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x01\x00\x18\x00"), wantErr: "not an image"}, + {name: "truncated jpeg", data: photo[:len(photo)/2], wantErr: "malformed JPEG"}, + {name: "plain jpeg", data: photo, strip: true}, + {name: "jpeg with metadata", data: withSegments(photo, segment(0xe1, gps), segment(0xe1, xmp), segment(0xed, iptc), segment(0xfe, []byte("Alice's"))), strip: true, orient: 6, + gone: [][]byte{gps[len(gps)-24:], []byte("S\x00\x00\x00"), []byte("xmpmeta"), []byte("Alice"), []byte("Bob"), []byte("Photoshop")}}, + {name: "jpeg with late comment and trailer", data: late, strip: true, gone: [][]byte{[]byte("Bob")}}, + {name: "jpeg with fill bytes", data: withSegments(photo, []byte{0xff, 0xff}, segment(0xfe, []byte("Alice"))), strip: true, gone: [][]byte{[]byte("Alice")}}, + } { + t.Run(c.name, func(t *testing.T) { + got, err := Safe(c.data) + if c.wantErr != "" { + if err == nil || err.Error() != c.wantErr { + t.Fatalf("%d bytes, %v", len(got), err) + } + return + } + if err != nil { + t.Fatal(err) + } + if c.same && !bytes.Equal(got, c.data) { + t.Fatal("changed") + } + for _, s := range c.gone { + if bytes.Contains(got, s) { + t.Errorf("still has %q", s) + } + } + if !c.strip { + return + } + if o := orientation(got); o != c.orient { + t.Errorf("orientation %d", o) + } + for _, m := range markers(got) { + if m == 0xed || m == 0xfe || m == 0xe1 && c.orient == 0 { + t.Errorf("still has marker %x", m) + } + } + if n := bytes.Count(got, []byte{0xff, 0xd8}); n != 1 { + t.Errorf("%d images", n) + } + want, err := jpeg.Decode(bytes.NewReader(photo)) + if err != nil { + t.Fatal(err) + } + out, err := jpeg.Decode(bytes.NewReader(got)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(out.(*image.YCbCr).Y, want.(*image.YCbCr).Y) || !bytes.Equal(out.(*image.YCbCr).Cb, want.(*image.YCbCr).Cb) { + t.Error("pixels changed") + } + }) + } +} + +// The orientation segment Safe writes reads back as the orientation it keeps. +func TestOrientationSegment(t *testing.T) { + photo := jpegBytes(t, 8, 8) + for o := 1; o <= 8; o++ { + if got := orientation(withSegments(photo, orientationSegment(o))); got != o { + t.Errorf("wrote %d, read %d", o, got) + } + } +} diff --git a/internal/signal/decode.go b/internal/signal/decode.go index fafce92..c70dab1 100644 --- a/internal/signal/decode.go +++ b/internal/signal/decode.go @@ -500,3 +500,26 @@ func (c *Client) Delivered(ctx context.Context, msg feature.Message) (bot.Ready, r.Message = msg return r, true } + +// Reachable reports whether the bot may still post in chat on its own, +// waiting up to 10s for signal-cli: in a group, while the bot is a member +// (listGroups); in a DM, while the user is in SIGNAL_DM_USER_IDS, by ACI or +// number. A failure is logged. +func (c *Client) Reachable(ctx context.Context, chat feature.Chat) bool { + wait, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + if c.WaitID(wait) == "" { + logx.Warnf("post dropped: not connected to signal-cli after 10s") + return false + } + if chat.GroupID == "" { + c.loadNames(wait, &envelope{}) + return c.allowed[chat.User] || c.allowed[c.number(chat.User)] + } + var gs []group + if err := c.call(wait, "listGroups", nil, &gs); err != nil { + logx.Warnf("post dropped: listGroups failed: %v", err) + return false + } + return slices.ContainsFunc(gs, func(g group) bool { return g.IsMember && g.ID == chat.GroupID }) +} diff --git a/internal/signal/decode_test.go b/internal/signal/decode_test.go index 8a19f58..99b7280 100644 --- a/internal/signal/decode_test.go +++ b/internal/signal/decode_test.go @@ -262,6 +262,29 @@ func TestLoad(t *testing.T) { } } +// The bot may post on its own in a group it is still a member of, and in +// the DM of someone still allowed, by ACI or number. +func TestReachable(t *testing.T) { + captureLogs(t) + f := newFake(t) + f.set("listContacts", `[{"uuid":"`+aliceID+`","number":"+1555","givenName":"Alice"},{"uuid":"`+bobID+`","givenName":"Bob"}]`) + f.set("listGroups", `[{"id":"`+groupID+`","isMember":true},{"id":"bGVmdA==","isMember":false}]`) + c := newClient(f.sock, map[string]bool{"+1555": true}, nil) + run(t, c, f) + ctx := context.Background() + for chat, want := range map[feature.Chat]bool{ + {User: aliceID}: true, + {User: bobID}: false, + {GroupID: groupID}: true, + {GroupID: "bGVmdA=="}: false, + {GroupID: "b3RoZXI="}: false, + } { + if got := c.Reachable(ctx, chat); got != want { + t.Errorf("%+v: %v", chat, got) + } + } +} + // A delivered message is checked as if its sender had just posted it: a // DM's sender must still be allowed, by ACI or number, and a group's still // a member. Its sender's name is filled in, the bot's @name is taken out, diff --git a/internal/telegram/decode.go b/internal/telegram/decode.go index 548149e..f00cd06 100644 --- a/internal/telegram/decode.go +++ b/internal/telegram/decode.go @@ -71,6 +71,19 @@ type sticker struct { Thumbnail *photoSize `json:"thumbnail"` } +// location is a point on a map; LivePeriod is set on a live location, one +// that follows its sender as they move. +type location struct { + Latitude float64 `json:"latitude"` + Longitude float64 `json:"longitude"` + LivePeriod int `json:"live_period"` +} + +// venue is a named place: only its location is read. +type venue struct { + Location location `json:"location"` +} + type message struct { MessageID int64 `json:"message_id"` ThreadID int64 `json:"message_thread_id"` @@ -92,6 +105,8 @@ type message struct { Audio *file `json:"audio"` Voice *file `json:"voice"` Sticker *sticker `json:"sticker"` + Location *location `json:"location"` + Venue *venue `json:"venue"` NewMembers []user `json:"new_chat_members"` LeftMember *user `json:"left_chat_member"` TimerChanged *struct { @@ -309,6 +324,9 @@ func (c *Client) message(m *message, edited int64) feature.Message { } ch := chatOf(m) body, mentioned := c.text(text, ents) + if link := mapLink(m); link != "" { + body = strings.TrimSpace(link + "\n" + body) + } msg := feature.Message{Chat: ch, Sender: id(m.From.ID), Name: nameOf(m.From), Text: body, Timestamp: m.MessageID, Edited: edited} self := c.selfID() replyToBot := m.ReplyTo != nil && m.ReplyTo.From != nil && id(m.ReplyTo.From.ID) == self @@ -371,6 +389,20 @@ func (c *Client) message(m *message, edited int64) feature.Message { return msg } +// mapLink is m's location or venue as a Google Maps link, which is how +// Signal sends one, or "" if it has none. A live location is left out: it +// is where its sender is right now. +func mapLink(m *message) string { + l := m.Location + if l == nil && m.Venue != nil { + l = &m.Venue.Location + } + if l == nil || l.LivePeriod != 0 { + return "" + } + return "https://maps.google.com/maps?q=" + strconv.FormatFloat(l.Latitude, 'f', -1, 64) + "," + strconv.FormatFloat(l.Longitude, 'f', -1, 64) +} + // best is the largest size of a photo within the bot's cap, or nil. func best(sizes []photoSize) *photoSize { var b *photoSize @@ -657,6 +689,22 @@ func (c *Client) Delivered(ctx context.Context, msg feature.Message) (bot.Ready, return r, true } +// Reachable reports whether the bot may still post in chat on its own: +// in a group, while it answers there (groupAllowed); in a DM, while the +// user is in TELEGRAM_DM_USER_IDS. +func (c *Client) Reachable(ctx context.Context, chat feature.Chat) bool { + wait, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + if c.WaitID(wait) == "" { + logx.Warnf("post dropped: not connected to Telegram after 10s") + return false + } + if chat.GroupID == "" { + return c.allowed[chat.User] + } + return c.groupAllowed(wait, c.dest(chat).chat) +} + // member reports whether user is in group, by getChatMember, logging a // failure. func (c *Client) member(ctx context.Context, group, user string) bool { diff --git a/internal/telegram/telegram_test.go b/internal/telegram/telegram_test.go index 40b58d7..94b4c0f 100644 --- a/internal/telegram/telegram_test.go +++ b/internal/telegram/telegram_test.go @@ -247,6 +247,34 @@ func TestMessage(t *testing.T) { } } +// A location or venue is a Google Maps link, as Signal sends one, ahead of +// any caption; a live location, where its sender is now, is dropped. +func TestLocation(t *testing.T) { + c := connected(newFake(t).client("1111111")) + for _, tc := range []struct{ name, msg, text string }{ + {"location", `"location":{"latitude":-37.8136,"longitude":144.9631}`, "https://maps.google.com/maps?q=-37.8136,144.9631"}, + {"captioned", `"location":{"latitude":48.8584,"longitude":2.2945},"caption":"my guess"`, "https://maps.google.com/maps?q=48.8584,2.2945\nmy guess"}, + {"venue", `"venue":{"location":{"latitude":51.5,"longitude":-0.1275},"title":"A place"}`, "https://maps.google.com/maps?q=51.5,-0.1275"}, + {"live", `"location":{"latitude":-37.8136,"longitude":144.9631,"live_period":900}`, ""}, + } { + r, ok := c.event(parse(t, `{"update_id":1,"message":{"message_id":10,`+fromA+`,`+inDM+`,`+tc.msg+`}}`)) + if tc.text == "" { + if ok { + t.Errorf("%s: kept %+v", tc.name, r) + } + continue + } + in, _ := r.(bot.Incoming) + if !ok || in.Load == nil { + t.Errorf("%s: dropped", tc.name) + continue + } + if m, _ := in.Load(context.Background(), func(string, string) {}); m.Text != tc.text { + t.Errorf("%s: %q", tc.name, m.Text) + } + } +} + // An edit is the message as it now reads, named by its message ID; in the // DM of someone the bot doesn't answer it forgets the original. func TestEdits(t *testing.T) { @@ -450,6 +478,26 @@ func TestDelivered(t *testing.T) { } } +// The bot may post on its own in a listed user's DM, and in a group while +// someone listed is a member. +func TestReachable(t *testing.T) { + captureLogs(t) + f := newFake(t) + c := connected(f.client("1111111")) + ctx := context.Background() + if !c.Reachable(ctx, feature.Chat{User: "1111111"}) || c.Reachable(ctx, feature.Chat{User: "2222222"}) { + t.Fatal("DMs") + } + if !c.Reachable(ctx, feature.Chat{GroupID: groupS}) { + t.Fatal("a group with Alice in it") + } + c.gate = map[string]gateState{} + f.results["getChatMember"] = `{"status":"left"}` + if c.Reachable(ctx, feature.Chat{GroupID: groupS}) { + t.Fatal("a group no one listed is in") + } +} + // Groups are those the bot has seen and the user is in; a group the bot // was removed from is gone. func TestGroups(t *testing.T) { diff --git a/scenario_fakes_test.go b/scenario_fakes_test.go index b0ef4c6..af6c36d 100644 --- a/scenario_fakes_test.go +++ b/scenario_fakes_test.go @@ -13,6 +13,7 @@ import ( "bytes" "encoding/base64" "encoding/json" + "flag" "fmt" "image" "image/png" @@ -93,6 +94,11 @@ type world struct { // their arguments: echo_error with an error result, rpc_error with a // JSON-RPC error. BrokenMCP bool + // Addon adds a local MCP addon, "game" (see TestScenarioAddonProcess), + // allowed in the test group and DMs: /game starts a round, a picture + // with a watch for "guess <number>" and a guard; each guess it is sent + // gets a 📍. + Addon bool // StateDir is the bot's state directory (STATE_DIRECTORY), where it // saves what must survive a restart; a fresh one if "". Two bots given // the same one are the same bot before and after a restart. @@ -204,7 +210,7 @@ func newHarness(t *testing.T, w world) *harness { } h.startSignal() h.startModel() - if w.MCP || w.BrokenMCP { + if w.MCP || w.BrokenMCP || w.Addon { h.startMCP() } return h @@ -819,10 +825,11 @@ func (r modelRequest) last() chatMessage { // fakeMCPTool is a tool a fake MCP server lists, and what calling it returns. // A tool that fails echoes its arguments: fail is "result" for an error -// result, "rpc" for a JSON-RPC error. +// result, "rpc" for a JSON-RPC error. meta is its _meta, if any. type fakeMCPTool struct { name, description, result string fail string + meta map[string]any } func (h *harness) startMCP() { @@ -831,6 +838,9 @@ func (h *harness) startMCP() { {name: "get_quote", description: "Get the latest price of a stock", result: `{"content":[{"type":"text","text":"AAPL 230.10 USD"}]}`}, {name: "price_chart", description: "Draw a price chart of a stock", result: `{"content":[{"type":"image","mimeType":"image/png","data":"` + base64.StdEncoding.EncodeToString(scenarioPNG()) + `"},{"type":"text","text":"chart of AAPL"}]}`}, + // Tools that aren't for the model: never offered to it, nor named in its prompt. + {name: "bot_only", description: "For the bot", meta: map[string]any{"io.github.robdevops.signalbot/visibility": []string{"bot"}}}, + {name: "app_only", description: "For an app's UI", meta: map[string]any{"ui": map[string]any{"visibility": []string{"app"}}}}, }, "weather": { {name: "get_forecast", description: "Get the weather forecast for a place", result: `{"content":[{"type":"text","text":"sunny, 24C"}]}`}, @@ -862,6 +872,12 @@ func (h *harness) startMCP() { if h.w.BrokenMCP { entries = append(entries, `"broken":{"url":"`+urls["broken"]+`"}`) } + if h.w.Addon { + self, _ := json.Marshal(os.Args[0]) + entries = append(entries, `"game":{"command":`+string(self)+`,"args":["-test.run=^TestScenarioAddonProcess$","addon"],`+ + `"chat_commands":{"game":{"tool":"game","direct":true}},`+ + `"addon":{"chats":["`+idGroup+`"],"dms":true,"react":true,"watch":true}}`) + } cfg := `{"mcpServers":{` + strings.Join(entries, ",") + `}}` h.mcpConfig = filepath.Join(h.t.TempDir(), "mcp.json") if err := os.WriteFile(h.mcpConfig, []byte(cfg), 0o600); err != nil { @@ -895,8 +911,12 @@ func (h *harness) mcpHandler(server string, tools []fakeMCPTool) http.Handler { case "tools/list": var list []map[string]any for _, t := range tools { - list = append(list, map[string]any{"name": t.name, "description": t.description, - "inputSchema": map[string]any{"type": "object", "properties": map[string]any{"q": map[string]string{"type": "string"}}}}) + entry := map[string]any{"name": t.name, "description": t.description, + "inputSchema": map[string]any{"type": "object", "properties": map[string]any{"q": map[string]string{"type": "string"}}}} + if t.meta != nil { + entry["_meta"] = t.meta + } + list = append(list, entry) } b, _ := json.Marshal(map[string]any{"tools": list}) result = string(b) @@ -927,6 +947,59 @@ func (h *harness) mcpHandler(server string, tools []fakeMCPTool) http.Handler { }) } +// TestScenarioAddonProcess is not a scenario: run as a subprocess with the +// argument "addon", it is the "game" addon, a stdio MCP server speaking +// signalbot's extension. Its tools are for the bot only: game answers with +// a picture and a watch, for an hour, on "guess <number>" with a guard; +// guess answers each guess with a 📍. It exits when its stdin closes. +func TestScenarioAddonProcess(t *testing.T) { + if flag.Arg(0) != "addon" { + return + } + bot := map[string]any{"io.github.robdevops.signalbot/visibility": []string{"bot"}} + sc := bufio.NewScanner(os.Stdin) + sc.Buffer(nil, 8<<20) + for sc.Scan() { + var req struct { + ID *int64 `json:"id"` + Method string `json:"method"` + Params struct { + Name string `json:"name"` + } `json:"params"` + } + json.Unmarshal(sc.Bytes(), &req) + if req.ID == nil { + continue + } + var result any = map[string]any{} + switch req.Method { + case "initialize": + result = map[string]any{"protocolVersion": "2025-06-18", "serverInfo": map[string]string{"name": "game", "title": "Game", "version": "1"}, + "capabilities": map[string]any{"tools": map[string]any{}, "experimental": map[string]any{"io.github.robdevops.signalbot/addon": map[string]int{"version": 1}}}} + case "tools/list": + result = map[string]any{"tools": []any{ + map[string]any{"name": "game", "inputSchema": map[string]string{"type": "object"}, "_meta": bot}, + map[string]any{"name": "guess", "inputSchema": map[string]string{"type": "object"}, "_meta": bot}, + }} + case "tools/call": + switch req.Params.Name { + case "game": + result = map[string]any{ + "content": []any{map[string]string{"type": "text", "text": "Round on"}, + map[string]string{"type": "image", "mimeType": "image/png", "data": base64.StdEncoding.EncodeToString(scenarioPNG())}}, + "_meta": map[string]any{"io.github.robdevops.signalbot/watch": map[string]string{"id": "r1", "pattern": `\bguess \d+`, + "until": time.Now().Add(time.Hour).Format(time.RFC3339), "tool": "guess", "guard": "No hints during a round"}}} + case "guess": + result = map[string]any{"content": []any{map[string]string{"type": "text", "text": "Recorded"}}, + "_meta": map[string]string{"io.github.robdevops.signalbot/react": "📍"}} + } + } + b, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": *req.ID, "result": result}) + fmt.Println(string(b)) + } + os.Exit(0) +} + // toolCalls is every MCP tool call, as "server/tool arguments". func (h *harness) toolCalls() []string { h.mu.Lock() diff --git a/scenario_test.go b/scenario_test.go index 7c0999d..118ffb5 100644 --- a/scenario_test.go +++ b/scenario_test.go @@ -1251,13 +1251,14 @@ func TestScenarioOtherProviderRejectsTools(t *testing.T) { // With no model, the bot answers only commands: a mention or a DM gets no // reply, no typing and no model request, group chatter isn't kept, MCP -// connects to no server, and a scheduled plain text is still posted. +// connects to no server but an addon (there is none), and a scheduled +// plain text is still posted. func TestScenarioNoModel(t *testing.T) { h := startBot(t, world{NoModel: true, MCP: true, Contacts: map[string]string{idAlice: "Alice", idBob: "Bob"}}) if l, ok := h.logged("no model: set MODEL_API_KEY (or MODEL_API_URL for a provider that needs no key); until then only commands are answered"); !ok || l.Pri != 4 { t.Fatalf("no notice: %v", h.logLines()) } - if _, ok := h.logged("MCP_CONFIG is set but no model is configured, so MCP servers were not started"); !ok { + if _, ok := h.logged("MCP_CONFIG is set but no model is configured, so only addon servers were started"); !ok { t.Fatalf("no MCP line: %v", h.logLines()) } if _, ok := h.logged("web search on"); ok { @@ -1991,6 +1992,75 @@ func checkToolReplay(t *testing.T, r modelRequest, tool, result string) { } } +// An addon's round watches the group for guesses: one sent as a reply to +// the round's photo, addressed to the bot, and one in passing both go to +// the addon, which pins them, and never to the model or history. A reply +// to the photo that isn't a guess gets the guard, not the model; other +// chatter is still context. +func TestScenarioAddonGuessInTheGroup(t *testing.T) { + h := startBot(t, world{Addon: true, Contacts: map[string]string{idAlice: "Alice", idBob: "Bob"}}) + if s := h.ask(atBot("/game")); s.GroupID != idGroup || s.Message != "Round on" || len(s.Attachments) != 1 { + t.Fatalf("sent %+v", s) + } + photo := h.lastSentAt() + + guess := inGroup("my guess 42").by(idBob, "Bob") + guess.Quote = "eOf{Author: idBot, Text: "Round on", Sent: photo} + h.receive(guess.frame()) + h.waitFor("a pin", func() bool { return len(h.callsTo("sendReaction")) == 1 }) + h.receive(inGroup("guess 7, maybe").frame()) + h.waitFor("a second pin", func() bool { return len(h.callsTo("sendReaction")) == 2 }) + for i, p := range h.callsTo("sendReaction") { + if p["emoji"] != "📍" || p["groupId"] != idGroup || p["targetAuthor"] != []string{idBob, idAlice}[i] { + t.Fatalf("sendReaction %v", p) + } + } + h.noMoreSends() + + hint := inGroup("where is this?") + hint.Quote = "eOf{Author: idBot, Text: "Round on", Sent: photo} + if s := h.ask(hint); s.Message != "No hints during a round" { + t.Fatalf("sent %+v", s) + } + h.ignored(inGroup("what a lovely view")) + if n := len(h.requests()); n != 0 { + t.Fatalf("%d model requests", n) + } + h.ask(atBot("anything new?")) + for _, c := range h.lastRequest().contents() { + if strings.Contains(c, "guess") { + t.Fatalf("a guess reached the model: %v", h.lastRequest().contents()) + } + } + if !slices.ContainsFunc(h.lastRequest().contents(), func(c string) bool { return strings.Contains(c, "what a lovely view") }) { + t.Fatalf("chatter isn't context: %v", h.lastRequest().contents()) + } +} + +// In an allowed DM, every message is addressed: a guess during a round goes +// to the addon, never to the model or history. +func TestScenarioAddonGuessInADM(t *testing.T) { + h := startBot(t, world{Addon: true}) + if s := h.ask(fromAlice("/game")); s.Recipient != idAlice || s.Message != "Round on" { + t.Fatalf("sent %+v", s) + } + h.receive(fromAlice("guess 12").frame()) + h.waitFor("a pin", func() bool { return len(h.callsTo("sendReaction")) == 1 }) + if p := h.callsTo("sendReaction")[0]; p["emoji"] != "📍" || fmt.Sprint(p["recipient"]) != "["+idAlice+"]" { + t.Fatalf("sendReaction %v", p) + } + h.noMoreSends() + if n := len(h.requests()); n != 0 { + t.Fatalf("%d model requests", n) + } + h.ask(fromAlice("hello")) + for _, c := range h.lastRequest().contents() { + if strings.Contains(c, "guess") { + t.Fatalf("a guess reached the model: %v", h.lastRequest().contents()) + } + } +} + // With require_arg, a bare command is answered by the bot, not the model. func TestScenarioChatCommandRequiresArg(t *testing.T) { h := startBot(t, world{MCP: true}) From 831434a1d1e2e93367f0d60f26189be03ee82554 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Fri, 20 Nov 2026 04:56:04 +0000 Subject: [PATCH 02/26] Signal: the bot's commands work in groups without a mention A group message that starts with one of the bot's registered commands (/geo, /intro, an MCP chat command, ...) now counts as addressed, as Telegram already does with bot_command. Other slash words, and a command later in the message, are still chatter. The core hands the network the command names before Run: Network.Watch now takes bot.Watch{Events, Commands}. The Signal client checks them on the reader with feature.ParseCommand, with no I/O; Telegram ignores them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- PRIVACY.md | 2 +- README.md | 2 +- TECHNICAL.md | 2 +- cmd/geoguess/README.md | 3 +++ internal/bot/bot.go | 16 +++++++++++---- internal/bot/fakes_test.go | 7 ++++++- internal/bot/host_test.go | 4 ++++ internal/feature/command.go | 9 +++++++++ internal/signal/client.go | 7 ++++--- internal/signal/client_test.go | 6 +++--- internal/signal/decode.go | 24 +++++++++++++++++------ internal/signal/decode_test.go | 31 ++++++++++++++++++++++++++++-- internal/signal/members.go | 14 +++++++++++--- internal/telegram/client.go | 5 +++-- internal/telegram/telegram_test.go | 4 ++-- scenario_test.go | 14 ++++++++++++++ 16 files changed, 121 insertions(+), 29 deletions(-) diff --git a/PRIVACY.md b/PRIVACY.md index 228c228..17cdcc1 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -61,7 +61,7 @@ Logs go to the journal or Docker's log driver and are kept as long as your setti ## What the bot can see -In a group, signal-cli passes every message to the bot, which checks each one for whether it is addressed to it. Messages not addressed to it are never logged and never answered. Their text, with the sender's display name, is kept in that group's history as context, the same way and for the same time as everything else there, unless `GROUP_CONTEXT=false`, in which case they are dropped on the spot. In DMs, the bot answers only the IDs listed in `SIGNAL_DM_USER_IDS`. A message an addon's watch takes (see below) is neither answered nor kept, even as context. +In a group, signal-cli passes every message to the bot, which checks each one for whether it is addressed to it: it mentions the bot, replies to it, or starts with one of its commands, such as `/intro`. Messages not addressed to it are never logged and never answered. Their text, with the sender's display name, is kept in that group's history as context, the same way and for the same time as everything else there, unless `GROUP_CONTEXT=false`, in which case they are dropped on the spot. In DMs, the bot answers only the IDs listed in `SIGNAL_DM_USER_IDS`. A message an addon's watch takes (see below) is neither answered nor kept, even as context. ## Telegram diff --git a/README.md b/README.md index 0801db5..8d685dd 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ A small, [privacy-conscious](PRIVACY.md) chat bot for Signal, through a running ## Features -- Responds to @mentions, replies to its messages, and DMs from whitelisted contacts +- Responds to @mentions, replies to its messages, its commands (such as `/intro`) without a mention, and DMs from whitelisted contacts - Tools: web search, line and pie charts, [pictures](docs/FILES_LINKS_TOOLS_MCP.md#images) (drawings, art, diagrams) with GPT Image 2, and your own [MCP connectors](docs/FILES_LINKS_TOOLS_MCP.md#mcp-connectors) - [`/schedule`](docs/SCHEDULING.md) a message or command, once or repeating - [Addons](docs/FILES_LINKS_TOOLS_MCP.md#addons): MCP servers that run their own commands and games in chosen groups, without the model, such as [GeoGuess](cmd/geoguess/README.md), seeing only pseudonyms diff --git a/TECHNICAL.md b/TECHNICAL.md index e7f936a..0d86ada 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -17,7 +17,7 @@ Go, the standard library plus `golang.org/x/image` (for chart text, with the bun What the bot does with no features registered. - **Receive.** JSON-RPC to `signal-cli daemon` over a unix socket or TCP (`listAccounts` once per connection to learn its own ID). If the connection drops it reconnects, waiting 1s, doubling up to 32s, reset once a connection has held for a minute; requests in flight fail rather than hang. Frames are capped at 17 MiB, room for a 12 MB image in base64; a longer frame is skipped with a warning and the request it answers (found by the `id` at its end) fails, but the connection is kept. The bot's own messages are ignored. -- **Addressed or not.** A message is answered if it mentions the bot, replies to one of its messages, or is a DM from a sender in `SIGNAL_DM_USER_IDS`, and it carries text, an attachment signal-cli can hand over (an ID, up to 12 MB: an image or any other file) or a sticker; anything else is never answered. A DM from anyone else is dropped and only the sender's ID is logged. An unaddressed group message goes to the features and is never logged. +- **Addressed or not.** A message is answered if it mentions the bot, replies to one of its messages, starts (in a group) with one of the bot's commands, or is a DM from a sender in `SIGNAL_DM_USER_IDS`, and it carries text, an attachment signal-cli can hand over (an ID, up to 12 MB: an image or any other file) or a sticker; anything else is never answered. A DM from anyone else is dropped and only the sender's ID is logged. An unaddressed group message goes to the features and is never logged. The commands are the names features registered with `Command` (as `/name` or `/name args`, any case), which the core hands the network before `Run` in `Network.Watch` (`bot.Watch{Events, Commands}`), so the reader decides without a lookup; another slash word, such as `/shrug`, or a command later in the message, is not one. Telegram marks a command at a message's start itself (`bot_command`), so its client ignores the list. - **Names** come from signal-cli's contact list (`listContacts` with `allRecipients`, at most 5,000), loaded on connect, on every group `UPDATE` event, and when a mention is unknown or the list is over 24 hours old, at most every 15s, with requests meanwhile folded into one. A group `UPDATE` also clears the names that chat remembers for turning `@Name` into mentions; it is a change, not a message, so no hook sees it, and it never takes a slot, even before the bot's own ID is known. An unresolved mention reaches the model as `[unnamed user]`; a group sender with no known name gets no prefix; an unknown quote author is "someone". The bot calls itself by its profile name, or `signalbot`. A name two people claim is never linked. - **Daily budget.** With `DAILY_BUDGET` above 0 (default 1) and an API that reports costs (OpenRouter's), each chat's spending is added up per day, midnight to midnight local time, from the cost each reply reports, every tool round included; scheduled runs count to their chat. Every request's cost counts, including those of a reply that fails or is retried. The limit is checked before each reply, so one expensive reply (several OCR'd PDFs, say) can take a chat past it; the next is refused. Before asking the model, a chat at or over the limit gets "I've reached today's spending limit for this chat, so I'll answer again in N hours. Commands that don't need me to think still work." (the time to midnight rounded up to whole minutes, and from 60 minutes to whole hours), once a day with one warning that names no one, and until midnight each further message it would ask the model about gets a ⏳ reaction instead (one sent by the bot, a scheduled post, gets nothing), so the bot is seen to be paused rather than broken; an `Answer` (a command that needs no model) is still sent. Today's spending is saved in `budget.json` in `STATE_DIRECTORY` (`kit/fsx.WriteAtomic`, as schedules are) under the SHA-256 of each chat's key, so the file holds no IDs, and only for chats that spent something today; at midnight it is rewritten empty, and a file from an earlier day, or one that can't be read, starts the day at 0. With another API one startup line says the cap isn't applied, a warning if `DAILY_BUDGET` was set. - **Reactions.** A reply that is exactly one emoji, by `txt.SingleEmoji` (a flag, a keycap, or one pictograph with its variation selector, skin tone or tags, or several joined by zero-width joiners; a symbol below U+10000 counts only if Unicode shows it as emoji by default, or with U+FE0F, so ✓ or ★ is text), and nothing else, is sent with `Network.React` as a reaction to the message answered (signal-cli `sendReaction` with its sender and `timestamp`), not as a message; history keeps "[reacted 🙏]". A merged batch reacts to its last message, and a message the bot made, such as a scheduled post, has no timestamp, so its emoji goes out as a message. The prompt's line says that a message needing no answer, such as thanks, gets a single emoji, sent as a reaction, and that a question or request always gets words; what happens is decided by code. A lone emoji, with no tool used, for a message whose own words matched a tool group's `Keywords` is not taken as the answer: that message asked for something, so the model is asked once more with "[This message asks you for something: answer it in words, or with a tool if one fits, not with an emoji alone.]" after it, and its second answer stands, a reaction if it is again an emoji. diff --git a/cmd/geoguess/README.md b/cmd/geoguess/README.md index 945ce4c..e66a870 100644 --- a/cmd/geoguess/README.md +++ b/cmd/geoguess/README.md @@ -14,6 +14,9 @@ bot names the place and ranks players by how far off they were. /geo scores this chat's totals over the last 7 days ``` +Nobody needs to mention the bot: a message that starts with `/geo`, and any +guess during a round, reaches it as it is. + It is a separate program that signalbot starts as an [MCP addon](../../docs/FILES_LINKS_TOOLS_MCP.md#addons) server. It speaks MCP 2025-06-18 over stdio (newline-delimited JSON-RPC) by hand, with signalbot's diff --git a/internal/bot/bot.go b/internal/bot/bot.go index 4554ade..e5858db 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -30,9 +30,11 @@ type Network interface { // Run calls handle for each message received until ctx ends. handle // must not block. Run(ctx context.Context, handle func(Received)) - // Watch says whether any feature has an event hook, before Run, so the - // network can skip work for events nothing would read. - Watch(events bool) + // Watch says, before Run, what the network should look out for: whether + // any feature has an event hook, so it can skip work for events nothing + // would read, and the commands features registered, so a group message + // that starts with one counts as addressed to the bot. + Watch(w Watch) WaitID(ctx context.Context) string // Send posts a reply, split as the network needs, and returns the // timestamps of the messages sent, which name them for a later delete. @@ -57,6 +59,12 @@ type Network interface { Redact(text string) string } +// Watch is what the network should look out for, set once before Run. +type Watch struct { + Events bool // a feature has an OnEvent hook + Commands []string // the commands features registered, lowercase, without "/" +} + // Member is a group member: a display name and the network's ID for them, // "" if they can never be linked. type Member struct{ Name, ID string } @@ -144,7 +152,7 @@ func (b *Bot) Run() { b.timers.Run(b.timerCtx) } }) - b.net.Watch(len(b.events) > 0) + b.net.Watch(Watch{Events: len(b.events) > 0, Commands: b.commands.Names()}) b.net.Run(b.ctx, b.handle) b.stopTimers() b.running.Wait() diff --git a/internal/bot/fakes_test.go b/internal/bot/fakes_test.go index 823718d..a306748 100644 --- a/internal/bot/fakes_test.go +++ b/internal/bot/fakes_test.go @@ -55,6 +55,7 @@ type fakeNet struct { typing int // Typing calls fetched []string // the media IDs fetched sends atomic.Int64 // Send calls, for their timestamps + watch Watch // what Watch was told } type sent struct { @@ -64,7 +65,11 @@ type sent struct { known map[string]string } -func (n *fakeNet) Watch(bool) {} +func (n *fakeNet) Watch(w Watch) { + n.mu.Lock() + defer n.mu.Unlock() + n.watch = w +} func (n *fakeNet) Run(ctx context.Context, handle func(Received)) { n.handle = handle diff --git a/internal/bot/host_test.go b/internal/bot/host_test.go index 18f4fd5..496a547 100644 --- a/internal/bot/host_test.go +++ b/internal/bot/host_test.go @@ -147,6 +147,10 @@ func TestCommands(t *testing.T) { } h.receive(chatter("/hi")) // not addressed: not a command h.noSend() + h.net.mu.Lock() + w := h.net.watch + h.net.mu.Unlock() + equal(t, "commands the network watches for", w.Commands, []string{"hi", "pick"}) } // A group with Keywords is offered when a message matches, and for the diff --git a/internal/feature/command.go b/internal/feature/command.go index 9cfd272..d311f02 100644 --- a/internal/feature/command.go +++ b/internal/feature/command.go @@ -3,7 +3,9 @@ package feature import ( "context" "fmt" + "maps" "regexp" + "slices" "strings" "sync" "unicode" @@ -36,6 +38,13 @@ func (c *Commands) Take(name string) error { return nil } +// Names lists the command names taken, sorted. +func (c *Commands) Names() []string { + c.mu.Lock() + defer c.mu.Unlock() + return slices.Sorted(maps.Keys(c.taken)) +} + // CommandHook is the OnMessage hook for command name: an addressed message // that is "/name" or "/name args", the name in any case, gets fn's Action. func CommandHook(name string, fn func(ctx context.Context, m Message, args string) Action) func(context.Context, Message) Action { diff --git a/internal/signal/client.go b/internal/signal/client.go index ae44650..ee88be1 100644 --- a/internal/signal/client.go +++ b/internal/signal/client.go @@ -74,9 +74,10 @@ type Client struct { knownOnce sync.Once closed atomic.Bool // Run has returned names names - recent recent // attachments of recent messages, for replies to them - members members // each group's members, to tell who joined and left - test *config.Test // nil in production + recent recent // attachments of recent messages, for replies to them + members members // each group's members, to tell who joined and left + commands atomic.Pointer[map[string]bool] // the commands features registered (Watch) + test *config.Test // nil in production } // New makes the client its settings say: SIGNALCLI_SOCKET, host:port diff --git a/internal/signal/client_test.go b/internal/signal/client_test.go index 32b1357..2f7aa80 100644 --- a/internal/signal/client_test.go +++ b/internal/signal/client_test.go @@ -531,7 +531,7 @@ func TestMemberChanges(t *testing.T) { f.set("listContacts", `[{"uuid":"`+bobID+`","profile":{"givenName":"Bob"}},{"uuid":"`+aliceID+`","profile":{"givenName":"Alice"}}]`) listed(botID, aliceID) c := newClient(f.sock, allowAll(), &config.Test{ReloadGap: time.Millisecond}) - c.Watch(true) + c.Watch(bot.Watch{Events: true}) got, conn := run(t, c, f) eventually(t, "the first listGroups", func() bool { return len(f.calls("listGroups")) == 1 }) update := func(group string) { // and wait for its comparison, so the next answer is the next update's @@ -593,7 +593,7 @@ func TestMemberChangeRules(t *testing.T) { listed(botID, aliceID) test := &config.Test{ReloadGap: time.Millisecond} c := newClient(f.sock, allowAll(), test) - c.Watch(true) + c.Watch(bot.Watch{Events: true}) got, conn := run(t, c, f) eventually(t, "the first listGroups", func() bool { return len(f.calls("listGroups")) == 1 }) frame := func(from string) string { @@ -665,7 +665,7 @@ func TestMemberChangeRules(t *testing.T) { // never taken for one of them. func TestMembersWaitForTheBotsID(t *testing.T) { c := newClient("x", nil, nil) - c.Watch(true) + c.Watch(bot.Watch{Events: true}) if gs, ok := c.members.load(context.Background(), func(string, ...any) {}); ok || gs != nil { t.Fatalf("loaded %v before the ID was known", gs) } diff --git a/internal/signal/decode.go b/internal/signal/decode.go index c70dab1..413a73c 100644 --- a/internal/signal/decode.go +++ b/internal/signal/decode.go @@ -178,10 +178,11 @@ func isAllowed(env *envelope, allowed map[string]bool) bool { } // isAddressed reports whether env is for the bot: it mentions the bot, -// replies to one of its messages, or is a DM from an allowed sender, and -// has text, an attachment the bot can fetch or a sticker. It never blocks, -// so the reader can use it. -func isAddressed(env *envelope, self string, allowed map[string]bool) bool { +// replies to one of its messages, starts with one of the commands (in a +// group; a DM is decided by the allowlist), or is a DM from an allowed +// sender, and has text, an attachment the bot can fetch or a sticker. It +// never blocks, so the reader can use it. +func isAddressed(env *envelope, self string, allowed, commands map[string]bool) bool { d := env.DataMessage if d == nil || self == "" || fromSelf(env, self) { return false @@ -193,10 +194,21 @@ func isAddressed(env *envelope, self string, allowed map[string]bool) bool { if env.chat().GroupID == "" { return isAllowed(env, allowed) } + if name, _, ok := feature.ParseCommand(d.Message); ok && commands[name] { + return true + } return slices.ContainsFunc(d.Mentions, func(m mention) bool { return is(self, m.UUID, m.Number) }) || d.Quote != nil && is(self, d.Quote.AuthorUUID, d.Quote.Author) } +// commandSet is the commands features registered, nil before Watch. +func (c *Client) commandSet() map[string]bool { + if p := c.commands.Load(); p != nil { + return *p + } + return nil +} + // event is env as the core gets it, decided on the reader goroutine without // calling the network; false if the core has nothing to do with it. func (c *Client) event(env *envelope) (bot.Received, bool) { @@ -325,7 +337,7 @@ func (c *Client) person(uuid, source, number, sent string) feature.Person { // not allowed, which is logged by ID only. func (c *Client) judge(env *envelope, self string) (addressed, other bool) { switch { - case isAddressed(env, self, c.allowed): + case isAddressed(env, self, c.allowed, c.commandSet()): return true, false case fromSelf(env, self): case env.chat().GroupID == "": @@ -373,7 +385,7 @@ func (c *Client) message(env *envelope, self string) feature.Message { Expires: time.Duration(d.ExpiresInSeconds) * time.Second, Timestamp: env.Timestamp, Edited: env.edited, - Addressed: isAddressed(env, self, c.allowed), + Addressed: isAddressed(env, self, c.allowed, c.commandSet()), } var images, files []feature.Media add := func(as []attachment, quoted bool) { diff --git a/internal/signal/decode_test.go b/internal/signal/decode_test.go index 99b7280..c91cf42 100644 --- a/internal/signal/decode_test.go +++ b/internal/signal/decode_test.go @@ -30,6 +30,7 @@ const ( func TestAddressed(t *testing.T) { allowed := map[string]bool{"+1555": true} + commands := map[string]bool{"geo": true} for _, tc := range []struct { name, env string want bool @@ -49,15 +50,41 @@ func TestAddressed(t *testing.T) { {"empty DM", `{` + fromBob + `,"dataMessage":{"message":" "}}`, false}, {"no data message", `{` + fromBob + `}`, false}, {"the bot's own", `{"sourceUuid":"` + botID + `","dataMessage":{"message":"hi"}}`, false}, + {"a command in a group", `{` + fromBob + `,"dataMessage":{"message":"/geo",` + inGroup + `}}`, true}, + {"a command with args", `{` + fromBob + `,"dataMessage":{"message":" /geo 90s",` + inGroup + `}}`, true}, + {"a command in capitals", `{` + fromBob + `,"dataMessage":{"message":"/GEO",` + inGroup + `}}`, true}, + {"another slash word", `{` + fromBob + `,"dataMessage":{"message":"/shrug",` + inGroup + `}}`, false}, + {"a command without its slash", `{` + fromBob + `,"dataMessage":{"message":"geo 90s",` + inGroup + `}}`, false}, + {"a command mid-message", `{` + fromBob + `,"dataMessage":{"message":"try /geo",` + inGroup + `}}`, false}, + {"a command glued to more", `{` + fromBob + `,"dataMessage":{"message":"/geography",` + inGroup + `}}`, false}, + {"the bot's own command", `{"sourceUuid":"` + botID + `","dataMessage":{"message":"/geo",` + inGroup + `}}`, false}, + {"a command in a DM from anyone else", `{"sourceUuid":"` + aliceID + `","dataMessage":{"message":"/geo"}}`, false}, } { self := botID - if got := isAddressed(parse(t, tc.env), self, allowed); got != tc.want { + if got := isAddressed(parse(t, tc.env), self, allowed, commands); got != tc.want { t.Errorf("%s: %v", tc.name, got) } - if isAddressed(parse(t, tc.env), "", allowed) { + if isAddressed(parse(t, tc.env), "", allowed, commands) { t.Errorf("%s: addressed before the bot's ID is known", tc.name) } } + // With no commands registered, a slash word in a group is chatter. + if isAddressed(parse(t, `{`+fromBob+`,"dataMessage":{"message":"/geo",`+inGroup+`}}`), botID, allowed, nil) { + t.Error("a slash word is addressed with no commands registered") + } +} + +func TestWatchCommands(t *testing.T) { + captureLogs(t) + c := newClient("x", nil, nil) + env := parse(t, `{`+fromBob+`,"dataMessage":{"message":"/geo 90s",`+inGroup+`}}`) + if c.message(env, botID).Addressed { + t.Fatal("addressed before Watch named the commands") + } + c.Watch(bot.Watch{Commands: []string{"geo"}}) + if m := c.message(env, botID); !m.Addressed || m.Text != "/geo 90s" { + t.Errorf("after Watch: addressed %v, text %q", m.Addressed, m.Text) + } } func TestMessageInGroup(t *testing.T) { diff --git a/internal/signal/members.go b/internal/signal/members.go index 1b158c0..65b2636 100644 --- a/internal/signal/members.go +++ b/internal/signal/members.go @@ -35,9 +35,17 @@ type pending struct { quiet bool // every update was the bot's own: compared, but not reported } -// Watch tells the client whether the core has a hook for events; without -// one it neither loads nor compares members. -func (c *Client) Watch(events bool) { c.members.on.Store(events) } +// Watch tells the client whether the core has a hook for events (without +// one it neither loads nor compares members) and which commands features +// registered, so a group message starting with one is addressed. +func (c *Client) Watch(w bot.Watch) { + c.members.on.Store(w.Events) + commands := map[string]bool{} + for _, name := range w.Commands { + commands[name] = true + } + c.commands.Store(&commands) +} // start loads the groups' members once the bot's ID is known, so the first // update is compared with them; nothing is reported for those already there. diff --git a/internal/telegram/client.go b/internal/telegram/client.go index efbb089..0a3f452 100644 --- a/internal/telegram/client.go +++ b/internal/telegram/client.go @@ -197,8 +197,9 @@ func (c *Client) Prompt() string { } // Watch says whether the core has an event hook, so updates only events -// would use are skipped without one. -func (c *Client) Watch(events bool) { c.watch.Store(events) } +// would use are skipped without one. Its commands go unused: Telegram marks +// a command at the start of a message itself (bot_command). +func (c *Client) Watch(w bot.Watch) { c.watch.Store(w.Events) } // Run learns who the bot is, then long-polls getUpdates and hands each // update the core may act on to handle, on this goroutine, until ctx ends. diff --git a/internal/telegram/telegram_test.go b/internal/telegram/telegram_test.go index 94b4c0f..46764da 100644 --- a/internal/telegram/telegram_test.go +++ b/internal/telegram/telegram_test.go @@ -526,7 +526,7 @@ func TestEvents(t *testing.T) { if _, ok := c.event(parse(t, `{"update_id":1,"message_reaction":{`+inGroup+`,"message_id":500,"user":{"id":1111111,"first_name":"Alice"},"old_reaction":[],"new_reaction":[{"type":"emoji","emoji":"👍"}]}}`)); ok { t.Fatal("an event with no hook") } - c.Watch(true) + c.Watch(bot.Watch{Events: true}) c.groupAllowed(context.Background(), groupS) // Alice is in it c.Send(feature.Chat{GroupID: groupS}, "hello", nil, nil) // message 500, the bot's r, _ := c.event(parse(t, `{"update_id":2,"message_reaction":{`+inGroup+`,"message_id":500,"user":{"id":1111111,"first_name":"Alice"},"old_reaction":[{"type":"emoji","emoji":"👍"}],"new_reaction":[]}}`)) @@ -778,7 +778,7 @@ func TestNoOneListed(t *testing.T) { func TestEventsAfterExpiry(t *testing.T) { f := newFake(t) c := connected(f.client("1111111")) - c.Watch(true) + c.Watch(bot.Watch{Events: true}) c.gate[groupS] = gateState{ok: true, until: time.Now().Add(-time.Minute)} r, ok := c.event(parse(t, `{"update_id":1,"message_reaction":{`+inGroup+`,"message_id":9,"user":{"id":1111111,"first_name":"Alice"},"old_reaction":[],"new_reaction":[{"type":"emoji","emoji":"👍"}]}}`)) if _, isH := r.(bot.Happened); !ok || !isH { diff --git a/scenario_test.go b/scenario_test.go index 118ffb5..9c298ff 100644 --- a/scenario_test.go +++ b/scenario_test.go @@ -256,6 +256,20 @@ func TestScenarioReplyToBotIsAnswered(t *testing.T) { []string{`user: Alice: [Replying to a message attributed to you: "oil around 78"]` + "\nAre you still there"}) } +// A group message that starts with one of the bot's commands is for the bot, +// as on Telegram, without a mention; another slash word is still chatter. +func TestScenarioUntaggedCommandIsAnswered(t *testing.T) { + h := startBot(t, world{}) + if s := h.ask(inGroup("/intro")); s.GroupID != idGroup || !strings.HasPrefix(s.Message, "hi, I'm") { + t.Fatalf("sent %+v", s) + } + if n := len(h.requests()); n != 0 { + t.Fatalf("the model was asked %d times", n) + } + h.ignored(inGroup("/shrug")) + h.ignored(inGroup("try /intro")) +} + func TestScenarioAllowedDMIsAnswered(t *testing.T) { h := startBot(t, world{}) if s := h.ask(fromAlice("a test direct message")); s.Recipient != idAlice || s.GroupID != "" || s.Message != "ok" { From 072afebeab556b9742010ecd4eb6120c242619da Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Fri, 20 Nov 2026 04:58:20 +0000 Subject: [PATCH 03/26] Untagged commands: tests for the reader's choice, doc fixes Test that a group command becomes an addressed message on the reader only once Watch names it, more isAddressed cases (a command replying to someone else, a photo captioned with one, a sticker), and that Watch's commands leave member loading alone. Correct the Addressed field's comment and the watch paths in TECHNICAL.md, say how Telegram and Signal differ (any command at the start versus only the bot's own), and that on Telegram with privacy mode on GeoGuess's plain guesses need a reply to the photo. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- TECHNICAL.md | 4 ++-- cmd/geoguess/README.md | 7 +++++-- internal/feature/feature.go | 2 +- internal/signal/decode_test.go | 21 +++++++++++++++++++++ 4 files changed, 29 insertions(+), 5 deletions(-) diff --git a/TECHNICAL.md b/TECHNICAL.md index 0d86ada..55a080a 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -17,7 +17,7 @@ Go, the standard library plus `golang.org/x/image` (for chart text, with the bun What the bot does with no features registered. - **Receive.** JSON-RPC to `signal-cli daemon` over a unix socket or TCP (`listAccounts` once per connection to learn its own ID). If the connection drops it reconnects, waiting 1s, doubling up to 32s, reset once a connection has held for a minute; requests in flight fail rather than hang. Frames are capped at 17 MiB, room for a 12 MB image in base64; a longer frame is skipped with a warning and the request it answers (found by the `id` at its end) fails, but the connection is kept. The bot's own messages are ignored. -- **Addressed or not.** A message is answered if it mentions the bot, replies to one of its messages, starts (in a group) with one of the bot's commands, or is a DM from a sender in `SIGNAL_DM_USER_IDS`, and it carries text, an attachment signal-cli can hand over (an ID, up to 12 MB: an image or any other file) or a sticker; anything else is never answered. A DM from anyone else is dropped and only the sender's ID is logged. An unaddressed group message goes to the features and is never logged. The commands are the names features registered with `Command` (as `/name` or `/name args`, any case), which the core hands the network before `Run` in `Network.Watch` (`bot.Watch{Events, Commands}`), so the reader decides without a lookup; another slash word, such as `/shrug`, or a command later in the message, is not one. Telegram marks a command at a message's start itself (`bot_command`), so its client ignores the list. +- **Addressed or not.** A message is answered if it mentions the bot, replies to one of its messages, starts (in a group) with one of the bot's commands, or is a DM from a sender in `SIGNAL_DM_USER_IDS`, and it carries text, an attachment signal-cli can hand over (an ID, up to 12 MB: an image or any other file) or a sticker; anything else is never answered. A DM from anyone else is dropped and only the sender's ID is logged. An unaddressed group message goes to the features and is never logged. The commands are the names features registered with `Command` (as `/name` or `/name args`, any case), which the core hands the network before `Run` in `Network.Watch` (`bot.Watch{Events, Commands}`), so the reader decides without a lookup; another slash word, such as `/shrug`, or a command later in the message, is not one. Telegram marks a command at a message's start itself (`bot_command`), so its client ignores the list. The two differ in one way: Telegram counts any command at the start, registered or not (an unknown one then reaches the model, as a mention would), while Signal counts only the bot's own, since Signal has no `/name@bot` suffix to tell several bots' commands apart. - **Names** come from signal-cli's contact list (`listContacts` with `allRecipients`, at most 5,000), loaded on connect, on every group `UPDATE` event, and when a mention is unknown or the list is over 24 hours old, at most every 15s, with requests meanwhile folded into one. A group `UPDATE` also clears the names that chat remembers for turning `@Name` into mentions; it is a change, not a message, so no hook sees it, and it never takes a slot, even before the bot's own ID is known. An unresolved mention reaches the model as `[unnamed user]`; a group sender with no known name gets no prefix; an unknown quote author is "someone". The bot calls itself by its profile name, or `signalbot`. A name two people claim is never linked. - **Daily budget.** With `DAILY_BUDGET` above 0 (default 1) and an API that reports costs (OpenRouter's), each chat's spending is added up per day, midnight to midnight local time, from the cost each reply reports, every tool round included; scheduled runs count to their chat. Every request's cost counts, including those of a reply that fails or is retried. The limit is checked before each reply, so one expensive reply (several OCR'd PDFs, say) can take a chat past it; the next is refused. Before asking the model, a chat at or over the limit gets "I've reached today's spending limit for this chat, so I'll answer again in N hours. Commands that don't need me to think still work." (the time to midnight rounded up to whole minutes, and from 60 minutes to whole hours), once a day with one warning that names no one, and until midnight each further message it would ask the model about gets a ⏳ reaction instead (one sent by the bot, a scheduled post, gets nothing), so the bot is seen to be paused rather than broken; an `Answer` (a command that needs no model) is still sent. Today's spending is saved in `budget.json` in `STATE_DIRECTORY` (`kit/fsx.WriteAtomic`, as schedules are) under the SHA-256 of each chat's key, so the file holds no IDs, and only for chats that spent something today; at midnight it is rewritten empty, and a file from an earlier day, or one that can't be read, starts the day at 0. With another API one startup line says the cap isn't applied, a warning if `DAILY_BUDGET` was set. - **Reactions.** A reply that is exactly one emoji, by `txt.SingleEmoji` (a flag, a keycap, or one pictograph with its variation selector, skin tone or tags, or several joined by zero-width joiners; a symbol below U+10000 counts only if Unicode shows it as emoji by default, or with U+FE0F, so ✓ or ★ is text), and nothing else, is sent with `Network.React` as a reaction to the message answered (signal-cli `sendReaction` with its sender and `timestamp`), not as a message; history keeps "[reacted 🙏]". A merged batch reacts to its last message, and a message the bot made, such as a scheduled post, has no timestamp, so its emoji goes out as a message. The prompt's line says that a message needing no answer, such as thanks, gets a single emoji, sent as a reaction, and that a question or request always gets words; what happens is decided by code. A lone emoji, with no tool used, for a message whose own words matched a tool group's `Keywords` is not taken as the answer: that message asked for something, so the model is asked once more with "[This message asks you for something: answer it in words, or with a tool if one fits, not with an emoji alone.]" after it, and its second answer stands, a reaction if it is again an emoji. @@ -245,7 +245,7 @@ In `features.go` order, which is the order hooks run in and of the tools line an - **Pseudonyms:** an addon never sees a phone number, account ID or group ID. Each addon has its own key, HMAC-SHA256 of the secret and its server's name. A chat is `c_` and HMAC(key, `chat\0` + chat key); a sender `u_` and HMAC(key, `user\0` + chat key + `\0` + ID), so the same person is someone else in each chat, or with `global_ids` HMAC(key, `user\0` + ID), the same everywhere; each cut to 128 bits and written in lowercase base32. A ref, `r_` and 128 random bits, names one message, for a reaction, and is kept in memory for 24 hours. - **Context:** each `tools/call` the bot makes itself carries the message's context in `_meta["io.github.robdevops.signalbot/context"]`: `chat`, `sender`, `ref`, `addressed`, `group`, `sent` and `edited` (when the bot got the message and its edit, in Unix seconds, never the sender's clock; `edited` is 0 for an original), and `name`, the sender's display name, only with `names`. Otherwise the bot keeps, in memory for 24 hours, the last name it saw each pseudonym use in the chat: a `{u_…}` placeholder in an addon's answer or post becomes `@Name`, linked as a mention, or "someone". - **Direct commands:** a chat command with `direct` makes `/name args` a call the bot makes itself, without the model, to a tool whose visibility has `"bot"` (looked up among all the server's tools; one without it is skipped with a warning), with `{"args": "<text after the command>"}`. It runs in the message's slot, with 15s, and at most 2 at once per server: a third is told "<title> is busy, try again in a moment." at once. The title is the server's `serverInfo.title`, else its name, made safe. In a chat its `chats` or `dms` don't allow, it answers "/name isn't available in this chat.". The result's text parts, joined, become the `Answer` (placeholders filled in, capped at 4,000 characters) and its image parts up to 2 `Pictures`, 2 MB together after `img.Safe` (any left out are counted in a warning); a result with neither is `Done`. An error result, a timeout, a bad result or a server that can't be reached answers "<title> couldn't do that just now.". Each call logs the command, the tool, the outcome (ok, or a code), the time and the result's size. Direct commands are kept with no model or one that can't call tools; a server with no tool for the model lists them with `ListCommands` under its label. - - **Watches:** a direct command's result may ask, in `_meta["io.github.robdevops.signalbot/watch"]`, for a watch on the chat the command came from (the only way to make one, so an addon can't watch a chat it wasn't used in): an `id` (at most 64 bytes), an RE2 `pattern` (at most 1 KB), `until` (RFC 3339, cut to `watch_max` from now and never extended), the `tool` to call with each match (one the bot may call) and an optional `guard` (at most 500 characters). It needs `watch`, and at most 8 are live in a chat per addon (one with the same ID is replaced). A pattern that matches the empty string or any of about 200 ordinary chat lines in `corpus.go` is refused, so no watch is a feed of the chat; a refusal is logged by reason, never the pattern. One `OnMessage` hook, registered after the chat commands, checks each message with text in an allowed chat against the chat's live watches, on both paths: unaddressed ones on the reader goroutine (only a map lookup and the patterns, under a mutex held briefly), addressed ones (a reply to the bot, a DM, an @mention) in their slot. A watch matches any message the bot gets while it lasts, by when the bot got it, not by its `Timestamp` (on Signal the sender's clock, which may be behind); an edit, unless its original was claimed, only if its original's `Timestamp` is at or after the command's, so an older message's edit isn't taken. An addressed message with no text (a bare mention, or a reply with only a picture) is still checked for the guard. A match is `Done`, so it is never answered, sent to the model or kept in history, and `groupctx` never sees it; it is claimed for 48 hours (chat key, sender's pseudonym, sent time), so a later edit of it goes the same way, to the same tool, whether or not the watch is still live; and it is passed without waiting to the addon's watch worker, whose queue holds 256 (when full, "addon <name>: watch queue full, a matched message dropped", still `Done`). The worker calls the watch's tool with `{"text": …}` and the context, within 120 calls a minute per chat (bursts of 20; a match past it waits its turn in the worker's queue, while other chats' matches go ahead), and keeps a match whose call found the server down (not running, or exited before answering) at the head of the queue until the server has started again (or a minute has passed), dropping it with a warning after 3 such calls, and if the result's `_meta["io.github.robdevops.signalbot/react"]` is one emoji, reacts with it (`React`), which needs `react` and counts against the addon's rate. A watch whose command answered with pictures records, through `OnSent`, the timestamps of the messages they went out in; while it lives, an addressed message quoting one of them gets the `guard` as its `Answer`, so nobody can ask the model about the picture. + - **Watches:** a direct command's result may ask, in `_meta["io.github.robdevops.signalbot/watch"]`, for a watch on the chat the command came from (the only way to make one, so an addon can't watch a chat it wasn't used in): an `id` (at most 64 bytes), an RE2 `pattern` (at most 1 KB), `until` (RFC 3339, cut to `watch_max` from now and never extended), the `tool` to call with each match (one the bot may call) and an optional `guard` (at most 500 characters). It needs `watch`, and at most 8 are live in a chat per addon (one with the same ID is replaced). A pattern that matches the empty string or any of about 200 ordinary chat lines in `corpus.go` is refused, so no watch is a feed of the chat; a refusal is logged by reason, never the pattern. One `OnMessage` hook, registered after the chat commands, checks each message with text in an allowed chat against the chat's live watches, on both paths: unaddressed ones on the reader goroutine (only a map lookup and the patterns, under a mutex held briefly), addressed ones (a reply to the bot, a DM, an @mention, a command) in their slot. A watch matches any message the bot gets while it lasts, by when the bot got it, not by its `Timestamp` (on Signal the sender's clock, which may be behind); an edit, unless its original was claimed, only if its original's `Timestamp` is at or after the command's, so an older message's edit isn't taken. An addressed message with no text (a bare mention, or a reply with only a picture) is still checked for the guard. A match is `Done`, so it is never answered, sent to the model or kept in history, and `groupctx` never sees it; it is claimed for 48 hours (chat key, sender's pseudonym, sent time), so a later edit of it goes the same way, to the same tool, whether or not the watch is still live; and it is passed without waiting to the addon's watch worker, whose queue holds 256 (when full, "addon <name>: watch queue full, a matched message dropped", still `Done`). The worker calls the watch's tool with `{"text": …}` and the context, within 120 calls a minute per chat (bursts of 20; a match past it waits its turn in the worker's queue, while other chats' matches go ahead), and keeps a match whose call found the server down (not running, or exited before answering) at the head of the queue until the server has started again (or a minute has passed), dropping it with a warning after 3 such calls, and if the result's `_meta["io.github.robdevops.signalbot/react"]` is one emoji, reacts with it (`React`), which needs `react` and counts against the addon's rate. A watch whose command answered with pictures records, through `OnSent`, the timestamps of the messages they went out in; while it lives, an addressed message quoting one of them gets the `guard` as its `Answer`, so nobody can ask the model about the picture. - **Leases:** an addon may post or react only in a chat where it had a direct command or a watch match in the last 24 hours; the lease maps the chat's pseudonym to the chat. - **Outbox:** if the server advertises `resources.subscribe`, the bot sends `resources/subscribe` for `signalbot://outbox` after each (re)start's `initialize`, then reads it; otherwise the outbox is off, with a warning. Any `notifications/resources/updated` from the server marks the outbox as having news (whatever the URI, which may be under the one subscribed). One reader goroutine per addon reads `resources/read` of `signalbot://outbox/<cursor>` (`0` at first), page by page while `more` is true, up to 100 pages, so two reads never race and news during a read is read after it. A page is one text content holding `{"cursor", "more", "ops"}`; a not-found error (-32002, or the Go SDK's -32602) is logged as no outbox. Ops are applied once each by `id`, the last 1,000 IDs remembered, and are `post` (`chat`, Markdown `text` with placeholders, up to 2 `images` as `{data, mimeType, name}`, 2 MB together), needing `post`; `react` (`ref`, `emoji`), needing `react`; and `unwatch` (`chat`, `watch`), which, for a watch not yet made, stops it being made for 10 minutes. A post or reaction needs a live lease in a chat the addon is still allowed, and counts against `rate` per chat. A post goes through `Post` with the addon's title as its `Label`, so history keeps it as `[Title] …`, the bot's own words. At most one of an addon's posts waits in a chat's mailbox: until its `Done`, later posts for that chat are held, each merged into the one held before it while their pictures together stay within 2 and 2 MB, and sent in turn. Delivery is at least once: a post counts as applied, and the cursor moves past it, only once its `Done` says it was sent. Until then each read starts from the cursor before it and skips it while it waits; one dropped before it was sent (as while the bot stops, or before the network is up at startup, when `Post` gives up on the chat) is posted again by a read 10s later, then 20s, doubling to 5 minutes, not counted against `rate` again, and given up with a warning after 6 tries. A page with `more` waits for its posts before the next is read, since reading past the cursor lets the addon forget them. A read that fails, is malformed, or stops at 100 pages is tried again after 10s, doubling to 5 minutes, without waiting for news. What a read drops is counted in one warning by reason, never content. - **What is saved,** per addon, in `mcp.json`: live watches (with their guard pictures' timestamps), claims, leases, the outbox cursor and the last 1,000 applied op IDs. Anything expired is left out. At startup they are restored, leaving out a watch whose chat is no longer allowed or whose pattern no longer passes, so a restart of the bot or the addon never lets a match fall through to history. Refs, names, tombstones and held posts are in memory only. diff --git a/cmd/geoguess/README.md b/cmd/geoguess/README.md index e66a870..f207fe1 100644 --- a/cmd/geoguess/README.md +++ b/cmd/geoguess/README.md @@ -14,8 +14,11 @@ bot names the place and ranks players by how far off they were. /geo scores this chat's totals over the last 7 days ``` -Nobody needs to mention the bot: a message that starts with `/geo`, and any -guess during a round, reaches it as it is. +On Signal nobody needs to mention the bot: a message that starts with `/geo`, +and any guess during a round, reaches it as it is. On Telegram `/geo` works +the same way, but plain guesses reach the bot only with privacy mode off (or +the bot an admin); with privacy mode on, which is the default, players reply +to the round's photo instead. It is a separate program that signalbot starts as an [MCP addon](../../docs/FILES_LINKS_TOOLS_MCP.md#addons) server. It speaks MCP diff --git a/internal/feature/feature.go b/internal/feature/feature.go index 597e6e9..4a1ef06 100644 --- a/internal/feature/feature.go +++ b/internal/feature/feature.go @@ -42,7 +42,7 @@ type Message struct { Expires time.Duration // the chat's disappearing-messages timer; 0 if off Timestamp int64 // when it was sent, by the sender's clock, as the network names it; 0 for one the bot made, such as a scheduled post. An edit keeps the original's Edited int64 // for an edit of the message sent at Timestamp, which it replaces, when it was edited; 0 for an original - Addressed bool // it mentions the bot, replies to it, or is a DM from an allowed sender + Addressed bool // it mentions the bot, replies to it, starts (in a group) with one of the bot's commands, or is a DM from an allowed sender } // Quote is the message another one replies to, as the replier's app sent it. diff --git a/internal/signal/decode_test.go b/internal/signal/decode_test.go index c91cf42..d08d046 100644 --- a/internal/signal/decode_test.go +++ b/internal/signal/decode_test.go @@ -59,6 +59,9 @@ func TestAddressed(t *testing.T) { {"a command glued to more", `{` + fromBob + `,"dataMessage":{"message":"/geography",` + inGroup + `}}`, false}, {"the bot's own command", `{"sourceUuid":"` + botID + `","dataMessage":{"message":"/geo",` + inGroup + `}}`, false}, {"a command in a DM from anyone else", `{"sourceUuid":"` + aliceID + `","dataMessage":{"message":"/geo"}}`, false}, + {"a command replying to someone else", `{` + fromBob + `,"dataMessage":{"message":"/geo","quote":{"authorUuid":"` + aliceID + `"},` + inGroup + `}}`, true}, + {"a command as a photo's caption", `{` + fromBob + `,"dataMessage":{"message":"/geo","attachments":[{"contentType":"image/png","id":"a","size":10}],` + inGroup + `}}`, true}, + {"a sticker with no text", `{` + fromBob + `,"dataMessage":{"sticker":{"packId":"p","stickerId":1},` + inGroup + `}}`, false}, } { self := botID if got := isAddressed(parse(t, tc.env), self, allowed, commands); got != tc.want { @@ -81,10 +84,28 @@ func TestWatchCommands(t *testing.T) { if c.message(env, botID).Addressed { t.Fatal("addressed before Watch named the commands") } + connected(c) + if r, ok := c.event(env); !ok { + t.Fatal("dropped before Watch") + } else if _, isChatter := r.(bot.Chatter); !isChatter { + t.Errorf("before Watch the reader made %T, want chatter", r) + } c.Watch(bot.Watch{Commands: []string{"geo"}}) if m := c.message(env, botID); !m.Addressed || m.Text != "/geo 90s" { t.Errorf("after Watch: addressed %v, text %q", m.Addressed, m.Text) } + if r, ok := c.event(env); !ok { + t.Fatal("dropped after Watch") + } else if _, isIncoming := r.(bot.Incoming); !isIncoming { + t.Errorf("after Watch the reader made %T, want an addressed message", r) + } + if c.members.on.Load() { + t.Error("commands alone turned member loading on") + } + c.Watch(bot.Watch{Events: true}) + if !c.members.on.Load() { + t.Error("Events didn't turn member loading on") + } } func TestMessageInGroup(t *testing.T) { From 418f0b81fab8d3462b01703c578b6fab3f69e014 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Fri, 20 Nov 2026 05:33:07 +0000 Subject: [PATCH 04/26] =?UTF-8?q?GeoGuess:=20Signal's=20location=20button?= =?UTF-8?q?=20is=20+,=20not=20=F0=9F=93=8E?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signal shares a location from the + button, Telegram from 📎. GeoGuess doesn't know which network it runs on, so the round's caption and the README now give both. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- cmd/geoguess/README.md | 5 +++-- cmd/geoguess/game.go | 2 +- cmd/geoguess/geo/parse_test.go | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/cmd/geoguess/README.md b/cmd/geoguess/README.md index f207fe1..c2761b2 100644 --- a/cmd/geoguess/README.md +++ b/cmd/geoguess/README.md @@ -1,8 +1,9 @@ # GeoGuess A GeoGuessr-style game for signalbot. `/geo` posts a street-level photo; -players answer by sending a location (Signal's 📎 → Location with the pin -moved, or typed coordinates such as `-37.81, 144.96`); when time is up the +players answer by sending a location (on Signal, the **+** button → +Location; on Telegram, 📎 → Location; with the pin moved), or typed +coordinates such as `-37.81, 144.96`; when time is up the bot names the place and ranks players by how far off they were. ``` diff --git a/cmd/geoguess/game.go b/cmd/geoguess/game.go index c44bd0d..429814a 100644 --- a/cmd/geoguess/game.go +++ b/cmd/geoguess/game.go @@ -159,7 +159,7 @@ func (s *server) start(ctx context.Context, c *callContext, length time.Duration // caption is the photo's caption: how to guess, and by when. func caption(deadline time.Time, length time.Duration) string { return "🌍 **Where is this?** Send a location before " + deadline.Local().Format("15:04") + " (" + lengthLabel(length) + ").\n" + - "Signal: 📎 → Location → **drag the pin**, then send. Or type coordinates, e.g. `-37.81, 144.96`.\n" + + "Signal: **+** → Location; Telegram: 📎 → Location. **Drag the pin**, then send. Or type coordinates, e.g. `-37.81, 144.96`.\n" + "⚠️ Location starts at *your* position. Move the pin before you send." } diff --git a/cmd/geoguess/geo/parse_test.go b/cmd/geoguess/geo/parse_test.go index b7b9dbb..8a9796e 100644 --- a/cmd/geoguess/geo/parse_test.go +++ b/cmd/geoguess/geo/parse_test.go @@ -13,7 +13,7 @@ func TestParse(t *testing.T) { want Point ok bool }{ - // Signal Android's Attach → Location. + // Signal's + → Location. {"https://maps.google.com/maps?q=-37.8136%2C144.9631", mel, true}, {"https://maps.google.com/maps?q=-37.8136,144.9631", mel, true}, {"Here: https://maps.google.com/maps?q=-37.8136%2C144.9631.", mel, true}, From f66f276bb942fccd5d2f584f02b98f3c03ec2508 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Fri, 20 Nov 2026 05:33:57 +0000 Subject: [PATCH 05/26] GeoGuess: tell players to zoom out before dragging the pin The location picker opens close in on the player's own position, so the caption and README now say to pinch to zoom out first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- cmd/geoguess/README.md | 3 ++- cmd/geoguess/game.go | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/cmd/geoguess/README.md b/cmd/geoguess/README.md index c2761b2..97a547b 100644 --- a/cmd/geoguess/README.md +++ b/cmd/geoguess/README.md @@ -2,7 +2,8 @@ A GeoGuessr-style game for signalbot. `/geo` posts a street-level photo; players answer by sending a location (on Signal, the **+** button → -Location; on Telegram, 📎 → Location; with the pin moved), or typed +Location; on Telegram, 📎 → Location; then pinch to zoom out and drag the +pin), or typed coordinates such as `-37.81, 144.96`; when time is up the bot names the place and ranks players by how far off they were. diff --git a/cmd/geoguess/game.go b/cmd/geoguess/game.go index 429814a..c29f074 100644 --- a/cmd/geoguess/game.go +++ b/cmd/geoguess/game.go @@ -159,7 +159,7 @@ func (s *server) start(ctx context.Context, c *callContext, length time.Duration // caption is the photo's caption: how to guess, and by when. func caption(deadline time.Time, length time.Duration) string { return "🌍 **Where is this?** Send a location before " + deadline.Local().Format("15:04") + " (" + lengthLabel(length) + ").\n" + - "Signal: **+** → Location; Telegram: 📎 → Location. **Drag the pin**, then send. Or type coordinates, e.g. `-37.81, 144.96`.\n" + + "Signal: **+** → Location; Telegram: 📎 → Location. Pinch to zoom out, **drag the pin**, then send. Or type coordinates, e.g. `-37.81, 144.96`.\n" + "⚠️ Location starts at *your* position. Move the pin before you send." } From dd55483fe07c12ca3efeda9cdb68ce1034a1adf2 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Fri, 20 Nov 2026 05:43:47 +0000 Subject: [PATCH 06/26] Addons learn the chat network; GeoGuess's caption names only its steps MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each network names itself (Network.Name: "signal", "telegram"), the core reports it as Info.Network, and the mcp feature offers it to addons in the handshake: experimental["io.github.robdevops.signalbot/addon"] = {"version": 1, "network": ...}. GeoGuess reads it and words the round's caption for that network only (Signal's + button, or Telegram's 📎), and both when the bot offers none. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- TECHNICAL.md | 2 +- cmd/geoguess/README.md | 3 +++ cmd/geoguess/game.go | 17 ++++++++++++---- cmd/geoguess/main_test.go | 33 ++++++++++++++++++++++++++++++- cmd/geoguess/rpc.go | 14 +++++++++++-- cmd/geoguess/server.go | 1 + internal/bot/bot.go | 3 +++ internal/bot/fakes_test.go | 1 + internal/bot/host.go | 2 +- internal/feature/feature.go | 1 + internal/features/mcp/conn.go | 24 +++++++++++----------- internal/features/mcp/mcp.go | 33 ++++++++++++++++++++----------- internal/features/mcp/mcp_test.go | 15 ++++++++++---- internal/signal/names.go | 3 +++ internal/telegram/client.go | 3 +++ 15 files changed, 120 insertions(+), 35 deletions(-) diff --git a/TECHNICAL.md b/TECHNICAL.md index 55a080a..2536928 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -237,7 +237,7 @@ In `features.go` order, which is the order hooks run in and of the tools line an - Config errors stop the bot, each starting with the file's path and naming the server: a key that is neither a setting nor one other clients write (`type`, `transport`, `timeout`, `alwaysAllow`, `autoApprove`, `description`, ignored), with the settings listed, in a server or a chat command; both `allowed_tools` and `blocked_tools`; a tool name the server lacks, with the list it is in and the server's tools (the first 20, then "…"); and two tools that become one name for the model, naming both. An addon server adds its own (below). - Tools are filtered by `_meta`: a tool whose `io.github.robdevops.signalbot/visibility` array, or MCP Apps' `ui.visibility`, leaves out `"model"` is never offered to the model, nor listed in `{tools}` or the tools line. A missing array means the model may see it. The bot calls a tool itself (an addon's direct command or watch) only if signalbot's array has `"bot"`; MCP Apps' `"app"` means a UI, not the bot. - **`img.Safe`** (`kit/img`) checks any image from a server before it is sent: only PNG, JPEG, GIF or WebP, read from the header alone, at most 8,192 pixels a side and 40 megapixels, so a small file claiming a huge canvas never reaches phones; a JPEG loses its EXIF (keeping its orientation), XMP, IPTC, comments and anything after the image, by walking its segments without decoding pixels, since signal-cli sends attachments as they are and GPS tags would say where a photo was taken. -- **Addons** are local MCP servers with an `addon` block in `MCP_CONFIG` that also advertise `io.github.robdevops.signalbot/addon` at version 1 in their `initialize` result's `capabilities.experimental`. One with the block that doesn't advertise it runs as a plain server, with a warning. They are part of `mcp`: no port of the core names them. +- **Addons** are local MCP servers with an `addon` block in `MCP_CONFIG` that also advertise `io.github.robdevops.signalbot/addon` at version 1 in their `initialize` result's `capabilities.experimental`. The bot offers the same key in its `initialize` request with the chat network it is on, `{"version": 1, "network": "signal"}` (`Info.Network`, which each network names itself with `Network.Name`), so an addon can word its messages for that network. One with the block that doesn't advertise it runs as a plain server, with a warning. They are part of `mcp`: no port of the core names them. - **Config:** the block's keys are `chats` (group IDs exactly as Signal or Telegram shows them, a Telegram topic counting as its group, or `["all"]` alone; anything else is an error asking for the group's ID), `dms`, `post`, `react`, `watch` (each off unless set), `watch_max` (1s to 24h, default 1h), `names`, `global_ids` and `rate` (`per_minute`, default 20, and `burst`, default 5). Unknown keys get the same error as a server's. An addon must be local (`command`), can't have an `env` block, and its server's name can't make a prefix (below) that one of the bot's own settings starts with (the names in `docs/CONFIGURATION.md`'s table, plus `STATE_DIRECTORY`, a list a test keeps in step); a `direct` chat command without an addon block is an error. Its error text and its start, initialize and call failures are logged by code only, never the server's words. - **Environment:** an addon gets `PATH`, `HOME`, those of `TZ`, `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` (and their lowercase forms), `SSL_CERT_FILE` and `SSL_CERT_DIR` that are set, so it keeps the bot's time zone and reaches the internet as the bot does, and every variable of the bot's environment that starts with its prefix: its server's name in capitals, anything but letters and digits as `_`, then `_` (`geo` gets `GEO_…`). Nothing else, so the bot's keys never reach it. These are read with `os.Environ`, not `Env`, so each addon documents its own. - **Stderr:** an addon's is never logged, since it may write what it was sent: only "addon <name> wrote N lines (M bytes) to stderr", at most once a minute, and once more when it exits for what was counted since, so a crash's output is never left uncounted. diff --git a/cmd/geoguess/README.md b/cmd/geoguess/README.md index 97a547b..f106759 100644 --- a/cmd/geoguess/README.md +++ b/cmd/geoguess/README.md @@ -134,6 +134,9 @@ coordinate, a place or person's name, a pseudonym or message text. - `initialize` advertises `tools`, `resources.subscribe` and `experimental["io.github.robdevops.signalbot/addon"] = {"version": 1}`. + It reads the `network` the bot offers under the same key, and the round's + caption gives the steps for that network only (Signal's **+** button, or + Telegram's 📎); with none, it gives both. - `tools/list` has `geo` (`{args}`) and `geo_guess` (`{text}`), both with `_meta["io.github.robdevops.signalbot/visibility"] = ["bot"]`, so neither is offered to the model. diff --git a/cmd/geoguess/game.go b/cmd/geoguess/game.go index c29f074..6d3c840 100644 --- a/cmd/geoguess/game.go +++ b/cmd/geoguess/game.go @@ -141,13 +141,14 @@ func (s *server) start(ctx context.Context, c *callContext, length time.Duration } s.rounds[c.Chat] = r s.arm(r) + network := s.network s.mu.Unlock() s.save() s.log.Printf("round %s started: %s, a %s photo", r.ID, length, photo.Source) return toolResult{ Content: []content{ {Type: "image", Data: base64.StdEncoding.EncodeToString(photo.JPEG), MimeType: "image/jpeg"}, - {Type: "text", Text: caption(r.Deadline, length)}, + {Type: "text", Text: caption(r.Deadline, length, network)}, }, Meta: &resultMeta{Watch: &watch{ ID: r.ID, Pattern: geo.Pattern, Until: r.Deadline.Add(watchSlack).Format(time.RFC3339), @@ -156,10 +157,18 @@ func (s *server) start(ctx context.Context, c *callContext, length time.Duration } } -// caption is the photo's caption: how to guess, and by when. -func caption(deadline time.Time, length time.Duration) string { +// caption is the photo's caption: how to guess, on the chat network the +// bot said it is on, and by when. +func caption(deadline time.Time, length time.Duration, network string) string { + share := "Signal: **+** → Location; Telegram: 📎 → Location. Pinch to zoom out" + switch network { + case "signal": + share = "Tap **+** → Location, pinch to zoom out" + case "telegram": + share = "Tap 📎 → Location, pinch to zoom out" + } return "🌍 **Where is this?** Send a location before " + deadline.Local().Format("15:04") + " (" + lengthLabel(length) + ").\n" + - "Signal: **+** → Location; Telegram: 📎 → Location. Pinch to zoom out, **drag the pin**, then send. Or type coordinates, e.g. `-37.81, 144.96`.\n" + + share + ", **drag the pin**, then send. Or type coordinates, e.g. `-37.81, 144.96`.\n" + "⚠️ Location starts at *your* position. Move the pin before you send." } diff --git a/cmd/geoguess/main_test.go b/cmd/geoguess/main_test.go index 291aab0..dd6617d 100644 --- a/cmd/geoguess/main_test.go +++ b/cmd/geoguess/main_test.go @@ -380,6 +380,37 @@ const ( bob = "u_bob" ) +// The caption gives the steps for the network the bot said it is on, and +// both when it said none. +func TestCaption(t *testing.T) { + at := time.Date(2026, 11, 20, 14, 3, 0, 0, time.Local) + for _, tc := range []struct{ network, want, not string }{ + {"signal", "Tap **+** → Location, pinch to zoom out, **drag the pin**", "📎"}, + {"telegram", "Tap 📎 → Location, pinch to zoom out, **drag the pin**", "**+**"}, + {"", "Signal: **+** → Location; Telegram: 📎 → Location. Pinch to zoom out, **drag the pin**", "Tap"}, + } { + got := caption(at, 3*time.Minute, tc.network) + if !strings.Contains(got, tc.want) || strings.Contains(got, tc.not) || !strings.Contains(got, "14:03 (3 min)") || + !strings.Contains(got, "-37.81, 144.96") || !strings.Contains(got, "Move the pin before you send") { + t.Errorf("%q: %q", tc.network, got) + } + } +} + +// A round's caption uses the network the bot offered in the handshake. +func TestCaptionNetwork(t *testing.T) { + clk, c, _ := start(t) + var init initializeResult + c.result("initialize", map[string]any{ + "protocolVersion": protocolVersion, + "capabilities": map[string]any{"experimental": map[string]any{vendor + "addon": map[string]any{"version": 1, "network": "signal"}}}, + }, &init) + r := c.geo("90s", from(clk, chat, alice)) + if got := words(r); !strings.Contains(got, "Tap **+** → Location") || strings.Contains(got, "📎") { + t.Errorf("caption %q", got) + } +} + func TestInitializeAndTools(t *testing.T) { _, c, _ := start(t) var init initializeResult @@ -430,7 +461,7 @@ func TestRound(t *testing.T) { if data, _ := base64.StdEncoding.DecodeString(r.Content[0].Data); !bytes.HasPrefix(data, []byte("jpeg ")) { t.Errorf("image %q", data) } - want := caption(began.Add(90*time.Second), 90*time.Second) + want := caption(began.Add(90*time.Second), 90*time.Second, "") if words(r) != want || !strings.Contains(want, "(90 sec)") { t.Errorf("caption %q", words(r)) } diff --git a/cmd/geoguess/rpc.go b/cmd/geoguess/rpc.go index 39c46e2..8002839 100644 --- a/cmd/geoguess/rpc.go +++ b/cmd/geoguess/rpc.go @@ -206,7 +206,8 @@ type ( Resources resourcesCapability `json:"resources"` } addonCapability struct { - Version int `json:"version"` + Version int `json:"version"` + Network string `json:"network,omitempty"` // the bot's chat network, as the bot offers it } resourcesCapability struct { Subscribe bool `json:"subscribe"` @@ -298,7 +299,16 @@ type callContext struct { // methods are the MCP methods GeoGuess answers. func (s *server) methods() map[string]handler { return map[string]handler{ - "initialize": func(context.Context, json.RawMessage) (any, error) { + "initialize": func(_ context.Context, raw json.RawMessage) (any, error) { + var p struct { + Capabilities struct { + Experimental map[string]addonCapability `json:"experimental"` + } `json:"capabilities"` + } + json.Unmarshal(raw, &p) // optional: without a network the caption names both + s.mu.Lock() + s.network = p.Capabilities.Experimental[vendor+"addon"].Network + s.mu.Unlock() r := initializeResult{ProtocolVersion: protocolVersion, ServerInfo: serverInfo{Name: "geoguess", Title: "GeoGuess", Version: "1"}} r.Capabilities.Experimental = map[string]addonCapability{vendor + "addon": {Version: 1}} r.Capabilities.Resources.Subscribe = true diff --git a/cmd/geoguess/server.go b/cmd/geoguess/server.go index 456a0ac..99ad2c9 100644 --- a/cmd/geoguess/server.go +++ b/cmd/geoguess/server.go @@ -42,6 +42,7 @@ type server struct { wants map[string]bool // regions a /geo asked for that the buffer lacks changed chan struct{} // closed when the buffer gains a photo seeds map[string]*geo.Seeds + network string // the chat network the bot said it is on, "" if it didn't saveMu sync.Mutex // one save at a time, so the last one written is the newest } diff --git a/internal/bot/bot.go b/internal/bot/bot.go index e5858db..77910d2 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -49,6 +49,9 @@ type Network interface { // in chat on its own: a group it is still in and answers in, or the DM // of a user still allowed to DM it. Reachable(ctx context.Context, chat feature.Chat) bool + // Name is the network's own short lowercase name, such as the one its + // package is named for; it never blocks. + Name() string // BotName never blocks. BotName() string // Prompt is the network's own line in the system prompt, such as its diff --git a/internal/bot/fakes_test.go b/internal/bot/fakes_test.go index a306748..a01cbe1 100644 --- a/internal/bot/fakes_test.go +++ b/internal/bot/fakes_test.go @@ -126,6 +126,7 @@ func (n *fakeNet) Reachable(_ context.Context, chat feature.Chat) bool { return chat.User == aliceID || chat.User == bobID } +func (n *fakeNet) Name() string { return "fake" } func (n *fakeNet) BotName() string { return "Botty" } // Prompt is Signal's, so the golden prompt holds with no features. diff --git a/internal/bot/host.go b/internal/bot/host.go index 2dfc0e2..6c9d9f4 100644 --- a/internal/bot/host.go +++ b/internal/bot/host.go @@ -92,7 +92,7 @@ func (b *Bot) Store(name string) (feature.Store, error) { } func (b *Bot) Info() feature.Info { - info := feature.Info{Name: b.net.BotName(), Version: b.cfg.Version, Model: b.cfg.Model, + info := feature.Info{Name: b.net.BotName(), Network: b.net.Name(), Version: b.cfg.Version, Model: b.cfg.Model, Images: b.images.Load(), Audio: b.audio.Load(), PDFs: b.files.Load(), CallsTools: b.callsTools.Load(), Tools: b.toolNames(false), Intro: b.intro(false), IntroDM: b.intro(true)} if b.ai == nil { info.Model = "" diff --git a/internal/feature/feature.go b/internal/feature/feature.go index 4a1ef06..8b3d2a8 100644 --- a/internal/feature/feature.go +++ b/internal/feature/feature.go @@ -180,6 +180,7 @@ type Info struct { PDFs bool // the model's API takes PDFs CallsTools bool // the model can call tools Provider string // the model API's provider, as server tools name it: "openrouter", or "" for another + Network string // the chat network, as it names itself, such as "signal" or "telegram" Tools []string // the Names of every tool group with tools, in feature order; none when it can't call tools Intro string // INTRO with {name}, {model}, {tools} and {more} filled in, as in a group IntroDM string // the same in a DM, with IntroLine's DM-only lines too diff --git a/internal/features/mcp/conn.go b/internal/features/mcp/conn.go index 6f1f113..b233325 100644 --- a/internal/features/mcp/conn.go +++ b/internal/features/mcp/conn.go @@ -55,12 +55,13 @@ type rpcMsg struct { // stdioConn runs a local MCP server and talks to it over stdin and stdout, // one JSON message per line. type stdioConn struct { - name, version string - cfg server - redact func(string) string // scrubs names and IDs from its output before it is logged - prefix string // an addon's: it gets the bot's variables that start with this, and its stderr is only counted - updated chan struct{} // an addon's: marked, without waiting, when it says a resource was updated - ready func(context.Context, handshake) // an addon's: called each time it has started again and initialized + name string + bot botInfo // what initialize tells the server + cfg server + redact func(string) string // scrubs names and IDs from its output before it is logged + prefix string // an addon's: it gets the bot's variables that start with this, and its stderr is only counted + updated chan struct{} // an addon's: marked, without waiting, when it says a resource was updated + ready func(context.Context, handshake) // an addon's: called each time it has started again and initialized nextID atomic.Int64 mu sync.Mutex // guards stdin, pending, done and the stderr counts @@ -276,7 +277,7 @@ func (c *stdioConn) supervise(ctx context.Context) { continue // c.done is still the exited process's, so it retries } ictx, cancel := context.WithTimeout(ctx, callTimeout) - hs, err := initialize(ictx, c, c.version) + hs, err := initialize(ictx, c, c.bot) cancel() if err != nil { logx.Warnf("MCP server %s failed to initialize: %s", c.name, describe(err, c.prefix != "")) @@ -371,9 +372,10 @@ func (c *stdioConn) notify(_ context.Context, method string, params any) error { // httpConn talks to a remote MCP server: each message is a POST, answered // with JSON or a stream of server-sent events. type httpConn struct { - url, version string - headers map[string]string - client *http.Client + url string + bot botInfo // what initialize tells the server + headers map[string]string + client *http.Client nextID atomic.Int64 mu sync.Mutex @@ -390,7 +392,7 @@ func (c *httpConn) call(ctx context.Context, method string, params any) (json.Ra c.mu.Lock() c.session, c.ready = "", false c.mu.Unlock() - if _, err := initialize(ctx, c, c.version); err != nil { + if _, err := initialize(ctx, c, c.bot); err != nil { return nil, err } res, err = c.roundTrip(ctx, method, params) diff --git a/internal/features/mcp/mcp.go b/internal/features/mcp/mcp.go index 9228ca8..2043b16 100644 --- a/internal/features/mcp/mcp.go +++ b/internal/features/mcp/mcp.go @@ -261,13 +261,24 @@ type handshake struct { subscribe bool // it takes resource subscriptions } -// initialize performs the MCP handshake, as the bot's version, offering -// signalbot's extension, and returns what the server said of itself. -func initialize(ctx context.Context, c conn, version string) (handshake, error) { +// botInfo is what the bot tells a server of itself in the handshake. +type botInfo struct { + version string // the bot's version, "dev" if unknown + network string // the chat network, as Info names it, for addons +} + +// initialize performs the MCP handshake, as self, offering signalbot's +// extension with the chat network the bot is on, and returns what the +// server said of itself. +func initialize(ctx context.Context, c conn, self botInfo) (handshake, error) { + offer := map[string]any{"version": addonVersion} + if self.network != "" { + offer["network"] = self.network + } res, err := c.call(ctx, "initialize", map[string]any{ "protocolVersion": protocol, - "capabilities": map[string]any{"experimental": map[string]any{vendor + "addon": map[string]int{"version": addonVersion}}}, - "clientInfo": map[string]string{"name": "signalbot", "version": version}, + "capabilities": map[string]any{"experimental": map[string]any{vendor + "addon": offer}}, + "clientInfo": map[string]string{"name": "signalbot", "version": self.version}, }) if err != nil { return handshake{}, err @@ -341,21 +352,21 @@ func modelName(server, tool string) string { // run addons as plain servers; each addon started joins it. func start(ctx context.Context, h feature.Host, path string, servers map[string]server, k *keeper) error { info := h.Info() - version := cmp.Or(info.Version, "dev") + self := botInfo{version: cmp.Or(info.Version, "dev"), network: info.Network} type owner struct{ server, tool string } taken := map[string]owner{} // the model's names for tools, and whose they are var cmds []string // for the startup line for _, name := range slices.Sorted(maps.Keys(servers)) { cfg := servers[name] - var c conn = &httpConn{url: cfg.URL, headers: cfg.Headers, client: httpx.Client(2), version: version} + var c conn = &httpConn{url: cfg.URL, headers: cfg.Headers, client: httpx.Client(2), bot: self} if cfg.Command != "" { - s := &stdioConn{name: name, cfg: cfg, version: version, redact: h.Redact} + s := &stdioConn{name: name, cfg: cfg, bot: self, redact: h.Redact} if cfg.Addon != nil { s.prefix, s.updated = envPrefix(name), make(chan struct{}, 1) } c = s } - listed, hs, err := connect(ctx, c, version) + listed, hs, err := connect(ctx, c, self) if err != nil { logx.Errorf("MCP server %s unavailable, its tools are left out: %s", name, describe(err, cfg.Addon != nil)) continue @@ -550,7 +561,7 @@ func command(h feature.Host, server, n string, c chatCommand, models map[string] // connect starts the server, initializes it, and lists its tools by name, // all of them, whoever they are for. -func connect(ctx context.Context, c conn, version string) ([]tool, handshake, error) { +func connect(ctx context.Context, c conn, self botInfo) ([]tool, handshake, error) { ctx2, cancel := context.WithTimeout(ctx, callTimeout) defer cancel() if s, ok := c.(*stdioConn); ok { @@ -558,7 +569,7 @@ func connect(ctx context.Context, c conn, version string) ([]tool, handshake, er return nil, handshake{}, err } } - hs, err := initialize(ctx2, c, version) + hs, err := initialize(ctx2, c, self) if err != nil { return nil, handshake{}, err } diff --git a/internal/features/mcp/mcp_test.go b/internal/features/mcp/mcp_test.go index a7b0bad..881d908 100644 --- a/internal/features/mcp/mcp_test.go +++ b/internal/features/mcp/mcp_test.go @@ -89,6 +89,7 @@ type fakeMCP struct { mu sync.Mutex session string // the live session id version string // the bot's, as initialize sent it + network string // the chat network, as initialize offered it inits int badCalls int // requests that carried the wrong session id } @@ -103,9 +104,15 @@ func (f *fakeMCP) ServeHTTP(w http.ResponseWriter, r *http.Request) { f.mu.Lock() defer f.mu.Unlock() if req.Method == "initialize" { - var p struct{ ClientInfo struct{ Version string } } + var p struct { + ClientInfo struct{ Version string } + Capabilities struct { + Experimental map[string]struct{ Network string } + } + } json.Unmarshal(req.Params, &p) f.inits, f.version = f.inits+1, p.ClientInfo.Version + f.network = p.Capabilities.Experimental[vendor+"addon"].Network f.session = fmt.Sprintf("s%d", f.inits) w.Header().Set("Mcp-Session-Id", f.session) } else if r.Header.Get("Mcp-Session-Id") != f.session { @@ -398,12 +405,12 @@ func TestToolGroups(t *testing.T) { "scout":{"url":"`+serve(t, scoutMCP)+`","allowed_tools":["fail"], "chat_commands":{"scout":{"tool":"fail"}}}, "plain_Mcp":{"url":"`+serve(t, &fakeMCP{})+`","allowed_tools":["echo"],"keywords":[]}}}`, - func(h *featuretest.Host) { h.Bot.Version = "v1.2.3" }) + func(h *featuretest.Host) { h.Bot.Version, h.Bot.Network = "v1.2.3", "signal" }) if err != nil { t.Fatal(err) } - if scoutMCP.version != "v1.2.3" { - t.Errorf("clientInfo version %q", scoutMCP.version) + if scoutMCP.version != "v1.2.3" || scoutMCP.network != "signal" { + t.Errorf("clientInfo version %q, network %q", scoutMCP.version, scoutMCP.network) } gs := h.ToolGroups() if len(gs) != 3 { diff --git a/internal/signal/names.go b/internal/signal/names.go index e9e88fb..7c7fbb7 100644 --- a/internal/signal/names.go +++ b/internal/signal/names.go @@ -216,6 +216,9 @@ func (c *Client) number(aci string) string { return c.names.numbers[aci] } +// Name is the network's name. +func (c *Client) Name() string { return "signal" } + // BotName is the bot's own profile name, or "signalbot", which loadNames loads. func (c *Client) BotName() string { return cmp.Or(c.name(c.self()), defaultName) } diff --git a/internal/telegram/client.go b/internal/telegram/client.go index 0a3f452..733640b 100644 --- a/internal/telegram/client.go +++ b/internal/telegram/client.go @@ -183,6 +183,9 @@ func (c *Client) WaitID(ctx context.Context) string { return c.selfID() } +// Name is the network's name. +func (c *Client) Name() string { return "telegram" } + // BotName is the bot's first name, or "telegrambot" until known. func (c *Client) BotName() string { if n, _ := c.name.Load().(string); n != "" { From b34fee88e8b435c0796827011518e52b7c5f114a Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Fri, 20 Nov 2026 05:51:21 +0000 Subject: [PATCH 07/26] GeoGuess: Signal's location picker needs a confirm before send Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- cmd/geoguess/README.md | 4 ++-- cmd/geoguess/game.go | 8 ++++---- cmd/geoguess/main_test.go | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/cmd/geoguess/README.md b/cmd/geoguess/README.md index f106759..2709be9 100644 --- a/cmd/geoguess/README.md +++ b/cmd/geoguess/README.md @@ -2,8 +2,8 @@ A GeoGuessr-style game for signalbot. `/geo` posts a street-level photo; players answer by sending a location (on Signal, the **+** button → -Location; on Telegram, 📎 → Location; then pinch to zoom out and drag the -pin), or typed +Location; on Telegram, 📎 → Location; then pinch to zoom out, drag the +pin, confirm on Signal, and send), or typed coordinates such as `-37.81, 144.96`; when time is up the bot names the place and ranks players by how far off they were. diff --git a/cmd/geoguess/game.go b/cmd/geoguess/game.go index 6d3c840..255361f 100644 --- a/cmd/geoguess/game.go +++ b/cmd/geoguess/game.go @@ -160,15 +160,15 @@ func (s *server) start(ctx context.Context, c *callContext, length time.Duration // caption is the photo's caption: how to guess, on the chat network the // bot said it is on, and by when. func caption(deadline time.Time, length time.Duration, network string) string { - share := "Signal: **+** → Location; Telegram: 📎 → Location. Pinch to zoom out" + steps := "Signal: **+** → Location; Telegram: 📎 → Location. Pinch to zoom out, **drag the pin**, confirm (on Signal), then send." switch network { case "signal": - share = "Tap **+** → Location, pinch to zoom out" + steps = "Tap **+** → Location, pinch to zoom out, **drag the pin**, confirm, then send." case "telegram": - share = "Tap 📎 → Location, pinch to zoom out" + steps = "Tap 📎 → Location, pinch to zoom out, **drag the pin**, then send." } return "🌍 **Where is this?** Send a location before " + deadline.Local().Format("15:04") + " (" + lengthLabel(length) + ").\n" + - share + ", **drag the pin**, then send. Or type coordinates, e.g. `-37.81, 144.96`.\n" + + steps + " Or type coordinates, e.g. `-37.81, 144.96`.\n" + "⚠️ Location starts at *your* position. Move the pin before you send." } diff --git a/cmd/geoguess/main_test.go b/cmd/geoguess/main_test.go index dd6617d..b257a3b 100644 --- a/cmd/geoguess/main_test.go +++ b/cmd/geoguess/main_test.go @@ -385,9 +385,9 @@ const ( func TestCaption(t *testing.T) { at := time.Date(2026, 11, 20, 14, 3, 0, 0, time.Local) for _, tc := range []struct{ network, want, not string }{ - {"signal", "Tap **+** → Location, pinch to zoom out, **drag the pin**", "📎"}, - {"telegram", "Tap 📎 → Location, pinch to zoom out, **drag the pin**", "**+**"}, - {"", "Signal: **+** → Location; Telegram: 📎 → Location. Pinch to zoom out, **drag the pin**", "Tap"}, + {"signal", "Tap **+** → Location, pinch to zoom out, **drag the pin**, confirm, then send.", "📎"}, + {"telegram", "Tap 📎 → Location, pinch to zoom out, **drag the pin**, then send.", "confirm"}, + {"", "Signal: **+** → Location; Telegram: 📎 → Location. Pinch to zoom out, **drag the pin**, confirm (on Signal), then send.", "Tap"}, } { got := caption(at, 3*time.Minute, tc.network) if !strings.Contains(got, tc.want) || strings.Contains(got, tc.not) || !strings.Contains(got, "14:03 (3 min)") || From ada1cd61c6971292ec19f36313070ecee1352679 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Fri, 20 Nov 2026 12:32:34 +0000 Subject: [PATCH 08/26] GeoGuess: 40 more Australian seed areas Regional cities, coasts, wine regions and the outback across every state and territory, so /geo AU (or GEO_REGIONS=AU) isn't mostly capital-city suburbs: 9 Australian areas become 49. The per-country cap keeps Australia's share of world rounds as it was. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- cmd/geoguess/geo/seeds.json | 40 +++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/cmd/geoguess/geo/seeds.json b/cmd/geoguess/geo/seeds.json index a3e025b..3d3f0e8 100644 --- a/cmd/geoguess/geo/seeds.json +++ b/cmd/geoguess/geo/seeds.json @@ -18,6 +18,46 @@ {"cc": "AU", "lat": -37.56, "lon": 143.85, "radius_km": 20, "weight": 1, "name": "Ballarat"}, {"cc": "AU", "lat": -19.26, "lon": 146.82, "radius_km": 20, "weight": 1, "name": "Townsville"}, {"cc": "AU", "lat": -35.28, "lon": 149.13, "radius_km": 20, "weight": 1, "name": "Canberra"}, + {"cc": "AU", "lat": -38.15, "lon": 144.36, "radius_km": 20, "weight": 2, "name": "Geelong"}, + {"cc": "AU", "lat": -36.76, "lon": 144.28, "radius_km": 15, "weight": 1, "name": "Bendigo"}, + {"cc": "AU", "lat": -38.37, "lon": 145.03, "radius_km": 20, "weight": 1, "name": "Mornington Peninsula"}, + {"cc": "AU", "lat": -38.76, "lon": 143.67, "radius_km": 25, "weight": 1, "name": "Great Ocean Road"}, + {"cc": "AU", "lat": -37.65, "lon": 145.52, "radius_km": 20, "weight": 1, "name": "Yarra Valley"}, + {"cc": "AU", "lat": -36.36, "lon": 146.31, "radius_km": 15, "weight": 1, "name": "Wangaratta"}, + {"cc": "AU", "lat": -34.21, "lon": 142.14, "radius_km": 15, "weight": 1, "name": "Mildura"}, + {"cc": "AU", "lat": -38.38, "lon": 142.48, "radius_km": 15, "weight": 1, "name": "Warrnambool"}, + {"cc": "AU", "lat": -38.11, "lon": 147.07, "radius_km": 20, "weight": 1, "name": "Sale"}, + {"cc": "AU", "lat": -32.93, "lon": 151.78, "radius_km": 25, "weight": 2, "name": "Newcastle"}, + {"cc": "AU", "lat": -34.42, "lon": 150.89, "radius_km": 20, "weight": 2, "name": "Wollongong"}, + {"cc": "AU", "lat": -33.71, "lon": 150.31, "radius_km": 20, "weight": 1, "name": "Blue Mountains"}, + {"cc": "AU", "lat": -28.64, "lon": 153.61, "radius_km": 20, "weight": 1, "name": "Byron Bay"}, + {"cc": "AU", "lat": -32.83, "lon": 151.36, "radius_km": 20, "weight": 1, "name": "Hunter Valley"}, + {"cc": "AU", "lat": -35.12, "lon": 147.37, "radius_km": 15, "weight": 1, "name": "Wagga Wagga"}, + {"cc": "AU", "lat": -32.25, "lon": 148.6, "radius_km": 15, "weight": 1, "name": "Dubbo"}, + {"cc": "AU", "lat": -31.95, "lon": 141.47, "radius_km": 15, "weight": 1, "name": "Broken Hill"}, + {"cc": "AU", "lat": -30.3, "lon": 153.11, "radius_km": 20, "weight": 1, "name": "Coffs Harbour"}, + {"cc": "AU", "lat": -36.08, "lon": 146.92, "radius_km": 15, "weight": 1, "name": "Albury"}, + {"cc": "AU", "lat": -31.43, "lon": 152.91, "radius_km": 15, "weight": 1, "name": "Port Macquarie"}, + {"cc": "AU", "lat": -28.02, "lon": 153.4, "radius_km": 25, "weight": 2, "name": "Gold Coast"}, + {"cc": "AU", "lat": -26.65, "lon": 153.07, "radius_km": 25, "weight": 2, "name": "Sunshine Coast"}, + {"cc": "AU", "lat": -16.92, "lon": 145.77, "radius_km": 20, "weight": 1, "name": "Cairns"}, + {"cc": "AU", "lat": -27.56, "lon": 151.95, "radius_km": 15, "weight": 1, "name": "Toowoomba"}, + {"cc": "AU", "lat": -23.38, "lon": 150.51, "radius_km": 15, "weight": 1, "name": "Rockhampton"}, + {"cc": "AU", "lat": -21.14, "lon": 149.19, "radius_km": 15, "weight": 1, "name": "Mackay"}, + {"cc": "AU", "lat": -20.73, "lon": 139.49, "radius_km": 10, "weight": 1, "name": "Mount Isa"}, + {"cc": "AU", "lat": -34.52, "lon": 138.96, "radius_km": 20, "weight": 1, "name": "Barossa Valley"}, + {"cc": "AU", "lat": -37.83, "lon": 140.78, "radius_km": 15, "weight": 1, "name": "Mount Gambier"}, + {"cc": "AU", "lat": -35.55, "lon": 138.62, "radius_km": 15, "weight": 1, "name": "Victor Harbor"}, + {"cc": "AU", "lat": -32.06, "lon": 115.75, "radius_km": 10, "weight": 1, "name": "Fremantle"}, + {"cc": "AU", "lat": -33.95, "lon": 115.07, "radius_km": 25, "weight": 1, "name": "Margaret River"}, + {"cc": "AU", "lat": -33.33, "lon": 115.64, "radius_km": 15, "weight": 1, "name": "Bunbury"}, + {"cc": "AU", "lat": -35.02, "lon": 117.88, "radius_km": 15, "weight": 1, "name": "Albany"}, + {"cc": "AU", "lat": -30.75, "lon": 121.47, "radius_km": 10, "weight": 1, "name": "Kalgoorlie"}, + {"cc": "AU", "lat": -28.77, "lon": 114.61, "radius_km": 15, "weight": 1, "name": "Geraldton"}, + {"cc": "AU", "lat": -17.96, "lon": 122.24, "radius_km": 10, "weight": 1, "name": "Broome"}, + {"cc": "AU", "lat": -12.46, "lon": 130.84, "radius_km": 20, "weight": 2, "name": "Darwin"}, + {"cc": "AU", "lat": -23.7, "lon": 133.88, "radius_km": 10, "weight": 1, "name": "Alice Springs"}, + {"cc": "AU", "lat": -41.44, "lon": 147.14, "radius_km": 15, "weight": 1, "name": "Launceston"}, {"cc": "NZ", "lat": -36.85, "lon": 174.76, "radius_km": 30, "weight": 2, "name": "Auckland"}, {"cc": "NZ", "lat": -41.29, "lon": 174.78, "radius_km": 20, "weight": 1, "name": "Wellington"}, {"cc": "NZ", "lat": -43.53, "lon": 172.64, "radius_km": 25, "weight": 1, "name": "Christchurch"}, From 36a32c8028d7b2634b168a90d7b3cadebbc810d7 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Fri, 20 Nov 2026 14:58:23 +0000 Subject: [PATCH 09/26] GeoGuess keeps a photo ready per GEO_KEEP region and waits longer GeoGuess: - GEO_KEEP (e.g. AU): always keep at least one ready photo for each listed region; trimming never drops it, a plain /geo prefers other photos, and a region whose searches keep failing backs off on its own without starving the normal buffer. - GEO_WAIT (default 50s, 5s to 110s) replaces the fixed 10s wait for a photo, with a clearer "still looking" reply. It never waits past the bot's deadline for the call, and a call the bot abandoned starts no round and puts its photo back. signalbot: - chat_commands.<name>.timeout (1s to 2m, default 15s) for direct commands; the example sets 60s for /geo. - Direct calls carry their deadline in the context _meta, and a call the bot gives up on is cancelled with notifications/cancelled. - The typing indicator shows while an addressed message's hooks run for over a second, so a slow command doesn't look ignored. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- TECHNICAL.md | 6 +- cmd/geoguess/README.md | 17 +- cmd/geoguess/config.go | 22 +++ cmd/geoguess/game.go | 20 +- cmd/geoguess/main_test.go | 280 ++++++++++++++++++++++++++-- cmd/geoguess/prefetch.go | 157 +++++++++++++--- cmd/geoguess/rpc.go | 33 +++- cmd/geoguess/server.go | 36 ++-- docs/FILES_LINKS_TOOLS_MCP.md | 8 +- examples/signalbot-mcp.json | 2 +- internal/bot/bot.go | 33 +++- internal/bot/bot_test.go | 29 +++ internal/bot/fakes_test.go | 14 +- internal/bot/host.go | 2 +- internal/features/mcp/addon.go | 1 + internal/features/mcp/addon_test.go | 30 ++- internal/features/mcp/conn.go | 9 + internal/features/mcp/direct.go | 29 ++- internal/features/mcp/mcp.go | 24 ++- internal/features/mcp/mcp_test.go | 9 +- 20 files changed, 658 insertions(+), 103 deletions(-) diff --git a/TECHNICAL.md b/TECHNICAL.md index 2536928..517a88a 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -21,7 +21,7 @@ What the bot does with no features registered. - **Names** come from signal-cli's contact list (`listContacts` with `allRecipients`, at most 5,000), loaded on connect, on every group `UPDATE` event, and when a mention is unknown or the list is over 24 hours old, at most every 15s, with requests meanwhile folded into one. A group `UPDATE` also clears the names that chat remembers for turning `@Name` into mentions; it is a change, not a message, so no hook sees it, and it never takes a slot, even before the bot's own ID is known. An unresolved mention reaches the model as `[unnamed user]`; a group sender with no known name gets no prefix; an unknown quote author is "someone". The bot calls itself by its profile name, or `signalbot`. A name two people claim is never linked. - **Daily budget.** With `DAILY_BUDGET` above 0 (default 1) and an API that reports costs (OpenRouter's), each chat's spending is added up per day, midnight to midnight local time, from the cost each reply reports, every tool round included; scheduled runs count to their chat. Every request's cost counts, including those of a reply that fails or is retried. The limit is checked before each reply, so one expensive reply (several OCR'd PDFs, say) can take a chat past it; the next is refused. Before asking the model, a chat at or over the limit gets "I've reached today's spending limit for this chat, so I'll answer again in N hours. Commands that don't need me to think still work." (the time to midnight rounded up to whole minutes, and from 60 minutes to whole hours), once a day with one warning that names no one, and until midnight each further message it would ask the model about gets a ⏳ reaction instead (one sent by the bot, a scheduled post, gets nothing), so the bot is seen to be paused rather than broken; an `Answer` (a command that needs no model) is still sent. Today's spending is saved in `budget.json` in `STATE_DIRECTORY` (`kit/fsx.WriteAtomic`, as schedules are) under the SHA-256 of each chat's key, so the file holds no IDs, and only for chats that spent something today; at midnight it is rewritten empty, and a file from an earlier day, or one that can't be read, starts the day at 0. With another API one startup line says the cap isn't applied, a warning if `DAILY_BUDGET` was set. - **Reactions.** A reply that is exactly one emoji, by `txt.SingleEmoji` (a flag, a keycap, or one pictograph with its variation selector, skin tone or tags, or several joined by zero-width joiners; a symbol below U+10000 counts only if Unicode shows it as emoji by default, or with U+FE0F, so ✓ or ★ is text), and nothing else, is sent with `Network.React` as a reaction to the message answered (signal-cli `sendReaction` with its sender and `timestamp`), not as a message; history keeps "[reacted 🙏]". A merged batch reacts to its last message, and a message the bot made, such as a scheduled post, has no timestamp, so its emoji goes out as a message. The prompt's line says that a message needing no answer, such as thanks, gets a single emoji, sent as a reaction, and that a question or request always gets words; what happens is decided by code. A lone emoji, with no tool used, for a message whose own words matched a tool group's `Keywords` is not taken as the answer: that message asked for something, so the model is asked once more with "[This message asks you for something: answer it in words, or with a tool if one fits, not with an emoji alone.]" after it, and its second answer stands, a reaction if it is again an emoji. -- **Answer.** Typing is shown until the reply is ready, then stopped with `sendTyping` and `stop`, so a reaction or a turn that sends nothing doesn't leave "typing…" up until Signal's own timeout. The prompt is built ([below](#the-prompt)) and sent to the model. On failure the "model error" line is logged, the chat gets "Sorry, I couldn't get an answer just now." (or, when the model was still calling tools after its last round with nothing to say, `model.ErrTooManyRounds`, "That took more lookups than I can do for one reply. Try asking for one thing at a time."), and history is unchanged. The network renders the reply's Markdown, then sends it without a leading @ and the bot's own name (an echo of how it was addressed), with @Name, and in a group the bot's own @name elsewhere (as in the intro's `I respond to @{name}`), linked to real mentions, as one message capped at 8,000 characters, the rest cut with " […truncated]" and a warning. A reply is never split: past 2,000 bytes, signal-cli 0.14.10 sends the body cut there with the whole text as a long-text attachment (`applyMessage` in `ManagerImpl`), as Signal's apps do, shown as one message with Read more. +- **Answer.** Typing is shown until the reply is ready, then stopped with `sendTyping` and `stop`, so a reaction or a turn that sends nothing doesn't leave "typing…" up until Signal's own timeout. A message a hook answers (a command) shows no typing, unless its `OnMessage` hooks are still running a second after it arrived, as a slow addon call can be; then typing is shown until they return. The prompt is built ([below](#the-prompt)) and sent to the model. On failure the "model error" line is logged, the chat gets "Sorry, I couldn't get an answer just now." (or, when the model was still calling tools after its last round with nothing to say, `model.ErrTooManyRounds`, "That took more lookups than I can do for one reply. Try asking for one thing at a time."), and history is unchanged. The network renders the reply's Markdown, then sends it without a leading @ and the bot's own name (an echo of how it was addressed), with @Name, and in a group the bot's own @name elsewhere (as in the intro's `I respond to @{name}`), linked to real mentions, as one message capped at 8,000 characters, the rest cut with " […truncated]" and a warning. A reply is never split: past 2,000 bytes, signal-cli 0.14.10 sends the body cut there with the whole text as a long-text attachment (`applyMessage` in `ManagerImpl`), as Signal's apps do, shown as one message with Read more. - **Markdown on Signal.** Signal shows text styles, not Markdown, so `internal/signal/markdown.go` turns a reply into plain text and signal-cli's `textStyle` ranges (`start:length:STYLE`, UTF-16 units of each message sent): `**bold**` and `__bold__` are BOLD, `*italic*` and `_italic_` ITALIC, `~~strike~~` STRIKETHROUGH, `` `code` `` and fenced code blocks (fences and language dropped) MONOSPACE, `||spoiler||` SPOILER; `# Heading` (1–6 `#`) is its text in bold, and `[text](url)` is "text (url)", or the url alone when they are the same. Markers open and close only at word boundaries (`2*3*4`, `snake_case_name` and `a * b` stay as they are), an unmatched one stays literal, nothing in code is converted, and lists, tables and quotes stay as written. Conversion comes first, so stripping and mentions work on the plain text. - **Nothing to answer.** A message with no text (only a photo or sticker) is answered only if an `OnTurn` hook adds something to it. - **The model.** A chat completions API in OpenAI's format at `MODEL_API_URL` (OpenRouter's by default, `internal/model`), with `MODEL_API_KEY` as a bearer token if set, over a keep-alive client that requires TLS 1.3 for `https://`. Requests to OpenRouter (host `openrouter.ai`) set `provider.data_collection: deny` and `usage.include` for the real cost, plus the `MODEL_REASONING` effort as `reasoning.effort`; requests elsewhere carry only `reasoning_effort`. Either effort is left out when `MODEL_REASONING` is `none`. The tokens are logged with each reply, and the cost when the API reports it. A network error, 429 or 5xx gets one retry; an error body is reduced to its message ("status N: message"). The tool loop takes at most 5 requests and 3 minutes per reply, and 4 pictures; if a request after a tool made pictures fails, the pictures are the reply, without words, since they may have cost money to make. `Host.CallAPI(ctx, path, body)` lets a tool post to another endpoint of the same API (`model.Client.Call`): the core adds the key, so a feature never sees it, and on OpenRouter `provider.data_collection: deny` (merged into any provider settings the body has); it waits up to 150s for at most 32 MB, retries as other requests do, refuses `/chat/completions` and any path that isn't a plain endpoint, and adds the `usage.cost` the response reports to the reply whose tool called it, through a tally in the tool loop's ctx, so `DAILY_BUDGET` counts it. Outside a tool's Run there is no reply to count it toward, so it refuses. `Info.Provider` is `openrouter` on OpenRouter's API, else empty. @@ -243,8 +243,8 @@ In `features.go` order, which is the order hooks run in and of the tools line an - **Stderr:** an addon's is never logged, since it may write what it was sent: only "addon <name> wrote N lines (M bytes) to stderr", at most once a minute, and once more when it exits for what was counted since, so a crash's output is never left uncounted. - **The store:** with any addon configured, `mcp` opens its `Store` (`mcp`, `mcp.json`), so MCP without addons needs no state directory. It holds a 32-byte random secret, made once, and each addon's state (below). If the store can't be opened, or the secret read or saved, addons run as plain servers, with an error at startup, rather than with a new secret that would change every pseudonym. A damaged secret is an error too. One saver goroutine writes the document whenever told something changed (a non-blocking send on a 1-buffered channel), and once at shutdown, so a hook never waits on the disk and a burst is one write; a failed save is logged once, the state stays in memory, and the next change tries again. The state of a server no longer configured as an addon is dropped at the first save. - **Pseudonyms:** an addon never sees a phone number, account ID or group ID. Each addon has its own key, HMAC-SHA256 of the secret and its server's name. A chat is `c_` and HMAC(key, `chat\0` + chat key); a sender `u_` and HMAC(key, `user\0` + chat key + `\0` + ID), so the same person is someone else in each chat, or with `global_ids` HMAC(key, `user\0` + ID), the same everywhere; each cut to 128 bits and written in lowercase base32. A ref, `r_` and 128 random bits, names one message, for a reaction, and is kept in memory for 24 hours. - - **Context:** each `tools/call` the bot makes itself carries the message's context in `_meta["io.github.robdevops.signalbot/context"]`: `chat`, `sender`, `ref`, `addressed`, `group`, `sent` and `edited` (when the bot got the message and its edit, in Unix seconds, never the sender's clock; `edited` is 0 for an original), and `name`, the sender's display name, only with `names`. Otherwise the bot keeps, in memory for 24 hours, the last name it saw each pseudonym use in the chat: a `{u_…}` placeholder in an addon's answer or post becomes `@Name`, linked as a mention, or "someone". - - **Direct commands:** a chat command with `direct` makes `/name args` a call the bot makes itself, without the model, to a tool whose visibility has `"bot"` (looked up among all the server's tools; one without it is skipped with a warning), with `{"args": "<text after the command>"}`. It runs in the message's slot, with 15s, and at most 2 at once per server: a third is told "<title> is busy, try again in a moment." at once. The title is the server's `serverInfo.title`, else its name, made safe. In a chat its `chats` or `dms` don't allow, it answers "/name isn't available in this chat.". The result's text parts, joined, become the `Answer` (placeholders filled in, capped at 4,000 characters) and its image parts up to 2 `Pictures`, 2 MB together after `img.Safe` (any left out are counted in a warning); a result with neither is `Done`. An error result, a timeout, a bad result or a server that can't be reached answers "<title> couldn't do that just now.". Each call logs the command, the tool, the outcome (ok, or a code), the time and the result's size. Direct commands are kept with no model or one that can't call tools; a server with no tool for the model lists them with `ListCommands` under its label. + - **Context:** each `tools/call` the bot makes itself carries the message's context in `_meta["io.github.robdevops.signalbot/context"]`: `chat`, `sender`, `ref`, `addressed`, `group`, `sent` and `edited` (when the bot got the message and its edit, in Unix seconds, never the sender's clock; `edited` is 0 for an original), `name`, the sender's display name, only with `names`, and for a direct command `deadline`, when the bot stops waiting (Unix seconds, rounded down). A call the bot stops waiting for gets `notifications/cancelled` with its `requestId`. Otherwise the bot keeps, in memory for 24 hours, the last name it saw each pseudonym use in the chat: a `{u_…}` placeholder in an addon's answer or post becomes `@Name`, linked as a mention, or "someone". + - **Direct commands:** a chat command with `direct` makes `/name args` a call the bot makes itself, without the model, to a tool whose visibility has `"bot"` (looked up among all the server's tools; one without it is skipped with a warning), with `{"args": "<text after the command>"}`. It runs in the message's slot, with 15s or the command's `timeout` (1s to 2m, only on a direct command), and at most 2 at once per server, each held for as long as its call runs: a third is told "<title> is busy, try again in a moment." at once. The title is the server's `serverInfo.title`, else its name, made safe. In a chat its `chats` or `dms` don't allow, it answers "/name isn't available in this chat.". The result's text parts, joined, become the `Answer` (placeholders filled in, capped at 4,000 characters) and its image parts up to 2 `Pictures`, 2 MB together after `img.Safe` (any left out are counted in a warning); a result with neither is `Done`. An error result, a timeout, a bad result or a server that can't be reached answers "<title> couldn't do that just now.". Each call logs the command, the tool, the outcome (ok, or a code), the time and the result's size. Direct commands are kept with no model or one that can't call tools; a server with no tool for the model lists them with `ListCommands` under its label. - **Watches:** a direct command's result may ask, in `_meta["io.github.robdevops.signalbot/watch"]`, for a watch on the chat the command came from (the only way to make one, so an addon can't watch a chat it wasn't used in): an `id` (at most 64 bytes), an RE2 `pattern` (at most 1 KB), `until` (RFC 3339, cut to `watch_max` from now and never extended), the `tool` to call with each match (one the bot may call) and an optional `guard` (at most 500 characters). It needs `watch`, and at most 8 are live in a chat per addon (one with the same ID is replaced). A pattern that matches the empty string or any of about 200 ordinary chat lines in `corpus.go` is refused, so no watch is a feed of the chat; a refusal is logged by reason, never the pattern. One `OnMessage` hook, registered after the chat commands, checks each message with text in an allowed chat against the chat's live watches, on both paths: unaddressed ones on the reader goroutine (only a map lookup and the patterns, under a mutex held briefly), addressed ones (a reply to the bot, a DM, an @mention, a command) in their slot. A watch matches any message the bot gets while it lasts, by when the bot got it, not by its `Timestamp` (on Signal the sender's clock, which may be behind); an edit, unless its original was claimed, only if its original's `Timestamp` is at or after the command's, so an older message's edit isn't taken. An addressed message with no text (a bare mention, or a reply with only a picture) is still checked for the guard. A match is `Done`, so it is never answered, sent to the model or kept in history, and `groupctx` never sees it; it is claimed for 48 hours (chat key, sender's pseudonym, sent time), so a later edit of it goes the same way, to the same tool, whether or not the watch is still live; and it is passed without waiting to the addon's watch worker, whose queue holds 256 (when full, "addon <name>: watch queue full, a matched message dropped", still `Done`). The worker calls the watch's tool with `{"text": …}` and the context, within 120 calls a minute per chat (bursts of 20; a match past it waits its turn in the worker's queue, while other chats' matches go ahead), and keeps a match whose call found the server down (not running, or exited before answering) at the head of the queue until the server has started again (or a minute has passed), dropping it with a warning after 3 such calls, and if the result's `_meta["io.github.robdevops.signalbot/react"]` is one emoji, reacts with it (`React`), which needs `react` and counts against the addon's rate. A watch whose command answered with pictures records, through `OnSent`, the timestamps of the messages they went out in; while it lives, an addressed message quoting one of them gets the `guard` as its `Answer`, so nobody can ask the model about the picture. - **Leases:** an addon may post or react only in a chat where it had a direct command or a watch match in the last 24 hours; the lease maps the chat's pseudonym to the chat. - **Outbox:** if the server advertises `resources.subscribe`, the bot sends `resources/subscribe` for `signalbot://outbox` after each (re)start's `initialize`, then reads it; otherwise the outbox is off, with a warning. Any `notifications/resources/updated` from the server marks the outbox as having news (whatever the URI, which may be under the one subscribed). One reader goroutine per addon reads `resources/read` of `signalbot://outbox/<cursor>` (`0` at first), page by page while `more` is true, up to 100 pages, so two reads never race and news during a read is read after it. A page is one text content holding `{"cursor", "more", "ops"}`; a not-found error (-32002, or the Go SDK's -32602) is logged as no outbox. Ops are applied once each by `id`, the last 1,000 IDs remembered, and are `post` (`chat`, Markdown `text` with placeholders, up to 2 `images` as `{data, mimeType, name}`, 2 MB together), needing `post`; `react` (`ref`, `emoji`), needing `react`; and `unwatch` (`chat`, `watch`), which, for a watch not yet made, stops it being made for 10 minutes. A post or reaction needs a live lease in a chat the addon is still allowed, and counts against `rate` per chat. A post goes through `Post` with the addon's title as its `Label`, so history keeps it as `[Title] …`, the bot's own words. At most one of an addon's posts waits in a chat's mailbox: until its `Done`, later posts for that chat are held, each merged into the one held before it while their pictures together stay within 2 and 2 MB, and sent in turn. Delivery is at least once: a post counts as applied, and the cursor moves past it, only once its `Done` says it was sent. Until then each read starts from the cursor before it and skips it while it waits; one dropped before it was sent (as while the bot stops, or before the network is up at startup, when `Post` gives up on the chat) is posted again by a read 10s later, then 20s, doubling to 5 minutes, not counted against `rate` again, and given up with a warning after 6 tries. A page with `more` waits for its posts before the next is read, since reading past the cursor lets the addon forget them. A read that fails, is malformed, or stops at 100 pages is tried again after 10s, doubling to 5 minutes, without waiting for news. What a read drops is counted in one warning by reason, never content. diff --git a/cmd/geoguess/README.md b/cmd/geoguess/README.md index 2709be9..1a91a2b 100644 --- a/cmd/geoguess/README.md +++ b/cmd/geoguess/README.md @@ -46,7 +46,7 @@ which is what gives it the `GEO_` settings below: ```jsonc "geo": { "command": "/addons/geoguess", - "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m"}}, + "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m", "timeout": "60s"}}, "addon": {"chats": ["<group id>"], "post": true, "react": true, "watch": true, "watch_max": "1h"} } ``` @@ -54,7 +54,13 @@ which is what gives it the `GEO_` settings below: `chats` takes the groups' IDs as Signal or Telegram shows them, or `["all"]`; add `"dms": true` to play in DMs too. GeoGuess needs `post` (for the results), `react` (the 📍 on a counted guess) and `watch` (to read guesses). A round -lasts at most 30 minutes, so the default `watch_max` of 1h is enough. +lasts at most 30 minutes, so the default `watch_max` of 1h is enough. The +`timeout` lets `/geo` wait for a photo when none is ready: keep it above +`GEO_WAIT` (50s by default). GeoGuess never waits past the bot's timeout +anyway, less a few seconds to send the photo, and starts no round the bot has +given up on. A call that waits holds one of the bot's 2 calls at once for +GeoGuess, so while two chats each wait for a photo, `/geo end`, `/geo skip` +and `/geo scores` are told GeoGuess is busy. GeoGuess keeps its own files in `GEO_STATE_DIR`, which you create, writable by the bot's user, and set in `/etc/signalbot.env`: @@ -87,6 +93,8 @@ trusts its CA), and nothing else. | `GEO_MIN_QUALITY` | `0.5` | Minimum Mapillary `quality_score` (0 to 1), when a photo has one | | `GEO_MAX_AGE_YEARS` | `10` | Ignore older photos | | `GEO_BUFFER` | `3` | Checked photos kept ready (1 to 20) | +| `GEO_KEEP` | empty | Regions to always keep a photo ready for, comma-separated, in `GEO_REGIONS`'s names, one photo each: `AU,NZ` keeps one Australian and one New Zealand photo, so `/geo AU` answers at once. Searched before topping up `GEO_BUFFER` (a region whose search fails is tried again after a backoff, and the buffer fills meanwhile), never dropped to make room or used by a `/geo` another photo can serve, and refilled once used | +| `GEO_WAIT` | `50s` | How long `/geo` waits for a photo when none is ready, 5s to 110s, before saying to try again; the search carries on either way. Keep the `geo` chat command's `timeout` above it | | `GEO_NOMINATIM_URL` | `https://nominatim.openstreetmap.org` | Reverse geocoder for the place names; `https://` only, as it is sent each round's answer | | `GEO_PANORAMAX_URL` | `https://api.panoramax.xyz` | Panoramax API (a STAC catalogue), such as one instance's; `https://` only | | `GEO_MAPILLARY_URL` | `https://graph.mapillary.com` | Mapillary Graph API; `https://` only | @@ -140,8 +148,9 @@ coordinate, a place or person's name, a pseudonym or message text. - `tools/list` has `geo` (`{args}`) and `geo_guess` (`{text}`), both with `_meta["io.github.robdevops.signalbot/visibility"] = ["bot"]`, so neither is offered to the model. -- `tools/call` reads the chat, the sender and the receive times from - `_meta["io.github.robdevops.signalbot/context"]`. Starting a round answers +- `tools/call` reads the chat, the sender, the receive times and the + `deadline` from `_meta["io.github.robdevops.signalbot/context"]`. A call + the bot cancels (`notifications/cancelled`) stops. Starting a round answers with the photo, its caption and a `…/watch` for `geo_guess`, until 5s past the deadline; a recorded guess answers with `…/react: "📍"`. - When a round's time is up GeoGuess queues a `post` with the results, its diff --git a/cmd/geoguess/config.go b/cmd/geoguess/config.go index bb73082..2ab4cfb 100644 --- a/cmd/geoguess/config.go +++ b/cmd/geoguess/config.go @@ -24,6 +24,8 @@ type config struct { MinQuality float64 // GEO_MIN_QUALITY: the least Mapillary quality_score MaxAge time.Duration // GEO_MAX_AGE_YEARS, as a duration Buffer int // GEO_BUFFER: checked photos kept ready + Keep []string // GEO_KEEP: regions always kept with a photo ready, one each + Wait time.Duration // GEO_WAIT: how long /geo waits for a photo when none is ready Nominatim string // GEO_NOMINATIM_URL Panoramax string // GEO_PANORAMAX_URL Mapillary string // GEO_MAPILLARY_URL @@ -35,6 +37,9 @@ const ( maxRound = 30 * time.Minute defaultRound = 3 * time.Minute defaultMemLimit = "200MiB" + minWait = 5 * time.Second + maxWait = 110 * time.Second // under the 2m a direct command may take, with time to reply + defaultWait = 50 * time.Second ) // year is a year as GEO_MAX_AGE_YEARS counts it. @@ -87,6 +92,23 @@ func loadConfig(getenv func(string) string) (config, error) { errs = append(errs, fmt.Errorf("GEO_BUFFER is %q: use a whole number from 1 to 20", v)) } } + for _, region := range strings.Split(getenv("GEO_KEEP"), ",") { + region = strings.TrimSpace(region) + if region == "" { + continue + } + if _, err := geo.LoadSeeds(region); err != nil { + errs = append(errs, fmt.Errorf("GEO_KEEP: %v", err)) + continue + } + c.Keep = append(c.Keep, region) + } + c.Wait = defaultWait + if v := strings.TrimSpace(getenv("GEO_WAIT")); v != "" { + if c.Wait, err = time.ParseDuration(v); err != nil || c.Wait < minWait || c.Wait > maxWait { + errs = append(errs, fmt.Errorf("GEO_WAIT is %q: use 5s to 110s, such as 50s", v)) + } + } // Over TLS only: the geocoder is sent each round's answer. for _, u := range []struct{ name, url string }{ {"GEO_NOMINATIM_URL", c.Nominatim}, {"GEO_PANORAMAX_URL", c.Panoramax}, {"GEO_MAPILLARY_URL", c.Mapillary}, diff --git a/cmd/geoguess/game.go b/cmd/geoguess/game.go index 255361f..4681fc9 100644 --- a/cmd/geoguess/game.go +++ b/cmd/geoguess/game.go @@ -18,7 +18,7 @@ const ( guard = "No hints during a round 😉" noChat = "GeoGuess works only in a chat." noRound = "There's no round on. Start one with /geo." - noPhoto = "I'm still looking for a photo. Try again in a minute." + noPhoto = "I couldn't find a good spot in time; I'm still looking, so try /geo again in a minute." badLength = "A round can be 30s to 30m, such as /geo 90s or /geo 5m." usage = "Try /geo, /geo 90s, /geo end, /geo skip, /geo scores, or a region such as /geo europe or /geo AU,NZ." ) @@ -26,6 +26,10 @@ const ( // pin is the reaction to a recorded guess. const pin = "📍" +// replyTime is what /geo leaves before the bot's deadline to start the +// round and send the photo, so it never starts one the bot won't show. +const replyTime = 3 * time.Second + // call runs one tool. Only an unknown tool is a protocol error; the rest // answer in words. func (s *server) call(ctx context.Context, p callParams) (any, error) { @@ -121,15 +125,25 @@ func (s *server) start(ctx context.Context, c *callContext, length time.Duration if r != nil { return busy(r, s.clock.Now()) } - photo, ok := s.take(ctx, region) + wait := s.cfg.Wait + if c.Deadline != 0 { // leave the bot time to send the photo + wait = min(wait, time.Until(time.Unix(c.Deadline, 0))-replyTime) + } + photo, ok := s.take(ctx, region, wait) if !ok { return text(noPhoto) } s.mu.Lock() now := s.clock.Now() - if r := s.rounds[c.Chat]; r != nil { // another /geo began one meanwhile + r = s.rounds[c.Chat] + if r != nil || ctx.Err() != nil { // another /geo began one meanwhile, or the bot gave up s.buffer = append([]geo.Photo{photo}, s.buffer...) + close(s.changed) // for a /geo waiting in another chat + s.changed = make(chan struct{}) s.mu.Unlock() + if r == nil { + return text(noPhoto) + } return busy(r, now) } r = &round{ diff --git a/cmd/geoguess/main_test.go b/cmd/geoguess/main_test.go index b257a3b..c4129c7 100644 --- a/cmd/geoguess/main_test.go +++ b/cmd/geoguess/main_test.go @@ -6,6 +6,7 @@ import ( "context" "encoding/base64" "encoding/json" + "errors" "fmt" "io" "log" @@ -98,17 +99,22 @@ func (b *syncBuffer) String() string { return b.buf.String() } -// fakeFinder finds a photo at once, or never if off. +// fakeFinder finds a photo at once, or never if off: in Ballarat, or in +// Paris for Europe, or with elsewhere for anywhere but AU. It keeps the +// regions it was asked for. type fakeFinder struct { - mu sync.Mutex - n int - off bool + mu sync.Mutex + n int + off bool + elsewhere bool + asked []string } func (f *fakeFinder) Find(ctx context.Context, regions string) (geo.Photo, error) { f.mu.Lock() f.n++ - n, off := f.n, f.off + n, off, elsewhere := f.n, f.off, f.elsewhere + f.asked = append(f.asked, regions) f.mu.Unlock() if off { <-ctx.Done() @@ -122,7 +128,7 @@ func (f *fakeFinder) Find(ctx context.Context, regions string) (geo.Photo, error Place: geo.Place{Name: "Ballarat, Victoria, Australia", Country: "Australia", CountryCode: "AU"}, JPEG: []byte("jpeg " + strconv.Itoa(n)), } - if strings.Contains(strings.ToLower(regions), "europe") { + if strings.Contains(strings.ToLower(regions), "europe") || elsewhere && regions != "AU" { p.At, p.Place = paris, geo.Place{Name: "Paris, Île-de-France, France", Country: "France", CountryCode: "FR"} } return p, nil @@ -155,10 +161,14 @@ type rpcIn struct { } // testServer is a server keeping its state in dir, on clk, with photos from -// the fake finder, and its log in logs. -func testServer(t *testing.T, dir string, clk clock, photos finder, logs io.Writer) *server { +// the fake finder, and its log in logs; extra settings come from env. +func testServer(t *testing.T, dir string, clk clock, photos finder, logs io.Writer, env ...string) *server { t.Helper() - cfg, err := loadConfig(func(k string) string { return map[string]string{"GEO_STATE_DIR": dir, "GEO_BUFFER": "2"}[k] }) + vars := map[string]string{"GEO_STATE_DIR": dir, "GEO_BUFFER": "2", "GEO_WAIT": "5s"} + for i := 0; i+1 < len(env); i += 2 { + vars[env[i]] = env[i+1] + } + cfg, err := loadConfig(func(k string) string { return vars[k] }) if err != nil { t.Fatal(err) } @@ -166,7 +176,6 @@ func testServer(t *testing.T, dir string, clk clock, photos finder, logs io.Writ if err != nil { t.Fatal(err) } - s.photoWait = 2 * time.Second return s } @@ -745,11 +754,15 @@ func TestNoPhotoAndRegions(t *testing.T) { clk := &fakeClock{now: time.Date(2026, 11, 20, 14, 0, 0, 0, time.UTC)} photos := &fakeFinder{off: true} s := testServer(t, t.TempDir(), clk, photos, io.Discard) - s.photoWait = 50 * time.Millisecond + s.cfg.Wait = 50 * time.Millisecond c := connect(t, s) + began := time.Now() if got := words(c.geo("", from(clk, chat, alice))); got != noPhoto { t.Errorf("no photo: %q", got) } + if waited := time.Since(began); waited < s.cfg.Wait { + t.Errorf("gave up after %s, before GEO_WAIT", waited) + } clk, c, _ = start(t) r := c.geo("Europe 2m", from(clk, chat, alice)) @@ -775,23 +788,30 @@ func TestNoPhotoAndRegions(t *testing.T) { func TestConfig(t *testing.T) { env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } } c, err := loadConfig(env(map[string]string{"GEO_STATE_DIR": "/x"})) - if err != nil || c.Round != 3*time.Minute || c.MemLimit != 200<<20 || c.Buffer != 3 || c.MinQuality != 0.5 || + if err != nil || c.Round != 3*time.Minute || c.MemLimit != 200<<20 || c.Buffer != 3 || c.MinQuality != 0.5 || c.Keep != nil || c.Wait != 50*time.Second || c.Nominatim != geo.NominatimURL || c.Panoramax != geo.PanoramaxURL || c.Mapillary != geo.MapillaryURL || c.MaxAge < 10*365*24*time.Hour { t.Errorf("defaults %+v, %v", c, err) } - c, err = loadConfig(env(map[string]string{"GEO_STATE_DIR": "/x", "GEO_ROUND": "90s", "GEO_MEMLIMIT": "1GiB", "GEO_REGIONS": "europe", "GEO_BUFFER": "5"})) - if err != nil || c.Round != 90*time.Second || c.MemLimit != 1<<30 || c.Regions != "europe" || c.Buffer != 5 { + c, err = loadConfig(env(map[string]string{"GEO_STATE_DIR": "/x", "GEO_ROUND": "90s", "GEO_MEMLIMIT": "1GiB", "GEO_REGIONS": "europe", "GEO_BUFFER": "5", + "GEO_KEEP": " AU, europe,", "GEO_WAIT": "110s"})) + if err != nil || c.Round != 90*time.Second || c.MemLimit != 1<<30 || c.Regions != "europe" || c.Buffer != 5 || + !slices.Equal(c.Keep, []string{"AU", "europe"}) || c.Wait != 110*time.Second { t.Errorf("set %+v, %v", c, err) } - _, err = loadConfig(env(map[string]string{"GEO_ROUND": "1h", "GEO_MEMLIMIT": "lots", "GEO_REGIONS": "atlantis", "GEO_BUFFER": "0", + _, err = loadConfig(env(map[string]string{"GEO_ROUND": "1h", "GEO_MEMLIMIT": "lots", "GEO_REGIONS": "atlantis", "GEO_BUFFER": "0", "GEO_KEEP": "AU,atlantis", "GEO_WAIT": "4s", "GEO_MIN_QUALITY": "2", "GEO_MAX_AGE_YEARS": "-1", "GEO_NOMINATIM_URL": "http://x", "GEO_PANORAMAX_URL": "ftp://x", "GEO_MAPILLARY_URL": "graph.example"})) - for _, name := range []string{"GEO_STATE_DIR", "GEO_ROUND", "GEO_MEMLIMIT", "GEO_REGIONS", "GEO_BUFFER", "GEO_MIN_QUALITY", "GEO_MAX_AGE_YEARS", + for _, name := range []string{"GEO_STATE_DIR", "GEO_ROUND", "GEO_MEMLIMIT", "GEO_REGIONS", "GEO_BUFFER", "GEO_KEEP", "GEO_WAIT", "GEO_MIN_QUALITY", "GEO_MAX_AGE_YEARS", "GEO_NOMINATIM_URL", "GEO_PANORAMAX_URL", "GEO_MAPILLARY_URL"} { if err == nil || !strings.Contains(err.Error(), name) { t.Errorf("no error for %s: %v", name, err) } } + for _, v := range []string{"2m", "soon", "0"} { + if _, err := loadConfig(env(map[string]string{"GEO_STATE_DIR": "/x", "GEO_WAIT": v})); err == nil || !strings.Contains(err.Error(), "GEO_WAIT") { + t.Errorf("GEO_WAIT %s: %v", v, err) + } + } for s, want := range map[string]int64{"200MiB": 200 << 20, "1GiB": 1 << 30, "67108864": 64 << 20, "65536KiB": 64 << 20, "0.5GiB": 512 << 20} { if got, err := parseSize(s); got != want || err != nil { t.Errorf("parseSize(%q) = %d, %v", s, got, err) @@ -810,6 +830,234 @@ func TestConfig(t *testing.T) { } } +// waitFor fails the test unless ok holds within a few seconds, checked +// with s.mu held. +func waitFor(t *testing.T, s *server, what string, ok func() bool) { + t.Helper() + for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(5 * time.Millisecond) { + s.mu.Lock() + done := ok() + s.mu.Unlock() + if done { + return + } + if time.Now().After(deadline) { + t.Fatalf("waited for %s", what) + } + } +} + +// count is how many photos in the buffer are in region. s.mu is held. +func (s *server) count(region string) int { + n := 0 + for _, p := range s.buffer { + if s.in(p, region) { + n++ + } + } + return n +} + +// With GEO_KEEP=AU the prefetcher keeps an Australian photo ready with no +// /geo asking, a /geo AU takes it at once, and it is replaced. +func TestKeep(t *testing.T) { + clk := &fakeClock{now: time.Date(2026, 11, 20, 14, 0, 0, 0, time.UTC)} + photos := &fakeFinder{elsewhere: true} + s := testServer(t, t.TempDir(), clk, photos, io.Discard, "GEO_KEEP", "AU") + for range s.cfg.Buffer { + p, _ := photos.Find(context.Background(), "") + s.add(p, "") + } + c := connect(t, s) + var ready string + waitFor(t, s, "an AU photo", func() bool { + if i := s.match("AU"); i >= 0 { + ready = s.buffer[i].Link + } + return ready != "" + }) + photos.mu.Lock() + if asked := photos.asked[s.cfg.Buffer:]; !slices.Equal(asked, []string{"AU"}) { + t.Errorf("searched %q", asked) + } + photos.mu.Unlock() + + if got := words(c.geo("end", from(clk, chat, alice))); got != noRound { + t.Errorf("end with no round: %q", got) + } + r := c.geo("AU 2m", from(clk, chat, alice)) + if r.Meta == nil { + t.Fatalf("/geo AU: %q", words(r)) + } + s.mu.Lock() + if got := s.rounds[chat].Credit.Link; got != ready { + t.Errorf("/geo AU used %s, not the photo kept ready", got) + } + s.mu.Unlock() + if got := words(c.geo("end", from(clk, chat, alice))); !strings.Contains(got, "Ballarat") { + t.Errorf("a round in AU: %q", got) + } + waitFor(t, s, "a new AU photo", func() bool { return s.count("AU") == 1 }) + photos.mu.Lock() + if asked := photos.asked[s.cfg.Buffer:]; !slices.Equal(asked, []string{"AU", "AU"}) { + t.Errorf("searched %q", asked) + } + photos.mu.Unlock() +} + +// Trimming the buffer never drops a GEO_KEEP region's last photo. +func TestKeepTrim(t *testing.T) { + clk := &fakeClock{now: time.Date(2026, 11, 20, 14, 0, 0, 0, time.UTC)} + photos := &fakeFinder{elsewhere: true} + s := testServer(t, t.TempDir(), clk, photos, io.Discard, "GEO_KEEP", "AU") + find := func(region string) geo.Photo { + p, err := photos.Find(context.Background(), region) + if err != nil { + t.Fatal(err) + } + return p + } + s.add(find("AU"), "AU") + limit := s.cfg.Buffer + extraPhotos + for range limit + 3 { + s.add(find(""), "") + } + s.mu.Lock() + n, au, first := len(s.buffer), s.count("AU"), s.buffer[0].ID + s.mu.Unlock() + if n != limit || au != 1 || first != "1" { + t.Errorf("%d photos, %d in AU, the oldest %s", n, au, first) + } + + // A second AU photo makes the first one droppable again. + s.add(find("AU"), "AU") + s.mu.Lock() + n, au = len(s.buffer), s.count("AU") + s.mu.Unlock() + if n != limit || au != 1 { + t.Errorf("%d photos, %d in AU", n, au) + } +} + +// failIn is the fake finder, failing every search in one region. +type failIn struct { + *fakeFinder + region string +} + +func (f failIn) Find(ctx context.Context, regions string) (geo.Photo, error) { + if regions == f.region { + f.mu.Lock() + f.asked = append(f.asked, regions) + f.mu.Unlock() + return geo.Photo{}, errors.New("nothing good there") + } + return f.fakeFinder.Find(ctx, regions) +} + +// A GEO_KEEP region whose searches fail waits its own backoff, and the +// buffer still fills meanwhile. +func TestKeepFailing(t *testing.T) { + clk := &fakeClock{now: time.Date(2026, 11, 20, 14, 0, 0, 0, time.UTC)} + photos := failIn{&fakeFinder{elsewhere: true}, "AU"} + s := testServer(t, t.TempDir(), clk, photos, io.Discard, "GEO_KEEP", "AU") + connect(t, s) + waitFor(t, s, "a full buffer", func() bool { return len(s.buffer) == s.cfg.Buffer }) + s.mu.Lock() + r, au := s.retries["AU"], s.count("AU") + s.mu.Unlock() + if r.failures != 1 || au != 0 { + t.Errorf("retry %+v, %d in AU", r, au) + } + photos.mu.Lock() + if asked := photos.asked; !slices.Equal(asked, []string{"AU", "", ""}) { + t.Errorf("searched %q", asked) + } + photos.mu.Unlock() +} + +// A plain /geo takes a photo GEO_KEEP can spare, leaving the kept one. +func TestKeepPlainTake(t *testing.T) { + clk := &fakeClock{now: time.Date(2026, 11, 20, 14, 0, 0, 0, time.UTC)} + photos := &fakeFinder{elsewhere: true} + s := testServer(t, t.TempDir(), clk, photos, io.Discard, "GEO_KEEP", "AU") + for _, region := range []string{"AU", ""} { + p, _ := photos.Find(context.Background(), region) + s.add(p, region) + } + c := connect(t, s) + if r := c.geo("", from(clk, chat, alice)); r.Meta == nil { + t.Fatalf("/geo: %q", words(r)) + } + s.mu.Lock() + place, au := s.rounds[chat].Place, s.count("AU") + s.mu.Unlock() + if !strings.Contains(place, "Paris") || au != 1 { + t.Errorf("/geo used a photo in %s, leaving %d in AU", place, au) + } +} + +// A /geo the bot gives up on starts no round: one cancelled while it waits +// leaves the photo found later ready, and one whose call is over when its +// photo is taken puts it back. Near the bot's deadline it doesn't wait. +func TestGeoAbandoned(t *testing.T) { + clk := &fakeClock{now: time.Date(2026, 11, 20, 14, 0, 0, 0, time.UTC)} + photos := &fakeFinder{off: true} + s := testServer(t, t.TempDir(), clk, photos, io.Discard) + c := connect(t, s) + got := make(chan response, 1) + c.mu.Lock() + c.waiting["99"] = got + c.mu.Unlock() + data, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 99, "method": "tools/call", "params": map[string]any{ + "name": "geo", "arguments": map[string]string{"args": ""}, "_meta": map[string]any{vendor + "context": from(clk, chat, alice)}, + }}) + c.send(string(data)) + time.Sleep(100 * time.Millisecond) // for it to wait + began := time.Now() + c.send(`{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":99}}`) + select { + case r := <-got: + var res toolResult + json.Unmarshal(r.Result.(json.RawMessage), &res) + if words(res) != noPhoto || time.Since(began) > time.Second { + t.Errorf("cancelled: %q after %s", words(res), time.Since(began)) + } + case <-time.After(3 * time.Second): + t.Fatal("the cancelled /geo went on waiting") + } + p := geo.Photo{Candidate: geo.Candidate{ID: "1", Source: "Mapillary", At: ballarat}, + Place: geo.Place{Name: "Ballarat, Victoria, Australia", Country: "Australia", CountryCode: "AU"}} + s.add(p, "") + time.Sleep(50 * time.Millisecond) + s.mu.Lock() + n, round := len(s.buffer), s.rounds[chat] + s.mu.Unlock() + if n != 1 || round != nil { + t.Errorf("%d photos ready, round %+v", n, round) + } + + ctx, cancel := context.WithCancel(context.Background()) + cancel() + cc := from(clk, chat, alice) + if got := words(s.start(ctx, &cc, s.cfg.Round, "")); got != noPhoto { + t.Errorf("start, the call over: %q", got) + } + s.mu.Lock() + n, round = len(s.buffer), s.rounds[chat] + s.mu.Unlock() + if n != 1 || round != nil { + t.Errorf("after the call was over: %d photos ready, round %+v", n, round) + } + + cc = from(clk, "c_two", bob) + cc.Deadline = time.Now().Add(replyTime).Unix() + began = time.Now() + if got := words(c.geo("Europe", cc)); got != noPhoto || time.Since(began) > time.Second { + t.Errorf("near the deadline: %q after %s", got, time.Since(began)) + } +} + func TestLabels(t *testing.T) { for d, want := range map[time.Duration]string{3 * time.Minute: "3 min", 90 * time.Second: "90 sec", 30 * time.Minute: "30 min"} { if got := lengthLabel(d); got != want { diff --git a/cmd/geoguess/prefetch.go b/cmd/geoguess/prefetch.go index fcaacb2..1b2bedd 100644 --- a/cmd/geoguess/prefetch.go +++ b/cmd/geoguess/prefetch.go @@ -26,20 +26,26 @@ const ( extraPhotos = 4 ) +// retry is when a GEO_KEEP region whose search failed is searched again, +// and how many times in a row it has failed. +type retry struct { + at time.Time + failures int +} + // prefetch keeps GEO_BUFFER checked photos ready, so /geo answers at once, // and looks for one in each region a /geo asked for. It is the only caller -// of Find. +// of Find. A GEO_KEEP region whose search fails waits its own backoff, +// while the rest go on, so one hard region can't starve the buffer. func (s *server) prefetch(ctx context.Context) { failures := 0 for { - region, ok := s.nextSearch() + region, ok, next := s.nextSearch(time.Now()) if !ok { - select { - case <-s.wake: - continue - case <-ctx.Done(): + if !s.idle(ctx, next) { return } + continue } fctx, cancel := context.WithTimeout(ctx, findTimeout) p, err := s.photos.Find(fctx, region) @@ -54,12 +60,20 @@ func (s *server) prefetch(ctx context.Context) { } s.mu.Lock() delete(s.wants, region) // asked again by the next /geo for it + keep := slices.Contains(s.cfg.Keep, region) + var wait time.Duration + if keep { + r := s.retries[region] + wait = backoff(r.failures, err) + s.retries[region] = retry{time.Now().Add(wait), min(r.failures+1, 10)} + } s.mu.Unlock() - wait := min(5*time.Second<<failures, 5*time.Minute) - failures = min(failures+1, 10) - if errors.Is(err, geo.ErrSlowDown) { - wait = time.Minute + if keep && !errors.Is(err, geo.ErrSlowDown) { + s.log.Printf("no photo found for a kept region (%v); trying it again in %s", err, wait) + continue } + wait = backoff(failures, err) + failures = min(failures+1, 10) s.log.Printf("no photo found (%v); trying again in %s", err, wait) t := time.NewTimer(wait) select { @@ -71,9 +85,39 @@ func (s *server) prefetch(ctx context.Context) { } } +// backoff is how long to wait after failures failed searches in a row and +// then err: from 5s, doubling to 5 minutes, or a minute when asked to slow +// down. +func backoff(failures int, err error) time.Duration { + if errors.Is(err, geo.ErrSlowDown) { + return time.Minute + } + return min(5*time.Second<<failures, 5*time.Minute) +} + +// idle waits for work: a wake, or next, when a GEO_KEEP region may be +// searched again (zero for none). It is false once ctx is done. +func (s *server) idle(ctx context.Context, next time.Time) bool { + var due <-chan time.Time + if !next.IsZero() { + t := time.NewTimer(time.Until(next)) + defer t.Stop() + due = t.C + } + select { + case <-s.wake: + case <-due: + case <-ctx.Done(): + return false + } + return true +} + // nextSearch is the region to look in next: the first a /geo asked for -// that the buffer lacks, else GEO_REGIONS while the buffer isn't full. -func (s *server) nextSearch() (string, bool) { +// that the buffer lacks, else the first GEO_KEEP region it lacks whose +// retry is due at now, else GEO_REGIONS while the buffer isn't full. With +// none, next is the earliest retry still to come, or zero. +func (s *server) nextSearch(now time.Time) (region string, ok bool, next time.Time) { s.mu.Lock() defer s.mu.Unlock() for _, region := range slices.Sorted(maps.Keys(s.wants)) { @@ -81,21 +125,40 @@ func (s *server) nextSearch() (string, bool) { delete(s.wants, region) continue } - return region, true + return region, true, time.Time{} + } + for _, region := range s.cfg.Keep { + if s.match(region) >= 0 { + delete(s.retries, region) + continue + } + r, failed := s.retries[region] + if !failed || !now.Before(r.at) { + return region, true, time.Time{} + } + if next.IsZero() || r.at.Before(next) { + next = r.at + } } - return "", len(s.buffer) < s.cfg.Buffer + return "", len(s.buffer) < s.cfg.Buffer, next } // add puts a photo found for region in the buffer, and marks it used so no -// later search finds it again. +// later search finds it again. Past GEO_BUFFER and extraPhotos it drops the +// oldest, but never a GEO_KEEP region's last. func (s *server) add(p geo.Photo, region string) { s.mu.Lock() s.buffer = append(s.buffer, p) - if over := len(s.buffer) - s.cfg.Buffer - extraPhotos; over > 0 { - s.buffer = slices.Delete(s.buffer, 0, over) + for over := len(s.buffer) - s.cfg.Buffer - extraPhotos; over > 0; over-- { + i := slices.IndexFunc(s.buffer, s.droppable) + if i < 0 { + break + } + s.buffer = slices.Delete(s.buffer, i, i+1) } s.markUsed(p.Key()) delete(s.wants, region) + delete(s.retries, region) close(s.changed) s.changed = make(chan struct{}) n := len(s.buffer) @@ -104,14 +167,35 @@ func (s *server) add(p geo.Photo, region string) { s.log.Printf("a %s photo is ready; %d in all", p.Source, n) } -// take is a photo from the buffer for region, waiting up to photoWait for -// the prefetcher to find one. -func (s *server) take(ctx context.Context, region string) (geo.Photo, bool) { - t := time.NewTimer(s.photoWait) +// droppable reports whether p, in the buffer, can leave it without leaving +// a GEO_KEEP region with no photo. s.mu is held. +func (s *server) droppable(p geo.Photo) bool { + for _, region := range s.cfg.Keep { + if !s.in(p, region) { + continue + } + n := 0 + for _, q := range s.buffer { + if s.in(q, region) { + n++ + } + } + if n < 2 { + return false + } + } + return true +} + +// take is a photo from the buffer for region, waiting up to wait for the +// prefetcher to find one. Taking one wakes the prefetcher, which refills a +// GEO_KEEP region it used up. +func (s *server) take(ctx context.Context, region string, wait time.Duration) (geo.Photo, bool) { + t := time.NewTimer(max(wait, 0)) defer t.Stop() for { s.mu.Lock() - if i := s.match(region); i >= 0 { + if i := s.pick(region); i >= 0 { p := s.buffer[i] s.buffer = slices.Delete(s.buffer, i, i+1) s.mu.Unlock() @@ -134,23 +218,36 @@ func (s *server) take(ctx context.Context, region string) (geo.Photo, bool) { } } +// pick is the index of the photo take gives for region, or -1: the oldest +// in it, but for a region not in GEO_KEEP, one a GEO_KEEP region can spare +// if there is one, so a plain /geo leaves the kept photo for its region. +// s.mu is held. +func (s *server) pick(region string) int { + if !slices.ContainsFunc(s.cfg.Keep, func(k string) bool { return strings.EqualFold(k, region) }) { + if i := slices.IndexFunc(s.buffer, func(p geo.Photo) bool { return s.in(p, region) && s.droppable(p) }); i >= 0 { + return i + } + } + return s.match(region) +} + // match is the index of the oldest photo in the buffer that is in region // ("" is GEO_REGIONS), or -1. s.mu is held. func (s *server) match(region string) int { + return slices.IndexFunc(s.buffer, func(p geo.Photo) bool { return s.in(p, region) }) +} + +// in reports whether p is in region ("" is GEO_REGIONS, and empty too the +// world). s.mu is held. +func (s *server) in(p geo.Photo, region string) bool { if region == "" { region = s.cfg.Regions } if region == "" { - if len(s.buffer) == 0 { - return -1 - } - return 0 + return true } seeds, err := s.seedsLocked(region) - if err != nil { - return -1 - } - return slices.IndexFunc(s.buffer, func(p geo.Photo) bool { return seeds.Has(p.Place.CountryCode) }) + return err == nil && seeds.Has(p.Place.CountryCode) } // regionSeeds is the seeds for region, a /geo argument, or an error if it diff --git a/cmd/geoguess/rpc.go b/cmd/geoguess/rpc.go index 8002839..fc758ce 100644 --- a/cmd/geoguess/rpc.go +++ b/cmd/geoguess/rpc.go @@ -84,7 +84,9 @@ func (w *wire) send(v any) error { type handler func(ctx context.Context, params json.RawMessage) (any, error) // serve reads requests from in until it ends or ctx does, answering each on -// its own goroutine through out, and waits for the answers in flight. +// its own goroutine through out, and waits for the answers in flight. A +// request the client cancels (notifications/cancelled) has its context +// cancelled, so it stops rather than act for no one. func (s *server) serve(ctx context.Context, in io.Reader, out io.Writer) error { s.out = &wire{w: out} ctx, cancel := context.WithCancel(ctx) @@ -92,6 +94,8 @@ func (s *server) serve(ctx context.Context, in io.Reader, out io.Writer) error { go s.notifier(ctx) var wg sync.WaitGroup defer wg.Wait() + var mu sync.Mutex + inFlight := map[string]context.CancelFunc{} // by request ID r := bufio.NewReaderSize(in, 64<<10) for { line, err := readLine(r) @@ -109,13 +113,34 @@ func (s *server) serve(ctx context.Context, in io.Reader, out io.Writer) error { s.out.send(response{JSONRPC: "2.0", ID: json.RawMessage("null"), Error: &rpcError{codeParse, "parse error"}}) continue } + if m.Method == "notifications/cancelled" { + var p struct { + RequestID json.RawMessage `json:"requestId"` + } + json.Unmarshal(m.Params, &p) + mu.Lock() + if stop := inFlight[string(p.RequestID)]; stop != nil { + stop() + } + mu.Unlock() + continue + } if len(m.ID) == 0 || m.Method == "" { // a notification, or a response continue } + id := string(m.ID) + rctx, stop := context.WithCancel(ctx) + mu.Lock() + inFlight[id] = stop + mu.Unlock() wg.Add(1) go func() { defer wg.Done() - s.out.send(s.answer(ctx, m)) + s.out.send(s.answer(rctx, m)) + mu.Lock() + delete(inFlight, id) + mu.Unlock() + stop() }() } } @@ -285,7 +310,8 @@ type callParams struct { } // callContext is the message a call came from: pseudonyms for its chat and -// sender, and the bot's receive times in whole seconds. +// sender, and the bot's receive times in whole seconds; and, for a call the +// bot waits on, when it stops waiting. type callContext struct { Chat string `json:"chat"` Sender string `json:"sender"` @@ -294,6 +320,7 @@ type callContext struct { Group bool `json:"group"` Sent int64 `json:"sent"` Edited int64 `json:"edited"` + Deadline int64 `json:"deadline,omitempty"` } // methods are the MCP methods GeoGuess answers. diff --git a/cmd/geoguess/server.go b/cmd/geoguess/server.go index 99ad2c9..4d290d5 100644 --- a/cmd/geoguess/server.go +++ b/cmd/geoguess/server.go @@ -18,13 +18,12 @@ import ( // server is GeoGuess: the chats' rounds, their scores, the outbox the bot // reads, and the photos kept ready. type server struct { - cfg config - clock clock - photos finder - log *log.Logger - doc *state.Doc - nonce string // this run's, in each outbox cursor and op ID - photoWait time.Duration // how long /geo waits for a photo when none is ready + cfg config + clock clock + photos finder + log *log.Logger + doc *state.Doc + nonce string // this run's, in each outbox cursor and op ID out *wire dirty chan struct{} // the outbox gained ops: tell the client @@ -40,6 +39,7 @@ type server struct { subscribed bool // the client wants to hear of the outbox buffer []geo.Photo // photos ready for a round, oldest first wants map[string]bool // regions a /geo asked for that the buffer lacks + retries map[string]retry // GEO_KEEP regions whose last search failed changed chan struct{} // closed when the buffer gains a photo seeds map[string]*geo.Seeds network string // the chat network the bot said it is on, "" if it didn't @@ -109,17 +109,17 @@ const ( func newServer(cfg config, clk clock, photos finder, logger *log.Logger) (*server, error) { s := &server{ cfg: cfg, clock: clk, photos: photos, log: logger, - doc: state.Open(cfg.StateDir, "geo"), - nonce: randomID(4), - photoWait: 10 * time.Second, - dirty: make(chan struct{}, 1), - wake: make(chan struct{}, 1), - rounds: map[string]*round{}, - timers: map[string]stopper{}, - scores: map[string][]score{}, - wants: map[string]bool{}, - changed: make(chan struct{}), - seeds: map[string]*geo.Seeds{}, + doc: state.Open(cfg.StateDir, "geo"), + nonce: randomID(4), + dirty: make(chan struct{}, 1), + wake: make(chan struct{}, 1), + rounds: map[string]*round{}, + timers: map[string]stopper{}, + scores: map[string][]score{}, + wants: map[string]bool{}, + retries: map[string]retry{}, + changed: make(chan struct{}), + seeds: map[string]*geo.Seeds{}, } var st saved if _, err := s.doc.Load(&st); err != nil { diff --git a/docs/FILES_LINKS_TOOLS_MCP.md b/docs/FILES_LINKS_TOOLS_MCP.md index 58cda10..0bccecc 100644 --- a/docs/FILES_LINKS_TOOLS_MCP.md +++ b/docs/FILES_LINKS_TOOLS_MCP.md @@ -56,7 +56,7 @@ The model can call tools from [MCP](https://modelcontextprotocol.io) servers, re }, "geo": { "command": "/addons/geoguess", - "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m"}}, + "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m", "timeout": "60s"}}, "addon": {"chats": ["all"], "dms": false, "post": true, "react": true, "watch": true, "watch_max": "1h"} }, "files": { @@ -77,7 +77,7 @@ The model can call tools from [MCP](https://modelcontextprotocol.io) servers, re | `allowed_tools` / `blocked_tools` | offer only these tools, or every tool but these (one or the other, not both) | | `instructions` | a line added to the system prompt while the server's tools are offered (see below) | | `keywords` | offer the server's tools only when a message has one of these words (see below). A server without them is offered with every message, except one whose page or file the model is shown, so what a document says can't call its tools | -| `chat_commands` | optional slash-command shortcuts to a tool (you can always just ask): `tool` names it, `require_arg` makes a bare command get a usage reply, and `example` adds one to it; for an addon, `direct` has the bot call the tool itself, without the model (see [Addons](#addons)) | +| `chat_commands` | optional slash-command shortcuts to a tool (you can always just ask): `tool` names it, `require_arg` makes a bare command get a usage reply, and `example` adds one to it; for an addon, `direct` has the bot call the tool itself, without the model, and `timeout` sets how long that call may take (see [Addons](#addons)) | | `addon` | makes a local server an addon, and says where it may act and what it may do (see [Addons](#addons)) | | `disabled` | leave the server out without deleting it | @@ -105,7 +105,7 @@ An addon is a local MCP server that does more than offer tools: it answers its o ```jsonc "geo": { "command": "/addons/geoguess", - "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m"}}, + "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m", "timeout": "60s"}}, "addon": { "chats": ["<group ID>"], "dms": false, @@ -133,7 +133,7 @@ Each permission is off unless set. For an addon, `chats`, `dms` and these permis **What an addon sees.** Never a phone number, account ID or group ID: chats and people are pseudonyms the bot makes with a secret kept in `mcp.json` in the state directory, different for each addon. It sees a command's text after the command, the messages its watches match, and, with `names`, display names. To name someone in what it says, it writes their pseudonym as `{u_…}`, and the bot puts in the name it last saw them use there, as an @mention, or "someone". -- **Direct commands.** `"direct": true` on a chat command has the bot call the addon's tool itself, with the text after the command, and send what it answers (text, and up to 2 pictures) without the model. The tool must be marked for the bot, and is then never offered to the model. A call has 15 seconds, and at most 2 run at once per addon; a third is told the addon is busy. When it fails, the chat gets a short line ("GeoGuess couldn't do that just now."), never the addon's own error text. An addon with no tool for the model has its commands named in the prompt's list of what the bot has, so the model can point people to them. +- **Direct commands.** `"direct": true` on a chat command has the bot call the addon's tool itself, with the text after the command, and send what it answers (text, and up to 2 pictures) without the model. The tool must be marked for the bot, and is then never offered to the model. A call has 15 seconds, or the command's `timeout`, from 1s to 2m (`"timeout": "60s"`), for an addon that may take a while, such as GeoGuess finding a photo; while it runs the chat sees the bot typing. At most 2 run at once per addon; a third is told the addon is busy, so with a long `timeout`, two calls that wait (two chats each waiting for a GeoGuess photo) make even a quick command such as `/geo scores` wait for one to end. When it fails, the chat gets a short line ("GeoGuess couldn't do that just now."), never the addon's own error text. An addon with no tool for the model has its commands named in the prompt's list of what the bot has, so the model can point people to them. - **Hidden tools.** A tool whose `_meta` says it is for the bot alone (`io.github.robdevops.signalbot/visibility` without `"model"`, or MCP Apps' `ui.visibility` without `"model"`) is never offered to the model or listed as one of its tools, so tools that read chat text stay out of its hands. - **Watches.** A direct command's answer can ask for a watch on its chat: a pattern, such as map links, until a time at most `watch_max` away. While it lasts, a message there that matches goes to the addon instead: it isn't answered, isn't sent to the model, and isn't kept in history, even as group context; so does an edit of it later. The addon may react to it, so people see it was counted. A pattern that would match ordinary chat ("lol", "see you at 5", a news link, …) is refused, so a watch can't become a feed of everything said; at most 8 run in a chat at once. While a watch lasts, a reply to the command's pictures that asks the bot gets the addon's set answer (GeoGuess's "No hints during a round 😉"), not the model's. - **Outbox.** An addon posts when it likes by queueing posts, reactions and the end of a watch in its outbox, an MCP resource the bot subscribes to (`signalbot://outbox`), and saying it changed; the bot reads it at once. It may post or react only in a chat where it was used, by a command or a watch, in the last 24 hours, and only within `rate`. Its posts go through the chat's queue like any message, never more than one at a time, and history keeps them as the bot's, labelled with the addon's name (`[GeoGuess] …`), so what an addon writes never poses as a person. diff --git a/examples/signalbot-mcp.json b/examples/signalbot-mcp.json index 3c5cfdf..e306e08 100644 --- a/examples/signalbot-mcp.json +++ b/examples/signalbot-mcp.json @@ -12,7 +12,7 @@ }, "geo": { "command": "/addons/geoguess", - "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m"}}, + "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m", "timeout": "60s"}}, "addon": {"chats": ["all"], "dms": false, "post": true, "react": true, "watch": true, "watch_max": "1h"} }, "files": { diff --git a/internal/bot/bot.go b/internal/bot/bot.go index 77910d2..6516326 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -403,7 +403,7 @@ func (b *Bot) work(rs []Received) { case !msg.Addressed: alone(func() { b.overhear(msg) }) default: - if act := b.onMessage(b.ctx, msg); !act.IsZero() { + if act := b.hooked(msg); !act.IsZero() { alone(func() { b.respond(msg, act, prompt(msg), refs(msg)) }) return } @@ -541,6 +541,37 @@ func (b *Bot) onMessage(ctx context.Context, msg feature.Message) feature.Action return feature.Action{} } +// slowHooks is how long an addressed message's OnMessage hooks may run +// before the chat sees the bot typing. +const slowHooks = time.Second + +// hooked runs the OnMessage hooks for an addressed message, in its chat's +// slot. If they haven't returned after slowHooks, the chat sees the bot +// typing until they do, as it would while the model answers; quick ones +// show nothing. +func (b *Bot) hooked(msg feature.Message) feature.Action { + var mu sync.Mutex + var stop func() + done := false + timer := time.AfterFunc(slowHooks, func() { + mu.Lock() + defer mu.Unlock() + if !done { + stop = b.net.Typing(msg.Chat) + } + }) + defer func() { // also if a hook panics + timer.Stop() + mu.Lock() + defer mu.Unlock() + done = true + if stop != nil { + stop() + } + }() + return b.onMessage(b.ctx, msg) +} + // introLine is a feature's line for the introduction, perhaps only in a DM. type introLine struct { text string diff --git a/internal/bot/bot_test.go b/internal/bot/bot_test.go index 7a4cffd..9942ec4 100644 --- a/internal/bot/bot_test.go +++ b/internal/bot/bot_test.go @@ -321,6 +321,35 @@ func TestWaitingCommandOnItsOwn(t *testing.T) { } } +// A hook that takes over a second on an addressed message shows the bot +// typing, stopped before the answer goes out; a quick one shows nothing. +func TestSlowHookTypes(t *testing.T) { + h := start(t, options{features: func(b *Bot) { + b.OnMessage(func(_ context.Context, m feature.Message) feature.Action { + switch m.Text { + case "/slow": + time.Sleep(1500 * time.Millisecond) + return feature.Action{Answer: "slow"} + case "/fast": + return feature.Action{Answer: "fast"} + } + return feature.Action{} + }) + }}) + h.receive(dm("/fast")) + if s := h.nextSend(); s.text != "fast" || h.typing() != 0 { + t.Fatalf("fast: sent %q, typing %d times", s.text, h.typing()) + } + h.receive(dm("/slow")) + if s := h.nextSend(); s.text != "slow" || h.typing() != 1 || h.stopped() != 1 { + t.Fatalf("slow: sent %q, typing %d times, stopped %d", s.text, h.typing(), h.stopped()) + } + h.settle() + if h.typing() != 1 || h.stopped() != 1 { + t.Fatalf("after: typing %d times, stopped %d", h.typing(), h.stopped()) + } +} + // While a batch is being answered, 4 more messages can wait, and they are // answered together after it, in one batch. func TestFourWaitDuringABatch(t *testing.T) { diff --git a/internal/bot/fakes_test.go b/internal/bot/fakes_test.go index a01cbe1..98fca83 100644 --- a/internal/bot/fakes_test.go +++ b/internal/bot/fakes_test.go @@ -53,6 +53,7 @@ type fakeNet struct { sent chan sent // what the bot sends, in order mu sync.Mutex typing int // Typing calls + stopped int // their stops called fetched []string // the media IDs fetched sends atomic.Int64 // Send calls, for their timestamps watch Watch // what Watch was told @@ -101,7 +102,11 @@ func (n *fakeNet) Typing(feature.Chat) func() { n.mu.Lock() defer n.mu.Unlock() n.typing++ - return func() {} + return func() { + n.mu.Lock() + defer n.mu.Unlock() + n.stopped++ + } } func (n *fakeNet) Delivered(ctx context.Context, msg feature.Message) (Ready, bool) { @@ -328,6 +333,13 @@ func (h *harness) noSend() { } } +// stopped is how many of the Typing calls' stops were called. +func (h *harness) stopped() int { + h.net.mu.Lock() + defer h.net.mu.Unlock() + return h.net.stopped +} + func (h *harness) typing() int { h.net.mu.Lock() defer h.net.mu.Unlock() diff --git a/internal/bot/host.go b/internal/bot/host.go index 6c9d9f4..2c901f6 100644 --- a/internal/bot/host.go +++ b/internal/bot/host.go @@ -259,7 +259,7 @@ func (b *Bot) delivered(msg feature.Message) { b.chats.Learn(key, msg.Name, msg.Sender) } msg.Addressed = true - if act := b.onMessage(b.ctx, msg); !act.IsZero() || r.Mentioned { + if act := b.hooked(msg); !act.IsZero() || r.Mentioned { b.respond(msg, act, prompt(msg), nil) return } diff --git a/internal/features/mcp/addon.go b/internal/features/mcp/addon.go index 62a1d52..4df2f4d 100644 --- a/internal/features/mcp/addon.go +++ b/internal/features/mcp/addon.go @@ -304,6 +304,7 @@ type callContext struct { Sent int64 `json:"sent"` // when the bot got it, in Unix seconds Edited int64 `json:"edited"` // when the bot got the edit; 0 for an original Name string `json:"name,omitempty"` + Deadline int64 `json:"deadline,omitempty"` // a direct call's: when the bot stops waiting, in Unix seconds } // context is m's context for the addon, which the bot got at at. It keeps diff --git a/internal/features/mcp/addon_test.go b/internal/features/mcp/addon_test.go index 8657658..10a0878 100644 --- a/internal/features/mcp/addon_test.go +++ b/internal/features/mcp/addon_test.go @@ -111,6 +111,9 @@ func TestAddonProcess(t *testing.T) { } `json:"params"` } json.Unmarshal(sc.Bytes(), &req) + if req.Method == "notifications/cancelled" { + fakeLog("cancelled " + string(sc.Bytes())) + } if req.ID == nil { continue } @@ -287,7 +290,7 @@ func TestAddonLoad(t *testing.T) { `{"mcpServers":{"geo":{"command":"x","addon":{"chats":["all","` + groupA + `"]}}}}`: `: MCP server "geo": addon chats: "all" goes alone`, `{"mcpServers":{"geo":{"command":"x","addon":{"watch_max":"25h"}}}}`: `: MCP server "geo": addon watch_max: "25h" isn't a time from 1s to 24h, such as 1h or 30m`, `{"mcpServers":{"geo":{"command":"x","addon":{"rate":{"burst":-1}}}}}`: `: MCP server "geo": addon rate: per_minute and burst can't be below 0`, - `{"mcpServers":{"geo":{"command":"x","chat_commands":{"g":{"tool":"g","drect":true}},"addon":{}}}}`: `: MCP server "geo": chat command "g": unknown setting "drect" (settings are tool, require_arg, example, direct)`, + `{"mcpServers":{"geo":{"command":"x","chat_commands":{"g":{"tool":"g","drect":true}},"addon":{}}}}`: `: MCP server "geo": chat command "g": unknown setting "drect" (settings are tool, require_arg, example, direct, timeout)`, } { p := writeConfig(t, bad) if _, err := load(p); err == nil || err.Error() != p+want { @@ -366,7 +369,8 @@ func TestDirect(t *testing.T) { c := meta[vendor+"context"] id := regexp.MustCompile(`^[cur]_[a-z2-7]{26}$`) if !id.MatchString(c.Chat) || !id.MatchString(c.Sender) || !id.MatchString(c.Ref) || c.Chat[0] != 'c' || c.Sender[0] != 'u' || c.Ref[0] != 'r' || - !c.Addressed || !c.Group || c.Edited != 0 || c.Name != "" || time.Since(time.Unix(c.Sent, 0)) > time.Minute { + !c.Addressed || !c.Group || c.Edited != 0 || c.Name != "" || time.Since(time.Unix(c.Sent, 0)) > time.Minute || + time.Until(time.Unix(c.Deadline, 0)) > directTimeout || time.Until(time.Unix(c.Deadline, 0)) < directTimeout-5*time.Second { t.Fatalf("context %+v", c) } if strings.Contains(got.Answer, "alice-id") || strings.Contains(got.Answer, groupA) || strings.Contains(got.Answer, "Alice") { @@ -447,6 +451,28 @@ func TestDirectResults(t *testing.T) { } } +// A direct command's timeout replaces directTimeout for its calls, and a +// call past it is cancelled, so the addon can stop work nobody will see. +func TestDirectTimeout(t *testing.T) { + t.Setenv("GAME_LOG", filepath.Join(t.TempDir(), "game.log")) + h, log := startAddon(t, `{"mcpServers":{"game":`+addonServer("addon", `{"dms":true}`, + `,"chat_commands":{"hang":{"tool":"hang","direct":true,"timeout":"1s"}}`)+`}}`) + start := time.Now() + if got := h.Message(context.Background(), in(inDM, "/hang")); got.Answer != "Game couldn't do that just now." { + t.Fatalf("hang: %+v", got) + } + if took := time.Since(start); took < time.Second || took >= directTimeout { + t.Errorf("took %v, want 1s", took) + } + if !strings.Contains(log.String(), "/hang called hang: no answer in time") { + t.Errorf("log %q", log.String()) + } + eventually(t, "a cancellation", func() bool { return len(gameLog(t, "cancelled ")) == 1 }) + if got := gameLog(t, "cancelled ")[0]; !regexp.MustCompile(`"params":\{"requestId":\d+\}`).MatchString(got) { + t.Errorf("cancelled %s", got) + } +} + // A require_arg direct command answers a bare one with its example, not // pointing to the model. func TestDirectRequireArg(t *testing.T) { diff --git a/internal/features/mcp/conn.go b/internal/features/mcp/conn.go index b233325..3b11ff3 100644 --- a/internal/features/mcp/conn.go +++ b/internal/features/mcp/conn.go @@ -359,10 +359,19 @@ func (c *stdioConn) call(ctx context.Context, method string, params any) (json.R } return m.Result, nil case <-ctx.Done(): + if method != "initialize" { // which MCP says is never cancelled + c.write(rpcMsg{JSONRPC: "2.0", Method: "notifications/cancelled", Params: cancelled{RequestID: id}}) + } return nil, ctx.Err() } } +// cancelled is notifications/cancelled's params: the server may stop work +// on a request whose answer the bot no longer waits for. +type cancelled struct { + RequestID int64 `json:"requestId"` +} + func (c *stdioConn) notify(_ context.Context, method string, params any) error { return c.write(rpcMsg{JSONRPC: "2.0", Method: method, Params: params}) } diff --git a/internal/features/mcp/direct.go b/internal/features/mcp/direct.go index b1fe02c..b20b379 100644 --- a/internal/features/mcp/direct.go +++ b/internal/features/mcp/direct.go @@ -1,6 +1,7 @@ package mcp import ( + "cmp" "context" "encoding/base64" "encoding/json" @@ -28,15 +29,22 @@ const ( maxPictureBytes = 2 << 20 ) -// directTimeout is how long a direct call may take, short of callTimeout so -// a hung addon can't hold a message's slot long; tests shorten it. +// directTimeout is how long a direct call may take, unless its command sets +// a timeout, and a watch's call; short of callTimeout so a hung addon can't +// hold a message's slot long; tests shorten it. maxDirectTimeout is the +// longest a command may set. var directTimeout = 15 * time.Second -// direct answers /name in m by calling the addon's tool itself, with args -// and m's context: the result's text and pictures, sent without the model. +const maxDirectTimeout = 2 * time.Minute + +// direct answers /name in m by calling the addon's tool c.Tool itself, with +// args and m's context, for at most c's timeout: the result's text and +// pictures, sent without the model. The context says when the bot stops +// waiting, so the addon can give up in time rather than act on a call +// nobody will see; one that runs past it is cancelled. // A failure is told in words for people; the server's own text is never // shown or logged. -func (a *addon) direct(ctx context.Context, m feature.Message, name, tool, args string) feature.Action { +func (a *addon) direct(ctx context.Context, m feature.Message, name string, c chatCommand, args string) feature.Action { if !a.allows(m.Chat) { return feature.Action{Answer: "/" + name + " isn't available in this chat."} } @@ -48,13 +56,16 @@ func (a *addon) direct(ctx context.Context, m feature.Message, name, tool, args return feature.Action{Answer: a.title + " is busy, try again in a moment."} } a.lease(m.Chat) - ctx, cancel := context.WithTimeout(ctx, directTimeout) + timeout := cmp.Or(c.timeout, directTimeout) + ctx, cancel := context.WithTimeout(ctx, timeout) defer cancel() start := time.Now() + cc := a.context(m, a.now()) + cc.Deadline = start.Add(timeout).Unix() // rounded down, so never late res, err := a.conn.call(ctx, "tools/call", map[string]any{ - "name": tool, + "name": c.Tool, "arguments": map[string]string{"args": args}, - "_meta": map[string]any{vendor + "context": a.context(m, a.now())}, + "_meta": map[string]any{vendor + "context": cc}, }) var r toolResult outcome := "ok" @@ -66,7 +77,7 @@ func (a *addon) direct(ctx context.Context, m feature.Message, name, tool, args case r.IsError: outcome = "an error result" } - logx.Infof("MCP server %s: /%s called %s: %s in %dms, %d bytes", a.server, name, tool, outcome, time.Since(start).Milliseconds(), len(res)) + logx.Infof("MCP server %s: /%s called %s: %s in %dms, %d bytes", a.server, name, c.Tool, outcome, time.Since(start).Milliseconds(), len(res)) if outcome != "ok" { return feature.Action{Answer: a.title + " couldn't do that just now."} } diff --git a/internal/features/mcp/mcp.go b/internal/features/mcp/mcp.go index 2043b16..97c0f22 100644 --- a/internal/features/mcp/mcp.go +++ b/internal/features/mcp/mcp.go @@ -56,12 +56,16 @@ type server struct { // chatCommand makes "/name ..." a turn in which the model must call tool, // or, if direct, an addon's tool the bot calls itself, without the model. // With require_arg, a bare "/name" is answered by the bot, not the model, -// showing example if set. +// showing example if set. A direct command's timeout is how long its call +// may take, from 1s to 2m; unset, directTimeout. type chatCommand struct { Tool string `json:"tool"` RequireArg bool `json:"require_arg"` Example string `json:"example"` Direct bool `json:"direct"` + Timeout string `json:"timeout"` + + timeout time.Duration // Timeout, read; 0 if unset } // settings are the keys a server may have, and commandSettings a chat @@ -70,7 +74,7 @@ type chatCommand struct { var ( settings = []string{"url", "headers", "command", "args", "env", "allowed_tools", "blocked_tools", "instructions", "keywords", "chat_commands", "disabled", "addon"} - commandSettings = []string{"tool", "require_arg", "example", "direct"} + commandSettings = []string{"tool", "require_arg", "example", "direct", "timeout"} ignored = []string{"type", "transport", "timeout", "alwaysAllow", "autoApprove", "description"} ) @@ -182,9 +186,21 @@ func load(path string) (map[string]server, error) { if err := unknown(c, commandSettings); err != nil { return nil, bad("chat command %q: %v", txt.Clamp(n, 40), err) } - if s.ChatCommands[n].Direct && s.Addon == nil { + cc := s.ChatCommands[n] + if cc.Direct && s.Addon == nil { return nil, bad("chat command %q is direct, which needs an addon block", txt.Clamp(n, 40)) } + if _, set := c["timeout"]; set { + if !cc.Direct { + return nil, bad("chat command %q has a timeout, which only a direct command takes", txt.Clamp(n, 40)) + } + d, err := time.ParseDuration(cc.Timeout) + if err != nil || d < time.Second || d > maxDirectTimeout { + return nil, bad("chat command %q: timeout %q isn't a time from 1s to 2m, such as 15s or 1m", txt.Clamp(n, 40), txt.Clamp(cc.Timeout, 40)) + } + cc.timeout = d + s.ChatCommands[n] = cc + } } switch { case (s.URL == "") == (s.Command == ""): @@ -548,7 +564,7 @@ func command(h feature.Host, server, n string, c chatCommand, models map[string] case c.RequireArg && args == "": return feature.Action{Answer: bare} case c.Direct: - return a.direct(ctx, m, name, c.Tool, args) + return a.direct(ctx, m, name, c, args) } return feature.Action{ToolChoice: model} }) diff --git a/internal/features/mcp/mcp_test.go b/internal/features/mcp/mcp_test.go index 881d908..75bbe4c 100644 --- a/internal/features/mcp/mcp_test.go +++ b/internal/features/mcp/mcp_test.go @@ -255,9 +255,12 @@ func TestLoad(t *testing.T) { // settings it could be, and both lists at once too; keys other clients // write are ignored, so a pasted entry starts. for bad, want := range map[string]string{ - `{"mcpServers":{"w":{"url":"u","allowedTools":["t"]}}}`: `: MCP server "w": unknown setting "allowedTools" (settings are url, headers, command, args, env, allowed_tools, blocked_tools, instructions, keywords, chat_commands, disabled, addon)`, - `{"mcpServers":{"w":{"url":"u","chat_commands":{"x":{"tool":"t","requireArg":true}}}}}`: `: MCP server "w": chat command "x": unknown setting "requireArg" (settings are tool, require_arg, example, direct)`, - `{"mcpServers":{"w":{"url":"u","allowed_tools":[],"blocked_tools":["t"]}}}`: `: MCP server "w": has both allowed_tools and blocked_tools; use one`, + `{"mcpServers":{"w":{"url":"u","allowedTools":["t"]}}}`: `: MCP server "w": unknown setting "allowedTools" (settings are url, headers, command, args, env, allowed_tools, blocked_tools, instructions, keywords, chat_commands, disabled, addon)`, + `{"mcpServers":{"w":{"url":"u","chat_commands":{"x":{"tool":"t","requireArg":true}}}}}`: `: MCP server "w": chat command "x": unknown setting "requireArg" (settings are tool, require_arg, example, direct, timeout)`, + `{"mcpServers":{"w":{"url":"u","chat_commands":{"x":{"tool":"t","timeout":"30s"}}}}}`: `: MCP server "w": chat command "x" has a timeout, which only a direct command takes`, + `{"mcpServers":{"w":{"command":"c","addon":{},"chat_commands":{"x":{"tool":"t","direct":true,"timeout":"3m"}}}}}`: `: MCP server "w": chat command "x": timeout "3m" isn't a time from 1s to 2m, such as 15s or 1m`, + `{"mcpServers":{"w":{"command":"c","addon":{},"chat_commands":{"x":{"tool":"t","direct":true,"timeout":"500ms"}}}}}`: `: MCP server "w": chat command "x": timeout "500ms" isn't a time from 1s to 2m, such as 15s or 1m`, + `{"mcpServers":{"w":{"url":"u","allowed_tools":[],"blocked_tools":["t"]}}}`: `: MCP server "w": has both allowed_tools and blocked_tools; use one`, } { p := writeConfig(t, bad) if _, err := load(p); err == nil || err.Error() != p+want { From 2a3dadc359926810c8ae59e52ce95e154bd1aca4 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Fri, 20 Nov 2026 20:32:47 +0000 Subject: [PATCH 10/26] Move GeoGuess to robdevops/chat-plugin-geoguess GeoGuess now lives in its own repository, with its history, as its own Go module. signalbot keeps the addon support (MCP_CONFIG's addon block, direct commands, watches, the outbox) and its docs, which now link the new repository as the example addon. The arch test's import rule for cmd/geoguess goes with it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- CONTRIBUTING.md | 3 +- PRIVACY.md | 2 +- README.md | 2 +- TECHNICAL.md | 1 - cmd/geoguess/README.md | 167 --- cmd/geoguess/clock.go | 19 - cmd/geoguess/config.go | 173 --- cmd/geoguess/game.go | 421 ------- cmd/geoguess/geo/find.go | 113 -- cmd/geoguess/geo/find_test.go | 178 --- cmd/geoguess/geo/mapillary.go | 177 --- cmd/geoguess/geo/panoramax.go | 214 ---- cmd/geoguess/geo/parse.go | 223 ---- cmd/geoguess/geo/parse_test.go | 136 --- cmd/geoguess/geo/pixels.go | 277 ----- cmd/geoguess/geo/pixels_test.go | 267 ---- cmd/geoguess/geo/place.go | 81 -- cmd/geoguess/geo/place_test.go | 56 - cmd/geoguess/geo/rules.go | 134 -- cmd/geoguess/geo/rules_test.go | 100 -- cmd/geoguess/geo/score.go | 108 -- cmd/geoguess/geo/score_test.go | 93 -- cmd/geoguess/geo/seeds.go | 149 --- cmd/geoguess/geo/seeds.json | 310 ----- cmd/geoguess/geo/seeds_test.go | 155 --- cmd/geoguess/geo/source.go | 176 --- cmd/geoguess/geo/source_test.go | 372 ------ cmd/geoguess/geo/testdata/mapillary_bbox.json | 244 ---- .../geo/testdata/mapillary_error.json | 1 - .../geo/testdata/mapillary_radius.json | 154 --- .../geo/testdata/panoramax_search.json | 614 ---------- cmd/geoguess/main.go | 113 -- cmd/geoguess/main_test.go | 1082 ----------------- cmd/geoguess/prefetch.go | 320 ----- cmd/geoguess/rpc.go | 447 ------- cmd/geoguess/server.go | 308 ----- docs/CONFIGURATION.md | 2 +- docs/FILES_LINKS_TOOLS_MCP.md | 2 +- internal/arch/arch_test.go | 5 +- 39 files changed, 6 insertions(+), 7393 deletions(-) delete mode 100644 cmd/geoguess/README.md delete mode 100644 cmd/geoguess/clock.go delete mode 100644 cmd/geoguess/config.go delete mode 100644 cmd/geoguess/game.go delete mode 100644 cmd/geoguess/geo/find.go delete mode 100644 cmd/geoguess/geo/find_test.go delete mode 100644 cmd/geoguess/geo/mapillary.go delete mode 100644 cmd/geoguess/geo/panoramax.go delete mode 100644 cmd/geoguess/geo/parse.go delete mode 100644 cmd/geoguess/geo/parse_test.go delete mode 100644 cmd/geoguess/geo/pixels.go delete mode 100644 cmd/geoguess/geo/pixels_test.go delete mode 100644 cmd/geoguess/geo/place.go delete mode 100644 cmd/geoguess/geo/place_test.go delete mode 100644 cmd/geoguess/geo/rules.go delete mode 100644 cmd/geoguess/geo/rules_test.go delete mode 100644 cmd/geoguess/geo/score.go delete mode 100644 cmd/geoguess/geo/score_test.go delete mode 100644 cmd/geoguess/geo/seeds.go delete mode 100644 cmd/geoguess/geo/seeds.json delete mode 100644 cmd/geoguess/geo/seeds_test.go delete mode 100644 cmd/geoguess/geo/source.go delete mode 100644 cmd/geoguess/geo/source_test.go delete mode 100644 cmd/geoguess/geo/testdata/mapillary_bbox.json delete mode 100644 cmd/geoguess/geo/testdata/mapillary_error.json delete mode 100644 cmd/geoguess/geo/testdata/mapillary_radius.json delete mode 100644 cmd/geoguess/geo/testdata/panoramax_search.json delete mode 100644 cmd/geoguess/main.go delete mode 100644 cmd/geoguess/main_test.go delete mode 100644 cmd/geoguess/prefetch.go delete mode 100644 cmd/geoguess/rpc.go delete mode 100644 cmd/geoguess/server.go diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index e5a3f70..54f1054 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,7 +16,6 @@ internal/feature/ the ports and shared types, command parsing, featuretest internal/features/* one package per feature internal/kit/* code with two or more users and no bot knowledge cmd/signalctl/ a small client for signal-cli's daemon socket, for one-off chores such as blocking; not part of the bot -cmd/geoguess/ GeoGuess, an addon: a separate program the bot runs as a local MCP server, speaking MCP over stdio by hand ``` ## The port rule @@ -54,7 +53,7 @@ Give a feature a tag only for a real saving, such as a dependency; a runtime set Tests in `internal/arch` enforce these: -- **Imports:** only the main package, at the module root, imports features and `internal/signal`; a feature imports only `internal/feature`, `internal/kit` and its own packages; `internal/signal` imports only `internal/feature`, kit, `internal/config` and `internal/bot` (network to core, never the reverse); `internal/config` and kit import no other internal package; `cmd/geoguess` imports only kit and its own packages. +- **Imports:** only the main package, at the module root, imports features and `internal/signal`; a feature imports only `internal/feature`, `internal/kit` and its own packages; `internal/signal` imports only `internal/feature`, kit, `internal/config` and `internal/bot` (network to core, never the reverse); `internal/config` and kit import no other internal package. - **No feature names in the core:** the core's source mentions no feature name or feature-only word (chart, MCP, group context, `/intro`, `/schedule`, …). - **Docs:** every setting read, the core's or a feature's (`h.Env("NAME", …)`), is in the table in [docs/CONFIGURATION.md](docs/CONFIGURATION.md). diff --git a/PRIVACY.md b/PRIVACY.md index 17cdcc1..baac305 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -79,7 +79,7 @@ On Telegram (`TELEGRAM_BOT_TOKEN` set) the above holds, with these differences: ## Addons -An addon is a program the bot runs on its own machine, as an [MCP server](docs/FILES_LINKS_TOOLS_MCP.md#addons), that answers its own commands, reads the messages it asks for and posts on its own, such as the [GeoGuess](cmd/geoguess/README.md) game. With none configured, none of this applies. +An addon is a program the bot runs on its own machine, as an [MCP server](docs/FILES_LINKS_TOOLS_MCP.md#addons), that answers its own commands, reads the messages it asks for and posts on its own, such as the [GeoGuess](https://github.com/robdevops/chat-plugin-geoguess) game. With none configured, none of this applies. - **It is trusted code.** It runs as the bot's user, in the same sandbox, and could read what the bot's user can, the state directory included. What follows limits what the bot hands it; it guards against mistakes and leaks, not against a hostile program. Install only addons you would let run as the bot. - **What it never gets:** phone numbers, account IDs or group IDs. Chats and people are pseudonyms, made from a secret in `mcp.json` and different for each addon; by default the same person has a different one in each chat, so an addon can't follow them between groups. It gets none of the bot's settings or keys either: only `PATH`, `HOME`, the time zone and proxy settings (`TZ`, `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, `SSL_CERT_FILE`, `SSL_CERT_DIR`) if set, and the variables named for it (such as `GEO_…`). diff --git a/README.md b/README.md index 8d685dd..d97c780 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ A small, [privacy-conscious](PRIVACY.md) chat bot for Signal, through a running - Responds to @mentions, replies to its messages, its commands (such as `/intro`) without a mention, and DMs from whitelisted contacts - Tools: web search, line and pie charts, [pictures](docs/FILES_LINKS_TOOLS_MCP.md#images) (drawings, art, diagrams) with GPT Image 2, and your own [MCP connectors](docs/FILES_LINKS_TOOLS_MCP.md#mcp-connectors) - [`/schedule`](docs/SCHEDULING.md) a message or command, once or repeating -- [Addons](docs/FILES_LINKS_TOOLS_MCP.md#addons): MCP servers that run their own commands and games in chosen groups, without the model, such as [GeoGuess](cmd/geoguess/README.md), seeing only pseudonyms +- [Addons](docs/FILES_LINKS_TOOLS_MCP.md#addons): MCP servers that run their own commands and games in chosen groups, without the model, such as [GeoGuess](https://github.com/robdevops/chat-plugin-geoguess), seeing only pseudonyms - Understands [files](docs/FILES_LINKS_TOOLS_MCP.md#files) (PDFs, text and code, Word, Excel and PowerPoint) and the [pages you link to](docs/FILES_LINKS_TOOLS_MCP.md#links), and if the model supports it, images, stickers, voice notes and other audio - Typing indicators, reactions, stickers, @mentions and replies - In-memory conversation context (Default: 10 messages). Never logged to disk, forgotten after 24 hours, or sooner if _disappearing messages_ requires. diff --git a/TECHNICAL.md b/TECHNICAL.md index 517a88a..e56f724 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -90,7 +90,6 @@ internal/features/* one package per feature internal/kit/* code with two or more users and no bot knowledge internal/arch/ the guardrail tests and the sizes report cmd/signalctl/ a small client for signal-cli's daemon socket, for one-off chores such as blocking; not part of the bot -cmd/geoguess/ GeoGuess, an MCP addon the bot can run as a child process (its own README); not part of the bot, and of the bot's packages it imports only internal/kit ``` - Core packages are concrete and call each other directly, with no interfaces between them. Files by role, no line limit. diff --git a/cmd/geoguess/README.md b/cmd/geoguess/README.md deleted file mode 100644 index 1a91a2b..0000000 --- a/cmd/geoguess/README.md +++ /dev/null @@ -1,167 +0,0 @@ -# GeoGuess - -A GeoGuessr-style game for signalbot. `/geo` posts a street-level photo; -players answer by sending a location (on Signal, the **+** button → -Location; on Telegram, 📎 → Location; then pinch to zoom out, drag the -pin, confirm on Signal, and send), or typed -coordinates such as `-37.81, 144.96`; when time is up the -bot names the place and ranks players by how far off they were. - -``` -/geo start a round (GEO_ROUND, default 3 minutes) -/geo 90s | /geo 5m start a round of that length (30s to 30m) -/geo europe a round in a continent or countries (/geo AU,NZ); combines with a length -/geo end finish now and reveal (only the player who started it) -/geo skip cancel and reveal without scoring (only the player who started it) -/geo scores this chat's totals over the last 7 days -``` - -On Signal nobody needs to mention the bot: a message that starts with `/geo`, -and any guess during a round, reaches it as it is. On Telegram `/geo` works -the same way, but plain guesses reach the bot only with privacy mode off (or -the bot an admin); with privacy mode on, which is the default, players reply -to the round's photo instead. - -It is a separate program that signalbot starts as an -[MCP addon](../../docs/FILES_LINKS_TOOLS_MCP.md#addons) server. It speaks MCP -2025-06-18 over stdio (newline-delimited JSON-RPC) by hand, with signalbot's -addon extension, and uses no MCP library. It needs no model: its commands and -guesses never reach one. - -## Install - -Build it as a static binary, which the Docker image needs (it has no shell -or runtimes) and systemd is happy with: - -``` -CGO_ENABLED=0 go build -o /opt/signalbot-addons/geoguess ./cmd/geoguess -``` - -Mount it read-only: under Docker, add `- /opt/signalbot-addons:/addons:ro` to -the volumes in `compose.yaml`; under systemd, use the host path, or bind it -with `BindReadOnlyPaths=/opt/signalbot-addons:/addons` in a drop-in. Then add -it to the MCP servers file (`MCP_CONFIG`). The server must be called `geo`, -which is what gives it the `GEO_` settings below: - -```jsonc -"geo": { - "command": "/addons/geoguess", - "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m", "timeout": "60s"}}, - "addon": {"chats": ["<group id>"], "post": true, "react": true, "watch": true, "watch_max": "1h"} -} -``` - -`chats` takes the groups' IDs as Signal or Telegram shows them, or `["all"]`; -add `"dms": true` to play in DMs too. GeoGuess needs `post` (for the results), -`react` (the 📍 on a counted guess) and `watch` (to read guesses). A round -lasts at most 30 minutes, so the default `watch_max` of 1h is enough. The -`timeout` lets `/geo` wait for a photo when none is ready: keep it above -`GEO_WAIT` (50s by default). GeoGuess never waits past the bot's timeout -anyway, less a few seconds to send the photo, and starts no round the bot has -given up on. A call that waits holds one of the bot's 2 calls at once for -GeoGuess, so while two chats each wait for a photo, `/geo end`, `/geo skip` -and `/geo scores` are told GeoGuess is busy. - -GeoGuess keeps its own files in `GEO_STATE_DIR`, which you create, writable by -the bot's user, and set in `/etc/signalbot.env`: - -- **systemd:** in a drop-in (`sudo systemctl edit signalbot`), add - `StateDirectory=geoguess` (the unit's `DynamicUser=` makes it and owns it), - and set `GEO_STATE_DIR=/var/lib/geoguess`. -- **Docker:** `sudo install -d -o 65532 -g 65532 -m 700 /var/lib/private/geoguess`, - add `- /var/lib/private/geoguess:/geo` to the volumes, and set - `GEO_STATE_DIR=/geo`. - -It shares the bot's memory limit, so allow for `GEO_MEMLIMIT` in `mem_limit` -or `MemoryMax`. - -## Settings - -signalbot passes an addon server called `geo` every `GEO_` variable from its -environment file, plus `PATH`, `HOME` and, if set, `TZ` (the round's deadline -is written in it), `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, `SSL_CERT_FILE` and -`SSL_CERT_DIR` (so it reaches the photo sources through the bot's proxy, and -trusts its CA), and nothing else. - -| Variable | Default | Description | -|---|---|---| -| `GEO_STATE_DIR` | — (required) | Where GeoGuess keeps `geo.json` and its log. Create it, writable by the bot's user; GeoGuess exits at start if it can't list and write it | -| `GEO_MAPILLARY_TOKEN` | empty | Mapillary client token (`MLY\|…`), sent as `Authorization: OAuth <token>`. Empty means Panoramax only, and then rounds are in France unless `GEO_REGIONS` says otherwise | -| `GEO_MEMLIMIT` | `200MiB` | Memory limit, applied with `debug.SetMemoryLimit`, written as `GOMEMLIMIT` is (`B`, `KiB`, `MiB`, `GiB`, `TiB`) | -| `GEO_ROUND` | `3m` | Default round length, 30s to 30m | -| `GEO_REGIONS` | empty (world) | Continents (`europe`, `asia`, `africa`, `north-america`, `south-america`, `oceania`) or ISO country codes, comma-separated | -| `GEO_MIN_QUALITY` | `0.5` | Minimum Mapillary `quality_score` (0 to 1), when a photo has one | -| `GEO_MAX_AGE_YEARS` | `10` | Ignore older photos | -| `GEO_BUFFER` | `3` | Checked photos kept ready (1 to 20) | -| `GEO_KEEP` | empty | Regions to always keep a photo ready for, comma-separated, in `GEO_REGIONS`'s names, one photo each: `AU,NZ` keeps one Australian and one New Zealand photo, so `/geo AU` answers at once. Searched before topping up `GEO_BUFFER` (a region whose search fails is tried again after a backoff, and the buffer fills meanwhile), never dropped to make room or used by a `/geo` another photo can serve, and refilled once used | -| `GEO_WAIT` | `50s` | How long `/geo` waits for a photo when none is ready, 5s to 110s, before saying to try again; the search carries on either way. Keep the `geo` chat command's `timeout` above it | -| `GEO_NOMINATIM_URL` | `https://nominatim.openstreetmap.org` | Reverse geocoder for the place names; `https://` only, as it is sent each round's answer | -| `GEO_PANORAMAX_URL` | `https://api.panoramax.xyz` | Panoramax API (a STAC catalogue), such as one instance's; `https://` only | -| `GEO_MAPILLARY_URL` | `https://graph.mapillary.com` | Mapillary Graph API; `https://` only | - -It reaches `graph.mapillary.com` and Mapillary's image CDN, `api.panoramax.xyz` -and the Panoramax instances' image hosts, and the Nominatim server, over -TLS 1.3. - -## Privacy - -GeoGuess gets only what signalbot's addon block allows: the text after -`/geo`, and during a round the messages that look like a location (a map link -or coordinates), each with the chat and sender as pseudonyms and the time the -bot got it. It never sees a phone number, account ID, group ID or, unless -`names` is set, a display name; it writes players as `{u_…}` and the bot puts -their names in. Guesses are claimed by the bot, so they are never answered, -sent to the model or kept in the chat's history. - -What it sends out is about photos, never about players: map areas to search -and photo IDs to Mapillary and Panoramax, and the answer's coordinates to -Nominatim for the place's name, each with the user agent -`geoguess (+https://github.com/robdevops/signalbot)`. - -A guess deleted for everyone afterwards is not passed on to GeoGuess, which -keeps only its distance anyway. - -### What it keeps - -`$GEO_STATE_DIR/geo.json`, rewritten whole on each change: - -- open rounds: the chat's pseudonym, who started it, its deadline, the answer - and its credit, and for each player (a per-chat pseudonym) only how far - their last guess was and when. Where anyone guessed is never kept, in - memory or on disk; -- the keys of the last 1,000 photos used, so none comes round again soon; -- 7 days of points per chat, by player pseudonym; -- outbox ops the bot hasn't read yet, for at most an hour. - -`$GEO_STATE_DIR/geoguess.log` (moved to `geoguess.log.1` past 4 MiB at start) -records rounds started and revealed with their guess counts, photos -rejected by reason, and API errors by status. It never holds a guess, a -coordinate, a place or person's name, a pseudonym or message text. - -## The protocol - -- `initialize` advertises `tools`, `resources.subscribe` and - `experimental["io.github.robdevops.signalbot/addon"] = {"version": 1}`. - It reads the `network` the bot offers under the same key, and the round's - caption gives the steps for that network only (Signal's **+** button, or - Telegram's 📎); with none, it gives both. -- `tools/list` has `geo` (`{args}`) and `geo_guess` (`{text}`), both with - `_meta["io.github.robdevops.signalbot/visibility"] = ["bot"]`, so neither is - offered to the model. -- `tools/call` reads the chat, the sender, the receive times and the - `deadline` from `_meta["io.github.robdevops.signalbot/context"]`. A call - the bot cancels (`notifications/cancelled`) stops. Starting a round answers - with the photo, its caption and a `…/watch` for `geo_guess`, until 5s past - the deadline; a recorded guess answers with `…/react: "📍"`. -- When a round's time is up GeoGuess queues a `post` with the results, its - players as `{u_…}` placeholders, and an `unwatch`, and sends - `notifications/resources/updated` for `signalbot://outbox` if subscribed. - `/geo end` and `/geo skip` answer with the results themselves and queue - only the `unwatch`. -- `resources/read` of `signalbot://outbox/<cursor>` returns - `{"cursor", "more", "ops"}`. A cursor is `<boot-nonce>.<seq>`; reading one of - this run lets go of the ops up to it, and any other cursor, such as `0` or - one from before a restart, gets everything still held. Op IDs survive a - restart, so the bot can skip those it already applied. -- On start, rounds still open get their timers back, and those whose time - passed while GeoGuess was down are revealed at once. diff --git a/cmd/geoguess/clock.go b/cmd/geoguess/clock.go deleted file mode 100644 index b6a9b3d..0000000 --- a/cmd/geoguess/clock.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import "time" - -// clock is the time and timers the game runs on: the real ones, or a test's. -type clock interface { - Now() time.Time - // AfterFunc calls f on its own goroutine once d has passed. - AfterFunc(d time.Duration, f func()) stopper -} - -// stopper is a timer that can be stopped before it fires. -type stopper interface{ Stop() bool } - -// realClock is the system's clock. -type realClock struct{} - -func (realClock) Now() time.Time { return time.Now() } -func (realClock) AfterFunc(d time.Duration, f func()) stopper { return time.AfterFunc(d, f) } diff --git a/cmd/geoguess/config.go b/cmd/geoguess/config.go deleted file mode 100644 index 2ab4cfb..0000000 --- a/cmd/geoguess/config.go +++ /dev/null @@ -1,173 +0,0 @@ -package main - -import ( - "cmp" - "errors" - "fmt" - "math" - "os" - "strconv" - "strings" - "time" - - "github.com/robdevops/signalbot/cmd/geoguess/geo" -) - -// config is GeoGuess's settings, every one from a GEO_ variable, the only -// ones signalbot passes an addon called geo. -type config struct { - StateDir string // GEO_STATE_DIR: where geo.json and the log are kept - Token string // GEO_MAPILLARY_TOKEN: empty is Panoramax only - MemLimit int64 // GEO_MEMLIMIT, in bytes - Round time.Duration // GEO_ROUND: a round's default length - Regions string // GEO_REGIONS: continents or country codes; empty is the world - MinQuality float64 // GEO_MIN_QUALITY: the least Mapillary quality_score - MaxAge time.Duration // GEO_MAX_AGE_YEARS, as a duration - Buffer int // GEO_BUFFER: checked photos kept ready - Keep []string // GEO_KEEP: regions always kept with a photo ready, one each - Wait time.Duration // GEO_WAIT: how long /geo waits for a photo when none is ready - Nominatim string // GEO_NOMINATIM_URL - Panoramax string // GEO_PANORAMAX_URL - Mapillary string // GEO_MAPILLARY_URL -} - -// The shortest and longest round, and the defaults of the settings. -const ( - minRound = 30 * time.Second - maxRound = 30 * time.Minute - defaultRound = 3 * time.Minute - defaultMemLimit = "200MiB" - minWait = 5 * time.Second - maxWait = 110 * time.Second // under the 2m a direct command may take, with time to reply - defaultWait = 50 * time.Second -) - -// year is a year as GEO_MAX_AGE_YEARS counts it. -const year = 365*24*time.Hour + 6*time.Hour - -// loadConfig reads the settings through getenv (os.Getenv), failing with a -// message that names the setting. -func loadConfig(getenv func(string) string) (config, error) { - c := config{ - StateDir: strings.TrimSpace(getenv("GEO_STATE_DIR")), - Token: strings.TrimSpace(getenv("GEO_MAPILLARY_TOKEN")), - Regions: strings.TrimSpace(getenv("GEO_REGIONS")), - Nominatim: cmp.Or(strings.TrimSpace(getenv("GEO_NOMINATIM_URL")), geo.NominatimURL), - Panoramax: cmp.Or(strings.TrimSpace(getenv("GEO_PANORAMAX_URL")), geo.PanoramaxURL), - Mapillary: cmp.Or(strings.TrimSpace(getenv("GEO_MAPILLARY_URL")), geo.MapillaryURL), - } - var errs []error - if c.StateDir == "" { - errs = append(errs, errors.New("GEO_STATE_DIR is not set: set it to a directory GeoGuess can write, and create it")) - } - var err error - if c.MemLimit, err = parseSize(cmp.Or(strings.TrimSpace(getenv("GEO_MEMLIMIT")), defaultMemLimit)); err != nil { - errs = append(errs, fmt.Errorf("GEO_MEMLIMIT: %v", err)) - } - c.Round = defaultRound - if v := strings.TrimSpace(getenv("GEO_ROUND")); v != "" { - if c.Round, err = roundLength(v); err != nil { - errs = append(errs, fmt.Errorf("GEO_ROUND: %v", err)) - } - } - if _, err := geo.LoadSeeds(c.Regions); err != nil { - errs = append(errs, fmt.Errorf("GEO_REGIONS: %v", err)) - } - c.MinQuality = 0.5 - if v := strings.TrimSpace(getenv("GEO_MIN_QUALITY")); v != "" { - if c.MinQuality, err = strconv.ParseFloat(v, 64); err != nil || c.MinQuality < 0 || c.MinQuality > 1 { - errs = append(errs, fmt.Errorf("GEO_MIN_QUALITY is %q: use a number from 0 to 1", v)) - } - } - years := 10.0 - if v := strings.TrimSpace(getenv("GEO_MAX_AGE_YEARS")); v != "" { - if years, err = strconv.ParseFloat(v, 64); err != nil || years <= 0 || years > 100 { - errs = append(errs, fmt.Errorf("GEO_MAX_AGE_YEARS is %q: use a number of years above 0", v)) - } - } - c.MaxAge = time.Duration(years * float64(year)) - c.Buffer = 3 - if v := strings.TrimSpace(getenv("GEO_BUFFER")); v != "" { - if c.Buffer, err = strconv.Atoi(v); err != nil || c.Buffer < 1 || c.Buffer > 20 { - errs = append(errs, fmt.Errorf("GEO_BUFFER is %q: use a whole number from 1 to 20", v)) - } - } - for _, region := range strings.Split(getenv("GEO_KEEP"), ",") { - region = strings.TrimSpace(region) - if region == "" { - continue - } - if _, err := geo.LoadSeeds(region); err != nil { - errs = append(errs, fmt.Errorf("GEO_KEEP: %v", err)) - continue - } - c.Keep = append(c.Keep, region) - } - c.Wait = defaultWait - if v := strings.TrimSpace(getenv("GEO_WAIT")); v != "" { - if c.Wait, err = time.ParseDuration(v); err != nil || c.Wait < minWait || c.Wait > maxWait { - errs = append(errs, fmt.Errorf("GEO_WAIT is %q: use 5s to 110s, such as 50s", v)) - } - } - // Over TLS only: the geocoder is sent each round's answer. - for _, u := range []struct{ name, url string }{ - {"GEO_NOMINATIM_URL", c.Nominatim}, {"GEO_PANORAMAX_URL", c.Panoramax}, {"GEO_MAPILLARY_URL", c.Mapillary}, - } { - if !strings.HasPrefix(u.url, "https://") { - errs = append(errs, fmt.Errorf("%s must start with https://", u.name)) - } - } - return c, errors.Join(errs...) -} - -// roundLength reads a round's length, such as 90s or 5m, from 30s to 30m. -func roundLength(s string) (time.Duration, error) { - d, err := time.ParseDuration(s) - if err != nil || d < minRound || d > maxRound { - return 0, fmt.Errorf("%q isn't a round length: use 30s to 30m, such as 90s or 5m", s) - } - return d, nil -} - -// sizeUnits are the suffixes parseSize takes, as GOMEMLIMIT does. -var sizeUnits = []struct { - suffix string - mult int64 -}{{"TiB", 1 << 40}, {"GiB", 1 << 30}, {"MiB", 1 << 20}, {"KiB", 1 << 10}, {"B", 1}} - -// parseSize reads a number of bytes written as GOMEMLIMIT is, such as -// 200MiB or 1GiB. -func parseSize(s string) (int64, error) { - mult := int64(1) - num := s - for _, u := range sizeUnits { - if n, ok := strings.CutSuffix(s, u.suffix); ok { - num, mult = n, u.mult - break - } - } - n, err := strconv.ParseFloat(strings.TrimSpace(num), 64) - if err != nil || n < 0 || n*float64(mult) >= math.MaxInt64 { - return 0, fmt.Errorf("%q isn't a size: use a number of bytes with B, KiB, MiB or GiB, such as 200MiB", s) - } - if n*float64(mult) < 16<<20 { - return 0, fmt.Errorf("%q is too small: GeoGuess needs at least 16MiB", s) - } - return int64(n * float64(mult)), nil -} - -// checkDir fails unless dir can be listed and written, leaving nothing. -func checkDir(dir string) error { - if _, err := os.ReadDir(dir); err != nil { - return fmt.Errorf("GEO_STATE_DIR %s can't be read (%v): create it, writable by the bot's user", dir, err) - } - f, err := os.CreateTemp(dir, ".check-*") - if err == nil { - f.Close() - err = os.Remove(f.Name()) - } - if err != nil { - return fmt.Errorf("GEO_STATE_DIR %s can't be written (%v): make it writable by the bot's user", dir, err) - } - return nil -} diff --git a/cmd/geoguess/game.go b/cmd/geoguess/game.go deleted file mode 100644 index 4681fc9..0000000 --- a/cmd/geoguess/game.go +++ /dev/null @@ -1,421 +0,0 @@ -package main - -import ( - "cmp" - "context" - "encoding/base64" - "fmt" - "slices" - "strconv" - "strings" - "time" - - "github.com/robdevops/signalbot/cmd/geoguess/geo" -) - -// The texts players see. -const ( - guard = "No hints during a round 😉" - noChat = "GeoGuess works only in a chat." - noRound = "There's no round on. Start one with /geo." - noPhoto = "I couldn't find a good spot in time; I'm still looking, so try /geo again in a minute." - badLength = "A round can be 30s to 30m, such as /geo 90s or /geo 5m." - usage = "Try /geo, /geo 90s, /geo end, /geo skip, /geo scores, or a region such as /geo europe or /geo AU,NZ." -) - -// pin is the reaction to a recorded guess. -const pin = "📍" - -// replyTime is what /geo leaves before the bot's deadline to start the -// round and send the photo, so it never starts one the bot won't show. -const replyTime = 3 * time.Second - -// call runs one tool. Only an unknown tool is a protocol error; the rest -// answer in words. -func (s *server) call(ctx context.Context, p callParams) (any, error) { - switch p.Name { - case "geo": - var a struct { - Args string `json:"args"` - } - if err := params(p.Arguments, &a); err != nil { - return nil, err - } - return s.command(ctx, p.Meta.Context, a.Args), nil - case "geo_guess": - var a struct { - Text string `json:"text"` - } - if err := params(p.Arguments, &a); err != nil { - return nil, err - } - return s.guess(p.Meta.Context, a.Text), nil - } - return nil, &rpcError{codeInvalidParams, "unknown tool"} -} - -// text is a tool result of words alone. -func text(s string) toolResult { return toolResult{Content: []content{{Type: "text", Text: s}}} } - -// fromChat reports whether c names a chat and a sender. -func fromChat(c *callContext) bool { - return c != nil && validID(c.Chat, "c_") && validID(c.Sender, "u_") -} - -// command is /geo with its arguments. -func (s *server) command(ctx context.Context, c *callContext, args string) toolResult { - if !fromChat(c) { - return toolResult{Content: text(noChat).Content, IsError: true} - } - fields := strings.Fields(args) - if len(fields) == 1 { - switch strings.ToLower(fields[0]) { - case "end": - return s.finish(c, false) - case "skip": - return s.finish(c, true) - case "scores": - return text(s.scoreboard(c.Chat)) - } - } - length := s.cfg.Round - var regions []string - for _, f := range fields { - if f[0] >= '0' && f[0] <= '9' { - d, err := roundLength(strings.ToLower(f)) - if err != nil { - return text(badLength) - } - length = d - continue - } - regions = append(regions, f) - } - region := strings.Join(regions, ",") - if region != "" { - if _, err := s.regionSeeds(region); err != nil { - return text("I don't know that region. " + usage) - } - } - return s.start(ctx, c, length, region) -} - -// busy is the answer to /geo while a round is on. -func busy(r *round, now time.Time) toolResult { - left := max(r.Deadline.Sub(now), 0).Round(time.Second) - m, sec := int(left/time.Minute), int(left%time.Minute/time.Second) - var label string - switch { - case m == 0: - label = fmt.Sprintf("%ds", sec) - case sec == 0: - label = fmt.Sprintf("%dm", m) - default: - label = fmt.Sprintf("%dm%ds", m, sec) - } - return text("A round is on: " + label + " left.") -} - -// start begins a round in c's chat with a photo from the buffer, and -// answers with the photo, its caption and the watch for guesses. -func (s *server) start(ctx context.Context, c *callContext, length time.Duration, region string) toolResult { - s.mu.Lock() - r := s.rounds[c.Chat] - s.mu.Unlock() - if r != nil { - return busy(r, s.clock.Now()) - } - wait := s.cfg.Wait - if c.Deadline != 0 { // leave the bot time to send the photo - wait = min(wait, time.Until(time.Unix(c.Deadline, 0))-replyTime) - } - photo, ok := s.take(ctx, region, wait) - if !ok { - return text(noPhoto) - } - s.mu.Lock() - now := s.clock.Now() - r = s.rounds[c.Chat] - if r != nil || ctx.Err() != nil { // another /geo began one meanwhile, or the bot gave up - s.buffer = append([]geo.Photo{photo}, s.buffer...) - close(s.changed) // for a /geo waiting in another chat - s.changed = make(chan struct{}) - s.mu.Unlock() - if r == nil { - return text(noPhoto) - } - return busy(r, now) - } - r = &round{ - ID: "r" + randomID(6), Chat: c.Chat, Starter: c.Sender, - Started: now, Deadline: now.Add(length), - Answer: photo.At, Place: photo.Place.Name, - Credit: credit{Creator: photo.Creator, Source: photo.Source, Licence: photo.Licence, Link: photo.Link}, - Guesses: map[string]guess{}, - } - s.rounds[c.Chat] = r - s.arm(r) - network := s.network - s.mu.Unlock() - s.save() - s.log.Printf("round %s started: %s, a %s photo", r.ID, length, photo.Source) - return toolResult{ - Content: []content{ - {Type: "image", Data: base64.StdEncoding.EncodeToString(photo.JPEG), MimeType: "image/jpeg"}, - {Type: "text", Text: caption(r.Deadline, length, network)}, - }, - Meta: &resultMeta{Watch: &watch{ - ID: r.ID, Pattern: geo.Pattern, Until: r.Deadline.Add(watchSlack).Format(time.RFC3339), - Tool: "geo_guess", Guard: guard, - }}, - } -} - -// caption is the photo's caption: how to guess, on the chat network the -// bot said it is on, and by when. -func caption(deadline time.Time, length time.Duration, network string) string { - steps := "Signal: **+** → Location; Telegram: 📎 → Location. Pinch to zoom out, **drag the pin**, confirm (on Signal), then send." - switch network { - case "signal": - steps = "Tap **+** → Location, pinch to zoom out, **drag the pin**, confirm, then send." - case "telegram": - steps = "Tap 📎 → Location, pinch to zoom out, **drag the pin**, then send." - } - return "🌍 **Where is this?** Send a location before " + deadline.Local().Format("15:04") + " (" + lengthLabel(length) + ").\n" + - steps + " Or type coordinates, e.g. `-37.81, 144.96`.\n" + - "⚠️ Location starts at *your* position. Move the pin before you send." -} - -// lengthLabel is a round's length as the caption says it: 3 min, 90 sec. -func lengthLabel(d time.Duration) string { - if d%time.Minute == 0 { - return strconv.Itoa(int(d/time.Minute)) + " min" - } - return strconv.Itoa(int(d.Round(time.Second)/time.Second)) + " sec" -} - -// arm sets r's timer to reveal it once its time is up. s.mu is held. -func (s *server) arm(r *round) { - chat, id := r.Chat, r.ID - s.timers[chat] = s.clock.AfterFunc(r.Deadline.Add(settle).Sub(s.clock.Now()), func() { s.timeUp(chat, id) }) -} - -// timeUp reveals the round id in chat, if it is still on. -func (s *server) timeUp(chat, id string) { - s.mu.Lock() - r := s.rounds[chat] - if r == nil || r.ID != id { - s.mu.Unlock() - return - } - s.timeUpLocked(r) - s.mu.Unlock() - s.poke() - s.save() -} - -// timeUpLocked ends r and queues its results and the end of its watch for -// the bot to post. s.mu is held. -func (s *server) timeUpLocked(r *round) { - results := s.end(r, true) - s.queue(op{Op: "post", Chat: r.Chat, Text: results}) - s.queue(op{Op: "unwatch", Chat: r.Chat, Watch: r.ID}) -} - -// finish is /geo end (skip false) or /geo skip, which only the player who -// started the round may use. It answers with the results, and queues the -// end of the round's watch. -func (s *server) finish(c *callContext, skip bool) toolResult { - s.mu.Lock() - r := s.rounds[c.Chat] - switch { - case r == nil: - s.mu.Unlock() - return text(noRound) - case r.Starter != c.Sender && skip: - s.mu.Unlock() - return text("Only the player who started this round can skip it.") - case r.Starter != c.Sender: - s.mu.Unlock() - return text("Only the player who started this round can end it.") - } - results := s.end(r, !skip) - s.queue(op{Op: "unwatch", Chat: r.Chat, Watch: r.ID}) - s.mu.Unlock() - s.poke() - s.save() - return text(results) -} - -// end closes r, adding its points to the chat's scores if scored, and -// returns its results. s.mu is held. -func (s *server) end(r *round, scored bool) string { - delete(s.rounds, r.Chat) - if t := s.timers[r.Chat]; t != nil { - t.Stop() - delete(s.timers, r.Chat) - } - guesses := make([]geo.Guess, 0, len(r.Guesses)) - for user, g := range r.Guesses { - guesses = append(guesses, geo.Guess{User: user, Km: g.Km, At: g.At}) - } - placings := geo.Rank(guesses) - how := "revealed" - if scored { - now := s.clock.Now() - s.pruneScores(now) - for _, p := range placings { - s.scores[r.Chat] = append(s.scores[r.Chat], score{User: p.User, Points: p.Points, At: now}) - } - } else { - how = "skipped" - } - s.log.Printf("round %s %s: %d guesses", r.ID, how, len(placings)) - return results(r, placings, scored) -} - -// results is a round's reveal: the place, then each player's distance and -// points, never where they guessed, then the photo's credit. Players are -// {u_…} placeholders, which the bot turns into names. -func results(r *round, placings []geo.Placing, scored bool) string { - place := "📍 [**" + plain(r.Place) + "**](" + mapLink(r.Answer) + ")" - var b strings.Builder - switch { - case !scored: - b.WriteString("Round skipped. It was " + place) - case len(placings) == 0: - b.WriteString("Nobody guessed. It was " + place) - default: - b.WriteString(place) - for _, p := range placings { - b.WriteString("\n" + medal(p.Rank) + " {" + p.User + "} " + geo.Distance(p.Km) + " · " + geo.Thousands(p.Points)) - } - } - b.WriteString("\n" + r.Credit.String()) - return b.String() -} - -// String is the credit line: "Photo: jsmith, Mapillary, CC BY-SA 4.0", -// linked to the photo's page. -func (c credit) String() string { - var parts []string - for _, p := range []string{plain(c.Creator), c.Source, c.Licence} { - if p != "" { - parts = append(parts, p) - } - } - line := strings.Join(parts, ", ") - if strings.HasPrefix(c.Link, "https://") && !strings.ContainsAny(c.Link, " ()") { - line = "[" + line + "](" + c.Link + ")" - } - return "Photo: " + line -} - -// plain is s without the characters Markdown would read, so a photo's -// author can't style or link the results. -func plain(s string) string { - return strings.Join(strings.Fields(strings.Map(func(r rune) rune { - if strings.ContainsRune("[]()*_`~\\<>|#", r) { - return -1 - } - return r - }, s)), " ") -} - -// mapLink is a map of the answer on OpenStreetMap. -func mapLink(p geo.Point) string { - lat, lon := strconv.FormatFloat(p.Lat, 'f', 5, 64), strconv.FormatFloat(p.Lon, 'f', 5, 64) - return "https://www.openstreetmap.org/?mlat=" + lat + "&mlon=" + lon + "#map=12/" + lat + "/" + lon -} - -// medal marks a rank: a medal for the first three, else the number. -func medal(rank int) string { - if rank <= 3 { - return []string{"🥇", "🥈", "🥉"}[rank-1] - } - return strconv.Itoa(rank) + "." -} - -// guess records the location in a chat message as its sender's guess in -// the chat's round: only how far it is from the answer, never where it is. -// A recorded guess answers with a pin for the bot to react with. -func (s *server) guess(c *callContext, msg string) toolResult { - if !fromChat(c) { - return text(noChat) - } - p, ok := geo.Parse(msg) - if !ok { - return text("No location found.") - } - at := s.clock.Now() - if t := cmp.Or(c.Edited, c.Sent); t > 0 { - at = time.Unix(t, 0) - } - s.mu.Lock() - r := s.rounds[c.Chat] - switch { - case r == nil: - s.mu.Unlock() - return text(noRound) - case c.Sent > 0 && c.Sent < r.Started.Unix(): - s.mu.Unlock() - return text("That message is from before this round.") - case at.After(r.Deadline): - s.mu.Unlock() - return text("Too late for this round.") - } - r.Guesses[c.Sender] = guess{Km: geo.Km(p, r.Answer), At: at} - s.mu.Unlock() - s.save() - return toolResult{Content: text("Recorded.").Content, Meta: &resultMeta{React: pin}} -} - -// scoreboard is /geo scores: the chat's totals over the last scoreDays. -func (s *server) scoreboard(chat string) string { - s.mu.Lock() - s.pruneScores(s.clock.Now()) - type total struct { - user string - points, rounds int - } - byUser := map[string]*total{} - var totals []*total - for _, sc := range s.scores[chat] { - t := byUser[sc.User] - if t == nil { - t = &total{user: sc.User} - byUser[sc.User] = t - totals = append(totals, t) - } - t.points += sc.Points - t.rounds++ - } - s.mu.Unlock() - if len(totals) == 0 { - return "No scores in the last 7 days. Start a round with /geo." - } - // Scores are kept in the order they were won, so a tie goes to who - // scored first. - slices.SortStableFunc(totals, func(a, b *total) int { return cmp.Compare(b.points, a.points) }) - var b strings.Builder - b.WriteString("🏆 **Scores, last 7 days**") - for i, t := range totals[:min(len(totals), 10)] { - rounds := "1 round" - if t.rounds != 1 { - rounds = strconv.Itoa(t.rounds) + " rounds" - } - fmt.Fprintf(&b, "\n%s {%s} %s · %s", medal(i+1), t.user, geo.Thousands(t.points), rounds) - } - return b.String() -} - -// pruneScores forgets scores older than scoreDays. s.mu is held. -func (s *server) pruneScores(now time.Time) { - since := now.Add(-scoreDays * 24 * time.Hour) - for chat, list := range s.scores { - s.scores[chat] = slices.DeleteFunc(list, func(sc score) bool { return sc.At.Before(since) }) - if len(s.scores[chat]) == 0 { - delete(s.scores, chat) - } - } -} diff --git a/cmd/geoguess/geo/find.go b/cmd/geoguess/geo/find.go deleted file mode 100644 index 466ecd8..0000000 --- a/cmd/geoguess/geo/find.go +++ /dev/null @@ -1,113 +0,0 @@ -package geo - -import ( - "context" - "errors" - "math/rand/v2" - "time" -) - -// Photo is a photo that passed every check, with its place named: ready for -// a round. -type Photo struct { - Candidate - Place Place - JPEG []byte -} - -// Finder looks for a photo worth a round: it picks a seed region, searches -// random boxes in it, and checks what it finds, cheapest checks first. -type Finder struct { - Sources []Source // tried in order for each box - Seeds *Seeds - Rules Rules - Places *Nominatim - Rand *rand.Rand - Now func() time.Time - - // Used reports whether a candidate's Key was used recently; nil is none. - Used func(key string) bool - // Rejected, if set, is told why each candidate was turned down. - Rejected func(source string, why Reject) - // Failed, if set, is told of each failed search or download, whose - // error holds no URL. - Failed func(err error) -} - -// The search's limits: boxes tried in a seed, seeds tried in one Find, and -// photos downloaded from one box. -const ( - boxesPerSeed = 4 - seedsPerFind = 8 - fetchesPerBox = 3 -) - -// ErrNotFound is a Find that tried its seeds and found nothing. -var ErrNotFound = errors.New("no photo found") - -// Find is a photo that passed every check. It gives up with ErrNotFound -// after seedsPerFind seeds, at once with ErrSlowDown if a source asks it to, -// or when ctx ends. -func (f *Finder) Find(ctx context.Context) (Photo, error) { - for range seedsPerFind { - seed := f.Seeds.Pick(f.Rand) - for range boxesPerSeed { - box := Around(seed.Point(f.Rand)) - for _, src := range f.Sources { - p, err := f.search(ctx, src, box) - if err == nil || errors.Is(err, ErrSlowDown) || ctx.Err() != nil { - return p, err - } - } - } - } - return Photo{}, ErrNotFound -} - -// search looks in one box of one source. -func (f *Finder) search(ctx context.Context, src Source, box BBox) (Photo, error) { - cands, err := src.Candidates(ctx, box) - if err != nil { - if !errors.Is(err, ErrSlowDown) && ctx.Err() == nil && f.Failed != nil { - f.Failed(err) - } - return Photo{}, err - } - reject := func(why Reject) { - if f.Rejected != nil { - f.Rejected(src.Name(), why) - } - } - kept := f.Rules.Filter(cands, f.Now(), f.Used, reject) - f.Rand.Shuffle(len(kept), func(i, j int) { kept[i], kept[j] = kept[j], kept[i] }) - for _, c := range kept[:min(len(kept), fetchesPerBox)] { - data, err := src.Fetch(ctx, c) - if err != nil { - if ctx.Err() != nil { - return Photo{}, ctx.Err() - } - if f.Failed != nil { - f.Failed(err) - } - continue - } - jpeg, err := Vet(data, c.Pano, f.Rand) - if err != nil { - reject(err.(Reject)) - continue - } - place, err := f.Places.Reverse(ctx, c.At) - if err != nil { - if why, ok := err.(Reject); ok { - reject(why) - } else if ctx.Err() != nil { - return Photo{}, ctx.Err() - } else if f.Failed != nil { - f.Failed(err) - } - continue - } - return Photo{Candidate: c, Place: place, JPEG: jpeg}, nil - } - return Photo{}, ErrNotFound -} diff --git a/cmd/geoguess/geo/find_test.go b/cmd/geoguess/geo/find_test.go deleted file mode 100644 index 1bbb8df..0000000 --- a/cmd/geoguess/geo/find_test.go +++ /dev/null @@ -1,178 +0,0 @@ -package geo - -import ( - "context" - "errors" - "math/rand/v2" - "net/http" - "slices" - "testing" - "time" -) - -// fakeSource offers the same candidates in every box, or with once only in -// the first, with photos by ID. -type fakeSource struct { - cands []Candidate - once bool - photos map[string][]byte - err error - boxes []BBox - fetched []string -} - -func (f *fakeSource) Name() string { return "Fake" } - -func (f *fakeSource) Candidates(ctx context.Context, b BBox) ([]Candidate, error) { - f.boxes = append(f.boxes, b) - if f.once && len(f.boxes) > 1 { - return nil, f.err - } - return f.cands, f.err -} - -func (f *fakeSource) Fetch(ctx context.Context, c Candidate) ([]byte, error) { - f.fetched = append(f.fetched, c.ID) - if p, ok := f.photos[c.ID]; ok { - return p, nil - } - return nil, StatusError{Source: "Fake", Code: 404} -} - -func newTestFinder(t *testing.T, country string, sources ...Source) (*Finder, *[]Reject, *[]error) { - api := newFakeAPI(t) - api.handle = func(w http.ResponseWriter, r *http.Request) { - if country == "" { - w.Write([]byte(`{"error":"Unable to geocode"}`)) - return - } - w.Write([]byte(`{"address":{"town":"Ballarat","state":"Victoria","country":"` + country + `","country_code":"au"}}`)) - } - places := NewNominatim(api.URL, api.Client()) - places.pace.every = 0 - seeds, err := LoadSeeds("AU") - if err != nil { - t.Fatal(err) - } - var rejects []Reject - var fails []error - f := &Finder{ - Sources: sources, Seeds: seeds, Places: places, - Rules: Rules{MinQuality: 0.5, MaxAge: 10 * 365 * 24 * time.Hour}, - Rand: rand.New(rand.NewPCG(1, 2)), - Now: func() time.Time { return time.Date(2026, 11, 20, 0, 0, 0, 0, time.UTC) }, - Used: func(key string) bool { return key == "Fake:used" }, - Rejected: func(source string, why Reject) { - if source != "Fake" { - t.Errorf("rejected by %q", source) - } - rejects = append(rejects, why) - }, - Failed: func(err error) { fails = append(fails, err) }, - } - return f, &rejects, &fails -} - -func TestFind(t *testing.T) { - t.Parallel() - noon := time.Date(2024, 12, 21, 2, 19, 0, 0, time.UTC) // in Victoria - at := Point{-37.56, 143.85} - c := func(id string) Candidate { - return Candidate{ID: id, Source: "Fake", Sequence: id, At: at, Raw: at, Captured: noon, Quality: 0.9} - } - r := rand.New(rand.NewPCG(3, 3)) - good := jpegOf(t, scene(1024, 768, r)) - foggy := jpegOf(t, testPhotos(1024, 768)[3].m) - night := c("night") - night.Captured = noon.Add(12 * time.Hour) - src := &fakeSource{ - cands: []Candidate{c("used"), night, c("foggy"), c("good")}, - photos: map[string][]byte{"foggy": foggy, "good": good}, - } - f, rejects, _ := newTestFinder(t, "Australia", src) - // The candidates kept are tried in a random order: search until the - // foggy one is tried before the good one. - for range 10 { - *rejects = nil - src.fetched = nil - p, err := f.Find(context.Background()) - if err != nil { - t.Fatal(err) - } - if p.ID != "good" || p.Place.Name != "Ballarat, Victoria, Australia" || len(p.JPEG) == 0 { - t.Fatalf("found %+v", p.Candidate) - } - if !slices.Contains(*rejects, RejectUsed) || !slices.Contains(*rejects, RejectDark) { - t.Errorf("rejected for %v", *rejects) - } - if slices.Contains(src.fetched, "foggy") { - if !slices.Contains(*rejects, RejectContrast) { - t.Errorf("fog rejected for %v", *rejects) - } - return - } - } - t.Error("the foggy photo was never tried") -} - -func TestFindBoxes(t *testing.T) { - src := &fakeSource{} - f, _, _ := newTestFinder(t, "Australia", src) - if _, err := f.Find(context.Background()); err != ErrNotFound { - t.Errorf("empty: %v", err) - } - if len(src.boxes) != seedsPerFind*boxesPerSeed { - t.Errorf("%d boxes searched", len(src.boxes)) - } - for _, b := range src.boxes { - c := b.Centre() - if c.Lat > -10 || c.Lat < -44 || c.Lon < 113 || c.Lon > 154 { - t.Errorf("searched outside Australia: %v", c) - } - } -} - -func TestFindErrors(t *testing.T) { - noon := time.Date(2024, 12, 21, 2, 19, 0, 0, time.UTC) - at := Point{-37.56, 143.85} - good := Candidate{ID: "good", Source: "Fake", At: at, Raw: at, Captured: noon, Quality: -1} - photo := jpegOf(t, scene(1024, 768, rand.New(rand.NewPCG(4, 4)))) - - // A failing source falls through to the next. - broken := &fakeSource{err: StatusError{Source: "Fake", Code: 500}} - working := &fakeSource{cands: []Candidate{good}, photos: map[string][]byte{"good": photo}} - f, _, fails := newTestFinder(t, "Australia", broken, working) - if p, err := f.Find(context.Background()); err != nil || p.ID != "good" { - t.Errorf("fallback: %+v, %v", p.Candidate, err) - } - if len(*fails) != 1 || (*fails)[0] != (StatusError{Source: "Fake", Code: 500}) { - t.Errorf("failures %v", *fails) - } - - // A source that asks to slow down stops the search. - slow := &fakeSource{err: ErrSlowDown} - f, _, _ = newTestFinder(t, "Australia", slow, working) - if _, err := f.Find(context.Background()); !errors.Is(err, ErrSlowDown) || len(slow.boxes) != 1 || len(working.boxes) != 1 { - t.Errorf("slow down: %v after %d boxes", err, len(slow.boxes)) - } - - // A photo with no country is dropped. - f, rejects, _ := newTestFinder(t, "", &fakeSource{cands: []Candidate{good}, photos: map[string][]byte{"good": photo}, once: true}) - if _, err := f.Find(context.Background()); err != ErrNotFound || !slices.Contains(*rejects, RejectNoPlace) { - t.Errorf("no country: %v, %v", err, *rejects) - } - - // A download that fails is reported, and the search goes on. - f, _, fails = newTestFinder(t, "Australia", &fakeSource{cands: []Candidate{good}}) - if _, err := f.Find(context.Background()); err != ErrNotFound || len(*fails) != seedsPerFind*boxesPerSeed { - t.Errorf("failed downloads: %v, %d reported", err, len(*fails)) - } - - // A cancelled search stops. - ctx, cancel := context.WithCancel(context.Background()) - cancel() - f, _, _ = newTestFinder(t, "Australia", &fakeSource{err: context.Canceled}) - if _, err := f.Find(ctx); !errors.Is(err, context.Canceled) { - t.Errorf("cancelled: %v", err) - } -} diff --git a/cmd/geoguess/geo/mapillary.go b/cmd/geoguess/geo/mapillary.go deleted file mode 100644 index 6759eec..0000000 --- a/cmd/geoguess/geo/mapillary.go +++ /dev/null @@ -1,177 +0,0 @@ -package geo - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "net/http" - "net/url" - "strconv" - "time" -) - -// MapillaryURL is Mapillary's Graph API. -const MapillaryURL = "https://graph.mapillary.com" - -// mapillaryFields are the fields a search asks for. -const mapillaryFields = "id,computed_geometry,geometry,captured_at,camera_type,is_pano,quality_score,width,height,sequence,creator,thumb_2048_url" - -// mapillaryLimit is the most images one search returns. -const mapillaryLimit = 100 - -// maxMapillaryAnswer caps one search's answer. -const maxMapillaryAnswer = 4 << 20 - -// Mapillary searches Mapillary's Graph API v4. Its photos are CC BY-SA 4.0. -type Mapillary struct { - url string - token string - client *http.Client -} - -// NewMapillary is a Mapillary client for the API at base (MapillaryURL), -// sending token (MLY|…) as "Authorization: OAuth <token>": Mapillary's -// answers to a Bearer token hold no data. -func NewMapillary(base, token string, client *http.Client) *Mapillary { - return &Mapillary{url: base, token: token, client: client} -} - -// Name is "Mapillary". -func (m *Mapillary) Name() string { return "Mapillary" } - -type mapillaryImage struct { - ID string `json:"id"` - ComputedGeometry *geoJSONPoint `json:"computed_geometry"` - Geometry *geoJSONPoint `json:"geometry"` - CapturedAt int64 `json:"captured_at"` // ms since the epoch, by the camera's clock - CameraType string `json:"camera_type"` - IsPano bool `json:"is_pano"` - QualityScore *float64 `json:"quality_score"` // null is unknown, not bad - Width int `json:"width"` - Height int `json:"height"` - Sequence string `json:"sequence"` - Creator struct { - Username string `json:"username"` - } `json:"creator"` - Thumb string `json:"thumb_2048_url"` -} - -type mapillaryAnswer struct { - Data []mapillaryImage `json:"data"` - Error *struct { - Code int `json:"code"` - } `json:"error"` -} - -// Candidates searches b, which must be under 0.01 deg². An empty answer is -// asked again once, since Mapillary sometimes leaves out images it has; a -// server error (Mapillary's answer to an area too dense to list) falls back -// to a radius search around b's centre. -func (m *Mapillary) Candidates(ctx context.Context, b BBox) ([]Candidate, error) { - q := url.Values{"bbox": {b.String()}, "fields": {mapillaryFields}, "limit": {strconv.Itoa(mapillaryLimit)}} - images, err := m.search(ctx, q) - if err == nil && len(images) == 0 { - images, err = m.search(ctx, q) - } - if se := (StatusError{}); errors.As(err, &se) && se.Code >= 500 { - c := b.Centre() - images, err = m.search(ctx, url.Values{ - "lat": {coord(c.Lat)}, "lng": {coord(c.Lon)}, "radius": {"50"}, - "fields": {mapillaryFields}, "limit": {strconv.Itoa(mapillaryLimit)}, - }) - } - if err != nil { - return nil, err - } - out := make([]Candidate, 0, len(images)) - for _, im := range images { - if c, ok := im.candidate(); ok { - out = append(out, c) - } - } - return out, nil -} - -// search is one call to /images. -func (m *Mapillary) search(ctx context.Context, q url.Values) ([]mapillaryImage, error) { - r := request{client: m.client, source: m.Name(), url: m.url + "/images?" + q.Encode(), auth: "OAuth " + m.token, limit: maxMapillaryAnswer} - body, err := r.get(ctx) - var a mapillaryAnswer - jerr := json.Unmarshal(body, &a) - if a.Error != nil && a.Error.Code == 4 { - return nil, ErrSlowDown // "application request limit reached" - } - if err != nil { - return nil, err - } - if jerr != nil || a.Error != nil { - return nil, fmt.Errorf("%s: unreadable answer", m.Name()) - } - return a.Data, nil -} - -// candidate is im as a Candidate, if it has an ID and a position. -func (im mapillaryImage) candidate() (Candidate, bool) { - raw, rawOK := im.Geometry.point() - at, ok := im.ComputedGeometry.point() - if !ok { - at, ok = raw, rawOK - } - if !rawOK { - raw = at - } - if im.ID == "" || !ok { - return Candidate{}, false - } - c := Candidate{ - ID: im.ID, - Source: "Mapillary", - Creator: im.Creator.Username, - Licence: "CC BY-SA 4.0", - Link: "https://www.mapillary.com/app/?pKey=" + url.QueryEscape(im.ID), - At: at, - Raw: raw, - Pano: im.IsPano || im.CameraType == "spherical" || im.CameraType == "equirectangular", - Fisheye: im.CameraType == "fisheye", - Quality: -1, - Width: im.Width, - Height: im.Height, - Sequence: im.Sequence, - image: im.Thumb, - } - if im.CapturedAt > 0 { - c.Captured = time.UnixMilli(im.CapturedAt).UTC() - } - if im.QualityScore != nil { - c.Quality = *im.QualityScore - } - return c, true -} - -// Fetch downloads c's 2048-px thumbnail. The URL a search gave is signed and -// expires, so a candidate without one, or whose URL has expired, gets a fresh -// one by ID. -func (m *Mapillary) Fetch(ctx context.Context, c Candidate) ([]byte, error) { - if c.image != "" { - data, err := request{client: m.client, source: m.Name(), url: c.image, limit: maxPhoto}.get(ctx) - if err == nil { - return data, nil - } - if se := (StatusError{}); !errors.As(err, &se) || (se.Code != http.StatusForbidden && se.Code != http.StatusNotFound && se.Code != http.StatusGone) { - return nil, err - } - } - var fresh struct { - Thumb string `json:"thumb_2048_url"` - } - q := url.Values{"fields": {"thumb_2048_url"}} - r := request{client: m.client, source: m.Name(), url: m.url + "/" + url.PathEscape(c.ID) + "?" + q.Encode(), auth: "OAuth " + m.token, limit: 64 << 10} - if err := r.getJSON(ctx, &fresh); err != nil { - return nil, err - } - if fresh.Thumb == "" { - return nil, fmt.Errorf("%s: no image", m.Name()) - } - return request{client: m.client, source: m.Name(), url: fresh.Thumb, limit: maxPhoto}.get(ctx) -} diff --git a/cmd/geoguess/geo/panoramax.go b/cmd/geoguess/geo/panoramax.go deleted file mode 100644 index 33c6d00..0000000 --- a/cmd/geoguess/geo/panoramax.go +++ /dev/null @@ -1,214 +0,0 @@ -package geo - -import ( - "context" - "fmt" - "math" - "net/http" - "net/url" - "strconv" - "strings" - "time" -) - -// PanoramaxURL is Panoramax's meta-catalogue, which lists the photos of -// every instance. -const PanoramaxURL = "https://api.panoramax.xyz" - -// panoramaxLimit is the most items one search returns. -const panoramaxLimit = 100 - -// maxPanoramaxAnswer caps one search's answer; items carry their EXIF. -const maxPanoramaxAnswer = 16 << 20 - -// Panoramax searches Panoramax's STAC API. It needs no key; it publishes no -// rate limit, so it is called at most once a second. -type Panoramax struct { - url string - client *http.Client - pace *pacer -} - -// NewPanoramax is a Panoramax client for the catalogue at base -// (PanoramaxURL). -func NewPanoramax(base string, client *http.Client) *Panoramax { - return &Panoramax{url: base, client: client, pace: &pacer{every: time.Second}} -} - -// Name is "Panoramax". -func (p *Panoramax) Name() string { return "Panoramax" } - -type panoramaxItem struct { - ID string `json:"id"` - Geometry *geoJSONPoint `json:"geometry"` - Collection string `json:"collection"` - Providers []struct { - Name string `json:"name"` - Roles []string `json:"roles"` - } `json:"providers"` - Assets map[string]struct { - Href string `json:"href"` - } `json:"assets"` - Properties struct { - Datetime string `json:"datetime"` // UTC - License string `json:"license"` // an SPDX ID - Orientation struct { - FieldOfView *float64 `json:"field_of_view"` - Dimensions []int `json:"sensor_array_dimensions"` - } `json:"pers:interior_orientation"` - Accuracy *float64 `json:"quality:horizontal_accuracy"` // m - Density *float64 `json:"panoramax:horizontal_pixel_density"` - } `json:"properties"` -} - -// Candidates searches b. -func (p *Panoramax) Candidates(ctx context.Context, b BBox) ([]Candidate, error) { - if err := p.pace.wait(ctx); err != nil { - return nil, err - } - q := url.Values{"bbox": {b.String()}, "limit": {strconv.Itoa(panoramaxLimit)}} - var a struct { - Features []panoramaxItem `json:"features"` - } - r := request{client: p.client, source: p.Name(), url: p.url + "/api/search?" + q.Encode(), limit: maxPanoramaxAnswer} - if err := r.getJSON(ctx, &a); err != nil { - if se, ok := err.(StatusError); ok && se.Code == http.StatusTooManyRequests { - return nil, ErrSlowDown - } - return nil, err - } - out := make([]Candidate, 0, len(a.Features)) - for _, it := range a.Features { - if c, ok := p.candidate(it); ok { - out = append(out, c) - } - } - return out, nil -} - -// candidate is it as a Candidate, if it has an ID, a position, a licence -// the credit can name, and an SD picture. -func (p *Panoramax) candidate(it panoramaxItem) (Candidate, bool) { - at, ok := it.Geometry.point() - licence := licenceName(it.Properties.License) - sd := it.Assets["sd"].Href - if it.ID == "" || !ok || licence == "" || sd == "" { - return Candidate{}, false - } - props := it.Properties - c := Candidate{ - ID: it.ID, - Source: "Panoramax", - Creator: producer(it), - Licence: licence, - Link: p.url + "/#focus=pic&pic=" + url.QueryEscape(it.ID), - At: at, - Raw: at, - Pano: props.Orientation.FieldOfView != nil && *props.Orientation.FieldOfView == 360, - Quality: -1, - Sequence: it.Collection, - image: sd, - } - if d := props.Orientation.Dimensions; len(d) == 2 { - c.Width, c.Height = d[0], d[1] - } - if t, err := time.Parse(time.RFC3339, props.Datetime); err == nil { - c.Captured = t.UTC() - } - c.Grade = grade(c.Pano, props.Density, props.Accuracy) - return c, true -} - -// producer is the first provider with the producer role: the author. -func producer(it panoramaxItem) string { - for _, pr := range it.Providers { - for _, role := range pr.Roles { - if role == "producer" { - return pr.Name - } - } - } - return "" -} - -// licenceName is an SPDX ID as the credit shows it: "CC-BY-SA-4.0" is -// "CC BY-SA 4.0", "etalab-2.0" is "Etalab 2.0". It is empty for a licence -// that isn't open (only Creative Commons and Etalab are). -func licenceName(spdx string) string { - parts := strings.Split(spdx, "-") - if len(parts) < 2 { - return "" - } - last := len(parts) - 1 - switch first := strings.ToLower(parts[0]); { - case first == "cc" && last >= 2: - return "CC " + strings.Join(parts[1:last], "-") + " " + parts[last] - case first == "cc0": - return "CC0 " + parts[last] - case first == "etalab" && last == 1: - return "Etalab " + parts[last] - } - return "" -} - -// grade is the A–E grade (5 to 1) that Panoramax's viewer shows, from the -// picture's horizontal pixel density and GPS accuracy: -// round(0.8 × resolution + 0.2 × GPS). Each is often missing, which is -// unknown rather than bad: the grade is then the known one's alone, or 0 if -// neither is known. -func grade(pano bool, density, accuracy *float64) int { - res := 0 - if density != nil { - d := *density - switch { - case pano && d < 15: - res = 3 - case pano && d < 30: - res = 4 - case pano: - res = 5 - case d < 10: - res = 1 - case d < 15: - res = 2 - case d < 30: - res = 3 - default: - res = 4 - } - } - gps := 0 - if accuracy != nil { - switch a := *accuracy; { - case a < 0.5: - gps = 5 - case a <= 2: - gps = 4 - case a <= 5: - gps = 3 - case a <= 10: - gps = 2 - default: - gps = 1 - } - } - switch { - case res == 0: - return gps - case gps == 0: - return res - } - return int(math.Round(0.8*float64(res) + 0.2*float64(gps))) -} - -// Fetch downloads c's SD picture, 2048 px wide, from the instance that holds -// it. -func (p *Panoramax) Fetch(ctx context.Context, c Candidate) ([]byte, error) { - if c.image == "" { - return nil, fmt.Errorf("%s: no image", p.Name()) - } - if err := p.pace.wait(ctx); err != nil { - return nil, err - } - return request{client: p.client, source: p.Name(), url: c.image, limit: maxPhoto}.get(ctx) -} diff --git a/cmd/geoguess/geo/parse.go b/cmd/geoguess/geo/parse.go deleted file mode 100644 index 3843e9f..0000000 --- a/cmd/geoguess/geo/parse.go +++ /dev/null @@ -1,223 +0,0 @@ -package geo - -import ( - "net/url" - "regexp" - "strconv" - "strings" -) - -// Pattern is the watch pattern for a round: Go RE2 that catches a message -// that may hold a location. It is specific, so ordinary chatter doesn't -// match: a map URL's host, a geo: URI, or a decimal coordinate pair. Parse -// does the real reading, and a message it can't read isn't a guess. -const Pattern = `(?i)(?:\bmaps\.google\.[a-z.]+/|\bgoogle\.[a-z.]+/maps|\bmaps\.apple\.com\b|\bgeo:[+-]?\d|\bopenstreetmap\.org/|(?:^|[^\w.])-?\d{1,3}\.\d+°?\s*,\s*-?\d{1,3}\.\d+)` - -// Parse reads the first location in text: a Google, Apple or OpenStreetMap -// map URL, a geo: URI (RFC 5870), or typed coordinates such as -// "-37.81, 144.96", each number with a decimal point. Only decimal degrees -// are read, and only a latitude in [-90, 90] with a longitude in -// [-180, 180]. Text that only looks like coordinates ("3, 4", times such as -// "12.30, 14.45", prices) isn't a location. -func Parse(text string) (Point, bool) { - text = strings.ReplaceAll(text, "−", "-") // U+2212 MINUS SIGN - for _, field := range strings.FieldsFunc(text, isFieldBreak) { - field = strings.TrimRight(field, ".,;:!?") - if p, ok := parseLink(field); ok { - return p, true - } - } - return parseTyped(text) -} - -// isFieldBreak ends a link: white space, or a bracket or quote around one. -func isFieldBreak(r rune) bool { - switch r { - case ' ', '\t', '\n', '\r', '<', '>', '(', ')', '[', ']', '"', '\'', '`': - return true - } - return false -} - -// parseLink reads a location from one map link or geo: URI. -func parseLink(s string) (Point, bool) { - if len(s) > 4 && strings.EqualFold(s[:4], "geo:") { - return parseGeoURI(s[4:]) - } - if !strings.Contains(s, "://") { - s = "https://" + s - } - u, err := url.Parse(s) - if err != nil || (u.Scheme != "http" && u.Scheme != "https") { - return Point{}, false - } - host := strings.TrimPrefix(strings.ToLower(u.Hostname()), "www.") - switch { - case isGoogle(host) && (strings.HasPrefix(host, "maps.") || strings.HasPrefix(u.Path, "/maps")): - return parseGoogle(u) - case host == "maps.apple.com": - return firstParam(u.Query(), "ll", "coordinate", "q", "sll") - case host == "openstreetmap.org": - return parseOSM(u) - } - return Point{}, false -} - -// googleHost is a Google host: google.com, google.com.au, maps.google.fr… -var googleHost = regexp.MustCompile(`^(?:maps\.)?google\.(?:[a-z]{2,3}|co|com)(?:\.[a-z]{2})?$`) - -func isGoogle(host string) bool { return googleHost.MatchString(host) } - -// googleAt is the map centre in a Google path: /maps/@-37.81,144.96,15z. -var googleAt = regexp.MustCompile(`/@([+-]?\d+(?:\.\d+)?),([+-]?\d+(?:\.\d+)?)(?:[,/]|$)`) - -// parseGoogle reads q= (what Signal sends), ll= or query=, then a place or -// search path segment that is a coordinate pair, then the @ map centre. -func parseGoogle(u *url.URL) (Point, bool) { - if p, ok := firstParam(u.Query(), "q", "ll", "query"); ok { - return p, true - } - segs := strings.Split(u.Path, "/") - for i, seg := range segs { - if (seg == "place" || seg == "search") && i+1 < len(segs) { - if v, err := url.PathUnescape(segs[i+1]); err == nil { - if p, ok := parsePair(strings.ReplaceAll(v, "+", " ")); ok { - return p, true - } - } - } - } - if m := googleAt.FindStringSubmatch(u.Path); m != nil { - return point(m[1], m[2]) - } - return Point{}, false -} - -// parseOSM reads a marker (mlat, mlon), else the map centre in the fragment -// (#map=15/-37.81/144.96). -func parseOSM(u *url.URL) (Point, bool) { - q := u.Query() - if q.Has("mlat") && q.Has("mlon") { - return point(q.Get("mlat"), q.Get("mlon")) - } - frag, err := url.ParseQuery(u.Fragment) - if err != nil { - return Point{}, false - } - parts := strings.Split(frag.Get("map"), "/") - if len(parts) != 3 { - return Point{}, false - } - return point(parts[1], parts[2]) -} - -// parseGeoURI reads what follows "geo:": lat,lon[,alt][;params][?q=…]. -// Android's geo:0,0?q=lat,lon(label) puts the place in q. -func parseGeoURI(s string) (Point, bool) { - coords, query, _ := strings.Cut(s, "?") - coords, _, _ = strings.Cut(coords, ";") - parts := strings.Split(coords, ",") - if len(parts) < 2 || len(parts) > 3 { - return Point{}, false - } - p, ok := point(parts[0], parts[1]) - if ok && (p != Point{}) { - return p, true - } - if q, err := url.ParseQuery(query); err == nil && q.Has("q") { - v, _, _ := strings.Cut(q.Get("q"), "(") - if qp, qok := parsePair(v); qok { - return qp, true - } - } - return p, ok -} - -// firstParam is the first of the named query parameters that is a -// coordinate pair. -func firstParam(q url.Values, names ...string) (Point, bool) { - for _, n := range names { - if p, ok := parsePair(q.Get(n)); ok { - return p, true - } - } - return Point{}, false -} - -// pair is a coordinate pair as a link holds it, maybe after "loc:". -var pair = regexp.MustCompile(`^\s*(?:loc:\s*)?([+-]?\d{1,3}(?:\.\d+)?)\s*,\s*([+-]?\d{1,3}(?:\.\d+)?)\s*$`) - -func parsePair(s string) (Point, bool) { - m := pair.FindStringSubmatch(s) - if m == nil { - return Point{}, false - } - return point(m[1], m[2]) -} - -// point is lat and lon as numbers, if both are in range. -func point(lat, lon string) (Point, bool) { - φ, err1 := strconv.ParseFloat(lat, 64) - λ, err2 := strconv.ParseFloat(lon, 64) - p := Point{Lat: φ, Lon: λ} - if err1 != nil || err2 != nil || !p.valid() { - return Point{}, false - } - return p, true -} - -// typed is a typed coordinate pair, each number with a decimal point, not -// part of a longer number, word, version ("v1.2.3") or link, nor next to a currency -// sign or a percent sign. A full stop may end the sentence after it. -var typed = regexp.MustCompile(`(?:^|[^\w.$€£¥=/@&?#+-])(-?\d{1,3}\.\d+)°?\s*,\s*(-?\d{1,3}\.\d+)°?(?:$|[^\w.%$€£¥]|\.(?:$|\D))`) - -// parseTyped reads the first typed coordinate pair in text that isn't a -// pair of clock times or prices. -func parseTyped(text string) (Point, bool) { - for _, m := range typed.FindAllStringSubmatchIndex(text, -1) { - lat, lon := text[m[2]:m[3]], text[m[4]:m[5]] - if (clock(lat) && clock(lon)) || money(text[:m[2]], text[m[5]:]) { - continue - } - if p, ok := point(lat, lon); ok { - return p, true - } - } - return Point{}, false -} - -// clock reports whether s reads as a time of day written with a dot, such -// as 9.30 or 14.45. -func clock(s string) bool { - h, m, _ := strings.Cut(s, ".") - if len(m) != 2 || len(h) > 2 || strings.HasPrefix(h, "-") { - return false - } - hh, _ := strconv.Atoi(h) - mm, _ := strconv.Atoi(m) - return hh <= 23 && mm <= 59 -} - -// currencies are the words and signs that make a pair of numbers prices. -var currencies = []string{"$", "€", "£", "¥", "aud", "usd", "eur", "gbp", "nzd", "cad", "dollars", "dollar", "euros", "euro", "pounds", "bucks", "each"} - -// money reports whether the text just before or after a pair names a -// currency, as in "AUD 3.50, 4.20" or "3.50, 4.20 euros". -func money(before, after string) bool { - before = strings.ToLower(strings.TrimRight(before, " ")) - after = strings.ToLower(strings.TrimLeft(strings.TrimLeft(after, "°"), " ")) - for _, c := range currencies { - sign := !isWordByte(c[0]) - if rest, ok := strings.CutSuffix(before, c); ok && (sign || rest == "" || !isWordByte(rest[len(rest)-1])) { - return true - } - if rest, ok := strings.CutPrefix(after, c); ok && (sign || rest == "" || !isWordByte(rest[0])) { - return true - } - } - return false -} - -func isWordByte(b byte) bool { - return b == '_' || ('0' <= b && b <= '9') || ('a' <= b && b <= 'z') -} diff --git a/cmd/geoguess/geo/parse_test.go b/cmd/geoguess/geo/parse_test.go deleted file mode 100644 index 8a9796e..0000000 --- a/cmd/geoguess/geo/parse_test.go +++ /dev/null @@ -1,136 +0,0 @@ -package geo - -import ( - "math" - "regexp" - "testing" -) - -func TestParse(t *testing.T) { - mel := Point{-37.8136, 144.9631} - for _, tc := range []struct { - text string - want Point - ok bool - }{ - // Signal's + → Location. - {"https://maps.google.com/maps?q=-37.8136%2C144.9631", mel, true}, - {"https://maps.google.com/maps?q=-37.8136,144.9631", mel, true}, - {"Here: https://maps.google.com/maps?q=-37.8136%2C144.9631.", mel, true}, - {"maps.google.com/maps?q=-37.8136%2C%20144.9631", mel, true}, - {"https://www.google.com/maps?q=loc:-37.8136,144.9631", mel, true}, - {"https://www.google.com.au/maps?ll=-37.8136,144.9631&z=15", mel, true}, - {"https://www.google.com/maps/search/?api=1&query=-37.8136%2C144.9631", mel, true}, - {"google.com/maps/@-37.8136,144.9631,15z", mel, true}, - {"https://www.google.com/maps/place/Melbourne+VIC/@-37.8136,144.9631,12z/data=!3m1", mel, true}, - {"https://www.google.com/maps/place/-37.8136,+144.9631", mel, true}, - {"(https://maps.google.fr/?q=-37.8136,144.9631)", mel, true}, - // Apple. - {"https://maps.apple.com/?ll=-37.8136,144.9631&q=Pin", mel, true}, - {"https://maps.apple.com/?q=Cafe&sll=-37.8136,144.9631", mel, true}, - {"https://maps.apple.com/place?coordinate=-37.8136,144.9631", mel, true}, - // geo: URIs. - {"geo:-37.8136,144.9631", mel, true}, - {"GEO:-37.8136,144.9631,30;u=35", mel, true}, - {"geo:0,0?q=-37.8136,144.9631(Pin)", mel, true}, - {"geo:0,0", Point{}, true}, - // OpenStreetMap. - {"https://www.openstreetmap.org/#map=15/-37.8136/144.9631", mel, true}, - {"https://www.openstreetmap.org/#map=15/-37.8136/144.9631&layers=H", mel, true}, - {"https://www.openstreetmap.org/?mlat=-37.8136&mlon=144.9631#map=3/0/0", mel, true}, - // Typed. - {"-37.8136, 144.9631", mel, true}, - {"-37.8136,144.9631", mel, true}, - {"I reckon −37.8136 , 144.9631.", mel, true}, - {"-37.8136°, 144.9631°", mel, true}, - {"my guess is 48.8584, 2.2945 final answer", Point{48.8584, 2.2945}, true}, - {"0.0, 0.0", Point{}, true}, - {"90.0, -180.0", Point{90, -180}, true}, - - // Not locations. - {"3, 4", Point{}, false}, - {"-37, 144", Point{}, false}, - {"meet at 12.30, 14.45 or later", Point{}, false}, - {"9.30, 10.15", Point{}, false}, - {"$3.50, $4.20", Point{}, false}, - {"they were 3.50, 4.20 each", Point{}, false}, - {"AUD 3.50, 4.20", Point{}, false}, - {"3.50, 4.20 euros", Point{}, false}, - {"3.5%, 4.2%", Point{}, false}, - {"v1.2, v1.3", Point{}, false}, - {"versions 1.2.3, 1.2.4", Point{}, false}, - {"91.5, 10.0", Point{}, false}, - {"45.5, 180.5", Point{}, false}, - {"https://maps.google.com/maps?q=Melbourne", Point{}, false}, - {"https://maps.google.com/maps?q=-97.1,144.9", Point{}, false}, - {"https://example.com/maps?q=-37.8136,144.9631", Point{}, false}, - {"https://maps.google.com.evil.example/?q=-37.8136,144.9631", Point{}, false}, - {"https://www.google.com/search?q=-37.8136,144.9631", Point{}, false}, - {"https://maps.app.goo.gl/abc123", Point{}, false}, - {"geo: what a game", Point{}, false}, - {"geo:-37.8136", Point{}, false}, - {"https://www.openstreetmap.org/#map=15/-37.8136", Point{}, false}, - {"", Point{}, false}, - } { - got, ok := Parse(tc.text) - if ok != tc.ok || !near(got, tc.want) { - t.Errorf("Parse(%q) = %v, %v; want %v, %v", tc.text, got, ok, tc.want, tc.ok) - } - } -} - -func near(a, b Point) bool { - return math.Abs(a.Lat-b.Lat) < 1e-9 && math.Abs(a.Lon-b.Lon) < 1e-9 -} - -// TestPatternCatchesEveryForm checks the watch pattern catches every text -// Parse reads, so no guess is missed. -func TestPatternCatchesEveryForm(t *testing.T) { - re := regexp.MustCompile(Pattern) - for _, text := range []string{ - "https://maps.google.com/maps?q=-37.8136%2C144.9631", - "google.com/maps/@-37.81,144.96,15z", - "https://www.google.com.au/maps/place/X/@-37.81,144.96,12z", - "https://maps.apple.com/?ll=-37.81,144.96", - "https://maps.apple.com?q=x&sll=-37.81,144.96", - "geo:-37.81,144.96", - "geo:0,0?q=-37.81,144.96", - "https://www.openstreetmap.org/#map=15/-37.81/144.96", - "https://www.openstreetmap.org/?mlat=-37.81&mlon=144.96", - "-37.81, 144.96", - "guess: 48.85,2.29", - "-37.81°, 144.96°", - } { - if !re.MatchString(text) { - t.Errorf("pattern misses %q", text) - } - if _, ok := Parse(text); !ok { - t.Errorf("Parse misses %q", text) - } - } -} - -// TestPatternSkipsChatter checks the watch pattern is specific: ordinary -// chat lines, links and numbers don't match, so it passes signalbot's -// catch-all check. -func TestPatternSkipsChatter(t *testing.T) { - re := regexp.MustCompile(Pattern) - if len(Pattern) > 1024 { - t.Errorf("pattern is %d bytes, over the 1 KB limit", len(Pattern)) - } - for _, text := range []string{ - "", "lol", "ok", "see you at 5", "what's for dinner?", "running 10 min late", - "meet at 12:30, 14:45 is too late", "3, 4", "it cost 3.50", "1.5 litres, 2 eggs", - "version 1.2.3 is out", "the score was 3-4", "call me on 0412 345 678", - "https://www.abc.net.au/news/2024-05-01/some-story/103789456", - "https://www.google.com/search?q=weather", "https://youtu.be/dQw4w9WgXcQ", - "Alice: are we still on for Saturday?", "Bob, can you grab milk", - "I'm at the station", "we're in Melbourne now", "geography homework is due", - "lat long of the house?", "😂😂😂", "100%", "1,000,000", "pi is 3.14159", - "Google Maps says 20 min", "check apple maps", "openstreetmap is great", - } { - if re.MatchString(text) { - t.Errorf("pattern matches chatter %q", text) - } - } -} diff --git a/cmd/geoguess/geo/pixels.go b/cmd/geoguess/geo/pixels.go deleted file mode 100644 index 72e9a2a..0000000 --- a/cmd/geoguess/geo/pixels.go +++ /dev/null @@ -1,277 +0,0 @@ -package geo - -import ( - "bytes" - "image" - "image/color" - "image/jpeg" - "math" - "math/rand/v2" - - xdraw "golang.org/x/image/draw" -) - -// The pixel checks' limits, on a view scaled to analysisWidth. The -// sharpness and detail limits were tuned on test images: a street scene -// passes them with room to spare, and the same scene blurred, or a bare wall, -// doesn't. -const ( - analysisWidth = 256 - minMeanLuma = 55 - maxMeanLuma = 205 - maxClipped = 0.15 // of pixels at luma ≤ 5 or ≥ 250 - minLumaSD = 28 - minSharpness = 100 // variance of the Laplacian - maxSky = 0.65 // of the top two-thirds - maxBand = 0.20 // of the height: a larger dark band at the bottom is a dashboard - minEdges = 0.02 // of pixels with a Sobel magnitude over edgeLevel - edgeLevel = 100 -) - -// The output and the panorama view. -const ( - outWidth = 1600 - outQuality = 85 - maxOut = 1 << 20 - viewFOV = math.Pi / 2 // a panorama's view is 90° wide - maxYaw = math.Pi / 3 // and turned up to 60° either way from the capture heading - maxPixels = 50 << 20 // the largest photo decoded -) - -// Vet runs the pixel checks on a downloaded photo and returns it ready to -// post: a 90° view of a panorama, at the capture heading turned a random -// angle by r, or a flat photo as it is, with any dashboard band cropped off, -// as a JPEG about 1600 px wide and under 1 MB, which carries no metadata. -// The error is a Reject. -func Vet(data []byte, pano bool, r *rand.Rand) ([]byte, error) { - cfg, _, err := image.DecodeConfig(bytes.NewReader(data)) - if err != nil || cfg.Width <= 0 || cfg.Height <= 0 || int64(cfg.Width)*int64(cfg.Height) > maxPixels { - return nil, RejectUnreadable - } - m, _, err := image.Decode(bytes.NewReader(data)) - if err != nil { - return nil, RejectUnreadable - } - src := image.NewRGBA(image.Rect(0, 0, cfg.Width, cfg.Height)) - xdraw.Draw(src, src.Bounds(), m, m.Bounds().Min, xdraw.Src) - - var render func(w int) *image.RGBA - width := min(outWidth, cfg.Width) - switch { - case pano && math.Abs(float64(cfg.Width)/float64(cfg.Height)-2) < 0.05: - yaw := (2*r.Float64() - 1) * maxYaw - render = func(w int) *image.RGBA { return gnomonic(src, yaw, w, w*3/4) } - width = min(outWidth, cfg.Width/2) // a 90° view holds a quarter of the width - case cfg.Width < minWidth: - return nil, RejectSmall - default: - render = func(w int) *image.RGBA { - if w == cfg.Width { - return src - } - return scale(src, w, w*cfg.Height/cfg.Width, xdraw.CatmullRom) - } - } - small := render(analysisWidth) - keep, err := checkPixels(small) - if err != nil { - return nil, err - } - out := render(width) - h := int(math.Round(float64(out.Bounds().Dy()) * keep)) - return encode(out.SubImage(image.Rect(0, 0, out.Bounds().Dx(), h))) -} - -// scale is src scaled to w × h. -func scale(src image.Image, w, h int, s xdraw.Scaler) *image.RGBA { - dst := image.NewRGBA(image.Rect(0, 0, max(w, 1), max(h, 1))) - s.Scale(dst, dst.Bounds(), src, src.Bounds(), xdraw.Src, nil) - return dst -} - -// gnomonic is a w × h rectilinear view, 90° wide and level, of the -// equirectangular panorama src, looking yaw radians right of its centre -// (the capture heading). -func gnomonic(src *image.RGBA, yaw float64, w, h int) *image.RGBA { - dst := image.NewRGBA(image.Rect(0, 0, w, h)) - sw, sh := float64(src.Bounds().Dx()), float64(src.Bounds().Dy()) - f := float64(w) / 2 / math.Tan(viewFOV/2) - for y := range h { - dy := (float64(y) + 0.5 - float64(h)/2) / f - for x := range w { - dx := (float64(x) + 0.5 - float64(w)/2) / f - lon := yaw + math.Atan(dx) // the ray (dx, dy, 1) - lat := -math.Atan2(dy, math.Hypot(dx, 1)) - u := (lon/(2*math.Pi)+0.5)*sw - 0.5 - v := (0.5-lat/math.Pi)*sh - 0.5 - dst.SetRGBA(x, y, bilinear(src, u, v)) - } - } - return dst -} - -// bilinear samples src at (u, v), wrapping round horizontally. -func bilinear(src *image.RGBA, u, v float64) color.RGBA { - w, h := src.Bounds().Dx(), src.Bounds().Dy() - v = math.Max(0, math.Min(float64(h-1), v)) - x0, y0 := int(math.Floor(u)), int(v) - fx, fy := u-math.Floor(u), v-float64(y0) - y1 := min(y0+1, h-1) - x0 = ((x0 % w) + w) % w - x1 := (x0 + 1) % w - var acc [4]float64 - for _, s := range [4]struct { - x, y int - k float64 - }{{x0, y0, (1 - fx) * (1 - fy)}, {x1, y0, fx * (1 - fy)}, {x0, y1, (1 - fx) * fy}, {x1, y1, fx * fy}} { - i := src.PixOffset(s.x, s.y) - for j := range acc { - acc[j] += s.k * float64(src.Pix[i+j]) - } - } - return color.RGBA{uint8(acc[0] + 0.5), uint8(acc[1] + 0.5), uint8(acc[2] + 0.5), 255} -} - -// checkPixels runs the pixel checks on m, cheapest first, and returns the -// share of its height to keep: less than 1 when a dashboard band is cropped -// off the bottom. -func checkPixels(m *image.RGBA) (float64, error) { - w, h := m.Bounds().Dx(), m.Bounds().Dy() - if w < 3 || h < 3 { - return 0, RejectUnreadable - } - luma := make([]float64, w*h) - var sum, sq float64 - clipped := 0 - for y := range h { - for x := range w { - i := m.PixOffset(x, y) - l := 0.299*float64(m.Pix[i]) + 0.587*float64(m.Pix[i+1]) + 0.114*float64(m.Pix[i+2]) - luma[y*w+x] = l - sum += l - sq += l * l - if l <= 5 || l >= 250 { - clipped++ - } - } - } - n := float64(w * h) - mean := sum / n - if mean < minMeanLuma || mean > maxMeanLuma || float64(clipped)/n >= maxClipped { - return 0, RejectExposure - } - if math.Sqrt(max(sq/n-mean*mean, 0)) <= minLumaSD { - return 0, RejectContrast - } - if laplacianVariance(luma, w, h) <= minSharpness { - return 0, RejectBlurry - } - edges := sobel(luma, w, h) - if sky(m, edges, w, h) >= maxSky { - return 0, RejectSky - } - band := dashboard(luma, w, h) - if float64(band) > maxBand*float64(h) { - return 0, RejectDashboard - } - keep := h - band - strong := 0 - for y := 1; y < keep-1; y++ { - for x := 1; x < w-1; x++ { - if edges[y*w+x] > edgeLevel { - strong++ - } - } - } - if float64(strong)/float64((keep-2)*(w-2)) < minEdges { - return 0, RejectBare - } - return float64(keep) / float64(h), nil -} - -// laplacianVariance is the variance of the 4-neighbour Laplacian of luma, -// over its inner pixels: low for a blurred photo. -func laplacianVariance(luma []float64, w, h int) float64 { - var sum, sq float64 - for y := 1; y < h-1; y++ { - for x := 1; x < w-1; x++ { - i := y*w + x - l := luma[i-1] + luma[i+1] + luma[i-w] + luma[i+w] - 4*luma[i] - sum += l - sq += l * l - } - } - n := float64((w - 2) * (h - 2)) - mean := sum / n - return sq/n - mean*mean -} - -// sobel is the Sobel gradient magnitude of luma, 0 on the border. -func sobel(luma []float64, w, h int) []float64 { - out := make([]float64, w*h) - for y := 1; y < h-1; y++ { - for x := 1; x < w-1; x++ { - i := y*w + x - gx := luma[i-w+1] + 2*luma[i+1] + luma[i+w+1] - luma[i-w-1] - 2*luma[i-1] - luma[i+w-1] - gy := luma[i+w-1] + 2*luma[i+w] + luma[i+w+1] - luma[i-w-1] - 2*luma[i-w] - luma[i-w+1] - out[i] = math.Hypot(gx, gy) - } - } - return out -} - -// sky is the share of the top two-thirds of m that looks like sky: smooth, -// and either blue or a bright, colourless overcast. -func sky(m *image.RGBA, edges []float64, w, h int) float64 { - top := h * 2 / 3 - count := 0 - for y := range top { - for x := range w { - if edges[y*w+x] > 40 { - continue - } - i := m.PixOffset(x, y) - r, g, b := int(m.Pix[i]), int(m.Pix[i+1]), int(m.Pix[i+2]) - l := (299*r + 587*g + 114*b) / 1000 - blue := b > r+10 && b >= g && l > 100 - overcast := l > 190 && max(r, g, b)-min(r, g, b) < 25 - if blue || overcast { - count++ - } - } - } - return float64(count) / float64(top*w) -} - -// dashboard is the height in rows of a dark, flat band along the bottom of -// luma, such as a car's dashboard or bonnet. -func dashboard(luma []float64, w, h int) int { - band := 0 - for y := h - 1; y >= 0; y-- { - var sum, sq float64 - for _, l := range luma[y*w : (y+1)*w] { - sum += l - sq += l * l - } - mean := sum / float64(w) - if mean >= 50 || math.Sqrt(max(sq/float64(w)-mean*mean, 0)) >= 12 { - break - } - band++ - } - return band -} - -// encode is m as a JPEG of quality 85, lower if that is over 1 MB. -func encode(m image.Image) ([]byte, error) { - for _, q := range []int{outQuality, 75, 65} { - var b bytes.Buffer - if err := jpeg.Encode(&b, m, &jpeg.Options{Quality: q}); err != nil { - return nil, RejectUnreadable - } - if b.Len() <= maxOut { - return b.Bytes(), nil - } - } - return nil, RejectUnreadable -} diff --git a/cmd/geoguess/geo/pixels_test.go b/cmd/geoguess/geo/pixels_test.go deleted file mode 100644 index 8231b36..0000000 --- a/cmd/geoguess/geo/pixels_test.go +++ /dev/null @@ -1,267 +0,0 @@ -package geo - -import ( - "bytes" - "image" - "image/color" - "image/jpeg" - "math" - "math/rand/v2" - "testing" - - xdraw "golang.org/x/image/draw" -) - -// The test photos are drawn, not downloaded: a street scene of sky, -// buildings with windows and a textured road, and variations on it that -// each fail one check. - -// scene is the street scene, w × h, drawn with r's noise. -func scene(w, h int, r *rand.Rand) *image.RGBA { - m := image.NewRGBA(image.Rect(0, 0, w, h)) - horizon := h / 3 - for y := range h { - for x := range w { - var c color.RGBA - switch { - case y < horizon: // sky, paler towards the horizon - k := uint8(80 * y / horizon) - c = color.RGBA{90 + k, 140 + k, 220, 255} - case y < h*3/4: // buildings, each its own colour, with windows - b := x * 7 / w - c = color.RGBA{uint8(60 + 25*b), uint8(50 + 15*b), uint8(40 + 10*b), 255} - if (x*40/w)%3 == 1 && ((y-horizon)*20/h)%2 == 1 { - c = color.RGBA{30, 35, 45, 255} - } - default: // road with lane marks - c = color.RGBA{105, 105, 110, 255} - if (x*10/w)%2 == 0 && y > h*7/8 && y < h*7/8+h/40 { - c = color.RGBA{230, 230, 230, 255} - } - } - n := int(r.NormFloat64() * 10) - m.SetRGBA(x, y, color.RGBA{clamp(int(c.R) + n), clamp(int(c.G) + n), clamp(int(c.B) + n), 255}) - } - } - // A tall building cuts into the sky. - for y := h / 6; y < horizon; y++ { - for x := w / 3; x < w/2; x++ { - m.SetRGBA(x, y, color.RGBA{150, 120, 100, 255}) - } - } - return m -} - -func clamp(v int) uint8 { return uint8(max(0, min(255, v))) } - -// mapPixels sets every pixel of m by f of its position and colour. -func mapPixels(m *image.RGBA, f func(x, y int, c color.RGBA) color.RGBA) *image.RGBA { - b := m.Bounds() - for y := b.Min.Y; y < b.Max.Y; y++ { - for x := b.Min.X; x < b.Max.X; x++ { - m.SetRGBA(x, y, f(x, y, m.RGBAAt(x, y))) - } - } - return m -} - -// blur is m out of focus: shrunk by k and scaled back up. -func blur(m *image.RGBA, k int) *image.RGBA { - w, h := m.Bounds().Dx(), m.Bounds().Dy() - return scale(scale(m, w/k, h/k, xdraw.ApproxBiLinear), w, h, xdraw.BiLinear) -} - -func jpegOf(t testing.TB, m image.Image) []byte { - t.Helper() - var b bytes.Buffer - if err := jpeg.Encode(&b, m, &jpeg.Options{Quality: 92}); err != nil { - t.Fatal(err) - } - return b.Bytes() -} - -// testPhotos are the test photos at w × h: name, image, the Reject wanted. -func testPhotos(w, h int) []struct { - name string - m *image.RGBA - want error -} { - r := rand.New(rand.NewPCG(1, 2)) - return []struct { - name string - m *image.RGBA - want error - }{ - {"good", scene(w, h, r), nil}, - {"night", mapPixels(scene(w, h, r), func(_, _ int, c color.RGBA) color.RGBA { - return color.RGBA{c.R / 6, c.G / 6, c.B / 6, 255} - }), RejectExposure}, - {"burnt out", mapPixels(scene(w, h, r), func(_, _ int, c color.RGBA) color.RGBA { - return color.RGBA{clamp(int(c.R) * 3), clamp(int(c.G) * 3), clamp(int(c.B) * 3), 255} - }), RejectExposure}, - {"fog", mapPixels(scene(w, h, r), func(_, _ int, c color.RGBA) color.RGBA { - return color.RGBA{150 + c.R/10, 150 + c.G/10, 150 + c.B/10, 255} - }), RejectContrast}, - {"blurry", blur(scene(w, h, r), max(w/64, 4)), RejectBlurry}, - {"sky", mapPixels(scene(w, h, r), func(x, y int, c color.RGBA) color.RGBA { - if y < h*2/3 { - return color.RGBA{170, 200, 240, 255} - } - return c - }), RejectSky}, - {"dashboard", mapPixels(scene(w, h, r), func(_, y int, c color.RGBA) color.RGBA { - if y >= h*65/100 { - return color.RGBA{20, 20, 22, 255} - } - return c - }), RejectDashboard}, - {"bare wall", bareWall(w, h, r), RejectBare}, - } -} - -// bareWall is a smooth, sharp-grained plaster wall: exposed well, with -// contrast and grain, but no edges. -func bareWall(w, h int, r *rand.Rand) *image.RGBA { - m := image.NewRGBA(image.Rect(0, 0, w, h)) - for y := range h { - for x := range w { - l := 60 + 140*float64(x)/float64(w) - n := r.NormFloat64() * 6 * float64(w) / analysisWidth - m.SetRGBA(x, y, color.RGBA{clamp(int(l + n + 20)), clamp(int(l + n)), clamp(int(l + n - 25)), 255}) - } - } - return m -} - -func TestCheckPixels(t *testing.T) { - for _, tc := range testPhotos(analysisWidth, analysisWidth*3/4) { - _, err := checkPixels(tc.m) - if err != tc.want { - t.Errorf("%s: %v, want %v", tc.name, err, tc.want) - } - } -} - -func TestVet(t *testing.T) { - t.Parallel() - r := rand.New(rand.NewPCG(3, 4)) - for _, tc := range testPhotos(1024, 768) { - out, err := Vet(jpegOf(t, tc.m), false, r) - if err != tc.want { - t.Errorf("%s: %v, want %v", tc.name, err, tc.want) - continue - } - if err != nil { - continue - } - m, format, err := image.Decode(bytes.NewReader(out)) - if err != nil || format != "jpeg" { - t.Fatalf("%s: output %s, %v", tc.name, format, err) - } - if m.Bounds().Dx() != 1024 || m.Bounds().Dy() != 768 || len(out) > maxOut { - t.Errorf("%s: output %v, %d bytes", tc.name, m.Bounds(), len(out)) - } - } -} - -func TestVetScalesAndCrops(t *testing.T) { - t.Parallel() - r := rand.New(rand.NewPCG(5, 6)) - // A wide photo with a short dashboard band: shrunk to 1600 wide, and - // the band cut off. - m := mapPixels(scene(2048, 1536, r), func(_, y int, c color.RGBA) color.RGBA { - if y >= 1536*90/100 { - return color.RGBA{15, 15, 18, 255} - } - return c - }) - out, err := Vet(jpegOf(t, m), false, r) - if err != nil { - t.Fatal(err) - } - cfg, _ := jpeg.DecodeConfig(bytes.NewReader(out)) - if cfg.Width != 1600 || cfg.Height > 1200*91/100 || cfg.Height < 1200*85/100 { - t.Errorf("output %d × %d, want 1600 wide with about the bottom 10%% cut", cfg.Width, cfg.Height) - } -} - -func TestVetRejects(t *testing.T) { - r := rand.New(rand.NewPCG(7, 8)) - for _, tc := range []struct { - name string - data []byte - want error - }{ - {"not an image", []byte("hello"), RejectUnreadable}, - {"truncated", jpegOf(t, scene(1280, 960, r))[:500], RejectUnreadable}, - {"narrow", jpegOf(t, scene(800, 600, r)), RejectSmall}, - } { - if _, err := Vet(tc.data, false, r); err != tc.want { - t.Errorf("%s: %v, want %v", tc.name, err, tc.want) - } - } -} - -// equirect is a panorama that is a street scene ahead (its centre, the -// capture heading) and blank grey all round the rest. -func equirect(w, h int, r *rand.Rand) *image.RGBA { - pano := mapPixels(image.NewRGBA(image.Rect(0, 0, w, h)), func(_, _ int, _ color.RGBA) color.RGBA { - return color.RGBA{128, 128, 128, 255} - }) - front := scene(w/2, h, r) - for y := range h { - for x := range w / 2 { - pano.SetRGBA(w/4+x, y, front.RGBAAt(x, y)) - } - } - return pano -} - -func TestVetPanorama(t *testing.T) { - t.Parallel() - r := rand.New(rand.NewPCG(9, 10)) - data := jpegOf(t, equirect(2048, 1024, r)) - out, err := Vet(data, true, r) - if err != nil { - t.Fatal(err) - } - cfg, _ := jpeg.DecodeConfig(bytes.NewReader(out)) - if cfg.Width != 1024 || cfg.Height != 768 { - t.Errorf("view %d × %d, want 1024 × 768", cfg.Width, cfg.Height) - } - // A photo that isn't 2:1 is checked as a flat photo. - if _, err := Vet(jpegOf(t, scene(1024, 768, r)), true, r); err != nil { - t.Errorf("a pano-flagged 4:3 photo: %v", err) - } -} - -func TestGnomonic(t *testing.T) { - // A panorama whose colour is its longitude: the view's centre column - // shows the yaw, and its edges 45° either side. - src := image.NewRGBA(image.Rect(0, 0, 360, 180)) - mapPixels(src, func(x, _ int, _ color.RGBA) color.RGBA { return color.RGBA{uint8(x * 255 / 359), 0, 0, 255} }) - for _, yaw := range []float64{0, math.Pi / 4, -math.Pi / 3} { - v := gnomonic(src, yaw, 101, 75) - lonAt := func(x int) float64 { return float64(v.RGBAAt(x, 37).R)*359/255 - 180 } - want := yaw * 180 / math.Pi - if got := lonAt(50); math.Abs(got-want) > 2.5 { - t.Errorf("yaw %.0f°: centre shows %.1f°", want, got) - } - if got := lonAt(0); math.Abs(got-(want-45)) > 3 { - t.Errorf("yaw %.0f°: left edge shows %.1f°, want %.1f", want, got, want-45) - } - if got := lonAt(100); math.Abs(got-(want+45)) > 3 { - t.Errorf("yaw %.0f°: right edge shows %.1f°, want %.1f", want, got, want+45) - } - } - // Level: the horizon is the middle row, and straight up is out of view. - src = image.NewRGBA(image.Rect(0, 0, 360, 180)) - mapPixels(src, func(_, y int, _ color.RGBA) color.RGBA { return color.RGBA{0, uint8(y * 255 / 179), 0, 255} }) - v := gnomonic(src, 0, 100, 100) - if g := v.RGBAAt(50, 50).G; g < 120 || g > 135 { - t.Errorf("middle row shows latitude level %d, want about 128", g) - } - if g := v.RGBAAt(50, 0).G; g < 50 { - t.Errorf("top row shows latitude level %d, want under 45° up", g) - } -} diff --git a/cmd/geoguess/geo/place.go b/cmd/geoguess/geo/place.go deleted file mode 100644 index 7dba429..0000000 --- a/cmd/geoguess/geo/place.go +++ /dev/null @@ -1,81 +0,0 @@ -package geo - -import ( - "context" - "net/http" - "net/url" - "strings" - "time" -) - -// NominatimURL is OpenStreetMap's public Nominatim, whose policy allows at -// most one request a second, with a User-Agent that names the program. -const NominatimURL = "https://nominatim.openstreetmap.org" - -// Place is where a photo was taken, as the reveal names it. -type Place struct { - Name string // "Ballarat, Victoria, Australia" - Country string - CountryCode string // ISO 3166-1 alpha-2, upper case -} - -// Nominatim names places by reverse geocoding, at most once a second. -type Nominatim struct { - url string - client *http.Client - pace *pacer -} - -// NewNominatim is a client for the Nominatim at base (NominatimURL, or a -// self-hosted one). -func NewNominatim(base string, client *http.Client) *Nominatim { - return &Nominatim{url: strings.TrimRight(base, "/"), client: client, pace: &pacer{every: time.Second}} -} - -// Reverse names the town, region and country at p. A place with no country, -// such as the open sea, is RejectNoPlace. -func (n *Nominatim) Reverse(ctx context.Context, p Point) (Place, error) { - if err := n.pace.wait(ctx); err != nil { - return Place{}, err - } - q := url.Values{ - "format": {"jsonv2"}, "lat": {coord(p.Lat)}, "lon": {coord(p.Lon)}, - "zoom": {"10"}, "addressdetails": {"1"}, "accept-language": {"en"}, - } - var a struct { - Error string `json:"error"` - Address map[string]string `json:"address"` - } - r := request{client: n.client, source: "Nominatim", url: n.url + "/reverse?" + q.Encode(), limit: 1 << 20} - if err := r.getJSON(ctx, &a); err != nil { - return Place{}, err - } - country := a.Address["country"] - if a.Error != "" || country == "" { - return Place{}, RejectNoPlace - } - parts := []string{} - add := func(s string) { - if s != "" && (len(parts) == 0 || parts[len(parts)-1] != s) { - parts = append(parts, s) - } - } - add(first(a.Address, "city", "town", "village", "municipality", "hamlet", "suburb", "county")) - add(first(a.Address, "state", "region", "province", "state_district")) - add(country) - return Place{ - Name: strings.Join(parts, ", "), - Country: country, - CountryCode: strings.ToUpper(a.Address["country_code"]), - }, nil -} - -// first is the first of keys that address has. -func first(address map[string]string, keys ...string) string { - for _, k := range keys { - if v := address[k]; v != "" { - return v - } - } - return "" -} diff --git a/cmd/geoguess/geo/place_test.go b/cmd/geoguess/geo/place_test.go deleted file mode 100644 index bf1de01..0000000 --- a/cmd/geoguess/geo/place_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package geo - -import ( - "context" - "net/http" - "testing" -) - -func TestNominatimReverse(t *testing.T) { - api := newFakeAPI(t) - answer := "" - status := http.StatusOK - api.handle = func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(status) - w.Write([]byte(answer)) - } - n := NewNominatim(api.URL+"/", api.Client()) - n.pace.every = 0 - ctx := context.Background() - for _, tc := range []struct { - name string - answer string - want Place - err error - }{ - {"city", `{"display_name":"…","address":{"city":"Ballarat","state":"Victoria","country":"Australia","country_code":"au"}}`, - Place{Name: "Ballarat, Victoria, Australia", Country: "Australia", CountryCode: "AU"}, nil}, - {"village and county", `{"address":{"village":"Bob's Bay","county":"Some County","country":"Ireland","country_code":"ie"}}`, - Place{Name: "Bob's Bay, Ireland", Country: "Ireland", CountryCode: "IE"}, nil}, - {"county only", `{"address":{"county":"Alice County","state":"Ohio","country":"United States","country_code":"us"}}`, - Place{Name: "Alice County, Ohio, United States", Country: "United States", CountryCode: "US"}, nil}, - {"city-state", `{"address":{"city":"Singapore","country":"Singapore","country_code":"sg"}}`, - Place{Name: "Singapore", Country: "Singapore", CountryCode: "SG"}, nil}, - {"no country", `{"address":{"state":"International waters"}}`, Place{}, RejectNoPlace}, - {"open sea", `{"error":"Unable to geocode"}`, Place{}, RejectNoPlace}, - } { - answer = tc.answer - got, err := n.Reverse(ctx, Point{-37.5622, 143.8503}) - if got != tc.want || err != tc.err { - t.Errorf("%s: %+v, %v; want %+v, %v", tc.name, got, err, tc.want, tc.err) - } - } - req := api.requests()[0] - q := req.URL.Query() - if req.URL.Path != "/reverse" || q.Get("lat") != "-37.562200" || q.Get("lon") != "143.850300" || q.Get("zoom") != "10" || q.Get("format") != "jsonv2" { - t.Errorf("request %v", req.URL) - } - if req.Header.Get("User-Agent") != userAgent { - t.Errorf("User-Agent %q", req.Header.Get("User-Agent")) - } - - status = http.StatusServiceUnavailable - if _, err := n.Reverse(ctx, Point{}); err != (StatusError{Source: "Nominatim", Code: 503}) { - t.Errorf("503: %v", err) - } -} diff --git a/cmd/geoguess/geo/rules.go b/cmd/geoguess/geo/rules.go deleted file mode 100644 index 4fd9479..0000000 --- a/cmd/geoguess/geo/rules.go +++ /dev/null @@ -1,134 +0,0 @@ -package geo - -import ( - "math" - "time" -) - -// Reject is why a candidate or its photo was turned down: one of a fixed -// list, so it is safe to log. -type Reject string - -func (r Reject) Error() string { return string(r) } - -// The reasons a candidate is rejected, from its metadata and then its -// pixels. -const ( - RejectQuality Reject = "low quality" - RejectUndated Reject = "no capture time" - RejectOld Reject = "too old" - RejectSmall Reject = "too small" - RejectFisheye Reject = "fisheye" - RejectDark Reject = "not daylight" - RejectDrift Reject = "GPS drift" - RejectSequence Reject = "same sequence" - RejectUsed Reject = "used recently" - RejectUnreadable Reject = "unreadable image" - RejectExposure Reject = "badly exposed" - RejectContrast Reject = "low contrast" - RejectBlurry Reject = "blurry" - RejectSky Reject = "mostly sky" - RejectDashboard Reject = "dashboard" - RejectBare Reject = "little detail" - RejectNoPlace Reject = "no country" -) - -// Rules are the metadata checks, which need no download. -type Rules struct { - MinQuality float64 // the least Mapillary quality_score, when it has one - MaxAge time.Duration // the oldest photo taken -} - -// The fixed limits of the metadata checks. -const ( - minWidth = 1024 // pixels - minGrade = 3 // Panoramax's C - minSunAngle = 12 // degrees above the horizon, a margin for camera clocks - maxDriftKm = 0.05 // between Mapillary's corrected and raw positions -) - -// Check is nil if c passes the metadata checks at now, from cheapest to -// dearest, else the first it fails. -func (r Rules) Check(c Candidate, now time.Time) error { - switch { - case c.Quality >= 0 && c.Quality < r.MinQuality: - return RejectQuality - case c.Grade > 0 && c.Grade < minGrade: - return RejectQuality - case c.Captured.IsZero(): - return RejectUndated - case now.Sub(c.Captured) > r.MaxAge: - return RejectOld - case c.Width > 0 && c.Width < minWidth: - return RejectSmall - case c.Fisheye: - return RejectFisheye - case SunElevation(c.At, c.Captured) <= minSunAngle: - return RejectDark - case Km(c.At, c.Raw) > maxDriftKm: - return RejectDrift - } - return nil -} - -// Filter is the candidates that pass the checks, at most one from each -// sequence and none whose Key used reports as recently used, in their order. It -// calls reject with why each other one was turned down. -func (r Rules) Filter(cands []Candidate, now time.Time, used func(id string) bool, reject func(Reject)) []Candidate { - var out []Candidate - seqs := map[string]bool{} - for _, c := range cands { - err := r.Check(c, now) - switch { - case err != nil: - case used != nil && used(c.Key()): - err = RejectUsed - case c.Sequence != "" && seqs[c.Sequence]: - err = RejectSequence - } - if err != nil { - if reject != nil { - reject(err.(Reject)) - } - continue - } - seqs[c.Sequence] = true - out = append(out, c) - } - return out -} - -// SunElevation is the sun's angle above the horizon in degrees at p and t, -// by NOAA's solar position formulas (good to about a degree for a century -// either side of 2000). -func SunElevation(p Point, t time.Time) float64 { - t = t.UTC() - jd := float64(t.UnixNano())/float64(24*time.Hour) + 2440587.5 - T := (jd - 2451545) / 36525 // Julian centuries since J2000 - - l0 := math.Mod(280.46646+T*(36000.76983+T*0.0003032), 360) // mean longitude - m := 357.52911 + T*(35999.05029-0.0001537*T) // mean anomaly - e := 0.016708634 - T*(0.000042037+0.0000001267*T) // orbit eccentricity - mr := radians(m) - centre := math.Sin(mr)*(1.914602-T*(0.004817+0.000014*T)) + math.Sin(2*mr)*(0.019993-0.000101*T) + math.Sin(3*mr)*0.000289 - ω := radians(125.04 - 1934.136*T) - λ := radians(l0 + centre - 0.00569 - 0.00478*math.Sin(ω)) // apparent longitude - ε0 := 23 + (26+(21.448-T*(46.815+T*(0.00059-T*0.001813)))/60)/60 - ε := radians(ε0 + 0.00256*math.Cos(ω)) // obliquity, corrected - decl := math.Asin(math.Sin(ε) * math.Sin(λ)) - - y := math.Pow(math.Tan(ε/2), 2) - l0r := radians(l0) - eqTime := 4 * degrees(y*math.Sin(2*l0r)-2*e*math.Sin(mr)+4*e*y*math.Sin(mr)*math.Cos(2*l0r)- - 0.5*y*y*math.Sin(4*l0r)-1.25*e*e*math.Sin(2*mr)) // minutes - - minutes := float64(t.Hour()*60+t.Minute()) + float64(t.Second())/60 + float64(t.Nanosecond())/6e10 - solarTime := math.Mod(minutes+eqTime+4*p.Lon, 1440) - if solarTime < 0 { - solarTime += 1440 - } - hourAngle := radians(solarTime/4 - 180) - φ := radians(p.Lat) - cosZenith := math.Sin(φ)*math.Sin(decl) + math.Cos(φ)*math.Cos(decl)*math.Cos(hourAngle) - return 90 - degrees(math.Acos(math.Max(-1, math.Min(1, cosZenith)))) -} diff --git a/cmd/geoguess/geo/rules_test.go b/cmd/geoguess/geo/rules_test.go deleted file mode 100644 index 745ac1b..0000000 --- a/cmd/geoguess/geo/rules_test.go +++ /dev/null @@ -1,100 +0,0 @@ -package geo - -import ( - "math" - "slices" - "testing" - "time" -) - -func TestSunElevation(t *testing.T) { - for _, tc := range []struct { - name string - p Point - t time.Time - want float64 // degrees, to within 0.5 - }{ - // At solar noon the sun is 90° − |latitude − declination| up, and at - // midnight latitude + declination − 90°. - {"June solstice noon at 40°N", Point{40, -105}, time.Date(2010, 6, 21, 19, 1, 40, 0, time.UTC), 73.44}, - {"March equinox noon at the equator", Point{0, 0}, time.Date(2024, 3, 20, 12, 7, 0, 0, time.UTC), 89.7}, - {"December solstice noon in Melbourne", Point{-37.81, 144.96}, time.Date(2025, 12, 21, 2, 19, 0, 0, time.UTC), 75.6}, - {"midnight in Melbourne", Point{-37.81, 144.96}, time.Date(2025, 12, 21, 14, 19, 0, 0, time.UTC), -28.7}, - {"midwinter noon in Tromsø", Point{69.65, 18.96}, time.Date(2025, 12, 21, 10, 45, 0, 0, time.UTC), -2.9}, - {"midsummer midnight in Tromsø", Point{69.65, 18.96}, time.Date(2025, 6, 21, 22, 45, 0, 0, time.UTC), 3.1}, - } { - if got := SunElevation(tc.p, tc.t); math.Abs(got-tc.want) > 0.5 { - t.Errorf("%s: %.2f°, want %.2f°", tc.name, got, tc.want) - } - } -} - -func TestRulesCheck(t *testing.T) { - now := time.Date(2026, 11, 20, 0, 0, 0, 0, time.UTC) - noon := time.Date(2024, 12, 21, 2, 19, 0, 0, time.UTC) // in Melbourne - mel := Point{-37.81, 144.96} - good := Candidate{ID: "1", At: mel, Raw: mel, Captured: noon, Quality: 0.8, Width: 2048} - rules := Rules{MinQuality: 0.5, MaxAge: 10 * 365 * 24 * time.Hour} - for _, tc := range []struct { - name string - edit func(*Candidate) - want error - }{ - {"good", func(*Candidate) {}, nil}, - {"quality unknown", func(c *Candidate) { c.Quality = -1 }, nil}, - {"quality at the minimum", func(c *Candidate) { c.Quality = 0.5 }, nil}, - {"low quality", func(c *Candidate) { c.Quality = 0.49 }, RejectQuality}, - {"grade C", func(c *Candidate) { c.Quality, c.Grade = -1, 3 }, nil}, - {"grade D", func(c *Candidate) { c.Quality, c.Grade = -1, 2 }, RejectQuality}, - {"undated", func(c *Candidate) { c.Captured = time.Time{} }, RejectUndated}, - {"11 years old", func(c *Candidate) { c.Captured = now.AddDate(-11, 0, 0) }, RejectOld}, - {"width unknown", func(c *Candidate) { c.Width = 0 }, nil}, - {"narrow", func(c *Candidate) { c.Width = 1023 }, RejectSmall}, - {"fisheye", func(c *Candidate) { c.Fisheye = true }, RejectFisheye}, - {"night", func(c *Candidate) { c.Captured = noon.Add(12 * time.Hour) }, RejectDark}, - {"dusk", func(c *Candidate) { c.Captured = noon.Add(7 * time.Hour) }, RejectDark}, - {"morning", func(c *Candidate) { c.Captured = noon.Add(-4 * time.Hour) }, nil}, - {"40 m drift", func(c *Candidate) { c.Raw.Lat += 0.00036 }, nil}, - {"60 m drift", func(c *Candidate) { c.Raw.Lat += 0.00054 }, RejectDrift}, - } { - c := good - tc.edit(&c) - if err := rules.Check(c, now); err != tc.want { - t.Errorf("%s: %v, want %v", tc.name, err, tc.want) - } - } -} - -func TestRulesFilter(t *testing.T) { - now := time.Date(2026, 11, 20, 0, 0, 0, 0, time.UTC) - noon := time.Date(2024, 12, 21, 2, 19, 0, 0, time.UTC) - mel := Point{-37.81, 144.96} - c := func(id, seq string, q float64) Candidate { - return Candidate{ID: id, Source: "Mapillary", Sequence: seq, At: mel, Raw: mel, Captured: noon, Quality: q} - } - cands := []Candidate{ - c("1", "a", 0.1), // low quality: doesn't take its sequence - c("2", "a", 0.9), - c("3", "a", 0.9), // same sequence - c("4", "b", 0.9), // used - c("5", "b", 0.9), - c("6", "", 0.9), - c("7", "", 0.9), // no sequence: each is its own - } - var why []Reject - used := func(key string) bool { return key == "Mapillary:4" } - got := Rules{MinQuality: 0.5, MaxAge: 24 * 365 * time.Hour * 10}.Filter(cands, now, used, func(r Reject) { why = append(why, r) }) - var ids []string - for _, g := range got { - ids = append(ids, g.ID) - } - if want := []string{"2", "5", "6", "7"}; !slices.Equal(ids, want) { - t.Errorf("kept %v, want %v", ids, want) - } - if want := []Reject{RejectQuality, RejectSequence, RejectUsed}; !slices.Equal(why, want) { - t.Errorf("rejected for %v, want %v", why, want) - } - if got := (Rules{}).Filter(nil, now, nil, nil); len(got) != 0 { - t.Errorf("Filter(nil) = %v", got) - } -} diff --git a/cmd/geoguess/geo/score.go b/cmd/geoguess/geo/score.go deleted file mode 100644 index ffe0619..0000000 --- a/cmd/geoguess/geo/score.go +++ /dev/null @@ -1,108 +0,0 @@ -// Package geo is GeoGuess's game logic: reading a guess, scoring and ranking -// guesses, finding a street-level photo worth playing and naming its place. -// It knows nothing of MCP or of chats. -package geo - -import ( - "cmp" - "math" - "slices" - "strconv" - "time" -) - -// Point is a place on Earth in decimal degrees. -type Point struct { - Lat, Lon float64 -} - -// valid reports whether p's latitude is in [-90, 90] and its longitude in -// [-180, 180]. -func (p Point) valid() bool { - return p.Lat >= -90 && p.Lat <= 90 && p.Lon >= -180 && p.Lon <= 180 -} - -// earthRadius is the mean radius of the Earth in km (IUGG). -const earthRadius = 6371.0088 - -// Km is the great-circle distance between a and b in km, by the haversine -// formula. -func Km(a, b Point) float64 { - φ1, φ2 := radians(a.Lat), radians(b.Lat) - dφ, dλ := φ2-φ1, radians(b.Lon-a.Lon) - h := math.Pow(math.Sin(dφ/2), 2) + math.Cos(φ1)*math.Cos(φ2)*math.Pow(math.Sin(dλ/2), 2) - return 2 * earthRadius * math.Asin(math.Sqrt(min(h, 1))) -} - -func radians(deg float64) float64 { return deg * math.Pi / 180 } -func degrees(rad float64) float64 { return rad * 180 / math.Pi } - -// MaxPoints is the score of a guess within 25 m. -const MaxPoints = 5000 - -// Points is the score of a guess km away: 5000·e^(−km/2000), rounded, and -// the full 5000 within 25 m. -func Points(km float64) int { - if km <= 0.025 { - return MaxPoints - } - return int(math.Round(MaxPoints * math.Exp(-km/2000))) -} - -// Guess is one player's guess in a round: only how far off it was, never -// where it was. -type Guess struct { - User string // the chat's pseudonymous user ID - Km float64 - At time.Time -} - -// Placing is a guess in the results: its rank (from 1) and its points. -type Placing struct { - Guess - Rank int - Points int -} - -// Rank orders guesses by distance, nearest first; a tie goes to the earlier -// guess. Every placing has its own rank. -func Rank(guesses []Guess) []Placing { - sorted := slices.Clone(guesses) - slices.SortStableFunc(sorted, func(a, b Guess) int { - return cmp.Or(cmp.Compare(a.Km, b.Km), a.At.Compare(b.At)) - }) - out := make([]Placing, len(sorted)) - for i, g := range sorted { - out[i] = Placing{Guess: g, Rank: i + 1, Points: Points(g.Km)} - } - return out -} - -// Distance is km as the results show it: metres under 1 km, one decimal under -// 100 km, else whole km with thousands separators. -func Distance(km float64) string { - switch { - case km < 1: - // Rounding can reach 1000 m, which reads better as 1.0 km. - if m := math.Round(km * 1000); m < 1000 { - return strconv.Itoa(int(m)) + " m" - } - return "1.0 km" - case math.Round(km*10)/10 < 100: - return strconv.FormatFloat(km, 'f', 1, 64) + " km" - } - return Thousands(int(math.Round(km))) + " km" -} - -// Thousands is n with a comma between each group of three digits. -func Thousands(n int) string { - s := strconv.Itoa(n) - sign := "" - if s[0] == '-' { - sign, s = "-", s[1:] - } - for i := len(s) - 3; i > 0; i -= 3 { - s = s[:i] + "," + s[i:] - } - return sign + s -} diff --git a/cmd/geoguess/geo/score_test.go b/cmd/geoguess/geo/score_test.go deleted file mode 100644 index 7e9e0db..0000000 --- a/cmd/geoguess/geo/score_test.go +++ /dev/null @@ -1,93 +0,0 @@ -package geo - -import ( - "math" - "slices" - "testing" - "time" -) - -func TestKm(t *testing.T) { - for _, tc := range []struct { - a, b Point - want float64 // km, to within 0.1% - }{ - {Point{-37.8136, 144.9631}, Point{-37.5622, 143.8503}, 101.8}, // Melbourne–Ballarat - {Point{51.5074, -0.1278}, Point{48.8566, 2.3522}, 343.9}, // London–Paris - {Point{0, 0}, Point{0, 180}, math.Pi * earthRadius}, - {Point{90, 0}, Point{-90, 0}, math.Pi * earthRadius}, - {Point{0, 179.9}, Point{0, -179.9}, 22.24}, - {Point{10, 10}, Point{10, 10}, 0}, - } { - got := Km(tc.a, tc.b) - if math.Abs(got-tc.want) > tc.want*0.001+1e-9 { - t.Errorf("Km(%v, %v) = %.3f, want %.3f", tc.a, tc.b, got, tc.want) - } - if back := Km(tc.b, tc.a); math.Abs(back-got) > 1e-9 { - t.Errorf("Km isn't symmetric: %v and %v", got, back) - } - } -} - -func TestPoints(t *testing.T) { - for _, tc := range []struct { - km float64 - want int - }{ - {0, 5000}, {0.025, 5000}, {0.026, 5000}, {1, 4998}, {12, 4970}, - {640, 3631}, {2000, 1839}, {9812, 37}, {20015, 0}, - } { - if got := Points(tc.km); got != tc.want { - t.Errorf("Points(%v) = %d, want %d", tc.km, got, tc.want) - } - } -} - -func TestRank(t *testing.T) { - t0 := time.Date(2026, 11, 19, 14, 30, 0, 0, time.UTC) - guesses := []Guess{ - {User: "u_bob", Km: 640, At: t0.Add(10 * time.Second)}, - {User: "u_alice", Km: 12, At: t0.Add(50 * time.Second)}, - {User: "u_3", Km: 640, At: t0.Add(5 * time.Second)}, // ties with Bob, but earlier - {User: "u_4", Km: 9812, At: t0}, - } - got := Rank(guesses) - want := []Placing{ - {Guess: guesses[1], Rank: 1, Points: 4970}, - {Guess: guesses[2], Rank: 2, Points: 3631}, - {Guess: guesses[0], Rank: 3, Points: 3631}, - {Guess: guesses[3], Rank: 4, Points: 37}, - } - if !slices.Equal(got, want) { - t.Errorf("Rank = %+v\nwant %+v", got, want) - } - if guesses[0].User != "u_bob" { - t.Error("Rank changed its input") - } - if len(Rank(nil)) != 0 { - t.Error("Rank(nil) isn't empty") - } -} - -func TestDistance(t *testing.T) { - for _, tc := range []struct { - km float64 - want string - }{ - {0, "0 m"}, {0.0124, "12 m"}, {0.640, "640 m"}, {0.9996, "1.0 km"}, - {1, "1.0 km"}, {12.345, "12.3 km"}, {99.94, "99.9 km"}, {99.96, "100 km"}, - {640.4, "640 km"}, {9812.2, "9,812 km"}, {20015.1, "20,015 km"}, - } { - if got := Distance(tc.km); got != tc.want { - t.Errorf("Distance(%v) = %q, want %q", tc.km, got, tc.want) - } - } -} - -func TestThousands(t *testing.T) { - for n, want := range map[int]string{0: "0", 37: "37", 999: "999", 1000: "1,000", 4970: "4,970", 1234567: "1,234,567", -1234: "-1,234"} { - if got := Thousands(n); got != want { - t.Errorf("Thousands(%d) = %q, want %q", n, got, want) - } - } -} diff --git a/cmd/geoguess/geo/seeds.go b/cmd/geoguess/geo/seeds.go deleted file mode 100644 index f0fc3c5..0000000 --- a/cmd/geoguess/geo/seeds.go +++ /dev/null @@ -1,149 +0,0 @@ -package geo - -import ( - _ "embed" - "encoding/json" - "fmt" - "maps" - "math" - "math/rand/v2" - "slices" - "strings" -) - -// seedsJSON lists regions with street-level coverage, each a centre, a -// radius and a weight, with the continents their countries are in and a cap -// on any one country's total weight. -// -//go:embed seeds.json -var seedsJSON []byte - -// Seed is one region worth searching. -type Seed struct { - CC string `json:"cc"` // ISO 3166-1 alpha-2 - Lat float64 `json:"lat"` - Lon float64 `json:"lon"` - RadiusKm float64 `json:"radius_km"` - Weight float64 `json:"weight"` - Name string `json:"name"` // for people reading the file -} - -// Seeds are the regions a round's photo is looked for in, with the weights -// they are picked by after the per-country cap. -type Seeds struct { - list []Seed - weights []float64 // cumulative -} - -type seedFile struct { - CountryCap float64 `json:"country_cap"` - Continents map[string][]string `json:"continents"` - Seeds []Seed `json:"seeds"` -} - -// LoadSeeds is the embedded seeds, narrowed to regions: a comma-separated -// list of continents (europe, asia, africa, north-america, south-america, -// oceania) and ISO country codes, such as "europe" or "AU,NZ,JP". Empty is -// the whole world. A region with no seeds is an error. -func LoadSeeds(regions string) (*Seeds, error) { - var f seedFile - if err := json.Unmarshal(seedsJSON, &f); err != nil { - return nil, fmt.Errorf("seeds.json: %w", err) - } - want, err := countries(f.Continents, regions) - if err != nil { - return nil, err - } - var list []Seed - for _, s := range f.Seeds { - if want == nil || want[s.CC] { - list = append(list, s) - } - } - if len(list) == 0 { - return nil, fmt.Errorf("no seed regions in %q", regions) - } - return newSeeds(list, f.CountryCap), nil -} - -// countries is the set of country codes regions names, or nil for all. -func countries(continents map[string][]string, regions string) (map[string]bool, error) { - if strings.TrimSpace(regions) == "" { - return nil, nil - } - want := map[string]bool{} - for _, r := range strings.Split(regions, ",") { - r = strings.TrimSpace(r) - name := strings.NewReplacer(" ", "-", "_", "-").Replace(strings.ToLower(r)) - switch ccs, ok := continents[name]; { - case ok: - for _, cc := range ccs { - want[cc] = true - } - case len(r) == 2: - want[strings.ToUpper(r)] = true - case r != "": - return nil, fmt.Errorf("unknown region %q: use a continent (%s) or a two-letter country code", r, strings.Join(slices.Sorted(maps.Keys(continents)), ", ")) - } - } - return want, nil -} - -// newSeeds weighs list, scaling down each country whose seeds weigh more -// than countryCap in all, so a few countries don't take most rounds. -func newSeeds(list []Seed, countryCap float64) *Seeds { - total := map[string]float64{} - for _, s := range list { - total[s.CC] += s.Weight - } - s := &Seeds{list: list, weights: make([]float64, len(list))} - sum := 0.0 - for i, seed := range list { - w := seed.Weight - if countryCap > 0 && total[seed.CC] > countryCap { - w *= countryCap / total[seed.CC] - } - sum += w - s.weights[i] = sum - } - return s -} - -// Len is the number of seeds. -func (s *Seeds) Len() int { return len(s.list) } - -// Has reports whether any seed is in the country cc (ISO 3166-1 alpha-2), -// so a photo found for one round can be matched to another's regions. -func (s *Seeds) Has(cc string) bool { - return slices.ContainsFunc(s.list, func(seed Seed) bool { return seed.CC == cc }) -} - -// Pick is a seed chosen by weight. -func (s *Seeds) Pick(r *rand.Rand) Seed { - x := r.Float64() * s.weights[len(s.weights)-1] - i, _ := slices.BinarySearch(s.weights, x) - return s.list[min(i, len(s.list)-1)] -} - -// Point is a random point within the seed's radius, uniform over the disc. -func (s Seed) Point(r *rand.Rand) Point { - d := s.RadiusKm * math.Sqrt(r.Float64()) / earthRadius // radians - θ := 2 * math.Pi * r.Float64() - lat := s.Lat + degrees(d*math.Cos(θ)) - lon := s.Lon + degrees(d*math.Sin(θ))/math.Max(math.Cos(radians(s.Lat)), 0.01) - lat = math.Max(-89.9, math.Min(89.9, lat)) - lon = math.Mod(lon+540, 360) - 180 - return Point{Lat: lat, Lon: lon} -} - -// boxHalf is half a search box's side in degrees: a 0.04° square is -// 0.0016 deg², under Mapillary's limit of 0.01. -const boxHalf = 0.02 - -// Around is the search box centred on p. -func Around(p Point) BBox { - return BBox{ - MinLon: max(p.Lon-boxHalf, -180), MinLat: max(p.Lat-boxHalf, -90), - MaxLon: min(p.Lon+boxHalf, 180), MaxLat: min(p.Lat+boxHalf, 90), - } -} diff --git a/cmd/geoguess/geo/seeds.json b/cmd/geoguess/geo/seeds.json deleted file mode 100644 index 3d3f0e8..0000000 --- a/cmd/geoguess/geo/seeds.json +++ /dev/null @@ -1,310 +0,0 @@ -{ - "country_cap": 8, - "continents": { - "europe": ["GB", "IE", "FR", "BE", "NL", "LU", "DE", "CH", "AT", "IT", "ES", "PT", "DK", "NO", "SE", "FI", "IS", "EE", "LV", "LT", "PL", "CZ", "SK", "HU", "SI", "HR", "RS", "BA", "ME", "MK", "AL", "GR", "BG", "RO", "MD", "UA", "CY", "MT"], - "asia": ["TR", "GE", "AM", "IL", "JO", "AE", "QA", "SA", "OM", "KZ", "UZ", "KG", "MN", "IN", "LK", "NP", "BD", "PK", "TH", "VN", "KH", "LA", "MY", "SG", "ID", "PH", "TW", "JP", "KR", "HK"], - "africa": ["ZA", "NA", "BW", "KE", "TZ", "UG", "RW", "ET", "GH", "NG", "SN", "CI", "MA", "TN", "EG", "MG", "MU", "RE"], - "north-america": ["US", "CA", "MX", "GT", "CR", "PA", "CU", "DO", "PR"], - "south-america": ["CO", "EC", "PE", "BO", "CL", "AR", "UY", "PY", "BR"], - "oceania": ["AU", "NZ"] - }, - "seeds": [ - {"cc": "AU", "lat": -37.81, "lon": 144.96, "radius_km": 40, "weight": 3, "name": "Melbourne"}, - {"cc": "AU", "lat": -33.87, "lon": 151.21, "radius_km": 40, "weight": 3, "name": "Sydney"}, - {"cc": "AU", "lat": -27.47, "lon": 153.03, "radius_km": 35, "weight": 2, "name": "Brisbane"}, - {"cc": "AU", "lat": -31.95, "lon": 115.86, "radius_km": 35, "weight": 2, "name": "Perth"}, - {"cc": "AU", "lat": -34.93, "lon": 138.6, "radius_km": 30, "weight": 2, "name": "Adelaide"}, - {"cc": "AU", "lat": -42.88, "lon": 147.33, "radius_km": 25, "weight": 1, "name": "Hobart"}, - {"cc": "AU", "lat": -37.56, "lon": 143.85, "radius_km": 20, "weight": 1, "name": "Ballarat"}, - {"cc": "AU", "lat": -19.26, "lon": 146.82, "radius_km": 20, "weight": 1, "name": "Townsville"}, - {"cc": "AU", "lat": -35.28, "lon": 149.13, "radius_km": 20, "weight": 1, "name": "Canberra"}, - {"cc": "AU", "lat": -38.15, "lon": 144.36, "radius_km": 20, "weight": 2, "name": "Geelong"}, - {"cc": "AU", "lat": -36.76, "lon": 144.28, "radius_km": 15, "weight": 1, "name": "Bendigo"}, - {"cc": "AU", "lat": -38.37, "lon": 145.03, "radius_km": 20, "weight": 1, "name": "Mornington Peninsula"}, - {"cc": "AU", "lat": -38.76, "lon": 143.67, "radius_km": 25, "weight": 1, "name": "Great Ocean Road"}, - {"cc": "AU", "lat": -37.65, "lon": 145.52, "radius_km": 20, "weight": 1, "name": "Yarra Valley"}, - {"cc": "AU", "lat": -36.36, "lon": 146.31, "radius_km": 15, "weight": 1, "name": "Wangaratta"}, - {"cc": "AU", "lat": -34.21, "lon": 142.14, "radius_km": 15, "weight": 1, "name": "Mildura"}, - {"cc": "AU", "lat": -38.38, "lon": 142.48, "radius_km": 15, "weight": 1, "name": "Warrnambool"}, - {"cc": "AU", "lat": -38.11, "lon": 147.07, "radius_km": 20, "weight": 1, "name": "Sale"}, - {"cc": "AU", "lat": -32.93, "lon": 151.78, "radius_km": 25, "weight": 2, "name": "Newcastle"}, - {"cc": "AU", "lat": -34.42, "lon": 150.89, "radius_km": 20, "weight": 2, "name": "Wollongong"}, - {"cc": "AU", "lat": -33.71, "lon": 150.31, "radius_km": 20, "weight": 1, "name": "Blue Mountains"}, - {"cc": "AU", "lat": -28.64, "lon": 153.61, "radius_km": 20, "weight": 1, "name": "Byron Bay"}, - {"cc": "AU", "lat": -32.83, "lon": 151.36, "radius_km": 20, "weight": 1, "name": "Hunter Valley"}, - {"cc": "AU", "lat": -35.12, "lon": 147.37, "radius_km": 15, "weight": 1, "name": "Wagga Wagga"}, - {"cc": "AU", "lat": -32.25, "lon": 148.6, "radius_km": 15, "weight": 1, "name": "Dubbo"}, - {"cc": "AU", "lat": -31.95, "lon": 141.47, "radius_km": 15, "weight": 1, "name": "Broken Hill"}, - {"cc": "AU", "lat": -30.3, "lon": 153.11, "radius_km": 20, "weight": 1, "name": "Coffs Harbour"}, - {"cc": "AU", "lat": -36.08, "lon": 146.92, "radius_km": 15, "weight": 1, "name": "Albury"}, - {"cc": "AU", "lat": -31.43, "lon": 152.91, "radius_km": 15, "weight": 1, "name": "Port Macquarie"}, - {"cc": "AU", "lat": -28.02, "lon": 153.4, "radius_km": 25, "weight": 2, "name": "Gold Coast"}, - {"cc": "AU", "lat": -26.65, "lon": 153.07, "radius_km": 25, "weight": 2, "name": "Sunshine Coast"}, - {"cc": "AU", "lat": -16.92, "lon": 145.77, "radius_km": 20, "weight": 1, "name": "Cairns"}, - {"cc": "AU", "lat": -27.56, "lon": 151.95, "radius_km": 15, "weight": 1, "name": "Toowoomba"}, - {"cc": "AU", "lat": -23.38, "lon": 150.51, "radius_km": 15, "weight": 1, "name": "Rockhampton"}, - {"cc": "AU", "lat": -21.14, "lon": 149.19, "radius_km": 15, "weight": 1, "name": "Mackay"}, - {"cc": "AU", "lat": -20.73, "lon": 139.49, "radius_km": 10, "weight": 1, "name": "Mount Isa"}, - {"cc": "AU", "lat": -34.52, "lon": 138.96, "radius_km": 20, "weight": 1, "name": "Barossa Valley"}, - {"cc": "AU", "lat": -37.83, "lon": 140.78, "radius_km": 15, "weight": 1, "name": "Mount Gambier"}, - {"cc": "AU", "lat": -35.55, "lon": 138.62, "radius_km": 15, "weight": 1, "name": "Victor Harbor"}, - {"cc": "AU", "lat": -32.06, "lon": 115.75, "radius_km": 10, "weight": 1, "name": "Fremantle"}, - {"cc": "AU", "lat": -33.95, "lon": 115.07, "radius_km": 25, "weight": 1, "name": "Margaret River"}, - {"cc": "AU", "lat": -33.33, "lon": 115.64, "radius_km": 15, "weight": 1, "name": "Bunbury"}, - {"cc": "AU", "lat": -35.02, "lon": 117.88, "radius_km": 15, "weight": 1, "name": "Albany"}, - {"cc": "AU", "lat": -30.75, "lon": 121.47, "radius_km": 10, "weight": 1, "name": "Kalgoorlie"}, - {"cc": "AU", "lat": -28.77, "lon": 114.61, "radius_km": 15, "weight": 1, "name": "Geraldton"}, - {"cc": "AU", "lat": -17.96, "lon": 122.24, "radius_km": 10, "weight": 1, "name": "Broome"}, - {"cc": "AU", "lat": -12.46, "lon": 130.84, "radius_km": 20, "weight": 2, "name": "Darwin"}, - {"cc": "AU", "lat": -23.7, "lon": 133.88, "radius_km": 10, "weight": 1, "name": "Alice Springs"}, - {"cc": "AU", "lat": -41.44, "lon": 147.14, "radius_km": 15, "weight": 1, "name": "Launceston"}, - {"cc": "NZ", "lat": -36.85, "lon": 174.76, "radius_km": 30, "weight": 2, "name": "Auckland"}, - {"cc": "NZ", "lat": -41.29, "lon": 174.78, "radius_km": 20, "weight": 1, "name": "Wellington"}, - {"cc": "NZ", "lat": -43.53, "lon": 172.64, "radius_km": 25, "weight": 1, "name": "Christchurch"}, - {"cc": "NZ", "lat": -45.03, "lon": 168.66, "radius_km": 20, "weight": 1, "name": "Queenstown"}, - {"cc": "US", "lat": 40.71, "lon": -74.0, "radius_km": 25, "weight": 2, "name": "New York"}, - {"cc": "US", "lat": 34.05, "lon": -118.24, "radius_km": 40, "weight": 2, "name": "Los Angeles"}, - {"cc": "US", "lat": 41.88, "lon": -87.63, "radius_km": 30, "weight": 2, "name": "Chicago"}, - {"cc": "US", "lat": 29.76, "lon": -95.37, "radius_km": 35, "weight": 1, "name": "Houston"}, - {"cc": "US", "lat": 33.45, "lon": -112.07, "radius_km": 35, "weight": 1, "name": "Phoenix"}, - {"cc": "US", "lat": 47.61, "lon": -122.33, "radius_km": 30, "weight": 2, "name": "Seattle"}, - {"cc": "US", "lat": 37.77, "lon": -122.42, "radius_km": 25, "weight": 2, "name": "San Francisco"}, - {"cc": "US", "lat": 39.74, "lon": -104.99, "radius_km": 30, "weight": 1, "name": "Denver"}, - {"cc": "US", "lat": 25.76, "lon": -80.19, "radius_km": 30, "weight": 1, "name": "Miami"}, - {"cc": "US", "lat": 42.36, "lon": -71.06, "radius_km": 25, "weight": 1, "name": "Boston"}, - {"cc": "US", "lat": 36.17, "lon": -115.14, "radius_km": 25, "weight": 1, "name": "Las Vegas"}, - {"cc": "US", "lat": 45.52, "lon": -122.68, "radius_km": 25, "weight": 1, "name": "Portland"}, - {"cc": "US", "lat": 30.27, "lon": -97.74, "radius_km": 25, "weight": 1, "name": "Austin"}, - {"cc": "US", "lat": 35.23, "lon": -80.84, "radius_km": 25, "weight": 1, "name": "Charlotte"}, - {"cc": "US", "lat": 44.98, "lon": -93.27, "radius_km": 25, "weight": 1, "name": "Minneapolis"}, - {"cc": "US", "lat": 21.31, "lon": -157.86, "radius_km": 20, "weight": 1, "name": "Honolulu"}, - {"cc": "US", "lat": 61.22, "lon": -149.9, "radius_km": 15, "weight": 1, "name": "Anchorage"}, - {"cc": "US", "lat": 35.08, "lon": -106.65, "radius_km": 20, "weight": 1, "name": "Albuquerque"}, - {"cc": "CA", "lat": 43.65, "lon": -79.38, "radius_km": 30, "weight": 2, "name": "Toronto"}, - {"cc": "CA", "lat": 45.5, "lon": -73.57, "radius_km": 25, "weight": 2, "name": "Montreal"}, - {"cc": "CA", "lat": 49.28, "lon": -123.12, "radius_km": 25, "weight": 2, "name": "Vancouver"}, - {"cc": "CA", "lat": 51.05, "lon": -114.07, "radius_km": 25, "weight": 1, "name": "Calgary"}, - {"cc": "CA", "lat": 46.81, "lon": -71.21, "radius_km": 20, "weight": 1, "name": "Quebec City"}, - {"cc": "CA", "lat": 44.65, "lon": -63.57, "radius_km": 20, "weight": 1, "name": "Halifax"}, - {"cc": "MX", "lat": 19.43, "lon": -99.13, "radius_km": 30, "weight": 2, "name": "Mexico City"}, - {"cc": "MX", "lat": 20.67, "lon": -103.35, "radius_km": 25, "weight": 1, "name": "Guadalajara"}, - {"cc": "MX", "lat": 25.69, "lon": -100.32, "radius_km": 25, "weight": 1, "name": "Monterrey"}, - {"cc": "MX", "lat": 21.16, "lon": -86.85, "radius_km": 20, "weight": 1, "name": "Cancun"}, - {"cc": "MX", "lat": 17.07, "lon": -96.72, "radius_km": 15, "weight": 1, "name": "Oaxaca"}, - {"cc": "GT", "lat": 14.63, "lon": -90.51, "radius_km": 15, "weight": 1, "name": "Guatemala City"}, - {"cc": "CR", "lat": 9.93, "lon": -84.08, "radius_km": 20, "weight": 1, "name": "San Jose"}, - {"cc": "PA", "lat": 8.98, "lon": -79.52, "radius_km": 15, "weight": 1, "name": "Panama City"}, - {"cc": "CU", "lat": 23.11, "lon": -82.37, "radius_km": 15, "weight": 1, "name": "Havana"}, - {"cc": "DO", "lat": 18.49, "lon": -69.93, "radius_km": 15, "weight": 1, "name": "Santo Domingo"}, - {"cc": "PR", "lat": 18.47, "lon": -66.11, "radius_km": 20, "weight": 1, "name": "San Juan"}, - {"cc": "CO", "lat": 4.71, "lon": -74.07, "radius_km": 25, "weight": 2, "name": "Bogota"}, - {"cc": "CO", "lat": 6.24, "lon": -75.58, "radius_km": 20, "weight": 1, "name": "Medellin"}, - {"cc": "EC", "lat": -0.18, "lon": -78.47, "radius_km": 15, "weight": 1, "name": "Quito"}, - {"cc": "PE", "lat": -12.05, "lon": -77.04, "radius_km": 25, "weight": 2, "name": "Lima"}, - {"cc": "PE", "lat": -13.53, "lon": -71.97, "radius_km": 15, "weight": 1, "name": "Cusco"}, - {"cc": "BO", "lat": -16.5, "lon": -68.15, "radius_km": 15, "weight": 1, "name": "La Paz"}, - {"cc": "CL", "lat": -33.45, "lon": -70.67, "radius_km": 30, "weight": 2, "name": "Santiago"}, - {"cc": "CL", "lat": -36.83, "lon": -73.05, "radius_km": 20, "weight": 1, "name": "Concepcion"}, - {"cc": "CL", "lat": -41.47, "lon": -72.94, "radius_km": 20, "weight": 1, "name": "Puerto Montt"}, - {"cc": "AR", "lat": -34.6, "lon": -58.38, "radius_km": 30, "weight": 2, "name": "Buenos Aires"}, - {"cc": "AR", "lat": -31.42, "lon": -64.18, "radius_km": 25, "weight": 1, "name": "Cordoba"}, - {"cc": "AR", "lat": -32.89, "lon": -68.84, "radius_km": 20, "weight": 1, "name": "Mendoza"}, - {"cc": "AR", "lat": -41.13, "lon": -71.31, "radius_km": 15, "weight": 1, "name": "Bariloche"}, - {"cc": "UY", "lat": -34.9, "lon": -56.16, "radius_km": 20, "weight": 1, "name": "Montevideo"}, - {"cc": "PY", "lat": -25.26, "lon": -57.58, "radius_km": 15, "weight": 1, "name": "Asuncion"}, - {"cc": "BR", "lat": -23.55, "lon": -46.63, "radius_km": 35, "weight": 3, "name": "Sao Paulo"}, - {"cc": "BR", "lat": -22.91, "lon": -43.17, "radius_km": 30, "weight": 2, "name": "Rio de Janeiro"}, - {"cc": "BR", "lat": -15.79, "lon": -47.88, "radius_km": 25, "weight": 1, "name": "Brasilia"}, - {"cc": "BR", "lat": -30.03, "lon": -51.23, "radius_km": 25, "weight": 1, "name": "Porto Alegre"}, - {"cc": "BR", "lat": -25.43, "lon": -49.27, "radius_km": 25, "weight": 1, "name": "Curitiba"}, - {"cc": "BR", "lat": -12.97, "lon": -38.5, "radius_km": 25, "weight": 1, "name": "Salvador"}, - {"cc": "BR", "lat": -3.73, "lon": -38.52, "radius_km": 20, "weight": 1, "name": "Fortaleza"}, - {"cc": "BR", "lat": -19.92, "lon": -43.94, "radius_km": 25, "weight": 1, "name": "Belo Horizonte"}, - {"cc": "GB", "lat": 51.51, "lon": -0.13, "radius_km": 30, "weight": 3, "name": "London"}, - {"cc": "GB", "lat": 53.48, "lon": -2.24, "radius_km": 25, "weight": 2, "name": "Manchester"}, - {"cc": "GB", "lat": 55.95, "lon": -3.19, "radius_km": 20, "weight": 1, "name": "Edinburgh"}, - {"cc": "GB", "lat": 52.49, "lon": -1.89, "radius_km": 25, "weight": 1, "name": "Birmingham"}, - {"cc": "GB", "lat": 51.45, "lon": -2.59, "radius_km": 20, "weight": 1, "name": "Bristol"}, - {"cc": "GB", "lat": 57.48, "lon": -4.22, "radius_km": 30, "weight": 1, "name": "Inverness"}, - {"cc": "GB", "lat": 54.6, "lon": -5.93, "radius_km": 20, "weight": 1, "name": "Belfast"}, - {"cc": "IE", "lat": 53.35, "lon": -6.26, "radius_km": 25, "weight": 2, "name": "Dublin"}, - {"cc": "IE", "lat": 51.9, "lon": -8.47, "radius_km": 20, "weight": 1, "name": "Cork"}, - {"cc": "IE", "lat": 53.27, "lon": -9.05, "radius_km": 25, "weight": 1, "name": "Galway"}, - {"cc": "FR", "lat": 48.86, "lon": 2.35, "radius_km": 25, "weight": 3, "name": "Paris"}, - {"cc": "FR", "lat": 45.76, "lon": 4.84, "radius_km": 25, "weight": 2, "name": "Lyon"}, - {"cc": "FR", "lat": 43.3, "lon": 5.37, "radius_km": 25, "weight": 2, "name": "Marseille"}, - {"cc": "FR", "lat": 44.84, "lon": -0.58, "radius_km": 25, "weight": 1, "name": "Bordeaux"}, - {"cc": "FR", "lat": 48.11, "lon": -1.68, "radius_km": 25, "weight": 2, "name": "Rennes"}, - {"cc": "FR", "lat": 43.6, "lon": 1.44, "radius_km": 25, "weight": 1, "name": "Toulouse"}, - {"cc": "FR", "lat": 47.22, "lon": -1.55, "radius_km": 25, "weight": 1, "name": "Nantes"}, - {"cc": "FR", "lat": 48.57, "lon": 7.75, "radius_km": 20, "weight": 1, "name": "Strasbourg"}, - {"cc": "FR", "lat": 45.19, "lon": 5.72, "radius_km": 25, "weight": 1, "name": "Grenoble"}, - {"cc": "FR", "lat": 43.7, "lon": 7.27, "radius_km": 20, "weight": 1, "name": "Nice"}, - {"cc": "FR", "lat": 50.63, "lon": 3.06, "radius_km": 20, "weight": 1, "name": "Lille"}, - {"cc": "FR", "lat": 48.39, "lon": -4.49, "radius_km": 30, "weight": 1, "name": "Brest"}, - {"cc": "BE", "lat": 50.85, "lon": 4.35, "radius_km": 20, "weight": 2, "name": "Brussels"}, - {"cc": "BE", "lat": 51.05, "lon": 3.72, "radius_km": 20, "weight": 1, "name": "Ghent"}, - {"cc": "NL", "lat": 52.37, "lon": 4.9, "radius_km": 25, "weight": 2, "name": "Amsterdam"}, - {"cc": "NL", "lat": 51.92, "lon": 4.48, "radius_km": 20, "weight": 1, "name": "Rotterdam"}, - {"cc": "NL", "lat": 52.09, "lon": 5.12, "radius_km": 20, "weight": 1, "name": "Utrecht"}, - {"cc": "NL", "lat": 53.22, "lon": 6.57, "radius_km": 20, "weight": 1, "name": "Groningen"}, - {"cc": "LU", "lat": 49.61, "lon": 6.13, "radius_km": 15, "weight": 1, "name": "Luxembourg"}, - {"cc": "DE", "lat": 52.52, "lon": 13.4, "radius_km": 30, "weight": 3, "name": "Berlin"}, - {"cc": "DE", "lat": 48.14, "lon": 11.58, "radius_km": 30, "weight": 2, "name": "Munich"}, - {"cc": "DE", "lat": 53.55, "lon": 9.99, "radius_km": 25, "weight": 2, "name": "Hamburg"}, - {"cc": "DE", "lat": 50.94, "lon": 6.96, "radius_km": 25, "weight": 2, "name": "Cologne"}, - {"cc": "DE", "lat": 50.11, "lon": 8.68, "radius_km": 25, "weight": 1, "name": "Frankfurt"}, - {"cc": "DE", "lat": 48.78, "lon": 9.18, "radius_km": 25, "weight": 1, "name": "Stuttgart"}, - {"cc": "DE", "lat": 51.34, "lon": 12.37, "radius_km": 20, "weight": 1, "name": "Leipzig"}, - {"cc": "DE", "lat": 51.05, "lon": 13.74, "radius_km": 20, "weight": 1, "name": "Dresden"}, - {"cc": "DE", "lat": 47.99, "lon": 7.84, "radius_km": 20, "weight": 1, "name": "Freiburg"}, - {"cc": "CH", "lat": 47.38, "lon": 8.54, "radius_km": 20, "weight": 2, "name": "Zurich"}, - {"cc": "CH", "lat": 46.2, "lon": 6.14, "radius_km": 20, "weight": 1, "name": "Geneva"}, - {"cc": "CH", "lat": 46.95, "lon": 7.45, "radius_km": 20, "weight": 1, "name": "Bern"}, - {"cc": "AT", "lat": 48.21, "lon": 16.37, "radius_km": 25, "weight": 2, "name": "Vienna"}, - {"cc": "AT", "lat": 47.27, "lon": 11.39, "radius_km": 20, "weight": 1, "name": "Innsbruck"}, - {"cc": "AT", "lat": 47.81, "lon": 13.04, "radius_km": 20, "weight": 1, "name": "Salzburg"}, - {"cc": "IT", "lat": 41.9, "lon": 12.5, "radius_km": 25, "weight": 2, "name": "Rome"}, - {"cc": "IT", "lat": 45.46, "lon": 9.19, "radius_km": 25, "weight": 2, "name": "Milan"}, - {"cc": "IT", "lat": 40.85, "lon": 14.27, "radius_km": 20, "weight": 1, "name": "Naples"}, - {"cc": "IT", "lat": 43.77, "lon": 11.26, "radius_km": 20, "weight": 1, "name": "Florence"}, - {"cc": "IT", "lat": 45.44, "lon": 12.32, "radius_km": 15, "weight": 1, "name": "Venice"}, - {"cc": "IT", "lat": 45.07, "lon": 7.69, "radius_km": 20, "weight": 1, "name": "Turin"}, - {"cc": "IT", "lat": 38.12, "lon": 13.36, "radius_km": 20, "weight": 1, "name": "Palermo"}, - {"cc": "IT", "lat": 44.49, "lon": 11.34, "radius_km": 20, "weight": 1, "name": "Bologna"}, - {"cc": "ES", "lat": 40.42, "lon": -3.7, "radius_km": 30, "weight": 2, "name": "Madrid"}, - {"cc": "ES", "lat": 41.39, "lon": 2.17, "radius_km": 25, "weight": 2, "name": "Barcelona"}, - {"cc": "ES", "lat": 37.39, "lon": -5.98, "radius_km": 20, "weight": 1, "name": "Seville"}, - {"cc": "ES", "lat": 39.47, "lon": -0.38, "radius_km": 20, "weight": 1, "name": "Valencia"}, - {"cc": "ES", "lat": 43.26, "lon": -2.93, "radius_km": 20, "weight": 1, "name": "Bilbao"}, - {"cc": "ES", "lat": 42.88, "lon": -8.54, "radius_km": 20, "weight": 1, "name": "Santiago de Compostela"}, - {"cc": "ES", "lat": 28.12, "lon": -15.43, "radius_km": 20, "weight": 1, "name": "Las Palmas"}, - {"cc": "PT", "lat": 38.72, "lon": -9.14, "radius_km": 25, "weight": 2, "name": "Lisbon"}, - {"cc": "PT", "lat": 41.15, "lon": -8.61, "radius_km": 20, "weight": 1, "name": "Porto"}, - {"cc": "PT", "lat": 37.02, "lon": -7.93, "radius_km": 25, "weight": 1, "name": "Faro"}, - {"cc": "DK", "lat": 55.68, "lon": 12.57, "radius_km": 20, "weight": 2, "name": "Copenhagen"}, - {"cc": "DK", "lat": 56.16, "lon": 10.2, "radius_km": 20, "weight": 1, "name": "Aarhus"}, - {"cc": "NO", "lat": 59.91, "lon": 10.75, "radius_km": 25, "weight": 2, "name": "Oslo"}, - {"cc": "NO", "lat": 60.39, "lon": 5.32, "radius_km": 20, "weight": 1, "name": "Bergen"}, - {"cc": "NO", "lat": 63.43, "lon": 10.4, "radius_km": 20, "weight": 1, "name": "Trondheim"}, - {"cc": "NO", "lat": 69.65, "lon": 18.96, "radius_km": 15, "weight": 1, "name": "Tromso"}, - {"cc": "SE", "lat": 59.33, "lon": 18.07, "radius_km": 25, "weight": 2, "name": "Stockholm"}, - {"cc": "SE", "lat": 57.71, "lon": 11.97, "radius_km": 20, "weight": 1, "name": "Gothenburg"}, - {"cc": "SE", "lat": 55.6, "lon": 13.0, "radius_km": 20, "weight": 1, "name": "Malmo"}, - {"cc": "FI", "lat": 60.17, "lon": 24.94, "radius_km": 25, "weight": 2, "name": "Helsinki"}, - {"cc": "FI", "lat": 61.5, "lon": 23.76, "radius_km": 20, "weight": 1, "name": "Tampere"}, - {"cc": "FI", "lat": 65.01, "lon": 25.47, "radius_km": 20, "weight": 1, "name": "Oulu"}, - {"cc": "IS", "lat": 64.15, "lon": -21.94, "radius_km": 20, "weight": 1, "name": "Reykjavik"}, - {"cc": "EE", "lat": 59.44, "lon": 24.75, "radius_km": 20, "weight": 1, "name": "Tallinn"}, - {"cc": "LV", "lat": 56.95, "lon": 24.11, "radius_km": 20, "weight": 1, "name": "Riga"}, - {"cc": "LT", "lat": 54.69, "lon": 25.28, "radius_km": 20, "weight": 1, "name": "Vilnius"}, - {"cc": "PL", "lat": 52.23, "lon": 21.01, "radius_km": 25, "weight": 2, "name": "Warsaw"}, - {"cc": "PL", "lat": 50.06, "lon": 19.94, "radius_km": 20, "weight": 1, "name": "Krakow"}, - {"cc": "PL", "lat": 51.11, "lon": 17.04, "radius_km": 20, "weight": 1, "name": "Wroclaw"}, - {"cc": "PL", "lat": 54.35, "lon": 18.65, "radius_km": 20, "weight": 1, "name": "Gdansk"}, - {"cc": "CZ", "lat": 50.08, "lon": 14.44, "radius_km": 25, "weight": 2, "name": "Prague"}, - {"cc": "CZ", "lat": 49.2, "lon": 16.61, "radius_km": 20, "weight": 1, "name": "Brno"}, - {"cc": "SK", "lat": 48.15, "lon": 17.11, "radius_km": 20, "weight": 1, "name": "Bratislava"}, - {"cc": "HU", "lat": 47.5, "lon": 19.04, "radius_km": 25, "weight": 2, "name": "Budapest"}, - {"cc": "SI", "lat": 46.06, "lon": 14.51, "radius_km": 20, "weight": 1, "name": "Ljubljana"}, - {"cc": "HR", "lat": 45.81, "lon": 15.98, "radius_km": 20, "weight": 1, "name": "Zagreb"}, - {"cc": "HR", "lat": 43.51, "lon": 16.44, "radius_km": 20, "weight": 1, "name": "Split"}, - {"cc": "RS", "lat": 44.79, "lon": 20.45, "radius_km": 20, "weight": 1, "name": "Belgrade"}, - {"cc": "BA", "lat": 43.86, "lon": 18.41, "radius_km": 15, "weight": 1, "name": "Sarajevo"}, - {"cc": "ME", "lat": 42.43, "lon": 19.26, "radius_km": 15, "weight": 1, "name": "Podgorica"}, - {"cc": "MK", "lat": 41.99, "lon": 21.43, "radius_km": 15, "weight": 1, "name": "Skopje"}, - {"cc": "AL", "lat": 41.33, "lon": 19.82, "radius_km": 15, "weight": 1, "name": "Tirana"}, - {"cc": "GR", "lat": 37.98, "lon": 23.73, "radius_km": 25, "weight": 2, "name": "Athens"}, - {"cc": "GR", "lat": 40.64, "lon": 22.94, "radius_km": 20, "weight": 1, "name": "Thessaloniki"}, - {"cc": "GR", "lat": 35.34, "lon": 25.13, "radius_km": 20, "weight": 1, "name": "Heraklion"}, - {"cc": "BG", "lat": 42.7, "lon": 23.32, "radius_km": 20, "weight": 1, "name": "Sofia"}, - {"cc": "RO", "lat": 44.43, "lon": 26.1, "radius_km": 25, "weight": 1, "name": "Bucharest"}, - {"cc": "RO", "lat": 46.77, "lon": 23.59, "radius_km": 20, "weight": 1, "name": "Cluj-Napoca"}, - {"cc": "MD", "lat": 47.01, "lon": 28.86, "radius_km": 15, "weight": 1, "name": "Chisinau"}, - {"cc": "UA", "lat": 50.45, "lon": 30.52, "radius_km": 25, "weight": 1, "name": "Kyiv"}, - {"cc": "UA", "lat": 49.84, "lon": 24.03, "radius_km": 20, "weight": 1, "name": "Lviv"}, - {"cc": "CY", "lat": 34.68, "lon": 33.04, "radius_km": 20, "weight": 1, "name": "Limassol"}, - {"cc": "MT", "lat": 35.9, "lon": 14.51, "radius_km": 10, "weight": 1, "name": "Valletta"}, - {"cc": "TR", "lat": 41.01, "lon": 28.98, "radius_km": 30, "weight": 2, "name": "Istanbul"}, - {"cc": "TR", "lat": 39.93, "lon": 32.86, "radius_km": 25, "weight": 1, "name": "Ankara"}, - {"cc": "TR", "lat": 38.42, "lon": 27.14, "radius_km": 20, "weight": 1, "name": "Izmir"}, - {"cc": "TR", "lat": 36.9, "lon": 30.7, "radius_km": 20, "weight": 1, "name": "Antalya"}, - {"cc": "GE", "lat": 41.72, "lon": 44.79, "radius_km": 15, "weight": 1, "name": "Tbilisi"}, - {"cc": "AM", "lat": 40.18, "lon": 44.51, "radius_km": 15, "weight": 1, "name": "Yerevan"}, - {"cc": "IL", "lat": 32.08, "lon": 34.78, "radius_km": 20, "weight": 1, "name": "Tel Aviv"}, - {"cc": "JO", "lat": 31.95, "lon": 35.93, "radius_km": 20, "weight": 1, "name": "Amman"}, - {"cc": "AE", "lat": 25.2, "lon": 55.27, "radius_km": 25, "weight": 1, "name": "Dubai"}, - {"cc": "QA", "lat": 25.29, "lon": 51.53, "radius_km": 15, "weight": 1, "name": "Doha"}, - {"cc": "SA", "lat": 24.71, "lon": 46.68, "radius_km": 25, "weight": 1, "name": "Riyadh"}, - {"cc": "OM", "lat": 23.59, "lon": 58.41, "radius_km": 20, "weight": 1, "name": "Muscat"}, - {"cc": "KZ", "lat": 43.24, "lon": 76.89, "radius_km": 20, "weight": 1, "name": "Almaty"}, - {"cc": "UZ", "lat": 41.3, "lon": 69.24, "radius_km": 20, "weight": 1, "name": "Tashkent"}, - {"cc": "KG", "lat": 42.87, "lon": 74.59, "radius_km": 15, "weight": 1, "name": "Bishkek"}, - {"cc": "MN", "lat": 47.89, "lon": 106.91, "radius_km": 15, "weight": 1, "name": "Ulaanbaatar"}, - {"cc": "IN", "lat": 28.61, "lon": 77.21, "radius_km": 30, "weight": 2, "name": "Delhi"}, - {"cc": "IN", "lat": 19.08, "lon": 72.88, "radius_km": 30, "weight": 2, "name": "Mumbai"}, - {"cc": "IN", "lat": 12.97, "lon": 77.59, "radius_km": 30, "weight": 2, "name": "Bengaluru"}, - {"cc": "IN", "lat": 13.08, "lon": 80.27, "radius_km": 25, "weight": 1, "name": "Chennai"}, - {"cc": "IN", "lat": 22.57, "lon": 88.36, "radius_km": 25, "weight": 1, "name": "Kolkata"}, - {"cc": "IN", "lat": 17.39, "lon": 78.49, "radius_km": 25, "weight": 1, "name": "Hyderabad"}, - {"cc": "IN", "lat": 18.52, "lon": 73.86, "radius_km": 25, "weight": 1, "name": "Pune"}, - {"cc": "IN", "lat": 26.91, "lon": 75.79, "radius_km": 20, "weight": 1, "name": "Jaipur"}, - {"cc": "IN", "lat": 9.93, "lon": 76.27, "radius_km": 20, "weight": 1, "name": "Kochi"}, - {"cc": "LK", "lat": 6.93, "lon": 79.86, "radius_km": 20, "weight": 1, "name": "Colombo"}, - {"cc": "NP", "lat": 27.72, "lon": 85.32, "radius_km": 15, "weight": 1, "name": "Kathmandu"}, - {"cc": "BD", "lat": 23.81, "lon": 90.41, "radius_km": 20, "weight": 1, "name": "Dhaka"}, - {"cc": "PK", "lat": 31.52, "lon": 74.36, "radius_km": 20, "weight": 1, "name": "Lahore"}, - {"cc": "TH", "lat": 13.76, "lon": 100.5, "radius_km": 30, "weight": 2, "name": "Bangkok"}, - {"cc": "TH", "lat": 18.79, "lon": 98.99, "radius_km": 20, "weight": 1, "name": "Chiang Mai"}, - {"cc": "TH", "lat": 7.88, "lon": 98.39, "radius_km": 20, "weight": 1, "name": "Phuket"}, - {"cc": "VN", "lat": 21.03, "lon": 105.85, "radius_km": 25, "weight": 1, "name": "Hanoi"}, - {"cc": "VN", "lat": 10.82, "lon": 106.63, "radius_km": 25, "weight": 1, "name": "Ho Chi Minh City"}, - {"cc": "VN", "lat": 16.05, "lon": 108.22, "radius_km": 20, "weight": 1, "name": "Da Nang"}, - {"cc": "KH", "lat": 11.56, "lon": 104.92, "radius_km": 15, "weight": 1, "name": "Phnom Penh"}, - {"cc": "LA", "lat": 17.98, "lon": 102.63, "radius_km": 15, "weight": 1, "name": "Vientiane"}, - {"cc": "MY", "lat": 3.14, "lon": 101.69, "radius_km": 25, "weight": 2, "name": "Kuala Lumpur"}, - {"cc": "MY", "lat": 5.41, "lon": 100.33, "radius_km": 20, "weight": 1, "name": "Penang"}, - {"cc": "SG", "lat": 1.35, "lon": 103.82, "radius_km": 15, "weight": 2, "name": "Singapore"}, - {"cc": "ID", "lat": -6.21, "lon": 106.85, "radius_km": 30, "weight": 2, "name": "Jakarta"}, - {"cc": "ID", "lat": -8.65, "lon": 115.22, "radius_km": 25, "weight": 1, "name": "Bali"}, - {"cc": "ID", "lat": -7.8, "lon": 110.36, "radius_km": 20, "weight": 1, "name": "Yogyakarta"}, - {"cc": "ID", "lat": -7.26, "lon": 112.75, "radius_km": 20, "weight": 1, "name": "Surabaya"}, - {"cc": "PH", "lat": 14.6, "lon": 120.98, "radius_km": 25, "weight": 2, "name": "Manila"}, - {"cc": "PH", "lat": 10.32, "lon": 123.89, "radius_km": 20, "weight": 1, "name": "Cebu"}, - {"cc": "TW", "lat": 25.03, "lon": 121.57, "radius_km": 25, "weight": 2, "name": "Taipei"}, - {"cc": "TW", "lat": 22.63, "lon": 120.3, "radius_km": 20, "weight": 1, "name": "Kaohsiung"}, - {"cc": "JP", "lat": 35.68, "lon": 139.69, "radius_km": 35, "weight": 3, "name": "Tokyo"}, - {"cc": "JP", "lat": 34.69, "lon": 135.5, "radius_km": 30, "weight": 2, "name": "Osaka"}, - {"cc": "JP", "lat": 35.01, "lon": 135.77, "radius_km": 20, "weight": 1, "name": "Kyoto"}, - {"cc": "JP", "lat": 43.06, "lon": 141.35, "radius_km": 25, "weight": 1, "name": "Sapporo"}, - {"cc": "JP", "lat": 33.59, "lon": 130.4, "radius_km": 25, "weight": 1, "name": "Fukuoka"}, - {"cc": "JP", "lat": 35.18, "lon": 136.91, "radius_km": 25, "weight": 1, "name": "Nagoya"}, - {"cc": "JP", "lat": 34.39, "lon": 132.46, "radius_km": 20, "weight": 1, "name": "Hiroshima"}, - {"cc": "JP", "lat": 38.27, "lon": 140.87, "radius_km": 20, "weight": 1, "name": "Sendai"}, - {"cc": "KR", "lat": 37.57, "lon": 126.98, "radius_km": 30, "weight": 2, "name": "Seoul"}, - {"cc": "KR", "lat": 35.18, "lon": 129.08, "radius_km": 25, "weight": 1, "name": "Busan"}, - {"cc": "HK", "lat": 22.32, "lon": 114.17, "radius_km": 15, "weight": 1, "name": "Hong Kong"}, - {"cc": "ZA", "lat": -33.92, "lon": 18.42, "radius_km": 30, "weight": 2, "name": "Cape Town"}, - {"cc": "ZA", "lat": -26.2, "lon": 28.05, "radius_km": 30, "weight": 2, "name": "Johannesburg"}, - {"cc": "ZA", "lat": -29.86, "lon": 31.02, "radius_km": 25, "weight": 1, "name": "Durban"}, - {"cc": "ZA", "lat": -25.75, "lon": 28.19, "radius_km": 20, "weight": 1, "name": "Pretoria"}, - {"cc": "NA", "lat": -22.56, "lon": 17.08, "radius_km": 15, "weight": 1, "name": "Windhoek"}, - {"cc": "BW", "lat": -24.65, "lon": 25.91, "radius_km": 15, "weight": 1, "name": "Gaborone"}, - {"cc": "KE", "lat": -1.29, "lon": 36.82, "radius_km": 25, "weight": 1, "name": "Nairobi"}, - {"cc": "TZ", "lat": -6.79, "lon": 39.21, "radius_km": 20, "weight": 1, "name": "Dar es Salaam"}, - {"cc": "UG", "lat": 0.35, "lon": 32.58, "radius_km": 20, "weight": 1, "name": "Kampala"}, - {"cc": "RW", "lat": -1.95, "lon": 30.06, "radius_km": 15, "weight": 1, "name": "Kigali"}, - {"cc": "ET", "lat": 9.03, "lon": 38.74, "radius_km": 20, "weight": 1, "name": "Addis Ababa"}, - {"cc": "GH", "lat": 5.6, "lon": -0.19, "radius_km": 20, "weight": 1, "name": "Accra"}, - {"cc": "NG", "lat": 6.52, "lon": 3.38, "radius_km": 25, "weight": 1, "name": "Lagos"}, - {"cc": "SN", "lat": 14.72, "lon": -17.47, "radius_km": 15, "weight": 1, "name": "Dakar"}, - {"cc": "CI", "lat": 5.36, "lon": -4.01, "radius_km": 20, "weight": 1, "name": "Abidjan"}, - {"cc": "MA", "lat": 33.57, "lon": -7.59, "radius_km": 25, "weight": 1, "name": "Casablanca"}, - {"cc": "MA", "lat": 31.63, "lon": -8.01, "radius_km": 20, "weight": 1, "name": "Marrakesh"}, - {"cc": "TN", "lat": 36.81, "lon": 10.18, "radius_km": 20, "weight": 1, "name": "Tunis"}, - {"cc": "EG", "lat": 30.04, "lon": 31.24, "radius_km": 25, "weight": 1, "name": "Cairo"}, - {"cc": "MG", "lat": -18.88, "lon": 47.51, "radius_km": 15, "weight": 1, "name": "Antananarivo"}, - {"cc": "MU", "lat": -20.16, "lon": 57.5, "radius_km": 20, "weight": 1, "name": "Port Louis"}, - {"cc": "RE", "lat": -21.12, "lon": 55.53, "radius_km": 20, "weight": 1, "name": "Reunion"} - ] -} diff --git a/cmd/geoguess/geo/seeds_test.go b/cmd/geoguess/geo/seeds_test.go deleted file mode 100644 index bbb4ec8..0000000 --- a/cmd/geoguess/geo/seeds_test.go +++ /dev/null @@ -1,155 +0,0 @@ -package geo - -import ( - "encoding/json" - "math" - "math/rand/v2" - "strings" - "testing" -) - -func TestSeedsFile(t *testing.T) { - var f seedFile - if err := json.Unmarshal(seedsJSON, &f); err != nil { - t.Fatal(err) - } - if len(f.Seeds) < 150 || f.CountryCap <= 0 { - t.Errorf("%d seeds, cap %v", len(f.Seeds), f.CountryCap) - } - continent := map[string]string{} - for name, ccs := range f.Continents { - for _, cc := range ccs { - if other, ok := continent[cc]; ok { - t.Errorf("%s is in %s and %s", cc, other, name) - } - continent[cc] = name - } - } - countries := map[string]bool{} - for _, s := range f.Seeds { - countries[s.CC] = true - if _, ok := continent[s.CC]; !ok { - t.Errorf("%s (%s) is in no continent", s.CC, s.Name) - } - if !(Point{s.Lat, s.Lon}).valid() || s.RadiusKm <= 0 || s.RadiusKm > 100 || s.Weight <= 0 || s.Name == "" { - t.Errorf("seed %+v", s) - } - } - if len(countries) < 60 || len(f.Continents) != 6 { - t.Errorf("%d countries in %d continents", len(countries), len(f.Continents)) - } -} - -func TestLoadSeeds(t *testing.T) { - world, err := LoadSeeds("") - if err != nil { - t.Fatal(err) - } - for _, tc := range []struct { - regions string - want func(Seed) bool - err string - }{ - {"europe", func(s Seed) bool { return s.Lon > -30 && s.Lon < 45 && s.Lat > 27 }, ""}, - {"AU,nz, JP", func(s Seed) bool { return s.CC == "AU" || s.CC == "NZ" || s.CC == "JP" }, ""}, - {"South America", func(s Seed) bool { return s.Lat < 13 && s.Lon < -34 && s.Lon > -82 }, ""}, - {"oceania,FR", func(s Seed) bool { return s.CC == "AU" || s.CC == "NZ" || s.CC == "FR" }, ""}, - {"atlantis", nil, "unknown region"}, - {"XX", nil, "no seed regions"}, - } { - s, err := LoadSeeds(tc.regions) - if tc.err != "" { - if err == nil || !strings.Contains(err.Error(), tc.err) { - t.Errorf("%q: %v, want %q", tc.regions, err, tc.err) - } - continue - } - if err != nil || s.Len() == 0 || s.Len() >= world.Len() { - t.Errorf("%q: %d seeds, %v", tc.regions, s.Len(), err) - continue - } - for _, seed := range s.list { - if !tc.want(seed) { - t.Errorf("%q: has %+v", tc.regions, seed) - } - } - } -} - -func TestSeedsCapCountries(t *testing.T) { - list := []Seed{ - {CC: "US", Weight: 6}, {CC: "US", Weight: 6}, // 12, capped at 4 - {CC: "NZ", Weight: 2}, {CC: "AU", Weight: 4}, - } - s := newSeeds(list, 4) - r := rand.New(rand.NewPCG(1, 1)) - got := map[string]int{} - const n = 20000 - for range n { - got[s.Pick(r).CC]++ - } - for cc, share := range map[string]float64{"US": 0.4, "NZ": 0.2, "AU": 0.4} { - if f := float64(got[cc]) / n; math.Abs(f-share) > 0.02 { - t.Errorf("%s picked %.3f of the time, want %.2f", cc, f, share) - } - } - - world, _ := LoadSeeds("") - us := 0 - for range n { - if world.Pick(r).CC == "US" { - us++ - } - } - if f := float64(us) / n; f > 0.05 { - t.Errorf("the US takes %.3f of rounds", f) - } -} - -func TestSeedPoint(t *testing.T) { - r := rand.New(rand.NewPCG(2, 2)) - for _, s := range []Seed{ - {Lat: -37.81, Lon: 144.96, RadiusKm: 40}, - {Lat: 69.65, Lon: 18.96, RadiusKm: 15}, - {Lat: 0, Lon: 179.99, RadiusKm: 30}, // wraps round the antimeridian - } { - far := 0.0 - for range 2000 { - p := s.Point(r) - if !p.valid() { - t.Fatalf("%v is out of range", p) - } - d := Km(p, Point{s.Lat, s.Lon}) - if d > s.RadiusKm*1.001 { - t.Errorf("%v is %.1f km from %+v", p, d, s) - } - far = max(far, d) - } - if far < s.RadiusKm*0.9 { - t.Errorf("points stay within %.1f of %v km", far, s.RadiusKm) - } - } -} - -func TestAround(t *testing.T) { - for _, p := range []Point{{-37.81, 144.96}, {89.99, 0}, {0, -180}} { - b := Around(p) - area := (b.MaxLon - b.MinLon) * (b.MaxLat - b.MinLat) - if area >= 0.01 || area <= 0 || b.MinLon < -180 || b.MaxLat > 90 { - t.Errorf("Around(%v) = %+v, %.4f deg²", p, b, area) - } - } - if got := Around(Point{-37.81, 144.96}).String(); got != "144.940000,-37.830000,144.980000,-37.790000" { - t.Errorf("String %s", got) - } -} - -func TestSeedsHas(t *testing.T) { - europe, err := LoadSeeds("europe") - if err != nil { - t.Fatal(err) - } - if !europe.Has("FR") || europe.Has("AU") || europe.Has("") { - t.Error("europe's countries") - } -} diff --git a/cmd/geoguess/geo/source.go b/cmd/geoguess/geo/source.go deleted file mode 100644 index 5d2fbcc..0000000 --- a/cmd/geoguess/geo/source.go +++ /dev/null @@ -1,176 +0,0 @@ -package geo - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "io" - "net/http" - "strconv" - "sync" - "time" -) - -// Source is a place to find street-level photos: Mapillary or Panoramax. -type Source interface { - // Name names the source in the credit and the log. - Name() string - // Candidates lists the photos in b. - Candidates(ctx context.Context, b BBox) ([]Candidate, error) - // Fetch downloads a candidate's photo. - Fetch(ctx context.Context, c Candidate) ([]byte, error) -} - -// BBox is an area to search, in decimal degrees. -type BBox struct { - MinLon, MinLat, MaxLon, MaxLat float64 -} - -// String is the bbox as both APIs take it: minLon,minLat,maxLon,maxLat. -func (b BBox) String() string { - return coord(b.MinLon) + "," + coord(b.MinLat) + "," + coord(b.MaxLon) + "," + coord(b.MaxLat) -} - -// Centre is the middle of b. -func (b BBox) Centre() Point { - return Point{Lat: (b.MinLat + b.MaxLat) / 2, Lon: (b.MinLon + b.MaxLon) / 2} -} - -func coord(f float64) string { return strconv.FormatFloat(f, 'f', 6, 64) } - -// Candidate is one photo a source offers, from its metadata alone. -type Candidate struct { - ID string // the source's own ID, which is all the state keeps - Source string // the source's Name - Creator string // the author, for the credit - Licence string // as the credit shows it, e.g. "CC BY-SA 4.0" - Link string // the photo's page, for the credit - At Point // where it was taken: the answer - Raw Point // the raw GPS position, for the drift check; At if there is none - Captured time.Time - Pano bool // an equirectangular 360° panorama - Fisheye bool // a fisheye lens, which is refused - Quality float64 // 0–1; -1 if unknown (Mapillary's quality_score) - Grade int // 1–5 (A is 5); 0 if unknown (Panoramax's grade) - Width int // pixels; 0 if unknown - Height int - Sequence string // the sequence the photo belongs to, if known - - image string // where to download the photo: a URL that may expire -} - -// Key names c across sources, for the list of photos used recently. -func (c Candidate) Key() string { return c.Source + ":" + c.ID } - -// StatusError is an API answering with an HTTP error status. It holds only -// the status, never the URL, so it is safe to log. -type StatusError struct { - Source string - Code int -} - -func (e StatusError) Error() string { return e.Source + ": status " + strconv.Itoa(e.Code) } - -// ErrSlowDown is a source asking to be called less often; the caller should -// wait a while before searching again. -var ErrSlowDown = errors.New("rate limited") - -// maxPhoto caps a downloaded photo. -const maxPhoto = 12 << 20 - -// userAgent names the program, never the person running it. -const userAgent = "geoguess (+https://github.com/robdevops/signalbot)" - -// pacer spaces requests at least every apart. -type pacer struct { - mu sync.Mutex - every time.Duration - next time.Time -} - -// wait blocks until the next request may go, or ctx ends. -func (p *pacer) wait(ctx context.Context) error { - p.mu.Lock() - now := time.Now() - at := now - if p.next.After(now) { - at = p.next - } - p.next = at.Add(p.every) - p.mu.Unlock() - t := time.NewTimer(at.Sub(now)) - defer t.Stop() - select { - case <-t.C: - return nil - case <-ctx.Done(): - return ctx.Err() - } -} - -// request is one GET to an API or an image host. -type request struct { - client *http.Client - source string // names the source in errors - url string - auth string // the Authorization header, if any - limit int64 // the most bytes read -} - -// get does r and returns the body. An error never holds the URL, which may -// carry a signature, nor the server's address. -func (r request) get(ctx context.Context) ([]byte, error) { - req, err := http.NewRequestWithContext(ctx, http.MethodGet, r.url, nil) - if err != nil { - return nil, fmt.Errorf("%s: bad request", r.source) - } - req.Header.Set("User-Agent", userAgent) - if r.auth != "" { - req.Header.Set("Authorization", r.auth) - } - resp, err := r.client.Do(req) - if err != nil { - if ctx.Err() != nil { - return nil, ctx.Err() - } - return nil, fmt.Errorf("%s: request failed", r.source) - } - defer resp.Body.Close() - body, err := io.ReadAll(io.LimitReader(resp.Body, r.limit+1)) - if resp.StatusCode != http.StatusOK { - return body, StatusError{Source: r.source, Code: resp.StatusCode} - } - if err != nil { - return nil, fmt.Errorf("%s: reading the answer failed", r.source) - } - if int64(len(body)) > r.limit { - return nil, fmt.Errorf("%s: answer too large", r.source) - } - return body, nil -} - -// getJSON does r and decodes its JSON body into v. -func (r request) getJSON(ctx context.Context, v any) error { - body, err := r.get(ctx) - if err != nil { - return err - } - if json.Unmarshal(body, v) != nil { - return fmt.Errorf("%s: unreadable answer", r.source) - } - return nil -} - -// geoJSONPoint is a GeoJSON point: [lon, lat]. -type geoJSONPoint struct { - Coordinates []float64 `json:"coordinates"` -} - -func (g *geoJSONPoint) point() (Point, bool) { - if g == nil || len(g.Coordinates) < 2 { - return Point{}, false - } - p := Point{Lat: g.Coordinates[1], Lon: g.Coordinates[0]} - return p, p.valid() -} diff --git a/cmd/geoguess/geo/source_test.go b/cmd/geoguess/geo/source_test.go deleted file mode 100644 index 1a711cd..0000000 --- a/cmd/geoguess/geo/source_test.go +++ /dev/null @@ -1,372 +0,0 @@ -package geo - -import ( - "context" - "errors" - "net/http" - "net/http/httptest" - "os" - "strings" - "sync" - "testing" - "time" -) - -// fixture is a recorded API answer from testdata, with {{cdn}} pointing at -// base. The recordings' people are renamed Alice and Bob, and their image -// URLs, which were signed, replaced. -func fixture(t *testing.T, name, base string) []byte { - t.Helper() - data, err := os.ReadFile("testdata/" + name) - if err != nil { - t.Fatal(err) - } - return []byte(strings.ReplaceAll(string(data), "{{cdn}}", base+"/cdn")) -} - -// fakeAPI is an httptest server whose handler the test sets, recording each -// request it gets. -type fakeAPI struct { - *httptest.Server - mu sync.Mutex - handle func(w http.ResponseWriter, r *http.Request) - queries []*http.Request -} - -func newFakeAPI(t *testing.T) *fakeAPI { - f := &fakeAPI{} - f.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - f.mu.Lock() - f.queries = append(f.queries, r.Clone(context.Background())) - h := f.handle - f.mu.Unlock() - h(w, r) - })) - t.Cleanup(f.Close) - return f -} - -func (f *fakeAPI) requests() []*http.Request { - f.mu.Lock() - defer f.mu.Unlock() - return append([]*http.Request(nil), f.queries...) -} - -var testBox = BBox{MinLon: 143.85, MinLat: -37.57, MaxLon: 143.87, MaxLat: -37.55} - -func TestMapillaryCandidates(t *testing.T) { - api := newFakeAPI(t) - api.handle = func(w http.ResponseWriter, r *http.Request) { w.Write(fixture(t, "mapillary_bbox.json", api.URL)) } - m := NewMapillary(api.URL, "MLY|test", api.Client()) - cands, err := m.Candidates(context.Background(), testBox) - if err != nil { - t.Fatal(err) - } - if len(cands) != 8 { - t.Fatalf("%d candidates, want 8", len(cands)) - } - req := api.requests()[0] - if got := req.Header.Get("Authorization"); got != "OAuth MLY|test" { - t.Errorf("Authorization %q", got) - } - if req.Header.Get("User-Agent") != userAgent { - t.Errorf("User-Agent %q", req.Header.Get("User-Agent")) - } - q := req.URL.Query() - if req.URL.Path != "/images" || q.Get("bbox") != "143.850000,-37.570000,143.870000,-37.550000" || q.Get("limit") != "100" || !strings.Contains(q.Get("fields"), "computed_geometry") { - t.Errorf("query %s %v", req.URL.Path, q) - } - - flat, pano := cands[0], cands[6] - want := Candidate{ - ID: "156004253082834", Source: "Mapillary", Creator: "alice", Licence: "CC BY-SA 4.0", - Link: "https://www.mapillary.com/app/?pKey=156004253082834", - Captured: time.UnixMilli(1566687341409).UTC(), Fisheye: true, Quality: 0.612, - Width: 3840, Height: 2160, Sequence: flat.Sequence, At: flat.At, Raw: flat.Raw, - image: api.URL + "/cdn/156004253082834.jpg", - } - if flat != want { - t.Errorf("candidate\n%+v\nwant\n%+v", flat, want) - } - if flat.At == flat.Raw || Km(flat.At, flat.Raw) > 0.05 || flat.At.Lat > -37.5 { - t.Errorf("positions %v (computed) and %v (raw)", flat.At, flat.Raw) - } - if !pano.Pano || pano.Fisheye || pano.Creator != "bob" || pano.Quality != 0.775 { - t.Errorf("panorama %+v", pano) - } -} - -func TestMapillaryImage(t *testing.T) { - q := 0.5 - for _, tc := range []struct { - name string - im mapillaryImage - ok bool - want func(Candidate) bool - }{ - {"quality null is unknown", mapillaryImage{ID: "1", Geometry: &geoJSONPoint{[]float64{1, 2}}}, true, - func(c Candidate) bool { return c.Quality == -1 && c.At == (Point{2, 1}) && c.Raw == c.At }}, - {"quality kept", mapillaryImage{ID: "1", Geometry: &geoJSONPoint{[]float64{1, 2}}, QualityScore: &q}, true, - func(c Candidate) bool { return c.Quality == 0.5 }}, - {"equirectangular is a panorama", mapillaryImage{ID: "1", Geometry: &geoJSONPoint{[]float64{1, 2}}, CameraType: "equirectangular"}, true, - func(c Candidate) bool { return c.Pano }}, - {"spherical is a panorama", mapillaryImage{ID: "1", Geometry: &geoJSONPoint{[]float64{1, 2}}, CameraType: "spherical"}, true, - func(c Candidate) bool { return c.Pano }}, - {"computed geometry is the answer", mapillaryImage{ID: "1", Geometry: &geoJSONPoint{[]float64{1, 2}}, ComputedGeometry: &geoJSONPoint{[]float64{3, 4}}}, true, - func(c Candidate) bool { return c.At == (Point{4, 3}) && c.Raw == (Point{2, 1}) }}, - {"no capture time", mapillaryImage{ID: "1", ComputedGeometry: &geoJSONPoint{[]float64{3, 4}}}, true, - func(c Candidate) bool { return c.Captured.IsZero() && c.Raw == c.At }}, - {"no position", mapillaryImage{ID: "1"}, false, nil}, - {"out of range", mapillaryImage{ID: "1", Geometry: &geoJSONPoint{[]float64{200, 2}}}, false, nil}, - {"no ID", mapillaryImage{Geometry: &geoJSONPoint{[]float64{1, 2}}}, false, nil}, - } { - c, ok := tc.im.candidate() - if ok != tc.ok || (ok && !tc.want(c)) { - t.Errorf("%s: %+v, %v", tc.name, c, ok) - } - } -} - -func TestMapillaryRetries(t *testing.T) { - for _, tc := range []struct { - name string - answers []string // status and fixture, by request - want int // candidates - calls int - radius bool // the last call was a radius search - err error - }{ - {"empty is asked again", []string{"200 {\"data\":[]}", "200 mapillary_bbox.json"}, 8, 2, false, nil}, - {"empty twice", []string{"200 {\"data\":[]}", "200 {\"data\":[]}"}, 0, 2, false, nil}, - {"too dense falls back to a radius", []string{"500 mapillary_error.json", "200 mapillary_radius.json"}, 5, 2, true, nil}, - {"empty then too dense", []string{"200 {\"data\":[]}", "500 mapillary_error.json", "200 mapillary_radius.json"}, 5, 3, true, nil}, - {"rate limited", []string{`429 {"error":{"code":4,"message":"limit"}}`}, 0, 1, false, ErrSlowDown}, - {"rate limited as a 400", []string{`400 {"error":{"code":4,"message":"limit"}}`}, 0, 1, false, ErrSlowDown}, - {"refused", []string{`401 {"error":{"code":190}}`}, 0, 1, false, StatusError{Source: "Mapillary", Code: 401}}, - {"unreadable", []string{`200 <html>`}, 0, 1, false, errors.New("Mapillary: unreadable answer")}, - } { - api := newFakeAPI(t) - n := 0 - api.handle = func(w http.ResponseWriter, r *http.Request) { - status, body, _ := strings.Cut(tc.answers[min(n, len(tc.answers)-1)], " ") - n++ - if strings.HasSuffix(body, ".json") { - body = string(fixture(t, body, api.URL)) - } - code := map[string]int{"200": 200, "400": 400, "401": 401, "429": 429, "500": 500}[status] - w.WriteHeader(code) - w.Write([]byte(body)) - } - cands, err := NewMapillary(api.URL, "MLY|test", api.Client()).Candidates(context.Background(), testBox) - if (err == nil) != (tc.err == nil) || (err != nil && err.Error() != tc.err.Error()) { - t.Errorf("%s: error %v, want %v", tc.name, err, tc.err) - } - reqs := api.requests() - if len(cands) != tc.want || len(reqs) != tc.calls { - t.Errorf("%s: %d candidates in %d calls, want %d in %d", tc.name, len(cands), len(reqs), tc.want, tc.calls) - continue - } - last := reqs[len(reqs)-1].URL.Query() - if tc.radius && (last.Get("lat") != "-37.560000" || last.Get("lng") != "143.860000" || last.Get("radius") != "50" || last.Has("bbox")) { - t.Errorf("%s: radius search %v", tc.name, last) - } - } -} - -func TestMapillaryFetch(t *testing.T) { - api := newFakeAPI(t) - expired := true - api.handle = func(w http.ResponseWriter, r *http.Request) { - switch { - case r.URL.Path == "/cdn/old.jpg" && expired: - w.WriteHeader(http.StatusForbidden) - case strings.HasPrefix(r.URL.Path, "/cdn/"): - w.Write([]byte("jpeg " + r.URL.Path)) - case r.URL.Path == "/42" && r.URL.Query().Get("fields") == "thumb_2048_url" && r.Header.Get("Authorization") == "OAuth tok": - w.Write([]byte(`{"id":"42","thumb_2048_url":"` + api.URL + `/cdn/fresh.jpg?sig=secret"}`)) - default: - http.NotFound(w, r) - } - } - m := NewMapillary(api.URL, "tok", api.Client()) - ctx := context.Background() - for _, tc := range []struct { - name string - image string - want string - }{ - {"by the search's URL", api.URL + "/cdn/old.jpg", "jpeg /cdn/old.jpg"}, - {"no URL", "", "jpeg /cdn/fresh.jpg"}, - } { - expired = false - data, err := m.Fetch(ctx, Candidate{ID: "42", image: tc.image}) - if err != nil || string(data) != tc.want { - t.Errorf("%s: %q, %v", tc.name, data, err) - } - } - expired = true - data, err := m.Fetch(ctx, Candidate{ID: "42", image: api.URL + "/cdn/old.jpg"}) - if err != nil || string(data) != "jpeg /cdn/fresh.jpg" { - t.Errorf("expired URL: %q, %v", data, err) - } - // An error names neither the URL nor its signature. - _, err = m.Fetch(ctx, Candidate{ID: "43", image: api.URL + "/cdn/old.jpg?sig=secret"}) - if err == nil || strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "127.0.0.1") { - t.Errorf("error %v", err) - } -} - -func TestRequestErrorsHoldNoURL(t *testing.T) { - api := newFakeAPI(t) - api.handle = func(w http.ResponseWriter, r *http.Request) {} - addr := api.URL - api.Close() // nothing listens now - for _, url := range []string{addr + "/x?sig=secret", "://bad?sig=secret"} { - _, err := request{client: http.DefaultClient, source: "Test", url: url, limit: 10}.get(context.Background()) - if err == nil || strings.Contains(err.Error(), "secret") || strings.Contains(err.Error(), "127.0.0.1") { - t.Errorf("error %v", err) - } - } -} - -func TestPanoramaxCandidates(t *testing.T) { - api := newFakeAPI(t) - api.handle = func(w http.ResponseWriter, r *http.Request) { w.Write(fixture(t, "panoramax_search.json", api.URL)) } - p := NewPanoramax(api.URL, api.Client()) - p.pace.every = 0 - cands, err := p.Candidates(context.Background(), testBox) - if err != nil { - t.Fatal(err) - } - if len(cands) != 5 { - t.Fatalf("%d candidates, want 5", len(cands)) - } - req := api.requests()[0] - if req.URL.Path != "/api/search" || req.URL.Query().Get("bbox") != testBox.String() || req.Header.Get("User-Agent") != userAgent || req.Header.Get("Authorization") != "" { - t.Errorf("request %v %v", req.URL, req.Header) - } - pano := cands[0] - want := Candidate{ - ID: "9a479835-1331-4b8a-adce-f2173f61ffc8", Source: "Panoramax", Creator: "alice", Licence: "Etalab 2.0", - Link: api.URL + "/#focus=pic&pic=9a479835-1331-4b8a-adce-f2173f61ffc8", - At: Point{48.859925491, 2.345090985}, - Raw: Point{48.859925491, 2.345090985}, - Captured: time.Date(2025, 5, 8, 9, 22, 36, 652e6, time.UTC), - Pano: true, Quality: -1, Grade: 5, Width: 12288, Height: 6144, - Sequence: "600d5cee-5328-4dd4-8838-5f27ef85aa59", - image: api.URL + "/cdn/9a479835-1331-4b8a-adce-f2173f61ffc8/sd.jpg", - } - if pano != want { - t.Errorf("candidate\n%+v\nwant\n%+v", pano, want) - } - flat := cands[3] - if flat.Pano || flat.Licence != "CC BY-SA 4.0" || flat.Creator != "bob" || flat.Grade != 3 || flat.Width != 1920 { - t.Errorf("flat %+v", flat) - } - - data, err := p.Fetch(context.Background(), flat) - if err != nil || !strings.Contains(string(data), "FeatureCollection") { // the fake serves the search for any path - t.Errorf("fetch: %v", err) - } - if got := api.requests()[1].URL.Path; got != "/cdn/4ff8d96e-5114-4ed5-b593-daea754a6998/sd.jpg" { - t.Errorf("fetched %s", got) - } -} - -func TestPanoramaxSkips(t *testing.T) { - api := newFakeAPI(t) - api.handle = func(w http.ResponseWriter, r *http.Request) { - w.Write([]byte(`{"features":[ - {"id":"a","geometry":{"coordinates":[2,48]},"assets":{"sd":{"href":"x"}},"properties":{"license":"proprietary"}}, - {"id":"b","geometry":{"coordinates":[2,48]},"assets":{"hd":{"href":"x"}},"properties":{"license":"CC-BY-4.0"}}, - {"id":"c","assets":{"sd":{"href":"x"}},"properties":{"license":"CC-BY-4.0"}}, - {"id":"d","geometry":{"coordinates":[2,48]},"assets":{"sd":{"href":"x"}},"properties":{"license":"CC0-1.0","datetime":"bad"}} - ]}`)) - } - p := NewPanoramax(api.URL, api.Client()) - p.pace.every = 0 - cands, err := p.Candidates(context.Background(), testBox) - if err != nil || len(cands) != 1 || cands[0].ID != "d" || cands[0].Licence != "CC0 1.0" || !cands[0].Captured.IsZero() || cands[0].Grade != 0 { - t.Errorf("%+v, %v", cands, err) - } - api.handle = func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTooManyRequests) } - if _, err := p.Candidates(context.Background(), testBox); err != ErrSlowDown { - t.Errorf("429: %v", err) - } - api.handle = func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusBadGateway) } - if _, err := p.Candidates(context.Background(), testBox); err != (StatusError{Source: "Panoramax", Code: 502}) { - t.Errorf("502: %v", err) - } -} - -func TestGrade(t *testing.T) { - f := func(v float64) *float64 { return &v } - for _, tc := range []struct { - pano bool - density, accuracy *float64 - want int - }{ - {false, nil, nil, 0}, - {false, f(5), nil, 1}, - {false, f(12), nil, 2}, - {false, f(20), nil, 3}, - {false, f(40), nil, 4}, - {true, f(10), nil, 3}, - {true, f(20), nil, 4}, - {true, f(34), nil, 5}, - {false, nil, f(0.3), 5}, - {false, nil, f(2), 4}, - {false, nil, f(5), 3}, - {false, nil, f(10), 2}, - {false, nil, f(11), 1}, - {true, f(34), f(2), 5}, // 0.8×5 + 0.2×4 = 4.8 - {false, f(20), f(3.6), 3}, // 0.8×3 + 0.2×3 - {false, f(12), f(0.3), 3}, // 0.8×2 + 0.2×5 = 2.6 - {false, f(12), f(11), 2}, // 0.8×2 + 0.2×1 = 1.8 - {false, f(5), f(0.3), 2}, // 0.8 + 1 = 1.8 - {false, f(40), f(11), 3}, // 3.2 + 0.2 = 3.4 - {true, f(10), f(20), 3}, // 2.4 + 0.2 = 2.6 - } { - if got := grade(tc.pano, tc.density, tc.accuracy); got != tc.want { - t.Errorf("grade(%v, %v, %v) = %d, want %d", tc.pano, deref(tc.density), deref(tc.accuracy), got, tc.want) - } - } -} - -func deref(f *float64) any { - if f == nil { - return nil - } - return *f -} - -func TestLicenceName(t *testing.T) { - for spdx, want := range map[string]string{ - "CC-BY-SA-4.0": "CC BY-SA 4.0", "CC-BY-4.0": "CC BY 4.0", "CC0-1.0": "CC0 1.0", - "etalab-2.0": "Etalab 2.0", "": "", "proprietary": "", "CC-4.0": "", "MIT": "", "GPL-3.0": "", - } { - if got := licenceName(spdx); got != want { - t.Errorf("licenceName(%q) = %q, want %q", spdx, got, want) - } - } -} - -func TestPacer(t *testing.T) { - p := &pacer{every: 30 * time.Millisecond} - start := time.Now() - for range 3 { - if err := p.wait(context.Background()); err != nil { - t.Fatal(err) - } - } - if d := time.Since(start); d < 60*time.Millisecond { - t.Errorf("3 requests in %v, want at least 60ms", d) - } - ctx, cancel := context.WithCancel(context.Background()) - cancel() - p.every = time.Hour - p.wait(context.Background()) - if err := p.wait(ctx); err != context.Canceled { - t.Errorf("cancelled wait: %v", err) - } -} diff --git a/cmd/geoguess/geo/testdata/mapillary_bbox.json b/cmd/geoguess/geo/testdata/mapillary_bbox.json deleted file mode 100644 index 850c41d..0000000 --- a/cmd/geoguess/geo/testdata/mapillary_bbox.json +++ /dev/null @@ -1,244 +0,0 @@ -{ - "data": [ - { - "id": "156004253082834", - "computed_geometry": { - "type": "Point", - "coordinates": [ - 143.85993803594, - -37.550111548392 - ] - }, - "geometry": { - "type": "Point", - "coordinates": [ - 143.85993831842, - -37.550110472726 - ] - }, - "captured_at": 1566687341409, - "camera_type": "fisheye", - "is_pano": false, - "quality_score": 0.612, - "width": 3840, - "height": 2160, - "computed_compass_angle": 184.75923939341, - "sequence": "xb2e6e9trvde7vkhc65y3i", - "creator": { - "username": "alice", - "id": "1001" - }, - "thumb_2048_url": "{{cdn}}/156004253082834.jpg" - }, - { - "id": "2880385632236073", - "computed_geometry": { - "type": "Point", - "coordinates": [ - 143.85975441019, - -37.551251776107 - ] - }, - "geometry": { - "type": "Point", - "coordinates": [ - 143.85975375285, - -37.551243574797 - ] - }, - "captured_at": 1566687354881, - "camera_type": "fisheye", - "is_pano": false, - "quality_score": 0.614, - "width": 3840, - "height": 2160, - "computed_compass_angle": 240.63145945093, - "sequence": "xb2e6e9trvde7vkhc65y3i", - "creator": { - "username": "alice", - "id": "1001" - }, - "thumb_2048_url": "{{cdn}}/2880385632236073.jpg" - }, - { - "id": "334718131329412", - "computed_geometry": { - "type": "Point", - "coordinates": [ - 143.85973240176, - -37.551255606257 - ] - }, - "geometry": { - "type": "Point", - "coordinates": [ - 143.85973159017, - -37.551247230787 - ] - }, - "captured_at": 1566687355180, - "camera_type": "fisheye", - "is_pano": false, - "quality_score": 0.618, - "width": 3840, - "height": 2160, - "computed_compass_angle": 250.45092854569, - "sequence": "xb2e6e9trvde7vkhc65y3i", - "creator": { - "username": "alice", - "id": "1001" - }, - "thumb_2048_url": "{{cdn}}/334718131329412.jpg" - }, - { - "id": "178895307446180", - "computed_geometry": { - "type": "Point", - "coordinates": [ - 143.85988012788, - -37.550447115403 - ] - }, - "geometry": { - "type": "Point", - "coordinates": [ - 143.85987935767, - -37.550449615938 - ] - }, - "captured_at": 1566687344327, - "camera_type": "fisheye", - "is_pano": false, - "quality_score": 0.682, - "width": 3840, - "height": 2160, - "computed_compass_angle": 184.78506751006, - "sequence": "xb2e6e9trvde7vkhc65y3i", - "creator": { - "username": "alice", - "id": "1001" - }, - "thumb_2048_url": "{{cdn}}/178895307446180.jpg" - }, - { - "id": "1142062562932199", - "computed_geometry": { - "type": "Point", - "coordinates": [ - 143.85985738968, - -37.550590850425 - ] - }, - "geometry": { - "type": "Point", - "coordinates": [ - 143.85985817455, - -37.550592772934 - ] - }, - "captured_at": 1566687345612, - "camera_type": "fisheye", - "is_pano": false, - "quality_score": 0.587, - "width": 3840, - "height": 2160, - "computed_compass_angle": 183.87523854316, - "sequence": "xb2e6e9trvde7vkhc65y3i", - "creator": { - "username": "alice", - "id": "1001" - }, - "thumb_2048_url": "{{cdn}}/1142062562932199.jpg" - }, - { - "id": "223444442539547", - "computed_geometry": { - "type": "Point", - "coordinates": [ - 143.85983656729, - -37.551193460445 - ] - }, - "geometry": { - "type": "Point", - "coordinates": [ - 143.85984588429, - -37.551196353464 - ] - }, - "captured_at": 1566687353395, - "camera_type": "fisheye", - "is_pano": false, - "quality_score": 0.57, - "width": 3840, - "height": 2160, - "computed_compass_angle": 194.20153045585, - "sequence": "xb2e6e9trvde7vkhc65y3i", - "creator": { - "username": "alice", - "id": "1001" - }, - "thumb_2048_url": "{{cdn}}/223444442539547.jpg" - }, - { - "id": "1197032491288598", - "computed_geometry": { - "type": "Point", - "coordinates": [ - 2.2951849294167, - 48.859976802118 - ] - }, - "geometry": { - "type": "Point", - "coordinates": [ - 2.2951917, - 48.8599845 - ] - }, - "captured_at": 1718006677000, - "camera_type": "spherical", - "is_pano": true, - "quality_score": 0.775, - "width": 5760, - "height": 2880, - "computed_compass_angle": 301.36099357275, - "sequence": "QVKZBMWUjyG9PRXJufv0wA", - "creator": { - "username": "bob", - "id": "1002" - }, - "thumb_2048_url": "{{cdn}}/1197032491288598.jpg" - }, - { - "id": "1011962813864670", - "computed_geometry": { - "type": "Point", - "coordinates": [ - 2.2954610949215, - 48.859805467701 - ] - }, - "geometry": { - "type": "Point", - "coordinates": [ - 2.2954703, - 48.8598093 - ] - }, - "captured_at": 1718006650000, - "camera_type": "spherical", - "is_pano": true, - "quality_score": 0.713, - "width": 5760, - "height": 2880, - "computed_compass_angle": 301.89596100548, - "sequence": "QVKZBMWUjyG9PRXJufv0wA", - "creator": { - "username": "bob", - "id": "1002" - }, - "thumb_2048_url": "{{cdn}}/1011962813864670.jpg" - } - ] -} \ No newline at end of file diff --git a/cmd/geoguess/geo/testdata/mapillary_error.json b/cmd/geoguess/geo/testdata/mapillary_error.json deleted file mode 100644 index 95f3f73..0000000 --- a/cmd/geoguess/geo/testdata/mapillary_error.json +++ /dev/null @@ -1 +0,0 @@ -{"error":{"code":1,"message":"Please reduce the amount of data you're asking for, then retry your request"}} \ No newline at end of file diff --git a/cmd/geoguess/geo/testdata/mapillary_radius.json b/cmd/geoguess/geo/testdata/mapillary_radius.json deleted file mode 100644 index 7aa312b..0000000 --- a/cmd/geoguess/geo/testdata/mapillary_radius.json +++ /dev/null @@ -1,154 +0,0 @@ -{ - "data": [ - { - "id": "1706189916395244", - "computed_geometry": { - "type": "Point", - "coordinates": [ - 144.96299697336, - -37.813278303317 - ] - }, - "geometry": { - "type": "Point", - "coordinates": [ - 144.96282777778, - -37.813338888889 - ] - }, - "captured_at": 1648397432000, - "camera_type": "perspective", - "is_pano": false, - "quality_score": 0.724, - "width": 4608, - "height": 3456, - "computed_compass_angle": 235.75898108927, - "sequence": "IPZOUkg6evRHs2oXz5nTi1", - "creator": { - "username": "alice", - "id": "1001" - }, - "thumb_2048_url": "{{cdn}}/1706189916395244.jpg" - }, - { - "id": "450966633448484", - "computed_geometry": { - "type": "Point", - "coordinates": [ - 144.96304115907, - -37.813265095945 - ] - }, - "geometry": { - "type": "Point", - "coordinates": [ - 144.96293611111, - -37.813344444444 - ] - }, - "captured_at": 1648397430000, - "camera_type": "perspective", - "is_pano": false, - "quality_score": 0.701, - "width": 4608, - "height": 3456, - "computed_compass_angle": 236.50575771839, - "sequence": "IPZOUkg6evRHs2oXz5nTi1", - "creator": { - "username": "alice", - "id": "1001" - }, - "thumb_2048_url": "{{cdn}}/450966633448484.jpg" - }, - { - "id": "649893549426488", - "computed_geometry": { - "type": "Point", - "coordinates": [ - 144.96308336398, - -37.813246905267 - ] - }, - "geometry": { - "type": "Point", - "coordinates": [ - 144.96304166667, - -37.813333333333 - ] - }, - "captured_at": 1648397428000, - "camera_type": "perspective", - "is_pano": false, - "quality_score": 0.738, - "width": 4608, - "height": 3456, - "computed_compass_angle": 243.79938219267, - "sequence": "IPZOUkg6evRHs2oXz5nTi1", - "creator": { - "username": "alice", - "id": "1001" - }, - "thumb_2048_url": "{{cdn}}/649893549426488.jpg" - }, - { - "id": "518951069663464", - "computed_geometry": { - "type": "Point", - "coordinates": [ - 144.9631266858, - -37.813233251456 - ] - }, - "geometry": { - "type": "Point", - "coordinates": [ - 144.96310277778, - -37.813330555556 - ] - }, - "captured_at": 1648397426000, - "camera_type": "perspective", - "is_pano": false, - "quality_score": 0.633, - "width": 4608, - "height": 3456, - "computed_compass_angle": 250.66612660699, - "sequence": "IPZOUkg6evRHs2oXz5nTi1", - "creator": { - "username": "alice", - "id": "1001" - }, - "thumb_2048_url": "{{cdn}}/518951069663464.jpg" - }, - { - "id": "965287747688046", - "computed_geometry": { - "type": "Point", - "coordinates": [ - 144.96317140375, - -37.813215415651 - ] - }, - "geometry": { - "type": "Point", - "coordinates": [ - 144.96317777778, - -37.813311111111 - ] - }, - "captured_at": 1648397424000, - "camera_type": "perspective", - "is_pano": false, - "quality_score": 0.603, - "width": 4608, - "height": 3456, - "computed_compass_angle": 242.16944133453, - "sequence": "IPZOUkg6evRHs2oXz5nTi1", - "creator": { - "username": "alice", - "id": "1001" - }, - "thumb_2048_url": "{{cdn}}/965287747688046.jpg" - } - ] -} \ No newline at end of file diff --git a/cmd/geoguess/geo/testdata/panoramax_search.json b/cmd/geoguess/geo/testdata/panoramax_search.json deleted file mode 100644 index 21ca04e..0000000 --- a/cmd/geoguess/geo/testdata/panoramax_search.json +++ /dev/null @@ -1,614 +0,0 @@ -{ - "type": "FeatureCollection", - "features": [ - { - "id": "9a479835-1331-4b8a-adce-f2173f61ffc8", - "bbox": [ - 2.345090985, - 48.859925491, - 2.345090985, - 48.859925491 - ], - "type": "Feature", - "links": [ - { - "rel": "license", - "href": "https://alliance.numerique.gouv.fr/licence-ouverte-open-licence/", - "title": "License for this object (etalab-2.0)" - }, - { - "rel": "self", - "href": "https://api.panoramax.xyz/api/collections/600d5cee-5328-4dd4-8838-5f27ef85aa59/items/9a479835-1331-4b8a-adce-f2173f61ffc8", - "type": "application/geo+json" - }, - { - "rel": "via", - "href": "https://panoramax.ign.fr", - "type": "application/json", - "title": "Link to the original instance", - "instance_name": "ign" - } - ], - "assets": { - "hd": { - "href": "{{cdn}}/9a479835-1331-4b8a-adce-f2173f61ffc8/1331-4b8a-adce-f2173f61ffc8.jpg", - "type": "image/jpeg", - "roles": [ - "data" - ], - "title": "HD picture", - "description": "Highest resolution available of this picture" - }, - "sd": { - "href": "{{cdn}}/9a479835-1331-4b8a-adce-f2173f61ffc8/sd.jpg", - "type": "image/jpeg", - "roles": [ - "visual" - ], - "title": "SD picture", - "description": "Picture in standard definition (fixed width of 2048px)" - }, - "thumb": { - "href": "{{cdn}}/9a479835-1331-4b8a-adce-f2173f61ffc8/thumb.jpg", - "type": "image/jpeg", - "roles": [ - "thumbnail" - ], - "title": "Thumbnail", - "description": "Picture in low definition (fixed width of 500px)" - } - }, - "geometry": { - "type": "Point", - "coordinates": [ - 2.345090985, - 48.859925491 - ] - }, - "providers": [ - { - "name": "alice", - "roles": [ - "producer" - ] - }, - { - "name": "Alice for the City", - "roles": [ - "producer" - ] - } - ], - "collection": "600d5cee-5328-4dd4-8838-5f27ef85aa59", - "properties": { - "created": "2025-12-05T19:45:40.220379+00:00", - "license": "etalab-2.0", - "updated": "2025-12-26T15:25:50.228724+00:00", - "datetime": "2025-05-08T09:22:36.652000+00:00", - "collection": { - "semantics": [ - { - "key": "producer", - "value": "Alice" - }, - { - "key": "transport", - "value": "car" - } - ] - }, - "datetimetz": "2025-05-08T11:22:36.652000+02:00", - "view:azimuth": 28, - "geovisio:status": "ready", - "original_file:size": 6521760, - "geovisio:visibility": "anyone", - "pers:interior_orientation": { - "camera_model": "imajbox 360 HD", - "field_of_view": 360, - "camera_manufacturer": "IMAJING", - "sensor_array_dimensions": [ - 12288, - 6144 - ] - }, - "geovisio:rank_in_collection": 5907, - "quality:horizontal_accuracy": 2.0, - "panoramax:horizontal_pixel_density": 34 - }, - "stac_version": "1.0.0", - "asset_templates": { - "tiles": { - "href": "https://panoramax-storage-public-fast.s3.gra.perf.cloud.ovh.net/derivates/9a/47/98/35/1331-4b8a-adce-f2173f61ffc8/tiles/{TileCol}_{TileRow}.jpg", - "type": "image/jpeg", - "roles": [ - "data" - ], - "title": "HD tiled picture", - "description": "Highest resolution available of this picture, as tiles" - } - }, - "stac_extensions": [ - "https://stac-extensions.github.io/view/v1.0.0/schema.json", - "https://stac-extensions.github.io/perspective-imagery/v1.0.0/schema.json", - "https://stac-extensions.github.io/tiled-assets/v1.0.0/schema.json" - ] - }, - { - "id": "ba1508dd-3154-47d2-aa61-250b5bbca547", - "bbox": [ - 2.345074156, - 48.859906028, - 2.345074156, - 48.859906028 - ], - "type": "Feature", - "links": [ - { - "rel": "license", - "href": "https://alliance.numerique.gouv.fr/licence-ouverte-open-licence/", - "title": "License for this object (etalab-2.0)" - }, - { - "rel": "self", - "href": "https://api.panoramax.xyz/api/collections/600d5cee-5328-4dd4-8838-5f27ef85aa59/items/ba1508dd-3154-47d2-aa61-250b5bbca547", - "type": "application/geo+json" - }, - { - "rel": "via", - "href": "https://panoramax.ign.fr", - "type": "application/json", - "title": "Link to the original instance", - "instance_name": "ign" - } - ], - "assets": { - "hd": { - "href": "{{cdn}}/ba1508dd-3154-47d2-aa61-250b5bbca547/3154-47d2-aa61-250b5bbca547.jpg", - "type": "image/jpeg", - "roles": [ - "data" - ], - "title": "HD picture", - "description": "Highest resolution available of this picture" - }, - "sd": { - "href": "{{cdn}}/ba1508dd-3154-47d2-aa61-250b5bbca547/sd.jpg", - "type": "image/jpeg", - "roles": [ - "visual" - ], - "title": "SD picture", - "description": "Picture in standard definition (fixed width of 2048px)" - }, - "thumb": { - "href": "{{cdn}}/ba1508dd-3154-47d2-aa61-250b5bbca547/thumb.jpg", - "type": "image/jpeg", - "roles": [ - "thumbnail" - ], - "title": "Thumbnail", - "description": "Picture in low definition (fixed width of 500px)" - } - }, - "geometry": { - "type": "Point", - "coordinates": [ - 2.345074156, - 48.859906028 - ] - }, - "providers": [ - { - "name": "alice", - "roles": [ - "producer" - ] - }, - { - "name": "Alice for the City", - "roles": [ - "producer" - ] - } - ], - "collection": "600d5cee-5328-4dd4-8838-5f27ef85aa59", - "properties": { - "created": "2025-12-05T19:45:38.673129+00:00", - "license": "etalab-2.0", - "updated": "2025-12-28T19:37:26.880936+00:00", - "datetime": "2025-05-08T09:22:36.251000+00:00", - "collection": { - "semantics": [ - { - "key": "producer", - "value": "Alice" - }, - { - "key": "transport", - "value": "car" - } - ] - }, - "datetimetz": "2025-05-08T11:22:36.251000+02:00", - "view:azimuth": 28, - "geovisio:status": "ready", - "original_file:size": 6561382, - "geovisio:visibility": "anyone", - "pers:interior_orientation": { - "camera_model": "imajbox 360 HD", - "field_of_view": 360, - "camera_manufacturer": "IMAJING", - "sensor_array_dimensions": [ - 12288, - 6144 - ] - }, - "geovisio:rank_in_collection": 5906, - "quality:horizontal_accuracy": 2.0, - "panoramax:horizontal_pixel_density": 34 - }, - "stac_version": "1.0.0", - "asset_templates": { - "tiles": { - "href": "https://panoramax-storage-public-fast.s3.gra.perf.cloud.ovh.net/derivates/ba/15/08/dd/3154-47d2-aa61-250b5bbca547/tiles/{TileCol}_{TileRow}.jpg", - "type": "image/jpeg", - "roles": [ - "data" - ], - "title": "HD tiled picture", - "description": "Highest resolution available of this picture, as tiles" - } - }, - "stac_extensions": [ - "https://stac-extensions.github.io/view/v1.0.0/schema.json", - "https://stac-extensions.github.io/perspective-imagery/v1.0.0/schema.json", - "https://stac-extensions.github.io/tiled-assets/v1.0.0/schema.json" - ] - }, - { - "id": "b79f56d3-4910-437a-ab3d-480dce9ea64a", - "bbox": [ - 2.345106645, - 48.859944271, - 2.345106645, - 48.859944271 - ], - "type": "Feature", - "links": [ - { - "rel": "license", - "href": "https://alliance.numerique.gouv.fr/licence-ouverte-open-licence/", - "title": "License for this object (etalab-2.0)" - }, - { - "rel": "self", - "href": "https://api.panoramax.xyz/api/collections/600d5cee-5328-4dd4-8838-5f27ef85aa59/items/b79f56d3-4910-437a-ab3d-480dce9ea64a", - "type": "application/geo+json" - }, - { - "rel": "via", - "href": "https://panoramax.ign.fr", - "type": "application/json", - "title": "Link to the original instance", - "instance_name": "ign" - } - ], - "assets": { - "hd": { - "href": "{{cdn}}/b79f56d3-4910-437a-ab3d-480dce9ea64a/4910-437a-ab3d-480dce9ea64a.jpg", - "type": "image/jpeg", - "roles": [ - "data" - ], - "title": "HD picture", - "description": "Highest resolution available of this picture" - }, - "sd": { - "href": "{{cdn}}/b79f56d3-4910-437a-ab3d-480dce9ea64a/sd.jpg", - "type": "image/jpeg", - "roles": [ - "visual" - ], - "title": "SD picture", - "description": "Picture in standard definition (fixed width of 2048px)" - }, - "thumb": { - "href": "{{cdn}}/b79f56d3-4910-437a-ab3d-480dce9ea64a/thumb.jpg", - "type": "image/jpeg", - "roles": [ - "thumbnail" - ], - "title": "Thumbnail", - "description": "Picture in low definition (fixed width of 500px)" - } - }, - "geometry": { - "type": "Point", - "coordinates": [ - 2.345106645, - 48.859944271 - ] - }, - "providers": [ - { - "name": "alice", - "roles": [ - "producer" - ] - }, - { - "name": "Alice for the City", - "roles": [ - "producer" - ] - } - ], - "collection": "600d5cee-5328-4dd4-8838-5f27ef85aa59", - "properties": { - "created": "2025-12-05T19:45:40.163540+00:00", - "license": "etalab-2.0", - "updated": "2025-12-28T20:20:31.844006+00:00", - "datetime": "2025-05-08T09:22:37.042000+00:00", - "collection": { - "semantics": [ - { - "key": "producer", - "value": "Alice" - }, - { - "key": "transport", - "value": "car" - } - ] - }, - "datetimetz": "2025-05-08T11:22:37.042000+02:00", - "view:azimuth": 27, - "geovisio:status": "ready", - "original_file:size": 6558079, - "geovisio:visibility": "anyone", - "pers:interior_orientation": { - "camera_model": "imajbox 360 HD", - "field_of_view": 360, - "camera_manufacturer": "IMAJING", - "sensor_array_dimensions": [ - 12288, - 6144 - ] - }, - "geovisio:rank_in_collection": 5908, - "quality:horizontal_accuracy": 2.0, - "panoramax:horizontal_pixel_density": 34 - }, - "stac_version": "1.0.0", - "asset_templates": { - "tiles": { - "href": "https://panoramax-storage-public-fast.s3.gra.perf.cloud.ovh.net/derivates/b7/9f/56/d3/4910-437a-ab3d-480dce9ea64a/tiles/{TileCol}_{TileRow}.jpg", - "type": "image/jpeg", - "roles": [ - "data" - ], - "title": "HD tiled picture", - "description": "Highest resolution available of this picture, as tiles" - } - }, - "stac_extensions": [ - "https://stac-extensions.github.io/view/v1.0.0/schema.json", - "https://stac-extensions.github.io/perspective-imagery/v1.0.0/schema.json", - "https://stac-extensions.github.io/tiled-assets/v1.0.0/schema.json" - ] - }, - { - "id": "4ff8d96e-5114-4ed5-b593-daea754a6998", - "bbox": [ - -1.680981389, - 48.114966389, - -1.680981389, - 48.114966389 - ], - "type": "Feature", - "links": [ - { - "rel": "license", - "href": "https://creativecommons.org/licenses/by-sa/4.0/", - "title": "License for this object (CC-BY-SA-4.0)" - }, - { - "rel": "self", - "href": "https://api.panoramax.xyz/api/collections/912ed747-c21c-4c04-9c9d-f1e75a51072e/items/4ff8d96e-5114-4ed5-b593-daea754a6998", - "type": "application/geo+json" - }, - { - "rel": "via", - "href": "https://panoramax.openstreetmap.fr", - "type": "application/json", - "title": "Link to the original instance", - "instance_name": "osm-fr" - } - ], - "assets": { - "hd": { - "href": "{{cdn}}/4ff8d96e-5114-4ed5-b593-daea754a6998/5114-4ed5-b593-daea754a6998.jpg", - "type": "image/jpeg", - "roles": [ - "data" - ], - "title": "HD picture", - "description": "Highest resolution available of this picture" - }, - "sd": { - "href": "{{cdn}}/4ff8d96e-5114-4ed5-b593-daea754a6998/sd.jpg", - "type": "image/jpeg", - "roles": [ - "visual" - ], - "title": "SD picture", - "description": "Picture in standard definition (fixed width of 2048px)" - }, - "thumb": { - "href": "{{cdn}}/4ff8d96e-5114-4ed5-b593-daea754a6998/thumb.jpg", - "type": "image/jpeg", - "roles": [ - "thumbnail" - ], - "title": "Thumbnail", - "description": "Picture in low definition (fixed width of 500px)" - } - }, - "geometry": { - "type": "Point", - "coordinates": [ - -1.680981389, - 48.114966389 - ] - }, - "providers": [ - { - "name": "bob", - "roles": [ - "producer" - ] - } - ], - "collection": "912ed747-c21c-4c04-9c9d-f1e75a51072e", - "properties": { - "created": "2023-07-30T10:21:28.425345+00:00", - "license": "CC-BY-SA-4.0", - "updated": "2025-06-03T03:02:44.485815+00:00", - "datetime": "2018-03-27T16:55:15+00:00", - "collection": { - "semantics": [] - }, - "datetimetz": "2018-03-27T16:55:15+00:00", - "view:azimuth": 174, - "geovisio:status": "ready", - "original_file:size": 514943, - "geovisio:visibility": "anyone", - "pers:interior_orientation": { - "camera_model": "FDR-X1000V", - "focal_length": 2.8, - "field_of_view": 96, - "camera_manufacturer": "SONY", - "sensor_array_dimensions": [ - 1920, - 1080 - ] - }, - "geovisio:rank_in_collection": 89, - "quality:horizontal_accuracy": 3.6, - "panoramax:horizontal_pixel_density": 20 - }, - "stac_version": "1.0.0", - "stac_extensions": [ - "https://stac-extensions.github.io/view/v1.0.0/schema.json", - "https://stac-extensions.github.io/perspective-imagery/v1.0.0/schema.json" - ] - }, - { - "id": "3f646b4a-caf0-4b2c-a3a6-f3273f9fc332", - "bbox": [ - -1.680981389, - 48.115098056, - -1.680981389, - 48.115098056 - ], - "type": "Feature", - "links": [ - { - "rel": "license", - "href": "https://creativecommons.org/licenses/by-sa/4.0/", - "title": "License for this object (CC-BY-SA-4.0)" - }, - { - "rel": "self", - "href": "https://api.panoramax.xyz/api/collections/912ed747-c21c-4c04-9c9d-f1e75a51072e/items/3f646b4a-caf0-4b2c-a3a6-f3273f9fc332", - "type": "application/geo+json" - }, - { - "rel": "via", - "href": "https://panoramax.openstreetmap.fr", - "type": "application/json", - "title": "Link to the original instance", - "instance_name": "osm-fr" - } - ], - "assets": { - "hd": { - "href": "{{cdn}}/3f646b4a-caf0-4b2c-a3a6-f3273f9fc332/caf0-4b2c-a3a6-f3273f9fc332.jpg", - "type": "image/jpeg", - "roles": [ - "data" - ], - "title": "HD picture", - "description": "Highest resolution available of this picture" - }, - "sd": { - "href": "{{cdn}}/3f646b4a-caf0-4b2c-a3a6-f3273f9fc332/sd.jpg", - "type": "image/jpeg", - "roles": [ - "visual" - ], - "title": "SD picture", - "description": "Picture in standard definition (fixed width of 2048px)" - }, - "thumb": { - "href": "{{cdn}}/3f646b4a-caf0-4b2c-a3a6-f3273f9fc332/thumb.jpg", - "type": "image/jpeg", - "roles": [ - "thumbnail" - ], - "title": "Thumbnail", - "description": "Picture in low definition (fixed width of 500px)" - } - }, - "geometry": { - "type": "Point", - "coordinates": [ - -1.680981389, - 48.115098056 - ] - }, - "providers": [ - { - "name": "bob", - "roles": [ - "producer" - ] - } - ], - "collection": "912ed747-c21c-4c04-9c9d-f1e75a51072e", - "properties": { - "created": "2023-07-30T10:21:34.688826+00:00", - "license": "CC-BY-SA-4.0", - "updated": "2025-06-03T03:02:44.485815+00:00", - "datetime": "2018-03-27T16:55:53+00:00", - "collection": { - "semantics": [] - }, - "datetimetz": "2018-03-27T16:55:53+00:00", - "view:azimuth": 28, - "geovisio:status": "ready", - "original_file:size": 483044, - "geovisio:visibility": "anyone", - "pers:interior_orientation": { - "camera_model": "FDR-X1000V", - "focal_length": 2.8, - "field_of_view": 96, - "camera_manufacturer": "SONY", - "sensor_array_dimensions": [ - 1920, - 1080 - ] - }, - "geovisio:rank_in_collection": 123, - "quality:horizontal_accuracy": 4.2, - "panoramax:horizontal_pixel_density": 20 - }, - "stac_version": "1.0.0", - "stac_extensions": [ - "https://stac-extensions.github.io/view/v1.0.0/schema.json", - "https://stac-extensions.github.io/perspective-imagery/v1.0.0/schema.json" - ] - } - ], - "links": [] -} \ No newline at end of file diff --git a/cmd/geoguess/main.go b/cmd/geoguess/main.go deleted file mode 100644 index 17723b3..0000000 --- a/cmd/geoguess/main.go +++ /dev/null @@ -1,113 +0,0 @@ -// Command geoguess is GeoGuess, a GeoGuessr-style game for signalbot: the -// bot posts a street-level photo, players answer with a location, and when -// time is up the bot names the place and ranks players by how far off -// they were. -// -// It is an MCP server on stdio (protocol 2025-06-18, newline-delimited -// JSON-RPC) that speaks signalbot's addon extension: signalbot starts it as -// a child process, calls its tools for /geo and for each guess its watch -// catches, and reads its outbox for the results. Stdout carries nothing -// but the protocol. It keeps its state and its own log in GEO_STATE_DIR; -// the log never holds a guess, a coordinate, a name or message text. -// -// Every setting is a GEO_ variable, which signalbot passes to an addon -// server called geo; see README.md. -package main - -import ( - "context" - "fmt" - "log" - "math/rand/v2" - "os" - "os/signal" - "path/filepath" - "runtime/debug" - "syscall" - - "github.com/robdevops/signalbot/cmd/geoguess/geo" - "github.com/robdevops/signalbot/internal/kit/httpx" -) - -// maxLog is the size past which the log is moved aside at start, keeping -// one old log. -const maxLog = 4 << 20 - -func main() { os.Exit(run()) } - -func run() int { - // Stdout is the protocol's: anything else printed by mistake goes to - // stderr, which signalbot counts but never logs. - stdout := os.Stdout - os.Stdout = os.Stderr - cfg, err := loadConfig(os.Getenv) - if err == nil { - err = checkDir(cfg.StateDir) - } - if err != nil { - fmt.Fprintf(os.Stderr, "geoguess: %v\n", err) - return 1 - } - debug.SetMemoryLimit(cfg.MemLimit) - logger, closeLog, err := openLog(cfg.StateDir) - if err != nil { - fmt.Fprintf(os.Stderr, "geoguess: %v\n", err) - return 1 - } - defer closeLog() - if cfg.Token == "" && cfg.Regions == "" { - // Panoramax alone is mostly France: world seeds would mostly search - // empty boxes. - cfg.Regions = "FR" - logger.Printf("GEO_MAPILLARY_TOKEN is not set: Panoramax only, in France unless GEO_REGIONS says otherwise") - } - client := httpx.Client(4) - var sources []geo.Source - if cfg.Token != "" { - sources = append(sources, geo.NewMapillary(cfg.Mapillary, cfg.Token, client)) - } - sources = append(sources, geo.NewPanoramax(cfg.Panoramax, client)) - finder := &search{ - sources: sources, rules: geo.Rules{MinQuality: cfg.MinQuality, MaxAge: cfg.MaxAge}, - places: geo.NewNominatim(cfg.Nominatim, client), rand: rand.New(rand.NewPCG(rand.Uint64(), rand.Uint64())), - log: logger, seeds: map[string]*geo.Seeds{}, regions: cfg.Regions, - } - s, err := newServer(cfg, realClock{}, finder, logger) - if err != nil { - logger.Printf("can't start: %v", err) - fmt.Fprintf(os.Stderr, "geoguess: %v\n", err) - return 1 - } - finder.used = s.isUsed - - ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt) - defer stop() - go s.prefetch(ctx) - done := make(chan error, 1) - go func() { done <- s.serve(ctx, os.Stdin, stdout) }() - select { - case err = <-done: - case <-ctx.Done(): - } - s.save() - if err != nil { - logger.Printf("stopped: %v", err) - return 1 - } - logger.Printf("stopped") - return 0 -} - -// openLog opens GeoGuess's own log, geoguess.log in dir, moving a large one -// aside to geoguess.log.1 first. -func openLog(dir string) (*log.Logger, func(), error) { - path := filepath.Join(dir, "geoguess.log") - if st, err := os.Stat(path); err == nil && st.Size() > maxLog { - os.Rename(path, path+".1") - } - f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0o600) - if err != nil { - return nil, nil, fmt.Errorf("can't open its log in GEO_STATE_DIR: %v", err) - } - return log.New(f, "", log.LstdFlags), func() { f.Close() }, nil -} diff --git a/cmd/geoguess/main_test.go b/cmd/geoguess/main_test.go deleted file mode 100644 index c4129c7..0000000 --- a/cmd/geoguess/main_test.go +++ /dev/null @@ -1,1082 +0,0 @@ -package main - -import ( - "bufio" - "bytes" - "context" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "io" - "log" - "slices" - "strconv" - "strings" - "sync" - "testing" - "time" - - "github.com/robdevops/signalbot/cmd/geoguess/geo" -) - -// fakeClock is a clock whose time moves only when a test says. -type fakeClock struct { - mu sync.Mutex - now time.Time - timers []*fakeTimer -} - -type fakeTimer struct { - at time.Time - f func() - stopped bool -} - -func (t *fakeTimer) Stop() bool { - was := !t.stopped - t.stopped = true - return was -} - -func (c *fakeClock) Now() time.Time { - c.mu.Lock() - defer c.mu.Unlock() - return c.now -} - -func (c *fakeClock) AfterFunc(d time.Duration, f func()) stopper { - c.mu.Lock() - defer c.mu.Unlock() - t := &fakeTimer{at: c.now.Add(d), f: f} - c.timers = append(c.timers, t) - return t -} - -// Advance moves the time on by d, firing the timers then due in order. -func (c *fakeClock) Advance(d time.Duration) { - c.mu.Lock() - c.now = c.now.Add(d) - var due []*fakeTimer - c.timers = slices.DeleteFunc(c.timers, func(t *fakeTimer) bool { - if !t.at.After(c.now) { - due = append(due, t) - return true - } - return false - }) - c.mu.Unlock() - slices.SortStableFunc(due, func(a, b *fakeTimer) int { return a.at.Compare(b.at) }) - for _, t := range due { - if !t.stopped { - t.f() - } - } -} - -// The photos the fake finder offers: one in Ballarat, and one in Paris for -// a round in Europe. -var ( - ballarat = geo.Point{Lat: -37.5622, Lon: 143.8503} - paris = geo.Point{Lat: 48.8566, Lon: 2.3522} -) - -// syncBuffer is a log a test can read while the server may write it. -type syncBuffer struct { - mu sync.Mutex - buf bytes.Buffer -} - -func (b *syncBuffer) Write(p []byte) (int, error) { - b.mu.Lock() - defer b.mu.Unlock() - return b.buf.Write(p) -} - -func (b *syncBuffer) String() string { - b.mu.Lock() - defer b.mu.Unlock() - return b.buf.String() -} - -// fakeFinder finds a photo at once, or never if off: in Ballarat, or in -// Paris for Europe, or with elsewhere for anywhere but AU. It keeps the -// regions it was asked for. -type fakeFinder struct { - mu sync.Mutex - n int - off bool - elsewhere bool - asked []string -} - -func (f *fakeFinder) Find(ctx context.Context, regions string) (geo.Photo, error) { - f.mu.Lock() - f.n++ - n, off, elsewhere := f.n, f.off, f.elsewhere - f.asked = append(f.asked, regions) - f.mu.Unlock() - if off { - <-ctx.Done() - return geo.Photo{}, ctx.Err() - } - p := geo.Photo{ - Candidate: geo.Candidate{ - ID: strconv.Itoa(n), Source: "Mapillary", Creator: "alice", Licence: "CC BY-SA 4.0", - Link: "https://www.mapillary.com/app/?pKey=" + strconv.Itoa(n), At: ballarat, - }, - Place: geo.Place{Name: "Ballarat, Victoria, Australia", Country: "Australia", CountryCode: "AU"}, - JPEG: []byte("jpeg " + strconv.Itoa(n)), - } - if strings.Contains(strings.ToLower(regions), "europe") || elsewhere && regions != "AU" { - p.At, p.Place = paris, geo.Place{Name: "Paris, Île-de-France, France", Country: "France", CountryCode: "FR"} - } - return p, nil -} - -// client drives a server over pipes, as signalbot would, and checks that -// every line the server writes is a valid JSON-RPC message. -type client struct { - t *testing.T - s *server - in *io.PipeWriter - notes chan string - served chan error - done sync.WaitGroup // the reader and the prefetcher - stop context.CancelFunc - - mu sync.Mutex - id int - waiting map[string]chan response - lines int -} - -// rpcIn is a message as the client reads it. -type rpcIn struct { - JSONRPC string `json:"jsonrpc"` - ID json.RawMessage `json:"id"` - Method string `json:"method"` - Result json.RawMessage `json:"result"` - Error *rpcError `json:"error"` -} - -// testServer is a server keeping its state in dir, on clk, with photos from -// the fake finder, and its log in logs; extra settings come from env. -func testServer(t *testing.T, dir string, clk clock, photos finder, logs io.Writer, env ...string) *server { - t.Helper() - vars := map[string]string{"GEO_STATE_DIR": dir, "GEO_BUFFER": "2", "GEO_WAIT": "5s"} - for i := 0; i+1 < len(env); i += 2 { - vars[env[i]] = env[i+1] - } - cfg, err := loadConfig(func(k string) string { return vars[k] }) - if err != nil { - t.Fatal(err) - } - s, err := newServer(cfg, clk, photos, log.New(logs, "", 0)) - if err != nil { - t.Fatal(err) - } - return s -} - -// connect serves s over pipes, with its prefetcher running. -func connect(t *testing.T, s *server) *client { - t.Helper() - inR, inW := io.Pipe() - outR, outW := io.Pipe() - ctx, cancel := context.WithCancel(context.Background()) - c := &client{t: t, s: s, in: inW, notes: make(chan string, 16), served: make(chan error, 1), stop: cancel, waiting: map[string]chan response{}} - c.done.Add(2) - go func() { - defer c.done.Done() - s.prefetch(ctx) - }() - go func() { - err := s.serve(ctx, inR, outW) - outW.Close() - c.served <- err - }() - go func() { - defer c.done.Done() - c.read(outR) - }() - t.Cleanup(c.close) - return c -} - -// read checks and dispatches each line the server writes. -func (c *client) read(r io.Reader) { - sc := bufio.NewScanner(r) - sc.Buffer(nil, 8<<20) - for sc.Scan() { - line := sc.Bytes() - c.mu.Lock() - c.lines++ - c.mu.Unlock() - var m rpcIn - dec := json.NewDecoder(bytes.NewReader(line)) - if err := dec.Decode(&m); err != nil || dec.More() || m.JSONRPC != "2.0" { - c.t.Errorf("stdout has a line that isn't one JSON-RPC message: %.200s", line) - continue - } - switch { - case m.Method != "" && len(m.ID) == 0: - c.notes <- m.Method - case len(m.ID) > 0 && m.Method == "" && (m.Error == nil) != (len(m.Result) == 0): - c.mu.Lock() - ch := c.waiting[string(m.ID)] - delete(c.waiting, string(m.ID)) - c.mu.Unlock() - if ch != nil { - ch <- response{ID: m.ID, Result: m.Result, Error: m.Error} - } - default: - c.t.Errorf("stdout has a message that is neither a response nor a notification: %.200s", line) - } - } -} - -// close ends the session as signalbot does, by closing stdin, and waits for -// the server to finish. -func (c *client) close() { - if c.in == nil { - return - } - c.in.Close() - c.in = nil - select { - case err := <-c.served: - if err != nil { - c.t.Errorf("serve: %v", err) - } - case <-time.After(5 * time.Second): - c.t.Error("the server didn't stop") - } - c.stop() - c.done.Wait() -} - -// send writes one raw line to the server. -func (c *client) send(line string) { - c.t.Helper() - if _, err := io.WriteString(c.in, line+"\n"); err != nil { - c.t.Fatal(err) - } -} - -// request sends a request and waits for its response. -func (c *client) request(method string, params any) response { - c.t.Helper() - c.mu.Lock() - c.id++ - id := strconv.Itoa(c.id) - ch := make(chan response, 1) - c.waiting[id] = ch - c.mu.Unlock() - data, err := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": c.id, "method": method, "params": params}) - if err != nil { - c.t.Fatal(err) - } - c.send(string(data)) - select { - case r := <-ch: - return r - case <-time.After(10 * time.Second): - c.t.Fatalf("no answer to %s", method) - } - return response{} -} - -// result is a request's result, which must not be an error. -func (c *client) result(method string, params any, v any) { - c.t.Helper() - r := c.request(method, params) - if r.Error != nil { - c.t.Fatalf("%s: error %d %s", method, r.Error.Code, r.Error.Message) - } - if err := json.Unmarshal(r.Result.(json.RawMessage), v); err != nil { - c.t.Fatalf("%s: %v", method, err) - } -} - -// from is the context of a message sent now by user in chat. -func from(clk clock, chat, user string) callContext { - return callContext{Chat: chat, Sender: user, Ref: "r_1", Addressed: true, Group: true, Sent: clk.Now().Unix()} -} - -// tool calls a tool as the bot does, with the message's context in _meta. -func (c *client) tool(name string, args map[string]string, ctx callContext) toolResult { - c.t.Helper() - var r toolResult - c.result("tools/call", map[string]any{ - "name": name, "arguments": args, - "_meta": map[string]any{vendor + "context": ctx}, - }, &r) - return r -} - -func (c *client) geo(args string, ctx callContext) toolResult { - c.t.Helper() - return c.tool("geo", map[string]string{"args": args}, ctx) -} - -func (c *client) guess(text string, ctx callContext) toolResult { - c.t.Helper() - return c.tool("geo_guess", map[string]string{"text": text}, ctx) -} - -// read is the outbox page after cursor. -func (c *client) outbox(cursor string) outboxPage { - c.t.Helper() - var r readResult - c.result("resources/read", uriParams{outboxURI + "/" + cursor}, &r) - if len(r.Contents) != 1 || r.Contents[0].MimeType != "application/json" { - c.t.Fatalf("read %+v", r) - } - var p outboxPage - if err := json.Unmarshal([]byte(r.Contents[0].Text), &p); err != nil { - c.t.Fatal(err) - } - return p -} - -// note waits for a notification. -func (c *client) note() string { - c.t.Helper() - select { - case m := <-c.notes: - return m - case <-time.After(5 * time.Second): - c.t.Fatal("no notification") - } - return "" -} - -// words is a tool result's text. -func words(r toolResult) string { - var parts []string - for _, c := range r.Content { - if c.Type == "text" { - parts = append(parts, c.Text) - } - } - return strings.Join(parts, "\n") -} - -func reacted(r toolResult) bool { return r.Meta != nil && r.Meta.React == pin } - -// start is a fake clock, a server and a client, with the session -// initialized and subscribed to the outbox. -func start(t *testing.T) (*fakeClock, *client, *syncBuffer) { - t.Helper() - clk := &fakeClock{now: time.Date(2026, 11, 20, 14, 0, 0, 0, time.UTC)} - logs := &syncBuffer{} - c := connect(t, testServer(t, t.TempDir(), clk, &fakeFinder{}, logs)) - var init initializeResult - c.result("initialize", map[string]any{ - "protocolVersion": protocolVersion, "clientInfo": map[string]string{"name": "signalbot", "version": "1"}, - "capabilities": map[string]any{"experimental": map[string]any{vendor + "addon": map[string]int{"version": 1}}}, - }, &init) - c.send(`{"jsonrpc":"2.0","method":"notifications/initialized"}`) - var empty struct{} - c.result("resources/subscribe", uriParams{outboxURI}, &empty) - return clk, c, logs -} - -const ( - chat = "c_one" - alice = "u_alice" - bob = "u_bob" -) - -// The caption gives the steps for the network the bot said it is on, and -// both when it said none. -func TestCaption(t *testing.T) { - at := time.Date(2026, 11, 20, 14, 3, 0, 0, time.Local) - for _, tc := range []struct{ network, want, not string }{ - {"signal", "Tap **+** → Location, pinch to zoom out, **drag the pin**, confirm, then send.", "📎"}, - {"telegram", "Tap 📎 → Location, pinch to zoom out, **drag the pin**, then send.", "confirm"}, - {"", "Signal: **+** → Location; Telegram: 📎 → Location. Pinch to zoom out, **drag the pin**, confirm (on Signal), then send.", "Tap"}, - } { - got := caption(at, 3*time.Minute, tc.network) - if !strings.Contains(got, tc.want) || strings.Contains(got, tc.not) || !strings.Contains(got, "14:03 (3 min)") || - !strings.Contains(got, "-37.81, 144.96") || !strings.Contains(got, "Move the pin before you send") { - t.Errorf("%q: %q", tc.network, got) - } - } -} - -// A round's caption uses the network the bot offered in the handshake. -func TestCaptionNetwork(t *testing.T) { - clk, c, _ := start(t) - var init initializeResult - c.result("initialize", map[string]any{ - "protocolVersion": protocolVersion, - "capabilities": map[string]any{"experimental": map[string]any{vendor + "addon": map[string]any{"version": 1, "network": "signal"}}}, - }, &init) - r := c.geo("90s", from(clk, chat, alice)) - if got := words(r); !strings.Contains(got, "Tap **+** → Location") || strings.Contains(got, "📎") { - t.Errorf("caption %q", got) - } -} - -func TestInitializeAndTools(t *testing.T) { - _, c, _ := start(t) - var init initializeResult - c.result("initialize", map[string]any{"protocolVersion": "2099-01-01"}, &init) - if init.ProtocolVersion != protocolVersion || init.Capabilities.Experimental[vendor+"addon"].Version != 1 || - !init.Capabilities.Resources.Subscribe || init.ServerInfo.Name != "geoguess" { - t.Errorf("initialize %+v", init) - } - var list struct { - Tools []tool `json:"tools"` - } - c.result("tools/list", struct{}{}, &list) - var names []string - for _, tl := range list.Tools { - names = append(names, tl.Name) - if !slices.Equal(tl.Meta.Visibility, []string{"bot"}) || tl.InputSchema.Type != "object" { - t.Errorf("tool %+v", tl) - } - } - if !slices.Equal(names, []string{"geo", "geo_guess"}) { - t.Errorf("tools %v", names) - } - var pong struct{} - c.result("ping", nil, &pong) - if r := c.request("tools/call", map[string]any{"name": "nope"}); r.Error == nil || r.Error.Code != codeInvalidParams { - t.Errorf("unknown tool %+v", r) - } - if r := c.request("resources/read", uriParams{"file:///etc/passwd"}); r.Error == nil || r.Error.Code != codeNotFound { - t.Errorf("another resource %+v", r) - } - // Called without a chat, as another MCP client might. - var r toolResult - c.result("tools/call", map[string]any{"name": "geo", "arguments": map[string]string{"args": ""}}, &r) - if !r.IsError || words(r) != noChat { - t.Errorf("no context %+v", r) - } -} - -// A whole round: the photo with its watch, guesses, the timer, and the -// results in the outbox. -func TestRound(t *testing.T) { - clk, c, logs := start(t) - began := clk.Now() - r := c.geo("90s", from(clk, chat, alice)) - if len(r.Content) != 2 || r.Content[0].Type != "image" || r.Content[0].MimeType != "image/jpeg" { - t.Fatalf("content %+v", r.Content) - } - if data, _ := base64.StdEncoding.DecodeString(r.Content[0].Data); !bytes.HasPrefix(data, []byte("jpeg ")) { - t.Errorf("image %q", data) - } - want := caption(began.Add(90*time.Second), 90*time.Second, "") - if words(r) != want || !strings.Contains(want, "(90 sec)") { - t.Errorf("caption %q", words(r)) - } - if r.Meta == nil || r.Meta.Watch == nil { - t.Fatalf("no watch: %+v", r.Meta) - } - w := *r.Meta.Watch - if w.ID == "" || w.Pattern != geo.Pattern || w.Tool != "geo_guess" || w.Guard != guard || - w.Until != began.Add(95*time.Second).Format(time.RFC3339) { - t.Errorf("watch %+v", w) - } - - if got := words(c.geo("", from(clk, chat, bob))); got != "A round is on: 1m30s left." { - t.Errorf("a second /geo: %q", got) - } - clk.Advance(10 * time.Second) - if r := c.guess("https://maps.google.com/maps?q=-37.6%2C143.9", from(clk, chat, alice)); !reacted(r) { - t.Errorf("Alice's guess: %+v", r) - } - if r := c.guess("I reckon -33.87, 151.21", from(clk, chat, bob)); !reacted(r) { - t.Errorf("Bob's guess: %+v", r) - } - if r := c.guess("see you at 5", from(clk, chat, bob)); reacted(r) { - t.Errorf("no location, but %+v", r) - } - if r := c.guess("-33.87, 151.21", from(clk, "c_two", bob)); reacted(r) || words(r) != noRound { - t.Errorf("a guess in another chat: %+v", r) - } - if p := c.outbox("0"); len(p.Ops) != 0 { - t.Errorf("ops before time is up: %+v", p) - } - - clk.Advance(80*time.Second + settle) - if m := c.note(); m != "notifications/resources/updated" { - t.Errorf("notification %q", m) - } - page := c.outbox("0") - aliceKm, bobKm := geo.Km(geo.Point{Lat: -37.6, Lon: 143.9}, ballarat), geo.Km(geo.Point{Lat: -33.87, Lon: 151.21}, ballarat) - results := "📍 [**Ballarat, Victoria, Australia**](https://www.openstreetmap.org/?mlat=-37.56220&mlon=143.85030#map=12/-37.56220/143.85030)\n" + - "🥇 {u_alice} " + geo.Distance(aliceKm) + " · " + geo.Thousands(geo.Points(aliceKm)) + "\n" + - "🥈 {u_bob} " + geo.Distance(bobKm) + " · " + geo.Thousands(geo.Points(bobKm)) + "\n" + - "Photo: [alice, Mapillary, CC BY-SA 4.0](https://www.mapillary.com/app/?pKey=1)" - if len(page.Ops) != 2 || page.More { - t.Fatalf("page %+v", page) - } - if o := page.Ops[0]; o.Op != "post" || o.Chat != chat || o.Text != results { - t.Errorf("post %+v\nwant %q", o, results) - } - if o := page.Ops[1]; o.Op != "unwatch" || o.Chat != chat || o.Watch != w.ID || o.ID != page.Cursor { - t.Errorf("unwatch %+v, cursor %s", o, page.Cursor) - } - if strings.Contains(page.Ops[0].Text, "151.2") || strings.Contains(page.Ops[0].Text, "-33.8") { - t.Error("the results say where Bob guessed") - } - if again := c.outbox(page.Cursor); len(again.Ops) != 0 || again.Cursor != page.Cursor { - t.Errorf("read past: %+v", again) - } - if r := c.guess("-37.56, 143.85", from(clk, chat, bob)); reacted(r) || words(r) != noRound { - t.Errorf("a guess after the round: %+v", r) - } - scores := c.geo("scores", from(clk, chat, bob)) - wantScores := "🏆 **Scores, last 7 days**\n🥇 {u_alice} " + geo.Thousands(geo.Points(aliceKm)) + " · 1 round\n🥈 {u_bob} " + geo.Thousands(geo.Points(bobKm)) + " · 1 round" - if words(scores) != wantScores { - t.Errorf("scores %q", words(scores)) - } - clk.Advance(8 * 24 * time.Hour) - if got := words(c.geo("scores", from(clk, chat, bob))); !strings.HasPrefix(got, "No scores") { - t.Errorf("scores a week later: %q", got) - } - - c.close() - for _, secret := range []string{"143.9", "151.2", "-33.8", "u_alice", "u_bob", "c_one", "maps.google", "reckon", "Ballarat"} { - if strings.Contains(logs.String(), secret) { - t.Errorf("the log holds %q:\n%s", secret, logs) - } - } - if !strings.Contains(logs.String(), "revealed: 2 guesses") { - t.Errorf("log:\n%s", logs) - } -} - -// An edited guess replaces the first; a late one, or an edit of a message -// from before the round, doesn't count. -func TestEditAndLateGuess(t *testing.T) { - clk, c, _ := start(t) - c.geo("1m", from(clk, chat, alice)) - clk.Advance(10 * time.Second) - first := from(clk, chat, alice) - if !reacted(c.guess("-33.87, 151.21", first)) { - t.Fatal("Alice's first guess") - } - clk.Advance(10 * time.Second) - edit := first - edit.Edited = clk.Now().Unix() - if !reacted(c.guess("geo:-37.57,143.86", edit)) { - t.Fatal("Alice's edit") - } - old := from(clk, chat, bob) - old.Sent, old.Edited = clk.Now().Add(-time.Hour).Unix(), clk.Now().Unix() - if r := c.guess("-37.56, 143.85", old); reacted(r) { - t.Errorf("an edit of an older message counted: %+v", r) - } - clk.Advance(41 * time.Second) // a second past the deadline, before the reveal - if r := c.guess("-37.56, 143.85", from(clk, chat, bob)); reacted(r) || words(r) != "Too late for this round." { - t.Errorf("a late guess: %+v", r) - } - clk.Advance(settle) - c.note() - ops := c.outbox("0").Ops - km := geo.Km(geo.Point{Lat: -37.57, Lon: 143.86}, ballarat) - if len(ops) != 2 || !strings.Contains(ops[0].Text, "\n🥇 {u_alice} "+geo.Distance(km)+" ·") || strings.Contains(ops[0].Text, "u_bob") || strings.Contains(ops[0].Text, "🥈") { - t.Errorf("results %+v", ops) - } -} - -// Only the player who started a round may end or skip it; a skip scores -// nothing, and an end reveals at once. -func TestEndAndSkip(t *testing.T) { - clk, c, _ := start(t) - if got := words(c.geo("end", from(clk, chat, alice))); got != noRound { - t.Errorf("end with no round: %q", got) - } - c.geo("", from(clk, chat, alice)) - if got := words(c.geo("end", from(clk, chat, bob))); got != "Only the player who started this round can end it." { - t.Errorf("Bob ends: %q", got) - } - if got := words(c.geo("SKIP", from(clk, chat, bob))); got != "Only the player who started this round can skip it." { - t.Errorf("Bob skips: %q", got) - } - c.guess("-37.6, 143.9", from(clk, chat, bob)) - skipped := words(c.geo("skip", from(clk, chat, alice))) - if !strings.HasPrefix(skipped, "Round skipped. It was 📍 [**Ballarat, Victoria, Australia**](") || strings.Contains(skipped, "u_bob") { - t.Errorf("skip: %q", skipped) - } - c.note() - page := c.outbox("0") - if len(page.Ops) != 1 || page.Ops[0].Op != "unwatch" { - t.Errorf("after a skip: %+v", page) - } - if got := words(c.geo("scores", from(clk, chat, alice))); !strings.HasPrefix(got, "No scores") { - t.Errorf("a skip scored: %q", got) - } - - c.geo("5m", from(clk, chat, alice)) - clk.Advance(time.Minute) - c.guess("-37.6, 143.9", from(clk, chat, bob)) - ended := words(c.geo("end", from(clk, chat, alice))) - if !strings.Contains(ended, "\n🥇 {u_bob} ") { - t.Errorf("end: %q", ended) - } - c.note() - page = c.outbox(page.Cursor) - if len(page.Ops) != 1 || page.Ops[0].Op != "unwatch" { - t.Errorf("after an end: %+v", page) - } - clk.Advance(5 * time.Minute) // the round's timer, stopped - if p := c.outbox(page.Cursor); len(p.Ops) != 0 { - t.Errorf("the timer of an ended round fired: %+v", p) - } - if got := words(c.geo("scores", from(clk, chat, alice))); !strings.Contains(got, "🥇 {u_bob} ") { - t.Errorf("scores %q", got) - } -} - -// A cursor the server doesn't know, such as one from before a restart, -// gets everything it still holds; one it gave lets go of what was read. -func TestUnknownCursor(t *testing.T) { - clk, c, _ := start(t) - c.geo("30s", from(clk, chat, alice)) - clk.Advance(30*time.Second + settle) - c.note() - for _, cursor := range []string{"0", "k7f2.18", "garbage", c.s.nonce + ".99", c.s.nonce + ".-1"} { - if p := c.outbox(cursor); len(p.Ops) != 2 { - t.Errorf("cursor %q: %+v", cursor, p) - } - } - p := c.outbox(c.s.nonce + ".1") // read the post, not the unwatch - if len(p.Ops) != 1 || p.Ops[0].Op != "unwatch" { - t.Errorf("after the post: %+v", p) - } - p = c.outbox(p.Cursor) - if len(p.Ops) != 0 { - t.Errorf("after all: %+v", p) - } - if again := c.outbox("unknown"); len(again.Ops) != 0 || again.Cursor != p.Cursor { - t.Errorf("nothing held: %+v", again) - } -} - -// A round survives a restart: its guesses are kept, its timer re-armed, and -// one whose time passed while GeoGuess was down is revealed at once. -func TestRestart(t *testing.T) { - clk := &fakeClock{now: time.Date(2026, 11, 20, 14, 0, 0, 0, time.UTC)} - dir := t.TempDir() - var logs syncBuffer - c := connect(t, testServer(t, dir, clk, &fakeFinder{}, &logs)) - c.geo("1m", from(clk, chat, alice)) - c.geo("1m", from(clk, "c_two", bob)) - clk.Advance(10 * time.Second) - c.guess("-37.6, 143.9", from(clk, chat, alice)) - c.guess("-37.6, 143.9", from(clk, "c_two", alice)) - c.close() - - // Back before c_one's deadline, with a new clock: the old timers are gone. - clk = &fakeClock{now: clk.Now().Add(20 * time.Second)} - c = connect(t, testServer(t, dir, clk, &fakeFinder{}, &logs)) - c.result("resources/subscribe", uriParams{outboxURI}, new(struct{})) - if got := words(c.geo("", from(clk, chat, bob))); got != "A round is on: 30s left." { - t.Errorf("after a restart: %q", got) - } - c.guess("-33.87, 151.21", from(clk, chat, bob)) - c.close() - - // Back after both deadlines: both rounds are revealed at once. - clk = &fakeClock{now: clk.Now().Add(time.Hour - 2*time.Minute)} - s := testServer(t, dir, clk, &fakeFinder{}, &logs) - c = connect(t, s) - c.result("resources/subscribe", uriParams{outboxURI}, new(struct{})) - c.note() - page := c.outbox("old.4") - if len(page.Ops) != 4 { - t.Fatalf("ops %+v", page) - } - ids := map[string]bool{} - for _, o := range page.Ops { - ids[o.ID] = true - if o.Op == "post" && o.Chat == chat && (!strings.Contains(o.Text, "🥇 {u_alice}") || !strings.Contains(o.Text, "🥈 {u_bob}")) { - t.Errorf("results %q", o.Text) - } - } - if len(ids) != 4 { - t.Errorf("op IDs %v", ids) - } - c.close() - - // Unread ops outlive another restart, with the same IDs, so the bot can - // tell those it already applied. - c = connect(t, testServer(t, dir, clk, &fakeFinder{}, &logs)) - again := c.outbox("0") - if len(again.Ops) != 4 { - t.Fatalf("after another restart: %+v", again) - } - for _, o := range again.Ops { - if !ids[o.ID] { - t.Errorf("op %s changed its ID", o.ID) - } - } - if got := words(c.geo("", from(clk, chat, bob))); !strings.HasPrefix(got, "🌍") { - t.Errorf("a new round: %q", got) - } - // Ops unread for an hour are let go; only the new round's are left. - clk.Advance(keepOps + time.Second) - if p := c.outbox("0"); len(p.Ops) != 2 || ids[p.Ops[0].ID] || ids[p.Ops[1].ID] { - t.Errorf("an hour on: %+v", p) - } -} - -// Stdout carries only JSON-RPC, whatever arrives on stdin. -func TestStdoutIsProtocol(t *testing.T) { - _, c, _ := start(t) - c.send("not json") - c.send("") - c.send(`{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":1}}`) - c.send(`{"jsonrpc":"2.0","id":99,"result":{}}`) - c.send(`{"id":"x"` + strings.Repeat(" ", maxLine) + `}`) - if r := c.request("nope/nope", nil); r.Error == nil || r.Error.Code != codeNoMethod { - t.Errorf("unknown method %+v", r) - } - if r := c.request("tools/call", "not an object"); r.Error == nil || r.Error.Code != codeInvalidParams { - t.Errorf("bad params %+v", r) - } - c.result("ping", nil, new(struct{})) - c.close() - // initialize, subscribe, the parse error, nope/nope, tools/call and ping. - if c.lines != 6 { - t.Errorf("%d lines on stdout", c.lines) - } -} - -func TestNoPhotoAndRegions(t *testing.T) { - clk := &fakeClock{now: time.Date(2026, 11, 20, 14, 0, 0, 0, time.UTC)} - photos := &fakeFinder{off: true} - s := testServer(t, t.TempDir(), clk, photos, io.Discard) - s.cfg.Wait = 50 * time.Millisecond - c := connect(t, s) - began := time.Now() - if got := words(c.geo("", from(clk, chat, alice))); got != noPhoto { - t.Errorf("no photo: %q", got) - } - if waited := time.Since(began); waited < s.cfg.Wait { - t.Errorf("gave up after %s, before GEO_WAIT", waited) - } - - clk, c, _ = start(t) - r := c.geo("Europe 2m", from(clk, chat, alice)) - if !strings.Contains(words(r), "(2 min)") { - t.Errorf("caption %q", words(r)) - } - if got := words(c.geo("end", from(clk, chat, alice))); !strings.Contains(got, "Paris") { - t.Errorf("a round in Europe: %q", got) - } - for _, args := range []string{"atlantis", "10s", "31m", "2x"} { - if r := c.geo(args, from(clk, chat, alice)); r.Meta != nil { - t.Errorf("/geo %s started a round", args) - } - } - if got := words(c.geo("", from(clk, chat, alice))); !strings.HasPrefix(got, "🌍") { - t.Errorf("a round anywhere: %q", got) - } - if got := words(c.geo("end", from(clk, chat, alice))); !strings.Contains(got, "Ballarat") { - t.Errorf("a world round: %q", got) - } -} - -func TestConfig(t *testing.T) { - env := func(m map[string]string) func(string) string { return func(k string) string { return m[k] } } - c, err := loadConfig(env(map[string]string{"GEO_STATE_DIR": "/x"})) - if err != nil || c.Round != 3*time.Minute || c.MemLimit != 200<<20 || c.Buffer != 3 || c.MinQuality != 0.5 || c.Keep != nil || c.Wait != 50*time.Second || - c.Nominatim != geo.NominatimURL || c.Panoramax != geo.PanoramaxURL || c.Mapillary != geo.MapillaryURL || c.MaxAge < 10*365*24*time.Hour { - t.Errorf("defaults %+v, %v", c, err) - } - c, err = loadConfig(env(map[string]string{"GEO_STATE_DIR": "/x", "GEO_ROUND": "90s", "GEO_MEMLIMIT": "1GiB", "GEO_REGIONS": "europe", "GEO_BUFFER": "5", - "GEO_KEEP": " AU, europe,", "GEO_WAIT": "110s"})) - if err != nil || c.Round != 90*time.Second || c.MemLimit != 1<<30 || c.Regions != "europe" || c.Buffer != 5 || - !slices.Equal(c.Keep, []string{"AU", "europe"}) || c.Wait != 110*time.Second { - t.Errorf("set %+v, %v", c, err) - } - _, err = loadConfig(env(map[string]string{"GEO_ROUND": "1h", "GEO_MEMLIMIT": "lots", "GEO_REGIONS": "atlantis", "GEO_BUFFER": "0", "GEO_KEEP": "AU,atlantis", "GEO_WAIT": "4s", - "GEO_MIN_QUALITY": "2", "GEO_MAX_AGE_YEARS": "-1", "GEO_NOMINATIM_URL": "http://x", - "GEO_PANORAMAX_URL": "ftp://x", "GEO_MAPILLARY_URL": "graph.example"})) - for _, name := range []string{"GEO_STATE_DIR", "GEO_ROUND", "GEO_MEMLIMIT", "GEO_REGIONS", "GEO_BUFFER", "GEO_KEEP", "GEO_WAIT", "GEO_MIN_QUALITY", "GEO_MAX_AGE_YEARS", - "GEO_NOMINATIM_URL", "GEO_PANORAMAX_URL", "GEO_MAPILLARY_URL"} { - if err == nil || !strings.Contains(err.Error(), name) { - t.Errorf("no error for %s: %v", name, err) - } - } - for _, v := range []string{"2m", "soon", "0"} { - if _, err := loadConfig(env(map[string]string{"GEO_STATE_DIR": "/x", "GEO_WAIT": v})); err == nil || !strings.Contains(err.Error(), "GEO_WAIT") { - t.Errorf("GEO_WAIT %s: %v", v, err) - } - } - for s, want := range map[string]int64{"200MiB": 200 << 20, "1GiB": 1 << 30, "67108864": 64 << 20, "65536KiB": 64 << 20, "0.5GiB": 512 << 20} { - if got, err := parseSize(s); got != want || err != nil { - t.Errorf("parseSize(%q) = %d, %v", s, got, err) - } - } - for _, s := range []string{"", "1MiB", "-5MiB", "200MB", "MiB"} { - if _, err := parseSize(s); err == nil { - t.Errorf("parseSize(%q) passed", s) - } - } - if err := checkDir(t.TempDir()); err != nil { - t.Error(err) - } - if err := checkDir(t.TempDir() + "/missing"); err == nil || !strings.Contains(err.Error(), "GEO_STATE_DIR") { - t.Errorf("a missing directory: %v", err) - } -} - -// waitFor fails the test unless ok holds within a few seconds, checked -// with s.mu held. -func waitFor(t *testing.T, s *server, what string, ok func() bool) { - t.Helper() - for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(5 * time.Millisecond) { - s.mu.Lock() - done := ok() - s.mu.Unlock() - if done { - return - } - if time.Now().After(deadline) { - t.Fatalf("waited for %s", what) - } - } -} - -// count is how many photos in the buffer are in region. s.mu is held. -func (s *server) count(region string) int { - n := 0 - for _, p := range s.buffer { - if s.in(p, region) { - n++ - } - } - return n -} - -// With GEO_KEEP=AU the prefetcher keeps an Australian photo ready with no -// /geo asking, a /geo AU takes it at once, and it is replaced. -func TestKeep(t *testing.T) { - clk := &fakeClock{now: time.Date(2026, 11, 20, 14, 0, 0, 0, time.UTC)} - photos := &fakeFinder{elsewhere: true} - s := testServer(t, t.TempDir(), clk, photos, io.Discard, "GEO_KEEP", "AU") - for range s.cfg.Buffer { - p, _ := photos.Find(context.Background(), "") - s.add(p, "") - } - c := connect(t, s) - var ready string - waitFor(t, s, "an AU photo", func() bool { - if i := s.match("AU"); i >= 0 { - ready = s.buffer[i].Link - } - return ready != "" - }) - photos.mu.Lock() - if asked := photos.asked[s.cfg.Buffer:]; !slices.Equal(asked, []string{"AU"}) { - t.Errorf("searched %q", asked) - } - photos.mu.Unlock() - - if got := words(c.geo("end", from(clk, chat, alice))); got != noRound { - t.Errorf("end with no round: %q", got) - } - r := c.geo("AU 2m", from(clk, chat, alice)) - if r.Meta == nil { - t.Fatalf("/geo AU: %q", words(r)) - } - s.mu.Lock() - if got := s.rounds[chat].Credit.Link; got != ready { - t.Errorf("/geo AU used %s, not the photo kept ready", got) - } - s.mu.Unlock() - if got := words(c.geo("end", from(clk, chat, alice))); !strings.Contains(got, "Ballarat") { - t.Errorf("a round in AU: %q", got) - } - waitFor(t, s, "a new AU photo", func() bool { return s.count("AU") == 1 }) - photos.mu.Lock() - if asked := photos.asked[s.cfg.Buffer:]; !slices.Equal(asked, []string{"AU", "AU"}) { - t.Errorf("searched %q", asked) - } - photos.mu.Unlock() -} - -// Trimming the buffer never drops a GEO_KEEP region's last photo. -func TestKeepTrim(t *testing.T) { - clk := &fakeClock{now: time.Date(2026, 11, 20, 14, 0, 0, 0, time.UTC)} - photos := &fakeFinder{elsewhere: true} - s := testServer(t, t.TempDir(), clk, photos, io.Discard, "GEO_KEEP", "AU") - find := func(region string) geo.Photo { - p, err := photos.Find(context.Background(), region) - if err != nil { - t.Fatal(err) - } - return p - } - s.add(find("AU"), "AU") - limit := s.cfg.Buffer + extraPhotos - for range limit + 3 { - s.add(find(""), "") - } - s.mu.Lock() - n, au, first := len(s.buffer), s.count("AU"), s.buffer[0].ID - s.mu.Unlock() - if n != limit || au != 1 || first != "1" { - t.Errorf("%d photos, %d in AU, the oldest %s", n, au, first) - } - - // A second AU photo makes the first one droppable again. - s.add(find("AU"), "AU") - s.mu.Lock() - n, au = len(s.buffer), s.count("AU") - s.mu.Unlock() - if n != limit || au != 1 { - t.Errorf("%d photos, %d in AU", n, au) - } -} - -// failIn is the fake finder, failing every search in one region. -type failIn struct { - *fakeFinder - region string -} - -func (f failIn) Find(ctx context.Context, regions string) (geo.Photo, error) { - if regions == f.region { - f.mu.Lock() - f.asked = append(f.asked, regions) - f.mu.Unlock() - return geo.Photo{}, errors.New("nothing good there") - } - return f.fakeFinder.Find(ctx, regions) -} - -// A GEO_KEEP region whose searches fail waits its own backoff, and the -// buffer still fills meanwhile. -func TestKeepFailing(t *testing.T) { - clk := &fakeClock{now: time.Date(2026, 11, 20, 14, 0, 0, 0, time.UTC)} - photos := failIn{&fakeFinder{elsewhere: true}, "AU"} - s := testServer(t, t.TempDir(), clk, photos, io.Discard, "GEO_KEEP", "AU") - connect(t, s) - waitFor(t, s, "a full buffer", func() bool { return len(s.buffer) == s.cfg.Buffer }) - s.mu.Lock() - r, au := s.retries["AU"], s.count("AU") - s.mu.Unlock() - if r.failures != 1 || au != 0 { - t.Errorf("retry %+v, %d in AU", r, au) - } - photos.mu.Lock() - if asked := photos.asked; !slices.Equal(asked, []string{"AU", "", ""}) { - t.Errorf("searched %q", asked) - } - photos.mu.Unlock() -} - -// A plain /geo takes a photo GEO_KEEP can spare, leaving the kept one. -func TestKeepPlainTake(t *testing.T) { - clk := &fakeClock{now: time.Date(2026, 11, 20, 14, 0, 0, 0, time.UTC)} - photos := &fakeFinder{elsewhere: true} - s := testServer(t, t.TempDir(), clk, photos, io.Discard, "GEO_KEEP", "AU") - for _, region := range []string{"AU", ""} { - p, _ := photos.Find(context.Background(), region) - s.add(p, region) - } - c := connect(t, s) - if r := c.geo("", from(clk, chat, alice)); r.Meta == nil { - t.Fatalf("/geo: %q", words(r)) - } - s.mu.Lock() - place, au := s.rounds[chat].Place, s.count("AU") - s.mu.Unlock() - if !strings.Contains(place, "Paris") || au != 1 { - t.Errorf("/geo used a photo in %s, leaving %d in AU", place, au) - } -} - -// A /geo the bot gives up on starts no round: one cancelled while it waits -// leaves the photo found later ready, and one whose call is over when its -// photo is taken puts it back. Near the bot's deadline it doesn't wait. -func TestGeoAbandoned(t *testing.T) { - clk := &fakeClock{now: time.Date(2026, 11, 20, 14, 0, 0, 0, time.UTC)} - photos := &fakeFinder{off: true} - s := testServer(t, t.TempDir(), clk, photos, io.Discard) - c := connect(t, s) - got := make(chan response, 1) - c.mu.Lock() - c.waiting["99"] = got - c.mu.Unlock() - data, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": 99, "method": "tools/call", "params": map[string]any{ - "name": "geo", "arguments": map[string]string{"args": ""}, "_meta": map[string]any{vendor + "context": from(clk, chat, alice)}, - }}) - c.send(string(data)) - time.Sleep(100 * time.Millisecond) // for it to wait - began := time.Now() - c.send(`{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":99}}`) - select { - case r := <-got: - var res toolResult - json.Unmarshal(r.Result.(json.RawMessage), &res) - if words(res) != noPhoto || time.Since(began) > time.Second { - t.Errorf("cancelled: %q after %s", words(res), time.Since(began)) - } - case <-time.After(3 * time.Second): - t.Fatal("the cancelled /geo went on waiting") - } - p := geo.Photo{Candidate: geo.Candidate{ID: "1", Source: "Mapillary", At: ballarat}, - Place: geo.Place{Name: "Ballarat, Victoria, Australia", Country: "Australia", CountryCode: "AU"}} - s.add(p, "") - time.Sleep(50 * time.Millisecond) - s.mu.Lock() - n, round := len(s.buffer), s.rounds[chat] - s.mu.Unlock() - if n != 1 || round != nil { - t.Errorf("%d photos ready, round %+v", n, round) - } - - ctx, cancel := context.WithCancel(context.Background()) - cancel() - cc := from(clk, chat, alice) - if got := words(s.start(ctx, &cc, s.cfg.Round, "")); got != noPhoto { - t.Errorf("start, the call over: %q", got) - } - s.mu.Lock() - n, round = len(s.buffer), s.rounds[chat] - s.mu.Unlock() - if n != 1 || round != nil { - t.Errorf("after the call was over: %d photos ready, round %+v", n, round) - } - - cc = from(clk, "c_two", bob) - cc.Deadline = time.Now().Add(replyTime).Unix() - began = time.Now() - if got := words(c.geo("Europe", cc)); got != noPhoto || time.Since(began) > time.Second { - t.Errorf("near the deadline: %q after %s", got, time.Since(began)) - } -} - -func TestLabels(t *testing.T) { - for d, want := range map[time.Duration]string{3 * time.Minute: "3 min", 90 * time.Second: "90 sec", 30 * time.Minute: "30 min"} { - if got := lengthLabel(d); got != want { - t.Errorf("lengthLabel(%s) = %q", d, got) - } - } - r := &round{Deadline: time.Unix(1000, 0)} - for left, want := range map[time.Duration]string{30 * time.Second: "30s", 2 * time.Minute: "2m", 102 * time.Second: "1m42s", -time.Second: "0s"} { - if got := words(busy(r, r.Deadline.Add(-left))); got != fmt.Sprintf("A round is on: %s left.", want) { - t.Errorf("busy %s: %q", left, got) - } - } - if got := (credit{Creator: "[bob](https://evil.example)*", Source: "Panoramax", Licence: "etalab-2.0", Link: "https://x.example/p"}).String(); got != "Photo: [bobhttps://evil.example, Panoramax, etalab-2.0](https://x.example/p)" { - t.Errorf("credit %q", got) - } - if got := (credit{Source: "Mapillary"}).String(); got != "Photo: Mapillary" { - t.Errorf("credit %q", got) - } - if !validID("u_ABC234", "u_") || validID("u_", "u_") || validID("u_a}b", "u_") || validID("c_x", "u_") { - t.Error("validID") - } -} diff --git a/cmd/geoguess/prefetch.go b/cmd/geoguess/prefetch.go deleted file mode 100644 index 1b2bedd..0000000 --- a/cmd/geoguess/prefetch.go +++ /dev/null @@ -1,320 +0,0 @@ -package main - -import ( - "context" - "errors" - "log" - "maps" - "math/rand/v2" - "slices" - "strings" - "time" - - "github.com/robdevops/signalbot/cmd/geoguess/geo" -) - -// finder finds a photo worth a round in regions ("" is GEO_REGIONS): the -// real search, or a test's. -type finder interface { - Find(ctx context.Context, regions string) (geo.Photo, error) -} - -// The prefetcher's limits: one search's time, and the photos kept beyond -// GEO_BUFFER for rounds in other regions. -const ( - findTimeout = 3 * time.Minute - extraPhotos = 4 -) - -// retry is when a GEO_KEEP region whose search failed is searched again, -// and how many times in a row it has failed. -type retry struct { - at time.Time - failures int -} - -// prefetch keeps GEO_BUFFER checked photos ready, so /geo answers at once, -// and looks for one in each region a /geo asked for. It is the only caller -// of Find. A GEO_KEEP region whose search fails waits its own backoff, -// while the rest go on, so one hard region can't starve the buffer. -func (s *server) prefetch(ctx context.Context) { - failures := 0 - for { - region, ok, next := s.nextSearch(time.Now()) - if !ok { - if !s.idle(ctx, next) { - return - } - continue - } - fctx, cancel := context.WithTimeout(ctx, findTimeout) - p, err := s.photos.Find(fctx, region) - cancel() - if ctx.Err() != nil { - return - } - if err == nil { - failures = 0 - s.add(p, region) - continue - } - s.mu.Lock() - delete(s.wants, region) // asked again by the next /geo for it - keep := slices.Contains(s.cfg.Keep, region) - var wait time.Duration - if keep { - r := s.retries[region] - wait = backoff(r.failures, err) - s.retries[region] = retry{time.Now().Add(wait), min(r.failures+1, 10)} - } - s.mu.Unlock() - if keep && !errors.Is(err, geo.ErrSlowDown) { - s.log.Printf("no photo found for a kept region (%v); trying it again in %s", err, wait) - continue - } - wait = backoff(failures, err) - failures = min(failures+1, 10) - s.log.Printf("no photo found (%v); trying again in %s", err, wait) - t := time.NewTimer(wait) - select { - case <-t.C: - case <-ctx.Done(): - t.Stop() - return - } - } -} - -// backoff is how long to wait after failures failed searches in a row and -// then err: from 5s, doubling to 5 minutes, or a minute when asked to slow -// down. -func backoff(failures int, err error) time.Duration { - if errors.Is(err, geo.ErrSlowDown) { - return time.Minute - } - return min(5*time.Second<<failures, 5*time.Minute) -} - -// idle waits for work: a wake, or next, when a GEO_KEEP region may be -// searched again (zero for none). It is false once ctx is done. -func (s *server) idle(ctx context.Context, next time.Time) bool { - var due <-chan time.Time - if !next.IsZero() { - t := time.NewTimer(time.Until(next)) - defer t.Stop() - due = t.C - } - select { - case <-s.wake: - case <-due: - case <-ctx.Done(): - return false - } - return true -} - -// nextSearch is the region to look in next: the first a /geo asked for -// that the buffer lacks, else the first GEO_KEEP region it lacks whose -// retry is due at now, else GEO_REGIONS while the buffer isn't full. With -// none, next is the earliest retry still to come, or zero. -func (s *server) nextSearch(now time.Time) (region string, ok bool, next time.Time) { - s.mu.Lock() - defer s.mu.Unlock() - for _, region := range slices.Sorted(maps.Keys(s.wants)) { - if s.match(region) >= 0 { - delete(s.wants, region) - continue - } - return region, true, time.Time{} - } - for _, region := range s.cfg.Keep { - if s.match(region) >= 0 { - delete(s.retries, region) - continue - } - r, failed := s.retries[region] - if !failed || !now.Before(r.at) { - return region, true, time.Time{} - } - if next.IsZero() || r.at.Before(next) { - next = r.at - } - } - return "", len(s.buffer) < s.cfg.Buffer, next -} - -// add puts a photo found for region in the buffer, and marks it used so no -// later search finds it again. Past GEO_BUFFER and extraPhotos it drops the -// oldest, but never a GEO_KEEP region's last. -func (s *server) add(p geo.Photo, region string) { - s.mu.Lock() - s.buffer = append(s.buffer, p) - for over := len(s.buffer) - s.cfg.Buffer - extraPhotos; over > 0; over-- { - i := slices.IndexFunc(s.buffer, s.droppable) - if i < 0 { - break - } - s.buffer = slices.Delete(s.buffer, i, i+1) - } - s.markUsed(p.Key()) - delete(s.wants, region) - delete(s.retries, region) - close(s.changed) - s.changed = make(chan struct{}) - n := len(s.buffer) - s.mu.Unlock() - s.save() - s.log.Printf("a %s photo is ready; %d in all", p.Source, n) -} - -// droppable reports whether p, in the buffer, can leave it without leaving -// a GEO_KEEP region with no photo. s.mu is held. -func (s *server) droppable(p geo.Photo) bool { - for _, region := range s.cfg.Keep { - if !s.in(p, region) { - continue - } - n := 0 - for _, q := range s.buffer { - if s.in(q, region) { - n++ - } - } - if n < 2 { - return false - } - } - return true -} - -// take is a photo from the buffer for region, waiting up to wait for the -// prefetcher to find one. Taking one wakes the prefetcher, which refills a -// GEO_KEEP region it used up. -func (s *server) take(ctx context.Context, region string, wait time.Duration) (geo.Photo, bool) { - t := time.NewTimer(max(wait, 0)) - defer t.Stop() - for { - s.mu.Lock() - if i := s.pick(region); i >= 0 { - p := s.buffer[i] - s.buffer = slices.Delete(s.buffer, i, i+1) - s.mu.Unlock() - s.wakeUp() - return p, true - } - if region != "" { - s.wants[region] = true - } - changed := s.changed - s.mu.Unlock() - s.wakeUp() - select { - case <-changed: - case <-t.C: - return geo.Photo{}, false - case <-ctx.Done(): - return geo.Photo{}, false - } - } -} - -// pick is the index of the photo take gives for region, or -1: the oldest -// in it, but for a region not in GEO_KEEP, one a GEO_KEEP region can spare -// if there is one, so a plain /geo leaves the kept photo for its region. -// s.mu is held. -func (s *server) pick(region string) int { - if !slices.ContainsFunc(s.cfg.Keep, func(k string) bool { return strings.EqualFold(k, region) }) { - if i := slices.IndexFunc(s.buffer, func(p geo.Photo) bool { return s.in(p, region) && s.droppable(p) }); i >= 0 { - return i - } - } - return s.match(region) -} - -// match is the index of the oldest photo in the buffer that is in region -// ("" is GEO_REGIONS), or -1. s.mu is held. -func (s *server) match(region string) int { - return slices.IndexFunc(s.buffer, func(p geo.Photo) bool { return s.in(p, region) }) -} - -// in reports whether p is in region ("" is GEO_REGIONS, and empty too the -// world). s.mu is held. -func (s *server) in(p geo.Photo, region string) bool { - if region == "" { - region = s.cfg.Regions - } - if region == "" { - return true - } - seeds, err := s.seedsLocked(region) - return err == nil && seeds.Has(p.Place.CountryCode) -} - -// regionSeeds is the seeds for region, a /geo argument, or an error if it -// names none. -func (s *server) regionSeeds(region string) (*geo.Seeds, error) { - s.mu.Lock() - defer s.mu.Unlock() - return s.seedsLocked(region) -} - -func (s *server) seedsLocked(region string) (*geo.Seeds, error) { - key := strings.ToUpper(region) - if seeds := s.seeds[key]; seeds != nil { - return seeds, nil - } - seeds, err := geo.LoadSeeds(region) - if err == nil && len(s.seeds) < 64 { - s.seeds[key] = seeds - } - return seeds, err -} - -// wakeUp tells the prefetcher to look at the buffer again, without waiting. -func (s *server) wakeUp() { - select { - case s.wake <- struct{}{}: - default: - } -} - -// search is the real finder: Mapillary and Panoramax, checked by the geo -// package, with places named by Nominatim. -type search struct { - sources []geo.Source - rules geo.Rules - places *geo.Nominatim - rand *rand.Rand - used func(key string) bool - log *log.Logger - seeds map[string]*geo.Seeds - regions string // GEO_REGIONS -} - -// Find looks for one photo. It logs only counts of rejections, by reason, -// and errors, which hold no URL. -func (f *search) Find(ctx context.Context, regions string) (geo.Photo, error) { - if regions == "" { - regions = f.regions - } - seeds := f.seeds[regions] - if seeds == nil { - var err error - if seeds, err = geo.LoadSeeds(regions); err != nil { - return geo.Photo{}, err - } - f.seeds[regions] = seeds - } - rejected := map[string]int{} - finder := geo.Finder{ - Sources: f.sources, Seeds: seeds, Rules: f.rules, Places: f.places, Rand: f.rand, Now: time.Now, - Used: f.used, - Rejected: func(source string, why geo.Reject) { rejected[source+": "+string(why)]++ }, - Failed: func(err error) { f.log.Printf("search failed: %v", err) }, - } - p, err := finder.Find(ctx) - if len(rejected) > 0 { - f.log.Printf("photos rejected: %v", rejected) - } - return p, err -} diff --git a/cmd/geoguess/rpc.go b/cmd/geoguess/rpc.go deleted file mode 100644 index fc758ce..0000000 --- a/cmd/geoguess/rpc.go +++ /dev/null @@ -1,447 +0,0 @@ -package main - -import ( - "bufio" - "context" - "encoding/json" - "errors" - "io" - "strings" - "sync" -) - -// The protocol GeoGuess speaks: MCP 2025-06-18, as newline-delimited -// JSON-RPC 2.0 on stdin and stdout, plus signalbot's addon extension. -const ( - protocolVersion = "2025-06-18" - vendor = "io.github.robdevops.signalbot/" - outboxURI = "signalbot://outbox" -) - -// maxLine caps one incoming line. signalbot's requests are small: a -// command's arguments or one chat message. -const maxLine = 1 << 20 - -// JSON-RPC's error codes, and MCP's for a resource that isn't there. -const ( - codeParse = -32700 - codeInvalidRequest = -32600 - codeNoMethod = -32601 - codeInvalidParams = -32602 - codeNotFound = -32002 -) - -// message is one JSON-RPC message read: a request, a notification (no ID) -// or a response to a request of ours (GeoGuess sends none). -type message struct { - JSONRPC string `json:"jsonrpc"` - ID json.RawMessage `json:"id,omitempty"` - Method string `json:"method"` - Params json.RawMessage `json:"params,omitempty"` -} - -// response is the answer to one request: its result or an error. -type response struct { - JSONRPC string `json:"jsonrpc"` - ID json.RawMessage `json:"id"` - Result any `json:"result,omitempty"` - Error *rpcError `json:"error,omitempty"` -} - -// notification is a message to the client that wants no answer. -type notification struct { - JSONRPC string `json:"jsonrpc"` - Method string `json:"method"` - Params any `json:"params,omitempty"` -} - -type rpcError struct { - Code int `json:"code"` - Message string `json:"message"` -} - -func (e *rpcError) Error() string { return e.Message } - -// wire writes whole messages to stdout, one per line, one at a time: it is -// the only writer of stdout, which carries nothing but the protocol. -type wire struct { - mu sync.Mutex - w io.Writer -} - -func (w *wire) send(v any) error { - data, err := json.Marshal(v) - if err != nil { - return err - } - w.mu.Lock() - defer w.mu.Unlock() - _, err = w.w.Write(append(data, '\n')) - return err -} - -// handler answers one request's params with a result, or an *rpcError. -type handler func(ctx context.Context, params json.RawMessage) (any, error) - -// serve reads requests from in until it ends or ctx does, answering each on -// its own goroutine through out, and waits for the answers in flight. A -// request the client cancels (notifications/cancelled) has its context -// cancelled, so it stops rather than act for no one. -func (s *server) serve(ctx context.Context, in io.Reader, out io.Writer) error { - s.out = &wire{w: out} - ctx, cancel := context.WithCancel(ctx) - defer cancel() - go s.notifier(ctx) - var wg sync.WaitGroup - defer wg.Wait() - var mu sync.Mutex - inFlight := map[string]context.CancelFunc{} // by request ID - r := bufio.NewReaderSize(in, 64<<10) - for { - line, err := readLine(r) - if err != nil { - if errors.Is(err, io.EOF) { - return nil - } - return err - } - if line == nil { // too long, or blank - continue - } - var m message - if json.Unmarshal(line, &m) != nil { - s.out.send(response{JSONRPC: "2.0", ID: json.RawMessage("null"), Error: &rpcError{codeParse, "parse error"}}) - continue - } - if m.Method == "notifications/cancelled" { - var p struct { - RequestID json.RawMessage `json:"requestId"` - } - json.Unmarshal(m.Params, &p) - mu.Lock() - if stop := inFlight[string(p.RequestID)]; stop != nil { - stop() - } - mu.Unlock() - continue - } - if len(m.ID) == 0 || m.Method == "" { // a notification, or a response - continue - } - id := string(m.ID) - rctx, stop := context.WithCancel(ctx) - mu.Lock() - inFlight[id] = stop - mu.Unlock() - wg.Add(1) - go func() { - defer wg.Done() - s.out.send(s.answer(rctx, m)) - mu.Lock() - delete(inFlight, id) - mu.Unlock() - stop() - }() - } -} - -// answer runs one request's handler. -func (s *server) answer(ctx context.Context, m message) response { - resp := response{JSONRPC: "2.0", ID: m.ID} - h, ok := s.methods()[m.Method] - switch { - case m.JSONRPC != "2.0": - resp.Error = &rpcError{codeInvalidRequest, "not JSON-RPC 2.0"} - case !ok: - resp.Error = &rpcError{codeNoMethod, "method not found"} - default: - result, err := h(ctx, m.Params) - var re *rpcError - switch { - case errors.As(err, &re): - resp.Error = re - case err != nil: - resp.Error = &rpcError{-32603, "internal error"} - default: - resp.Result = result - } - } - return resp -} - -// readLine reads one line without its end. A line longer than maxLine is -// skipped whole, and nil returned for it, as for a blank one. -func readLine(r *bufio.Reader) ([]byte, error) { - var line []byte - tooLong := false - for { - part, err := r.ReadSlice('\n') - if !tooLong { - line = append(line, part...) - if len(line) > maxLine { - line, tooLong = nil, true - } - } - switch { - case errors.Is(err, bufio.ErrBufferFull): - continue - case err != nil && (len(line) == 0 || !errors.Is(err, io.EOF)): - return nil, err - } - if tooLong { - return nil, nil - } - line = trimEOL(line) - if len(line) == 0 { - return nil, nil - } - return line, nil - } -} - -func trimEOL(b []byte) []byte { - for len(b) > 0 && (b[len(b)-1] == '\n' || b[len(b)-1] == '\r' || b[len(b)-1] == ' ') { - b = b[:len(b)-1] - } - return b -} - -// params reads a request's params into v, or fails as JSON-RPC's invalid -// params. -func params(raw json.RawMessage, v any) error { - if len(raw) == 0 { - raw = json.RawMessage("{}") - } - if json.Unmarshal(raw, v) != nil { - return &rpcError{codeInvalidParams, "invalid params"} - } - return nil -} - -// The MCP methods' results. -type ( - initializeResult struct { - ProtocolVersion string `json:"protocolVersion"` - Capabilities capabilities `json:"capabilities"` - ServerInfo serverInfo `json:"serverInfo"` - } - capabilities struct { - Experimental map[string]addonCapability `json:"experimental"` - Tools struct{} `json:"tools"` - Resources resourcesCapability `json:"resources"` - } - addonCapability struct { - Version int `json:"version"` - Network string `json:"network,omitempty"` // the bot's chat network, as the bot offers it - } - resourcesCapability struct { - Subscribe bool `json:"subscribe"` - } - serverInfo struct { - Name string `json:"name"` - Title string `json:"title,omitempty"` - Version string `json:"version"` - } - - tool struct { - Name string `json:"name"` - Description string `json:"description"` - InputSchema schema `json:"inputSchema"` - Meta visibility `json:"_meta"` - } - schema struct { - Type string `json:"type"` - Properties map[string]schema `json:"properties,omitempty"` - Required []string `json:"required,omitempty"` - } - visibility struct { - Visibility []string `json:"io.github.robdevops.signalbot/visibility"` - } - - toolResult struct { - Content []content `json:"content"` - IsError bool `json:"isError,omitempty"` - Meta *resultMeta `json:"_meta,omitempty"` - } - content struct { - Type string `json:"type"` // text or image - Text string `json:"text,omitempty"` - Data string `json:"data,omitempty"` // base64 - MimeType string `json:"mimeType,omitempty"` - } - resultMeta struct { - Watch *watch `json:"io.github.robdevops.signalbot/watch,omitempty"` - React string `json:"io.github.robdevops.signalbot/react,omitempty"` - } - watch struct { - ID string `json:"id"` - Pattern string `json:"pattern"` - Until string `json:"until"` // RFC 3339 - Tool string `json:"tool"` - Guard string `json:"guard,omitempty"` - } - - resourceTemplate struct { - URITemplate string `json:"uriTemplate"` - Name string `json:"name"` - MimeType string `json:"mimeType"` - } - readResult struct { - Contents []resourceContent `json:"contents"` - } - resourceContent struct { - URI string `json:"uri"` - MimeType string `json:"mimeType"` - Text string `json:"text"` - } - uriParams struct { - URI string `json:"uri"` - } -) - -// callParams are tools/call's params, with the context signalbot puts in -// _meta when the bot itself makes the call. -type callParams struct { - Name string `json:"name"` - Arguments json.RawMessage `json:"arguments"` - Meta struct { - Context *callContext `json:"io.github.robdevops.signalbot/context"` - } `json:"_meta"` -} - -// callContext is the message a call came from: pseudonyms for its chat and -// sender, and the bot's receive times in whole seconds; and, for a call the -// bot waits on, when it stops waiting. -type callContext struct { - Chat string `json:"chat"` - Sender string `json:"sender"` - Ref string `json:"ref"` - Addressed bool `json:"addressed"` - Group bool `json:"group"` - Sent int64 `json:"sent"` - Edited int64 `json:"edited"` - Deadline int64 `json:"deadline,omitempty"` -} - -// methods are the MCP methods GeoGuess answers. -func (s *server) methods() map[string]handler { - return map[string]handler{ - "initialize": func(_ context.Context, raw json.RawMessage) (any, error) { - var p struct { - Capabilities struct { - Experimental map[string]addonCapability `json:"experimental"` - } `json:"capabilities"` - } - json.Unmarshal(raw, &p) // optional: without a network the caption names both - s.mu.Lock() - s.network = p.Capabilities.Experimental[vendor+"addon"].Network - s.mu.Unlock() - r := initializeResult{ProtocolVersion: protocolVersion, ServerInfo: serverInfo{Name: "geoguess", Title: "GeoGuess", Version: "1"}} - r.Capabilities.Experimental = map[string]addonCapability{vendor + "addon": {Version: 1}} - r.Capabilities.Resources.Subscribe = true - return r, nil - }, - "ping": func(context.Context, json.RawMessage) (any, error) { return struct{}{}, nil }, - "tools/list": func(context.Context, json.RawMessage) (any, error) { - return struct { - Tools []tool `json:"tools"` - }{tools}, nil - }, - "tools/call": func(ctx context.Context, raw json.RawMessage) (any, error) { - var p callParams - if err := params(raw, &p); err != nil { - return nil, err - } - return s.call(ctx, p) - }, - "resources/list": func(context.Context, json.RawMessage) (any, error) { - return struct { - Resources []struct{} `json:"resources"` - }{[]struct{}{}}, nil - }, - "resources/templates/list": func(context.Context, json.RawMessage) (any, error) { - return struct { - Templates []resourceTemplate `json:"resourceTemplates"` - }{[]resourceTemplate{{URITemplate: outboxURI + "/{cursor}", Name: "outbox", MimeType: "application/json"}}}, nil - }, - "resources/subscribe": func(_ context.Context, raw json.RawMessage) (any, error) { return s.subscribe(raw, true) }, - "resources/unsubscribe": func(_ context.Context, raw json.RawMessage) (any, error) { return s.subscribe(raw, false) }, - "resources/read": func(_ context.Context, raw json.RawMessage) (any, error) { - var p uriParams - if err := params(raw, &p); err != nil { - return nil, err - } - cursor, ok := strings.CutPrefix(p.URI, outboxURI+"/") - if !ok { - return nil, &rpcError{codeNotFound, "resource not found"} - } - page, err := json.Marshal(s.readOutbox(cursor)) - if err != nil { - return nil, err - } - return readResult{[]resourceContent{{URI: p.URI, MimeType: "application/json", Text: string(page)}}}, nil - }, - } -} - -// tools are GeoGuess's tools, both for the bot alone: neither is offered to -// the model. -var tools = []tool{ - { - Name: "geo", - Description: "The /geo command: start, end or skip this chat's round, or show its scores.", - InputSchema: schema{Type: "object", Properties: map[string]schema{"args": {Type: "string"}}}, - Meta: visibility{[]string{"bot"}}, - }, - { - Name: "geo_guess", - Description: "Records the location in one chat message as a guess in this chat's round.", - InputSchema: schema{Type: "object", Properties: map[string]schema{"text": {Type: "string"}}, Required: []string{"text"}}, - Meta: visibility{[]string{"bot"}}, - }, -} - -// subscribe records whether the client wants to hear of the outbox. -func (s *server) subscribe(raw json.RawMessage, on bool) (any, error) { - var p uriParams - if err := params(raw, &p); err != nil { - return nil, err - } - if _, ok := strings.CutPrefix(p.URI, outboxURI); !ok { - return nil, &rpcError{codeNotFound, "resource not found"} - } - s.mu.Lock() - s.subscribed = on - pending := len(s.outbox) > 0 - s.mu.Unlock() - if on && pending { - s.poke() - } - return struct{}{}, nil -} - -// notifier tells a subscribed client each time the outbox gains ops, on -// its own goroutine, as a write can wait on a client that is busy. -func (s *server) notifier(ctx context.Context) { - for { - select { - case <-ctx.Done(): - return - case <-s.dirty: - } - s.mu.Lock() - on := s.subscribed - s.mu.Unlock() - if on { - s.out.send(notification{JSONRPC: "2.0", Method: "notifications/resources/updated", Params: uriParams{outboxURI}}) - } - } -} - -// poke marks the outbox changed, without waiting. -func (s *server) poke() { - select { - case s.dirty <- struct{}{}: - default: - } -} diff --git a/cmd/geoguess/server.go b/cmd/geoguess/server.go deleted file mode 100644 index 4d290d5..0000000 --- a/cmd/geoguess/server.go +++ /dev/null @@ -1,308 +0,0 @@ -package main - -import ( - "crypto/rand" - "encoding/hex" - "encoding/json" - "log" - "slices" - "strconv" - "strings" - "sync" - "time" - - "github.com/robdevops/signalbot/cmd/geoguess/geo" - "github.com/robdevops/signalbot/internal/kit/state" -) - -// server is GeoGuess: the chats' rounds, their scores, the outbox the bot -// reads, and the photos kept ready. -type server struct { - cfg config - clock clock - photos finder - log *log.Logger - doc *state.Doc - nonce string // this run's, in each outbox cursor and op ID - - out *wire - dirty chan struct{} // the outbox gained ops: tell the client - wake chan struct{} // the prefetcher has work - - mu sync.Mutex - rounds map[string]*round // by chat - timers map[string]stopper // each round's, by chat - used []string // the last maxUsed photos' keys, oldest first - scores map[string][]score // by chat, the last scoreDays days - outbox []held // ops the bot hasn't read past, oldest first - seq int64 // the last op's sequence number - subscribed bool // the client wants to hear of the outbox - buffer []geo.Photo // photos ready for a round, oldest first - wants map[string]bool // regions a /geo asked for that the buffer lacks - retries map[string]retry // GEO_KEEP regions whose last search failed - changed chan struct{} // closed when the buffer gains a photo - seeds map[string]*geo.Seeds - network string // the chat network the bot said it is on, "" if it didn't - - saveMu sync.Mutex // one save at a time, so the last one written is the newest -} - -// round is one chat's round. Its guesses are distances only: where anyone -// guessed is never kept. -type round struct { - ID string `json:"id"` // also the watch's - Chat string `json:"chat"` - Starter string `json:"starter"` // who may end or skip it - Started time.Time `json:"started"` - Deadline time.Time `json:"deadline"` - Answer geo.Point `json:"answer"` - Place string `json:"place"` - Credit credit `json:"credit"` - Guesses map[string]guess `json:"guesses"` // by player -} - -// guess is how far one player's last guess was from the answer, and when -// it was sent. -type guess struct { - Km float64 `json:"km"` - At time.Time `json:"at"` -} - -// credit names a photo's author, source and licence, with a link to it. -type credit struct { - Creator string `json:"creator"` - Source string `json:"source"` - Licence string `json:"licence"` - Link string `json:"link"` -} - -// score is a player's points from one round. -type score struct { - User string `json:"user"` - Points int `json:"points"` - At time.Time `json:"at"` -} - -// saved is geo.json. -type saved struct { - Rounds []*round `json:"rounds"` - Used []string `json:"used"` - Scores map[string][]score `json:"scores"` - Outbox []held `json:"outbox"` -} - -// The state's limits: photos remembered as used, days of scores, and the -// slack on a round's end. -const ( - maxUsed = 1000 - scoreDays = 7 - // settle is how long after its deadline a round is revealed, so a guess - // sent in time that waited in the bot's queue still counts. - settle = 3 * time.Second - // watchSlack is how long after the deadline the bot keeps the watch, so a - // late guess still stays out of the chat's history. - watchSlack = 5 * time.Second -) - -// newServer loads the state saved in cfg.StateDir, re-arms its rounds' -// timers and reveals at once those whose time passed while it was down. -func newServer(cfg config, clk clock, photos finder, logger *log.Logger) (*server, error) { - s := &server{ - cfg: cfg, clock: clk, photos: photos, log: logger, - doc: state.Open(cfg.StateDir, "geo"), - nonce: randomID(4), - dirty: make(chan struct{}, 1), - wake: make(chan struct{}, 1), - rounds: map[string]*round{}, - timers: map[string]stopper{}, - scores: map[string][]score{}, - wants: map[string]bool{}, - retries: map[string]retry{}, - changed: make(chan struct{}), - seeds: map[string]*geo.Seeds{}, - } - var st saved - if _, err := s.doc.Load(&st); err != nil { - return nil, err - } - s.used = st.Used - if st.Scores != nil { - s.scores = st.Scores - } - for _, h := range st.Outbox { - s.seq++ - h.seq = s.seq - s.outbox = append(s.outbox, h) - } - s.mu.Lock() - revealed := 0 - for _, r := range st.Rounds { - if r == nil || s.rounds[r.Chat] != nil { - continue - } - if r.Guesses == nil { - r.Guesses = map[string]guess{} - } - s.rounds[r.Chat] = r - if !s.clock.Now().Before(r.Deadline.Add(settle)) { - s.timeUpLocked(r) - revealed++ - } else { - s.arm(r) - } - } - s.mu.Unlock() - s.log.Printf("started: %d rounds open, %d revealed late, %d ops held", len(s.rounds), revealed, len(s.outbox)) - if revealed > 0 { - s.poke() - s.save() - } - return s, nil -} - -// save writes geo.json, logging a failure; the state stays in memory, and -// the next change tries again. -func (s *server) save() { - s.saveMu.Lock() - defer s.saveMu.Unlock() - s.mu.Lock() - st := saved{Used: s.used, Scores: s.scores, Outbox: s.outbox, Rounds: make([]*round, 0, len(s.rounds))} - for _, r := range s.rounds { - st.Rounds = append(st.Rounds, r) - } - slices.SortFunc(st.Rounds, func(a, b *round) int { return strings.Compare(a.Chat, b.Chat) }) - data, err := json.Marshal(st) - s.mu.Unlock() - if err == nil { - err = s.doc.Save(json.RawMessage(data)) - } - if err != nil { - s.log.Printf("saving failed: %v", err) - } -} - -// markUsed remembers a photo's key, forgetting the oldest past maxUsed. -// s.mu is held. -func (s *server) markUsed(key string) { - s.used = append(s.used, key) - if over := len(s.used) - maxUsed; over > 0 { - s.used = slices.Delete(s.used, 0, over) - } -} - -// isUsed reports whether a photo's key is among those used recently. -func (s *server) isUsed(key string) bool { - s.mu.Lock() - defer s.mu.Unlock() - return slices.Contains(s.used, key) -} - -// randomID is n random bytes in hex. -func randomID(n int) string { - b := make([]byte, n) - rand.Read(b) - return hex.EncodeToString(b) -} - -// validID reports whether id is one of signalbot's pseudonyms with prefix -// (c_ or u_), so it can go into a {u_…} placeholder safely. -func validID(id, prefix string) bool { - rest, ok := strings.CutPrefix(id, prefix) - if !ok || rest == "" || len(rest) > 100 { - return false - } - for _, c := range rest { - if !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' || c == '_' || c == '-') { - return false - } - } - return true -} - -// held is an op waiting for the bot to read past it. -type held struct { - Op op `json:"op"` - Queued time.Time `json:"queued"` - seq int64 // this run's, which cursors count in -} - -// op is one thing the bot is asked to do: post in a chat, or end a watch. -type op struct { - ID string `json:"id"` - Op string `json:"op"` // post or unwatch - Chat string `json:"chat"` - Text string `json:"text,omitempty"` - Watch string `json:"watch,omitempty"` -} - -// outboxPage is what reading the outbox returns. -type outboxPage struct { - Cursor string `json:"cursor"` - More bool `json:"more"` - Ops []op `json:"ops"` -} - -// The outbox's limits: how long an op unread is kept, and the most a page -// holds, well under the 4 MiB line signalbot reads. -const ( - keepOps = time.Hour - pageSize = 3 << 20 -) - -// queue adds an op to the outbox. s.mu is held; the caller pokes the -// client and saves once it is released. -func (s *server) queue(o op) { - s.seq++ - o.ID = s.nonce + "." + strconv.FormatInt(s.seq, 10) - s.outbox = append(s.outbox, held{Op: o, Queued: s.clock.Now(), seq: s.seq}) -} - -// readOutbox is the page after cursor. A cursor of this run lets go of the -// ops up to it, which the bot has read; any other, such as one from before -// a restart, gets everything still held. -func (s *server) readOutbox(cursor string) outboxPage { - s.mu.Lock() - after, known := s.cursor(cursor) - now := s.clock.Now() - n := len(s.outbox) - s.outbox = slices.DeleteFunc(s.outbox, func(h held) bool { - return known && h.seq <= after || now.Sub(h.Queued) > keepOps - }) - changed := len(s.outbox) != n - last := s.seq - if known { - last = after - } - page := outboxPage{Ops: []op{}} - size := 0 - for _, h := range s.outbox { - data, _ := json.Marshal(h.Op) - if len(page.Ops) > 0 && size+len(data) > pageSize { - page.More = true - break - } - size += len(data) - page.Ops = append(page.Ops, h.Op) - last = h.seq - } - page.Cursor = s.nonce + "." + strconv.FormatInt(last, 10) - s.mu.Unlock() - if changed { - s.save() - } - return page -} - -// cursor reads a cursor of this run: the sequence number read up to. -// s.mu is held. -func (s *server) cursor(c string) (int64, bool) { - nonce, seq, ok := strings.Cut(c, ".") - if !ok || nonce != s.nonce { - return 0, false - } - n, err := strconv.ParseInt(seq, 10, 64) - if err != nil || n < 0 || n > s.seq { - return 0, false - } - return n, true -} diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index a022749..9247563 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -26,7 +26,7 @@ Every setting, read from the environment (`/etc/signalbot.env` in the install). | `INTRO` | built-in sentence | Overrides the self-introduction; `{name}`, `{model}` (without any OpenRouter `provider/` prefix) and `{tools}` (the names of the tools, or `none`) are substituted | | `MAX_CONCURRENCY` | `32` | Conversations in flight at once; messages beyond this are dropped, with a warning | | `MCP_CONFIG` | empty | Path of an MCP servers file; see [MCP connectors](FILES_LINKS_TOOLS_MCP.md#mcp-connectors) | -| `<SERVER>_…` | none | An [addon's](FILES_LINKS_TOOLS_MCP.md#addons) own settings, read by the addon, not the bot. An addon server gets every variable that starts with its name in capitals, anything but letters and digits as `_`, then `_` (the server `geo` gets `GEO_STATE_DIR` and the rest), plus `PATH`, `HOME` and, if set, `TZ`, `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, `SSL_CERT_FILE` and `SSL_CERT_DIR`, and nothing else, so none of the other settings above reach it. A server whose prefix one of the settings above starts with (such as `model` or `mcp`) is a config error. Each addon documents its own, such as [GeoGuess's](../cmd/geoguess/README.md#settings) | +| `<SERVER>_…` | none | An [addon's](FILES_LINKS_TOOLS_MCP.md#addons) own settings, read by the addon, not the bot. An addon server gets every variable that starts with its name in capitals, anything but letters and digits as `_`, then `_` (the server `geo` gets `GEO_STATE_DIR` and the rest), plus `PATH`, `HOME` and, if set, `TZ`, `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, `SSL_CERT_FILE` and `SSL_CERT_DIR`, and nothing else, so none of the other settings above reach it. A server whose prefix one of the settings above starts with (such as `model` or `mcp`) is a config error. Each addon documents its own, such as [GeoGuess's](https://github.com/robdevops/chat-plugin-geoguess#settings) | | `STATE_DIRECTORY` | working directory | Where features save their state, one file each, such as `/schedule`'s `schedules.json`, `mcp.json` when an MCP server is an [addon](FILES_LINKS_TOOLS_MCP.md#addons) (and the core its `budget.json`); the bot won't start if a feature that saves can't list and write it. Set by systemd's `StateDirectory=signalbot` (`/var/lib/private/signalbot`) and by the Docker image (`/data`, which must be writable by user 65532) | | `TOOL_LINGER_ROUNDS` | `2` | Replies a keyword-gated tool group (charts, an MCP server with `keywords`) stays offered after the last one that matched its keywords or used its tools; `0` offers it only on a matching message. Any use or match starts the count again, so a run of follow-ups keeps it. Capped at `HISTORY_MAX`. See [How tools are offered](FILES_LINKS_TOOLS_MCP.md#how-tools-are-offered) | | `TZ` | `UTC` in Docker, the host's under systemd | Time zone for `/schedule` times without an offset and for `DARKMODE` hours, e.g. `Australia/Sydney`; addons get it too, for the times they write (GeoGuess's round deadline) | diff --git a/docs/FILES_LINKS_TOOLS_MCP.md b/docs/FILES_LINKS_TOOLS_MCP.md index 0bccecc..dfd2145 100644 --- a/docs/FILES_LINKS_TOOLS_MCP.md +++ b/docs/FILES_LINKS_TOOLS_MCP.md @@ -98,7 +98,7 @@ A server that can't be reached at startup is logged and left out. A config error ## Addons -An addon is a local MCP server that does more than offer tools: it answers its own commands without the model, reads the messages it asks for, and posts and reacts when it likes. [GeoGuess](../cmd/geoguess/README.md), a photo-guessing game, is one. It is still an ordinary MCP server (protocol 2025-06-18 over stdio), which also speaks signalbot's small extension, under keys starting `io.github.robdevops.signalbot/`. A server is an addon when it has an `addon` block in the MCP file and says it speaks the extension when the bot connects; one with the block that doesn't runs as a plain server, with a warning. Addons run even with [no model](MODELS.md#no-model). +An addon is a local MCP server that does more than offer tools: it answers its own commands without the model, reads the messages it asks for, and posts and reacts when it likes. [GeoGuess](https://github.com/robdevops/chat-plugin-geoguess), a photo-guessing game, is one. It is still an ordinary MCP server (protocol 2025-06-18 over stdio), which also speaks signalbot's small extension, under keys starting `io.github.robdevops.signalbot/`. A server is an addon when it has an `addon` block in the MCP file and says it speaks the extension when the bot connects; one with the block that doesn't runs as a plain server, with a warning. Addons run even with [no model](MODELS.md#no-model). **An addon is trusted code.** It runs as the bot's user, inside the same systemd or Docker sandbox, and could read what that user can. The bot gives it as little as it can (below), but that guards against bugs and leaks, not a hostile program: install only addons you would let run as the bot. diff --git a/internal/arch/arch_test.go b/internal/arch/arch_test.go index 13e56fe..75c1bfd 100644 --- a/internal/arch/arch_test.go +++ b/internal/arch/arch_test.go @@ -43,8 +43,7 @@ func under(p, dir string) bool { return p == dir || strings.HasPrefix(p, dir+"/" // its own packages and kit; internal/signal imports only those, // internal/config and internal/bot (for Received: the network depends on // the core, never the reverse); internal/config and kit import no other -// internal package; GeoGuess, an addon the bot runs as a separate program, -// imports only kit and its own packages. +// internal package. func TestImports(t *testing.T) { for _, p := range goFiles(t) { f, err := parser.ParseFile(token.NewFileSet(), root+"/"+p, nil, parser.ImportsOnly) @@ -72,8 +71,6 @@ func TestImports(t *testing.T) { ok = under(imp, "internal/feature") || under(imp, "internal/kit") || imp == "internal/config" || imp == "internal/bot" case under(dir, "internal/kit"), dir == "internal/config": ok = under(imp, "internal/kit") - case under(dir, "cmd/geoguess"): - ok = under(imp, "internal/kit") || under(imp, "cmd/geoguess") default: ok = dir == "." || !under(imp, "internal/features") && !under(imp, "internal/signal") && !under(imp, "internal/telegram") } From 833209f1c095e72fdef50de4a695af0730a6eebe Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Fri, 20 Nov 2026 21:06:54 +0000 Subject: [PATCH 11/26] One callback shape for sent messages; OnSent alone claims nothing Action.OnSent and Post's callback did the same job under two names and shapes, and Post.Done sat next to Action.Done, an unrelated bool. Both are now OnSent func(sent []int64, dropped bool). IsZero no longer counts OnSent: an Action with only OnSent set used to claim the message, stop later hooks and then fall through to the model with OnSent never called. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- TECHNICAL.md | 8 ++++---- internal/bot/answer.go | 2 +- internal/bot/bot.go | 6 +++--- internal/bot/host.go | 12 ++++++------ internal/bot/host_test.go | 6 +++--- internal/feature/feature.go | 19 ++++++++++--------- internal/feature/feature_test.go | 7 +++++-- internal/features/mcp/direct.go | 2 +- internal/features/mcp/outbox.go | 2 +- internal/features/mcp/watch_test.go | 18 +++++++++--------- 10 files changed, 43 insertions(+), 39 deletions(-) diff --git a/TECHNICAL.md b/TECHNICAL.md index e56f724..3362527 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -116,7 +116,7 @@ The core's lifecycle has three stages. Each port is one stage; nothing else is a **Hook rules:** - Hooks run in feature order (`features.go`). - For an unaddressed message, `OnMessage` runs on the reader goroutine, so it must not block or call the network. For an addressed or delivered one it runs in the message's slot. The first non-zero `Action` wins. -- `Answer`, `Pictures`, `OnSent` and `ToolChoice` count only on an addressed message, and `Context` only on an unaddressed one. `Done` counts on both: the hook handled the message, so it gets no answer and no model; an unaddressed one is kept nowhere, even with a `Context`, and later hooks never see it. An `Answer` and `Pictures` are sent together, with the caption rule as for a tool's pictures, and `OnSent`, if set, is called with the timestamps of the messages they went out in. Nothing of them is kept in history. +- `Answer`, `Pictures`, `OnSent` and `ToolChoice` count only on an addressed message, and `Context` only on an unaddressed one. `Done` counts on both: the hook handled the message, so it gets no answer and no model; an unaddressed one is kept nowhere, even with a `Context`, and later hooks never see it. An `Answer` and `Pictures` are sent together, with the caption rule as for a tool's pictures, and `OnSent`, if set, is called with the timestamps of the messages they went out in; `OnSent` alone doesn't count, so it can't claim a message. Nothing of them is kept in history. - An `Event` is a reaction (its emoji, whether it was taken back, who wrote the message and when, and whether that was the bot) or a change in a group's members (who joined, who left, or that the bot was added), with who did it. The network decides which reach the core, as for messages: never the bot's own, in a DM only an allowed sender's, member changes only in groups. With no `OnEvent` hook the core drops events as they arrive. Otherwise each goes into its chat's mailbox and runs on a slot of its own, so a hook may block or call the network: a reaction in order with that chat's messages, a member change once the network has worked it out, which can be after messages that came later (below); the first non-empty reply is sent with `@Name` linked to the chat's known names and the event's people. Events are never logged, kept in history or shown to the model. - **Member changes on Signal:** signal-cli's group `UPDATE` says only that something changed, so the client keeps each group's members from `listGroups`, loaded once the bot's ID is known, and on an update reloads them and compares, only when the core has an `OnEvent` hook (`Network.Watch`). Updates are folded and spaced like the contact list, at most one load per 15 seconds after a contact load, so a member change can reach features after messages read later. Members already there at startup are never reported; a group the bot wasn't in is `BotAdded`; a change of name or description alone is no event. The bot's own update (from its linked phone) refreshes the members it compares with but reaches no feature. `By` is whoever sent the update, or empty when several people's updates were folded together. Each comparison updates only the groups it compares, and one whose `listGroups` call fails keeps its updates for the next. - `OnTurn` runs only when the model is about to be asked. @@ -136,7 +136,7 @@ The core's lifecycle has three stages. Each port is one stage; nothing else is a - anything else the bot posts as written, with @Name linked against the group's members (never an ambiguous name), and history keeps it as the sender's message, "<name>: <text>", not as something the bot chose to say. These rules are what "as if its sender had just posted it" means for any feature, not just `/schedule`, so the host applies them rather than each feature. The membership check calls the network, so it runs in the message's slot; a feature's timer callback has no slot to make that call in. -- `Post(Post)`: the bot posts `Text`, with any `Pictures` (the caption rule applies), to a group or a DM, as written, never through the model, through that chat's mailbox. In the slot, `Network.Reachable` must say the bot may still post there, or it is dropped and logged at info. `@Name` is linked against the chat's known names. With a `Label`, history keeps the post as the bot's own entry, `[Label] text` (the pictures' notes in place of text they replaced), clamped to 500 characters, so a feature's text can never pose as a person; with none, or with no model, nothing is kept. `Done`, if set, is called once, with the timestamps sent, or with dropped set when it never goes out (a full mailbox, an unreachable chat, shutdown). `/schedule` uses it, with no label, to tell an owner in their DM that a one-off was dropped. +- `Post(Post)`: the bot posts `Text`, with any `Pictures` (the caption rule applies), to a group or a DM, as written, never through the model, through that chat's mailbox. In the slot, `Network.Reachable` must say the bot may still post there, or it is dropped and logged at info. `@Name` is linked against the chat's known names. With a `Label`, history keeps the post as the bot's own entry, `[Label] text` (the pictures' notes in place of text they replaced), clamped to 500 characters, so a feature's text can never pose as a person; with none, or with no model, nothing is kept. `OnSent`, if set, is called once, with the timestamps sent, or with dropped set when it never goes out (a full mailbox, an unreachable chat, shutdown). `/schedule` uses it, with no label, to tell an owner in their DM that a one-off was dropped. - `React(chat, msg, emoji)`: the bot puts `emoji` on `msg`, through the chat's mailbox at low priority (see the per-chat mailbox): a later reaction to the same message replaces a waiting one, at most 16 wait per chat, and one to a message deleted or replaced by an edit since is skipped. - `Groups(ctx, user)`: the groups the bot shares with a user, with their names (`listGroups`). - `Redact(text)`: text with every name and ID the bot knows for anyone but itself, and any UUID or phone number, replaced with "redacted", for logging text the bot doesn't control (a local MCP server's output). @@ -144,8 +144,8 @@ The core's lifecycle has three stages. Each port is one stage; nothing else is a **Types**, each field being a stage's natural input or output: ```go -type Action struct{ Answer string; Pictures []Picture; OnSent func(sent []int64); ToolChoice, Context string; Done bool } // IsZero: carry on -type Post struct{ Chat Chat; Label, Text string; Pictures []Picture; Done func(sent []int64, dropped bool) } +type Action struct{ Answer string; Pictures []Picture; OnSent func(sent []int64, dropped bool); ToolChoice, Context string; Done bool } // IsZero: carry on +type Post struct{ Chat Chat; Label, Text string; Pictures []Picture; OnSent func(sent []int64, dropped bool) } type Additions struct{ Note, HistoryNote string; Images []string; Files []File } type File struct{ Name, MIME string; Data []byte } type Picture struct{ Data []byte; Caption, HistoryNote string } diff --git a/internal/bot/answer.go b/internal/bot/answer.go index 9868e7e..8044e4f 100644 --- a/internal/bot/answer.go +++ b/internal/bot/answer.go @@ -73,7 +73,7 @@ func (b *Bot) respond(msg feature.Message, act feature.Action, text string, refs text, _ := captioned(act.Answer, act.Pictures) sent := b.net.Send(msg.Chat, text, act.Pictures, b.chats.Names(msg.Chat.Key())) if act.OnSent != nil { - act.OnSent(sent) + act.OnSent(sent, false) } return case b.ai == nil: diff --git a/internal/bot/bot.go b/internal/bot/bot.go index 6516326..fc8f278 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -322,7 +322,7 @@ func (b *Bot) dropped(r Received, err error) { switch r := r.(type) { case Outgoing: what = "a post" - r.Post.Done(nil, true) + r.Post.OnSent(nil, true) case Reacted: what = "a reaction" if n := len(r.Reactions); n > 1 { @@ -341,7 +341,7 @@ func (b *Bot) dropped(r Received, err error) { func abandon(rs []Received) { for _, r := range rs { if o, ok := r.(Outgoing); ok { - o.Post.Done(nil, true) + o.Post.OnSent(nil, true) } } } @@ -387,7 +387,7 @@ func (b *Bot) work(rs []Received) { return case Outgoing: alone(func() { b.say(r.Post) }) - r.Post.Done(nil, true) // if shutdown began first + r.Post.OnSent(nil, true) // if shutdown began first return case Reacted: alone(func() { b.react(r) }) diff --git a/internal/bot/host.go b/internal/bot/host.go index 2c901f6..0617066 100644 --- a/internal/bot/host.go +++ b/internal/bot/host.go @@ -131,13 +131,13 @@ func (b *Bot) Deliver(msg feature.Message) { } } -// Post sends p from the bot, in its chat's mailbox. Its Done is called +// Post sends p from the bot, in its chat's mailbox. Its OnSent is called // once, whatever happens to it. func (b *Bot) Post(p feature.Post) { - p.Done = once(p.Done) + p.OnSent = once(p.OnSent) switch { case b.closing.Load(), p.Text == "" && len(p.Pictures) == 0: - p.Done(nil, true) + p.OnSent(nil, true) default: b.post(Outgoing{Post: p}) } @@ -160,7 +160,7 @@ func once(done func(sent []int64, dropped bool)) func(sent []int64, dropped bool // with @Name linked to the chat's known names. With a label, history keeps // it as the bot's own entry, "[Label] text", clamped; without one, nothing. func (b *Bot) say(p feature.Post) { - defer p.Done(nil, true) // if it is never sent + defer p.OnSent(nil, true) // if it is never sent if !b.net.Reachable(b.ctx, p.Chat) { logx.Infof("dropped a post: the bot can no longer post in its chat") return @@ -168,12 +168,12 @@ func (b *Bot) say(p feature.Post) { key := p.Chat.Key() text, kept := captioned(p.Text, p.Pictures) if p.Label == "" || b.ai == nil { // with no model, nothing would read it - p.Done(b.net.Send(p.Chat, text, p.Pictures, b.chats.Names(key)), false) + p.OnSent(b.net.Send(p.Chat, text, p.Pictures, b.chats.Names(key)), false) return } ref := b.pending() b.chats.Add(key, b.now(), 0, chats.Entry{Role: "assistant", Content: txt.Clamp("["+p.Label+"] "+kept, maxPostKept), Refs: []chats.Ref{ref}}) - p.Done(b.sendKept(key, ref, p.Chat, text, p.Pictures, b.chats.Names(key)), false) + p.OnSent(b.sendKept(key, ref, p.Chat, text, p.Pictures, b.chats.Names(key)), false) } // maxPostKept caps what history keeps of a post. diff --git a/internal/bot/host_test.go b/internal/bot/host_test.go index 496a547..3ef04ff 100644 --- a/internal/bot/host_test.go +++ b/internal/bot/host_test.go @@ -658,7 +658,7 @@ func TestDone(t *testing.T) { // caption rule; OnSent gets the timestamps Send returned. func TestActionPictures(t *testing.T) { var sentAt [][]int64 - onSent := func(ts []int64) { sentAt = append(sentAt, ts) } + onSent := func(ts []int64, _ bool) { sentAt = append(sentAt, ts) } h := start(t, options{features: func(b *Bot) { b.Command("plain", func(context.Context, feature.Message, string) feature.Action { return feature.Action{Answer: "here", Pictures: []feature.Picture{{Data: png}}, OnSent: onSent} @@ -707,7 +707,7 @@ func TestPost(t *testing.T) { } dones := make(chan done, 16) post := func(p feature.Post) { - p.Done = func(sent []int64, dropped bool) { dones <- done{sent, dropped} } + p.OnSent = func(sent []int64, dropped bool) { dones <- done{sent, dropped} } h.b.Post(p) } next := func() done { @@ -785,7 +785,7 @@ func TestPostDropped(t *testing.T) { h.receive(dm(s)) } dropped := make(chan bool, 1) - h.b.Post(feature.Post{Chat: feature.Chat{User: aliceID}, Text: "never sent", Done: func(_ []int64, d bool) { dropped <- d }}) + h.b.Post(feature.Post{Chat: feature.Chat{User: aliceID}, Text: "never sent", OnSent: func(_ []int64, d bool) { dropped <- d }}) if !<-dropped { t.Fatal("Done said it was sent") } diff --git a/internal/feature/feature.go b/internal/feature/feature.go index 8b3d2a8..bc2451f 100644 --- a/internal/feature/feature.go +++ b/internal/feature/feature.go @@ -104,17 +104,18 @@ type File struct { // Action is what an OnMessage hook decides. The zero value carries on. type Action struct { - Answer string // reply with this text, without the model (addressed messages only) - Pictures []Picture // send these with Answer, or alone, without the model; captions as for a tool's pictures (addressed messages only) - OnSent func(sent []int64) // called with the timestamps of the messages Answer and Pictures went out in (addressed messages only) - ToolChoice string // make the model call this tool before answering (addressed messages only) - Context string // keep this text in the chat's history (unaddressed messages only) - Done bool // the hook handled the message: no answer, no model, and for an unaddressed one nothing kept and no later hook + Answer string // reply with this text, without the model (addressed messages only) + Pictures []Picture // send these with Answer, or alone, without the model; captions as for a tool's pictures (addressed messages only) + OnSent func(sent []int64, dropped bool) // if set with Answer or Pictures, called with the timestamps they went out in (addressed messages only); alone it doesn't count + ToolChoice string // make the model call this tool before answering (addressed messages only) + Context string // keep this text in the chat's history (unaddressed messages only) + Done bool // the hook handled the message: no answer, no model, and for an unaddressed one nothing kept and no later hook } -// IsZero reports whether a carries on: no field is set. +// IsZero reports whether a carries on: nothing set but, at most, OnSent, +// which only follows an Answer or Pictures. func (a Action) IsZero() bool { - return a.Answer == "" && len(a.Pictures) == 0 && a.OnSent == nil && a.ToolChoice == "" && a.Context == "" && !a.Done + return a.Answer == "" && len(a.Pictures) == 0 && a.ToolChoice == "" && a.Context == "" && !a.Done } // For returns a copy of the action keeping only the fields that apply to @@ -204,7 +205,7 @@ type Post struct { Label string // history keeps the post as the bot's, as "[Label] text"; "" keeps nothing Text string // Markdown, as written; @Name is linked to the chat's known names Pictures []Picture // sent with Text; captions as for a tool's pictures - Done func(sent []int64, dropped bool) // if set, called once: with the timestamps sent, or dropped + OnSent func(sent []int64, dropped bool) // if set, called once: with the timestamps sent, or dropped } // Group is a group chat. diff --git a/internal/feature/feature_test.go b/internal/feature/feature_test.go index 951b101..03140fa 100644 --- a/internal/feature/feature_test.go +++ b/internal/feature/feature_test.go @@ -14,7 +14,6 @@ func TestActionIsZero(t *testing.T) { for name, a := range map[string]feature.Action{ "Answer": {Answer: "a"}, "Pictures": {Pictures: []feature.Picture{{}}}, - "OnSent": {OnSent: func([]int64) {}}, "ToolChoice": {ToolChoice: "t"}, "Context": {Context: "c"}, "Done": {Done: true}, @@ -23,11 +22,15 @@ func TestActionIsZero(t *testing.T) { t.Errorf("an Action with only %s set is zero", name) } } + // OnSent alone claims nothing: it only follows an Answer or Pictures. + if !(feature.Action{OnSent: func([]int64, bool) {}}).IsZero() { + t.Error("an Action with only OnSent set isn't zero") + } } // For keeps what applies to the message, and Done on both. func TestActionFor(t *testing.T) { - a := feature.Action{Answer: "a", Pictures: []feature.Picture{{}}, OnSent: func([]int64) {}, ToolChoice: "t", Context: "c", Done: true} + a := feature.Action{Answer: "a", Pictures: []feature.Picture{{}}, OnSent: func([]int64, bool) {}, ToolChoice: "t", Context: "c", Done: true} if got := a.For(feature.Message{Addressed: true}); got.Answer != "a" || len(got.Pictures) != 1 || got.OnSent == nil || got.ToolChoice != "t" || got.Context != "" || !got.Done { t.Errorf("addressed: %+v", got) } diff --git a/internal/features/mcp/direct.go b/internal/features/mcp/direct.go index b20b379..1bc740c 100644 --- a/internal/features/mcp/direct.go +++ b/internal/features/mcp/direct.go @@ -84,7 +84,7 @@ func (a *addon) direct(ctx context.Context, m feature.Message, name string, c ch act := a.action(m.Chat, r) if r.Meta.Watch != nil { if w := a.watch(m, *r.Meta.Watch); w != nil && len(act.Pictures) > 0 { - act.OnSent = func(sent []int64) { a.guarding(w, sent) } + act.OnSent = func(sent []int64, _ bool) { a.guarding(w, sent) } } } if act.IsZero() { diff --git a/internal/features/mcp/outbox.go b/internal/features/mcp/outbox.go index bdfb6c7..01a40e5 100644 --- a/internal/features/mcp/outbox.go +++ b/internal/features/mcp/outbox.go @@ -361,7 +361,7 @@ func (a *addon) send(id string, out *outgoing) { // mail puts out in its chat's mailbox. func (a *addon) mail(id string, out *outgoing) { p := out.Post - p.Done = func(_ []int64, dropped bool) { + p.OnSent = func(_ []int64, dropped bool) { a.sent(out.ops, !dropped) a.mu.Lock() held := a.waiting[id] diff --git a/internal/features/mcp/watch_test.go b/internal/features/mcp/watch_test.go index 76bd8fe..eb56c2a 100644 --- a/internal/features/mcp/watch_test.go +++ b/internal/features/mcp/watch_test.go @@ -234,7 +234,7 @@ func round(t *testing.T, h *featuretest.Host, chat feature.Chat, ts int64, spec t.Fatalf("round: %+v", act) } if act.OnSent != nil { - act.OnSent([]int64{5000}) + act.OnSent([]int64{5000}, false) } return act } @@ -515,7 +515,7 @@ func TestOutbox(t *testing.T) { } queue(t, h, 1, post("1", "hello {"+c.Sender+"}")) eventually(t, "the post", func() bool { return len(h.Posts()) == 1 }) - if p := h.Posts()[0]; p.Chat != inA || p.Label != "Game" || p.Text != "hello @Alice" || p.Done == nil { + if p := h.Posts()[0]; p.Chat != inA || p.Label != "Game" || p.Text != "hello @Alice" || p.OnSent == nil { t.Fatalf("post %+v", p) } @@ -525,7 +525,7 @@ func TestOutbox(t *testing.T) { if n := len(h.Posts()); n != 1 { t.Fatalf("%d posts while one waits", n) } - h.Posts()[0].Done([]int64{1}, false) + h.Posts()[0].OnSent([]int64{1}, false) eventually(t, "the held posts", func() bool { return len(h.Posts()) == 2 }) if p := h.Posts()[1]; p.Text != "two\n\nthree" { t.Fatalf("held %q", p.Text) @@ -533,11 +533,11 @@ func TestOutbox(t *testing.T) { // Dropped before it was sent, as while the bot stops: posted again, // one by one, as nothing waits. - h.Posts()[1].Done(nil, true) + h.Posts()[1].OnSent(nil, true) eventually(t, "the post again", func() bool { return len(h.Posts()) == 3 }) - h.Posts()[2].Done([]int64{2}, false) + h.Posts()[2].OnSent([]int64{2}, false) eventually(t, "the next post again", func() bool { return len(h.Posts()) == 4 }) - h.Posts()[3].Done([]int64{3}, false) + h.Posts()[3].OnSent([]int64{3}, false) if p := h.Posts(); p[2].Text != "two" || p[3].Text != "three" { t.Fatalf("again %q, %q", p[2].Text, p[3].Text) } @@ -551,7 +551,7 @@ func TestOutbox(t *testing.T) { if p := h.Posts(); len(p) != 5 || p[4].Text != "four" { t.Fatalf("posts %+v", p) } - h.Posts()[4].Done(nil, false) + h.Posts()[4].OnSent(nil, false) // A reaction, to a message the addon has a ref for; ops it may not do, // or for a chat it has no lease in, are dropped and counted. @@ -603,7 +603,7 @@ func TestOutboxDelivery(t *testing.T) { var texts []string for i := 0; i < len(h.Posts()); i++ { texts = append(texts, h.Posts()[i].Text) - h.Posts()[i].Done([]int64{int64(i)}, false) + h.Posts()[i].OnSent([]int64{int64(i)}, false) } if want := []string{"post 1", "post 2\n\npost 3", "post 4\n\npost 5"}; !slices.Equal(texts, want) { t.Fatalf("posts %q", texts) @@ -622,7 +622,7 @@ func TestOutboxDelivery(t *testing.T) { if p.Text != "post 6" { t.Fatalf("try %d: %q", try, p.Text) } - p.Done(nil, true) + p.OnSent(nil, true) if a.apply(postOp("6", nil)); len(h.Posts()) != 4+try { t.Fatalf("try %d: posted again before it was due", try) } From d523464a80c2b757864cd870b5899d1d816a156c Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Fri, 20 Nov 2026 21:29:16 +0000 Subject: [PATCH 12/26] Ports: one OnSent contract, failed sends count as dropped, docs match - Action.OnSent now keeps Post.OnSent's contract: called exactly once, with dropped set when the answer is never sent (shutdown first, a panic, Done). - A send that fails returns no timestamps and reports dropped, so the addon outbox retries it (at least once; a timed-out send that went out may be posted twice). A labelled post whose send fails is taken back out of history (chats.Store.Withdraw), so retries don't pile up copies. - Stale Done wording from the rename is gone (TECHNICAL.md, featuretest, once(), host tests). - Port docs match the code: the IsZero rule, Info's fields, what joins a mailbox, the type listing, four stages, CONTRIBUTING's port table (OnEvent, OfferTools, Store), React's Timestamp-0 rule. - Reachable logs a neutral reason; PostLow's merge takes the new item. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- CONTRIBUTING.md | 5 +- TECHNICAL.md | 24 +++---- internal/bot/answer.go | 8 ++- internal/bot/bot.go | 19 ++++-- internal/bot/bot_test.go | 30 +++++++++ internal/bot/fakes_test.go | 7 ++- internal/bot/host.go | 52 +++++++++------ internal/bot/host_test.go | 70 ++++++++++++++++----- internal/chats/chats.go | 21 ++++++- internal/chats/chats_test.go | 22 +++++-- internal/feature/feature.go | 6 +- internal/feature/featuretest/featuretest.go | 3 +- internal/signal/decode.go | 4 +- internal/telegram/decode.go | 2 +- 14 files changed, 204 insertions(+), 69 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 54f1054..b4959c7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -25,10 +25,11 @@ Features reach the core only through the ports in `internal/feature`, one per st | Stage | Port | |---|---| | A message arrives | `OnMessage`: carry on, answer without the model (text or pictures), choose a tool, keep text as context, or mark it done | -| The model is asked | `OnTurn` (a note on the message, images) and `Tools` (a `ToolGroup`) | +| The model is asked | `OnTurn` (a note on the message, images) and `OfferTools` (a `ToolGroup`) | | Time arrives | `At`: a one-shot timer | +| Something besides a message happens | `OnEvent`: a reaction or a member change, answered without the model | -and the host's services: `Env`, `Info`, `Media`, `CallAPI`, `Deliver`, `Post`, `React`, `Groups`, `Redact` and `Go`. Hooks run in `features.go` order. An `OnMessage` hook for an unaddressed message runs on the reader goroutine, so it must not block or call the network. +and the host's services, among them `Env`, `Store`, `Info`, `Media`, `CallAPI`, `Deliver`, `Post`, `React`, `Groups`, `Redact` and `Go` ([TECHNICAL.md](TECHNICAL.md#lifecycle-and-ports) lists them all). Hooks run in `features.go` order. An `OnMessage` hook for an unaddressed message runs on the reader goroutine, so it must not block or call the network. If a feature can't be built on these, that's a design finding. Either a port becomes more generic, and stays tied to its stage, or the feature takes on more of the work. A feature-shaped field in the core is never the answer: delete any feature and the core doesn't change. diff --git a/TECHNICAL.md b/TECHNICAL.md index 3362527..08dc128 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -64,8 +64,8 @@ Each line has a journald priority, and every priority is always written: - **Reader goroutine.** The Signal client's reader parses each frame and decides "addressed?" without blocking or calling the network, then hands the bot a `bot.Received`, one of a closed set of types (`internal/bot/received.go`): `Incoming`, a message completed in its slot by its `Load` (an addressed one, or any other data message that arrived before the bot's own ID was known); `Chatter`, an unaddressed group message; `GroupChanged`; `Deleted`, a delete or a replacing edit, handled on the spot like `GroupChanged`; and `Happened` for a reaction, never passed to `OnMessage`. A member change, also a `Happened`, comes from the client's member-comparison goroutine through the same handler. The core switches on the type. `Incoming` goes to its chat's mailbox from here, and `Happened` too when an `OnEvent` hook is registered; the only other kinds there are `Outgoing`, a post the bot makes on its own (`Post`), `Reacted`, the bot's reactions (`React`), and `Posted`, a message a feature delivers, which `Network.Delivered` turns into a `Ready` (its sender's name, the bot's @name stripped, a group's members) in its slot. The bot may briefly take the chat store's lock (to queue a message or keep context). Unaddressed group messages go to the `OnMessage` hooks here. - **Worker slots.** A fixed pool of `MAX_CONCURRENCY`. Message handling that may call the network (waiting for the account ID, contacts a message needs, sticker labels, media, the model) runs only in a slot. The contact reloads on connect and on group changes run on their own timer, one at a time, and `listAccounts` on each connection's own goroutine. Until the bot's own ID is known, a message waits for it in a slot, up to 10s. A full pool drops the message with a warning. -- **Per-chat mailbox.** An addressed message, one a feature delivers, or one waiting for the bot's own ID joins its chat's mailbox (`chats.Store.Post`, generic over what it holds, so chats needn't know the bot's type); at most 4 wait, and more are dropped with a warning that says what was dropped (a message, a post or reactions). The bot's own reactions wait at low priority: those for one chat are merged into one item, handled after everything else waiting, and dropped first, with a warning, when a message needs their place, so they never cost an addressed message its place. One deleted, or replaced by an edit, before its turn is skipped (see Edits and deletes). A chat with work has one worker, holding one slot, which takes everything waiting at once, handles it in order, and exits when nothing is left, so each answer sees the ones before it. Different chats run in parallel. -- **Answered together.** Messages that arrive while the worker is busy are answered as one turn, a line each (in a group with the sender's name), so "actually" and "forget it" get one reply that sees both. On its own, in order, goes a message a hook acts on (such as a command), a delivered one, and one that waited for the bot's ID and was not addressed after all; a run is split where it would carry more than 4 images or a second sticker. A panic loses only the message or turn that caused it, and once shutdown begins nothing more that waited starts, not even its hooks. +- **Per-chat mailbox.** An addressed message, one a feature delivers, one waiting for the bot's own ID, a post the bot makes on its own, an event for an `OnEvent` hook, or the bot's reactions join its chat's mailbox (`chats.Store.Post`, generic over what it holds, so chats needn't know the bot's type); at most 4 wait, and more are dropped with a warning that says what was dropped (a message, a post or reactions). The bot's own reactions wait at low priority: those for one chat are merged into one item, handled after everything else waiting, and dropped first, with a warning, when a message needs their place, so they never cost an addressed message its place. One deleted, or replaced by an edit, before its turn is skipped (see Edits and deletes). A chat with work has one worker, holding one slot, which takes everything waiting at once, handles it in order, and exits when nothing is left, so each answer sees the ones before it. Different chats run in parallel. +- **Answered together.** Messages that arrive while the worker is busy are answered as one turn, a line each (in a group with the sender's name), so "actually" and "forget it" get one reply that sees both. On its own, in order, goes a message a hook acts on (such as a command), a delivered one, a post, an event, the bot's reactions, and one that waited for the bot's ID and was not addressed after all; a run is split where it would carry more than 4 images or a second sticker. A panic loses only the message or turn that caused it, and once shutdown begins nothing more that waited starts, not even its hooks; a post still waiting then, or a hook's answer not yet sent, is told it was dropped (`OnSent`). - **Per-chat state.** One struct per chat (`internal/chats`), in one capped map: the history and its expiry timer, recent message keys (for dedupe), mention names, the tool groups' follow-up counts, the cuts of deleted or edited messages (at most 64, kept while anything waits), and the mailbox. One lock guards the whole map and is held only to read or change it, never across a model call. The struct is deleted, or evicted when the map is full, only once its mailbox is empty and no worker is active, so a chat never gets a second worker. - **HTTP.** The model client keeps up to `MAX_CONCURRENCY` idle connections (Go's default is 2 per host). - **Shutdown.** On SIGTERM or SIGINT, timers and new work stop, work in flight drains for up to 8s (under Docker's 10s stop timeout), then the connection closes and the bot waits for what features run with `Go`. A second signal kills the process at once. @@ -95,7 +95,7 @@ cmd/signalctl/ a small client for signal-cli's daemon socket, for one-o - Core packages are concrete and call each other directly, with no interfaces between them. Files by role, no line limit. - **The network seam.** The bot reaches its chat network only through `bot.Network`; `*signal.Client` and `*telegram.Client` implement it, one process runs one (`TELEGRAM_BOT_TOKEN` set chooses Telegram, and `SIGNALCLI_SOCKET` set too is an error), only main imports them, and the interface exists for the bot's in-memory test fake. The network depends on the core, never the reverse: `internal/signal` imports `internal/bot` for `Received`, which sits next to `Network`. The core's prompt names no network: Signal's line, that a long message shows only its start until Read more, comes from `Network.Prompt`, and the golden prompts pin it. - **`bot.Received`** is what the network hands the core, and what a chat's mailbox holds: one of the kinds above, `Outgoing`, `Reacted`, or `Posted`, a message a feature delivers. Features never see one, so it isn't in `internal/feature`. `Network.Reachable(ctx, chat)` says, in the chat's slot, whether the bot may still post there on its own: on Signal, a group it is still a member of (`listGroups`) or the DM of someone still in `SIGNAL_DM_USER_IDS`; on Telegram, a group that passes the `TELEGRAM_DM_USER_IDS` member check, or a listed user's DM. `Network.Delivered(ctx, msg)` returns a `Ready` and ok: the message with its sender's name and without the bot's @name, `Mentioned` if that was there, and in a group its `Members` (name and ID), which the core claims into the names a post links. -- **`Send` returns what it sent.** It waits for signal-cli's answer to each `send` (up to a minute; attachments take longer) and returns the messages' timestamps, which the core keeps with the reply in history so a delete from the account's linked device can find it. A reply is added to history before it is sent, holding a placeholder ref, and `chats.Store.Retag` swaps in the timestamps once `Send` returns, so a message that arrives while the send is out lands after the turn in history, not before it; a recipient it wasn't delivered to is logged as each send returns. +- **`Send` returns what it sent.** It waits for signal-cli's answer to each `send` (up to a minute; attachments take longer) and returns the messages' timestamps, which the core keeps with the reply in history so a delete from the account's linked device can find it. A reply is added to history before it is sent, holding a placeholder ref, and `chats.Store.Retag` swaps in the timestamps once `Send` returns, so a message that arrives while the send is out lands after the turn in history, not before it (a labelled post whose send fails is taken back out, since the chat never saw it and it may be posted again); a recipient it wasn't delivered to is logged as each send returns. - **Why `Send` takes the names to link.** The chat's `@Name`-to-ID map is per-chat state, so it lives in `internal/chats` with the rest: learned from the names the model was shown, cleared on a group change, gone when the history goes, and with one rule for a name two people claim (`chats.Claim`). The network keeps no per-chat state, and only the core knows which map a send needs: the chat's for a reply, the group's members for a delivered post. So `Send` takes it as an argument rather than the network keeping a copy. - **Why the caption rule is the core's.** When a reply's pictures have captions, the core sends those in place of the model's text, and history keeps only the pictures' notes. It decides what history keeps, which is core state, and it happens after the model answers, where no port reaches; a feature doing it would need a fourth stage for this alone. `Picture.Caption` is generic (any tool's picture may have one), so the rule stays a few lines in the core. - `Message`, `Media`, `Picture` and the port types are defined once, in `internal/feature`, and the core uses them directly: nothing is copied or converted. @@ -104,7 +104,7 @@ cmd/signalctl/ a small client for signal-cli's daemon socket, for one-o ## Lifecycle and ports -The core's lifecycle has three stages. Each port is one stage; nothing else is a port. +The core's lifecycle has four stages. Each port is one stage; nothing else is a port. | Stage | Port | Returns | |---|---|---| @@ -115,8 +115,8 @@ The core's lifecycle has three stages. Each port is one stage; nothing else is a **Hook rules:** - Hooks run in feature order (`features.go`). -- For an unaddressed message, `OnMessage` runs on the reader goroutine, so it must not block or call the network. For an addressed or delivered one it runs in the message's slot. The first non-zero `Action` wins. -- `Answer`, `Pictures`, `OnSent` and `ToolChoice` count only on an addressed message, and `Context` only on an unaddressed one. `Done` counts on both: the hook handled the message, so it gets no answer and no model; an unaddressed one is kept nowhere, even with a `Context`, and later hooks never see it. An `Answer` and `Pictures` are sent together, with the caption rule as for a tool's pictures, and `OnSent`, if set, is called with the timestamps of the messages they went out in; `OnSent` alone doesn't count, so it can't claim a message. Nothing of them is kept in history. +- For an unaddressed message, `OnMessage` runs on the reader goroutine, so it must not block or call the network. For an addressed or delivered one it runs in the message's slot. The first `Action` that isn't zero (`IsZero`, after `For`, so an `OnSent` alone carries on) wins. +- `Answer`, `Pictures`, `OnSent` and `ToolChoice` count only on an addressed message, and `Context` only on an unaddressed one. `Done` counts on both: the hook handled the message, so it gets no answer and no model; an unaddressed one is kept nowhere, even with a `Context`, and later hooks never see it. An `Answer` and `Pictures` are sent together, with the caption rule as for a tool's pictures, and `OnSent`, if set, is called once: with the timestamps of the messages they went out in, or with dropped set when they never go out (shutdown began first, the send failed, or the answer was cut off by a panic); `OnSent` alone doesn't count, so it can't claim a message. Nothing of them is kept in history. - An `Event` is a reaction (its emoji, whether it was taken back, who wrote the message and when, and whether that was the bot) or a change in a group's members (who joined, who left, or that the bot was added), with who did it. The network decides which reach the core, as for messages: never the bot's own, in a DM only an allowed sender's, member changes only in groups. With no `OnEvent` hook the core drops events as they arrive. Otherwise each goes into its chat's mailbox and runs on a slot of its own, so a hook may block or call the network: a reaction in order with that chat's messages, a member change once the network has worked it out, which can be after messages that came later (below); the first non-empty reply is sent with `@Name` linked to the chat's known names and the event's people. Events are never logged, kept in history or shown to the model. - **Member changes on Signal:** signal-cli's group `UPDATE` says only that something changed, so the client keeps each group's members from `listGroups`, loaded once the bot's ID is known, and on an update reloads them and compares, only when the core has an `OnEvent` hook (`Network.Watch`). Updates are folded and spaced like the contact list, at most one load per 15 seconds after a contact load, so a member change can reach features after messages read later. Members already there at startup are never reported; a group the bot wasn't in is `BotAdded`; a change of name or description alone is no event. The bot's own update (from its linked phone) refreshes the members it compares with but reaches no feature. `By` is whoever sent the update, or empty when several people's updates were folded together. Each comparison updates only the groups it compares, and one whose `listGroups` call fails keeps its updates for the next. - `OnTurn` runs only when the model is about to be asked. @@ -126,7 +126,7 @@ The core's lifecycle has three stages. Each port is one stage; nothing else is a - `CallAPI(ctx, path, body)`: from a tool's Run, post a JSON body to another endpoint of the model's API, such as OpenRouter's `/images`, and get the response; the core keeps the key and the data-collection request, and counts the cost toward the reply (see the model, above). - `Env(key, def)`: a feature's own setting. The docs guardrail finds each name passed to it. - `Store(name)`: the feature's saved state, opened while it registers: one JSON document, `<name>.json` in the state directory (`STATE_DIRECTORY`'s first directory, or the working directory when it isn't set), with `Load(v)` (found is false when nothing is saved yet; a file that can't be read is an error, so the feature can stop the bot rather than overwrite it) and `Save(v)` (written to a temporary file, synced and renamed over the old one, at most 4 MiB, its newline included). The first `Store` call checks that the directory can be listed and written, and fails with how to fix it otherwise (for Docker's `/data`, `chown 65532`; elsewhere, the unit's `StateDirectory`), so a bot whose features save nothing needs no state directory. A name is lowercase letters, digits, `-` and `_`, up to 32, and may be opened once; `budget` is the core's (`budget.json`, written the same way). Features save files only this way (a guardrail below). -- `Info()`: the bot's name, its version, the model ("" with no model), the API's provider (`openrouter` or ""), whether it takes images and can call tools, and the names of the tools, as in `{tools}` (none when it can't call tools). All but the name and the tools are known when features register; images and tool calling may turn off later ([Capabilities](#the-core)). +- `Info()`: the bot's name, the chat network (`Network`, from `Network.Name`: `signal` or `telegram`), its version, the model ("" with no model), the API's provider (`openrouter` or ""), whether it takes images, audio and PDFs (`Audio`, `PDFs`) and can call tools, the names of the tools, as in `{tools}` (none when it can't call tools), and the introduction, in a group and in a DM. All but the name and the tools are known when features register; images, audio, PDFs and tool calling may turn off later ([Capabilities](#the-core)). - `Media(ctx, msg, i)`: the bytes of a message's image or sticker (15s). The core fills in each sticker's `Label` (its emoji and pack title) when it loads the message. - `Deliver(msg)`: act on a message as if its sender had just posted it in its chat, through the chat's mailbox. Inside the message's slot: - it waits up to 10s for the bot to be connected, else it is dropped with a warning; @@ -136,8 +136,8 @@ The core's lifecycle has three stages. Each port is one stage; nothing else is a - anything else the bot posts as written, with @Name linked against the group's members (never an ambiguous name), and history keeps it as the sender's message, "<name>: <text>", not as something the bot chose to say. These rules are what "as if its sender had just posted it" means for any feature, not just `/schedule`, so the host applies them rather than each feature. The membership check calls the network, so it runs in the message's slot; a feature's timer callback has no slot to make that call in. -- `Post(Post)`: the bot posts `Text`, with any `Pictures` (the caption rule applies), to a group or a DM, as written, never through the model, through that chat's mailbox. In the slot, `Network.Reachable` must say the bot may still post there, or it is dropped and logged at info. `@Name` is linked against the chat's known names. With a `Label`, history keeps the post as the bot's own entry, `[Label] text` (the pictures' notes in place of text they replaced), clamped to 500 characters, so a feature's text can never pose as a person; with none, or with no model, nothing is kept. `OnSent`, if set, is called once, with the timestamps sent, or with dropped set when it never goes out (a full mailbox, an unreachable chat, shutdown). `/schedule` uses it, with no label, to tell an owner in their DM that a one-off was dropped. -- `React(chat, msg, emoji)`: the bot puts `emoji` on `msg`, through the chat's mailbox at low priority (see the per-chat mailbox): a later reaction to the same message replaces a waiting one, at most 16 wait per chat, and one to a message deleted or replaced by an edit since is skipped. +- `Post(Post)`: the bot posts `Text`, with any `Pictures` (the caption rule applies), to a group or a DM, as written, never through the model, through that chat's mailbox. In the slot, `Network.Reachable` must say the bot may still post there, or it is dropped and logged at info. `@Name` is linked against the chat's known names. With a `Label`, history keeps the post as the bot's own entry, `[Label] text` (the pictures' notes in place of text they replaced), clamped to 500 characters, so a feature's text can never pose as a person; with none, or with no model, nothing is kept. `OnSent`, if set, is called once, with the timestamps sent, or with dropped set when it never goes out (a full mailbox, an unreachable chat, shutdown, a send that failed and returned no timestamps). `/schedule` uses it, with no label, to tell an owner in their DM that a one-off was dropped. +- `React(chat, msg, emoji)`: the bot puts `emoji` on `msg`, through the chat's mailbox at low priority (see the per-chat mailbox): a later reaction to the same message replaces a waiting one, at most 16 wait per chat, and one to a message deleted or replaced by an edit since is skipped. `chat` mirrors `Network.React`; `msg`'s own `Chat` is ignored. A message the bot made (`Timestamp` 0) can't be reacted to; nothing happens. - `Groups(ctx, user)`: the groups the bot shares with a user, with their names (`listGroups`). - `Redact(text)`: text with every name and ID the bot knows for anyone but itself, and any UUID or phone number, replaced with "redacted", for logging text the bot doesn't control (a local MCP server's output). - `Go(fn)`: run `fn` for as long as the bot runs. Its ctx ends when the bot stops, which then waits for `fn` to return (MCP stops its local servers this way). @@ -146,9 +146,9 @@ The core's lifecycle has three stages. Each port is one stage; nothing else is a ```go type Action struct{ Answer string; Pictures []Picture; OnSent func(sent []int64, dropped bool); ToolChoice, Context string; Done bool } // IsZero: carry on type Post struct{ Chat Chat; Label, Text string; Pictures []Picture; OnSent func(sent []int64, dropped bool) } -type Additions struct{ Note, HistoryNote string; Images []string; Files []File } +type Additions struct{ Note, HistoryNote string; Images []string; Files []File; Content bool } type File struct{ Name, MIME string; Data []byte } -type Picture struct{ Data []byte; Caption, HistoryNote string } +type Picture struct{ Data []byte; Name, Caption, HistoryNote string } type ToolGroup struct{ Names []string; Listing, System string; Tools []Tool; Keywords *regexp.Regexp } type Tool struct{ Name, Description string; Schema json.RawMessage; Server string; Run func(ctx context.Context, args string) (string, []Picture, error) } ``` @@ -246,7 +246,7 @@ In `features.go` order, which is the order hooks run in and of the tools line an - **Direct commands:** a chat command with `direct` makes `/name args` a call the bot makes itself, without the model, to a tool whose visibility has `"bot"` (looked up among all the server's tools; one without it is skipped with a warning), with `{"args": "<text after the command>"}`. It runs in the message's slot, with 15s or the command's `timeout` (1s to 2m, only on a direct command), and at most 2 at once per server, each held for as long as its call runs: a third is told "<title> is busy, try again in a moment." at once. The title is the server's `serverInfo.title`, else its name, made safe. In a chat its `chats` or `dms` don't allow, it answers "/name isn't available in this chat.". The result's text parts, joined, become the `Answer` (placeholders filled in, capped at 4,000 characters) and its image parts up to 2 `Pictures`, 2 MB together after `img.Safe` (any left out are counted in a warning); a result with neither is `Done`. An error result, a timeout, a bad result or a server that can't be reached answers "<title> couldn't do that just now.". Each call logs the command, the tool, the outcome (ok, or a code), the time and the result's size. Direct commands are kept with no model or one that can't call tools; a server with no tool for the model lists them with `ListCommands` under its label. - **Watches:** a direct command's result may ask, in `_meta["io.github.robdevops.signalbot/watch"]`, for a watch on the chat the command came from (the only way to make one, so an addon can't watch a chat it wasn't used in): an `id` (at most 64 bytes), an RE2 `pattern` (at most 1 KB), `until` (RFC 3339, cut to `watch_max` from now and never extended), the `tool` to call with each match (one the bot may call) and an optional `guard` (at most 500 characters). It needs `watch`, and at most 8 are live in a chat per addon (one with the same ID is replaced). A pattern that matches the empty string or any of about 200 ordinary chat lines in `corpus.go` is refused, so no watch is a feed of the chat; a refusal is logged by reason, never the pattern. One `OnMessage` hook, registered after the chat commands, checks each message with text in an allowed chat against the chat's live watches, on both paths: unaddressed ones on the reader goroutine (only a map lookup and the patterns, under a mutex held briefly), addressed ones (a reply to the bot, a DM, an @mention, a command) in their slot. A watch matches any message the bot gets while it lasts, by when the bot got it, not by its `Timestamp` (on Signal the sender's clock, which may be behind); an edit, unless its original was claimed, only if its original's `Timestamp` is at or after the command's, so an older message's edit isn't taken. An addressed message with no text (a bare mention, or a reply with only a picture) is still checked for the guard. A match is `Done`, so it is never answered, sent to the model or kept in history, and `groupctx` never sees it; it is claimed for 48 hours (chat key, sender's pseudonym, sent time), so a later edit of it goes the same way, to the same tool, whether or not the watch is still live; and it is passed without waiting to the addon's watch worker, whose queue holds 256 (when full, "addon <name>: watch queue full, a matched message dropped", still `Done`). The worker calls the watch's tool with `{"text": …}` and the context, within 120 calls a minute per chat (bursts of 20; a match past it waits its turn in the worker's queue, while other chats' matches go ahead), and keeps a match whose call found the server down (not running, or exited before answering) at the head of the queue until the server has started again (or a minute has passed), dropping it with a warning after 3 such calls, and if the result's `_meta["io.github.robdevops.signalbot/react"]` is one emoji, reacts with it (`React`), which needs `react` and counts against the addon's rate. A watch whose command answered with pictures records, through `OnSent`, the timestamps of the messages they went out in; while it lives, an addressed message quoting one of them gets the `guard` as its `Answer`, so nobody can ask the model about the picture. - **Leases:** an addon may post or react only in a chat where it had a direct command or a watch match in the last 24 hours; the lease maps the chat's pseudonym to the chat. - - **Outbox:** if the server advertises `resources.subscribe`, the bot sends `resources/subscribe` for `signalbot://outbox` after each (re)start's `initialize`, then reads it; otherwise the outbox is off, with a warning. Any `notifications/resources/updated` from the server marks the outbox as having news (whatever the URI, which may be under the one subscribed). One reader goroutine per addon reads `resources/read` of `signalbot://outbox/<cursor>` (`0` at first), page by page while `more` is true, up to 100 pages, so two reads never race and news during a read is read after it. A page is one text content holding `{"cursor", "more", "ops"}`; a not-found error (-32002, or the Go SDK's -32602) is logged as no outbox. Ops are applied once each by `id`, the last 1,000 IDs remembered, and are `post` (`chat`, Markdown `text` with placeholders, up to 2 `images` as `{data, mimeType, name}`, 2 MB together), needing `post`; `react` (`ref`, `emoji`), needing `react`; and `unwatch` (`chat`, `watch`), which, for a watch not yet made, stops it being made for 10 minutes. A post or reaction needs a live lease in a chat the addon is still allowed, and counts against `rate` per chat. A post goes through `Post` with the addon's title as its `Label`, so history keeps it as `[Title] …`, the bot's own words. At most one of an addon's posts waits in a chat's mailbox: until its `Done`, later posts for that chat are held, each merged into the one held before it while their pictures together stay within 2 and 2 MB, and sent in turn. Delivery is at least once: a post counts as applied, and the cursor moves past it, only once its `Done` says it was sent. Until then each read starts from the cursor before it and skips it while it waits; one dropped before it was sent (as while the bot stops, or before the network is up at startup, when `Post` gives up on the chat) is posted again by a read 10s later, then 20s, doubling to 5 minutes, not counted against `rate` again, and given up with a warning after 6 tries. A page with `more` waits for its posts before the next is read, since reading past the cursor lets the addon forget them. A read that fails, is malformed, or stops at 100 pages is tried again after 10s, doubling to 5 minutes, without waiting for news. What a read drops is counted in one warning by reason, never content. + - **Outbox:** if the server advertises `resources.subscribe`, the bot sends `resources/subscribe` for `signalbot://outbox` after each (re)start's `initialize`, then reads it; otherwise the outbox is off, with a warning. Any `notifications/resources/updated` from the server marks the outbox as having news (whatever the URI, which may be under the one subscribed). One reader goroutine per addon reads `resources/read` of `signalbot://outbox/<cursor>` (`0` at first), page by page while `more` is true, up to 100 pages, so two reads never race and news during a read is read after it. A page is one text content holding `{"cursor", "more", "ops"}`; a not-found error (-32002, or the Go SDK's -32602) is logged as no outbox. Ops are applied once each by `id`, the last 1,000 IDs remembered, and are `post` (`chat`, Markdown `text` with placeholders, up to 2 `images` as `{data, mimeType, name}`, 2 MB together), needing `post`; `react` (`ref`, `emoji`), needing `react`; and `unwatch` (`chat`, `watch`), which, for a watch not yet made, stops it being made for 10 minutes. A post or reaction needs a live lease in a chat the addon is still allowed, and counts against `rate` per chat. A post goes through `Post` with the addon's title as its `Label`, so history keeps it as `[Title] …`, the bot's own words. At most one of an addon's posts waits in a chat's mailbox: until its `OnSent`, later posts for that chat are held, each merged into the one held before it while their pictures together stay within 2 and 2 MB, and sent in turn. Delivery is at least once: a post counts as applied, and the cursor moves past it, only once its `OnSent` says it was sent. A send that fails counts as dropped, so a post whose send timed out after it went out may be posted twice, rather than lost. Until then each read starts from the cursor before it and skips it while it waits; one dropped before it was sent (as while the bot stops, or before the network is up at startup, when `Post` gives up on the chat) is posted again by a read 10s later, then 20s, doubling to 5 minutes, not counted against `rate` again, and given up with a warning after 6 tries. A page with `more` waits for its posts before the next is read, since reading past the cursor lets the addon forget them. A read that fails, is malformed, or stops at 100 pages is tried again after 10s, doubling to 5 minutes, without waiting for news. What a read drops is counted in one warning by reason, never content. - **What is saved,** per addon, in `mcp.json`: live watches (with their guard pictures' timestamps), claims, leases, the outbox cursor and the last 1,000 applied op IDs. Anything expired is left out. At startup they are restored, leaving out a watch whose chat is no longer allowed or whose pattern no longer passes, so a restart of the bot or the addon never lets a match fall through to history. Refs, names, tombstones and held posts are in memory only. - **`groupctx`** (`GROUP_CONTEXT`, on by default) comes after `mcp`, so an earlier hook can claim a message (`Done`) before it is kept, and keeps each other unaddressed group message as context: `Name: text`, capped at 2,000 characters, with photos, stickers and files noted as `[image]`, `[sticker]` and `[file "name"]` but never fetched. The core keeps it like any history entry, marked as context, and never logs it. - **`schedule`** is `/schedule` ([below](#schedule)). diff --git a/internal/bot/answer.go b/internal/bot/answer.go index 8044e4f..eeda4ec 100644 --- a/internal/bot/answer.go +++ b/internal/bot/answer.go @@ -57,7 +57,8 @@ const ( ) // respond acts on an addressed message: as act says (nothing if Done; its -// Answer and Pictures sent, with OnSent told of what went out), else by +// Answer and Pictures sent, with OnSent told of what went out, and told +// they were dropped if they weren't, or Send failed), else by // asking the model and sending its reply (asking again if the API rejects // its images or tools; see fallBack); with no model, only an Answer and // Pictures are sent, and with tools off a chat command gets noTools rather @@ -66,6 +67,9 @@ const ( // are offered by msg.Text alone, what was typed, never a sender's name or a // quote. refs names the messages answered, for history (see Forget). func (b *Bot) respond(msg feature.Message, act feature.Action, text string, refs []chats.Ref) { + if act.OnSent != nil { // made once by hooked + defer act.OnSent(nil, true) // if nothing is sent, also if something below panics + } switch { case act.Done: return @@ -73,7 +77,7 @@ func (b *Bot) respond(msg feature.Message, act feature.Action, text string, refs text, _ := captioned(act.Answer, act.Pictures) sent := b.net.Send(msg.Chat, text, act.Pictures, b.chats.Names(msg.Chat.Key())) if act.OnSent != nil { - act.OnSent(sent, false) + act.OnSent(sent, len(sent) == 0) } return case b.ai == nil: diff --git a/internal/bot/bot.go b/internal/bot/bot.go index fc8f278..5b399cb 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -37,7 +37,8 @@ type Network interface { Watch(w Watch) WaitID(ctx context.Context) string // Send posts a reply, split as the network needs, and returns the - // timestamps of the messages sent, which name them for a later delete. + // timestamps of the messages sent, which name them for a later delete; + // a send that fails returns no timestamps. Send(chat feature.Chat, text string, pics []feature.Picture, known map[string]string) (sent []int64) // React puts emoji on msg in chat, as a reaction from the bot. React(chat feature.Chat, msg feature.Message, emoji string) @@ -353,7 +354,8 @@ func abandon(rs []Received) { // an answer), a delivered one, a post, the bot's reactions, and one that // waited for the bot's ID and was not addressed after all. A panic loses // only the message or turn that caused it, and nothing new starts once -// shutdown begins; a post left waiting then is told it was dropped. +// shutdown begins; a post left waiting then, or a hook's answer not yet +// sent, is told it was dropped. func (b *Bot) work(rs []Received) { var batch []feature.Message flush := func() { @@ -405,6 +407,9 @@ func (b *Bot) work(rs []Received) { default: if act := b.hooked(msg); !act.IsZero() { alone(func() { b.respond(msg, act, prompt(msg), refs(msg)) }) + if act.OnSent != nil { + act.OnSent(nil, true) // if shutdown began first + } return } if !fits(batch, msg) { @@ -546,7 +551,9 @@ func (b *Bot) onMessage(ctx context.Context, msg feature.Message) feature.Action const slowHooks = time.Second // hooked runs the OnMessage hooks for an addressed message, in its chat's -// slot. If they haven't returned after slowHooks, the chat sees the bot +// slot, and makes the OnSent of the Action that wins safe to call more than +// once, so it can be told the answer was dropped wherever it isn't sent. +// If the hooks haven't returned after slowHooks, the chat sees the bot // typing until they do, as it would while the model answers; quick ones // show nothing. func (b *Bot) hooked(msg feature.Message) feature.Action { @@ -569,7 +576,11 @@ func (b *Bot) hooked(msg feature.Message) feature.Action { stop() } }() - return b.onMessage(b.ctx, msg) + act := b.onMessage(b.ctx, msg) + if act.OnSent != nil { + act.OnSent = once(act.OnSent) + } + return act } // introLine is a feature's line for the introduction, perhaps only in a DM. diff --git a/internal/bot/bot_test.go b/internal/bot/bot_test.go index 9942ec4..7d26c2d 100644 --- a/internal/bot/bot_test.go +++ b/internal/bot/bot_test.go @@ -452,6 +452,36 @@ func TestShutdownStopsWaiting(t *testing.T) { } } +// A hook's answer cut off by shutdown, which began after the hook +// returned, is never sent, and its OnSent is told it was dropped, once. +func TestShutdownDropsAnswer(t *testing.T) { + outcomes := make(chan bool, 2) + stopped := make(chan struct{}) + h := start(t, options{features: func(b *Bot) { + b.Command("ping", func(context.Context, feature.Message, string) feature.Action { + go func() { defer close(stopped); b.Shutdown(5 * time.Second) }() + for !b.closing.Load() { + time.Sleep(time.Millisecond) + } + return feature.Action{Answer: "pong", OnSent: func(_ []int64, dropped bool) { outcomes <- dropped }} + }) + }}) + h.receive(dm("/ping")) + <-stopped + h.noSend() + select { + case dropped := <-outcomes: + if !dropped { + t.Fatal("OnSent said it was sent") + } + default: + t.Fatal("OnSent never called") + } + if len(outcomes) != 0 { + t.Fatal("OnSent called again") + } +} + // Waiting messages whose photos together pass 4 are answered in two turns, // so no turn carries more pictures than one message may. func TestWaitingPhotosSplit(t *testing.T) { diff --git a/internal/bot/fakes_test.go b/internal/bot/fakes_test.go index 98fca83..ca79be7 100644 --- a/internal/bot/fakes_test.go +++ b/internal/bot/fakes_test.go @@ -56,6 +56,7 @@ type fakeNet struct { stopped int // their stops called fetched []string // the media IDs fetched sends atomic.Int64 // Send calls, for their timestamps + fail atomic.Bool // while set, Send fails: nothing is sent watch Watch // what Watch was told } @@ -87,8 +88,12 @@ func (n *fakeNet) WaitID(ctx context.Context) string { } } -// Send returns one timestamp per call, counting up from 5000. +// Send returns one timestamp per call, counting up from 5000, or none +// while fail is set. func (n *fakeNet) Send(chat feature.Chat, text string, images []feature.Picture, known map[string]string) []int64 { + if n.fail.Load() { + return nil + } n.sent <- sent{chat, text, images, known} return []int64{5000 + n.sends.Add(1)} } diff --git a/internal/bot/host.go b/internal/bot/host.go index 0617066..713e1ad 100644 --- a/internal/bot/host.go +++ b/internal/bot/host.go @@ -143,14 +143,14 @@ func (b *Bot) Post(p feature.Post) { } } -// once is done made safe to call more than once, the calls after the first -// doing nothing; nil does nothing. -func once(done func(sent []int64, dropped bool)) func(sent []int64, dropped bool) { +// once is onSent made safe to call more than once, the calls after the +// first doing nothing; nil does nothing. +func once(onSent func(sent []int64, dropped bool)) func(sent []int64, dropped bool) { var o sync.Once return func(sent []int64, dropped bool) { o.Do(func() { - if done != nil { - done(sent, dropped) + if onSent != nil { + onSent(sent, dropped) } }) } @@ -158,22 +158,30 @@ func once(done func(sent []int64, dropped bool)) func(sent []int64, dropped bool // say sends a post in its chat's slot, if the bot may still post there, // with @Name linked to the chat's known names. With a label, history keeps -// it as the bot's own entry, "[Label] text", clamped; without one, nothing. +// it as the bot's own entry, "[Label] text", clamped, unless the send +// fails; without one, nothing. func (b *Bot) say(p feature.Post) { defer p.OnSent(nil, true) // if it is never sent if !b.net.Reachable(b.ctx, p.Chat) { - logx.Infof("dropped a post: the bot can no longer post in its chat") + logx.Infof("dropped a post: its chat isn't reachable") return } key := p.Chat.Key() text, kept := captioned(p.Text, p.Pictures) if p.Label == "" || b.ai == nil { // with no model, nothing would read it - p.OnSent(b.net.Send(p.Chat, text, p.Pictures, b.chats.Names(key)), false) + sent := b.net.Send(p.Chat, text, p.Pictures, b.chats.Names(key)) + p.OnSent(sent, len(sent) == 0) return } ref := b.pending() b.chats.Add(key, b.now(), 0, chats.Entry{Role: "assistant", Content: txt.Clamp("["+p.Label+"] "+kept, maxPostKept), Refs: []chats.Ref{ref}}) - p.OnSent(b.sendKept(key, ref, p.Chat, text, p.Pictures, b.chats.Names(key)), false) + sent := b.net.Send(p.Chat, text, p.Pictures, b.chats.Names(key)) + if len(sent) == 0 { + b.chats.Withdraw(key, ref.ID) // the chat never saw it, and it may be posted again + } else { + b.chats.Retag(key, ref.ID, botRefs(sent)) + } + p.OnSent(sent, len(sent) == 0) } // maxPostKept caps what history keeps of a post. @@ -187,23 +195,29 @@ func (b *Bot) React(chat feature.Chat, msg feature.Message, emoji string) { return } msg.Chat = chat - r := Reaction{Message: msg, Emoji: emoji} - add := Reacted{Chat: chat, Reactions: []Reaction{r}} - merge := func(waiting Received) Received { - w := waiting.(Reacted) - w.Reactions = slices.DeleteFunc(slices.Clone(w.Reactions), func(x Reaction) bool { - return x.Message.Sender == msg.Sender && x.Message.Timestamp == msg.Timestamp + add := Reacted{Chat: chat, Reactions: []Reaction{{Message: msg, Emoji: emoji}}} + if err := b.chats.PostLow(chat.Key(), add, mergeReactions); err != nil { + b.dropped(add, err) + } +} + +// mergeReactions adds m's reactions to those waiting: one on a message +// that already has one waiting replaces it, and past maxReactions the +// oldest is dropped. +func mergeReactions(waiting, m Received) Received { + w := waiting.(Reacted) + w.Reactions = slices.Clone(w.Reactions) + for _, r := range m.(Reacted).Reactions { + w.Reactions = slices.DeleteFunc(w.Reactions, func(x Reaction) bool { + return x.Message.Sender == r.Message.Sender && x.Message.Timestamp == r.Message.Timestamp }) if len(w.Reactions) >= maxReactions { logx.Warnf("dropped a reaction: %d already wait in its chat", maxReactions) w.Reactions = w.Reactions[1:] } w.Reactions = append(w.Reactions, r) - return w - } - if err := b.chats.PostLow(chat.Key(), add, merge); err != nil { - b.dropped(add, err) } + return w } // maxReactions caps the reactions waiting in one chat. diff --git a/internal/bot/host_test.go b/internal/bot/host_test.go index 3ef04ff..fda8b1d 100644 --- a/internal/bot/host_test.go +++ b/internal/bot/host_test.go @@ -698,26 +698,26 @@ const strangerID = "33333333-3333-4333-8333-333333333333" // A post goes to a group or a DM, with @Name linked to the chat's known // names, unless the network says the bot can no longer post there. History // keeps a labelled one as the bot's own, clamped, and nothing of one with -// no label. Done is called once: when it is sent, or dropped. +// no label. OnSent is called once: when it is sent, or dropped. func TestPost(t *testing.T) { h := start(t, options{}) - type done struct { + type outcome struct { sent []int64 dropped bool } - dones := make(chan done, 16) + outcomes := make(chan outcome, 16) post := func(p feature.Post) { - p.OnSent = func(sent []int64, dropped bool) { dones <- done{sent, dropped} } + p.OnSent = func(sent []int64, dropped bool) { outcomes <- outcome{sent, dropped} } h.b.Post(p) } - next := func() done { + next := func() outcome { t.Helper() select { - case d := <-dones: + case d := <-outcomes: return d case <-time.After(5 * time.Second): - t.Fatal("Done never called") - return done{} + t.Fatal("OnSent never called") + return outcome{} } } group := feature.Chat{GroupID: groupID} @@ -728,7 +728,7 @@ func TestPost(t *testing.T) { t.Fatalf("sent %+v", s) } if d := next(); d.dropped || fmt.Sprint(d.sent) != "[5002]" { - t.Fatalf("done %+v", d) + t.Fatalf("OnSent got %+v", d) } post(feature.Post{Chat: group, Label: "Label", Text: "never sent", Pictures: []feature.Picture{{Data: png, Caption: "a caption", HistoryNote: "[a picture]"}}}) if s := h.nextSend(); s.text != "a caption" || len(s.images) != 1 { @@ -754,19 +754,19 @@ func TestPost(t *testing.T) { for _, chat := range []feature.Chat{{User: strangerID}, {GroupID: "other"}} { post(feature.Post{Chat: chat, Label: "Label", Text: "never sent"}) if d := next(); !d.dropped || d.sent != nil { - t.Fatalf("done %+v", d) + t.Fatalf("OnSent got %+v", d) } } post(feature.Post{Chat: group}) // nothing to send if d := next(); !d.dropped { - t.Fatalf("done %+v", d) + t.Fatalf("OnSent got %+v", d) } h.settle() h.noSend() - if len(dones) != 0 { - t.Fatalf("Done called again: %+v", <-dones) + if len(outcomes) != 0 { + t.Fatalf("OnSent called again: %+v", <-outcomes) } - if n := strings.Count(h.logs.String(), "<6>dropped a post: the bot can no longer post in its chat\n"); n != 2 { + if n := strings.Count(h.logs.String(), "<6>dropped a post: its chat isn't reachable\n"); n != 2 { t.Fatalf("%d drops logged:\n%s", n, h.logs) } if strings.Contains(h.logs.String(), "never sent") { @@ -775,7 +775,7 @@ func TestPost(t *testing.T) { } // A post that doesn't fit in its chat's mailbox is dropped, with a warning -// of its own, and Done says so. +// of its own, and OnSent says so. func TestPostDropped(t *testing.T) { h := start(t, options{}) h.holdModel() @@ -787,7 +787,7 @@ func TestPostDropped(t *testing.T) { dropped := make(chan bool, 1) h.b.Post(feature.Post{Chat: feature.Chat{User: aliceID}, Text: "never sent", OnSent: func(_ []int64, d bool) { dropped <- d }}) if !<-dropped { - t.Fatal("Done said it was sent") + t.Fatal("OnSent said it was sent") } if !strings.Contains(h.logs.String(), "<4>dropped a post: 4 messages are already waiting in this chat\n") { t.Fatalf("logs:\n%s", h.logs) @@ -802,6 +802,44 @@ func TestPostDropped(t *testing.T) { h.noSend() } +// A send that fails counts as dropped, for a post with or without a label +// and for a hook's answer, so the feature can try again; a labelled post +// leaves history as it was, so trying again doesn't keep it twice. +func TestFailedSendDropped(t *testing.T) { + type outcome struct { + sent []int64 + dropped bool + } + outcomes := make(chan outcome, 4) + onSent := func(sent []int64, dropped bool) { outcomes <- outcome{sent, dropped} } + h := start(t, options{features: func(b *Bot) { + b.Command("ping", func(context.Context, feature.Message, string) feature.Action { + return feature.Action{Answer: "pong", OnSent: onSent} + }) + }}) + h.net.fail.Store(true) + h.b.Post(feature.Post{Chat: feature.Chat{User: aliceID}, Text: "never sent", OnSent: onSent}) + h.b.Post(feature.Post{Chat: feature.Chat{GroupID: groupID}, Label: "Label", Text: "never sent", OnSent: onSent}) + h.receive(dm("/ping")) + for range 3 { + select { + case o := <-outcomes: + if !o.dropped || o.sent != nil { + t.Fatalf("OnSent got %+v", o) + } + case <-time.After(5 * time.Second): + t.Fatal("OnSent never called") + } + } + h.settle() + if len(outcomes) != 0 { + t.Fatalf("OnSent called again: %+v", <-outcomes) + } + if hist := h.b.chats.History(feature.Chat{GroupID: groupID}.Key()); len(hist) != 0 { + t.Fatalf("history %v", hist) + } +} + // The bot's reactions wait at low priority: merged into one item, a later // one on the same message replacing the earlier, sent after what waited // with them, dropped first to make room, and skipped for a message deleted diff --git a/internal/chats/chats.go b/internal/chats/chats.go index 693b50e..e5c5412 100644 --- a/internal/chats/chats.go +++ b/internal/chats/chats.go @@ -220,8 +220,8 @@ func (s *Store[M]) Post(key string, m M) error { // PostLow adds m to the chat's mailbox at low priority: it waits after // everything else, and is the first dropped, by Post, to make room, so it // never takes the place of a message. A low-priority item already waiting -// is replaced by merge(waiting), so at most one waits. -func (s *Store[M]) PostLow(key string, m M, merge func(waiting M) M) error { +// is replaced by merge(waiting, m), so at most one waits. +func (s *Store[M]) PostLow(key string, m M, merge func(waiting, m M) M) error { s.mu.Lock() defer s.mu.Unlock() c := s.get(key, true) @@ -229,7 +229,7 @@ func (s *Store[M]) PostLow(key string, m M, merge func(waiting M) M) error { case c == nil: return errFull case c.busy && len(c.low) > 0: - c.low[0] = merge(c.low[0]) + c.low[0] = merge(c.low[0], m) return nil case c.busy && len(c.queue) >= maxQueue: return errQueueFull @@ -378,6 +378,21 @@ func (s *Store[M]) Retag(key, id string, refs []Ref) { } } +// Withdraw drops the entries holding the ref named id: for a post kept +// before it was sent, whose send failed, so the chat never saw it. +func (s *Store[M]) Withdraw(key, id string) { + s.mu.Lock() + defer s.mu.Unlock() + c := s.get(key, false) + if c == nil { + return + } + c.history = slices.DeleteFunc(c.history, func(e Entry) bool { + return slices.ContainsFunc(e.Refs, func(r Ref) bool { return r.ID == id }) + }) + s.tidy(key, c) +} + // Gone reports whether the version of message id at at was deleted or // replaced by an edit, so it is not answered or kept. func (s *Store[M]) Gone(key, id string, at int64) bool { diff --git a/internal/chats/chats_test.go b/internal/chats/chats_test.go index e2c17fc..edb1f07 100644 --- a/internal/chats/chats_test.go +++ b/internal/chats/chats_test.go @@ -79,10 +79,10 @@ func TestLowPriority(t *testing.T) { }, pool.spawn) var evicted []string s.SetEvicted(func(m string) { evicted = append(evicted, m) }) - merge := func(m string) func(string) string { return func(w string) string { return w + "+" + m } } + merge := func(w, m string) string { return w + "+" + m } s.Post("g:1", "0") for _, m := range []string{"a", "b", "c"} { - if err := s.PostLow("g:1", m, merge(m)); err != nil { + if err := s.PostLow("g:1", m, merge); err != nil { t.Fatal(err) } } @@ -96,7 +96,7 @@ func TestLowPriority(t *testing.T) { if fmt.Sprint(evicted) != "[a+b+c]" { t.Fatalf("evicted %v", evicted) } - if err := s.PostLow("g:1", "d", merge("d")); err != errQueueFull { + if err := s.PostLow("g:1", "d", merge); err != errQueueFull { t.Errorf("a low-priority item took a message's place: err %v", err) } close(release) @@ -108,7 +108,7 @@ func TestLowPriority(t *testing.T) { release = make(chan struct{}) got = nil s.Post("g:1", "0") - s.PostLow("g:1", "a", merge("a")) + s.PostLow("g:1", "a", merge) s.Post("g:1", "1") close(release) pool.wg.Wait() @@ -381,3 +381,17 @@ func TestRetag(t *testing.T) { t.Fatalf("forgetting a retagged ref left %v", h) } } + +// Withdraw drops the entries holding a placeholder ref, and leaves the +// rest. +func TestWithdraw(t *testing.T) { + s := New(10, func([]string) {}, newSlots(1).spawn) + s.Add("k", time.Now(), 0, + Entry{Role: "user", Content: "q", Refs: []Ref{{"alice\\x001", 1}}}, + Entry{Role: "assistant", Content: "a", Refs: []Ref{{"pending\\x001", 0}}}) + s.Withdraw("k", "pending\\x001") + s.Withdraw("none", "pending\\x001") + if h := s.History("k"); len(h) != 1 || h[0].Content != "q" { + t.Fatalf("withdrawing left %v", h) + } +} diff --git a/internal/feature/feature.go b/internal/feature/feature.go index bc2451f..b741362 100644 --- a/internal/feature/feature.go +++ b/internal/feature/feature.go @@ -106,7 +106,7 @@ type File struct { type Action struct { Answer string // reply with this text, without the model (addressed messages only) Pictures []Picture // send these with Answer, or alone, without the model; captions as for a tool's pictures (addressed messages only) - OnSent func(sent []int64, dropped bool) // if set with Answer or Pictures, called with the timestamps they went out in (addressed messages only); alone it doesn't count + OnSent func(sent []int64, dropped bool) // if set with Answer or Pictures, called once: with the timestamps they went out in, or dropped (addressed messages only); alone it doesn't count ToolChoice string // make the model call this tool before answering (addressed messages only) Context string // keep this text in the chat's history (unaddressed messages only) Done bool // the hook handled the message: no answer, no model, and for an unaddressed one nothing kept and no later hook @@ -270,7 +270,9 @@ type Host interface { Post(p Post) // React puts emoji on msg in chat, as a reaction from the bot, through // the chat's mailbox at low priority: unless msg was deleted or edited - // since, and unless the reaction is dropped to make room. + // since, and unless the reaction is dropped to make room. chat mirrors + // the network's React; msg's own Chat is ignored. A message the bot + // made (Timestamp 0) can't be reacted to; nothing happens. React(chat Chat, msg Message, emoji string) // Groups lists the groups the bot shares with user. Groups(ctx context.Context, user string) ([]Group, error) diff --git a/internal/feature/featuretest/featuretest.go b/internal/feature/featuretest/featuretest.go index 9348d38..6fad5a6 100644 --- a/internal/feature/featuretest/featuretest.go +++ b/internal/feature/featuretest/featuretest.go @@ -201,7 +201,8 @@ func (h *Host) Deliver(m feature.Message) { h.delivered = append(h.delivered, m) } -// Post records p; Posts returns what was posted. Done is never called. +// Post records p; Posts returns what was posted. OnSent is never called: +// a test calls it to say the post was sent or dropped. func (h *Host) Post(p feature.Post) { h.mu.Lock() defer h.mu.Unlock() diff --git a/internal/signal/decode.go b/internal/signal/decode.go index 413a73c..5158ed7 100644 --- a/internal/signal/decode.go +++ b/internal/signal/decode.go @@ -521,7 +521,7 @@ func (c *Client) Reachable(ctx context.Context, chat feature.Chat) bool { wait, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() if c.WaitID(wait) == "" { - logx.Warnf("post dropped: not connected to signal-cli after 10s") + logx.Warnf("not connected to signal-cli after 10s") return false } if chat.GroupID == "" { @@ -530,7 +530,7 @@ func (c *Client) Reachable(ctx context.Context, chat feature.Chat) bool { } var gs []group if err := c.call(wait, "listGroups", nil, &gs); err != nil { - logx.Warnf("post dropped: listGroups failed: %v", err) + logx.Warnf("listGroups failed: %v", err) return false } return slices.ContainsFunc(gs, func(g group) bool { return g.IsMember && g.ID == chat.GroupID }) diff --git a/internal/telegram/decode.go b/internal/telegram/decode.go index f00cd06..2b7e182 100644 --- a/internal/telegram/decode.go +++ b/internal/telegram/decode.go @@ -696,7 +696,7 @@ func (c *Client) Reachable(ctx context.Context, chat feature.Chat) bool { wait, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() if c.WaitID(wait) == "" { - logx.Warnf("post dropped: not connected to Telegram after 10s") + logx.Warnf("not connected to Telegram after 10s") return false } if chat.GroupID == "" { From 3d04bb76effde2b0306e436d4d00fb81fbb57fd7 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 21 Nov 2026 00:08:15 +0000 Subject: [PATCH 13/26] addon: a public package for signalbot's MCP addon extension The extension's wire format was written twice, once in the mcp feature and once in each addon. It now lives in one public package, github.com/robdevops/signalbot/addon, standard library only: - the types: Context, Watch, Result, Content, Op, Image, Page, Held, Capability and the keys; - a ready MCP 2025-06-18 stdio server for an addon written in Go: tools with visibility, the call context, cancellation, the outbox with its cursor, Queue, Outbox and Restore for saving, and the bot's network. The mcp feature uses the package's types (no behaviour change), and a new test runs the bot against an addon built from the package. The arch test lets features import addon and keeps addon to the standard library. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- CONTRIBUTING.md | 3 +- TECHNICAL.md | 3 +- addon/server.go | 572 ++++++++++++++++++++++++++ addon/server_test.go | 352 ++++++++++++++++ addon/types.go | 125 ++++++ docs/FILES_LINKS_TOOLS_MCP.md | 2 + internal/arch/arch_test.go | 13 +- internal/features/mcp/addon.go | 25 +- internal/features/mcp/addon_test.go | 15 +- internal/features/mcp/direct.go | 3 +- internal/features/mcp/interop_test.go | 85 ++++ internal/features/mcp/mcp.go | 17 +- internal/features/mcp/mcp_test.go | 3 +- internal/features/mcp/outbox.go | 42 +- internal/features/mcp/watch.go | 14 +- internal/features/mcp/watch_test.go | 29 +- 16 files changed, 1196 insertions(+), 107 deletions(-) create mode 100644 addon/server.go create mode 100644 addon/server_test.go create mode 100644 addon/types.go create mode 100644 internal/features/mcp/interop_test.go diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b4959c7..6bff809 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -15,6 +15,7 @@ internal/bot/ the decision, the prompt, the hooks; wires the core, and internal/feature/ the ports and shared types, command parsing, featuretest internal/features/* one package per feature internal/kit/* code with two or more users and no bot knowledge +addon/ signalbot's MCP addon extension, for the bot and any addon written in Go: its wire format and a ready stdio server; public, standard library only cmd/signalctl/ a small client for signal-cli's daemon socket, for one-off chores such as blocking; not part of the bot ``` @@ -54,7 +55,7 @@ Give a feature a tag only for a real saving, such as a dependency; a runtime set Tests in `internal/arch` enforce these: -- **Imports:** only the main package, at the module root, imports features and `internal/signal`; a feature imports only `internal/feature`, `internal/kit` and its own packages; `internal/signal` imports only `internal/feature`, kit, `internal/config` and `internal/bot` (network to core, never the reverse); `internal/config` and kit import no other internal package. +- **Imports:** only the main package, at the module root, imports features and `internal/signal`; a feature imports only `internal/feature`, `internal/kit` and its own packages; `internal/signal` imports only `internal/feature`, kit, `internal/config` and `internal/bot` (network to core, never the reverse); `internal/config` and kit import no other internal package; a feature may also import `addon`, and `addon` imports only the standard library, since every addon builds it. - **No feature names in the core:** the core's source mentions no feature name or feature-only word (chart, MCP, group context, `/intro`, `/schedule`, …). - **Docs:** every setting read, the core's or a feature's (`h.Env("NAME", …)`), is in the table in [docs/CONFIGURATION.md](docs/CONFIGURATION.md). diff --git a/TECHNICAL.md b/TECHNICAL.md index 08dc128..14e2cbd 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -89,6 +89,7 @@ internal/feature/ the ports and shared types (the only part of the core fe internal/features/* one package per feature internal/kit/* code with two or more users and no bot knowledge internal/arch/ the guardrail tests and the sizes report +addon/ signalbot's MCP addon extension, for the bot and any addon written in Go: its wire format and a ready stdio server; public, standard library only cmd/signalctl/ a small client for signal-cli's daemon socket, for one-off chores such as blocking; not part of the bot ``` @@ -236,7 +237,7 @@ In `features.go` order, which is the order hooks run in and of the tools line an - Config errors stop the bot, each starting with the file's path and naming the server: a key that is neither a setting nor one other clients write (`type`, `transport`, `timeout`, `alwaysAllow`, `autoApprove`, `description`, ignored), with the settings listed, in a server or a chat command; both `allowed_tools` and `blocked_tools`; a tool name the server lacks, with the list it is in and the server's tools (the first 20, then "…"); and two tools that become one name for the model, naming both. An addon server adds its own (below). - Tools are filtered by `_meta`: a tool whose `io.github.robdevops.signalbot/visibility` array, or MCP Apps' `ui.visibility`, leaves out `"model"` is never offered to the model, nor listed in `{tools}` or the tools line. A missing array means the model may see it. The bot calls a tool itself (an addon's direct command or watch) only if signalbot's array has `"bot"`; MCP Apps' `"app"` means a UI, not the bot. - **`img.Safe`** (`kit/img`) checks any image from a server before it is sent: only PNG, JPEG, GIF or WebP, read from the header alone, at most 8,192 pixels a side and 40 megapixels, so a small file claiming a huge canvas never reaches phones; a JPEG loses its EXIF (keeping its orientation), XMP, IPTC, comments and anything after the image, by walking its segments without decoding pixels, since signal-cli sends attachments as they are and GPS tags would say where a photo was taken. -- **Addons** are local MCP servers with an `addon` block in `MCP_CONFIG` that also advertise `io.github.robdevops.signalbot/addon` at version 1 in their `initialize` result's `capabilities.experimental`. The bot offers the same key in its `initialize` request with the chat network it is on, `{"version": 1, "network": "signal"}` (`Info.Network`, which each network names itself with `Network.Name`), so an addon can word its messages for that network. One with the block that doesn't advertise it runs as a plain server, with a warning. They are part of `mcp`: no port of the core names them. +- **Addons** are local MCP servers with an `addon` block (the extension's wire format, which the feature and every addon written in Go share, is the public package `addon`, in [Layout](#layout)) in `MCP_CONFIG` that also advertise `io.github.robdevops.signalbot/addon` at version 1 in their `initialize` result's `capabilities.experimental`. The bot offers the same key in its `initialize` request with the chat network it is on, `{"version": 1, "network": "signal"}` (`Info.Network`, which each network names itself with `Network.Name`), so an addon can word its messages for that network. One with the block that doesn't advertise it runs as a plain server, with a warning. They are part of `mcp`: no port of the core names them. - **Config:** the block's keys are `chats` (group IDs exactly as Signal or Telegram shows them, a Telegram topic counting as its group, or `["all"]` alone; anything else is an error asking for the group's ID), `dms`, `post`, `react`, `watch` (each off unless set), `watch_max` (1s to 24h, default 1h), `names`, `global_ids` and `rate` (`per_minute`, default 20, and `burst`, default 5). Unknown keys get the same error as a server's. An addon must be local (`command`), can't have an `env` block, and its server's name can't make a prefix (below) that one of the bot's own settings starts with (the names in `docs/CONFIGURATION.md`'s table, plus `STATE_DIRECTORY`, a list a test keeps in step); a `direct` chat command without an addon block is an error. Its error text and its start, initialize and call failures are logged by code only, never the server's words. - **Environment:** an addon gets `PATH`, `HOME`, those of `TZ`, `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` (and their lowercase forms), `SSL_CERT_FILE` and `SSL_CERT_DIR` that are set, so it keeps the bot's time zone and reaches the internet as the bot does, and every variable of the bot's environment that starts with its prefix: its server's name in capitals, anything but letters and digits as `_`, then `_` (`geo` gets `GEO_…`). Nothing else, so the bot's keys never reach it. These are read with `os.Environ`, not `Env`, so each addon documents its own. - **Stderr:** an addon's is never logged, since it may write what it was sent: only "addon <name> wrote N lines (M bytes) to stderr", at most once a minute, and once more when it exits for what was counted since, so a crash's output is never left uncounted. diff --git a/addon/server.go b/addon/server.go new file mode 100644 index 0000000..80b1ebd --- /dev/null +++ b/addon/server.go @@ -0,0 +1,572 @@ +package addon + +import ( + "bufio" + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "io" + "slices" + "strconv" + "strings" + "sync" + "time" +) + +// Tool is one of an addon's tools. +type Tool struct { + Name string + Description string + Schema json.RawMessage // its arguments' JSON Schema; nil is an object with no properties + // Visibility is who may call it: "bot" for the bot itself (a direct + // command, a watch), "model" for the model. Nil is the model alone. + Visibility []string + // Call runs it. c is nil for a call the model makes, which carries no + // chat. An error fails the call (DecodeArgs's as invalid params); a + // Result with IsError is a failure written for people. + Call func(ctx context.Context, c *Context, args json.RawMessage) (Result, error) +} + +// Config is what a Server is made from. +type Config struct { + Name, Title, Version string // serverInfo; Title is the name people see + Tools []Tool + Now func() time.Time // nil is time.Now; tests set it + // Changed, if set, is called when a read of the outbox lets go of ops + // the bot has read past, or ones held too long, so the addon can save + // Outbox(). It isn't called for Queue: Queue's caller knows to save. + Changed func() +} + +// Server is an addon's side of the protocol, on stdin and stdout: MCP's +// initialize, tools and resources, the extension's context and outbox, and +// cancellation. Make one with New. +type Server struct { + cfg Config + tools map[string]Tool + nonce string // this run's, in each outbox cursor and op ID + dirty chan struct{} // the outbox gained ops: tell the bot + + mu sync.Mutex + network string + subscribed bool + outbox []held // ops the bot hasn't read past, oldest first + seq int64 // the last op's sequence number +} + +// held is an op waiting in the outbox, with this run's sequence number, +// which cursors count in. +type held struct { + Held + seq int64 +} + +// The outbox's limits: how long an op unread is kept, and the most a page +// holds, well under the 4 MiB line the bot reads. +const ( + keepOps = time.Hour + pageSize = 3 << 20 +) + +// maxLine caps one incoming line. The bot's requests are small: a +// command's arguments or one chat message. +const maxLine = 1 << 20 + +// JSON-RPC's error codes, and MCP's for a resource that isn't there. +const ( + codeParse = -32700 + codeInvalidRequest = -32600 + codeNoMethod = -32601 + codeInvalidParams = -32602 + codeInternal = -32603 + codeNotFound = -32002 +) + +// New makes a Server for an addon with c's tools. +func New(c Config) *Server { + if c.Now == nil { + c.Now = time.Now + } + s := &Server{cfg: c, tools: map[string]Tool{}, nonce: randomID(4), dirty: make(chan struct{}, 1)} + for _, t := range c.Tools { + s.tools[t.Name] = t + } + return s +} + +// Network is the chat network the bot said it is on ("signal", +// "telegram"), or "" before initialize or if it said none. +func (s *Server) Network() string { + s.mu.Lock() + defer s.mu.Unlock() + return s.network +} + +// Queue adds ops to the outbox, giving each its ID, and tells a subscribed +// bot. The bot reads them when it can; save Outbox() afterwards to keep +// them over a restart. +func (s *Server) Queue(ops ...Op) { + if len(ops) == 0 { + return + } + s.mu.Lock() + now := s.cfg.Now() + for _, o := range ops { + s.seq++ + o.ID = s.nonce + "." + strconv.FormatInt(s.seq, 10) + s.outbox = append(s.outbox, held{Held: Held{Op: o, Queued: now}, seq: s.seq}) + } + s.mu.Unlock() + s.poke() +} + +// Outbox is what the bot hasn't read past yet, oldest first, to save. +func (s *Server) Outbox() []Held { + s.mu.Lock() + defer s.mu.Unlock() + out := make([]Held, len(s.outbox)) + for i, h := range s.outbox { + out[i] = h.Held + } + return out +} + +// Restore puts saved ops back in the outbox, before Run. They keep their +// IDs, so the bot, which remembers the IDs it applied, never applies one +// twice; a cursor from before the restart is this run's no longer, so the +// bot's next read gets them all. +func (s *Server) Restore(ops []Held) { + s.mu.Lock() + defer s.mu.Unlock() + for _, h := range ops { + s.seq++ + s.outbox = append(s.outbox, held{Held: h, seq: s.seq}) + } +} + +// Run serves the bot on in and out until in ends (the bot closed stdin: it +// returns nil) or ctx does. Each request is answered on its own goroutine, +// with a context the bot can cancel (notifications/cancelled), and Run +// waits for the answers in flight before it returns. +func (s *Server) Run(ctx context.Context, in io.Reader, out io.Writer) error { + w := &wire{w: out} + ctx, cancel := context.WithCancel(ctx) + defer cancel() + go s.notifier(ctx, w) + if len(s.Outbox()) > 0 { + s.poke() + } + var wg sync.WaitGroup + defer wg.Wait() + var mu sync.Mutex + inFlight := map[string]context.CancelFunc{} // by request ID + r := bufio.NewReaderSize(in, 64<<10) + for { + line, err := readLine(r) + if err != nil { + if errors.Is(err, io.EOF) { + return nil + } + return err + } + if line == nil { // too long, or blank + continue + } + var m message + if json.Unmarshal(line, &m) != nil { + w.send(response{JSONRPC: "2.0", ID: json.RawMessage("null"), Error: &rpcError{codeParse, "parse error"}}) + continue + } + if m.Method == "notifications/cancelled" { + var p struct { + RequestID json.RawMessage `json:"requestId"` + } + json.Unmarshal(m.Params, &p) + mu.Lock() + if stop := inFlight[string(p.RequestID)]; stop != nil { + stop() + } + mu.Unlock() + continue + } + if len(m.ID) == 0 || m.Method == "" { // a notification, or a response + continue + } + id := string(m.ID) + rctx, stop := context.WithCancel(ctx) + mu.Lock() + inFlight[id] = stop + mu.Unlock() + wg.Add(1) + go func() { + defer wg.Done() + w.send(s.answer(rctx, m)) + mu.Lock() + delete(inFlight, id) + mu.Unlock() + stop() + }() + } +} + +// DecodeArgs reads a tool's arguments into v; an error fails the call as +// invalid params. +func DecodeArgs(raw json.RawMessage, v any) error { return decode(raw, v) } + +// message is one JSON-RPC message read: a request, a notification (no ID) +// or a response to a request of the addon's (it sends none). +type message struct { + JSONRPC string `json:"jsonrpc"` + ID json.RawMessage `json:"id,omitempty"` + Method string `json:"method"` + Params json.RawMessage `json:"params,omitempty"` +} + +// response is the answer to one request: its result or an error. +type response struct { + JSONRPC string `json:"jsonrpc"` + ID json.RawMessage `json:"id"` + Result any `json:"result,omitempty"` + Error *rpcError `json:"error,omitempty"` +} + +// notification is a message to the bot that wants no answer. +type notification struct { + JSONRPC string `json:"jsonrpc"` + Method string `json:"method"` + Params any `json:"params,omitempty"` +} + +type rpcError struct { + Code int `json:"code"` + Message string `json:"message"` +} + +func (e *rpcError) Error() string { return e.Message } + +// wire writes whole messages to stdout, one per line, one at a time: it is +// the only writer of stdout, which carries nothing but the protocol. +type wire struct { + mu sync.Mutex + w io.Writer +} + +func (w *wire) send(v any) error { + data, err := json.Marshal(v) + if err != nil { + return err + } + w.mu.Lock() + defer w.mu.Unlock() + _, err = w.w.Write(append(data, '\n')) + return err +} + +// handler answers one request's params with a result, or an *rpcError. +type handler func(ctx context.Context, params json.RawMessage) (any, error) + +// answer runs one request's handler. +func (s *Server) answer(ctx context.Context, m message) response { + resp := response{JSONRPC: "2.0", ID: m.ID} + h, ok := s.methods()[m.Method] + switch { + case m.JSONRPC != "2.0": + resp.Error = &rpcError{codeInvalidRequest, "not JSON-RPC 2.0"} + case !ok: + resp.Error = &rpcError{codeNoMethod, "method not found"} + default: + result, err := h(ctx, m.Params) + var re *rpcError + switch { + case errors.As(err, &re): + resp.Error = re + case err != nil: + resp.Error = &rpcError{codeInternal, "internal error"} + default: + resp.Result = result + } + } + return resp +} + +// readLine reads one line without its end. A line longer than maxLine is +// skipped whole, and nil returned for it, as for a blank one. +func readLine(r *bufio.Reader) ([]byte, error) { + var line []byte + tooLong := false + for { + part, err := r.ReadSlice('\n') + if !tooLong { + line = append(line, part...) + if len(line) > maxLine { + line, tooLong = nil, true + } + } + switch { + case errors.Is(err, bufio.ErrBufferFull): + continue + case err != nil && (len(line) == 0 || !errors.Is(err, io.EOF)): + return nil, err + } + if tooLong { + return nil, nil + } + line = trimEOL(line) + if len(line) == 0 { + return nil, nil + } + return line, nil + } +} + +func trimEOL(b []byte) []byte { + for len(b) > 0 && (b[len(b)-1] == '\n' || b[len(b)-1] == '\r' || b[len(b)-1] == ' ') { + b = b[:len(b)-1] + } + return b +} + +// decode reads a request's params into v, or fails as JSON-RPC's invalid +// params. +func decode(raw json.RawMessage, v any) error { + if len(raw) == 0 { + raw = json.RawMessage("{}") + } + if json.Unmarshal(raw, v) != nil { + return &rpcError{codeInvalidParams, "invalid params"} + } + return nil +} + +// The MCP methods' results, as the server writes them. +type ( + initializeResult struct { + ProtocolVersion string `json:"protocolVersion"` + Capabilities capabilities `json:"capabilities"` + ServerInfo serverInfo `json:"serverInfo"` + } + capabilities struct { + Experimental map[string]Capability `json:"experimental"` + Tools struct{} `json:"tools"` + Resources struct { + Subscribe bool `json:"subscribe"` + } `json:"resources"` + } + serverInfo struct { + Name string `json:"name"` + Title string `json:"title,omitempty"` + Version string `json:"version"` + } + toolInfo struct { + Name string `json:"name"` + Description string `json:"description"` + InputSchema json.RawMessage `json:"inputSchema"` + Meta map[string]any `json:"_meta,omitempty"` + } + resourceTemplate struct { + URITemplate string `json:"uriTemplate"` + Name string `json:"name"` + MimeType string `json:"mimeType"` + } + resourceContent struct { + URI string `json:"uri"` + MimeType string `json:"mimeType"` + Text string `json:"text"` + } + uriParams struct { + URI string `json:"uri"` + } +) + +// callParams are tools/call's params, with the context the bot puts in +// _meta when it makes the call itself. +type callParams struct { + Name string `json:"name"` + Arguments json.RawMessage `json:"arguments"` + Meta struct { + Context *Context `json:"io.github.robdevops.signalbot/context"` + } `json:"_meta"` +} + +// methods are the MCP methods the server answers. +func (s *Server) methods() map[string]handler { + return map[string]handler{ + "initialize": func(_ context.Context, raw json.RawMessage) (any, error) { + var p struct { + Capabilities struct { + Experimental map[string]Capability `json:"experimental"` + } `json:"capabilities"` + } + json.Unmarshal(raw, &p) // optional: a bot that offers no network still gets an answer + s.mu.Lock() + s.network = p.Capabilities.Experimental[KeyAddon].Network + s.mu.Unlock() + r := initializeResult{ProtocolVersion: Protocol, ServerInfo: serverInfo{Name: s.cfg.Name, Title: s.cfg.Title, Version: s.cfg.Version}} + r.Capabilities.Experimental = map[string]Capability{KeyAddon: {Version: Version}} + r.Capabilities.Resources.Subscribe = true + return r, nil + }, + "ping": func(context.Context, json.RawMessage) (any, error) { return struct{}{}, nil }, + "tools/list": func(context.Context, json.RawMessage) (any, error) { + list := make([]toolInfo, 0, len(s.cfg.Tools)) + for _, t := range s.cfg.Tools { + schema := t.Schema + if schema == nil { + schema = json.RawMessage(`{"type":"object"}`) + } + info := toolInfo{Name: t.Name, Description: t.Description, InputSchema: schema} + if t.Visibility != nil { + info.Meta = map[string]any{KeyVisibility: t.Visibility} + } + list = append(list, info) + } + return struct { + Tools []toolInfo `json:"tools"` + }{list}, nil + }, + "tools/call": func(ctx context.Context, raw json.RawMessage) (any, error) { + var p callParams + if err := decode(raw, &p); err != nil { + return nil, err + } + t, ok := s.tools[p.Name] + if !ok || t.Call == nil { + return nil, &rpcError{codeInvalidParams, "unknown tool"} + } + return t.Call(ctx, p.Meta.Context, p.Arguments) + }, + "resources/list": func(context.Context, json.RawMessage) (any, error) { + return struct { + Resources []struct{} `json:"resources"` + }{[]struct{}{}}, nil + }, + "resources/templates/list": func(context.Context, json.RawMessage) (any, error) { + return struct { + Templates []resourceTemplate `json:"resourceTemplates"` + }{[]resourceTemplate{{URITemplate: OutboxURI + "/{cursor}", Name: "outbox", MimeType: "application/json"}}}, nil + }, + "resources/subscribe": func(_ context.Context, raw json.RawMessage) (any, error) { return s.subscribe(raw, true) }, + "resources/unsubscribe": func(_ context.Context, raw json.RawMessage) (any, error) { return s.subscribe(raw, false) }, + "resources/read": func(_ context.Context, raw json.RawMessage) (any, error) { + var p uriParams + if err := decode(raw, &p); err != nil { + return nil, err + } + cursor, ok := strings.CutPrefix(p.URI, OutboxURI+"/") + if !ok { + return nil, &rpcError{codeNotFound, "resource not found"} + } + page, err := json.Marshal(s.read(cursor)) + if err != nil { + return nil, err + } + return struct { + Contents []resourceContent `json:"contents"` + }{[]resourceContent{{URI: p.URI, MimeType: "application/json", Text: string(page)}}}, nil + }, + } +} + +// subscribe records whether the bot wants to hear of the outbox. +func (s *Server) subscribe(raw json.RawMessage, on bool) (any, error) { + var p uriParams + if err := decode(raw, &p); err != nil { + return nil, err + } + if !strings.HasPrefix(p.URI, OutboxURI) { + return nil, &rpcError{codeNotFound, "resource not found"} + } + s.mu.Lock() + s.subscribed = on + pending := len(s.outbox) > 0 + s.mu.Unlock() + if on && pending { + s.poke() + } + return struct{}{}, nil +} + +// read is the outbox's page after cursor. A cursor of this run lets go of +// the ops up to it, which the bot has read; any other, such as one from +// before a restart, gets everything still held. +func (s *Server) read(cursor string) Page { + s.mu.Lock() + after, known := s.cursor(cursor) + now := s.cfg.Now() + n := len(s.outbox) + s.outbox = slices.DeleteFunc(s.outbox, func(h held) bool { + return known && h.seq <= after || now.Sub(h.Queued) > keepOps + }) + changed := len(s.outbox) != n + last := s.seq + if known { + last = after + } + page := Page{Ops: []Op{}} + size := 0 + for _, h := range s.outbox { + data, _ := json.Marshal(h.Op) + if len(page.Ops) > 0 && size+len(data) > pageSize { + page.More = true + break + } + size += len(data) + page.Ops = append(page.Ops, h.Op) + last = h.seq + } + page.Cursor = s.nonce + "." + strconv.FormatInt(last, 10) + s.mu.Unlock() + if changed && s.cfg.Changed != nil { + s.cfg.Changed() + } + return page +} + +// cursor reads a cursor of this run: the sequence number read up to. +// s.mu is held. +func (s *Server) cursor(c string) (int64, bool) { + nonce, seq, ok := strings.Cut(c, ".") + if !ok || nonce != s.nonce { + return 0, false + } + n, err := strconv.ParseInt(seq, 10, 64) + if err != nil || n < 0 || n > s.seq { + return 0, false + } + return n, true +} + +// notifier tells a subscribed bot each time the outbox gains ops, on its +// own goroutine, as a write can wait on a bot that is busy. +func (s *Server) notifier(ctx context.Context, w *wire) { + for { + select { + case <-ctx.Done(): + return + case <-s.dirty: + } + s.mu.Lock() + on := s.subscribed + s.mu.Unlock() + if on { + w.send(notification{JSONRPC: "2.0", Method: "notifications/resources/updated", Params: uriParams{OutboxURI}}) + } + } +} + +// poke marks the outbox changed, without waiting. +func (s *Server) poke() { + select { + case s.dirty <- struct{}{}: + default: + } +} + +// randomID is n random bytes in hex. +func randomID(n int) string { + b := make([]byte, n) + rand.Read(b) + return hex.EncodeToString(b) +} diff --git a/addon/server_test.go b/addon/server_test.go new file mode 100644 index 0000000..3ddd727 --- /dev/null +++ b/addon/server_test.go @@ -0,0 +1,352 @@ +package addon + +import ( + "bufio" + "context" + "encoding/json" + "io" + "strconv" + "strings" + "sync" + "testing" + "time" +) + +// client plays the bot: it writes requests to a Server's stdin and reads +// what the Server writes to stdout, which must be JSON-RPC lines alone. +type client struct { + t *testing.T + in *io.PipeWriter + lines chan json.RawMessage // every line the server wrote + nextID int + done chan error // Run's result +} + +func start(t *testing.T, s *Server) *client { + t.Helper() + inR, inW := io.Pipe() + outR, outW := io.Pipe() + c := &client{t: t, in: inW, lines: make(chan json.RawMessage, 64), done: make(chan error, 1)} + go func() { c.done <- s.Run(context.Background(), inR, outW); outW.Close() }() + go func() { + sc := bufio.NewScanner(outR) + sc.Buffer(nil, 4<<20) + for sc.Scan() { + line := json.RawMessage(append([]byte(nil), sc.Bytes()...)) + if !json.Valid(line) { + t.Errorf("stdout carried something not JSON: %q", line) + } + c.lines <- line + } + close(c.lines) + }() + t.Cleanup(func() { + inW.Close() + select { + case err := <-c.done: + if err != nil { + t.Errorf("Run: %v", err) + } + case <-time.After(5 * time.Second): + t.Error("Run didn't return when stdin closed") + } + }) + return c +} + +func (c *client) send(v any) { + c.t.Helper() + data, _ := json.Marshal(v) + if _, err := c.in.Write(append(data, '\n')); err != nil { + c.t.Fatal(err) + } +} + +// request sends a request and returns its ID. +func (c *client) request(method string, params any) int { + c.nextID++ + c.send(map[string]any{"jsonrpc": "2.0", "id": c.nextID, "method": method, "params": params}) + return c.nextID +} + +// reply is the next message for id, skipping notifications, which it +// returns too. +func (c *client) reply(id int) (resp struct { + Result json.RawMessage + Error *rpcError +}, notes []string) { + c.t.Helper() + timeout := time.After(5 * time.Second) + for { + select { + case line, ok := <-c.lines: + if !ok { + c.t.Fatal("stdout closed") + } + var m struct { + ID *int + Method string + Result json.RawMessage + Error *rpcError + } + json.Unmarshal(line, &m) + if m.ID == nil { + notes = append(notes, m.Method) + continue + } + if *m.ID != id { + c.t.Fatalf("reply to %d while waiting for %d", *m.ID, id) + } + resp.Result, resp.Error = m.Result, m.Error + return resp, notes + case <-timeout: + c.t.Fatalf("no reply to %d", id) + } + } +} + +// result asks and decodes the result into v. +func (c *client) result(method string, params, v any) { + c.t.Helper() + resp, _ := c.reply(c.request(method, params)) + if resp.Error != nil { + c.t.Fatalf("%s: %v", method, resp.Error.Message) + } + if v != nil { + if err := json.Unmarshal(resp.Result, v); err != nil { + c.t.Fatalf("%s: %v", method, err) + } + } +} + +// note waits for a notification. +func (c *client) note(method string) { + c.t.Helper() + timeout := time.After(5 * time.Second) + for { + select { + case line := <-c.lines: + var m struct{ Method string } + json.Unmarshal(line, &m) + if m.Method == method { + return + } + case <-timeout: + c.t.Fatalf("no %s", method) + } + } +} + +func initialize(c *client, network string) map[string]any { + var r map[string]any + c.result("initialize", map[string]any{ + "protocolVersion": Protocol, + "capabilities": map[string]any{"experimental": map[string]any{KeyAddon: Capability{Version: Version, Network: network}}}, + }, &r) + return r +} + +func echoTool() Tool { + return Tool{ + Name: "echo", Description: "says it back", Visibility: []string{"bot"}, + Schema: json.RawMessage(`{"type":"object","properties":{"text":{"type":"string"}}}`), + Call: func(_ context.Context, c *Context, raw json.RawMessage) (Result, error) { + var a struct{ Text string } + if err := DecodeArgs(raw, &a); err != nil { + return Result{}, err + } + who := "the model" + if c != nil { + who = c.Sender + " in " + c.Chat + } + return Result{Content: []Content{{Type: "text", Text: a.Text + " from " + who}}, Meta: &ResultMeta{React: "👍"}}, nil + }, + } +} + +func TestInitializeAndTools(t *testing.T) { + s := New(Config{Name: "game", Title: "Game", Version: "1", Tools: []Tool{echoTool(), {Name: "both", Visibility: []string{"model", "bot"}}, {Name: "plain"}}}) + c := start(t, s) + r := initialize(c, "signal") + caps, _ := json.Marshal(r["capabilities"]) + if r["protocolVersion"] != Protocol || !strings.Contains(string(caps), `"`+KeyAddon+`":{"version":1}`) || !strings.Contains(string(caps), `"subscribe":true`) { + t.Fatalf("initialize %v", r) + } + if info, _ := json.Marshal(r["serverInfo"]); string(info) != `{"name":"game","title":"Game","version":"1"}` { + t.Errorf("serverInfo %s", info) + } + if s.Network() != "signal" { + t.Errorf("network %q", s.Network()) + } + var list struct { + Tools []struct { + Name string + InputSchema json.RawMessage + Meta map[string][]string `json:"_meta"` + } + } + c.result("tools/list", struct{}{}, &list) + if len(list.Tools) != 3 { + t.Fatalf("tools %+v", list.Tools) + } + if got := list.Tools[0].Meta[KeyVisibility]; len(got) != 1 || got[0] != "bot" || !strings.Contains(string(list.Tools[0].InputSchema), `"text"`) { + t.Errorf("echo %+v", list.Tools[0]) + } + if list.Tools[2].Meta != nil || string(list.Tools[2].InputSchema) != `{"type":"object"}` { + t.Errorf("plain %+v", list.Tools[2]) + } + c.result("ping", struct{}{}, nil) + resp, _ := c.reply(c.request("nope", struct{}{})) + if resp.Error == nil || resp.Error.Code != codeNoMethod { + t.Errorf("unknown method %+v", resp) + } +} + +func TestCall(t *testing.T) { + c := start(t, New(Config{Name: "game", Tools: []Tool{echoTool()}})) + initialize(c, "") + var r Result + c.result("tools/call", map[string]any{"name": "echo", "arguments": map[string]string{"text": "hi"}, + "_meta": map[string]any{KeyContext: Context{Chat: "c_one", Sender: "u_alice", Addressed: true, Group: true, Sent: 100}}}, &r) + if len(r.Content) != 1 || r.Content[0].Text != "hi from u_alice in c_one" || r.Meta == nil || r.Meta.React != "👍" { + t.Errorf("with context %+v", r) + } + c.result("tools/call", map[string]any{"name": "echo", "arguments": map[string]string{"text": "hi"}}, &r) + if r.Content[0].Text != "hi from the model" { + t.Errorf("without context %+v", r) + } + for name, params := range map[string]any{ + "unknown tool": map[string]any{"name": "nope"}, + "bad args": map[string]any{"name": "echo", "arguments": "not an object"}, + } { + resp, _ := c.reply(c.request("tools/call", params)) + if resp.Error == nil || resp.Error.Code != codeInvalidParams { + t.Errorf("%s: %+v", name, resp) + } + } +} + +// A call the bot gives up on is cancelled: its context ends. +func TestCancel(t *testing.T) { + ended := make(chan error, 1) + slow := Tool{Name: "slow", Call: func(ctx context.Context, _ *Context, _ json.RawMessage) (Result, error) { + <-ctx.Done() + ended <- ctx.Err() + return Text("too late"), nil + }} + c := start(t, New(Config{Name: "game", Tools: []Tool{slow}})) + id := c.request("tools/call", map[string]any{"name": "slow"}) + c.send(map[string]any{"jsonrpc": "2.0", "method": "notifications/cancelled", "params": map[string]any{"requestId": id}}) + select { + case err := <-ended: + if err != context.Canceled { + t.Errorf("ended with %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("the call wasn't cancelled") + } + c.reply(id) +} + +// The outbox: a subscribed bot hears of new ops, a read gets them with a +// cursor, a read at that cursor lets go of them, and a cursor the server +// doesn't know gets everything still held. +func TestOutbox(t *testing.T) { + now := time.Date(2026, 11, 21, 9, 0, 0, 0, time.UTC) + var mu sync.Mutex + changes := 0 + s := New(Config{Name: "game", Now: func() time.Time { return now }, Changed: func() { mu.Lock(); changes++; mu.Unlock() }}) + c := start(t, s) + initialize(c, "") + c.result("resources/subscribe", uriParams{OutboxURI}, nil) + s.Queue(Op{Op: "post", Chat: "c_one", Text: "{u_alice} wins"}, Op{Op: "unwatch", Chat: "c_one", Watch: "r1"}) + c.note("notifications/resources/updated") + + read := func(cursor string) Page { + var r struct { + Contents []resourceContent + } + c.result("resources/read", uriParams{OutboxURI + "/" + cursor}, &r) + var p Page + if len(r.Contents) != 1 || json.Unmarshal([]byte(r.Contents[0].Text), &p) != nil { + t.Fatalf("read %+v", r) + } + return p + } + p := read("0") + if len(p.Ops) != 2 || p.Ops[0].Text != "{u_alice} wins" || p.Ops[1].Watch != "r1" || p.More || !strings.HasSuffix(p.Ops[1].ID, ".2") { + t.Fatalf("first page %+v", p) + } + if len(s.Outbox()) != 2 { + t.Fatal("ops let go of before the bot read past them") + } + if p2 := read(p.Cursor); len(p2.Ops) != 0 || p2.Cursor != p.Cursor || len(s.Outbox()) != 0 { + t.Fatalf("after the cursor %+v, outbox %v", p2, s.Outbox()) + } + mu.Lock() + if changes != 1 { + t.Errorf("Changed called %d times", changes) + } + mu.Unlock() + + s.Queue(Op{Op: "post", Chat: "c_one", Text: "again"}) + if p := read("other.5"); len(p.Ops) != 1 || p.Ops[0].Text != "again" { + t.Errorf("an unknown cursor %+v", p) + } + resp, _ := c.reply(c.request("resources/read", uriParams{"signalbot://elsewhere"})) + if resp.Error == nil || resp.Error.Code != codeNotFound { + t.Errorf("another resource %+v", resp) + } +} + +// Ops saved before a restart come back with their IDs, and a new run's +// first read, whatever its cursor, gets them; ones held past keepOps go. +func TestRestore(t *testing.T) { + now := time.Date(2026, 11, 21, 9, 0, 0, 0, time.UTC) + s := New(Config{Name: "game", Now: func() time.Time { return now }}) + s.Restore([]Held{ + {Op: Op{ID: "old.7", Op: "post", Chat: "c_one", Text: "results"}, Queued: now.Add(-time.Minute)}, + {Op: Op{ID: "old.8", Op: "post", Chat: "c_one", Text: "stale"}, Queued: now.Add(-2 * time.Hour)}, + }) + c := start(t, s) + initialize(c, "") + var r struct{ Contents []resourceContent } + c.result("resources/read", uriParams{OutboxURI + "/old.8"}, &r) + var p Page + json.Unmarshal([]byte(r.Contents[0].Text), &p) + if len(p.Ops) != 1 || p.Ops[0].ID != "old.7" { + t.Errorf("after a restart %+v", p) + } + if strings.HasPrefix(p.Cursor, "old.") { + t.Errorf("cursor %q is the old run's", p.Cursor) + } +} + +// A long page is split, at least one op a page. +func TestOutboxPages(t *testing.T) { + s := New(Config{Name: "game"}) + big := strings.Repeat("x", pageSize/2) + for i := range 3 { + s.Queue(Op{Op: "post", Chat: "c_one", Text: big + strconv.Itoa(i)}) + } + c := start(t, s) + initialize(c, "") + var r struct{ Contents []resourceContent } + c.result("resources/read", uriParams{OutboxURI + "/0"}, &r) + var p Page + json.Unmarshal([]byte(r.Contents[0].Text), &p) + if len(p.Ops) != 1 || !p.More { + t.Errorf("%d ops, more %v", len(p.Ops), p.More) + } +} + +// Garbage on stdin gets a parse error, and Run carries on. +func TestBadLine(t *testing.T) { + c := start(t, New(Config{Name: "game"})) + c.in.Write([]byte("not json\n")) + line := <-c.lines + if !strings.Contains(string(line), `"code":-32700`) { + t.Errorf("got %s", line) + } + c.result("ping", struct{}{}, nil) +} diff --git a/addon/types.go b/addon/types.go new file mode 100644 index 0000000..53fb19c --- /dev/null +++ b/addon/types.go @@ -0,0 +1,125 @@ +// Package addon is signalbot's addon extension of MCP 2025-06-18: the wire +// format the bot and an addon share, and a ready stdio server for an addon +// written in Go. An addon is a local MCP server the bot runs as a child +// process (see docs/FILES_LINKS_TOOLS_MCP.md#addons): it answers its own +// commands without the model, reads the chat messages its watches match, +// and posts and reacts when it likes through its outbox. +// +// The bot's mcp feature and an addon both use these types, so the +// protocol is defined once. An addon in another language implements the +// same JSON. The package uses only the standard library. +package addon + +import "time" + +// The protocol: the MCP version, the prefix of every key of the extension, +// the extension's version, and the outbox's URI. +const ( + Protocol = "2025-06-18" + Vendor = "io.github.robdevops.signalbot/" + Version = 1 + OutboxURI = "signalbot://outbox" +) + +// The extension's keys: the capability both sides offer in initialize, and +// the _meta keys on a call (the context), a tool (who may call it) and a +// result (a watch to start, a reaction to put on the message). +const ( + KeyAddon = Vendor + "addon" + KeyContext = Vendor + "context" + KeyVisibility = Vendor + "visibility" + KeyWatch = Vendor + "watch" + KeyReact = Vendor + "react" +) + +// Capability is the extension's entry in capabilities.experimental under +// KeyAddon. The bot offers its chat network; an addon answers with the +// version alone. +type Capability struct { + Version int `json:"version"` + Network string `json:"network,omitempty"` // the bot's chat network, as it names itself: "signal", "telegram" +} + +// Context is the message a call the bot makes came from, in the call's +// _meta under KeyContext: pseudonyms for its chat and sender, a handle for +// it, and the bot's receive times in whole seconds, never the sender's +// clock. +type Context struct { + Chat string `json:"chat"` // c_…, the chat's pseudonym + Sender string `json:"sender"` // u_…, the sender's, in that chat unless global_ids + Ref string `json:"ref"` // r_…, the message, for a react op + Addressed bool `json:"addressed"` + Group bool `json:"group"` + Sent int64 `json:"sent"` // when the bot got it, in Unix seconds + Edited int64 `json:"edited"` // when the bot got the edit; 0 for an original + Name string `json:"name,omitempty"` // the sender's display name, with the names permission + Deadline int64 `json:"deadline,omitempty"` // a direct call's: when the bot stops waiting, in Unix seconds +} + +// Watch is what a direct command's result asks for, in its _meta under +// KeyWatch: the messages matching Pattern in the command's chat, until +// Until, go to Tool instead of the model. +type Watch struct { + ID string `json:"id"` + Pattern string `json:"pattern"` // RE2 + Until string `json:"until"` // RFC 3339 + Tool string `json:"tool"` // called with each message it matches, as {"text": …} + Guard string `json:"guard,omitempty"` // the answer, while it lasts, to a message addressed to the bot that quotes the command's pictures +} + +// Content is one block of a tool's result: text, or an image. +type Content struct { + Type string `json:"type"` // "text" or "image" + Text string `json:"text,omitempty"` + Data string `json:"data,omitempty"` // an image's bytes, in base64 + MimeType string `json:"mimeType,omitempty"` +} + +// Result is a tool's result. +type Result struct { + Content []Content `json:"content"` + IsError bool `json:"isError,omitempty"` + Meta *ResultMeta `json:"_meta,omitempty"` +} + +// ResultMeta is what a result asks of the bot besides its content. +type ResultMeta struct { + Watch *Watch `json:"io.github.robdevops.signalbot/watch,omitempty"` // a direct command's only + React string `json:"io.github.robdevops.signalbot/react,omitempty"` // an emoji for the message the call came from +} + +// Text is a result of words alone. +func Text(s string) Result { return Result{Content: []Content{{Type: "text", Text: s}}} } + +// Op is one thing an addon's outbox asks the bot to do. +type Op struct { + ID string `json:"id"` + Op string `json:"op"` // "post", "react" or "unwatch" + Chat string `json:"chat,omitempty"` // a post's or unwatch's chat pseudonym + Text string `json:"text,omitempty"` // a post's, with {u_…} placeholders the bot fills in with names + Images []Image `json:"images,omitempty"` // a post's: at most 2, 2 MB in all + Ref string `json:"ref,omitempty"` // a reaction's message + Emoji string `json:"emoji,omitempty"` // a reaction's + Watch string `json:"watch,omitempty"` // the ID of the watch an unwatch ends +} + +// Image is an image in a post. +type Image struct { + Data string `json:"data"` // base64 + MimeType string `json:"mimeType"` + Name string `json:"name,omitempty"` +} + +// Page is what reading the outbox at OutboxURI + "/" + cursor returns. +type Page struct { + Cursor string `json:"cursor"` + More bool `json:"more"` + Ops []Op `json:"ops"` +} + +// Held is an op the bot hasn't read past yet, as an addon saves it to post +// it after a restart (Server.Outbox, Server.Restore). +type Held struct { + Op Op `json:"op"` + Queued time.Time `json:"queued"` +} diff --git a/docs/FILES_LINKS_TOOLS_MCP.md b/docs/FILES_LINKS_TOOLS_MCP.md index dfd2145..c8cc1e6 100644 --- a/docs/FILES_LINKS_TOOLS_MCP.md +++ b/docs/FILES_LINKS_TOOLS_MCP.md @@ -100,6 +100,8 @@ A server that can't be reached at startup is logged and left out. A config error An addon is a local MCP server that does more than offer tools: it answers its own commands without the model, reads the messages it asks for, and posts and reacts when it likes. [GeoGuess](https://github.com/robdevops/chat-plugin-geoguess), a photo-guessing game, is one. It is still an ordinary MCP server (protocol 2025-06-18 over stdio), which also speaks signalbot's small extension, under keys starting `io.github.robdevops.signalbot/`. A server is an addon when it has an `addon` block in the MCP file and says it speaks the extension when the bot connects; one with the block that doesn't runs as a plain server, with a warning. Addons run even with [no model](MODELS.md#no-model). +An addon written in Go can use the package [`github.com/robdevops/signalbot/addon`](../addon), which has the extension's types and a ready stdio server: give it the tools, and queue posts, reactions and the end of a watch with `Queue`; GeoGuess is built on it. An addon in another language speaks the same JSON, described below. + **An addon is trusted code.** It runs as the bot's user, inside the same systemd or Docker sandbox, and could read what that user can. The bot gives it as little as it can (below), but that guards against bugs and leaks, not a hostile program: install only addons you would let run as the bot. ```jsonc diff --git a/internal/arch/arch_test.go b/internal/arch/arch_test.go index 75c1bfd..de2fd82 100644 --- a/internal/arch/arch_test.go +++ b/internal/arch/arch_test.go @@ -43,7 +43,9 @@ func under(p, dir string) bool { return p == dir || strings.HasPrefix(p, dir+"/" // its own packages and kit; internal/signal imports only those, // internal/config and internal/bot (for Received: the network depends on // the core, never the reverse); internal/config and kit import no other -// internal package. +// internal package. addon, the public package of signalbot's MCP addon +// extension that the bot and every addon written in Go share, imports +// nothing of the bot's; a feature may import it, as it may import kit. func TestImports(t *testing.T) { for _, p := range goFiles(t) { f, err := parser.ParseFile(token.NewFileSet(), root+"/"+p, nil, parser.ImportsOnly) @@ -57,6 +59,11 @@ func TestImports(t *testing.T) { } for _, spec := range f.Imports { imp, _ := strconv.Unquote(spec.Path.Value) + // addon is built into every addon, so it needs nothing beyond the + // standard library, whose paths have no dot in their first part. + if under(dir, "addon") && !strings.HasPrefix(imp, module) && strings.Contains(strings.Split(imp, "/")[0], ".") { + t.Errorf("%s imports %s, outside the standard library", p, imp) + } if !strings.HasPrefix(imp, module) { continue } @@ -64,7 +71,9 @@ func TestImports(t *testing.T) { var ok bool switch { case under(dir, "internal/features"): - ok = under(imp, "internal/feature") || under(imp, "internal/kit") || under(imp, own) + ok = under(imp, "internal/feature") || under(imp, "internal/kit") || under(imp, own) || under(imp, "addon") + case under(dir, "addon"): + ok = under(imp, "addon") case under(dir, "internal/feature"): ok = under(imp, "internal/feature") || under(imp, "internal/kit") case under(dir, "internal/signal"), under(dir, "internal/telegram"): diff --git a/internal/features/mcp/addon.go b/internal/features/mcp/addon.go index 4df2f4d..53a3e14 100644 --- a/internal/features/mcp/addon.go +++ b/internal/features/mcp/addon.go @@ -17,17 +17,11 @@ import ( "sync" "time" + ext "github.com/robdevops/signalbot/addon" "github.com/robdevops/signalbot/internal/feature" "github.com/robdevops/signalbot/internal/kit/txt" ) -// vendor prefixes the keys of signalbot's MCP extension: the capability, -// tool visibility and the context of the bot's own calls. -const vendor = "io.github.robdevops.signalbot/" - -// addonVersion is the version of the extension the bot speaks. -const addonVersion = 1 - // addonConfig is a server's "addon" block: what an addon may do, and where. type addonConfig struct { Chats []string `json:"chats"` // group IDs, or "all" @@ -294,23 +288,10 @@ func (a *addon) userID(chat feature.Chat, sender string) string { return a.pseudonym("u_", "user\x00"+chat.Key()+"\x00"+sender) } -// callContext is the context of a call the bot starts, in its _meta. -type callContext struct { - Chat string `json:"chat"` - Sender string `json:"sender"` - Ref string `json:"ref"` - Addressed bool `json:"addressed"` - Group bool `json:"group"` - Sent int64 `json:"sent"` // when the bot got it, in Unix seconds - Edited int64 `json:"edited"` // when the bot got the edit; 0 for an original - Name string `json:"name,omitempty"` - Deadline int64 `json:"deadline,omitempty"` // a direct call's: when the bot stops waiting, in Unix seconds -} - // context is m's context for the addon, which the bot got at at. It keeps // the sender's name, for placeholders, and a ref for m. sent and edited are // when the bot got it, never the sender's clock. -func (a *addon) context(m feature.Message, at time.Time) callContext { +func (a *addon) context(m feature.Message, at time.Time) ext.Context { now := a.now() user := a.userID(m.Chat, m.Sender) r := make([]byte, 16) @@ -332,7 +313,7 @@ func (a *addon) context(m feature.Message, at time.Time) callContext { a.names[m.Chat.Key()+"\x00"+user] = seen{m.Name, now.Add(nameLife)} } a.mu.Unlock() - c := callContext{Chat: a.chatID(m.Chat), Sender: user, Ref: id, Addressed: m.Addressed, Group: m.Chat.GroupID != "", Sent: at.Unix()} + c := ext.Context{Chat: a.chatID(m.Chat), Sender: user, Ref: id, Addressed: m.Addressed, Group: m.Chat.GroupID != "", Sent: at.Unix()} if m.Edited != 0 { c.Edited = c.Sent } diff --git a/internal/features/mcp/addon_test.go b/internal/features/mcp/addon_test.go index 10a0878..fe78634 100644 --- a/internal/features/mcp/addon_test.go +++ b/internal/features/mcp/addon_test.go @@ -25,6 +25,7 @@ import ( "testing" "time" + ext "github.com/robdevops/signalbot/addon" "github.com/robdevops/signalbot/internal/feature" "github.com/robdevops/signalbot/internal/feature/featuretest" "github.com/robdevops/signalbot/internal/kit/logx" @@ -121,7 +122,7 @@ func TestAddonProcess(t *testing.T) { switch req.Method { case "initialize": caps := `{"tools":{}}` - if mode == "addon" && p.Caps.Experimental[vendor+"addon"].Version == 1 { // only if offered + if mode == "addon" && p.Caps.Experimental[ext.KeyAddon].Version == 1 { // only if offered caps = `{"tools":{},"resources":{"subscribe":true},"experimental":{"io.github.robdevops.signalbot/addon":{"version":1}}}` } reply(id, `"result":{"protocolVersion":"`+protocol+`","capabilities":`+caps+`,"serverInfo":{"name":"game","title":"Game","version":"1"}}`) @@ -139,9 +140,9 @@ func TestAddonProcess(t *testing.T) { go func() { switch p.Name { case "play": - var meta map[string]callContext + var meta map[string]ext.Context json.Unmarshal(p.Meta, &meta) - reply(id, text("you said "+p.Arguments["args"]+"\n{"+meta[vendor+"context"].Sender+"} plays")) + reply(id, text("you said "+p.Arguments["args"]+"\n{"+meta[ext.KeyContext].Sender+"} plays")) case "context": reply(id, text(string(p.Meta))) case "pics": @@ -362,11 +363,11 @@ func TestDirect(t *testing.T) { } } got := h.Message(ctx, in(inA, "/ctx")) - var meta map[string]callContext + var meta map[string]ext.Context if err := json.Unmarshal([]byte(got.Answer), &meta); err != nil { t.Fatalf("ctx %q: %v", got.Answer, err) } - c := meta[vendor+"context"] + c := meta[ext.KeyContext] id := regexp.MustCompile(`^[cur]_[a-z2-7]{26}$`) if !id.MatchString(c.Chat) || !id.MatchString(c.Sender) || !id.MatchString(c.Ref) || c.Chat[0] != 'c' || c.Sender[0] != 'u' || c.Ref[0] != 'r' || !c.Addressed || !c.Group || c.Edited != 0 || c.Name != "" || time.Since(time.Unix(c.Sent, 0)) > time.Minute || @@ -524,9 +525,9 @@ func TestPseudonyms(t *testing.T) { t.Fatal(err) } defer h.Stop() - var meta map[string]callContext + var meta map[string]ext.Context json.Unmarshal([]byte(h.Message(context.Background(), in(inDM, "/ctx")).Answer), &meta) - return meta[vendor+"context"].Chat + return meta[ext.KeyContext].Chat } first := chatIDs() if first == "" || chatIDs() != first { diff --git a/internal/features/mcp/direct.go b/internal/features/mcp/direct.go index 1bc740c..5d963ac 100644 --- a/internal/features/mcp/direct.go +++ b/internal/features/mcp/direct.go @@ -10,6 +10,7 @@ import ( "strings" "time" + ext "github.com/robdevops/signalbot/addon" "github.com/robdevops/signalbot/internal/feature" "github.com/robdevops/signalbot/internal/kit/img" "github.com/robdevops/signalbot/internal/kit/logx" @@ -65,7 +66,7 @@ func (a *addon) direct(ctx context.Context, m feature.Message, name string, c ch res, err := a.conn.call(ctx, "tools/call", map[string]any{ "name": c.Tool, "arguments": map[string]string{"args": args}, - "_meta": map[string]any{vendor + "context": cc}, + "_meta": map[string]any{ext.KeyContext: cc}, }) var r toolResult outcome := "ok" diff --git a/internal/features/mcp/interop_test.go b/internal/features/mcp/interop_test.go new file mode 100644 index 0000000..b9bf992 --- /dev/null +++ b/internal/features/mcp/interop_test.go @@ -0,0 +1,85 @@ +package mcp + +import ( + "context" + "encoding/json" + "flag" + "os" + "strings" + "testing" + "time" + + ext "github.com/robdevops/signalbot/addon" + "github.com/robdevops/signalbot/internal/feature/featuretest" +) + +// TestPackageAddonProcess is not a real test: run as a subprocess with the +// argument "pkg", it is an addon built from the addon package, as an addon +// written in Go would be. /start answers, watches the chat for "guess N" +// and queues a post; the watch's tool reacts to each guess. +func TestPackageAddonProcess(t *testing.T) { + if flag.Arg(0) != "pkg" { + return + } + var s *ext.Server + s = ext.New(ext.Config{Name: "game", Title: "Game", Version: "1", Tools: []ext.Tool{ + { + Name: "start", Visibility: []string{"bot"}, + Call: func(_ context.Context, c *ext.Context, _ json.RawMessage) (ext.Result, error) { + if c == nil { + return ext.Text("no chat"), nil + } + s.Queue(ext.Op{Op: "post", Chat: c.Chat, Text: "{" + c.Sender + "} started a round on " + s.Network()}) + r := ext.Text("started") + r.Meta = &ext.ResultMeta{Watch: &ext.Watch{ID: "r1", Pattern: `\bguess \d+`, Until: time.Now().Add(time.Hour).Format(time.RFC3339), Tool: "guess"}} + return r, nil + }, + }, + { + Name: "guess", Visibility: []string{"bot"}, + Schema: json.RawMessage(`{"type":"object","properties":{"text":{"type":"string"}}}`), + Call: func(_ context.Context, _ *ext.Context, raw json.RawMessage) (ext.Result, error) { + var a struct{ Text string } + if err := ext.DecodeArgs(raw, &a); err != nil { + return ext.Result{}, err + } + return ext.Result{Content: []ext.Content{{Type: "text", Text: "got " + a.Text}}, Meta: &ext.ResultMeta{React: "🎯"}}, nil + }, + }, + }}) + if err := s.Run(context.Background(), os.Stdin, os.Stdout); err != nil { + os.Exit(1) + } + os.Exit(0) +} + +// The bot's side and the addon package, against each other: the handshake +// makes it an addon, a direct command answers and starts a watch, a +// matching message goes to the watch's tool and gets its reaction, and the +// post it queued reaches the chat with the placeholder filled in. +func TestPackageAddon(t *testing.T) { + h, log := startAddon(t, `{"mcpServers":{"game":`+strings.Replace(addonServer("pkg", `{"chats":["`+groupA+`"],"post":true,"react":true,"watch":true}`, + `,"chat_commands":{"start":{"tool":"start","direct":true}}`), "TestAddonProcess", "TestPackageAddonProcess", 1)+`}}`, + func(h *featuretest.Host) { h.Bot.Network = "signal" }) + if !strings.Contains(log.String(), "<5>game MCP: an addon, with tools for the bot: guess, start\n") { + t.Fatalf("log %q", log.String()) + } + ctx := context.Background() + if got := h.Message(ctx, in(inA, "/start")); got.Answer != "started" { + t.Fatalf("/start: %+v", got) + } + eventually(t, "the post", func() bool { return len(h.Posts()) == 1 }) + if p := h.Posts()[0]; p.Chat != inA || p.Text != "@Alice started a round on signal" || p.Label != "Game" { + t.Fatalf("post %+v", p) + } + if got := h.Message(ctx, said(inA, "bob-id", 1700000001000, "guess 42")); !got.Done { + t.Fatalf("a guess wasn't taken: %+v", got) + } + eventually(t, "the reaction", func() bool { return len(h.Reactions()) == 1 }) + if r := h.Reactions()[0]; r.Emoji != "🎯" || r.Chat != inA || r.Message.Timestamp != 1700000001000 { + t.Fatalf("reaction %+v", r) + } + if got := h.Message(ctx, said(inA, "bob-id", 1700000002000, "nice weather")); !got.IsZero() { + t.Fatalf("chatter was taken: %+v", got) + } +} diff --git a/internal/features/mcp/mcp.go b/internal/features/mcp/mcp.go index 97c0f22..e2f40a7 100644 --- a/internal/features/mcp/mcp.go +++ b/internal/features/mcp/mcp.go @@ -20,6 +20,7 @@ import ( "strings" "time" + ext "github.com/robdevops/signalbot/addon" "github.com/robdevops/signalbot/internal/feature" "github.com/robdevops/signalbot/internal/kit/httpx" "github.com/robdevops/signalbot/internal/kit/img" @@ -287,13 +288,9 @@ type botInfo struct { // extension with the chat network the bot is on, and returns what the // server said of itself. func initialize(ctx context.Context, c conn, self botInfo) (handshake, error) { - offer := map[string]any{"version": addonVersion} - if self.network != "" { - offer["network"] = self.network - } res, err := c.call(ctx, "initialize", map[string]any{ "protocolVersion": protocol, - "capabilities": map[string]any{"experimental": map[string]any{vendor + "addon": offer}}, + "capabilities": map[string]any{"experimental": map[string]any{ext.KeyAddon: ext.Capability{Version: ext.Version, Network: self.network}}}, "clientInfo": map[string]string{"name": "signalbot", "version": self.version}, }) if err != nil { @@ -313,10 +310,8 @@ func initialize(ctx context.Context, c conn, self botInfo) (handshake, error) { } `json:"capabilities"` } json.Unmarshal(res, &r) // all optional; a bad result shows up in tools/list - var ext struct { - Version int `json:"version"` - } - addon := json.Unmarshal(r.Capabilities.Experimental[vendor+"addon"], &ext) == nil && ext.Version == addonVersion + var offered ext.Capability + addon := json.Unmarshal(r.Capabilities.Experimental[ext.KeyAddon], &offered) == nil && offered.Version == ext.Version return handshake{ instructions: strings.TrimSpace(r.Instructions), title: txt.SafeName(cmp.Or(r.ServerInfo.Title, r.ServerInfo.Name)), @@ -399,7 +394,7 @@ func start(ctx context.Context, h feature.Host, path string, servers map[string] switch { case cfg.Addon == nil: case !hs.addon: - logx.Warnf("MCP server %s has an addon block but doesn't speak signalbot's addon extension (version %d), so it runs as a plain server", name, addonVersion) + logx.Warnf("MCP server %s has an addon block but doesn't speak signalbot's addon extension (version %d), so it runs as a plain server", name, ext.Version) case k != nil: bot := map[string]bool{} for _, t := range listed { @@ -678,7 +673,7 @@ type toolResult struct { } `json:"content"` IsError bool `json:"isError"` Meta struct { - Watch *watchSpec `json:"io.github.robdevops.signalbot/watch"` + Watch *ext.Watch `json:"io.github.robdevops.signalbot/watch"` React string `json:"io.github.robdevops.signalbot/react"` // an emoji to put on the message } `json:"_meta"` } diff --git a/internal/features/mcp/mcp_test.go b/internal/features/mcp/mcp_test.go index 75bbe4c..e6ff3bf 100644 --- a/internal/features/mcp/mcp_test.go +++ b/internal/features/mcp/mcp_test.go @@ -22,6 +22,7 @@ import ( "testing" "time" + ext "github.com/robdevops/signalbot/addon" "github.com/robdevops/signalbot/internal/feature" "github.com/robdevops/signalbot/internal/feature/featuretest" "github.com/robdevops/signalbot/internal/kit/logx" @@ -112,7 +113,7 @@ func (f *fakeMCP) ServeHTTP(w http.ResponseWriter, r *http.Request) { } json.Unmarshal(req.Params, &p) f.inits, f.version = f.inits+1, p.ClientInfo.Version - f.network = p.Capabilities.Experimental[vendor+"addon"].Network + f.network = p.Capabilities.Experimental[ext.KeyAddon].Network f.session = fmt.Sprintf("s%d", f.inits) w.Header().Set("Mcp-Session-Id", f.session) } else if r.Header.Get("Mcp-Session-Id") != f.session { diff --git a/internal/features/mcp/outbox.go b/internal/features/mcp/outbox.go index 01a40e5..de849a0 100644 --- a/internal/features/mcp/outbox.go +++ b/internal/features/mcp/outbox.go @@ -11,16 +11,12 @@ import ( "strings" "time" + ext "github.com/robdevops/signalbot/addon" "github.com/robdevops/signalbot/internal/feature" "github.com/robdevops/signalbot/internal/kit/logx" "github.com/robdevops/signalbot/internal/kit/txt" ) -// outboxURI is the resource an addon queues its posts and other ops in. -// The bot subscribes to it, and reads outboxURI/<cursor> for the ops past -// cursor. -const outboxURI = "signalbot://outbox" - // maxPages caps the pages of one outbox read, so an addon that always has // more can't keep the reader. const maxPages = 100 @@ -50,7 +46,7 @@ func (a *addon) ready(ctx context.Context, hs handshake) { } ctx, cancel := context.WithTimeout(ctx, callTimeout) defer cancel() - if _, err := a.conn.call(ctx, "resources/subscribe", map[string]string{"uri": outboxURI}); err != nil { + if _, err := a.conn.call(ctx, "resources/subscribe", map[string]string{"uri": ext.OutboxURI}); err != nil { logx.Warnf("MCP server %s: subscribing to its outbox failed: %s", a.server, errCode(err)) return } @@ -87,32 +83,6 @@ func (a *addon) readOutbox(ctx context.Context) { } } -// page is a page of an addon's outbox. -type page struct { - Cursor string `json:"cursor"` - More bool `json:"more"` - Ops []op `json:"ops"` -} - -// op is one thing an addon asks the bot to do. -type op struct { - ID string `json:"id"` - Op string `json:"op"` // post, react or unwatch - Chat string `json:"chat"` // a post's or unwatch's chat pseudonym - Text string `json:"text"` - Images []postImage `json:"images"` - Ref string `json:"ref"` // a reaction's message - Emoji string `json:"emoji"` - Watch string `json:"watch"` // the ID of the watch to end -} - -// postImage is an image in a post. -type postImage struct { - Data string `json:"data"` // base64 - MimeType string `json:"mimeType"` - Name string `json:"name"` -} - // errNotFound is a resource the server doesn't have: -32002 in the // 2025-06-18 spec and older SDKs, -32602 in the Go SDK. func errNotFound(err error) bool { @@ -156,14 +126,14 @@ func (a *addon) drain(ctx context.Context) bool { cursor := cmp.Or(a.cursor, "0") a.mu.Unlock() rctx, cancel := context.WithTimeout(ctx, callTimeout) - res, err := a.conn.call(rctx, "resources/read", map[string]string{"uri": outboxURI + "/" + cursor}) + res, err := a.conn.call(rctx, "resources/read", map[string]string{"uri": ext.OutboxURI + "/" + cursor}) cancel() var r struct { Contents []struct { Text string `json:"text"` } `json:"contents"` } - var p page + var p ext.Page switch { case errNotFound(err): logx.Warnf("MCP server %s has no outbox to read", a.server) @@ -233,7 +203,7 @@ type failure struct { // apply does what o asks, once, and returns why it was dropped, if it was. // A post counts as applied only once it is sent. -func (a *addon) apply(o op) (why string) { +func (a *addon) apply(o ext.Op) (why string) { if o.ID == "" { return "without an id" } @@ -289,7 +259,7 @@ func (a *addon) apply(o op) (why string) { // post posts o in its chat, if the addon may. One posted again, after it // was dropped, isn't counted against the rate again. -func (a *addon) post(o op, again bool) (why string) { +func (a *addon) post(o ext.Op, again bool) (why string) { now := a.now() a.mu.Lock() l, ok := a.leases[o.Chat] diff --git a/internal/features/mcp/watch.go b/internal/features/mcp/watch.go index 9ff23ca..43cb116 100644 --- a/internal/features/mcp/watch.go +++ b/internal/features/mcp/watch.go @@ -10,6 +10,7 @@ import ( "sync" "time" + ext "github.com/robdevops/signalbot/addon" "github.com/robdevops/signalbot/internal/feature" "github.com/robdevops/signalbot/internal/kit/logx" "github.com/robdevops/signalbot/internal/kit/txt" @@ -31,15 +32,6 @@ const ( // waits its turn. Tests change it. var watchRate = rateConfig{PerMinute: 120, Burst: 20} -// watchSpec is the watch a direct command's result asks for, in its _meta. -type watchSpec struct { - ID string `json:"id"` - Pattern string `json:"pattern"` // RE2 - Until string `json:"until"` // RFC 3339 - Tool string `json:"tool"` // called with each message it matches - Guard string `json:"guard"` // optional: the answer, while it lasts, to a message addressed to the bot that quotes its pictures -} - // watch is a live watch: an addon's claim, until Until, on the messages // matching Pattern in one chat that the bot gets while it lasts, and the // edits of those sent from Since on. @@ -108,7 +100,7 @@ func (a *addon) lease(chat feature.Chat) { // watch makes the watch spec asks for in m's chat, after the command m, // and returns it, or nil if it is refused, which is logged without the // pattern. -func (a *addon) watch(m feature.Message, spec watchSpec) *watch { +func (a *addon) watch(m feature.Message, spec ext.Watch) *watch { refuse := func(why string) *watch { logx.Warnf("MCP server %s: a watch refused: %s", a.server, why) return nil @@ -311,7 +303,7 @@ func (a *addon) forward(ctx context.Context, m match) (down bool) { res, err := a.conn.call(ctx, "tools/call", map[string]any{ "name": m.tool, "arguments": map[string]string{"text": m.msg.Text}, - "_meta": map[string]any{vendor + "context": c}, + "_meta": map[string]any{ext.KeyContext: c}, }) var r toolResult outcome := "ok" diff --git a/internal/features/mcp/watch_test.go b/internal/features/mcp/watch_test.go index eb56c2a..3b8e674 100644 --- a/internal/features/mcp/watch_test.go +++ b/internal/features/mcp/watch_test.go @@ -16,6 +16,7 @@ import ( "testing" "time" + ext "github.com/robdevops/signalbot/addon" "github.com/robdevops/signalbot/internal/feature" "github.com/robdevops/signalbot/internal/feature/featuretest" "github.com/robdevops/signalbot/internal/kit/logx" @@ -47,9 +48,9 @@ func (b *fakeOutbox) call(name string, args map[string]string, meta json.RawMess return `"result":{"content":[{"type":"text","text":"Round on"},{"type":"image","mimeType":"image/png","data":"` + tinyPNG() + `"}],` + `"_meta":{"io.github.robdevops.signalbot/watch":` + args["args"] + `}}` case "guess": - var m map[string]callContext + var m map[string]ext.Context json.Unmarshal(meta, &m) - line, _ := json.Marshal(guessed{args["text"], m[vendor+"context"]}) + line, _ := json.Marshal(guessed{args["text"], m[ext.KeyContext]}) fakeLog("guess " + string(line)) if strings.Contains(args["text"], "nopin") { return text("Recorded") @@ -93,7 +94,7 @@ func (b *fakeOutbox) read(uri string) string { defer b.mu.Unlock() b.reading-- from := 0 - if n, ok := strings.CutPrefix(strings.TrimPrefix(uri, outboxURI+"/"), b.nonce+"."); ok { + if n, ok := strings.CutPrefix(strings.TrimPrefix(uri, ext.OutboxURI+"/"), b.nonce+"."); ok { if i, err := strconv.Atoi(n); err == nil && i <= len(b.ops) { from = i } @@ -108,7 +109,7 @@ func (b *fakeOutbox) read(uri string) string { // guessed is what the fake addon's guess tool was sent. type guessed struct { Text string - Context callContext + Context ext.Context } var fakeLogMu sync.Mutex @@ -221,7 +222,7 @@ func edit(m feature.Message, at int64, text string) feature.Message { // spec is a watch called id, for "guess <number>", lasting d, with guard. func spec(id string, d time.Duration, guard string) string { - b, _ := json.Marshal(watchSpec{ID: id, Pattern: `\bguess \d+`, Until: time.Now().Add(d).Format(time.RFC3339), Tool: "guess", Guard: guard}) + b, _ := json.Marshal(ext.Watch{ID: id, Pattern: `\bguess \d+`, Until: time.Now().Add(d).Format(time.RFC3339), Tool: "guess", Guard: guard}) return string(b) } @@ -240,13 +241,13 @@ func round(t *testing.T, h *featuretest.Host, chat feature.Chat, ts int64, spec } // chatID is the fake addon's pseudonym for chat, from /ctx there. -func chatID(t *testing.T, h *featuretest.Host, chat feature.Chat) callContext { +func chatID(t *testing.T, h *featuretest.Host, chat feature.Chat) ext.Context { t.Helper() - var meta map[string]callContext + var meta map[string]ext.Context if err := json.Unmarshal([]byte(h.Message(context.Background(), in(chat, "/ctx")).Answer), &meta); err != nil { t.Fatal(err) } - return meta[vendor+"context"] + return meta[ext.KeyContext] } // queue has the fake addon queue ops, telling the bot notify times. @@ -586,11 +587,11 @@ func TestOutboxDelivery(t *testing.T) { a.host = h a.lease(inA) id := a.chatID(inA) - pic := []postImage{{Data: tinyPNG(), MimeType: "image/png"}} - postOp := func(n string, images []postImage) op { - return op{ID: n, Op: "post", Chat: id, Text: "post " + n, Images: images} + pic := []ext.Image{{Data: tinyPNG(), MimeType: "image/png"}} + postOp := func(n string, images []ext.Image) ext.Op { + return ext.Op{ID: n, Op: "post", Chat: id, Text: "post " + n, Images: images} } - for _, o := range []op{postOp("1", nil), postOp("2", pic), postOp("3", pic), postOp("4", pic), postOp("5", nil)} { + for _, o := range []ext.Op{postOp("1", nil), postOp("2", pic), postOp("3", pic), postOp("4", pic), postOp("5", nil)} { if why := a.apply(o); why != "" { t.Fatalf("%s: %s", o.ID, why) } @@ -715,8 +716,8 @@ func unitAddon(cfg addonConfig) (*addon, *time.Time) { var everything = addonConfig{Chats: []string{"all"}, DMs: true, Watch: true, Post: true, React: true, watchMax: time.Hour, Rate: rateConfig{20, 5}} // specAt is a watch spec ending at until. -func specAt(id string, until time.Time) watchSpec { - return watchSpec{ID: id, Pattern: `\bguess \d+`, Until: until.Format(time.RFC3339), Tool: "guess"} +func specAt(id string, until time.Time) ext.Watch { + return ext.Watch{ID: id, Pattern: `\bguess \d+`, Until: until.Format(time.RFC3339), Tool: "guess"} } // A chat has at most maxWatches; a claim lasts claimLife, a watch until its From a776459ec38e9b5b966b23196fe43ee23b371d83 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 21 Nov 2026 00:14:30 +0000 Subject: [PATCH 14/26] addon: pages fit the bot's line, Run stops cleanly; fix a test race From review of the new package: - An outbox page is measured as it is sent (its JSON escaped again inside the resource's text), so it stays under the bot's 4 MiB line, and Queue refuses an op that could never fit or has more than MaxImages images. - Run returns when its context ends, cancels the calls in flight before it waits for them (on stdin's end too), and waits for its notifier. - A result with no content sends an empty array, as MCP requires. - Changed may run concurrently, and Restore comes before any Queue: both documented. The docs no longer say GeoGuess uses the package yet. TestActionPictures read OnSent's slice while the chat's worker wrote it; it now holds a lock. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- addon/server.go | 104 ++++++++++++++++++++------ addon/server_test.go | 93 +++++++++++++++++++++++ docs/FILES_LINKS_TOOLS_MCP.md | 2 +- internal/bot/host_test.go | 6 +- internal/features/mcp/interop_test.go | 4 +- 5 files changed, 182 insertions(+), 27 deletions(-) diff --git a/addon/server.go b/addon/server.go index 80b1ebd..14f2e3b 100644 --- a/addon/server.go +++ b/addon/server.go @@ -7,6 +7,7 @@ import ( "encoding/hex" "encoding/json" "errors" + "fmt" "io" "slices" "strconv" @@ -36,7 +37,8 @@ type Config struct { Now func() time.Time // nil is time.Now; tests set it // Changed, if set, is called when a read of the outbox lets go of ops // the bot has read past, or ones held too long, so the addon can save - // Outbox(). It isn't called for Queue: Queue's caller knows to save. + // Outbox(). It isn't called for Queue: Queue's caller knows to save. It + // can run on several goroutines at once, so saving must allow that. Changed func() } @@ -64,12 +66,16 @@ type held struct { } // The outbox's limits: how long an op unread is kept, and the most a page -// holds, well under the 4 MiB line the bot reads. +// holds as sent, well under the 4 MiB line the bot reads. const ( keepOps = time.Hour pageSize = 3 << 20 ) +// MaxImages is the most images a post may have; the bot also caps them at +// 2 MB in all. +const MaxImages = 2 + // maxLine caps one incoming line. The bot's requests are small: a // command's arguments or one chat message. const maxLine = 1 << 20 @@ -106,10 +112,20 @@ func (s *Server) Network() string { // Queue adds ops to the outbox, giving each its ID, and tells a subscribed // bot. The bot reads them when it can; save Outbox() afterwards to keep -// them over a restart. -func (s *Server) Queue(ops ...Op) { +// them over a restart. It queues none, and says why, if one could never +// reach the bot: a post with more than MaxImages images, or an op too big +// for a page as it is sent. +func (s *Server) Queue(ops ...Op) error { + for _, o := range ops { + switch { + case len(o.Images) > MaxImages: + return fmt.Errorf("a post has %d images; the most is %d", len(o.Images), MaxImages) + case sentSize(o) > pageSize: + return fmt.Errorf("an op is %d bytes as sent; the most is %d", sentSize(o), pageSize) + } + } if len(ops) == 0 { - return + return nil } s.mu.Lock() now := s.cfg.Now() @@ -120,6 +136,15 @@ func (s *Server) Queue(ops ...Op) { } s.mu.Unlock() s.poke() + return nil +} + +// sentSize is o's size as the bot gets it: JSON inside the JSON string of +// a resource's text, where every quote and backslash is escaped again. +func sentSize(o Op) int { + data, _ := json.Marshal(o) + quoted, _ := json.Marshal(string(data)) + return len(quoted) } // Outbox is what the bot hasn't read past yet, oldest first, to save. @@ -133,7 +158,8 @@ func (s *Server) Outbox() []Held { return out } -// Restore puts saved ops back in the outbox, before Run. They keep their +// Restore puts saved ops back in the outbox. Call it before Run and before +// any Queue, so the ops stay in the order they were queued. They keep their // IDs, so the bot, which remembers the IDs it applied, never applies one // twice; a cursor from before the restart is this run's no longer, so the // bot's next read gets them all. @@ -146,33 +172,59 @@ func (s *Server) Restore(ops []Held) { } } -// Run serves the bot on in and out until in ends (the bot closed stdin: it -// returns nil) or ctx does. Each request is answered on its own goroutine, -// with a context the bot can cancel (notifications/cancelled), and Run -// waits for the answers in flight before it returns. +// Run serves the bot on in and out until in ends (the bot closed stdin: +// it returns nil) or ctx does (it returns ctx's error). Each request is +// answered on its own goroutine, with a context the bot can cancel +// (notifications/cancelled). When Run stops, it cancels the calls still +// running and waits for them, so none acts after it returns. A read from +// in that is still waiting when ctx ends is left to finish on its own. func (s *Server) Run(ctx context.Context, in io.Reader, out io.Writer) error { w := &wire{w: out} ctx, cancel := context.WithCancel(ctx) - defer cancel() - go s.notifier(ctx, w) + var wg sync.WaitGroup + notified := make(chan struct{}) + defer func() { + cancel() // first, so the calls in flight stop + wg.Wait() + <-notified + }() + go func() { defer close(notified); s.notifier(ctx, w) }() if len(s.Outbox()) > 0 { s.poke() } - var wg sync.WaitGroup - defer wg.Wait() + lines := make(chan []byte) + failed := make(chan error, 1) + go func() { + r := bufio.NewReaderSize(in, 64<<10) + for { + line, err := readLine(r) + if err != nil { + failed <- err + return + } + if line == nil { // too long, or blank + continue + } + select { + case lines <- line: + case <-ctx.Done(): + return + } + } + }() var mu sync.Mutex inFlight := map[string]context.CancelFunc{} // by request ID - r := bufio.NewReaderSize(in, 64<<10) for { - line, err := readLine(r) - if err != nil { + var line []byte + select { + case <-ctx.Done(): + return ctx.Err() + case err := <-failed: if errors.Is(err, io.EOF) { return nil } return err - } - if line == nil { // too long, or blank - continue + case line = <-lines: } var m message if json.Unmarshal(line, &m) != nil { @@ -435,7 +487,11 @@ func (s *Server) methods() map[string]handler { if !ok || t.Call == nil { return nil, &rpcError{codeInvalidParams, "unknown tool"} } - return t.Call(ctx, p.Meta.Context, p.Arguments) + r, err := t.Call(ctx, p.Meta.Context, p.Arguments) + if r.Content == nil { + r.Content = []Content{} // MCP's content is an array, never null + } + return r, err }, "resources/list": func(context.Context, json.RawMessage) (any, error) { return struct { @@ -507,12 +563,12 @@ func (s *Server) read(cursor string) Page { page := Page{Ops: []Op{}} size := 0 for _, h := range s.outbox { - data, _ := json.Marshal(h.Op) - if len(page.Ops) > 0 && size+len(data) > pageSize { + data := sentSize(h.Op) + if len(page.Ops) > 0 && size+data > pageSize { page.More = true break } - size += len(data) + size += data page.Ops = append(page.Ops, h.Op) last = h.seq } diff --git a/addon/server_test.go b/addon/server_test.go index 3ddd727..07e6720 100644 --- a/addon/server_test.go +++ b/addon/server_test.go @@ -350,3 +350,96 @@ func TestBadLine(t *testing.T) { } c.result("ping", struct{}{}, nil) } + +// Queue refuses an op that could never reach the bot, and queues none of +// the ops given with it. +func TestQueueLimits(t *testing.T) { + s := New(Config{Name: "game"}) + img := Image{Data: "aGk=", MimeType: "image/png"} + if err := s.Queue(Op{Op: "post", Chat: "c_one", Text: "ok"}, Op{Op: "post", Chat: "c_one", Images: []Image{img, img, img}}); err == nil { + t.Error("3 images queued") + } + if err := s.Queue(Op{Op: "post", Chat: "c_one", Text: strings.Repeat(`"`, pageSize/2)}); err == nil { + t.Error("an op too big once escaped was queued") + } + if n := len(s.Outbox()); n != 0 { + t.Fatalf("%d ops queued", n) + } + if err := s.Queue(Op{Op: "post", Chat: "c_one", Images: []Image{img, img}}); err != nil { + t.Errorf("2 images: %v", err) + } +} + +// A page of ops full of characters JSON escapes still fits the bot's +// 4 MiB line. +func TestPageFitsALine(t *testing.T) { + s := New(Config{Name: "game"}) + for range 1000 { + if err := s.Queue(Op{Op: "post", Chat: "c_one", Text: strings.Repeat(`"\`, 1500)}); err != nil { + t.Fatal(err) + } + } + c := start(t, s) + initialize(c, "") + id := c.request("resources/read", uriParams{OutboxURI + "/0"}) + for line := range c.lines { + if len(line) >= 4<<20 { + t.Fatalf("a %d-byte line", len(line)) + } + var m struct{ ID *int } + if json.Unmarshal(line, &m) == nil && m.ID != nil && *m.ID == id { + return + } + } + t.Fatal("no reply") +} + +// Run returns when its context ends, and cancels the calls in flight; when +// stdin ends it cancels them too before it returns. +func TestRunStops(t *testing.T) { + for _, how := range []string{"ctx", "eof"} { + ended := make(chan struct{}) + slow := Tool{Name: "slow", Call: func(ctx context.Context, _ *Context, _ json.RawMessage) (Result, error) { + <-ctx.Done() + close(ended) + return Text("stopped"), nil + }} + s := New(Config{Name: "game", Tools: []Tool{slow}}) + inR, inW := io.Pipe() + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- s.Run(ctx, inR, io.Discard) }() + inW.Write([]byte(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"slow"}}` + "\n")) + time.Sleep(50 * time.Millisecond) + if how == "ctx" { + cancel() + } else { + inW.Close() + } + select { + case err := <-done: + if how == "ctx" && err != context.Canceled || how == "eof" && err != nil { + t.Errorf("%s: Run returned %v", how, err) + } + case <-time.After(5 * time.Second): + t.Fatalf("%s: Run didn't return", how) + } + select { + case <-ended: + default: + t.Errorf("%s: the call in flight wasn't cancelled before Run returned", how) + } + cancel() + inW.Close() + } +} + +// A result with no content still sends an array, as MCP requires. +func TestEmptyResult(t *testing.T) { + empty := Tool{Name: "empty", Call: func(context.Context, *Context, json.RawMessage) (Result, error) { return Result{}, nil }} + c := start(t, New(Config{Name: "game", Tools: []Tool{empty}})) + resp, _ := c.reply(c.request("tools/call", map[string]any{"name": "empty"})) + if !strings.Contains(string(resp.Result), `"content":[]`) { + t.Errorf("result %s", resp.Result) + } +} diff --git a/docs/FILES_LINKS_TOOLS_MCP.md b/docs/FILES_LINKS_TOOLS_MCP.md index c8cc1e6..ad853d4 100644 --- a/docs/FILES_LINKS_TOOLS_MCP.md +++ b/docs/FILES_LINKS_TOOLS_MCP.md @@ -100,7 +100,7 @@ A server that can't be reached at startup is logged and left out. A config error An addon is a local MCP server that does more than offer tools: it answers its own commands without the model, reads the messages it asks for, and posts and reacts when it likes. [GeoGuess](https://github.com/robdevops/chat-plugin-geoguess), a photo-guessing game, is one. It is still an ordinary MCP server (protocol 2025-06-18 over stdio), which also speaks signalbot's small extension, under keys starting `io.github.robdevops.signalbot/`. A server is an addon when it has an `addon` block in the MCP file and says it speaks the extension when the bot connects; one with the block that doesn't runs as a plain server, with a warning. Addons run even with [no model](MODELS.md#no-model). -An addon written in Go can use the package [`github.com/robdevops/signalbot/addon`](../addon), which has the extension's types and a ready stdio server: give it the tools, and queue posts, reactions and the end of a watch with `Queue`; GeoGuess is built on it. An addon in another language speaks the same JSON, described below. +An addon written in Go can use the package [`github.com/robdevops/signalbot/addon`](../addon), which has the extension's types and a ready stdio server: give it the tools, and queue posts, reactions and the end of a watch with `Queue`. An addon in another language speaks the same JSON, described below. **An addon is trusted code.** It runs as the bot's user, inside the same systemd or Docker sandbox, and could read what that user can. The bot gives it as little as it can (below), but that guards against bugs and leaks, not a hostile program: install only addons you would let run as the bot. diff --git a/internal/bot/host_test.go b/internal/bot/host_test.go index fda8b1d..d9c9f12 100644 --- a/internal/bot/host_test.go +++ b/internal/bot/host_test.go @@ -9,6 +9,7 @@ import ( "regexp" "slices" "strings" + "sync" "sync/atomic" "testing" "time" @@ -657,8 +658,9 @@ func TestDone(t *testing.T) { // A command's pictures are sent with its Answer, without the model, by the // caption rule; OnSent gets the timestamps Send returned. func TestActionPictures(t *testing.T) { + var mu sync.Mutex // OnSent runs on the chat's worker var sentAt [][]int64 - onSent := func(ts []int64, _ bool) { sentAt = append(sentAt, ts) } + onSent := func(ts []int64, _ bool) { mu.Lock(); sentAt = append(sentAt, ts); mu.Unlock() } h := start(t, options{features: func(b *Bot) { b.Command("plain", func(context.Context, feature.Message, string) feature.Action { return feature.Action{Answer: "here", Pictures: []feature.Picture{{Data: png}}, OnSent: onSent} @@ -686,6 +688,8 @@ func TestActionPictures(t *testing.T) { if len(h.requests()) != 0 { t.Fatal("the model was asked") } + mu.Lock() + defer mu.Unlock() if fmt.Sprint(sentAt) != "[[5001] [5002]]" { t.Fatalf("OnSent got %v", sentAt) } diff --git a/internal/features/mcp/interop_test.go b/internal/features/mcp/interop_test.go index b9bf992..897a9e5 100644 --- a/internal/features/mcp/interop_test.go +++ b/internal/features/mcp/interop_test.go @@ -29,7 +29,9 @@ func TestPackageAddonProcess(t *testing.T) { if c == nil { return ext.Text("no chat"), nil } - s.Queue(ext.Op{Op: "post", Chat: c.Chat, Text: "{" + c.Sender + "} started a round on " + s.Network()}) + if err := s.Queue(ext.Op{Op: "post", Chat: c.Chat, Text: "{" + c.Sender + "} started a round on " + s.Network()}); err != nil { + return ext.Result{}, err + } r := ext.Text("started") r.Meta = &ext.ResultMeta{Watch: &ext.Watch{ID: "r1", Pattern: `\bguess \d+`, Until: time.Now().Add(time.Hour).Format(time.RFC3339), Tool: "guess"}} return r, nil From 8e661eb5f9c5531c4bf33c1c71dac7611a3acc76 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 21 Nov 2026 00:19:09 +0000 Subject: [PATCH 15/26] docs: GeoGuess is built on the addon package Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- docs/FILES_LINKS_TOOLS_MCP.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/FILES_LINKS_TOOLS_MCP.md b/docs/FILES_LINKS_TOOLS_MCP.md index ad853d4..015de41 100644 --- a/docs/FILES_LINKS_TOOLS_MCP.md +++ b/docs/FILES_LINKS_TOOLS_MCP.md @@ -100,7 +100,7 @@ A server that can't be reached at startup is logged and left out. A config error An addon is a local MCP server that does more than offer tools: it answers its own commands without the model, reads the messages it asks for, and posts and reacts when it likes. [GeoGuess](https://github.com/robdevops/chat-plugin-geoguess), a photo-guessing game, is one. It is still an ordinary MCP server (protocol 2025-06-18 over stdio), which also speaks signalbot's small extension, under keys starting `io.github.robdevops.signalbot/`. A server is an addon when it has an `addon` block in the MCP file and says it speaks the extension when the bot connects; one with the block that doesn't runs as a plain server, with a warning. Addons run even with [no model](MODELS.md#no-model). -An addon written in Go can use the package [`github.com/robdevops/signalbot/addon`](../addon), which has the extension's types and a ready stdio server: give it the tools, and queue posts, reactions and the end of a watch with `Queue`. An addon in another language speaks the same JSON, described below. +An addon written in Go can use the package [`github.com/robdevops/signalbot/addon`](../addon), which has the extension's types and a ready stdio server: give it the tools, and queue posts, reactions and the end of a watch with `Queue`. [GeoGuess](https://github.com/robdevops/chat-plugin-geoguess) is built on it. An addon in another language speaks the same JSON, described below. **An addon is trusted code.** It runs as the bot's user, inside the same systemd or Docker sandbox, and could read what that user can. The bot gives it as little as it can (below), but that guards against bugs and leaks, not a hostile program: install only addons you would let run as the bot. From ddcc90d6a71cec5c0cc3b04e83ad5fd3afa05516 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 21 Nov 2026 00:30:23 +0000 Subject: [PATCH 16/26] addon: a JSON Schema of the extension, for addons in other languages addon/schema.json describes each message of the extension: the capability, a tool's visibility, the call context, the watch and reaction in a result, the outbox page and its post, react and unwatch ops, and the saved outbox entry. A test keeps it in step with the Go types (keys, required keys, types, the version and the image limit), checks samples both ways with a small validator, and checks what a real Server writes; the bot's pseudonyms and refs are checked against its patterns. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- CONTRIBUTING.md | 2 +- TECHNICAL.md | 2 +- addon/schema.json | 142 ++++++++ addon/schema_test.go | 484 ++++++++++++++++++++++++++++ addon/types.go | 3 +- docs/FILES_LINKS_TOOLS_MCP.md | 2 +- internal/features/mcp/addon_test.go | 43 +++ 7 files changed, 674 insertions(+), 4 deletions(-) create mode 100644 addon/schema.json create mode 100644 addon/schema_test.go diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 6bff809..222272a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -15,7 +15,7 @@ internal/bot/ the decision, the prompt, the hooks; wires the core, and internal/feature/ the ports and shared types, command parsing, featuretest internal/features/* one package per feature internal/kit/* code with two or more users and no bot knowledge -addon/ signalbot's MCP addon extension, for the bot and any addon written in Go: its wire format and a ready stdio server; public, standard library only +addon/ signalbot's MCP addon extension, for the bot and any addon written in Go: its wire format, a ready stdio server, and schema.json for addons in other languages; public, standard library only cmd/signalctl/ a small client for signal-cli's daemon socket, for one-off chores such as blocking; not part of the bot ``` diff --git a/TECHNICAL.md b/TECHNICAL.md index 14e2cbd..27ec456 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -89,7 +89,7 @@ internal/feature/ the ports and shared types (the only part of the core fe internal/features/* one package per feature internal/kit/* code with two or more users and no bot knowledge internal/arch/ the guardrail tests and the sizes report -addon/ signalbot's MCP addon extension, for the bot and any addon written in Go: its wire format and a ready stdio server; public, standard library only +addon/ signalbot's MCP addon extension, for the bot and any addon written in Go: its wire format, a ready stdio server, and schema.json for addons in other languages; public, standard library only cmd/signalctl/ a small client for signal-cli's daemon socket, for one-off chores such as blocking; not part of the bot ``` diff --git a/addon/schema.json b/addon/schema.json new file mode 100644 index 0000000..e008324 --- /dev/null +++ b/addon/schema.json @@ -0,0 +1,142 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://raw.githubusercontent.com/robdevops/signalbot/main/addon/schema.json", + "title": "signalbot's addon extension of MCP 2025-06-18, version 1", + "description": "The JSON of signalbot's addon extension, for an addon in any language: each object the bot and an addon exchange on top of MCP, under $defs. The keys of the extension start io.github.robdevops.signalbot/. The Go types in addon/types.go are the same messages, and a test keeps the two in step. Each side ignores keys it doesn't know; the objects an addon sends (Watch, Op, Image, Page) forbid them here, so a misspelt key fails validation instead of being ignored.", + "$defs": { + "Capability": { + "description": "capabilities.experimental[\"io.github.robdevops.signalbot/addon\"] in initialize. The bot offers its chat network; an addon answers with the version alone.", + "type": "object", + "properties": { + "version": {"description": "The extension's version.", "const": 1}, + "network": {"description": "The bot's chat network, as it names itself.", "type": "string", "examples": ["signal", "telegram"]} + }, + "required": ["version"] + }, + "ToolMeta": { + "description": "A tool's _meta in tools/list: who may call it. Without the key, only the model. A tool for the bot alone is never offered to the model.", + "type": "object", + "properties": { + "io.github.robdevops.signalbot/visibility": { + "type": "array", + "items": {"enum": ["bot", "model"]}, + "uniqueItems": true + } + } + }, + "Context": { + "description": "A tools/call's _meta[\"io.github.robdevops.signalbot/context\"], when the bot itself makes the call: the message the call came from. Times are when the bot got the message, never the sender's clock.", + "type": "object", + "properties": { + "chat": {"description": "The chat's pseudonym.", "type": "string", "pattern": "^c_[a-z2-7]{26}$"}, + "sender": {"description": "The sender's pseudonym, in that chat unless global_ids. Written as {u_…} in a post, the bot puts in their name.", "type": "string", "pattern": "^u_[a-z2-7]{26}$"}, + "ref": {"description": "A handle for the message, for a react op, good for 24 hours.", "type": "string", "pattern": "^r_[a-z2-7]{26}$"}, + "addressed": {"description": "The message was addressed to the bot.", "type": "boolean"}, + "group": {"description": "The chat is a group, not a DM.", "type": "boolean"}, + "sent": {"description": "When the bot got the message, in Unix seconds.", "type": "integer", "minimum": 0}, + "edited": {"description": "When the bot got the edit, in Unix seconds; 0 for an original.", "type": "integer", "minimum": 0}, + "name": {"description": "The sender's display name, with the addon block's names permission.", "type": "string"}, + "deadline": {"description": "A direct command's: when the bot stops waiting, in Unix seconds.", "type": "integer", "minimum": 0} + }, + "required": ["chat", "sender", "ref", "addressed", "group", "sent", "edited"] + }, + "Watch": { + "description": "A direct command's result's _meta[\"io.github.robdevops.signalbot/watch\"]: the messages matching pattern in the command's chat, until until, go to tool instead of the model. The bot refuses a pattern that would match ordinary chat, and shortens until to the addon block's watch_max.", + "type": "object", + "properties": { + "id": {"description": "The watch's name, for an unwatch op; at most 64 bytes. A new watch with the ID of a live one in the chat replaces it.", "type": "string", "minLength": 1, "maxLength": 64}, + "pattern": {"description": "An RE2 regular expression, at most 1 KB.", "type": "string", "minLength": 1, "maxLength": 1024}, + "until": {"description": "An RFC 3339 time, in the future.", "type": "string", "format": "date-time"}, + "tool": {"description": "A tool for the bot, called with each message the watch takes, as {\"text\": …}, with its context.", "type": "string", "minLength": 1}, + "guard": {"description": "While the watch lasts, the answer to a message addressed to the bot that replies to the command's pictures; at most 500 characters.", "type": "string", "maxLength": 500} + }, + "required": ["id", "pattern", "until", "tool"], + "additionalProperties": false + }, + "Content": { + "description": "One block of a tool's result. The bot uses text and image blocks.", + "type": "object", + "properties": { + "type": {"enum": ["text", "image"]}, + "text": {"type": "string"}, + "data": {"description": "An image's bytes, in base64.", "type": "string", "contentEncoding": "base64"}, + "mimeType": {"type": "string", "examples": ["image/jpeg", "image/png"]} + }, + "required": ["type"], + "allOf": [ + {"if": {"properties": {"type": {"const": "image"}}}, "then": {"required": ["data", "mimeType"]}} + ] + }, + "Result": { + "description": "A tool's result (MCP's CallToolResult), with what it asks of the bot in _meta. A direct command's answer is its text and up to 2 images.", + "type": "object", + "properties": { + "content": {"type": "array", "items": {"$ref": "#/$defs/Content"}}, + "isError": {"type": "boolean"}, + "_meta": {"$ref": "#/$defs/ResultMeta"} + }, + "required": ["content"] + }, + "ResultMeta": { + "description": "A result's _meta: what it asks of the bot besides its content.", + "type": "object", + "properties": { + "io.github.robdevops.signalbot/watch": {"description": "A direct command's only.", "$ref": "#/$defs/Watch"}, + "io.github.robdevops.signalbot/react": {"description": "One emoji, for the message the call came from.", "type": "string", "minLength": 1} + } + }, + "Op": { + "description": "One thing an addon's outbox asks the bot to do: post in a chat, react to a message, or end a watch. The bot does each ID once, so an op read again, such as after a restart, is skipped.", + "type": "object", + "properties": { + "id": {"description": "Unique among the addon's ops, for as long as the bot may read it again.", "type": "string", "minLength": 1}, + "op": {"enum": ["post", "react", "unwatch"]}, + "chat": {"description": "A post's or unwatch's chat.", "type": "string", "pattern": "^c_[a-z2-7]{26}$"}, + "text": {"description": "A post's text, with {u_…} placeholders the bot fills in with names; at most 4000 characters.", "type": "string"}, + "images": {"description": "A post's images: at most 2, and 2 MiB in all.", "type": "array", "items": {"$ref": "#/$defs/Image"}, "maxItems": 2}, + "ref": {"description": "The message a reaction is for: a context's ref.", "type": "string", "pattern": "^r_[a-z2-7]{26}$"}, + "emoji": {"description": "A reaction's: one emoji.", "type": "string", "minLength": 1}, + "watch": {"description": "The ID of the watch an unwatch ends.", "type": "string", "minLength": 1, "maxLength": 64} + }, + "required": ["id", "op"], + "additionalProperties": false, + "allOf": [ + {"if": {"properties": {"op": {"const": "post"}}}, "then": {"required": ["chat"], "anyOf": [{"required": ["text"]}, {"required": ["images"]}]}}, + {"if": {"properties": {"op": {"const": "react"}}}, "then": {"required": ["ref", "emoji"]}}, + {"if": {"properties": {"op": {"const": "unwatch"}}}, "then": {"required": ["chat", "watch"]}} + ] + }, + "Image": { + "description": "An image in a post. The bot reads its bytes, whatever mimeType says.", + "type": "object", + "properties": { + "data": {"description": "The image's bytes, in base64.", "type": "string", "minLength": 1, "contentEncoding": "base64"}, + "mimeType": {"type": "string", "examples": ["image/jpeg", "image/png"]}, + "name": {"type": "string"} + }, + "required": ["data", "mimeType"], + "additionalProperties": false + }, + "Page": { + "description": "The text of resources/read of signalbot://outbox/{cursor}: the ops after cursor. The bot reads from \"0\" at first and then from each page's cursor; an addon gives everything it still holds for a cursor it doesn't know, such as one from before it restarted. A page is at most 3 MiB, under the 4 MiB line the bot reads.", + "type": "object", + "properties": { + "cursor": {"description": "Where the next read starts; opaque to the bot.", "type": "string", "minLength": 1}, + "more": {"description": "More ops wait past this page.", "type": "boolean"}, + "ops": {"type": "array", "items": {"$ref": "#/$defs/Op"}} + }, + "required": ["cursor", "more", "ops"], + "additionalProperties": false + }, + "Held": { + "description": "An op the bot hasn't read past yet, as an addon may save it, with its ID, to post it after a restart. Not on the wire.", + "type": "object", + "properties": { + "op": {"$ref": "#/$defs/Op"}, + "queued": {"description": "When it was queued, in RFC 3339.", "type": "string", "format": "date-time"} + }, + "required": ["op", "queued"], + "additionalProperties": false + } + } +} diff --git a/addon/schema_test.go b/addon/schema_test.go new file mode 100644 index 0000000..0a224ae --- /dev/null +++ b/addon/schema_test.go @@ -0,0 +1,484 @@ +package addon + +import ( + "context" + "encoding/json" + "fmt" + "os" + "reflect" + "regexp" + "slices" + "sort" + "strings" + "testing" + "time" +) + +// schema is schema.json, decoded. +func schema(t *testing.T) map[string]any { + t.Helper() + data, err := os.ReadFile("schema.json") + if err != nil { + t.Fatal(err) + } + var s map[string]any + if err := json.Unmarshal(data, &s); err != nil { + t.Fatal(err) + } + return s +} + +// defs is the schema's $defs. +func defs(t *testing.T, s map[string]any) map[string]any { + t.Helper() + d, ok := s["$defs"].(map[string]any) + if !ok { + t.Fatal("schema.json has no $defs") + } + return d +} + +// wireTypes are the Go types schema.json describes, by their $defs name. +var wireTypes = map[string]reflect.Type{ + "Capability": reflect.TypeFor[Capability](), + "Context": reflect.TypeFor[Context](), + "Watch": reflect.TypeFor[Watch](), + "Content": reflect.TypeFor[Content](), + "Result": reflect.TypeFor[Result](), + "ResultMeta": reflect.TypeFor[ResultMeta](), + "Op": reflect.TypeFor[Op](), + "Image": reflect.TypeFor[Image](), + "Page": reflect.TypeFor[Page](), + "Held": reflect.TypeFor[Held](), +} + +// The schema and the Go types say the same: the same objects, each with +// the same keys, the same keys required (those Go always writes), and the +// same type for each. +func TestSchemaMatchesTypes(t *testing.T) { + d := defs(t, schema(t)) + var names []string + for name := range d { + if _, ok := wireTypes[name]; !ok && name != "ToolMeta" { + t.Errorf("$defs/%s has no Go type", name) + } + names = append(names, name) + } + for name, typ := range wireTypes { + def, ok := d[name].(map[string]any) + if !ok { + t.Errorf("%s isn't in $defs", typ) + continue + } + props, _ := def["properties"].(map[string]any) + var keys, required []string + for i := range typ.NumField() { + f := typ.Field(i) + tag, opts, _ := strings.Cut(f.Tag.Get("json"), ",") + if !f.IsExported() || tag == "-" || tag == "" { + t.Errorf("%s.%s has no JSON name", typ, f.Name) + continue + } + keys = append(keys, tag) + if !slices.Contains(strings.Split(opts, ","), "omitempty") { + required = append(required, tag) + } + p, ok := props[tag].(map[string]any) + if !ok { + t.Errorf("$defs/%s has no %q, %s.%s's key", name, tag, typ, f.Name) + continue + } + // A Go string may hold a formatted one, such as Watch.Until. + if want, got := goSchema(f.Type), propType(p); want != got && (want != "string" || !strings.HasPrefix(got, "string(")) { + t.Errorf("$defs/%s %q is %s; %s.%s is %s", name, tag, got, typ, f.Name, want) + } + } + var schemaKeys []string + for k := range props { + schemaKeys = append(schemaKeys, k) + } + var schemaRequired []string + for _, r := range asList(def["required"]) { + schemaRequired = append(schemaRequired, r.(string)) + } + sort.Strings(keys) + sort.Strings(schemaKeys) + sort.Strings(required) + sort.Strings(schemaRequired) + if !slices.Equal(keys, schemaKeys) { + t.Errorf("$defs/%s has keys %v; %s has %v", name, schemaKeys, typ, keys) + } + if !slices.Equal(required, schemaRequired) { + t.Errorf("$defs/%s requires %v; %s always writes %v", name, schemaRequired, typ, required) + } + } + // The _meta keys are the package's. + for def, key := range map[string]string{"ToolMeta": KeyVisibility, "ResultMeta": KeyWatch} { + if _, ok := d[def].(map[string]any)["properties"].(map[string]any)[key]; !ok { + t.Errorf("$defs/%s lacks %s", def, key) + } + } + if v := d["Capability"].(map[string]any)["properties"].(map[string]any)["version"].(map[string]any)["const"]; v != float64(Version) { + t.Errorf("the schema's version is %v; the package's %d", v, Version) + } + if n := d["Op"].(map[string]any)["properties"].(map[string]any)["images"].(map[string]any)["maxItems"]; n != float64(MaxImages) { + t.Errorf("the schema's most images is %v; the package's %d", n, MaxImages) + } + if title := schema(t)["title"].(string); !strings.Contains(title, Protocol) { + t.Errorf("the title %q doesn't name MCP %s", title, Protocol) + } +} + +// goSchema is the schema type a Go type is written as: a JSON type, a +// $ref to another of $defs, or an array of either. +func goSchema(t reflect.Type) string { + if t == reflect.TypeFor[time.Time]() { + return "string(date-time)" + } + switch t.Kind() { + case reflect.Pointer: + return goSchema(t.Elem()) + case reflect.Struct: + return "#/$defs/" + t.Name() + case reflect.Slice: + return "array of " + goSchema(t.Elem()) + case reflect.String: + return "string" + case reflect.Bool: + return "boolean" + case reflect.Int, reflect.Int64: + return "integer" + } + return "unknown " + t.String() +} + +// propType is a property's type as goSchema writes it. A const stands for +// its value's type. +func propType(p map[string]any) string { + if ref, ok := p["$ref"].(string); ok { + return ref + } + typ, _ := p["type"].(string) + switch { + case typ == "array": + items, _ := p["items"].(map[string]any) + return "array of " + propType(items) + case typ == "string" && p["format"] == "date-time": + return "string(date-time)" + case typ == "": + if _, ok := p["const"].(float64); ok { + return "integer" + } + if e := asList(p["enum"]); len(e) > 0 { + if _, ok := e[0].(string); ok { + return "string" + } + } + } + return typ +} + +func asList(v any) []any { l, _ := v.([]any); return l } + +// validate reports why v breaks the schema s (a subschema of root), or nil. +// It knows the keywords schema.json uses, and fails on any other, so a +// keyword added to the schema can't be skipped here unnoticed. +func validate(root, s map[string]any, v any, at string) error { + for k, kv := range s { + switch k { + case "$schema", "$id", "title", "description", "examples", "format", "contentEncoding", "$defs", "properties", "additionalProperties": + case "$ref": + name, ok := strings.CutPrefix(kv.(string), "#/$defs/") + def, found := root["$defs"].(map[string]any)[name].(map[string]any) + if !ok || !found { + return fmt.Errorf("%s: no %s", at, kv) + } + if err := validate(root, def, v, at); err != nil { + return err + } + case "type": + if !isType(v, kv.(string)) { + return fmt.Errorf("%s: not %s", at, kv) + } + case "const": + if !reflect.DeepEqual(v, kv) { + return fmt.Errorf("%s: not %v", at, kv) + } + case "enum": + if !slices.ContainsFunc(asList(kv), func(e any) bool { return reflect.DeepEqual(v, e) }) { + return fmt.Errorf("%s: %v isn't one of %v", at, v, kv) + } + case "pattern": + if str, ok := v.(string); ok && !regexp.MustCompile(kv.(string)).MatchString(str) { + return fmt.Errorf("%s: %q doesn't match %s", at, str, kv) + } + case "minLength", "maxLength": + if str, ok := v.(string); ok { + n := float64(len([]rune(str))) + if k == "minLength" && n < kv.(float64) || k == "maxLength" && n > kv.(float64) { + return fmt.Errorf("%s: %d characters, %s %v", at, len([]rune(str)), k, kv) + } + } + case "minimum": + if n, ok := v.(float64); ok && n < kv.(float64) { + return fmt.Errorf("%s: %v under %v", at, n, kv) + } + case "maxItems": + if l, ok := v.([]any); ok && float64(len(l)) > kv.(float64) { + return fmt.Errorf("%s: %d items, at most %v", at, len(l), kv) + } + case "uniqueItems": + l, _ := v.([]any) + for i := range l { + for j := range i { + if reflect.DeepEqual(l[i], l[j]) { + return fmt.Errorf("%s: %v twice", at, l[i]) + } + } + } + case "items": + for i, e := range asList(v) { + if err := validate(root, kv.(map[string]any), e, fmt.Sprintf("%s[%d]", at, i)); err != nil { + return err + } + } + case "required": + if o, ok := v.(map[string]any); ok { + for _, r := range asList(kv) { + if _, ok := o[r.(string)]; !ok { + return fmt.Errorf("%s: no %s", at, r) + } + } + } + case "allOf": + for _, sub := range asList(kv) { + if err := validate(root, sub.(map[string]any), v, at); err != nil { + return err + } + } + case "anyOf": + var errs []string + for _, sub := range asList(kv) { + err := validate(root, sub.(map[string]any), v, at) + if err == nil { + errs = nil + break + } + errs = append(errs, err.Error()) + } + if errs != nil { + return fmt.Errorf("%s: none of anyOf: %s", at, strings.Join(errs, "; ")) + } + case "if": + branch := "then" + if validate(root, kv.(map[string]any), v, at) != nil { + branch = "else" + } + if sub, ok := s[branch].(map[string]any); ok { + if err := validate(root, sub, v, at); err != nil { + return err + } + } + case "then", "else": + default: + return fmt.Errorf("%s: the test's validator doesn't know %q", at, k) + } + } + o, ok := v.(map[string]any) + if !ok { + return nil + } + props, _ := s["properties"].(map[string]any) + for key, val := range o { + p, known := props[key].(map[string]any) + switch { + case known: + if err := validate(root, p, val, at+"."+key); err != nil { + return err + } + case s["additionalProperties"] == false: + return fmt.Errorf("%s: unknown key %q", at, key) + } + } + return nil +} + +// isType reports whether a decoded JSON value is of a JSON Schema type. +func isType(v any, typ string) bool { + switch typ { + case "object": + _, ok := v.(map[string]any) + return ok + case "array": + _, ok := v.([]any) + return ok + case "string": + _, ok := v.(string) + return ok + case "boolean": + _, ok := v.(bool) + return ok + case "integer": + n, ok := v.(float64) + return ok && n == float64(int64(n)) + } + return false +} + +// check validates v, as JSON, against $defs/def. +func check(t *testing.T, root map[string]any, def string, v any) error { + t.Helper() + data, err := json.Marshal(v) + if err != nil { + t.Fatal(err) + } + var decoded any + if err := json.Unmarshal(data, &decoded); err != nil { + t.Fatal(err) + } + return validate(root, map[string]any{"$ref": "#/$defs/" + def}, decoded, def) +} + +// Pseudonyms as the bot makes them. +const ( + chatID = "c_abcdefghijklmnopqrstuvwxyz" + senderID = "u_abcdefghijklmnopqrstuvwx23" + refID = "r_234567abcdefghijklmnopqrst" +) + +// Messages as the bot and the package write them are valid, and the +// mistakes the schema is for are not. +func TestSchemaSamples(t *testing.T) { + root := schema(t) + until := time.Date(2026, 11, 21, 9, 3, 0, 0, time.UTC).Format(time.RFC3339) + post := Op{ID: "a1b2.1", Op: "post", Chat: chatID, Text: "{" + senderID + "} wins"} + valid := []struct { + def string + v any + }{ + {"Capability", Capability{Version: Version, Network: "signal"}}, + {"Capability", Capability{Version: Version}}, + {"Context", Context{Chat: chatID, Sender: senderID, Ref: refID, Addressed: true, Group: true, Sent: 1763715600}}, + {"Context", Context{Chat: chatID, Sender: senderID, Ref: refID, Sent: 1763715600, Edited: 1763715660, Name: "Alice", Deadline: 1763715615}}, + {"Watch", Watch{ID: "r1", Pattern: `maps\.google`, Until: until, Tool: "guess", Guard: "No hints 😉"}}, + {"Result", Text("started")}, + {"Result", Text("")}, + {"Result", Result{Content: []Content{{Type: "image", Data: "aGk=", MimeType: "image/jpeg"}, {Type: "text", Text: "go"}}, + Meta: &ResultMeta{Watch: &Watch{ID: "r1", Pattern: `\d`, Until: until, Tool: "guess"}}}}, + {"Result", Result{Content: []Content{{Type: "text", Text: "no"}}, IsError: true, Meta: &ResultMeta{React: "📍"}}}, + {"Op", post}, + {"Op", Op{ID: "2", Op: "post", Chat: chatID, Images: []Image{{Data: "aGk=", MimeType: "image/png", Name: "a.png"}}}}, + {"Op", Op{ID: "3", Op: "react", Ref: refID, Emoji: "🎯"}}, + {"Op", Op{ID: "4", Op: "unwatch", Chat: chatID, Watch: "r1"}}, + {"Page", Page{Cursor: "a1b2.4", Ops: []Op{post}}}, + {"Page", Page{Cursor: "a1b2.0", More: true, Ops: []Op{}}}, + {"Held", Held{Op: post, Queued: time.Now()}}, + {"ToolMeta", map[string]any{KeyVisibility: []string{"bot"}}}, + {"ToolMeta", map[string]any{}}, + } + for _, c := range valid { + if err := check(t, root, c.def, c.v); err != nil { + t.Errorf("%+v: %v", c.v, err) + } + } + invalid := []struct { + def, why string + v any + }{ + {"Capability", "another version", map[string]any{"version": 2}}, + {"Context", "a phone number for a sender", Context{Chat: chatID, Sender: "+61400000000", Ref: refID}}, + {"Context", "no ref", map[string]any{"chat": chatID, "sender": senderID, "addressed": true, "group": true, "sent": 1, "edited": 0}}, + {"Watch", "no tool", Watch{ID: "r1", Pattern: `\d`, Until: until}}, + {"Watch", "a misspelt key", map[string]any{"id": "r1", "pattern": `\d`, "until": until, "tool": "guess", "gaurd": "x"}}, + {"Watch", "too long an ID", Watch{ID: strings.Repeat("x", 65), Pattern: `\d`, Until: until, Tool: "guess"}}, + {"Result", "an image without its bytes", Result{Content: []Content{{Type: "image", MimeType: "image/jpeg"}}}}, + {"Result", "audio", Result{Content: []Content{{Type: "audio", Data: "aGk=", MimeType: "audio/wav"}}}}, + {"Result", "a watch without a pattern", Result{Content: []Content{}, Meta: &ResultMeta{Watch: &Watch{ID: "r1", Until: until, Tool: "g"}}}}, + {"Op", "no ID", Op{Op: "unwatch", Chat: chatID, Watch: "r1"}}, + {"Op", "an unknown op", Op{ID: "1", Op: "delete", Chat: chatID}}, + {"Op", "a post without a chat", Op{ID: "1", Op: "post", Text: "hi"}}, + {"Op", "an empty post", Op{ID: "1", Op: "post", Chat: chatID}}, + {"Op", "three images", Op{ID: "1", Op: "post", Chat: chatID, Images: slices.Repeat([]Image{{Data: "aGk=", MimeType: "image/png"}}, MaxImages+1)}}, + {"Op", "an image without its type", map[string]any{"id": "1", "op": "post", "chat": chatID, "images": []any{map[string]any{"data": "aGk="}}}}, + {"Op", "a reaction without an emoji", Op{ID: "1", Op: "react", Ref: refID}}, + {"Op", "a reaction to a chat", Op{ID: "1", Op: "react", Ref: chatID, Emoji: "🎯"}}, + {"Op", "an unwatch without its watch", Op{ID: "1", Op: "unwatch", Chat: chatID}}, + {"Op", "a group ID for a chat", Op{ID: "1", Op: "unwatch", Chat: "group.abc=", Watch: "r1"}}, + {"Page", "no cursor", map[string]any{"more": false, "ops": []any{}}}, + {"Page", "a bad op", Page{Cursor: "x.1", Ops: []Op{{ID: "1", Op: "post"}}}}, + {"Held", "no time", map[string]any{"op": post}}, + {"ToolMeta", "an unknown caller", map[string]any{KeyVisibility: []string{"everyone"}}}, + } + for _, c := range invalid { + if check(t, root, c.def, c.v) == nil { + t.Errorf("%s (%s) passed", c.def, c.why) + } + } +} + +// What a Server really writes is valid: its tools' _meta, a tool's result +// with a watch, and an outbox page. +func TestSchemaServer(t *testing.T) { + root := schema(t) + until := time.Now().Add(time.Minute).Format(time.RFC3339) + var s *Server + s = New(Config{Name: "game", Tools: []Tool{{ + Name: "start", Visibility: []string{"bot"}, + Call: func(_ context.Context, c *Context, _ json.RawMessage) (Result, error) { + if err := s.Queue(Op{Op: "post", Chat: c.Chat, Text: "{" + c.Sender + "} started"}, + Op{Op: "react", Ref: c.Ref, Emoji: "🎲"}, Op{Op: "unwatch", Chat: c.Chat, Watch: "r1"}); err != nil { + return Result{}, err + } + r := Text("started") + r.Meta = &ResultMeta{Watch: &Watch{ID: "r1", Pattern: `\bguess \d+`, Until: until, Tool: "start"}} + return r, nil + }, + }}}) + c := start(t, s) + var init struct { + Capabilities struct { + Experimental map[string]any `json:"experimental"` + } `json:"capabilities"` + } + c.result("initialize", map[string]any{"protocolVersion": Protocol, "capabilities": map[string]any{ + "experimental": map[string]any{KeyAddon: Capability{Version: Version, Network: "telegram"}}}}, &init) + if err := validate(root, map[string]any{"$ref": "#/$defs/Capability"}, init.Capabilities.Experimental[KeyAddon], "Capability"); err != nil { + t.Error(err) + } + var list struct { + Tools []struct { + Meta any `json:"_meta"` + } `json:"tools"` + } + c.result("tools/list", struct{}{}, &list) + for _, tl := range list.Tools { + if err := validate(root, map[string]any{"$ref": "#/$defs/ToolMeta"}, tl.Meta, "ToolMeta"); err != nil { + t.Error(err) + } + } + var res any + c.result("tools/call", map[string]any{"name": "start", "arguments": map[string]any{}, + "_meta": map[string]any{KeyContext: Context{Chat: chatID, Sender: senderID, Ref: refID, Sent: 1}}}, &res) + if err := validate(root, map[string]any{"$ref": "#/$defs/Result"}, res, "Result"); err != nil { + t.Error(err) + } + var read struct { + Contents []resourceContent + } + c.result("resources/read", uriParams{OutboxURI + "/0"}, &read) + var page any + if len(read.Contents) != 1 || json.Unmarshal([]byte(read.Contents[0].Text), &page) != nil { + t.Fatalf("read %+v", read) + } + if err := validate(root, map[string]any{"$ref": "#/$defs/Page"}, page, "Page"); err != nil { + t.Error(err) + } + if ops := page.(map[string]any)["ops"].([]any); len(ops) != 3 { + t.Errorf("ops %v", ops) + } + for _, h := range s.Outbox() { + if err := check(t, root, "Held", h); err != nil { + t.Error(err) + } + } +} diff --git a/addon/types.go b/addon/types.go index 53fb19c..9e21d8c 100644 --- a/addon/types.go +++ b/addon/types.go @@ -7,7 +7,8 @@ // // The bot's mcp feature and an addon both use these types, so the // protocol is defined once. An addon in another language implements the -// same JSON. The package uses only the standard library. +// same JSON, which schema.json, a JSON Schema kept in step with these types +// by a test, describes. The package uses only the standard library. package addon import "time" diff --git a/docs/FILES_LINKS_TOOLS_MCP.md b/docs/FILES_LINKS_TOOLS_MCP.md index 015de41..3fb9482 100644 --- a/docs/FILES_LINKS_TOOLS_MCP.md +++ b/docs/FILES_LINKS_TOOLS_MCP.md @@ -100,7 +100,7 @@ A server that can't be reached at startup is logged and left out. A config error An addon is a local MCP server that does more than offer tools: it answers its own commands without the model, reads the messages it asks for, and posts and reacts when it likes. [GeoGuess](https://github.com/robdevops/chat-plugin-geoguess), a photo-guessing game, is one. It is still an ordinary MCP server (protocol 2025-06-18 over stdio), which also speaks signalbot's small extension, under keys starting `io.github.robdevops.signalbot/`. A server is an addon when it has an `addon` block in the MCP file and says it speaks the extension when the bot connects; one with the block that doesn't runs as a plain server, with a warning. Addons run even with [no model](MODELS.md#no-model). -An addon written in Go can use the package [`github.com/robdevops/signalbot/addon`](../addon), which has the extension's types and a ready stdio server: give it the tools, and queue posts, reactions and the end of a watch with `Queue`. [GeoGuess](https://github.com/robdevops/chat-plugin-geoguess) is built on it. An addon in another language speaks the same JSON, described below. +An addon written in Go can use the package [`github.com/robdevops/signalbot/addon`](../addon), which has the extension's types and a ready stdio server: give it the tools, and queue posts, reactions and the end of a watch with `Queue`. [GeoGuess](https://github.com/robdevops/chat-plugin-geoguess) is built on it. An addon in another language speaks the same JSON, described below and, message by message, in the JSON Schema [`addon/schema.json`](../addon/schema.json), which it can validate what it sends against. **An addon is trusted code.** It runs as the bot's user, inside the same systemd or Docker sandbox, and could read what that user can. The bot gives it as little as it can (below), but that guards against bugs and leaks, not a hostile program: install only addons you would let run as the bot. diff --git a/internal/features/mcp/addon_test.go b/internal/features/mcp/addon_test.go index fe78634..9609111 100644 --- a/internal/features/mcp/addon_test.go +++ b/internal/features/mcp/addon_test.go @@ -656,3 +656,46 @@ func alive(pid int) bool { _, after, _ := strings.Cut(string(stat), ") ") return !strings.HasPrefix(after, "Z") } + +// The pseudonyms and refs the bot makes, and the context it sends, are as +// addon/schema.json, the extension's schema for addons in any language, +// says. +func TestPseudonymsMatchSchema(t *testing.T) { + data, err := os.ReadFile("../../../addon/schema.json") + if err != nil { + t.Fatal(err) + } + var s struct { + Defs struct { + Context struct { + Properties map[string]struct { + Pattern string `json:"pattern"` + } `json:"properties"` + } `json:"Context"` + } `json:"$defs"` + } + if err := json.Unmarshal(data, &s); err != nil { + t.Fatal(err) + } + a := newAddon("game", "Game", addonConfig{}, bytes.Repeat([]byte{7}, secretSize), nil, nil) + g := newAddon("game", "Game", addonConfig{GlobalIDs: true}, bytes.Repeat([]byte{7}, secretSize), nil, nil) + c := a.context(in(inA, "/play"), time.Now()) + for key, ids := range map[string][]string{ + "chat": {c.Chat, a.chatID(inB)}, + "sender": {c.Sender, g.userID(inA, "bob-id")}, + "ref": {c.Ref}, + } { + re, err := regexp.Compile(s.Defs.Context.Properties[key].Pattern) + if err != nil || s.Defs.Context.Properties[key].Pattern == "" { + t.Fatalf("the schema's %s pattern: %v", key, err) + } + for _, id := range ids { + if !re.MatchString(id) { + t.Errorf("%s %q doesn't match the schema's %s", key, id, re) + } + } + } + if !placeholder.MatchString("{" + c.Sender + "}") { + t.Error("a sender's placeholder isn't filled in") + } +} From 588ced52c01ea1208142d059bcdf913656497967 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 21 Nov 2026 00:40:27 +0000 Subject: [PATCH 17/26] addon schema: fixes from review; an addon's merged posts are never cut - The bot merged posts held in a chat while their pictures fit, then cut the joined text to 4,000 characters, so a later post could lose its end while counting as sent. They now merge only while the texts fit whole too. - schema.json: a post needs non-blank text or at least one image, as the bot drops one with neither; a text block needs its text, as MCP's TextContent does, and addon.Content now always writes it; react is a watch's call's only; the watch's ID and pattern limits are bytes, which maxLength can't check past ASCII. - schema_test.go: every struct in types.go must be checked; the react key and the pseudonym patterns in Op are tied too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- TECHNICAL.md | 2 +- addon/schema.json | 11 ++++---- addon/schema_test.go | 43 ++++++++++++++++++++++++++--- addon/types.go | 20 ++++++++++++-- internal/features/mcp/outbox.go | 14 +++++++--- internal/features/mcp/watch_test.go | 30 ++++++++++++++++++++ 6 files changed, 104 insertions(+), 16 deletions(-) diff --git a/TECHNICAL.md b/TECHNICAL.md index 27ec456..5f66a96 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -247,7 +247,7 @@ In `features.go` order, which is the order hooks run in and of the tools line an - **Direct commands:** a chat command with `direct` makes `/name args` a call the bot makes itself, without the model, to a tool whose visibility has `"bot"` (looked up among all the server's tools; one without it is skipped with a warning), with `{"args": "<text after the command>"}`. It runs in the message's slot, with 15s or the command's `timeout` (1s to 2m, only on a direct command), and at most 2 at once per server, each held for as long as its call runs: a third is told "<title> is busy, try again in a moment." at once. The title is the server's `serverInfo.title`, else its name, made safe. In a chat its `chats` or `dms` don't allow, it answers "/name isn't available in this chat.". The result's text parts, joined, become the `Answer` (placeholders filled in, capped at 4,000 characters) and its image parts up to 2 `Pictures`, 2 MB together after `img.Safe` (any left out are counted in a warning); a result with neither is `Done`. An error result, a timeout, a bad result or a server that can't be reached answers "<title> couldn't do that just now.". Each call logs the command, the tool, the outcome (ok, or a code), the time and the result's size. Direct commands are kept with no model or one that can't call tools; a server with no tool for the model lists them with `ListCommands` under its label. - **Watches:** a direct command's result may ask, in `_meta["io.github.robdevops.signalbot/watch"]`, for a watch on the chat the command came from (the only way to make one, so an addon can't watch a chat it wasn't used in): an `id` (at most 64 bytes), an RE2 `pattern` (at most 1 KB), `until` (RFC 3339, cut to `watch_max` from now and never extended), the `tool` to call with each match (one the bot may call) and an optional `guard` (at most 500 characters). It needs `watch`, and at most 8 are live in a chat per addon (one with the same ID is replaced). A pattern that matches the empty string or any of about 200 ordinary chat lines in `corpus.go` is refused, so no watch is a feed of the chat; a refusal is logged by reason, never the pattern. One `OnMessage` hook, registered after the chat commands, checks each message with text in an allowed chat against the chat's live watches, on both paths: unaddressed ones on the reader goroutine (only a map lookup and the patterns, under a mutex held briefly), addressed ones (a reply to the bot, a DM, an @mention, a command) in their slot. A watch matches any message the bot gets while it lasts, by when the bot got it, not by its `Timestamp` (on Signal the sender's clock, which may be behind); an edit, unless its original was claimed, only if its original's `Timestamp` is at or after the command's, so an older message's edit isn't taken. An addressed message with no text (a bare mention, or a reply with only a picture) is still checked for the guard. A match is `Done`, so it is never answered, sent to the model or kept in history, and `groupctx` never sees it; it is claimed for 48 hours (chat key, sender's pseudonym, sent time), so a later edit of it goes the same way, to the same tool, whether or not the watch is still live; and it is passed without waiting to the addon's watch worker, whose queue holds 256 (when full, "addon <name>: watch queue full, a matched message dropped", still `Done`). The worker calls the watch's tool with `{"text": …}` and the context, within 120 calls a minute per chat (bursts of 20; a match past it waits its turn in the worker's queue, while other chats' matches go ahead), and keeps a match whose call found the server down (not running, or exited before answering) at the head of the queue until the server has started again (or a minute has passed), dropping it with a warning after 3 such calls, and if the result's `_meta["io.github.robdevops.signalbot/react"]` is one emoji, reacts with it (`React`), which needs `react` and counts against the addon's rate. A watch whose command answered with pictures records, through `OnSent`, the timestamps of the messages they went out in; while it lives, an addressed message quoting one of them gets the `guard` as its `Answer`, so nobody can ask the model about the picture. - **Leases:** an addon may post or react only in a chat where it had a direct command or a watch match in the last 24 hours; the lease maps the chat's pseudonym to the chat. - - **Outbox:** if the server advertises `resources.subscribe`, the bot sends `resources/subscribe` for `signalbot://outbox` after each (re)start's `initialize`, then reads it; otherwise the outbox is off, with a warning. Any `notifications/resources/updated` from the server marks the outbox as having news (whatever the URI, which may be under the one subscribed). One reader goroutine per addon reads `resources/read` of `signalbot://outbox/<cursor>` (`0` at first), page by page while `more` is true, up to 100 pages, so two reads never race and news during a read is read after it. A page is one text content holding `{"cursor", "more", "ops"}`; a not-found error (-32002, or the Go SDK's -32602) is logged as no outbox. Ops are applied once each by `id`, the last 1,000 IDs remembered, and are `post` (`chat`, Markdown `text` with placeholders, up to 2 `images` as `{data, mimeType, name}`, 2 MB together), needing `post`; `react` (`ref`, `emoji`), needing `react`; and `unwatch` (`chat`, `watch`), which, for a watch not yet made, stops it being made for 10 minutes. A post or reaction needs a live lease in a chat the addon is still allowed, and counts against `rate` per chat. A post goes through `Post` with the addon's title as its `Label`, so history keeps it as `[Title] …`, the bot's own words. At most one of an addon's posts waits in a chat's mailbox: until its `OnSent`, later posts for that chat are held, each merged into the one held before it while their pictures together stay within 2 and 2 MB, and sent in turn. Delivery is at least once: a post counts as applied, and the cursor moves past it, only once its `OnSent` says it was sent. A send that fails counts as dropped, so a post whose send timed out after it went out may be posted twice, rather than lost. Until then each read starts from the cursor before it and skips it while it waits; one dropped before it was sent (as while the bot stops, or before the network is up at startup, when `Post` gives up on the chat) is posted again by a read 10s later, then 20s, doubling to 5 minutes, not counted against `rate` again, and given up with a warning after 6 tries. A page with `more` waits for its posts before the next is read, since reading past the cursor lets the addon forget them. A read that fails, is malformed, or stops at 100 pages is tried again after 10s, doubling to 5 minutes, without waiting for news. What a read drops is counted in one warning by reason, never content. + - **Outbox:** if the server advertises `resources.subscribe`, the bot sends `resources/subscribe` for `signalbot://outbox` after each (re)start's `initialize`, then reads it; otherwise the outbox is off, with a warning. Any `notifications/resources/updated` from the server marks the outbox as having news (whatever the URI, which may be under the one subscribed). One reader goroutine per addon reads `resources/read` of `signalbot://outbox/<cursor>` (`0` at first), page by page while `more` is true, up to 100 pages, so two reads never race and news during a read is read after it. A page is one text content holding `{"cursor", "more", "ops"}`; a not-found error (-32002, or the Go SDK's -32602) is logged as no outbox. Ops are applied once each by `id`, the last 1,000 IDs remembered, and are `post` (`chat`, Markdown `text` with placeholders, up to 2 `images` as `{data, mimeType, name}`, 2 MB together), needing `post`; `react` (`ref`, `emoji`), needing `react`; and `unwatch` (`chat`, `watch`), which, for a watch not yet made, stops it being made for 10 minutes. A post or reaction needs a live lease in a chat the addon is still allowed, and counts against `rate` per chat. A post goes through `Post` with the addon's title as its `Label`, so history keeps it as `[Title] …`, the bot's own words. At most one of an addon's posts waits in a chat's mailbox: until its `OnSent`, later posts for that chat are held, each merged into the one held before it while their pictures together stay within 2 and 2 MB and their texts together within 4,000 characters, so a merge never cuts one, and sent in turn. Delivery is at least once: a post counts as applied, and the cursor moves past it, only once its `OnSent` says it was sent. A send that fails counts as dropped, so a post whose send timed out after it went out may be posted twice, rather than lost. Until then each read starts from the cursor before it and skips it while it waits; one dropped before it was sent (as while the bot stops, or before the network is up at startup, when `Post` gives up on the chat) is posted again by a read 10s later, then 20s, doubling to 5 minutes, not counted against `rate` again, and given up with a warning after 6 tries. A page with `more` waits for its posts before the next is read, since reading past the cursor lets the addon forget them. A read that fails, is malformed, or stops at 100 pages is tried again after 10s, doubling to 5 minutes, without waiting for news. What a read drops is counted in one warning by reason, never content. - **What is saved,** per addon, in `mcp.json`: live watches (with their guard pictures' timestamps), claims, leases, the outbox cursor and the last 1,000 applied op IDs. Anything expired is left out. At startup they are restored, leaving out a watch whose chat is no longer allowed or whose pattern no longer passes, so a restart of the bot or the addon never lets a match fall through to history. Refs, names, tombstones and held posts are in memory only. - **`groupctx`** (`GROUP_CONTEXT`, on by default) comes after `mcp`, so an earlier hook can claim a message (`Done`) before it is kept, and keeps each other unaddressed group message as context: `Name: text`, capped at 2,000 characters, with photos, stickers and files noted as `[image]`, `[sticker]` and `[file "name"]` but never fetched. The core keeps it like any history entry, marked as context, and never logs it. - **`schedule`** is `/schedule` ([below](#schedule)). diff --git a/addon/schema.json b/addon/schema.json index e008324..698a213 100644 --- a/addon/schema.json +++ b/addon/schema.json @@ -44,8 +44,8 @@ "description": "A direct command's result's _meta[\"io.github.robdevops.signalbot/watch\"]: the messages matching pattern in the command's chat, until until, go to tool instead of the model. The bot refuses a pattern that would match ordinary chat, and shortens until to the addon block's watch_max.", "type": "object", "properties": { - "id": {"description": "The watch's name, for an unwatch op; at most 64 bytes. A new watch with the ID of a live one in the chat replaces it.", "type": "string", "minLength": 1, "maxLength": 64}, - "pattern": {"description": "An RE2 regular expression, at most 1 KB.", "type": "string", "minLength": 1, "maxLength": 1024}, + "id": {"description": "The watch's name, for an unwatch op; at most 64 bytes of UTF-8, which maxLength, counting characters, can't check past ASCII. A new watch with the ID of a live one in the chat replaces it.", "type": "string", "minLength": 1, "maxLength": 64}, + "pattern": {"description": "An RE2 regular expression, at most 1024 bytes of UTF-8, which maxLength, counting characters, can't check past ASCII.", "type": "string", "minLength": 1, "maxLength": 1024}, "until": {"description": "An RFC 3339 time, in the future.", "type": "string", "format": "date-time"}, "tool": {"description": "A tool for the bot, called with each message the watch takes, as {\"text\": …}, with its context.", "type": "string", "minLength": 1}, "guard": {"description": "While the watch lasts, the answer to a message addressed to the bot that replies to the command's pictures; at most 500 characters.", "type": "string", "maxLength": 500} @@ -64,6 +64,7 @@ }, "required": ["type"], "allOf": [ + {"if": {"properties": {"type": {"const": "text"}}}, "then": {"required": ["text"]}}, {"if": {"properties": {"type": {"const": "image"}}}, "then": {"required": ["data", "mimeType"]}} ] }, @@ -82,7 +83,7 @@ "type": "object", "properties": { "io.github.robdevops.signalbot/watch": {"description": "A direct command's only.", "$ref": "#/$defs/Watch"}, - "io.github.robdevops.signalbot/react": {"description": "One emoji, for the message the call came from.", "type": "string", "minLength": 1} + "io.github.robdevops.signalbot/react": {"description": "A watch's call's only: one emoji, for the message the watch took. Ignored on any other call; to react to a command, queue a react op with its context's ref.", "type": "string", "minLength": 1} } }, "Op": { @@ -92,7 +93,7 @@ "id": {"description": "Unique among the addon's ops, for as long as the bot may read it again.", "type": "string", "minLength": 1}, "op": {"enum": ["post", "react", "unwatch"]}, "chat": {"description": "A post's or unwatch's chat.", "type": "string", "pattern": "^c_[a-z2-7]{26}$"}, - "text": {"description": "A post's text, with {u_…} placeholders the bot fills in with names; at most 4000 characters.", "type": "string"}, + "text": {"description": "A post's text, with {u_…} placeholders the bot fills in with names; at most 4000 characters, names filled in. A post with neither text nor images is dropped.", "type": "string"}, "images": {"description": "A post's images: at most 2, and 2 MiB in all.", "type": "array", "items": {"$ref": "#/$defs/Image"}, "maxItems": 2}, "ref": {"description": "The message a reaction is for: a context's ref.", "type": "string", "pattern": "^r_[a-z2-7]{26}$"}, "emoji": {"description": "A reaction's: one emoji.", "type": "string", "minLength": 1}, @@ -101,7 +102,7 @@ "required": ["id", "op"], "additionalProperties": false, "allOf": [ - {"if": {"properties": {"op": {"const": "post"}}}, "then": {"required": ["chat"], "anyOf": [{"required": ["text"]}, {"required": ["images"]}]}}, + {"if": {"properties": {"op": {"const": "post"}}}, "then": {"required": ["chat"], "anyOf": [{"required": ["text"], "properties": {"text": {"pattern": "\\S"}}}, {"required": ["images"], "properties": {"images": {"minItems": 1}}}]}}, {"if": {"properties": {"op": {"const": "react"}}}, "then": {"required": ["ref", "emoji"]}}, {"if": {"properties": {"op": {"const": "unwatch"}}}, "then": {"required": ["chat", "watch"]}} ] diff --git a/addon/schema_test.go b/addon/schema_test.go index 0a224ae..c60340d 100644 --- a/addon/schema_test.go +++ b/addon/schema_test.go @@ -4,6 +4,9 @@ import ( "context" "encoding/json" "fmt" + "go/ast" + "go/parser" + "go/token" "os" "reflect" "regexp" @@ -57,12 +60,27 @@ var wireTypes = map[string]reflect.Type{ // same type for each. func TestSchemaMatchesTypes(t *testing.T) { d := defs(t, schema(t)) - var names []string for name := range d { if _, ok := wireTypes[name]; !ok && name != "ToolMeta" { t.Errorf("$defs/%s has no Go type", name) } - names = append(names, name) + } + // Every struct types.go declares is in wireTypes, so in the schema. + f, err := parser.ParseFile(token.NewFileSet(), "types.go", nil, 0) + if err != nil { + t.Fatal(err) + } + for _, decl := range f.Decls { + g, ok := decl.(*ast.GenDecl) + if !ok || g.Tok != token.TYPE { + continue + } + for _, spec := range g.Specs { + ts := spec.(*ast.TypeSpec) + if _, isStruct := ts.Type.(*ast.StructType); isStruct && ts.Name.IsExported() && wireTypes[ts.Name.Name] == nil { + t.Errorf("types.go's %s isn't in wireTypes, so the schema isn't checked for it", ts.Name.Name) + } + } } for name, typ := range wireTypes { def, ok := d[name].(map[string]any) @@ -113,11 +131,20 @@ func TestSchemaMatchesTypes(t *testing.T) { } } // The _meta keys are the package's. - for def, key := range map[string]string{"ToolMeta": KeyVisibility, "ResultMeta": KeyWatch} { + for key, def := range map[string]string{KeyVisibility: "ToolMeta", KeyWatch: "ResultMeta", KeyReact: "ResultMeta"} { if _, ok := d[def].(map[string]any)["properties"].(map[string]any)[key]; !ok { t.Errorf("$defs/%s lacks %s", def, key) } } + // A pseudonym's pattern is the same wherever it appears. + prop := func(def, key string) any { + return d[def].(map[string]any)["properties"].(map[string]any)[key].(map[string]any)["pattern"] + } + for _, k := range []string{"chat", "ref"} { + if prop("Op", k) != prop("Context", k) { + t.Errorf("Op's %s pattern %v isn't Context's %v", k, prop("Op", k), prop("Context", k)) + } + } if v := d["Capability"].(map[string]any)["properties"].(map[string]any)["version"].(map[string]any)["const"]; v != float64(Version) { t.Errorf("the schema's version is %v; the package's %d", v, Version) } @@ -223,6 +250,10 @@ func validate(root, s map[string]any, v any, at string) error { if n, ok := v.(float64); ok && n < kv.(float64) { return fmt.Errorf("%s: %v under %v", at, n, kv) } + case "minItems": + if l, ok := v.([]any); ok && float64(len(l)) < kv.(float64) { + return fmt.Errorf("%s: %d items, at least %v", at, len(l), kv) + } case "maxItems": if l, ok := v.([]any); ok && float64(len(l)) > kv.(float64) { return fmt.Errorf("%s: %d items, at most %v", at, len(l), kv) @@ -362,7 +393,8 @@ func TestSchemaSamples(t *testing.T) { {"Context", Context{Chat: chatID, Sender: senderID, Ref: refID, Sent: 1763715600, Edited: 1763715660, Name: "Alice", Deadline: 1763715615}}, {"Watch", Watch{ID: "r1", Pattern: `maps\.google`, Until: until, Tool: "guess", Guard: "No hints 😉"}}, {"Result", Text("started")}, - {"Result", Text("")}, + {"Result", Text("")}, // MCP's TextContent needs its text, even empty + {"Op", Op{ID: "5", Op: "post", Chat: chatID, Text: "", Images: []Image{{Data: "aGk=", MimeType: "image/png"}}}}, {"Result", Result{Content: []Content{{Type: "image", Data: "aGk=", MimeType: "image/jpeg"}, {Type: "text", Text: "go"}}, Meta: &ResultMeta{Watch: &Watch{ID: "r1", Pattern: `\d`, Until: until, Tool: "guess"}}}}, {"Result", Result{Content: []Content{{Type: "text", Text: "no"}}, IsError: true, Meta: &ResultMeta{React: "📍"}}}, @@ -392,12 +424,15 @@ func TestSchemaSamples(t *testing.T) { {"Watch", "a misspelt key", map[string]any{"id": "r1", "pattern": `\d`, "until": until, "tool": "guess", "gaurd": "x"}}, {"Watch", "too long an ID", Watch{ID: strings.Repeat("x", 65), Pattern: `\d`, Until: until, Tool: "guess"}}, {"Result", "an image without its bytes", Result{Content: []Content{{Type: "image", MimeType: "image/jpeg"}}}}, + {"Result", "a text block without its text", map[string]any{"content": []any{map[string]any{"type": "text"}}}}, {"Result", "audio", Result{Content: []Content{{Type: "audio", Data: "aGk=", MimeType: "audio/wav"}}}}, {"Result", "a watch without a pattern", Result{Content: []Content{}, Meta: &ResultMeta{Watch: &Watch{ID: "r1", Until: until, Tool: "g"}}}}, {"Op", "no ID", Op{Op: "unwatch", Chat: chatID, Watch: "r1"}}, {"Op", "an unknown op", Op{ID: "1", Op: "delete", Chat: chatID}}, {"Op", "a post without a chat", Op{ID: "1", Op: "post", Text: "hi"}}, {"Op", "an empty post", Op{ID: "1", Op: "post", Chat: chatID}}, + {"Op", "a post of empty text", map[string]any{"id": "1", "op": "post", "chat": chatID, "text": " \n"}}, + {"Op", "a post of no images", map[string]any{"id": "1", "op": "post", "chat": chatID, "images": []any{}}}, {"Op", "three images", Op{ID: "1", Op: "post", Chat: chatID, Images: slices.Repeat([]Image{{Data: "aGk=", MimeType: "image/png"}}, MaxImages+1)}}, {"Op", "an image without its type", map[string]any{"id": "1", "op": "post", "chat": chatID, "images": []any{map[string]any{"data": "aGk="}}}}, {"Op", "a reaction without an emoji", Op{ID: "1", Op: "react", Ref: refID}}, diff --git a/addon/types.go b/addon/types.go index 9e21d8c..1d45064 100644 --- a/addon/types.go +++ b/addon/types.go @@ -11,7 +11,10 @@ // by a test, describes. The package uses only the standard library. package addon -import "time" +import ( + "encoding/json" + "time" +) // The protocol: the MCP version, the prefix of every key of the extension, // the extension's version, and the outbox's URI. @@ -76,6 +79,19 @@ type Content struct { MimeType string `json:"mimeType,omitempty"` } +// MarshalJSON writes a text block's text even when it is empty, as MCP's +// TextContent requires. +func (c Content) MarshalJSON() ([]byte, error) { + type plain Content + if c.Type != "text" { + return json.Marshal(plain(c)) + } + return json.Marshal(struct { + plain + Text string `json:"text"` + }{plain(c), c.Text}) +} + // Result is a tool's result. type Result struct { Content []Content `json:"content"` @@ -86,7 +102,7 @@ type Result struct { // ResultMeta is what a result asks of the bot besides its content. type ResultMeta struct { Watch *Watch `json:"io.github.robdevops.signalbot/watch,omitempty"` // a direct command's only - React string `json:"io.github.robdevops.signalbot/react,omitempty"` // an emoji for the message the call came from + React string `json:"io.github.robdevops.signalbot/react,omitempty"` // a watch's call's only: an emoji for the message it took } // Text is a result of words alone. diff --git a/internal/features/mcp/outbox.go b/internal/features/mcp/outbox.go index de849a0..6f1bed2 100644 --- a/internal/features/mcp/outbox.go +++ b/internal/features/mcp/outbox.go @@ -10,6 +10,7 @@ import ( "slices" "strings" "time" + "unicode/utf8" ext "github.com/robdevops/signalbot/addon" "github.com/robdevops/signalbot/internal/feature" @@ -292,18 +293,23 @@ type outgoing struct { ops []string } -// fits reports whether p's pictures can join o's in one post. +// fits reports whether p can join o in one post: their pictures, and +// their texts whole, so a merge never cuts a post that fit on its own. func (o *outgoing) fits(p *outgoing) bool { size := 0 for _, pic := range append(slices.Clone(o.Pictures), p.Pictures...) { size += len(pic.Data) } - return len(o.Pictures)+len(p.Pictures) <= maxAddonPictures && size <= maxPictureBytes + return len(o.Pictures)+len(p.Pictures) <= maxAddonPictures && size <= maxPictureBytes && + utf8.RuneCountInString(merged(o.Text, p.Text)) <= maxAnswer } +// merged is two posts' texts as one. +func merged(a, b string) string { return strings.TrimSpace(a + "\n\n" + b) } + // send posts out in the chat whose pseudonym is id, unless a post of the // addon's still waits in that chat's mailbox: then out is held, merged with -// the last one held if their pictures fit in one post, and posted once +// the last one held if they fit in one post, and posted once // those before it have gone. So an addon never takes more than one place in // a chat's mailbox. func (a *addon) send(id string, out *outgoing) { @@ -314,7 +320,7 @@ func (a *addon) send(id string, out *outgoing) { if held, waiting := a.waiting[id]; waiting { if n := len(held); n > 0 && held[n-1].fits(out) { last := held[n-1] - last.Text = txt.Clamp(strings.TrimSpace(last.Text+"\n\n"+out.Text), maxAnswer) + last.Text = merged(last.Text, out.Text) last.Pictures = append(last.Pictures, out.Pictures...) last.ops = append(last.ops, out.ops...) } else { diff --git a/internal/features/mcp/watch_test.go b/internal/features/mcp/watch_test.go index 3b8e674..d893488 100644 --- a/internal/features/mcp/watch_test.go +++ b/internal/features/mcp/watch_test.go @@ -15,6 +15,7 @@ import ( "sync" "testing" "time" + "unicode/utf8" ext "github.com/robdevops/signalbot/addon" "github.com/robdevops/signalbot/internal/feature" @@ -634,6 +635,35 @@ func TestOutboxDelivery(t *testing.T) { } } +// Posts held behind one are merged only while their texts fit in one post +// whole: two long ones go one after the other, neither cut. +func TestOutboxMergeKeepsTexts(t *testing.T) { + a, _ := unitAddon(everything) + h := featuretest.New() + a.host = h + a.lease(inA) + id := a.chatID(inA) + long := strings.Repeat("é", 3000) + for i, text := range []string{"first", long, long} { + if why := a.apply(ext.Op{ID: strconv.Itoa(i), Op: "post", Chat: id, Text: text}); why != "" { + t.Fatal(why) + } + } + var texts []string + for i := 0; i < len(h.Posts()); i++ { + texts = append(texts, h.Posts()[i].Text) + h.Posts()[i].OnSent([]int64{int64(i)}, false) + } + if !slices.Equal(texts, []string{"first", long, long}) { + t.Fatalf("%d posts, of %v runes", len(texts), func() (n []int) { + for _, s := range texts { + n = append(n, utf8.RuneCountInString(s)) + } + return + }()) + } +} + // One reader per addon: a burst of news never makes two reads at once, a // read misses nothing that came during it, and news the addon never sent is // read with the next. From 673606bd431c0996d2bf91cf4d7d0dbfd19318e9 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 21 Nov 2026 01:09:53 +0000 Subject: [PATCH 18/26] addon: a watch's ID and pattern limits are characters, as the schema counts The bot measured a watch's ID (64) and pattern (1,024) in bytes, which JSON Schema's maxLength, counting characters, matches only for ASCII: an accented ID passed the schema and was refused. Both are now counted in characters, as the guard already was, so the schema states the bot's rule exactly in any script. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- TECHNICAL.md | 2 +- addon/schema.json | 4 ++-- addon/schema_test.go | 2 ++ internal/features/mcp/keep.go | 3 ++- internal/features/mcp/watch.go | 11 ++++++----- internal/features/mcp/watch_test.go | 27 ++++++++++++++++++++++++++- 6 files changed, 39 insertions(+), 10 deletions(-) diff --git a/TECHNICAL.md b/TECHNICAL.md index 5f66a96..31309bd 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -245,7 +245,7 @@ In `features.go` order, which is the order hooks run in and of the tools line an - **Pseudonyms:** an addon never sees a phone number, account ID or group ID. Each addon has its own key, HMAC-SHA256 of the secret and its server's name. A chat is `c_` and HMAC(key, `chat\0` + chat key); a sender `u_` and HMAC(key, `user\0` + chat key + `\0` + ID), so the same person is someone else in each chat, or with `global_ids` HMAC(key, `user\0` + ID), the same everywhere; each cut to 128 bits and written in lowercase base32. A ref, `r_` and 128 random bits, names one message, for a reaction, and is kept in memory for 24 hours. - **Context:** each `tools/call` the bot makes itself carries the message's context in `_meta["io.github.robdevops.signalbot/context"]`: `chat`, `sender`, `ref`, `addressed`, `group`, `sent` and `edited` (when the bot got the message and its edit, in Unix seconds, never the sender's clock; `edited` is 0 for an original), `name`, the sender's display name, only with `names`, and for a direct command `deadline`, when the bot stops waiting (Unix seconds, rounded down). A call the bot stops waiting for gets `notifications/cancelled` with its `requestId`. Otherwise the bot keeps, in memory for 24 hours, the last name it saw each pseudonym use in the chat: a `{u_…}` placeholder in an addon's answer or post becomes `@Name`, linked as a mention, or "someone". - **Direct commands:** a chat command with `direct` makes `/name args` a call the bot makes itself, without the model, to a tool whose visibility has `"bot"` (looked up among all the server's tools; one without it is skipped with a warning), with `{"args": "<text after the command>"}`. It runs in the message's slot, with 15s or the command's `timeout` (1s to 2m, only on a direct command), and at most 2 at once per server, each held for as long as its call runs: a third is told "<title> is busy, try again in a moment." at once. The title is the server's `serverInfo.title`, else its name, made safe. In a chat its `chats` or `dms` don't allow, it answers "/name isn't available in this chat.". The result's text parts, joined, become the `Answer` (placeholders filled in, capped at 4,000 characters) and its image parts up to 2 `Pictures`, 2 MB together after `img.Safe` (any left out are counted in a warning); a result with neither is `Done`. An error result, a timeout, a bad result or a server that can't be reached answers "<title> couldn't do that just now.". Each call logs the command, the tool, the outcome (ok, or a code), the time and the result's size. Direct commands are kept with no model or one that can't call tools; a server with no tool for the model lists them with `ListCommands` under its label. - - **Watches:** a direct command's result may ask, in `_meta["io.github.robdevops.signalbot/watch"]`, for a watch on the chat the command came from (the only way to make one, so an addon can't watch a chat it wasn't used in): an `id` (at most 64 bytes), an RE2 `pattern` (at most 1 KB), `until` (RFC 3339, cut to `watch_max` from now and never extended), the `tool` to call with each match (one the bot may call) and an optional `guard` (at most 500 characters). It needs `watch`, and at most 8 are live in a chat per addon (one with the same ID is replaced). A pattern that matches the empty string or any of about 200 ordinary chat lines in `corpus.go` is refused, so no watch is a feed of the chat; a refusal is logged by reason, never the pattern. One `OnMessage` hook, registered after the chat commands, checks each message with text in an allowed chat against the chat's live watches, on both paths: unaddressed ones on the reader goroutine (only a map lookup and the patterns, under a mutex held briefly), addressed ones (a reply to the bot, a DM, an @mention, a command) in their slot. A watch matches any message the bot gets while it lasts, by when the bot got it, not by its `Timestamp` (on Signal the sender's clock, which may be behind); an edit, unless its original was claimed, only if its original's `Timestamp` is at or after the command's, so an older message's edit isn't taken. An addressed message with no text (a bare mention, or a reply with only a picture) is still checked for the guard. A match is `Done`, so it is never answered, sent to the model or kept in history, and `groupctx` never sees it; it is claimed for 48 hours (chat key, sender's pseudonym, sent time), so a later edit of it goes the same way, to the same tool, whether or not the watch is still live; and it is passed without waiting to the addon's watch worker, whose queue holds 256 (when full, "addon <name>: watch queue full, a matched message dropped", still `Done`). The worker calls the watch's tool with `{"text": …}` and the context, within 120 calls a minute per chat (bursts of 20; a match past it waits its turn in the worker's queue, while other chats' matches go ahead), and keeps a match whose call found the server down (not running, or exited before answering) at the head of the queue until the server has started again (or a minute has passed), dropping it with a warning after 3 such calls, and if the result's `_meta["io.github.robdevops.signalbot/react"]` is one emoji, reacts with it (`React`), which needs `react` and counts against the addon's rate. A watch whose command answered with pictures records, through `OnSent`, the timestamps of the messages they went out in; while it lives, an addressed message quoting one of them gets the `guard` as its `Answer`, so nobody can ask the model about the picture. + - **Watches:** a direct command's result may ask, in `_meta["io.github.robdevops.signalbot/watch"]`, for a watch on the chat the command came from (the only way to make one, so an addon can't watch a chat it wasn't used in): an `id` (at most 64 characters), an RE2 `pattern` (at most 1,024 characters), `until` (RFC 3339, cut to `watch_max` from now and never extended), the `tool` to call with each match (one the bot may call) and an optional `guard` (at most 500 characters). It needs `watch`, and at most 8 are live in a chat per addon (one with the same ID is replaced). A pattern that matches the empty string or any of about 200 ordinary chat lines in `corpus.go` is refused, so no watch is a feed of the chat; a refusal is logged by reason, never the pattern. One `OnMessage` hook, registered after the chat commands, checks each message with text in an allowed chat against the chat's live watches, on both paths: unaddressed ones on the reader goroutine (only a map lookup and the patterns, under a mutex held briefly), addressed ones (a reply to the bot, a DM, an @mention, a command) in their slot. A watch matches any message the bot gets while it lasts, by when the bot got it, not by its `Timestamp` (on Signal the sender's clock, which may be behind); an edit, unless its original was claimed, only if its original's `Timestamp` is at or after the command's, so an older message's edit isn't taken. An addressed message with no text (a bare mention, or a reply with only a picture) is still checked for the guard. A match is `Done`, so it is never answered, sent to the model or kept in history, and `groupctx` never sees it; it is claimed for 48 hours (chat key, sender's pseudonym, sent time), so a later edit of it goes the same way, to the same tool, whether or not the watch is still live; and it is passed without waiting to the addon's watch worker, whose queue holds 256 (when full, "addon <name>: watch queue full, a matched message dropped", still `Done`). The worker calls the watch's tool with `{"text": …}` and the context, within 120 calls a minute per chat (bursts of 20; a match past it waits its turn in the worker's queue, while other chats' matches go ahead), and keeps a match whose call found the server down (not running, or exited before answering) at the head of the queue until the server has started again (or a minute has passed), dropping it with a warning after 3 such calls, and if the result's `_meta["io.github.robdevops.signalbot/react"]` is one emoji, reacts with it (`React`), which needs `react` and counts against the addon's rate. A watch whose command answered with pictures records, through `OnSent`, the timestamps of the messages they went out in; while it lives, an addressed message quoting one of them gets the `guard` as its `Answer`, so nobody can ask the model about the picture. - **Leases:** an addon may post or react only in a chat where it had a direct command or a watch match in the last 24 hours; the lease maps the chat's pseudonym to the chat. - **Outbox:** if the server advertises `resources.subscribe`, the bot sends `resources/subscribe` for `signalbot://outbox` after each (re)start's `initialize`, then reads it; otherwise the outbox is off, with a warning. Any `notifications/resources/updated` from the server marks the outbox as having news (whatever the URI, which may be under the one subscribed). One reader goroutine per addon reads `resources/read` of `signalbot://outbox/<cursor>` (`0` at first), page by page while `more` is true, up to 100 pages, so two reads never race and news during a read is read after it. A page is one text content holding `{"cursor", "more", "ops"}`; a not-found error (-32002, or the Go SDK's -32602) is logged as no outbox. Ops are applied once each by `id`, the last 1,000 IDs remembered, and are `post` (`chat`, Markdown `text` with placeholders, up to 2 `images` as `{data, mimeType, name}`, 2 MB together), needing `post`; `react` (`ref`, `emoji`), needing `react`; and `unwatch` (`chat`, `watch`), which, for a watch not yet made, stops it being made for 10 minutes. A post or reaction needs a live lease in a chat the addon is still allowed, and counts against `rate` per chat. A post goes through `Post` with the addon's title as its `Label`, so history keeps it as `[Title] …`, the bot's own words. At most one of an addon's posts waits in a chat's mailbox: until its `OnSent`, later posts for that chat are held, each merged into the one held before it while their pictures together stay within 2 and 2 MB and their texts together within 4,000 characters, so a merge never cuts one, and sent in turn. Delivery is at least once: a post counts as applied, and the cursor moves past it, only once its `OnSent` says it was sent. A send that fails counts as dropped, so a post whose send timed out after it went out may be posted twice, rather than lost. Until then each read starts from the cursor before it and skips it while it waits; one dropped before it was sent (as while the bot stops, or before the network is up at startup, when `Post` gives up on the chat) is posted again by a read 10s later, then 20s, doubling to 5 minutes, not counted against `rate` again, and given up with a warning after 6 tries. A page with `more` waits for its posts before the next is read, since reading past the cursor lets the addon forget them. A read that fails, is malformed, or stops at 100 pages is tried again after 10s, doubling to 5 minutes, without waiting for news. What a read drops is counted in one warning by reason, never content. - **What is saved,** per addon, in `mcp.json`: live watches (with their guard pictures' timestamps), claims, leases, the outbox cursor and the last 1,000 applied op IDs. Anything expired is left out. At startup they are restored, leaving out a watch whose chat is no longer allowed or whose pattern no longer passes, so a restart of the bot or the addon never lets a match fall through to history. Refs, names, tombstones and held posts are in memory only. diff --git a/addon/schema.json b/addon/schema.json index 698a213..fc3cdc0 100644 --- a/addon/schema.json +++ b/addon/schema.json @@ -44,8 +44,8 @@ "description": "A direct command's result's _meta[\"io.github.robdevops.signalbot/watch\"]: the messages matching pattern in the command's chat, until until, go to tool instead of the model. The bot refuses a pattern that would match ordinary chat, and shortens until to the addon block's watch_max.", "type": "object", "properties": { - "id": {"description": "The watch's name, for an unwatch op; at most 64 bytes of UTF-8, which maxLength, counting characters, can't check past ASCII. A new watch with the ID of a live one in the chat replaces it.", "type": "string", "minLength": 1, "maxLength": 64}, - "pattern": {"description": "An RE2 regular expression, at most 1024 bytes of UTF-8, which maxLength, counting characters, can't check past ASCII.", "type": "string", "minLength": 1, "maxLength": 1024}, + "id": {"description": "The watch's name, for an unwatch op; at most 64 characters. A new watch with the ID of a live one in the chat replaces it.", "type": "string", "minLength": 1, "maxLength": 64}, + "pattern": {"description": "An RE2 regular expression, at most 1,024 characters.", "type": "string", "minLength": 1, "maxLength": 1024}, "until": {"description": "An RFC 3339 time, in the future.", "type": "string", "format": "date-time"}, "tool": {"description": "A tool for the bot, called with each message the watch takes, as {\"text\": …}, with its context.", "type": "string", "minLength": 1}, "guard": {"description": "While the watch lasts, the answer to a message addressed to the bot that replies to the command's pictures; at most 500 characters.", "type": "string", "maxLength": 500} diff --git a/addon/schema_test.go b/addon/schema_test.go index c60340d..167e939 100644 --- a/addon/schema_test.go +++ b/addon/schema_test.go @@ -392,6 +392,7 @@ func TestSchemaSamples(t *testing.T) { {"Context", Context{Chat: chatID, Sender: senderID, Ref: refID, Addressed: true, Group: true, Sent: 1763715600}}, {"Context", Context{Chat: chatID, Sender: senderID, Ref: refID, Sent: 1763715600, Edited: 1763715660, Name: "Alice", Deadline: 1763715615}}, {"Watch", Watch{ID: "r1", Pattern: `maps\.google`, Until: until, Tool: "guess", Guard: "No hints 😉"}}, + {"Watch", Watch{ID: strings.Repeat("é", 64), Pattern: `\bdevinette \d+`, Until: until, Tool: "guess"}}, {"Result", Text("started")}, {"Result", Text("")}, // MCP's TextContent needs its text, even empty {"Op", Op{ID: "5", Op: "post", Chat: chatID, Text: "", Images: []Image{{Data: "aGk=", MimeType: "image/png"}}}}, @@ -423,6 +424,7 @@ func TestSchemaSamples(t *testing.T) { {"Watch", "no tool", Watch{ID: "r1", Pattern: `\d`, Until: until}}, {"Watch", "a misspelt key", map[string]any{"id": "r1", "pattern": `\d`, "until": until, "tool": "guess", "gaurd": "x"}}, {"Watch", "too long an ID", Watch{ID: strings.Repeat("x", 65), Pattern: `\d`, Until: until, Tool: "guess"}}, + {"Watch", "too long an ID, accented", Watch{ID: strings.Repeat("é", 65), Pattern: `\d`, Until: until, Tool: "guess"}}, {"Result", "an image without its bytes", Result{Content: []Content{{Type: "image", MimeType: "image/jpeg"}}}}, {"Result", "a text block without its text", map[string]any{"content": []any{map[string]any{"type": "text"}}}}, {"Result", "audio", Result{Content: []Content{{Type: "audio", Data: "aGk=", MimeType: "audio/wav"}}}}, diff --git a/internal/features/mcp/keep.go b/internal/features/mcp/keep.go index 948aa7c..57dd1fa 100644 --- a/internal/features/mcp/keep.go +++ b/internal/features/mcp/keep.go @@ -7,6 +7,7 @@ import ( "regexp" "slices" "strings" + "unicode/utf8" "github.com/robdevops/signalbot/internal/feature" "github.com/robdevops/signalbot/internal/kit/logx" @@ -151,7 +152,7 @@ func (a *addon) restore(s addonState) { for _, w := range s.Watches { l, ok := a.leases[w.Chat] re, err := regexp.Compile(w.Pattern) - if !ok || !now.Before(w.Until) || !a.allows(l.Chat) || err != nil || len(w.Pattern) > maxPattern || ordinary(re) || + if !ok || !now.Before(w.Until) || !a.allows(l.Chat) || err != nil || utf8.RuneCountInString(w.Pattern) > maxPattern || ordinary(re) || len(a.watches[l.Chat.Key()]) >= maxWatches { continue } diff --git a/internal/features/mcp/watch.go b/internal/features/mcp/watch.go index 43cb116..4ac9ecc 100644 --- a/internal/features/mcp/watch.go +++ b/internal/features/mcp/watch.go @@ -9,6 +9,7 @@ import ( "strings" "sync" "time" + "unicode/utf8" ext "github.com/robdevops/signalbot/addon" "github.com/robdevops/signalbot/internal/feature" @@ -19,8 +20,8 @@ import ( // A watch's limits. const ( maxWatches = 8 // live in one chat, per addon - maxPattern = 1 << 10 // a pattern's size, in bytes - maxWatchID = 64 // an ID's size, in bytes + maxPattern = 1 << 10 // a pattern's size, in characters, as addon/schema.json counts + maxWatchID = 64 // an ID's size, in characters maxGuard = 500 // a guard's size, in runes maxMatches = 256 // matched messages waiting for the watch worker, per addon claimLife = 48 * time.Hour @@ -111,12 +112,12 @@ func (a *addon) watch(m feature.Message, spec ext.Watch) *watch { switch { case !a.cfg.Watch: return refuse("the addon block doesn't allow watch") - case spec.ID == "" || len(spec.ID) > maxWatchID: + case spec.ID == "" || utf8.RuneCountInString(spec.ID) > maxWatchID: return refuse("its id is empty or too long") case !a.bot[spec.Tool]: return refuse("its tool isn't one the bot may call") - case len(spec.Pattern) > maxPattern: - return refuse("its pattern is over 1 KB") + case utf8.RuneCountInString(spec.Pattern) > maxPattern: + return refuse("its pattern is over 1,024 characters") case err != nil: return refuse("its until isn't an RFC 3339 time") case !until.After(now): diff --git a/internal/features/mcp/watch_test.go b/internal/features/mcp/watch_test.go index d893488..630ead0 100644 --- a/internal/features/mcp/watch_test.go +++ b/internal/features/mcp/watch_test.go @@ -357,7 +357,7 @@ func TestWatchRefused(t *testing.T) { t.Fatalf("a refused watch took a message: %+v", got) } for _, want := range []string{"its pattern matches ordinary chat", "its pattern isn't RE2", "its tool isn't one the bot may call", - "its until isn't an RFC 3339 time", "its pattern is over 1 KB"} { + "its until isn't an RFC 3339 time", "its pattern is over 1,024 characters"} { if !strings.Contains(log.String(), "<4>MCP server game: a watch refused: "+want+"\n") { t.Errorf("log %q, want %q", log.String(), want) } @@ -750,6 +750,31 @@ func specAt(id string, until time.Time) ext.Watch { return ext.Watch{ID: id, Pattern: `\bguess \d+`, Until: until.Format(time.RFC3339), Tool: "guess"} } +// A watch's ID and pattern are measured in characters, as addon/schema.json +// counts them, whatever their script. +func TestWatchSizesInCharacters(t *testing.T) { + var log logx.Buffer + t.Cleanup(logx.SetOutput(&log, &log, true)) + a, now := unitAddon(everything) + cmd := said(inA, "alice-id", 1000, "/round") + w := func(id, pattern string) ext.Watch { + s := specAt(id, now.Add(time.Minute)) + s.Pattern = pattern + return s + } + pattern := `\bdevinette \d+ ` + strings.Repeat("é", maxPattern-len(`\bdevinette \d+ `)) + for _, s := range []ext.Watch{w(strings.Repeat("é", maxWatchID), `\bguess \d+`), w("p", pattern)} { + if a.watch(cmd, s) == nil { + t.Fatalf("refused at the limit, %d bytes: %s", len(s.ID)+len(s.Pattern), log.String()) + } + } + for _, s := range []ext.Watch{w(strings.Repeat("é", maxWatchID+1), `\bguess \d+`), w("q", pattern+"é")} { + if a.watch(cmd, s) != nil { + t.Fatalf("taken past the limit: %d characters of ID", utf8.RuneCountInString(s.ID)) + } + } +} + // A chat has at most maxWatches; a claim lasts claimLife, a watch until its // end, a tombstone tombLife. func TestWatchLimits(t *testing.T) { From 7e5ff71d32eb39c6477c2c6513c8d90257517dc5 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 21 Nov 2026 02:37:34 +0000 Subject: [PATCH 19/26] Addons can use the bot's model (MCP sampling), and watch replies - Core: Host.CallAPI works outside a tool when ctx names the chat that pays (feature.ChargeTo): the chat's daily budget is checked and charged. /chat/completions is allowed, always on the bot's own model, with the cost reported on OpenRouter. - mcp: an addon with the new model permission (per_hour, max_tokens) is offered capabilities.sampling and may send sampling/createMessage, charged to a chat it has a lease in; one call at a time, text only, size-capped, logged without content. Requests are served off the reader goroutine; string IDs work; a cancelled or crashed call is still charged. - Reply watches: a watch with replies takes only replies to the addon's own messages sent while it lives, whatever they say; the bot offers watchReplies. - addon package: Server.Sample, CanSample, WatchReplies; the new types in schema.json, kept in step by the drift test. - Docs: addons, privacy, configuration, technical, models. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- PRIVACY.md | 7 +- TECHNICAL.md | 14 +- addon/schema.json | 58 +- addon/schema_test.go | 55 +- addon/server.go | 201 +++++- addon/server_test.go | 260 +++++++ addon/types.go | 61 +- docs/CONFIGURATION.md | 2 +- docs/FILES_LINKS_TOOLS_MCP.md | 10 +- docs/MODELS.md | 2 +- examples/signalbot-mcp.json | 5 + internal/bot/host.go | 22 +- internal/bot/host_test.go | 59 ++ internal/feature/feature.go | 30 +- internal/feature/featuretest/featuretest.go | 16 +- .../feature/featuretest/featuretest_test.go | 16 + internal/features/mcp/addon.go | 57 +- internal/features/mcp/addon_test.go | 16 +- internal/features/mcp/conn.go | 150 +++- internal/features/mcp/direct.go | 16 +- internal/features/mcp/keep.go | 8 +- internal/features/mcp/mcp.go | 38 +- internal/features/mcp/mcp_test.go | 5 +- internal/features/mcp/outbox.go | 5 +- internal/features/mcp/sample.go | 209 ++++++ internal/features/mcp/sample_test.go | 653 ++++++++++++++++++ internal/features/mcp/watch.go | 65 +- internal/model/model.go | 44 +- internal/model/model_test.go | 58 +- 29 files changed, 2026 insertions(+), 116 deletions(-) create mode 100644 internal/features/mcp/sample.go create mode 100644 internal/features/mcp/sample_test.go diff --git a/PRIVACY.md b/PRIVACY.md index baac305..cb34c20 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -86,10 +86,11 @@ An addon is a program the bot runs on its own machine, as an [MCP server](docs/F - **Where it works:** only in the groups its `chats` lists (or all, if set to `all`), and in DMs only with `dms`. - **What each permission sends:** - a command (`/geo …`) sends the text after it, and who sent it, as a pseudonym, and when the bot got it, never the sender's own clock; - - `watch` sends the messages its watch matches (GeoGuess: map links and coordinates during a round), with the same; nothing else said in the chat. A pattern that would match ordinary chat is refused, so there is no feed of everything; + - `watch` sends the messages its watch matches (GeoGuess: map links and coordinates during a round), with the same; nothing else said in the chat. A pattern that would match ordinary chat is refused, so there is no feed of everything. A reply watch sends replies to the addon's own messages that ask the bot, such as answers to a quiz, whatever they say; - `names` adds each sender's display name. Without it, the addon writes a pseudonym where a name goes, and the bot puts in the name it last saw that person use in that chat, kept in memory for a day; - `global_ids` gives a person the same pseudonym in every chat, so the addon can link them across groups; - - `post` and `react` send nothing: they let it post and react, only in a chat where it was used in the last day. + - `post` and `react` send nothing: they let it post and react, only in a chat where it was used in the last day; + - `model` lets it ask the bot's model, with the bot's key: the addon's prompts, and whatever it put in them from the chat, go to the model provider, as chat with the bot does, and what they cost counts toward that chat's `DAILY_BUDGET`. The bot logs only each request's outcome, time, size and cost, never the prompt or the answer. - **What the addon keeps** is its own, in whatever directory you give it (GeoGuess: `GEO_STATE_DIR`), outside what this page lists for the bot. Read its own documentation. - **Deletes and edits are not passed on.** A message an addon took stays with the addon if its sender later deletes it for everyone. An edit of one is passed on, as a new version. - **Taken messages are kept nowhere by the bot:** not in history, not as context (so `GROUP_CONTEXT=false` makes no difference to them), not in the log. The addon still gets them. @@ -100,7 +101,7 @@ An addon is a program the bot runs on its own machine, as an [MCP server](docs/F |---|---| | The pseudonym secret | Until `mcp.json` is deleted, which gives everyone new pseudonyms | | Chats an addon may post in: the chat's pseudonym and its real ID | 24 hours after the addon was last used there | - | Live watches: the chat's pseudonym, the pattern, and the times of the bot's messages with the command's pictures | Until the watch ends, at most `watch_max` (24 hours at most) | + | Live watches: the chat's pseudonym, the pattern, and the times of the bot's messages with the command's pictures, and for a reply watch of the addon's messages | Until the watch ends, at most `watch_max` (24 hours at most) | | Messages a watch took: the chat's ID, the sender's pseudonym and the message's time, never its text | 48 hours, so a later edit is taken too | | How far the bot has read each addon's outbox, and the last 1,000 outbox entries' IDs | Replaced on each save; dropped once the server is no longer an addon | diff --git a/TECHNICAL.md b/TECHNICAL.md index 31309bd..ef55ed6 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -24,7 +24,7 @@ What the bot does with no features registered. - **Answer.** Typing is shown until the reply is ready, then stopped with `sendTyping` and `stop`, so a reaction or a turn that sends nothing doesn't leave "typing…" up until Signal's own timeout. A message a hook answers (a command) shows no typing, unless its `OnMessage` hooks are still running a second after it arrived, as a slow addon call can be; then typing is shown until they return. The prompt is built ([below](#the-prompt)) and sent to the model. On failure the "model error" line is logged, the chat gets "Sorry, I couldn't get an answer just now." (or, when the model was still calling tools after its last round with nothing to say, `model.ErrTooManyRounds`, "That took more lookups than I can do for one reply. Try asking for one thing at a time."), and history is unchanged. The network renders the reply's Markdown, then sends it without a leading @ and the bot's own name (an echo of how it was addressed), with @Name, and in a group the bot's own @name elsewhere (as in the intro's `I respond to @{name}`), linked to real mentions, as one message capped at 8,000 characters, the rest cut with " […truncated]" and a warning. A reply is never split: past 2,000 bytes, signal-cli 0.14.10 sends the body cut there with the whole text as a long-text attachment (`applyMessage` in `ManagerImpl`), as Signal's apps do, shown as one message with Read more. - **Markdown on Signal.** Signal shows text styles, not Markdown, so `internal/signal/markdown.go` turns a reply into plain text and signal-cli's `textStyle` ranges (`start:length:STYLE`, UTF-16 units of each message sent): `**bold**` and `__bold__` are BOLD, `*italic*` and `_italic_` ITALIC, `~~strike~~` STRIKETHROUGH, `` `code` `` and fenced code blocks (fences and language dropped) MONOSPACE, `||spoiler||` SPOILER; `# Heading` (1–6 `#`) is its text in bold, and `[text](url)` is "text (url)", or the url alone when they are the same. Markers open and close only at word boundaries (`2*3*4`, `snake_case_name` and `a * b` stay as they are), an unmatched one stays literal, nothing in code is converted, and lists, tables and quotes stay as written. Conversion comes first, so stripping and mentions work on the plain text. - **Nothing to answer.** A message with no text (only a photo or sticker) is answered only if an `OnTurn` hook adds something to it. -- **The model.** A chat completions API in OpenAI's format at `MODEL_API_URL` (OpenRouter's by default, `internal/model`), with `MODEL_API_KEY` as a bearer token if set, over a keep-alive client that requires TLS 1.3 for `https://`. Requests to OpenRouter (host `openrouter.ai`) set `provider.data_collection: deny` and `usage.include` for the real cost, plus the `MODEL_REASONING` effort as `reasoning.effort`; requests elsewhere carry only `reasoning_effort`. Either effort is left out when `MODEL_REASONING` is `none`. The tokens are logged with each reply, and the cost when the API reports it. A network error, 429 or 5xx gets one retry; an error body is reduced to its message ("status N: message"). The tool loop takes at most 5 requests and 3 minutes per reply, and 4 pictures; if a request after a tool made pictures fails, the pictures are the reply, without words, since they may have cost money to make. `Host.CallAPI(ctx, path, body)` lets a tool post to another endpoint of the same API (`model.Client.Call`): the core adds the key, so a feature never sees it, and on OpenRouter `provider.data_collection: deny` (merged into any provider settings the body has); it waits up to 150s for at most 32 MB, retries as other requests do, refuses `/chat/completions` and any path that isn't a plain endpoint, and adds the `usage.cost` the response reports to the reply whose tool called it, through a tally in the tool loop's ctx, so `DAILY_BUDGET` counts it. Outside a tool's Run there is no reply to count it toward, so it refuses. `Info.Provider` is `openrouter` on OpenRouter's API, else empty. +- **The model.** A chat completions API in OpenAI's format at `MODEL_API_URL` (OpenRouter's by default, `internal/model`), with `MODEL_API_KEY` as a bearer token if set, over a keep-alive client that requires TLS 1.3 for `https://`. Requests to OpenRouter (host `openrouter.ai`) set `provider.data_collection: deny` and `usage.include` for the real cost, plus the `MODEL_REASONING` effort as `reasoning.effort`; requests elsewhere carry only `reasoning_effort`. Either effort is left out when `MODEL_REASONING` is `none`. The tokens are logged with each reply, and the cost when the API reports it. A network error, 429 or 5xx gets one retry; an error body is reduced to its message ("status N: message"). The tool loop takes at most 5 requests and 3 minutes per reply, and 4 pictures; if a request after a tool made pictures fails, the pictures are the reply, without words, since they may have cost money to make. `Host.CallAPI(ctx, path, body)` lets a feature post to an endpoint of the same API (`model.Client.Call`): the core adds the key, so a feature never sees it, and on OpenRouter `provider.data_collection: deny` (merged into any provider settings the body has); it waits up to 150s for at most 32 MB, retries as other requests do, and refuses any path that isn't a plain endpoint. For `/chat/completions` it sets `model` to the bot's own `MODEL`, whatever the body names, so a feature can't pick a dearer one, and on OpenRouter adds `usage.include`, so the cost is reported; the rest of the body (messages, tools, reasoning) is the caller's. From a tool's Run, it adds the `usage.cost` the response reports to the reply whose tool called it, through a tally in the tool loop's ctx, so `DAILY_BUDGET` counts it. Outside a tool, the ctx must come from `feature.ChargeTo(ctx, chat)`, naming the chat that pays: the core refuses the call when that chat is at or over `DAILY_BUDGET`, makes it with a tally of its own (`model.Meter`), and adds the reported cost to that chat's spending; with no budget applied it just makes the call. Without either it refuses. `Info.Provider` is `openrouter` on OpenRouter's API, else empty. - **Edits and deletes.** The network honours deletes and edits exactly as its network's official client would; the core forgets what it is told. The rules, one each: - **Who counts (Signal).** The author's delete or edit, or a group admin's delete of anyone's message. What Signal's app refuses never reaches the bot: signal-cli drops everything from a blocked person or group, group messages from non-members, and admin deletes from non-admins. Signal's time window (the sender's window plus a day) needs no check while history lasts at most 24 hours; a longer history must add it. - **The allowlist never decides it.** `SIGNAL_DM_USER_IDS` says only who the bot answers, as message requests do in the app (which still applies an unaccepted sender's deletes); it is not a block. So someone removed from it still has their deletes and edits honoured. @@ -124,7 +124,7 @@ The core's lifecycle has four stages. Each port is one stage; nothing else is a **Services the host offers:** - `IntroLine(line)`, `IntroLineDM(line)`: a paragraph for the bot's introduction, placed where `INTRO` has `{more}`; with `IntroLineDM`, only in the introduction a DM gets (`Info.IntroDM`, and the prompt's rule in a DM), not a group's (`Info.Intro`). The core pads each with a blank line and never leaves two blank lines in a row. `/schedule` uses it, DM only, for `Type "/schedule" for schedules and reminders.`, since schedules are made only in a DM. -- `CallAPI(ctx, path, body)`: from a tool's Run, post a JSON body to another endpoint of the model's API, such as OpenRouter's `/images`, and get the response; the core keeps the key and the data-collection request, and counts the cost toward the reply (see the model, above). +- `CallAPI(ctx, path, body)`: post a JSON body to an endpoint of the model's API, such as OpenRouter's `/images` or `/chat/completions` (with the bot's own model), and get the response; the core keeps the key and the data-collection request. From a tool's Run the cost counts toward the reply; outside one the ctx must come from `ChargeTo(ctx, chat)`, and the cost counts toward that chat's daily budget, which refuses the call once spent (see the model, above). - `Env(key, def)`: a feature's own setting. The docs guardrail finds each name passed to it. - `Store(name)`: the feature's saved state, opened while it registers: one JSON document, `<name>.json` in the state directory (`STATE_DIRECTORY`'s first directory, or the working directory when it isn't set), with `Load(v)` (found is false when nothing is saved yet; a file that can't be read is an error, so the feature can stop the bot rather than overwrite it) and `Save(v)` (written to a temporary file, synced and renamed over the old one, at most 4 MiB, its newline included). The first `Store` call checks that the directory can be listed and written, and fails with how to fix it otherwise (for Docker's `/data`, `chown 65532`; elsewhere, the unit's `StateDirectory`), so a bot whose features save nothing needs no state directory. A name is lowercase letters, digits, `-` and `_`, up to 32, and may be opened once; `budget` is the core's (`budget.json`, written the same way). Features save files only this way (a guardrail below). - `Info()`: the bot's name, the chat network (`Network`, from `Network.Name`: `signal` or `telegram`), its version, the model ("" with no model), the API's provider (`openrouter` or ""), whether it takes images, audio and PDFs (`Audio`, `PDFs`) and can call tools, the names of the tools, as in `{tools}` (none when it can't call tools), and the introduction, in a group and in a DM. All but the name and the tools are known when features register; images, audio, PDFs and tool calling may turn off later ([Capabilities](#the-core)). @@ -218,7 +218,7 @@ In `features.go` order, which is the order hooks run in and of the tools line an | `links` | `OnTurn` returning `Note` and `Files`, `Info` | | `charts` | `OfferTools` with `Keywords` | | `imagegen` | `OfferTools` with `Keywords`, `CallAPI`, `Info` | -| `mcp` | `OfferTools` (one group per server), `Command` returning `ToolChoice`, or `Answer` and `Pictures` for an addon's direct command, `ListCommands`, `OnMessage` returning `Done` (or `Answer`, for a guard), `Post`, `React`, `Info`, `Redact`, `Store`, `Go` | +| `mcp` | `OfferTools` (one group per server), `Command` returning `ToolChoice`, or `Answer` and `Pictures` for an addon's direct command, `ListCommands`, `OnMessage` returning `Done` (or `Answer`, for a guard), `Post`, `React`, `CallAPI` with `ChargeTo` (an addon's sampling), `Info`, `Redact`, `Store`, `Go` | | `groupctx` | `OnMessage` returning `Context` | | `schedule` | `Command`, `ListCommands`, `IntroLineDM`, `At`, `Deliver`, `Post`, `Groups`, `Info`, `Store` | @@ -237,8 +237,8 @@ In `features.go` order, which is the order hooks run in and of the tools line an - Config errors stop the bot, each starting with the file's path and naming the server: a key that is neither a setting nor one other clients write (`type`, `transport`, `timeout`, `alwaysAllow`, `autoApprove`, `description`, ignored), with the settings listed, in a server or a chat command; both `allowed_tools` and `blocked_tools`; a tool name the server lacks, with the list it is in and the server's tools (the first 20, then "…"); and two tools that become one name for the model, naming both. An addon server adds its own (below). - Tools are filtered by `_meta`: a tool whose `io.github.robdevops.signalbot/visibility` array, or MCP Apps' `ui.visibility`, leaves out `"model"` is never offered to the model, nor listed in `{tools}` or the tools line. A missing array means the model may see it. The bot calls a tool itself (an addon's direct command or watch) only if signalbot's array has `"bot"`; MCP Apps' `"app"` means a UI, not the bot. - **`img.Safe`** (`kit/img`) checks any image from a server before it is sent: only PNG, JPEG, GIF or WebP, read from the header alone, at most 8,192 pixels a side and 40 megapixels, so a small file claiming a huge canvas never reaches phones; a JPEG loses its EXIF (keeping its orientation), XMP, IPTC, comments and anything after the image, by walking its segments without decoding pixels, since signal-cli sends attachments as they are and GPS tags would say where a photo was taken. -- **Addons** are local MCP servers with an `addon` block (the extension's wire format, which the feature and every addon written in Go share, is the public package `addon`, in [Layout](#layout)) in `MCP_CONFIG` that also advertise `io.github.robdevops.signalbot/addon` at version 1 in their `initialize` result's `capabilities.experimental`. The bot offers the same key in its `initialize` request with the chat network it is on, `{"version": 1, "network": "signal"}` (`Info.Network`, which each network names itself with `Network.Name`), so an addon can word its messages for that network. One with the block that doesn't advertise it runs as a plain server, with a warning. They are part of `mcp`: no port of the core names them. - - **Config:** the block's keys are `chats` (group IDs exactly as Signal or Telegram shows them, a Telegram topic counting as its group, or `["all"]` alone; anything else is an error asking for the group's ID), `dms`, `post`, `react`, `watch` (each off unless set), `watch_max` (1s to 24h, default 1h), `names`, `global_ids` and `rate` (`per_minute`, default 20, and `burst`, default 5). Unknown keys get the same error as a server's. An addon must be local (`command`), can't have an `env` block, and its server's name can't make a prefix (below) that one of the bot's own settings starts with (the names in `docs/CONFIGURATION.md`'s table, plus `STATE_DIRECTORY`, a list a test keeps in step); a `direct` chat command without an addon block is an error. Its error text and its start, initialize and call failures are logged by code only, never the server's words. +- **Addons** are local MCP servers with an `addon` block (the extension's wire format, which the feature and every addon written in Go share, is the public package `addon`, in [Layout](#layout)) in `MCP_CONFIG` that also advertise `io.github.robdevops.signalbot/addon` at version 1 in their `initialize` result's `capabilities.experimental`. The bot offers the same key in its `initialize` request with the chat network it is on, `{"version": 1, "network": "signal"}` (`Info.Network`, which each network names itself with `Network.Name`), so an addon can word its messages for that network, and, to a server with an addon block, `"watchReplies": true`, so it knows it may ask for a reply watch. To an addon with `model`, while `Info.Model` is set and the store is open, it also offers MCP's `capabilities.sampling: {}`. One with the block that doesn't advertise it runs as a plain server, with a warning. They are part of `mcp`: no port of the core names them. + - **Config:** the block's keys are `chats` (group IDs exactly as Signal or Telegram shows them, a Telegram topic counting as its group, or `["all"]` alone; anything else is an error asking for the group's ID), `dms`, `post`, `react`, `watch` (each off unless set), `watch_max` (1s to 24h, default 1h), `names`, `global_ids`, `rate` (`per_minute`, default 20, and `burst`, default 5) and `model` (`per_hour`, default 30, and `max_tokens`, default 4000, at most 32,000; off unless set, `{}` for the defaults; neither below 0). Unknown keys get the same error as a server's. An addon must be local (`command`), can't have an `env` block, and its server's name can't make a prefix (below) that one of the bot's own settings starts with (the names in `docs/CONFIGURATION.md`'s table, plus `STATE_DIRECTORY`, a list a test keeps in step); a `direct` chat command without an addon block is an error. Its error text and its start, initialize and call failures are logged by code only, never the server's words. - **Environment:** an addon gets `PATH`, `HOME`, those of `TZ`, `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` (and their lowercase forms), `SSL_CERT_FILE` and `SSL_CERT_DIR` that are set, so it keeps the bot's time zone and reaches the internet as the bot does, and every variable of the bot's environment that starts with its prefix: its server's name in capitals, anything but letters and digits as `_`, then `_` (`geo` gets `GEO_…`). Nothing else, so the bot's keys never reach it. These are read with `os.Environ`, not `Env`, so each addon documents its own. - **Stderr:** an addon's is never logged, since it may write what it was sent: only "addon <name> wrote N lines (M bytes) to stderr", at most once a minute, and once more when it exits for what was counted since, so a crash's output is never left uncounted. - **The store:** with any addon configured, `mcp` opens its `Store` (`mcp`, `mcp.json`), so MCP without addons needs no state directory. It holds a 32-byte random secret, made once, and each addon's state (below). If the store can't be opened, or the secret read or saved, addons run as plain servers, with an error at startup, rather than with a new secret that would change every pseudonym. A damaged secret is an error too. One saver goroutine writes the document whenever told something changed (a non-blocking send on a 1-buffered channel), and once at shutdown, so a hook never waits on the disk and a burst is one write; a failed save is logged once, the state stays in memory, and the next change tries again. The state of a server no longer configured as an addon is dropped at the first save. @@ -246,9 +246,11 @@ In `features.go` order, which is the order hooks run in and of the tools line an - **Context:** each `tools/call` the bot makes itself carries the message's context in `_meta["io.github.robdevops.signalbot/context"]`: `chat`, `sender`, `ref`, `addressed`, `group`, `sent` and `edited` (when the bot got the message and its edit, in Unix seconds, never the sender's clock; `edited` is 0 for an original), `name`, the sender's display name, only with `names`, and for a direct command `deadline`, when the bot stops waiting (Unix seconds, rounded down). A call the bot stops waiting for gets `notifications/cancelled` with its `requestId`. Otherwise the bot keeps, in memory for 24 hours, the last name it saw each pseudonym use in the chat: a `{u_…}` placeholder in an addon's answer or post becomes `@Name`, linked as a mention, or "someone". - **Direct commands:** a chat command with `direct` makes `/name args` a call the bot makes itself, without the model, to a tool whose visibility has `"bot"` (looked up among all the server's tools; one without it is skipped with a warning), with `{"args": "<text after the command>"}`. It runs in the message's slot, with 15s or the command's `timeout` (1s to 2m, only on a direct command), and at most 2 at once per server, each held for as long as its call runs: a third is told "<title> is busy, try again in a moment." at once. The title is the server's `serverInfo.title`, else its name, made safe. In a chat its `chats` or `dms` don't allow, it answers "/name isn't available in this chat.". The result's text parts, joined, become the `Answer` (placeholders filled in, capped at 4,000 characters) and its image parts up to 2 `Pictures`, 2 MB together after `img.Safe` (any left out are counted in a warning); a result with neither is `Done`. An error result, a timeout, a bad result or a server that can't be reached answers "<title> couldn't do that just now.". Each call logs the command, the tool, the outcome (ok, or a code), the time and the result's size. Direct commands are kept with no model or one that can't call tools; a server with no tool for the model lists them with `ListCommands` under its label. - **Watches:** a direct command's result may ask, in `_meta["io.github.robdevops.signalbot/watch"]`, for a watch on the chat the command came from (the only way to make one, so an addon can't watch a chat it wasn't used in): an `id` (at most 64 characters), an RE2 `pattern` (at most 1,024 characters), `until` (RFC 3339, cut to `watch_max` from now and never extended), the `tool` to call with each match (one the bot may call) and an optional `guard` (at most 500 characters). It needs `watch`, and at most 8 are live in a chat per addon (one with the same ID is replaced). A pattern that matches the empty string or any of about 200 ordinary chat lines in `corpus.go` is refused, so no watch is a feed of the chat; a refusal is logged by reason, never the pattern. One `OnMessage` hook, registered after the chat commands, checks each message with text in an allowed chat against the chat's live watches, on both paths: unaddressed ones on the reader goroutine (only a map lookup and the patterns, under a mutex held briefly), addressed ones (a reply to the bot, a DM, an @mention, a command) in their slot. A watch matches any message the bot gets while it lasts, by when the bot got it, not by its `Timestamp` (on Signal the sender's clock, which may be behind); an edit, unless its original was claimed, only if its original's `Timestamp` is at or after the command's, so an older message's edit isn't taken. An addressed message with no text (a bare mention, or a reply with only a picture) is still checked for the guard. A match is `Done`, so it is never answered, sent to the model or kept in history, and `groupctx` never sees it; it is claimed for 48 hours (chat key, sender's pseudonym, sent time), so a later edit of it goes the same way, to the same tool, whether or not the watch is still live; and it is passed without waiting to the addon's watch worker, whose queue holds 256 (when full, "addon <name>: watch queue full, a matched message dropped", still `Done`). The worker calls the watch's tool with `{"text": …}` and the context, within 120 calls a minute per chat (bursts of 20; a match past it waits its turn in the worker's queue, while other chats' matches go ahead), and keeps a match whose call found the server down (not running, or exited before answering) at the head of the queue until the server has started again (or a minute has passed), dropping it with a warning after 3 such calls, and if the result's `_meta["io.github.robdevops.signalbot/react"]` is one emoji, reacts with it (`React`), which needs `react` and counts against the addon's rate. A watch whose command answered with pictures records, through `OnSent`, the timestamps of the messages they went out in; while it lives, an addressed message quoting one of them gets the `guard` as its `Answer`, so nobody can ask the model about the picture. + - **Reply watches:** a watch with `replies` takes only addressed messages whose `Quote.Bot` is set and whose `Quote.Sent` is the timestamp of one of the addon's own messages in the chat sent while it lives: a direct command's answer (any answer, through the `Action`'s `OnSent`) and each outbox post (through the `Post`'s `OnSent`), recorded on every live reply watch in the chat, the last 64 each. Its `pattern`, if set, must match too; it may be empty, and isn't checked against `corpus.go`, since a reply to the addon's own message is meant for it. Claims, edits, the worker, its rate and queue work as for any watch. Without `replies`, a watch works as above, and an empty pattern is refused. - **Leases:** an addon may post or react only in a chat where it had a direct command or a watch match in the last 24 hours; the lease maps the chat's pseudonym to the chat. - **Outbox:** if the server advertises `resources.subscribe`, the bot sends `resources/subscribe` for `signalbot://outbox` after each (re)start's `initialize`, then reads it; otherwise the outbox is off, with a warning. Any `notifications/resources/updated` from the server marks the outbox as having news (whatever the URI, which may be under the one subscribed). One reader goroutine per addon reads `resources/read` of `signalbot://outbox/<cursor>` (`0` at first), page by page while `more` is true, up to 100 pages, so two reads never race and news during a read is read after it. A page is one text content holding `{"cursor", "more", "ops"}`; a not-found error (-32002, or the Go SDK's -32602) is logged as no outbox. Ops are applied once each by `id`, the last 1,000 IDs remembered, and are `post` (`chat`, Markdown `text` with placeholders, up to 2 `images` as `{data, mimeType, name}`, 2 MB together), needing `post`; `react` (`ref`, `emoji`), needing `react`; and `unwatch` (`chat`, `watch`), which, for a watch not yet made, stops it being made for 10 minutes. A post or reaction needs a live lease in a chat the addon is still allowed, and counts against `rate` per chat. A post goes through `Post` with the addon's title as its `Label`, so history keeps it as `[Title] …`, the bot's own words. At most one of an addon's posts waits in a chat's mailbox: until its `OnSent`, later posts for that chat are held, each merged into the one held before it while their pictures together stay within 2 and 2 MB and their texts together within 4,000 characters, so a merge never cuts one, and sent in turn. Delivery is at least once: a post counts as applied, and the cursor moves past it, only once its `OnSent` says it was sent. A send that fails counts as dropped, so a post whose send timed out after it went out may be posted twice, rather than lost. Until then each read starts from the cursor before it and skips it while it waits; one dropped before it was sent (as while the bot stops, or before the network is up at startup, when `Post` gives up on the chat) is posted again by a read 10s later, then 20s, doubling to 5 minutes, not counted against `rate` again, and given up with a warning after 6 tries. A page with `more` waits for its posts before the next is read, since reading past the cursor lets the addon forget them. A read that fails, is malformed, or stops at 100 pages is tried again after 10s, doubling to 5 minutes, without waiting for news. What a read drops is counted in one warning by reason, never content. - - **What is saved,** per addon, in `mcp.json`: live watches (with their guard pictures' timestamps), claims, leases, the outbox cursor and the last 1,000 applied op IDs. Anything expired is left out. At startup they are restored, leaving out a watch whose chat is no longer allowed or whose pattern no longer passes, so a restart of the bot or the addon never lets a match fall through to history. Refs, names, tombstones and held posts are in memory only. + - **Sampling:** an addon offered sampling may send MCP's `sampling/createMessage`. The stdio client reads every message's ID as raw JSON, so a server's request may use a string ID, answered with the same one. `dispatch` hands the request to the addon's handler on a goroutine of its own, never the reader's, so a slow model call never holds up replies; one is served at a time per addon, and a second gets -32000 at once. The handler is installed before `initialize`, behind a `gate` that holds a request until the addon is set up after `tools/list`, and refuses it with -32000 if it never is (as when the server turns out not to speak the extension), so a request is never called unsupported while sampling is offered. An incoming `notifications/cancelled` naming it, or the process exiting, cancels its ctx, and a cancelled request gets no answer; an answer to a process that has since restarted is dropped. The model call doesn't take that cancel: it runs under `context.WithoutCancel` with its own 2 minutes, so a call the provider bills is always charged to the chat, and the addon can't spend outside `DAILY_BUDGET` by cancelling or exiting. Any other request, or this one from an addon without it, gets -32601, and `ping` `{}`, as before. The handler (`sample.go`) takes text messages only, `user` or `assistant`, at most 16 and 32 KB of text with the system prompt, and a `maxTokens` of at least 1, capped at `max_tokens`; `temperature` (0 to 2) is passed on, and `modelPreferences` and `includeContext` are ignored. `_meta["io.github.robdevops.signalbot/chat"]` must name a chat the addon holds a live lease in and is still allowed, and `per_hour` (a `limiter`, all of the addon's chats as one bucket) must have room; a refusal is -32602 or -32000 with a short message. It posts `{"messages": [system, …], "max_tokens", "temperature"}` to `/chat/completions` through `CallAPI` with `feature.ChargeTo` that chat, so the core sets its own model, refuses a chat over `DAILY_BUDGET` and charges it, within 2 minutes, and answers `{role: "assistant", content: {type: "text", text}, model, stopReason}` from `choices[0].message.content`, `model` and `finish_reason` (`stop` as `endTurn`, `length` as `maxTokens`). A failure is -32603, "the model couldn't answer", never the API's text. It logs the outcome, time, the request's text size, the answer's tokens and the cost, never the prompt or the answer. + - **What is saved,** per addon, in `mcp.json`: live watches (with their guard pictures' timestamps, and a reply watch's messages' timestamps), claims, leases, the outbox cursor and the last 1,000 applied op IDs. Anything expired is left out. At startup they are restored, leaving out a watch whose chat is no longer allowed or whose pattern no longer passes, so a restart of the bot or the addon never lets a match fall through to history. Refs, names, tombstones and held posts are in memory only. - **`groupctx`** (`GROUP_CONTEXT`, on by default) comes after `mcp`, so an earlier hook can claim a message (`Done`) before it is kept, and keeps each other unaddressed group message as context: `Name: text`, capped at 2,000 characters, with photos, stickers and files noted as `[image]`, `[sticker]` and `[file "name"]` but never fetched. The core keeps it like any history entry, marked as context, and never logs it. - **`schedule`** is `/schedule` ([below](#schedule)). diff --git a/addon/schema.json b/addon/schema.json index fc3cdc0..bcc16b6 100644 --- a/addon/schema.json +++ b/addon/schema.json @@ -5,11 +5,12 @@ "description": "The JSON of signalbot's addon extension, for an addon in any language: each object the bot and an addon exchange on top of MCP, under $defs. The keys of the extension start io.github.robdevops.signalbot/. The Go types in addon/types.go are the same messages, and a test keeps the two in step. Each side ignores keys it doesn't know; the objects an addon sends (Watch, Op, Image, Page) forbid them here, so a misspelt key fails validation instead of being ignored.", "$defs": { "Capability": { - "description": "capabilities.experimental[\"io.github.robdevops.signalbot/addon\"] in initialize. The bot offers its chat network; an addon answers with the version alone.", + "description": "capabilities.experimental[\"io.github.robdevops.signalbot/addon\"] in initialize. The bot offers its chat network and what it can do; an addon answers with the version alone.", "type": "object", "properties": { "version": {"description": "The extension's version.", "const": 1}, - "network": {"description": "The bot's chat network, as it names itself.", "type": "string", "examples": ["signal", "telegram"]} + "network": {"description": "The bot's chat network, as it names itself.", "type": "string", "examples": ["signal", "telegram"]}, + "watchReplies": {"description": "The bot's: it takes a watch with replies. A bot without it refuses one.", "type": "boolean"} }, "required": ["version"] }, @@ -41,17 +42,20 @@ "required": ["chat", "sender", "ref", "addressed", "group", "sent", "edited"] }, "Watch": { - "description": "A direct command's result's _meta[\"io.github.robdevops.signalbot/watch\"]: the messages matching pattern in the command's chat, until until, go to tool instead of the model. The bot refuses a pattern that would match ordinary chat, and shortens until to the addon block's watch_max.", + "description": "A direct command's result's _meta[\"io.github.robdevops.signalbot/watch\"]: the messages matching pattern in the command's chat, until until, go to tool instead of the model. The bot refuses a pattern that would match ordinary chat, and shortens until to the addon block's watch_max. With replies, the watch takes only replies to the addon's own messages, and pattern, then optional, must match them too.", "type": "object", "properties": { "id": {"description": "The watch's name, for an unwatch op; at most 64 characters. A new watch with the ID of a live one in the chat replaces it.", "type": "string", "minLength": 1, "maxLength": 64}, - "pattern": {"description": "An RE2 regular expression, at most 1,024 characters.", "type": "string", "minLength": 1, "maxLength": 1024}, + "pattern": {"description": "An RE2 regular expression, at most 1,024 characters. Needed unless replies.", "type": "string", "minLength": 1, "maxLength": 1024}, "until": {"description": "An RFC 3339 time, in the future.", "type": "string", "format": "date-time"}, "tool": {"description": "A tool for the bot, called with each message the watch takes, as {\"text\": …}, with its context.", "type": "string", "minLength": 1}, - "guard": {"description": "While the watch lasts, the answer to a message addressed to the bot that replies to the command's pictures; at most 500 characters.", "type": "string", "maxLength": 500} + "guard": {"description": "While the watch lasts, the answer to a message addressed to the bot that replies to the command's pictures; at most 500 characters.", "type": "string", "maxLength": 500}, + "replies": {"description": "Take only messages in the chat that reply to the command's answer or to the addon's posts there while the watch lives. Only for a bot whose capability has watchReplies; the bot doesn't check such a pattern against ordinary chat.", "type": "boolean"} }, - "required": ["id", "pattern", "until", "tool"], - "additionalProperties": false + "required": ["id", "until", "tool"], + "additionalProperties": false, + "if": {"properties": {"replies": {"const": true}}, "required": ["replies"]}, + "else": {"required": ["pattern"]} }, "Content": { "description": "One block of a tool's result. The bot uses text and image blocks.", @@ -129,6 +133,46 @@ "required": ["cursor", "more", "ops"], "additionalProperties": false }, + "SampleRequest": { + "description": "The params of sampling/createMessage, MCP's request for the bot's model, which an addon may send once the bot offers capabilities.sampling in initialize (with the addon block's model permission). The bot runs it on its own model, charges _meta's chat, and takes text alone; it caps maxTokens at the permission's max_tokens, takes at most 16 messages and 32 KB of text in all, and ignores MCP's other keys, such as modelPreferences and includeContext.", + "type": "object", + "properties": { + "messages": {"type": "array", "items": {"$ref": "#/$defs/SampleMessage"}, "minItems": 1, "maxItems": 16}, + "systemPrompt": {"type": "string"}, + "maxTokens": {"type": "integer", "minimum": 1}, + "temperature": {"type": "number"}, + "_meta": {"$ref": "#/$defs/SampleMeta"} + }, + "required": ["messages", "maxTokens", "_meta"] + }, + "SampleMeta": { + "description": "A sampling request's _meta: the chat that pays.", + "type": "object", + "properties": { + "io.github.robdevops.signalbot/chat": {"description": "The chat whose budget the request is charged to: one the addon may post in now, as for a post op. Without it, the bot refuses the request.", "type": "string", "pattern": "^c_[a-z2-7]{26}$"} + }, + "required": ["io.github.robdevops.signalbot/chat"] + }, + "SampleMessage": { + "description": "One message of a sampling request.", + "type": "object", + "properties": { + "role": {"enum": ["user", "assistant"]}, + "content": {"description": "Text alone.", "$ref": "#/$defs/Content", "properties": {"type": {"const": "text"}}} + }, + "required": ["role", "content"] + }, + "SampleResult": { + "description": "The bot's result for sampling/createMessage: MCP's CreateMessageResult.", + "type": "object", + "properties": { + "role": {"type": "string", "const": "assistant"}, + "content": {"description": "The model's text.", "$ref": "#/$defs/Content", "properties": {"type": {"const": "text"}}}, + "model": {"description": "The model that wrote it.", "type": "string"}, + "stopReason": {"description": "Why the model stopped.", "type": "string", "examples": ["endTurn", "maxTokens"]} + }, + "required": ["role", "content", "model"] + }, "Held": { "description": "An op the bot hasn't read past yet, as an addon may save it, with its ID, to post it after a restart. Not on the wire.", "type": "object", diff --git a/addon/schema_test.go b/addon/schema_test.go index 167e939..a117915 100644 --- a/addon/schema_test.go +++ b/addon/schema_test.go @@ -53,6 +53,11 @@ var wireTypes = map[string]reflect.Type{ "Image": reflect.TypeFor[Image](), "Page": reflect.TypeFor[Page](), "Held": reflect.TypeFor[Held](), + + "SampleRequest": reflect.TypeFor[SampleRequest](), + "SampleMeta": reflect.TypeFor[SampleMeta](), + "SampleMessage": reflect.TypeFor[SampleMessage](), + "SampleResult": reflect.TypeFor[SampleResult](), } // The schema and the Go types say the same: the same objects, each with @@ -131,7 +136,7 @@ func TestSchemaMatchesTypes(t *testing.T) { } } // The _meta keys are the package's. - for key, def := range map[string]string{KeyVisibility: "ToolMeta", KeyWatch: "ResultMeta", KeyReact: "ResultMeta"} { + for key, def := range map[string]string{KeyVisibility: "ToolMeta", KeyWatch: "ResultMeta", KeyReact: "ResultMeta", KeyChat: "SampleMeta"} { if _, ok := d[def].(map[string]any)["properties"].(map[string]any)[key]; !ok { t.Errorf("$defs/%s lacks %s", def, key) } @@ -145,6 +150,9 @@ func TestSchemaMatchesTypes(t *testing.T) { t.Errorf("Op's %s pattern %v isn't Context's %v", k, prop("Op", k), prop("Context", k)) } } + if prop("SampleMeta", KeyChat) != prop("Context", "chat") { + t.Errorf("SampleMeta's chat pattern %v isn't Context's %v", prop("SampleMeta", KeyChat), prop("Context", "chat")) + } if v := d["Capability"].(map[string]any)["properties"].(map[string]any)["version"].(map[string]any)["const"]; v != float64(Version) { t.Errorf("the schema's version is %v; the package's %d", v, Version) } @@ -175,6 +183,8 @@ func goSchema(t reflect.Type) string { return "boolean" case reflect.Int, reflect.Int64: return "integer" + case reflect.Float64: + return "number" } return "unknown " + t.String() } @@ -352,6 +362,9 @@ func isType(v any, typ string) bool { case "integer": n, ok := v.(float64) return ok && n == float64(int64(n)) + case "number": + _, ok := v.(float64) + return ok } return false } @@ -383,6 +396,15 @@ func TestSchemaSamples(t *testing.T) { root := schema(t) until := time.Date(2026, 11, 21, 9, 3, 0, 0, time.UTC).Format(time.RFC3339) post := Op{ID: "a1b2.1", Op: "post", Chat: chatID, Text: "{" + senderID + "} wins"} + temp := 0.7 + sample := SampleRequest{Messages: []SampleMessage{{Role: "user", Content: Content{Type: "text", Text: "a question"}}}, MaxTokens: 100, Meta: SampleMeta{Chat: chatID}} + withSample := func(f func(m map[string]any)) map[string]any { + data, _ := json.Marshal(sample) + var m map[string]any + json.Unmarshal(data, &m) + f(m) + return m + } valid := []struct { def string v any @@ -408,6 +430,15 @@ func TestSchemaSamples(t *testing.T) { {"Held", Held{Op: post, Queued: time.Now()}}, {"ToolMeta", map[string]any{KeyVisibility: []string{"bot"}}}, {"ToolMeta", map[string]any{}}, + {"Capability", Capability{Version: Version, Network: "signal", WatchReplies: true}}, + {"Watch", Watch{ID: "q1", Until: until, Tool: "answer", Replies: true}}, + {"Watch", Watch{ID: "q1", Pattern: `(?i)^\s*[a-d]\s*$`, Until: until, Tool: "answer", Replies: true}}, + {"SampleRequest", sample}, + {"SampleRequest", SampleRequest{Messages: []SampleMessage{{Role: "user", Content: Content{Type: "text", Text: "a question"}}, + {Role: "assistant", Content: Content{Type: "text", Text: "{"}}}, SystemPrompt: "Answer in JSON.", MaxTokens: 2000, Temperature: &temp, + Meta: SampleMeta{Chat: chatID}}}, + {"SampleResult", SampleResult{Role: "assistant", Content: Content{Type: "text", Text: "an answer"}, Model: "a-model", StopReason: "endTurn"}}, + {"SampleResult", SampleResult{Role: "assistant", Content: Content{Type: "text"}, Model: "a-model"}}, } for _, c := range valid { if err := check(t, root, c.def, c.v); err != nil { @@ -445,6 +476,28 @@ func TestSchemaSamples(t *testing.T) { {"Page", "a bad op", Page{Cursor: "x.1", Ops: []Op{{ID: "1", Op: "post"}}}}, {"Held", "no time", map[string]any{"op": post}}, {"ToolMeta", "an unknown caller", map[string]any{KeyVisibility: []string{"everyone"}}}, + {"Capability", "watchReplies not a boolean", map[string]any{"version": 1, "watchReplies": "yes"}}, + {"Watch", "no pattern and no replies", Watch{ID: "r1", Until: until, Tool: "guess"}}, + {"Watch", "no pattern, replies false", map[string]any{"id": "r1", "until": until, "tool": "guess", "replies": false}}, + {"Watch", "an empty pattern with replies", map[string]any{"id": "r1", "pattern": "", "until": until, "tool": "guess", "replies": true}}, + {"Watch", "replies not a boolean", map[string]any{"id": "r1", "until": until, "tool": "guess", "replies": "yes"}}, + {"SampleRequest", "no chat", withSample(func(m map[string]any) { m["_meta"] = map[string]any{} })}, + {"SampleRequest", "no _meta", withSample(func(m map[string]any) { delete(m, "_meta") })}, + {"SampleRequest", "a sender for a chat", withSample(func(m map[string]any) { m["_meta"] = map[string]any{KeyChat: senderID} })}, + {"SampleRequest", "no maxTokens", withSample(func(m map[string]any) { delete(m, "maxTokens") })}, + {"SampleRequest", "no tokens", withSample(func(m map[string]any) { m["maxTokens"] = 0 })}, + {"SampleRequest", "no messages", withSample(func(m map[string]any) { m["messages"] = []any{} })}, + {"SampleRequest", "17 messages", withSample(func(m map[string]any) { m["messages"] = slices.Repeat(m["messages"].([]any), 17) })}, + {"SampleRequest", "a temperature in words", withSample(func(m map[string]any) { m["temperature"] = "warm" })}, + {"SampleRequest", "a system role", withSample(func(m map[string]any) { + m["messages"] = []any{map[string]any{"role": "system", "content": map[string]any{"type": "text", "text": "x"}}} + })}, + {"SampleRequest", "an image", withSample(func(m map[string]any) { + m["messages"] = []any{map[string]any{"role": "user", "content": map[string]any{"type": "image", "data": "aGk=", "mimeType": "image/png"}}} + })}, + {"SampleResult", "no model", map[string]any{"role": "assistant", "content": map[string]any{"type": "text", "text": "x"}}}, + {"SampleResult", "the user's", SampleResult{Role: "user", Content: Content{Type: "text", Text: "x"}, Model: "m"}}, + {"SampleResult", "a text block without its text", map[string]any{"role": "assistant", "content": map[string]any{"type": "text"}, "model": "m"}}, } for _, c := range invalid { if check(t, root, c.def, c.v) == nil { diff --git a/addon/server.go b/addon/server.go index 14f2e3b..6c7f619 100644 --- a/addon/server.go +++ b/addon/server.go @@ -43,19 +43,31 @@ type Config struct { } // Server is an addon's side of the protocol, on stdin and stdout: MCP's -// initialize, tools and resources, the extension's context and outbox, and -// cancellation. Make one with New. +// initialize, tools and resources, the extension's context and outbox, +// cancellation, and sampling the bot's model. Make one with New. type Server struct { cfg Config tools map[string]Tool - nonce string // this run's, in each outbox cursor and op ID + nonce string // this run's, in each outbox cursor, op ID and request ID dirty chan struct{} // the outbox gained ops: tell the bot - mu sync.Mutex - network string - subscribed bool - outbox []held // ops the bot hasn't read past, oldest first - seq int64 // the last op's sequence number + mu sync.Mutex + network string + sampling bool // the bot offered sampling in initialize + watchReplies bool // the bot takes a watch with Replies + subscribed bool + outbox []held // ops the bot hasn't read past, oldest first + seq int64 // the last op's sequence number + wire *wire // Run's, while it runs + asked int64 // the last request's sequence number + pending map[string]chan answer // the requests to the bot awaiting an answer, by ID +} + +// answer is the bot's answer to a request of the addon's: its result, or +// why there is none. +type answer struct { + result json.RawMessage + err error } // held is an op waiting in the outbox, with this run's sequence number, @@ -77,7 +89,8 @@ const ( const MaxImages = 2 // maxLine caps one incoming line. The bot's requests are small: a -// command's arguments or one chat message. +// command's arguments or one chat message; so are its answers to Sample, +// which the addon block's max_tokens caps. const maxLine = 1 << 20 // JSON-RPC's error codes, and MCP's for a resource that isn't there. @@ -95,7 +108,7 @@ func New(c Config) *Server { if c.Now == nil { c.Now = time.Now } - s := &Server{cfg: c, tools: map[string]Tool{}, nonce: randomID(4), dirty: make(chan struct{}, 1)} + s := &Server{cfg: c, tools: map[string]Tool{}, nonce: randomID(4), dirty: make(chan struct{}, 1), pending: map[string]chan answer{}} for _, t := range c.Tools { s.tools[t.Name] = t } @@ -110,6 +123,120 @@ func (s *Server) Network() string { return s.network } +// CanSample reports whether the bot offered sampling in initialize, so +// that Sample may work: it does with the addon block's model permission. +func (s *Server) CanSample() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.sampling +} + +// WatchReplies reports whether the bot said in initialize that it takes a +// watch with Replies. One that didn't would refuse it. +func (s *Server) WatchReplies() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.watchReplies +} + +// BotError is the bot's error answer to a request of the addon's, such as +// a sampling request it refused. +type BotError struct { + Code int + Message string +} + +func (e *BotError) Error() string { return fmt.Sprintf("the bot refused: %s (%d)", e.Message, e.Code) } + +// errStopped is a request's error when Run returns before the bot answers. +var errStopped = errors.New("addon: Run returned before the bot answered") + +// Sample asks the bot's model, through MCP's sampling/createMessage, with +// the cost charged to chat, a chat pseudonym the addon may post in now. It +// needs Run running and a bot that offered sampling (CanSample); without +// either it fails at once. When ctx ends first, it tells the bot the +// request is cancelled and returns ctx's error. An error answer is a +// *BotError. +func (s *Server) Sample(ctx context.Context, chat string, req SampleRequest) (SampleResult, error) { + if err := ctx.Err(); err != nil { + return SampleResult{}, err + } + req.Meta.Chat = chat + s.mu.Lock() + w := s.wire + if w == nil || !s.sampling { + s.mu.Unlock() + if w == nil { + return SampleResult{}, errors.New("addon: Sample needs Run running") + } + return SampleResult{}, errors.New("addon: the bot offers no sampling") + } + s.asked++ + id := s.nonce + "." + strconv.FormatInt(s.asked, 10) + got := make(chan answer, 1) + s.pending[id] = got + s.mu.Unlock() + if err := w.send(request{JSONRPC: "2.0", ID: id, Method: "sampling/createMessage", Params: req}); err != nil { + if s.forget(id) { + return SampleResult{}, err + } + } + var a answer + select { + case a = <-got: + case <-ctx.Done(): + if s.forget(id) { + w.send(notification{JSONRPC: "2.0", Method: "notifications/cancelled", Params: struct { + RequestID string `json:"requestId"` + }{id}}) + return SampleResult{}, ctx.Err() + } + a = <-got // answered as ctx ended + } + if a.err != nil { + return SampleResult{}, a.err + } + var r SampleResult + if err := json.Unmarshal(a.result, &r); err != nil { + return SampleResult{}, fmt.Errorf("addon: the bot's sampling result: %w", err) + } + return r, nil +} + +// forget drops a request still awaiting its answer, and reports whether it +// was. +func (s *Server) forget(id string) bool { + s.mu.Lock() + defer s.mu.Unlock() + _, ok := s.pending[id] + delete(s.pending, id) + return ok +} + +// settle hands the bot's answer to the request it answers, if one awaits +// it. +func (s *Server) settle(m message) { + var id string + if json.Unmarshal(m.ID, &id) != nil { + return + } + s.mu.Lock() + got := s.pending[id] + delete(s.pending, id) + s.mu.Unlock() + if got == nil { + return + } + switch { + case m.Error != nil: + got <- answer{err: &BotError{m.Error.Code, m.Error.Message}} + case len(m.Result) == 0: + got <- answer{err: errors.New("addon: the bot's answer has neither result nor error")} + default: + got <- answer{result: m.Result} + } +} + // Queue adds ops to the outbox, giving each its ID, and tells a subscribed // bot. The bot reads them when it can; save Outbox() afterwards to keep // them over a restart. It queues none, and says why, if one could never @@ -183,10 +310,21 @@ func (s *Server) Run(ctx context.Context, in io.Reader, out io.Writer) error { ctx, cancel := context.WithCancel(ctx) var wg sync.WaitGroup notified := make(chan struct{}) + s.mu.Lock() + s.wire = w + s.mu.Unlock() defer func() { cancel() // first, so the calls in flight stop + s.mu.Lock() + s.wire = nil + for id, got := range s.pending { + got <- answer{err: errStopped} + delete(s.pending, id) + } + s.mu.Unlock() wg.Wait() <-notified + w.close() // so a Sample still finishing writes nothing more }() go func() { defer close(notified); s.notifier(ctx, w) }() if len(s.Outbox()) > 0 { @@ -243,7 +381,13 @@ func (s *Server) Run(ctx context.Context, in io.Reader, out io.Writer) error { mu.Unlock() continue } - if len(m.ID) == 0 || m.Method == "" { // a notification, or a response + if m.Method == "" { // an answer to a request of the addon's + if len(m.ID) > 0 { + s.settle(m) + } + continue + } + if len(m.ID) == 0 { // a notification continue } id := string(m.ID) @@ -268,12 +412,22 @@ func (s *Server) Run(ctx context.Context, in io.Reader, out io.Writer) error { func DecodeArgs(raw json.RawMessage, v any) error { return decode(raw, v) } // message is one JSON-RPC message read: a request, a notification (no ID) -// or a response to a request of the addon's (it sends none). +// or a response to a request of the addon's (no method). type message struct { JSONRPC string `json:"jsonrpc"` ID json.RawMessage `json:"id,omitempty"` Method string `json:"method"` Params json.RawMessage `json:"params,omitempty"` + Result json.RawMessage `json:"result,omitempty"` + Error *rpcError `json:"error,omitempty"` +} + +// request is a request of the addon's to the bot. +type request struct { + JSONRPC string `json:"jsonrpc"` + ID string `json:"id"` + Method string `json:"method"` + Params any `json:"params"` } // response is the answer to one request: its result or an error. @@ -299,10 +453,12 @@ type rpcError struct { func (e *rpcError) Error() string { return e.Message } // wire writes whole messages to stdout, one per line, one at a time: it is -// the only writer of stdout, which carries nothing but the protocol. +// the only writer of stdout, which carries nothing but the protocol. Once +// closed, when Run returns, it writes nothing. type wire struct { - mu sync.Mutex - w io.Writer + mu sync.Mutex + w io.Writer + closed bool } func (w *wire) send(v any) error { @@ -312,10 +468,19 @@ func (w *wire) send(v any) error { } w.mu.Lock() defer w.mu.Unlock() + if w.closed { + return errStopped + } _, err = w.w.Write(append(data, '\n')) return err } +func (w *wire) close() { + w.mu.Lock() + w.closed = true + w.mu.Unlock() +} + // handler answers one request's params with a result, or an *rpcError. type handler func(ctx context.Context, params json.RawMessage) (any, error) @@ -449,11 +614,15 @@ func (s *Server) methods() map[string]handler { var p struct { Capabilities struct { Experimental map[string]Capability `json:"experimental"` + Sampling *struct{} `json:"sampling"` } `json:"capabilities"` } json.Unmarshal(raw, &p) // optional: a bot that offers no network still gets an answer + addon := p.Capabilities.Experimental[KeyAddon] s.mu.Lock() - s.network = p.Capabilities.Experimental[KeyAddon].Network + s.network = addon.Network + s.watchReplies = addon.WatchReplies + s.sampling = p.Capabilities.Sampling != nil s.mu.Unlock() r := initializeResult{ProtocolVersion: Protocol, ServerInfo: serverInfo{Name: s.cfg.Name, Title: s.cfg.Title, Version: s.cfg.Version}} r.Capabilities.Experimental = map[string]Capability{KeyAddon: {Version: Version}} diff --git a/addon/server_test.go b/addon/server_test.go index 07e6720..364e6b7 100644 --- a/addon/server_test.go +++ b/addon/server_test.go @@ -4,6 +4,7 @@ import ( "bufio" "context" "encoding/json" + "errors" "io" "strconv" "strings" @@ -443,3 +444,262 @@ func TestEmptyResult(t *testing.T) { t.Errorf("result %s", resp.Result) } } + +// asked waits for the server's request of method, skipping other lines, +// and returns its ID and params. +func (c *client) asked(method string) (id json.RawMessage, params json.RawMessage) { + c.t.Helper() + timeout := time.After(5 * time.Second) + for { + select { + case line := <-c.lines: + var m message + json.Unmarshal(line, &m) + if m.Method == method && len(m.ID) > 0 { + return m.ID, m.Params + } + case <-timeout: + c.t.Fatalf("no %s", method) + } + } +} + +// initializeSampling initializes as a bot offering sampling and reply +// watches. +func initializeSampling(c *client) { + c.result("initialize", map[string]any{ + "protocolVersion": Protocol, + "capabilities": map[string]any{"sampling": map[string]any{}, + "experimental": map[string]any{KeyAddon: Capability{Version: Version, Network: "signal", WatchReplies: true}}}, + }, nil) +} + +// sampled is Sample's outcome, run on its own goroutine. +type sampled struct { + r SampleResult + err error +} + +func sampleAsync(ctx context.Context, s *Server, req SampleRequest) chan sampled { + done := make(chan sampled, 1) + go func() { + r, err := s.Sample(ctx, chatID, req) + done <- sampled{r, err} + }() + return done +} + +func waitSampled(t *testing.T, done chan sampled) sampled { + t.Helper() + select { + case got := <-done: + return got + case <-time.After(5 * time.Second): + t.Fatal("Sample didn't return") + } + return sampled{} +} + +var question = SampleRequest{Messages: []SampleMessage{{Role: "user", Content: Content{Type: "text", Text: "a question"}}}, SystemPrompt: "Be brief.", MaxTokens: 100} + +// The bot's initialize says whether Sample and reply watches may work. +func TestCanSample(t *testing.T) { + s := New(Config{Name: "game"}) + c := start(t, s) + initialize(c, "signal") + if s.CanSample() || s.WatchReplies() { + t.Errorf("without them: sample %v, replies %v", s.CanSample(), s.WatchReplies()) + } + if _, err := s.Sample(context.Background(), "c_one", question); err == nil { + t.Error("Sample worked with no sampling offered") + } + initializeSampling(c) + if !s.CanSample() || !s.WatchReplies() || s.Network() != "signal" { + t.Errorf("with them: sample %v, replies %v, network %q", s.CanSample(), s.WatchReplies(), s.Network()) + } +} + +// Sample before Run fails at once. +func TestSampleBeforeRun(t *testing.T) { + if _, err := New(Config{Name: "game"}).Sample(context.Background(), "c_one", question); err == nil { + t.Error("Sample worked before Run") + } +} + +// Sample sends sampling/createMessage with the chat in _meta and an ID of +// the server's, and returns the bot's result. +func TestSample(t *testing.T) { + s := New(Config{Name: "game"}) + c := start(t, s) + initializeSampling(c) + done := sampleAsync(context.Background(), s, question) + id, params := c.asked("sampling/createMessage") + var p SampleRequest + if err := json.Unmarshal(params, &p); err != nil || p.Meta.Chat != chatID || p.MaxTokens != 100 || p.SystemPrompt != "Be brief." || + len(p.Messages) != 1 || p.Messages[0].Content.Text != "a question" { + t.Errorf("params %s", params) + } + var raw any + json.Unmarshal(params, &raw) + if err := validate(schema(t), map[string]any{"$ref": "#/$defs/SampleRequest"}, raw, "SampleRequest"); err != nil { + t.Error(err) + } + var sid string + if json.Unmarshal(id, &sid) != nil || !strings.HasPrefix(sid, s.nonce+".") { + t.Errorf("ID %s", id) + } + // Another ID is ignored, and the server still serves. + c.send(map[string]any{"jsonrpc": "2.0", "id": "other.1", "result": map[string]any{}}) + c.result("ping", struct{}{}, nil) + c.send(map[string]any{"jsonrpc": "2.0", "id": id, "result": SampleResult{Role: "assistant", Content: Content{Type: "text", Text: "an answer"}, Model: "a-model", StopReason: "endTurn"}}) + got := waitSampled(t, done) + if got.err != nil || got.r.Content.Text != "an answer" || got.r.Model != "a-model" || got.r.StopReason != "endTurn" { + t.Errorf("got %+v", got) + } + // A second request has another ID. + done = sampleAsync(context.Background(), s, question) + id2, _ := c.asked("sampling/createMessage") + if string(id2) == string(id) { + t.Errorf("the same ID twice: %s", id) + } + c.send(map[string]any{"jsonrpc": "2.0", "id": id2, "result": SampleResult{Role: "assistant", Content: Content{Type: "text", Text: "again"}, Model: "m"}}) + if got := waitSampled(t, done); got.err != nil || got.r.Content.Text != "again" { + t.Errorf("second %+v", got) + } +} + +// An error answer is a *BotError with its code and message. +func TestSampleRefused(t *testing.T) { + s := New(Config{Name: "game"}) + c := start(t, s) + initializeSampling(c) + done := sampleAsync(context.Background(), s, question) + id, _ := c.asked("sampling/createMessage") + c.send(map[string]any{"jsonrpc": "2.0", "id": id, "error": map[string]any{"code": -32600, "message": "over budget"}}) + got := waitSampled(t, done) + var be *BotError + if !errors.As(got.err, &be) || be.Code != -32600 || be.Message != "over budget" { + t.Errorf("got %+v", got) + } +} + +// When Sample's context ends, the bot is told, and a late answer is +// ignored. +func TestSampleCancel(t *testing.T) { + s := New(Config{Name: "game"}) + c := start(t, s) + initializeSampling(c) + ctx, cancel := context.WithCancel(context.Background()) + done := sampleAsync(ctx, s, question) + id, _ := c.asked("sampling/createMessage") + cancel() + timeout := time.After(5 * time.Second) + for cancelled := false; !cancelled; { + select { + case line := <-c.lines: + var m struct { + Method string + Params struct { + RequestID json.RawMessage `json:"requestId"` + } + } + json.Unmarshal(line, &m) + cancelled = m.Method == "notifications/cancelled" && string(m.Params.RequestID) == string(id) + case <-timeout: + t.Fatal("no notifications/cancelled") + } + } + if got := waitSampled(t, done); !errors.Is(got.err, context.Canceled) { + t.Errorf("got %+v", got) + } + c.send(map[string]any{"jsonrpc": "2.0", "id": id, "result": SampleResult{Role: "assistant", Content: Content{Type: "text", Text: "late"}, Model: "m"}}) + c.result("ping", struct{}{}, nil) +} + +// A Sample awaiting its answer when Run returns fails, and one after fails +// at once. +func TestSampleRunEnds(t *testing.T) { + s := New(Config{Name: "game"}) + c := start(t, s) + initializeSampling(c) + done := sampleAsync(context.Background(), s, question) + c.asked("sampling/createMessage") + c.in.Close() + if got := waitSampled(t, done); !errors.Is(got.err, errStopped) { + t.Errorf("got %+v", got) + } + select { + case got := <-sampleAsync(context.Background(), s, question): + if got.err == nil { + t.Error("Sample worked after Run returned") + } + case <-time.After(time.Second): + t.Error("Sample after Run waited") + } +} + +// A tool's call may sample; when Run stops mid-call, the call's Sample +// ends and nothing is written after Run returns. +func TestSampleInACall(t *testing.T) { + ended := make(chan error, 1) + var s *Server + s = New(Config{Name: "game", Tools: []Tool{{Name: "quiz", Call: func(ctx context.Context, c *Context, _ json.RawMessage) (Result, error) { + _, err := s.Sample(ctx, c.Chat, question) + ended <- err + return Text("stopped"), nil + }}}}) + inR, inW := io.Pipe() + outR, outW := io.Pipe() + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- s.Run(ctx, inR, outW) }() + lines := make(chan string, 16) + go func() { + sc := bufio.NewScanner(outR) + for sc.Scan() { + lines <- sc.Text() + } + close(lines) + }() + send := func(v string) { + if _, err := inW.Write([]byte(v + "\n")); err != nil { + t.Fatal(err) + } + } + send(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"capabilities":{"sampling":{}}}}`) + for line := range lines { // requests are answered at once, so wait + if strings.Contains(line, `"id":1`) { + break + } + } + send(`{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"quiz","_meta":{"` + KeyContext + `":{"chat":"c_one"}}}}`) + for line := range lines { + if strings.Contains(line, "sampling/createMessage") { + break + } + } + cancel() + select { + case err := <-done: + if err != context.Canceled { + t.Errorf("Run returned %v", err) + } + case <-time.After(5 * time.Second): + t.Fatal("Run didn't return") + } + select { + case err := <-ended: + if err == nil { + t.Error("the call's Sample worked") + } + default: + t.Error("the call's Sample hadn't returned when Run did") + } + outW.Close() + for line := range lines { + if !strings.Contains(line, "notifications/cancelled") && !strings.Contains(line, `"id":2`) { + t.Errorf("after the cancel: %s", line) + } + } + inW.Close() +} diff --git a/addon/types.go b/addon/types.go index 1d45064..9bfb003 100644 --- a/addon/types.go +++ b/addon/types.go @@ -26,22 +26,25 @@ const ( ) // The extension's keys: the capability both sides offer in initialize, and -// the _meta keys on a call (the context), a tool (who may call it) and a -// result (a watch to start, a reaction to put on the message). +// the _meta keys on a call (the context), a tool (who may call it), a +// result (a watch to start, a reaction to put on the message) and a +// sampling request (the chat that pays). const ( KeyAddon = Vendor + "addon" KeyContext = Vendor + "context" KeyVisibility = Vendor + "visibility" KeyWatch = Vendor + "watch" KeyReact = Vendor + "react" + KeyChat = Vendor + "chat" ) // Capability is the extension's entry in capabilities.experimental under -// KeyAddon. The bot offers its chat network; an addon answers with the -// version alone. +// KeyAddon. The bot offers its chat network and what it can do; an addon +// answers with the version alone. type Capability struct { - Version int `json:"version"` - Network string `json:"network,omitempty"` // the bot's chat network, as it names itself: "signal", "telegram" + Version int `json:"version"` + Network string `json:"network,omitempty"` // the bot's chat network, as it names itself: "signal", "telegram" + WatchReplies bool `json:"watchReplies,omitempty"` // the bot's: it takes a watch with Replies } // Context is the message a call the bot makes came from, in the call's @@ -62,13 +65,17 @@ type Context struct { // Watch is what a direct command's result asks for, in its _meta under // KeyWatch: the messages matching Pattern in the command's chat, until -// Until, go to Tool instead of the model. +// Until, go to Tool instead of the model. With Replies, it takes only +// replies to the addon's own messages, and Pattern, which may then be +// empty, must match them too; offer it only to a bot whose Capability has +// WatchReplies. type Watch struct { ID string `json:"id"` - Pattern string `json:"pattern"` // RE2 - Until string `json:"until"` // RFC 3339 - Tool string `json:"tool"` // called with each message it matches, as {"text": …} - Guard string `json:"guard,omitempty"` // the answer, while it lasts, to a message addressed to the bot that quotes the command's pictures + Pattern string `json:"pattern,omitempty"` // RE2; needed unless Replies + Until string `json:"until"` // RFC 3339 + Tool string `json:"tool"` // called with each message it matches, as {"text": …} + Guard string `json:"guard,omitempty"` // the answer, while it lasts, to a message addressed to the bot that quotes the command's pictures + Replies bool `json:"replies,omitempty"` // only replies to the command's answer and the addon's posts in the chat while it lives } // Content is one block of a tool's result: text, or an image. @@ -140,3 +147,35 @@ type Held struct { Op Op `json:"op"` Queued time.Time `json:"queued"` } + +// SampleRequest is MCP's sampling/createMessage params, as an addon asks +// the bot's model (Server.Sample): the bot runs it on its own model and +// charges the chat in Meta. The bot takes text alone. +type SampleRequest struct { + Messages []SampleMessage `json:"messages"` + SystemPrompt string `json:"systemPrompt,omitempty"` + MaxTokens int `json:"maxTokens"` // the bot caps it at the addon block's max_tokens + Temperature *float64 `json:"temperature,omitempty"` // nil is the model's own + Meta SampleMeta `json:"_meta"` +} + +// SampleMeta is a sampling request's _meta. +type SampleMeta struct { + Chat string `json:"io.github.robdevops.signalbot/chat"` // c_…, the chat that pays, one the addon may post in now +} + +// SampleMessage is one message of a sampling request: what the user or the +// assistant said. +type SampleMessage struct { + Role string `json:"role"` // "user" or "assistant" + Content Content `json:"content"` +} + +// SampleResult is the bot's answer to a sampling request: MCP's +// CreateMessageResult. +type SampleResult struct { + Role string `json:"role"` // "assistant" + Content Content `json:"content"` + Model string `json:"model"` // the model that wrote it + StopReason string `json:"stopReason,omitempty"` // "endTurn", "maxTokens", … +} diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index 9247563..a3f9643 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -18,7 +18,7 @@ Every setting, read from the environment (`/etc/signalbot.env` in the install). | `CHARTS` | `true` | The built-in line and pie charts. Set to `no` if you don't want charts, or wish to use your own charts MCP server ([MCP connectors](FILES_LINKS_TOOLS_MCP.md#mcp-connectors)); `go build -tags nocharts` leaves them out of the binary too | | `IMAGE_MODEL` | `openai/gpt-image-2` | The OpenRouter image model the bot makes pictures with when asked for a drawing, art, a diagram or the like; `off` turns pictures off. Only on OpenRouter; each picture's cost counts toward `DAILY_BUDGET`. See [Images](FILES_LINKS_TOOLS_MCP.md#images) | | `IMAGE_QUALITY` | `medium` | `low`, `medium`, `high` or `auto`: higher costs more; the log shows what each picture cost | -| `DAILY_BUDGET` | `1` | US dollars each group and each DM may spend on the model a day, midnight to midnight in `TZ`; `0` for no cap. Once a chat reaches it, the bot says once "I've reached today's spending limit for this chat, so I'll answer again in 5 hours. Commands that don't need me to think still work." and until midnight reacts ⏳ to anything else there, answering only commands that don't use the model. Today's spending is saved in `budget.json` in `STATE_DIRECTORY`, so a restart doesn't reset it. Only OpenRouter reports costs, so with another API it isn't applied | +| `DAILY_BUDGET` | `1` | US dollars each group and each DM may spend on the model a day, midnight to midnight in `TZ`; `0` for no cap. Once a chat reaches it, the bot says once "I've reached today's spending limit for this chat, so I'll answer again in 5 hours. Commands that don't need me to think still work." and until midnight reacts ⏳ to anything else there, answering only commands that don't use the model. Today's spending is saved in `budget.json` in `STATE_DIRECTORY`, so a restart doesn't reset it. An [addon](FILES_LINKS_TOOLS_MCP.md#addons) allowed the model has its requests charged to the chat it names, and refused once that chat is over. Only OpenRouter reports costs, so with another API it isn't applied | | `DARKMODE` | `off` | Chart colours: `off` for light charts (also `false`, `no`, `0`, `light`), `on` for dark (also `true`, `yes`, `1`, `dark`), or the hours charts are dark in `TZ`, such as `18:00-6:00`, `18-6` or `6pm-6am` | | `FILES` | `true` | Show the model the files people send ([Files](FILES_LINKS_TOOLS_MCP.md#files)): PDFs, audio, text and Office documents. Off (`false`, `off`, `0`), files are never fetched, and the model is told only that a file was attached, so it can say it can't read it | | `GROUP_CONTEXT` | `true` | Remember group messages not addressed to the bot as context, so "what do you think @bot" works without replying to the message; they are never logged | diff --git a/docs/FILES_LINKS_TOOLS_MCP.md b/docs/FILES_LINKS_TOOLS_MCP.md index 3fb9482..856c755 100644 --- a/docs/FILES_LINKS_TOOLS_MCP.md +++ b/docs/FILES_LINKS_TOOLS_MCP.md @@ -59,6 +59,11 @@ The model can call tools from [MCP](https://modelcontextprotocol.io) servers, re "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m", "timeout": "60s"}}, "addon": {"chats": ["all"], "dms": false, "post": true, "react": true, "watch": true, "watch_max": "1h"} }, + "quiz": { + "command": "/addons/quiz", + "chat_commands": {"quiz": {"tool": "quiz", "direct": true, "example": "/quiz 80s music", "timeout": "90s"}}, + "addon": {"chats": ["all"], "post": true, "react": true, "watch": true, "model": {"per_hour": 30, "max_tokens": 4000}} + }, "files": { "command": "uvx", "args": ["some-mcp-server"], @@ -115,6 +120,7 @@ An addon written in Go can use the package [`github.com/robdevops/signalbot/addo "watch_max": "1h", "names": false, "global_ids": false, "rate": {"per_minute": 20, "burst": 5} + // "model": {"per_hour": 30, "max_tokens": 4000}, only for an addon that asks the model } } ``` @@ -130,6 +136,7 @@ An addon written in Go can use the package [`github.com/robdevops/signalbot/addo | `names` | each call it gets carries the sender's display name. Off, it gets none | | `global_ids` | a person has the same ID in every chat. Off, each chat gives them a different one, so the addon can't follow someone between groups | | `rate` | its posts and reactions a minute in each chat (`per_minute`, default 20), with bursts of `burst` (default 5) | +| `model` | it may ask the bot's model (below): at most `per_hour` requests an hour, all chats together (default 30), each answer at most `max_tokens` tokens (default 4000, at most 32000) | Each permission is off unless set. For an addon, `chats`, `dms` and these permissions are the gate: anyone in an allowed chat can use its commands, and nothing it does reaches another chat. @@ -137,7 +144,8 @@ Each permission is off unless set. For an addon, `chats`, `dms` and these permis - **Direct commands.** `"direct": true` on a chat command has the bot call the addon's tool itself, with the text after the command, and send what it answers (text, and up to 2 pictures) without the model. The tool must be marked for the bot, and is then never offered to the model. A call has 15 seconds, or the command's `timeout`, from 1s to 2m (`"timeout": "60s"`), for an addon that may take a while, such as GeoGuess finding a photo; while it runs the chat sees the bot typing. At most 2 run at once per addon; a third is told the addon is busy, so with a long `timeout`, two calls that wait (two chats each waiting for a GeoGuess photo) make even a quick command such as `/geo scores` wait for one to end. When it fails, the chat gets a short line ("GeoGuess couldn't do that just now."), never the addon's own error text. An addon with no tool for the model has its commands named in the prompt's list of what the bot has, so the model can point people to them. - **Hidden tools.** A tool whose `_meta` says it is for the bot alone (`io.github.robdevops.signalbot/visibility` without `"model"`, or MCP Apps' `ui.visibility` without `"model"`) is never offered to the model or listed as one of its tools, so tools that read chat text stay out of its hands. -- **Watches.** A direct command's answer can ask for a watch on its chat: a pattern, such as map links, until a time at most `watch_max` away. While it lasts, a message there that matches goes to the addon instead: it isn't answered, isn't sent to the model, and isn't kept in history, even as group context; so does an edit of it later. The addon may react to it, so people see it was counted. A pattern that would match ordinary chat ("lol", "see you at 5", a news link, …) is refused, so a watch can't become a feed of everything said; at most 8 run in a chat at once. While a watch lasts, a reply to the command's pictures that asks the bot gets the addon's set answer (GeoGuess's "No hints during a round 😉"), not the model's. +- **Watches.** A direct command's answer can ask for a watch on its chat: a pattern, such as map links, until a time at most `watch_max` away. While it lasts, a message there that matches goes to the addon instead: it isn't answered, isn't sent to the model, and isn't kept in history, even as group context; so does an edit of it later. The addon may react to it, so people see it was counted. A pattern that would match ordinary chat ("lol", "see you at 5", a news link, …) is refused, so a watch can't become a feed of everything said; at most 8 run in a chat at once. While a watch lasts, a reply to the command's pictures that asks the bot gets the addon's set answer (GeoGuess's "No hints during a round 😉"), not the model's. A reply watch (`"replies": true`) takes instead only replies to the addon's own messages in the chat while it lasts, the command's answer and its posts, that ask the bot, such as a quiz's free-text answers; its pattern, if it has one, must match them too, and isn't held to the ordinary-chat rule, since such a reply is meant for the addon. +- **Model.** With `model`, an addon may ask the bot's model for text, through MCP's standard sampling request (`sampling/createMessage`): it sends the prompt, and the bot runs it on its own model, with its own key, and sends back the answer. The addon needs no key or provider of its own. The bot offers this only to an addon with `model`, and only while it has a model; MCP suggests a person approve each request, and here the `model` setting is that approval. Each request names the chat it is for, one the addon may post in now, and is charged to that chat's `DAILY_BUDGET`: one over its budget is refused, and so is one past `per_hour`. A request is text only, at most 16 messages and 32 KB, with one in flight per addon at a time. Only its outcome, time, size, tokens and cost are logged, never the prompt or the answer. - **Outbox.** An addon posts when it likes by queueing posts, reactions and the end of a watch in its outbox, an MCP resource the bot subscribes to (`signalbot://outbox`), and saying it changed; the bot reads it at once. It may post or react only in a chat where it was used, by a command or a watch, in the last 24 hours, and only within `rate`. Its posts go through the chat's queue like any message, never more than one at a time, and history keeps them as the bot's, labelled with the addon's name (`[GeoGuess] …`), so what an addon writes never poses as a person. - **Settings.** An addon has no `env` block. It gets `PATH`, `HOME`, the bot's time zone (`TZ`) and proxy settings (`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, and `SSL_CERT_FILE` or `SSL_CERT_DIR` for a custom CA) if set, and every variable in the bot's environment (`/etc/signalbot.env`) that starts with its server's name in capitals, anything but letters and digits as `_`, then `_`: the server `geo` gets `GEO_STATE_DIR`, `GEO_MAPILLARY_TOKEN` and so on, and never the bot's own keys. A name whose prefix starts one of the bot's settings (such as `model`, `signal` or `mcp`) is a config error. If an addon keeps files, give it a directory under its prefix and create it, writable by the bot's user. - **Logs.** The bot logs an addon's commands, calls and drops by name, outcome, time and size, never what was said. An addon's stderr is counted ("addon geo wrote 3 lines (210 bytes) to stderr", at most once a minute and once more when it exits), never logged, since it may echo a message. To debug an addon, run it on its own with stderr going to your own file. diff --git a/docs/MODELS.md b/docs/MODELS.md index 33c4534..10a7602 100644 --- a/docs/MODELS.md +++ b/docs/MODELS.md @@ -26,7 +26,7 @@ What differs from OpenRouter: ## No model -With neither `MODEL_API_KEY` nor `MODEL_API_URL` set, the bot runs without a model, and its startup log warns "no model: set MODEL_API_KEY (or MODEL_API_URL for a provider that needs no key); until then only commands are answered". Commands still work: `/intro`, `/schedule` and its aliases, and scheduled plain text is posted as written; `/intro` then says it runs no model. Anything else addressed to it, a mention, a reply or a DM, gets no reply, no typing indicator and no model request. Nothing is kept in history, not even group context, and MCP servers aren't started. +With neither `MODEL_API_KEY` nor `MODEL_API_URL` set, the bot runs without a model, and its startup log warns "no model: set MODEL_API_KEY (or MODEL_API_URL for a provider that needs no key); until then only commands are answered". Commands still work: `/intro`, `/schedule` and its aliases, and scheduled plain text is posted as written; `/intro` then says it runs no model. Anything else addressed to it, a mention, a reply or a DM, gets no reply, no typing indicator and no model request. Nothing is kept in history, not even group context. Of the MCP servers, only [addons](FILES_LINKS_TOOLS_MCP.md#addons) are started, and none is offered the model. --- diff --git a/examples/signalbot-mcp.json b/examples/signalbot-mcp.json index e306e08..7d291ef 100644 --- a/examples/signalbot-mcp.json +++ b/examples/signalbot-mcp.json @@ -15,6 +15,11 @@ "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m", "timeout": "60s"}}, "addon": {"chats": ["all"], "dms": false, "post": true, "react": true, "watch": true, "watch_max": "1h"} }, + "quiz": { + "command": "/addons/quiz", + "chat_commands": {"quiz": {"tool": "quiz", "direct": true, "example": "/quiz 80s music", "timeout": "90s"}}, + "addon": {"chats": ["all"], "post": true, "react": true, "watch": true, "model": {"per_hour": 30, "max_tokens": 4000}} + }, "files": { "command": "uvx", "args": ["some-mcp-server"], diff --git a/internal/bot/host.go b/internal/bot/host.go index 713e1ad..e6d0a7b 100644 --- a/internal/bot/host.go +++ b/internal/bot/host.go @@ -17,6 +17,7 @@ import ( "github.com/robdevops/signalbot/internal/kit/logx" "github.com/robdevops/signalbot/internal/kit/state" "github.com/robdevops/signalbot/internal/kit/txt" + "github.com/robdevops/signalbot/internal/model" ) // The ports. Features call them while they register, before Run. @@ -106,9 +107,28 @@ func (b *Bot) CallAPI(ctx context.Context, path string, body map[string]any) (js if b.ai == nil { return nil, errors.New("no model") } - return b.ai.Call(ctx, path, body) + chat, charged := feature.ChargedChat(ctx) + if model.Metered(ctx) || !charged { // a tool's cost counts toward its reply; with neither, Call refuses + return b.ai.Call(ctx, path, body) + } + key := chat.Key() + if b.budget != nil { + if over, _ := b.budget.over(key); over { + return nil, errOverBudget + } + } + ctx, spent := model.Meter(ctx) + data, err := b.ai.Call(ctx, path, body) + if cost, ok := spent(); ok && b.budget != nil { + b.budget.add(key, cost) + } + return data, err } +// errOverBudget refuses a call charged to a chat that has spent its daily +// budget. +var errOverBudget = errors.New("the chat has reached its daily budget") + func (b *Bot) Go(fn func(context.Context)) { b.running.Go(func() { fn(b.ctx) }) } diff --git a/internal/bot/host_test.go b/internal/bot/host_test.go index d9c9f12..b5b4b37 100644 --- a/internal/bot/host_test.go +++ b/internal/bot/host_test.go @@ -911,3 +911,62 @@ func TestReact(t *testing.T) { t.Fatalf("logs:\n%s", h.logs) } } + +// Outside a tool, CallAPI is made only for a ctx charged to a chat: it is +// refused when that chat is over its daily budget, and what it cost is +// added to that chat's budget. The model is the bot's own. +func TestCallAPICharged(t *testing.T) { + dir := t.TempDir() + h := start(t, options{cfg: func(c *config.Config) { c.DailyBudget, c.StateDir = 0.0015, dir }}) + alice := feature.Chat{User: "+15550000001"} + group := feature.Chat{GroupID: "Z3JvdXA="} + body := map[string]any{"model": "x/dearer", "messages": []any{map[string]any{"role": "user", "content": "hi"}}} + if _, err := h.b.CallAPI(context.Background(), "/chat/completions", body); err == nil { + t.Fatal("a call neither from a tool nor charged was made") + } + if n := len(h.requests()); n != 0 { + t.Fatalf("%d requests", n) + } + charged := feature.ChargeTo(context.Background(), alice) + if data, err := h.b.CallAPI(charged, "/chat/completions", body); err != nil || !strings.Contains(string(data), `"ok"`) { + t.Fatalf("got %s, %v", data, err) + } + if r := h.requests(); len(r) != 1 || r[0]["model"] != "test/test-model" { + t.Fatalf("requests %v", r) + } + if over, _ := h.b.budget.over(alice.Key()); over { + t.Fatal("over after $0.001") + } + if _, err := h.b.CallAPI(charged, "/chat/completions", body); err != nil { + t.Fatal(err) + } + if over, _ := h.b.budget.over(alice.Key()); !over { + t.Fatal("the cost wasn't added to the chat's budget") + } + if _, err := h.b.CallAPI(charged, "/chat/completions", body); err != errOverBudget { + t.Fatalf("over budget: %v", err) + } + if n := len(h.requests()); n != 2 { + t.Fatalf("%d requests", n) + } + if _, err := h.b.CallAPI(feature.ChargeTo(context.Background(), group), "/chat/completions", body); err != nil { + t.Fatalf("another chat: %v", err) + } + if over, _ := h.b.budget.over(group.Key()); over { + t.Fatal("another chat is over") + } +} + +// With no daily budget, a charged call is made all the same. +func TestCallAPIChargedNoBudget(t *testing.T) { + h := start(t, options{}) + charged := feature.ChargeTo(context.Background(), feature.Chat{User: "+15550000002"}) + for range 3 { + if _, err := h.b.CallAPI(charged, "/chat/completions", map[string]any{}); err != nil { + t.Fatal(err) + } + } + if h.b.budget != nil || len(h.requests()) != 3 { + t.Fatalf("budget %v, %d requests", h.b.budget, len(h.requests())) + } +} diff --git a/internal/feature/feature.go b/internal/feature/feature.go index b741362..3fb5e9a 100644 --- a/internal/feature/feature.go +++ b/internal/feature/feature.go @@ -31,6 +31,20 @@ func (c Chat) Key() string { return "u:" + c.User } +type chargeKey struct{} + +// ChargeTo is ctx naming chat as the one that pays for the model's API +// calls made with it outside a tool, through Host.CallAPI. +func ChargeTo(ctx context.Context, chat Chat) context.Context { + return context.WithValue(ctx, chargeKey{}, chat) +} + +// ChargedChat is the chat ChargeTo named in ctx, if any. +func ChargedChat(ctx context.Context) (Chat, bool) { + c, ok := ctx.Value(chargeKey{}).(Chat) + return c, ok +} + // Message is a message posted in a chat. type Message struct { Chat Chat @@ -276,11 +290,17 @@ type Host interface { React(chat Chat, msg Message, emoji string) // Groups lists the groups the bot shares with user. Groups(ctx context.Context, user string) ([]Group, error) - // CallAPI posts body as JSON to path (such as "/images") at the model's - // API and returns the response body, from a tool's Run only, so what it - // cost counts toward the reply and the chat's daily budget. The core - // adds the key, and on OpenRouter asks for providers that don't collect - // the data; a feature never sees the key. + // CallAPI posts body as JSON to path (such as "/images" or + // "/chat/completions") at the model's API and returns the response + // body. Inside a tool's Run, what it cost counts toward the reply and + // the chat's daily budget. Outside one, ctx must come from ChargeTo: + // the core refuses the call when that chat is over its daily budget, + // makes it, and adds what it cost to that chat's budget. Without + // either, it refuses. For "/chat/completions" the core sets the model + // to the bot's own, whatever the body says, and on OpenRouter asks for + // the cost to be reported. The core adds the key, and on OpenRouter + // asks for providers that don't collect the data; a feature never sees + // the key. CallAPI(ctx context.Context, path string, body map[string]any) (json.RawMessage, error) // Redact replaces every name and ID of anyone but the bot in text with // "redacted", for logging text the bot doesn't control. diff --git a/internal/feature/featuretest/featuretest.go b/internal/feature/featuretest/featuretest.go index 6fad5a6..e856c9d 100644 --- a/internal/feature/featuretest/featuretest.go +++ b/internal/feature/featuretest/featuretest.go @@ -40,6 +40,7 @@ type Host struct { posts []feature.Post reactions []Reaction stores []string + charged []feature.Chat commands feature.Commands life context.Context // what Go passes; ended by Stop end context.CancelFunc @@ -161,14 +162,27 @@ func (h *Host) Env(key, def string) string { func (h *Host) Info() feature.Info { return h.Bot } -// CallAPI returns what API does; nil fails. +// CallAPI returns what API does; nil fails. It records the chat ctx is +// charged to, if any, for Charged. func (h *Host) CallAPI(ctx context.Context, path string, body map[string]any) (json.RawMessage, error) { + if chat, ok := feature.ChargedChat(ctx); ok { + h.mu.Lock() + h.charged = append(h.charged, chat) + h.mu.Unlock() + } if h.API == nil { return nil, errors.New("no API") } return h.API(ctx, path, body) } +// Charged lists the chats CallAPI's calls were charged to, in order. +func (h *Host) Charged() []feature.Chat { + h.mu.Lock() + defer h.mu.Unlock() + return slices.Clone(h.charged) +} + // Store opens a saved state as the core does, in the directory // Settings["STATE_DIRECTORY"] names (the working directory if unset): each // name once, refusing the names the core refuses, and failing with StoreErr diff --git a/internal/feature/featuretest/featuretest_test.go b/internal/feature/featuretest/featuretest_test.go index 5353c7d..3d80cd2 100644 --- a/internal/feature/featuretest/featuretest_test.go +++ b/internal/feature/featuretest/featuretest_test.go @@ -119,3 +119,19 @@ func TestStoreNames(t *testing.T) { } } } + +// CallAPI records the chat a call is charged to, if any. +func TestCallAPICharged(t *testing.T) { + h := New() + alice := feature.Chat{User: "alice"} + h.CallAPI(context.Background(), "/images", nil) + if _, err := h.CallAPI(feature.ChargeTo(context.Background(), alice), "/chat/completions", nil); err == nil { + t.Error("no API, yet a call worked") + } + if got := h.Charged(); len(got) != 1 || got[0] != alice { + t.Errorf("charged %v", got) + } + if c, ok := feature.ChargedChat(context.Background()); ok { + t.Errorf("a plain ctx is charged to %v", c) + } +} diff --git a/internal/features/mcp/addon.go b/internal/features/mcp/addon.go index 53a3e14..1a0642f 100644 --- a/internal/features/mcp/addon.go +++ b/internal/features/mcp/addon.go @@ -24,30 +24,46 @@ import ( // addonConfig is a server's "addon" block: what an addon may do, and where. type addonConfig struct { - Chats []string `json:"chats"` // group IDs, or "all" - DMs bool `json:"dms"` - Post bool `json:"post"` - React bool `json:"react"` - Watch bool `json:"watch"` - WatchMax string `json:"watch_max"` // how long a watch may last: 1h by default, 24h at most - Names bool `json:"names"` // the context carries the sender's display name - GlobalIDs bool `json:"global_ids"` - Rate rateConfig `json:"rate"` + Chats []string `json:"chats"` // group IDs, or "all" + DMs bool `json:"dms"` + Post bool `json:"post"` + React bool `json:"react"` + Watch bool `json:"watch"` + WatchMax string `json:"watch_max"` // how long a watch may last: 1h by default, 24h at most + Names bool `json:"names"` // the context carries the sender's display name + GlobalIDs bool `json:"global_ids"` + Rate rateConfig `json:"rate"` + Model *modelConfig `json:"model"` // nil: it may not ask the bot's model watchMax time.Duration // WatchMax, read } +// modelConfig lets an addon ask the bot's model, through MCP sampling: at +// most PerHour requests an hour, of at most MaxTokens each. +type modelConfig struct { + PerHour int `json:"per_hour"` + MaxTokens int `json:"max_tokens"` +} + +// The model permission's defaults, and the most max_tokens may be. +const ( + defaultPerHour = 30 + defaultMaxTokens = 4000 + maxMaxTokens = 32000 +) + // rateConfig caps an addon's posts and reactions in each chat. type rateConfig struct { PerMinute int `json:"per_minute"` Burst int `json:"burst"` } -// addonSettings are the keys an addon block may have, and rateSettings its -// rate's. +// addonSettings are the keys an addon block may have, rateSettings its +// rate's and modelSettings its model's. var ( - addonSettings = []string{"chats", "dms", "post", "react", "watch", "watch_max", "names", "global_ids", "rate"} + addonSettings = []string{"chats", "dms", "post", "react", "watch", "watch_max", "names", "global_ids", "rate", "model"} rateSettings = []string{"per_minute", "burst"} + modelSettings = []string{"per_hour", "max_tokens"} ) // coreSettings are signalbot's own settings, docs/CONFIGURATION.md's table @@ -95,6 +111,11 @@ func (a *addonConfig) check(entry map[string]json.RawMessage) error { if err := unknown(rate, rateSettings); err != nil { return fmt.Errorf("addon rate: %v", err) } + var model map[string]json.RawMessage + json.Unmarshal(entry["model"], &model) + if err := unknown(model, modelSettings); err != nil { + return fmt.Errorf("addon model: %v", err) + } for _, c := range a.Chats { switch { case c == "all" && len(a.Chats) > 1: @@ -115,6 +136,15 @@ func (a *addonConfig) check(entry map[string]json.RawMessage) error { return errors.New("addon rate: per_minute and burst can't be below 0") } a.Rate.PerMinute, a.Rate.Burst = cmp.Or(a.Rate.PerMinute, 20), cmp.Or(a.Rate.Burst, 5) + if m := a.Model; m != nil { + switch { + case m.PerHour < 0 || m.MaxTokens < 0: + return errors.New("addon model: per_hour and max_tokens can't be below 0") + case m.MaxTokens > maxMaxTokens: + return fmt.Errorf("addon model: max_tokens can't be over %d", maxMaxTokens) + } + m.PerHour, m.MaxTokens = cmp.Or(m.PerHour, defaultPerHour), cmp.Or(m.MaxTokens, defaultMaxTokens) + } return nil } @@ -219,6 +249,7 @@ type addon struct { matches chan match // matched messages, for the watch worker posts *limiter // its posts and reactions, per chat calls *limiter // the watch worker's calls, per chat + asks *limiter // its requests to the model, all chats as one; nil without the permission mu sync.Mutex refs map[string]ref // by ref @@ -255,7 +286,7 @@ func newAddon(server, title string, cfg addonConfig, secret []byte, c conn, bot return &addon{server: server, title: title, cfg: cfg, key: mac.Sum(nil), conn: c, bot: bot, busy: make(chan struct{}, maxDirect), now: time.Now, changed: func() {}, dirty: make(chan struct{}, 1), up: make(chan struct{}, 1), settled: make(chan struct{}, 1), - matches: make(chan match, maxMatches), posts: newLimiter(cfg.Rate), calls: newLimiter(watchRate), + matches: make(chan match, maxMatches), posts: newLimiter(cfg.Rate), calls: newLimiter(watchRate), asks: hourly(cfg.Model), refs: map[string]ref{}, names: map[string]seen{}, watches: map[string][]*watch{}, claims: map[claimKey]claim{}, leases: map[string]lease{}, tombs: map[string]time.Time{}, done: map[string]bool{}, sending: map[string]bool{}, failed: map[string]failure{}, waiting: map[string][]*outgoing{}} diff --git a/internal/features/mcp/addon_test.go b/internal/features/mcp/addon_test.go index 9609111..662c351 100644 --- a/internal/features/mcp/addon_test.go +++ b/internal/features/mcp/addon_test.go @@ -269,28 +269,36 @@ func TestCoreSettingsAreTheDocs(t *testing.T) { func TestAddonLoad(t *testing.T) { s, err := load(writeConfig(t, `{"mcpServers":{"game":`+addonServer("addon", `{"chats":["`+groupA+`","`+telegram+`"],"dms":true}`, direct)+`,`+ - `"all":`+addonServer("addon", `{"chats":["all"],"watch_max":"30m","rate":{"per_minute":6}}`, "")+`}}`)) + `"all":`+addonServer("addon", `{"chats":["all"],"watch_max":"30m","rate":{"per_minute":6},"model":{"per_hour":5}}`, "")+`,`+ + `"ask":`+addonServer("addon", `{"model":{}}`, "")+`}}`)) if err != nil { t.Fatal(err) } - if a := s["game"].Addon; a == nil || !a.DMs || len(a.Chats) != 2 || a.watchMax != time.Hour || a.Rate != (rateConfig{20, 5}) || !s["game"].ChatCommands["play"].Direct { + if a := s["game"].Addon; a == nil || !a.DMs || len(a.Chats) != 2 || a.watchMax != time.Hour || a.Rate != (rateConfig{20, 5}) || a.Model != nil || + !s["game"].ChatCommands["play"].Direct { t.Fatalf("game: %+v", s["game"]) } - if a := s["all"].Addon; a.watchMax != 30*time.Minute || a.Rate != (rateConfig{6, 5}) { + if a := s["all"].Addon; a.watchMax != 30*time.Minute || a.Rate != (rateConfig{6, 5}) || a.Model == nil || *a.Model != (modelConfig{5, 4000}) { t.Fatalf("all: %+v", a) } + if a := s["ask"].Addon; a.Model == nil || *a.Model != (modelConfig{30, 4000}) { + t.Fatalf("ask: %+v", a) + } for bad, want := range map[string]string{ `{"mcpServers":{"geo":{"url":"https://x","addon":{}}}}`: `: MCP server "geo": an addon needs a command: addons run only as local servers`, `{"mcpServers":{"geo":{"command":"x","env":{"A":"b"},"addon":{}}}}`: `: MCP server "geo": an addon server takes no env block: put its settings in the bot's environment, starting with GEO_, and it gets them`, `{"mcpServers":{"model":{"command":"x","addon":{}}}}`: `: MCP server "model": an addon's settings start with MODEL_, as the bot's own MODEL_API_KEY does; rename the server`, `{"mcpServers":{"Daily":{"command":"x","addon":{}}}}`: `: MCP server "Daily": an addon's settings start with DAILY_, as the bot's own DAILY_BUDGET does; rename the server`, `{"mcpServers":{"geo":{"command":"x","chat_commands":{"geo":{"tool":"geo","direct":true}}}}}`: `: MCP server "geo": chat command "geo" is direct, which needs an addon block`, - `{"mcpServers":{"geo":{"command":"x","addon":{"chat":["all"]}}}}`: `: MCP server "geo": addon: unknown setting "chat" (settings are chats, dms, post, react, watch, watch_max, names, global_ids, rate)`, + `{"mcpServers":{"geo":{"command":"x","addon":{"chat":["all"]}}}}`: `: MCP server "geo": addon: unknown setting "chat" (settings are chats, dms, post, react, watch, watch_max, names, global_ids, rate, model)`, `{"mcpServers":{"geo":{"command":"x","addon":{"rate":{"perMinute":1}}}}}`: `: MCP server "geo": addon rate: unknown setting "perMinute" (settings are per_minute, burst)`, `{"mcpServers":{"geo":{"command":"x","addon":{"chats":["Family"]}}}}`: `: MCP server "geo": addon chats: "Family" isn't a group ID; copy the group's ID as Signal or Telegram shows it, or use "all"`, `{"mcpServers":{"geo":{"command":"x","addon":{"chats":["all","` + groupA + `"]}}}}`: `: MCP server "geo": addon chats: "all" goes alone`, `{"mcpServers":{"geo":{"command":"x","addon":{"watch_max":"25h"}}}}`: `: MCP server "geo": addon watch_max: "25h" isn't a time from 1s to 24h, such as 1h or 30m`, `{"mcpServers":{"geo":{"command":"x","addon":{"rate":{"burst":-1}}}}}`: `: MCP server "geo": addon rate: per_minute and burst can't be below 0`, + `{"mcpServers":{"geo":{"command":"x","addon":{"model":{"perHour":1}}}}}`: `: MCP server "geo": addon model: unknown setting "perHour" (settings are per_hour, max_tokens)`, + `{"mcpServers":{"geo":{"command":"x","addon":{"model":{"per_hour":-1}}}}}`: `: MCP server "geo": addon model: per_hour and max_tokens can't be below 0`, + `{"mcpServers":{"geo":{"command":"x","addon":{"model":{"max_tokens":40000}}}}}`: `: MCP server "geo": addon model: max_tokens can't be over 32000`, `{"mcpServers":{"geo":{"command":"x","chat_commands":{"g":{"tool":"g","drect":true}},"addon":{}}}}`: `: MCP server "geo": chat command "g": unknown setting "drect" (settings are tool, require_arg, example, direct, timeout)`, } { p := writeConfig(t, bad) diff --git a/internal/features/mcp/conn.go b/internal/features/mcp/conn.go index 3b11ff3..8ca16db 100644 --- a/internal/features/mcp/conn.go +++ b/internal/features/mcp/conn.go @@ -11,6 +11,7 @@ import ( "net/http" "os" "os/exec" + "strconv" "strings" "sync" "sync/atomic" @@ -41,15 +42,29 @@ var ( errExited = errors.New("server exited") ) +// rpcMsg is a JSON-RPC message. Its ID is a number or a string: the bot's +// own requests use numbers, and a server's may use either. type rpcMsg struct { JSONRPC string `json:"jsonrpc"` - ID *int64 `json:"id,omitempty"` + ID json.RawMessage `json:"id,omitempty"` Method string `json:"method,omitempty"` Params any `json:"params,omitempty"` Result json.RawMessage `json:"result,omitempty"` Error *rpcError `json:"error,omitempty"` } +// hasID reports whether m has an ID: a request or a response. +func (m rpcMsg) hasID() bool { return len(m.ID) > 0 && string(m.ID) != "null" } + +// number is m's ID as one of the bot's own, if it is a number. +func (m rpcMsg) number() (int64, bool) { + var id int64 + return id, json.Unmarshal(m.ID, &id) == nil +} + +// idOf is the bot's own request ID n, as a message carries it. +func idOf(n int64) json.RawMessage { return json.RawMessage(strconv.FormatInt(n, 10)) } + // --- stdio -------------------------------------------------------------- // stdioConn runs a local MCP server and talks to it over stdin and stdout, @@ -64,10 +79,14 @@ type stdioConn struct { ready func(context.Context, handshake) // an addon's: called each time it has started again and initialized nextID atomic.Int64 - mu sync.Mutex // guards stdin, pending, done and the stderr counts + mu sync.Mutex // guards stdin, pending, done, life, serve, serving and the stderr counts stdin io.WriteCloser pending map[int64]chan rpcMsg - done chan struct{} // closed when the current process exits + done chan struct{} // closed when the current process exits + life context.Context // what start was given: the server's whole run + + serve requestFunc // an addon's: answers its sampling requests; nil refuses them + serving *served // the server's request being answered, if any errLines, errBytes int // an addon's stderr, since it was last logged errLogged time.Time // when it was @@ -127,7 +146,7 @@ func (c *stdioConn) start(ctx context.Context) error { } done, exited := make(chan struct{}), make(chan struct{}) c.mu.Lock() - c.stdin, c.pending, c.done = stdin, map[int64]chan rpcMsg{}, done + c.stdin, c.pending, c.done, c.life = stdin, map[int64]chan rpcMsg{}, done, ctx c.mu.Unlock() go c.readStderr(errR) @@ -170,6 +189,10 @@ func (c *stdioConn) start(ctx context.Context) error { delete(c.pending, id) } c.stdin = nil + if c.serving != nil { // nobody is left to answer + c.serving.cancel() + c.serving = nil + } c.mu.Unlock() close(done) }() @@ -297,21 +320,40 @@ func (c *stdioConn) dispatch(line []byte) { return } switch { - case m.ID != nil && m.Method != "": - // A request from the server: answer pings, refuse the rest. - reply := rpcMsg{JSONRPC: "2.0", ID: m.ID, Result: json.RawMessage(`{}`)} - if m.Method != "ping" { - reply = rpcMsg{JSONRPC: "2.0", ID: m.ID, Error: &rpcError{Code: -32601, Message: "method not supported"}} + case m.hasID() && m.Method != "": + // A request from the server: answer pings and, for an addon that + // may, sampling; refuse the rest. + switch { + case m.Method == "ping": + c.write(rpcMsg{JSONRPC: "2.0", ID: m.ID, Result: json.RawMessage(`{}`)}) + case m.Method == "sampling/createMessage" && c.request(m.ID, line): + default: + c.write(rpcMsg{JSONRPC: "2.0", ID: m.ID, Error: &rpcError{Code: -32601, Message: "method not supported"}}) + } + case m.hasID(): + id, ok := m.number() + if !ok { + return // not an answer to the bot's } - c.write(reply) - case m.ID != nil: c.mu.Lock() - ch := c.pending[*m.ID] - delete(c.pending, *m.ID) + ch := c.pending[id] + delete(c.pending, id) c.mu.Unlock() if ch != nil { ch <- m } + case m.Method == "notifications/cancelled": + var p struct { + Params struct { + RequestID json.RawMessage `json:"requestId"` + } `json:"params"` + } + json.Unmarshal(line, &p) + c.mu.Lock() + if s := c.serving; s != nil && bytes.Equal(bytes.TrimSpace(p.Params.RequestID), s.id) { + s.cancel() + } + c.mu.Unlock() case m.Method == "notifications/resources/updated" && c.updated != nil: // Any resource: the spec lets it be one under the one subscribed. select { @@ -321,6 +363,74 @@ func (c *stdioConn) dispatch(line []byte) { } } +// requestFunc answers a server's request, given its params: a result, or +// an error to send back. Its ctx ends when the server cancels the request, +// or exits. +type requestFunc func(ctx context.Context, params json.RawMessage) (any, *rpcError) + +// served is a server's request being answered. +type served struct { + id json.RawMessage + cancel context.CancelFunc +} + +// serveRequests has fn answer the server's sampling requests from now on. +func (c *stdioConn) serveRequests(fn requestFunc) { + c.mu.Lock() + c.serve = fn + c.mu.Unlock() +} + +// request answers the server's request id, whose whole message is line, +// with c.serve, on a goroutine of its own, so the reader never waits on +// it, and reports whether it was taken. One is answered at a time: while +// one is, another gets an error at once. The answer goes to the process +// that asked, and is dropped if it has exited. +func (c *stdioConn) request(id json.RawMessage, line []byte) bool { + var m struct { + Params json.RawMessage `json:"params"` + } + json.Unmarshal(line, &m) + c.mu.Lock() + fn, life, proc := c.serve, c.life, c.done + if fn == nil || life == nil { + c.mu.Unlock() + return false + } + if c.serving != nil { + c.mu.Unlock() + c.write(rpcMsg{JSONRPC: "2.0", ID: id, Error: &rpcError{Code: -32000, Message: "busy: one request at a time"}}) + return true + } + ctx, cancel := context.WithCancel(life) + s := &served{id: bytes.TrimSpace(id), cancel: cancel} + c.serving = s + c.mu.Unlock() + go func() { + defer cancel() + res, rerr := fn(ctx, m.Params) + reply := rpcMsg{JSONRPC: "2.0", ID: id, Error: rerr} + if rerr == nil { + data, err := json.Marshal(res) + if err != nil { + reply.Error = &rpcError{Code: -32603, Message: "internal error"} + } else { + reply.Result = data + } + } + c.mu.Lock() + if c.serving == s { + c.serving = nil + } + same := c.done == proc + c.mu.Unlock() + if same && ctx.Err() == nil { // a cancelled request gets no answer, as MCP says + c.write(reply) + } + }() + return true +} + func (c *stdioConn) write(m rpcMsg) error { data, err := json.Marshal(m) if err != nil { @@ -346,7 +456,7 @@ func (c *stdioConn) call(ctx context.Context, method string, params any) (json.R c.pending[id] = ch c.mu.Unlock() defer func() { c.mu.Lock(); delete(c.pending, id); c.mu.Unlock() }() - if err := c.write(rpcMsg{JSONRPC: "2.0", ID: &id, Method: method, Params: params}); err != nil { + if err := c.write(rpcMsg{JSONRPC: "2.0", ID: idOf(id), Method: method, Params: params}); err != nil { return nil, err } select { @@ -411,7 +521,7 @@ func (c *httpConn) call(ctx context.Context, method string, params any) (json.Ra func (c *httpConn) roundTrip(ctx context.Context, method string, params any) (json.RawMessage, error) { id := c.nextID.Add(1) - resp, err := c.post(ctx, rpcMsg{JSONRPC: "2.0", ID: &id, Method: method, Params: params}) + resp, err := c.post(ctx, rpcMsg{JSONRPC: "2.0", ID: idOf(id), Method: method, Params: params}) if err != nil { return nil, err } @@ -501,7 +611,7 @@ func readSSE(r io.Reader, id int64) (*rpcMsg, error) { data.WriteString(strings.TrimPrefix(strings.TrimPrefix(line, "data:"), " ")) case line == "" && data.Len() > 0: var m rpcMsg - if json.Unmarshal([]byte(data.String()), &m) == nil && m.ID != nil && *m.ID == id { + if json.Unmarshal([]byte(data.String()), &m) == nil && answers(m, id) { return &m, nil } data.Reset() @@ -509,9 +619,15 @@ func readSSE(r io.Reader, id int64) (*rpcMsg, error) { } if data.Len() > 0 { var m rpcMsg - if json.Unmarshal([]byte(data.String()), &m) == nil && m.ID != nil && *m.ID == id { + if json.Unmarshal([]byte(data.String()), &m) == nil && answers(m, id) { return &m, nil } } return nil, errors.New("no response in event stream") } + +// answers reports whether m is the response to the bot's request id. +func answers(m rpcMsg, id int64) bool { + n, ok := m.number() + return m.Method == "" && ok && n == id +} diff --git a/internal/features/mcp/direct.go b/internal/features/mcp/direct.go index 5d963ac..fa441c9 100644 --- a/internal/features/mcp/direct.go +++ b/internal/features/mcp/direct.go @@ -83,9 +83,21 @@ func (a *addon) direct(ctx context.Context, m feature.Message, name string, c ch return feature.Action{Answer: a.title + " couldn't do that just now."} } act := a.action(m.Chat, r) + var w *watch if r.Meta.Watch != nil { - if w := a.watch(m, *r.Meta.Watch); w != nil && len(act.Pictures) > 0 { - act.OnSent = func(sent []int64, _ bool) { a.guarding(w, sent) } + w = a.watch(m, *r.Meta.Watch) + } + if !act.IsZero() { + // When the answer went out: for the guard, if it has pictures, and + // for the chat's reply watches. + pics := w != nil && len(act.Pictures) > 0 + act.OnSent = func(sent []int64, dropped bool) { + if pics { + a.guarding(w, sent) + } + if !dropped { + a.replied(m.Chat, sent) + } } } if act.IsZero() { diff --git a/internal/features/mcp/keep.go b/internal/features/mcp/keep.go index 57dd1fa..29b36df 100644 --- a/internal/features/mcp/keep.go +++ b/internal/features/mcp/keep.go @@ -101,7 +101,7 @@ func (a *addon) state() addonState { a.watches[key] = ws for _, w := range ws { c := *w - c.Pictures = slices.Clone(w.Pictures) + c.Pictures, c.Sent = slices.Clone(w.Pictures), slices.Clone(w.Sent) s.Watches = append(s.Watches, c) } } @@ -134,7 +134,7 @@ func (a *addon) state() addonState { // restore takes up s, as saved, leaving out what has expired, and a watch // in a chat the addon is no longer allowed in or whose pattern no longer -// passes. +// passes: a reply watch's pattern isn't checked against ordinary chat. func (a *addon) restore(s addonState) { now := a.now() a.mu.Lock() @@ -152,11 +152,11 @@ func (a *addon) restore(s addonState) { for _, w := range s.Watches { l, ok := a.leases[w.Chat] re, err := regexp.Compile(w.Pattern) - if !ok || !now.Before(w.Until) || !a.allows(l.Chat) || err != nil || utf8.RuneCountInString(w.Pattern) > maxPattern || ordinary(re) || + if !ok || !now.Before(w.Until) || !a.allows(l.Chat) || err != nil || utf8.RuneCountInString(w.Pattern) > maxPattern || !w.Replies && ordinary(re) || len(a.watches[l.Chat.Key()]) >= maxWatches { continue } - w.key, w.re = l.Chat.Key(), re + w.key, w.re, w.Sent = l.Chat.Key(), re, w.Sent[max(len(w.Sent)-maxSent, 0):] a.watches[w.key] = append(a.watches[w.key], &w) } a.cursor = s.Cursor diff --git a/internal/features/mcp/mcp.go b/internal/features/mcp/mcp.go index e2f40a7..464afad 100644 --- a/internal/features/mcp/mcp.go +++ b/internal/features/mcp/mcp.go @@ -282,15 +282,24 @@ type handshake struct { type botInfo struct { version string // the bot's version, "dev" if unknown network string // the chat network, as Info names it, for addons + addon bool // the server has an addon block: offer what addons get + sample bool // the addon may ask the bot's model: offer sampling } // initialize performs the MCP handshake, as self, offering signalbot's -// extension with the chat network the bot is on, and returns what the +// extension with the chat network the bot is on, reply watches to an +// addon, and sampling to one that may ask the model, and returns what the // server said of itself. func initialize(ctx context.Context, c conn, self botInfo) (handshake, error) { + caps := map[string]any{"experimental": map[string]any{ + ext.KeyAddon: ext.Capability{Version: ext.Version, Network: self.network, WatchReplies: self.addon}, + }} + if self.sample { + caps["sampling"] = map[string]any{} + } res, err := c.call(ctx, "initialize", map[string]any{ "protocolVersion": protocol, - "capabilities": map[string]any{"experimental": map[string]any{ext.KeyAddon: ext.Capability{Version: ext.Version, Network: self.network}}}, + "capabilities": caps, "clientInfo": map[string]string{"name": "signalbot", "version": self.version}, }) if err != nil { @@ -363,22 +372,43 @@ func modelName(server, tool string) string { // run addons as plain servers; each addon started joins it. func start(ctx context.Context, h feature.Host, path string, servers map[string]server, k *keeper) error { info := h.Info() - self := botInfo{version: cmp.Or(info.Version, "dev"), network: info.Network} + base := botInfo{version: cmp.Or(info.Version, "dev"), network: info.Network} type owner struct{ server, tool string } taken := map[string]owner{} // the model's names for tools, and whose they are var cmds []string // for the startup line + var gates []*gate // opened on return, so no request waits on one for good + defer func() { + for _, g := range gates { + g.open(nil) + } + }() for _, name := range slices.Sorted(maps.Keys(servers)) { cfg := servers[name] + self := base + if cfg.Addon != nil { + // Sampling only where it can be answered: with a model, and + // addon features on. + self.addon, self.sample = true, cfg.Addon.Model != nil && info.Model != "" && k != nil + } var c conn = &httpConn{url: cfg.URL, headers: cfg.Headers, client: httpx.Client(2), bot: self} + var gt *gate if cfg.Command != "" { s := &stdioConn{name: name, cfg: cfg, bot: self, redact: h.Redact} if cfg.Addon != nil { s.prefix, s.updated = envPrefix(name), make(chan struct{}, 1) } + if self.sample { + // Sampling is offered from initialize on, so its requests are + // taken from then on, and wait for the addon to be ready. + gt = &gate{ready: make(chan struct{})} + gates = append(gates, gt) + s.serveRequests(gt.sample) + } c = s } listed, hs, err := connect(ctx, c, self) if err != nil { + gt.open(nil) logx.Errorf("MCP server %s unavailable, its tools are left out: %s", name, describe(err, cfg.Addon != nil)) continue } @@ -405,8 +435,10 @@ func start(ctx context.Context, h feature.Host, path string, servers map[string] a = newAddon(name, cmp.Or(hs.title, name), *cfg.Addon, k.doc.Secret, c, bot) a.host, a.changed, a.dirty = h, k.changed, c.(*stdioConn).updated a.restore(k.doc.Addons[name]) + gt.open(a) k.addons = append(k.addons, a) } + gt.open(nil) // a plain server: its requests are refused g := feature.ToolGroup{ System: instructions(cfg.Instructions, hs.instructions), Keywords: keywords(cfg.Keywords), diff --git a/internal/features/mcp/mcp_test.go b/internal/features/mcp/mcp_test.go index e6ff3bf..67580ea 100644 --- a/internal/features/mcp/mcp_test.go +++ b/internal/features/mcp/mcp_test.go @@ -678,8 +678,9 @@ func TestExampleFile(t *testing.T) { } t.Setenv("WEATHER_TOKEN", "x") s, err := load("../../../examples/signalbot-mcp.json") - if err != nil || len(s) != 2 || s["weather"].Headers["Authorization"] != "Bearer x" || s["weather"].ChatCommands["forecast"].Example == "" || - s["geo"].Addon == nil || !s["geo"].Addon.Watch || !s["geo"].ChatCommands["geo"].Direct { + if err != nil || len(s) != 3 || s["weather"].Headers["Authorization"] != "Bearer x" || s["weather"].ChatCommands["forecast"].Example == "" || + s["geo"].Addon == nil || !s["geo"].Addon.Watch || !s["geo"].ChatCommands["geo"].Direct || s["geo"].Addon.Model != nil || + s["quiz"].Addon == nil || s["quiz"].Addon.Model == nil || *s["quiz"].Addon.Model != (modelConfig{30, 4000}) { t.Fatalf("loaded %+v, %v", s, err) } } diff --git a/internal/features/mcp/outbox.go b/internal/features/mcp/outbox.go index 6f1bed2..a20c7c0 100644 --- a/internal/features/mcp/outbox.go +++ b/internal/features/mcp/outbox.go @@ -337,7 +337,10 @@ func (a *addon) send(id string, out *outgoing) { // mail puts out in its chat's mailbox. func (a *addon) mail(id string, out *outgoing) { p := out.Post - p.OnSent = func(_ []int64, dropped bool) { + p.OnSent = func(sent []int64, dropped bool) { + if !dropped { + a.replied(p.Chat, sent) + } a.sent(out.ops, !dropped) a.mu.Lock() held := a.waiting[id] diff --git a/internal/features/mcp/sample.go b/internal/features/mcp/sample.go new file mode 100644 index 0000000..0ad6803 --- /dev/null +++ b/internal/features/mcp/sample.go @@ -0,0 +1,209 @@ +package mcp + +import ( + "cmp" + "context" + "encoding/json" + "fmt" + "math" + "sync" + "time" + + ext "github.com/robdevops/signalbot/addon" + "github.com/robdevops/signalbot/internal/feature" + "github.com/robdevops/signalbot/internal/kit/logx" + "github.com/robdevops/signalbot/internal/kit/txt" +) + +// A sampling request's limits: its messages, and their text and the +// system prompt's, in bytes, in all. +const ( + maxSampleMessages = 16 + maxSampleText = 32 << 10 +) + +// sampleTimeout is how long the model has to answer a sampling request. +var sampleTimeout = 2 * time.Minute + +// gate holds an addon's sampling requests from initialize on, until the +// addon is ready to answer them: until open, which gives the addon, or +// nil for none, when they are refused. +type gate struct { + once sync.Once + ready chan struct{} + a *addon +} + +// open lets the requests through to a, or refuses them if a is nil. Only +// the first call counts. A nil gate does nothing. +func (g *gate) open(a *addon) { + if g == nil { + return + } + g.once.Do(func() { + g.a = a + close(g.ready) + }) +} + +// sample waits for the gate to open, then answers as the addon's sample. +func (g *gate) sample(ctx context.Context, params json.RawMessage) (any, *rpcError) { + select { + case <-g.ready: + case <-ctx.Done(): + return nil, &rpcError{Code: -32000, Message: "addon not ready yet"} + } + if g.a == nil { + return nil, &rpcError{Code: -32000, Message: "the bot can't answer model requests from this server"} + } + return g.a.sample(ctx, params) +} + +// sample answers the addon's sampling/createMessage, whose params are +// params: it asks the bot's model, charged to the chat the request names, +// which must be one the addon may post in now, and within the addon's +// hourly rate. Only text is taken. A refusal is a JSON-RPC error with a +// short message; only the outcome, the time, sizes and cost are logged, +// never the prompt or the answer. +func (a *addon) sample(ctx context.Context, params json.RawMessage) (any, *rpcError) { + start := time.Now() + res, size, why, rerr := a.ask(ctx, params) + outcome := "ok" + if rerr != nil { + outcome = why + } + var tokens int + var cost *float64 + if res != nil { + tokens, cost = res.tokens, res.cost + } + line := fmt.Sprintf("MCP server %s: a model request: %s in %dms, %d bytes in, %d tokens", a.server, outcome, time.Since(start).Milliseconds(), size, tokens) + if cost != nil { + line += fmt.Sprintf(", $%.4f", *cost) + } + if rerr != nil { + logx.Warnf("%s", line) + return nil, rerr + } + logx.Infof("%s", line) + return res.result, nil +} + +// answer is what the model said, and what it cost. +type answer struct { + result ext.SampleResult + tokens int + cost *float64 // nil if not reported +} + +// ask is sample's work: the answer, the size of the request's text, and +// for a refusal, why, for the log, and the error to send. +func (a *addon) ask(ctx context.Context, params json.RawMessage) (*answer, int, string, *rpcError) { + invalid := func(why, msg string) (*answer, int, string, *rpcError) { + return nil, 0, why, &rpcError{Code: -32602, Message: msg} + } + var req ext.SampleRequest + if json.Unmarshal(params, &req) != nil { + return invalid("malformed", "invalid params") + } + if a.cfg.Model == nil || a.host == nil || a.host.Info().Model == "" { + return nil, 0, "not allowed", &rpcError{Code: -32601, Message: "method not supported"} + } + size := len(req.SystemPrompt) + for _, m := range req.Messages { + size += len(m.Content.Text) + } + switch { + case len(req.Messages) == 0 || len(req.Messages) > maxSampleMessages: + return invalid("refused: messages", fmt.Sprintf("from 1 to %d messages", maxSampleMessages)) + case size > maxSampleText: + return invalid("refused: too long", fmt.Sprintf("at most %d KB of text", maxSampleText>>10)) + case req.MaxTokens < 1: + return invalid("refused: maxTokens", "maxTokens must be at least 1") + case req.Temperature != nil && (math.IsNaN(*req.Temperature) || *req.Temperature < 0 || *req.Temperature > 2): + return invalid("refused: temperature", "temperature must be from 0 to 2") + } + msgs := make([]map[string]string, 0, len(req.Messages)+1) + if req.SystemPrompt != "" { + msgs = append(msgs, map[string]string{"role": "system", "content": req.SystemPrompt}) + } + for _, m := range req.Messages { + if m.Role != "user" && m.Role != "assistant" || m.Content.Type != "text" { + return invalid("refused: not text", "only text messages, from user or assistant") + } + msgs = append(msgs, map[string]string{"role": m.Role, "content": m.Content.Text}) + } + now := a.now() + a.mu.Lock() + l, ok := a.leases[req.Meta.Chat] + a.mu.Unlock() + if req.Meta.Chat == "" || !ok || !now.Before(l.Expires) || !a.allows(l.Chat) { + return nil, size, "refused: no chat", &rpcError{Code: -32602, Message: "_meta needs the chat that pays, one the addon may post in now"} + } + if !a.asks.allow("", now) { + return nil, size, "refused: over the hourly rate", &rpcError{Code: -32000, Message: "too many requests this hour"} + } + body := map[string]any{"messages": msgs, "max_tokens": min(req.MaxTokens, a.cfg.Model.MaxTokens)} + if req.Temperature != nil { + body["temperature"] = *req.Temperature + } + // The addon cancelling, or exiting, doesn't stop the call: one stopped + // part way is billed by the provider but never charged to the chat, so + // the call runs to its end, or to the bot's own limit, and is charged, + // and the answer is dropped. + callCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), sampleTimeout) + defer cancel() + data, err := a.host.CallAPI(feature.ChargeTo(callCtx, l.Chat), "/chat/completions", body) + if err != nil { + why := "failed" + switch { + case ctx.Err() != nil: + why = "cancelled by the addon" + case callCtx.Err() != nil: + why = "timed out" + } + return nil, size, why, &rpcError{Code: -32603, Message: "the model couldn't answer"} + } + var r struct { + Model string `json:"model"` + Choices []struct { + Message struct { + Content *string `json:"content"` + } `json:"message"` + FinishReason string `json:"finish_reason"` + } `json:"choices"` + Usage struct { + Tokens int `json:"completion_tokens"` + Cost *float64 `json:"cost"` + } `json:"usage"` + } + if json.Unmarshal(data, &r) != nil || len(r.Choices) == 0 || r.Choices[0].Message.Content == nil { + return nil, size, "no answer", &rpcError{Code: -32603, Message: "the model gave no answer"} + } + c := r.Choices[0] + res := &answer{ + result: ext.SampleResult{ + Role: "assistant", + Content: ext.Content{Type: "text", Text: *c.Message.Content}, + Model: cmp.Or(r.Model, a.host.Info().Model), + StopReason: stopReason(c.FinishReason), + }, + tokens: r.Usage.Tokens, + cost: r.Usage.Cost, + } + if ctx.Err() != nil { + return res, size, "cancelled by the addon", &rpcError{Code: -32603, Message: "cancelled"} + } + return res, size, "", nil +} + +// stopReason is a completion's finish_reason as MCP names it. +func stopReason(finish string) string { + switch finish { + case "stop": + return "endTurn" + case "length": + return "maxTokens" + } + return txt.Clamp(finish, 40) +} diff --git a/internal/features/mcp/sample_test.go b/internal/features/mcp/sample_test.go new file mode 100644 index 0000000..49265f7 --- /dev/null +++ b/internal/features/mcp/sample_test.go @@ -0,0 +1,653 @@ +package mcp + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "os" + "strings" + "sync" + "testing" + "time" + + ext "github.com/robdevops/signalbot/addon" + "github.com/robdevops/signalbot/internal/feature" + "github.com/robdevops/signalbot/internal/feature/featuretest" + "github.com/robdevops/signalbot/internal/kit/logx" +) + +// --- in memory ------------------------------------------------------------------ + +// sampler is an addon allowed everywhere, with the model permission m, on a +// host whose model answers what said says, and records what it was sent. +func sampler(m *modelConfig) (*addon, *featuretest.Host, *[]map[string]any) { + cfg := everything + cfg.Model = m + a, _ := unitAddon(cfg) + h := featuretest.New() + h.Bot.Model = "x/test-model" + var mu sync.Mutex + var bodies []map[string]any + h.API = func(_ context.Context, path string, body map[string]any) (json.RawMessage, error) { + if path != "/chat/completions" { + return nil, errors.New("wrong path") + } + mu.Lock() + bodies = append(bodies, body) + mu.Unlock() + return json.RawMessage(`{"model":"x/test-model-0611","choices":[{"message":{"role":"assistant","content":"Canberra"},"finish_reason":"length"}],` + + `"usage":{"completion_tokens":3,"cost":0.0012}}`), nil + } + a.host = h + return a, h, &bodies +} + +// ask is a sampling request's params for chat, saying text. +func ask(chat, text string, maxTokens int) json.RawMessage { + t := 0.5 + b, _ := json.Marshal(ext.SampleRequest{ + Messages: []ext.SampleMessage{{Role: "user", Content: ext.Content{Type: "text", Text: text}}}, + SystemPrompt: "You write quiz questions.", + MaxTokens: maxTokens, + Temperature: &t, + Meta: ext.SampleMeta{Chat: chat}, + }) + return b +} + +// A request is run on the bot's model, charged to the chat it names, with +// the system prompt first and maxTokens capped; the answer is MCP's; the +// log has no prompt or answer. +func TestSample(t *testing.T) { + var log logx.Buffer + t.Cleanup(logx.SetOutput(&log, &log, true)) + a, h, bodies := sampler(&modelConfig{PerHour: 30, MaxTokens: 100}) + a.lease(inA) + res, rerr := a.sample(context.Background(), ask(a.chatID(inA), "Alice asks for the capital of Australia", 500)) + if rerr != nil { + t.Fatal(rerr) + } + want := ext.SampleResult{Role: "assistant", Content: ext.Content{Type: "text", Text: "Canberra"}, Model: "x/test-model-0611", StopReason: "maxTokens"} + if res != want { + t.Fatalf("result %+v", res) + } + if c := h.Charged(); len(c) != 1 || c[0] != inA { + t.Fatalf("charged %+v", c) + } + got, _ := json.Marshal((*bodies)[0]) + if w := `{"max_tokens":100,"messages":[{"content":"You write quiz questions.","role":"system"},` + + `{"content":"Alice asks for the capital of Australia","role":"user"}],"temperature":0.5}`; string(got) != w { + t.Fatalf("body %s", got) + } + l := log.String() + if !strings.Contains(l, "<6>MCP server game: a model request: ok in ") || !strings.Contains(l, ", 3 tokens, $0.0012\n") { + t.Fatalf("log %q", l) + } + for _, s := range []string{"Alice", "Canberra", "quiz"} { + if strings.Contains(l, s) { + t.Fatalf("%q reached the log: %q", s, l) + } + } +} + +// A request is refused without the permission or a model, without a chat +// the addon may post in now, past the hourly rate, or too big or not text. +func TestSampleRefused(t *testing.T) { + var log logx.Buffer + t.Cleanup(logx.SetOutput(&log, &log, true)) + refused := func(a *addon, params json.RawMessage, code int) { + t.Helper() + if _, rerr := a.sample(context.Background(), params); rerr == nil || rerr.Code != code { + t.Fatalf("got %v, want code %d", rerr, code) + } + } + a, h, bodies := sampler(nil) + a.lease(inA) + refused(a, ask(a.chatID(inA), "hi", 10), -32601) + + a, h, bodies = sampler(&modelConfig{PerHour: 2, MaxTokens: 100}) + a.lease(inA) + chat := a.chatID(inA) + h.Bot.Model = "" + refused(a, ask(chat, "hi", 10), -32601) + h.Bot.Model = "x/test-model" + + refused(a, ask("", "hi", 10), -32602) + refused(a, ask(a.chatID(inB), "hi", 10), -32602) // no lease + refused(a, json.RawMessage(`{"messages":"hi"}`), -32602) + refused(a, ask(chat, strings.Repeat("x", maxSampleText+1), 10), -32602) + refused(a, ask(chat, "hi", 0), -32602) + var req ext.SampleRequest + json.Unmarshal(ask(chat, "hi", 10), &req) + for range maxSampleMessages { + req.Messages = append(req.Messages, req.Messages[0]) + } + many, _ := json.Marshal(req) + refused(a, many, -32602) + req.Messages = []ext.SampleMessage{{Role: "user", Content: ext.Content{Type: "image", Data: tinyPNG(), MimeType: "image/png"}}} + image, _ := json.Marshal(req) + refused(a, image, -32602) + req.Messages = []ext.SampleMessage{{Role: "system", Content: ext.Content{Type: "text", Text: "hi"}}} + system, _ := json.Marshal(req) + refused(a, system, -32602) + if len(*bodies) != 0 || len(h.Charged()) != 0 { + t.Fatalf("the model was asked: %v", *bodies) + } + + for range 2 { + if _, rerr := a.sample(context.Background(), ask(chat, "hi", 10)); rerr != nil { + t.Fatal(rerr) + } + } + refused(a, ask(chat, "hi", 10), -32000) // the hour's 2 are used + + // A chat the addon is no longer allowed in. + a, _, _ = sampler(&modelConfig{PerHour: 2, MaxTokens: 100}) + a.lease(inA) + a.cfg.Chats = []string{groupB} + refused(a, ask(a.chatID(inA), "hi", 10), -32602) + + // The model failing, as when the chat is over its daily budget. + a, h, _ = sampler(&modelConfig{PerHour: 2, MaxTokens: 100}) + a.lease(inA) + h.API = func(context.Context, string, map[string]any) (json.RawMessage, error) { + return nil, errors.New("the chat has reached its daily budget") + } + refused(a, ask(a.chatID(inA), "hi", 10), -32603) + if strings.Contains(log.String(), "hi") { + t.Fatalf("the prompt reached the log: %q", log.String()) + } +} + +// --- through the addon package, against the bot's side --------------------- + +// TestSampleAddonProcess is not a real test: run as a subprocess with the +// argument "sample", it is an addon built from the addon package that asks +// the bot's model. /ask asks it what its args say, in the command's chat +// ("cancel" gives up after 300ms; "crash" exits mid-request; "nochat" names +// no chat); /caps says what the bot offered; /round starts a reply watch. +func TestSampleAddonProcess(t *testing.T) { + if flag.Arg(0) != "sample" { + return + } + var s *ext.Server + args := json.RawMessage(`{"type":"object","properties":{"args":{"type":"string"}}}`) + s = ext.New(ext.Config{Name: "quiz", Title: "Quiz", Version: "1", Tools: []ext.Tool{ + { + Name: "ask", Visibility: []string{"bot"}, Schema: args, + Call: func(ctx context.Context, c *ext.Context, raw json.RawMessage) (ext.Result, error) { + var a struct{ Args string } + if err := ext.DecodeArgs(raw, &a); err != nil { + return ext.Result{}, err + } + chat := c.Chat + switch a.Args { + case "nochat": + chat = "" + case "cancel": + var cancel context.CancelFunc + ctx, cancel = context.WithTimeout(ctx, 300*time.Millisecond) + defer cancel() + case "crash": + time.AfterFunc(300*time.Millisecond, func() { os.Exit(3) }) + } + r, err := s.Sample(ctx, chat, ext.SampleRequest{ + Messages: []ext.SampleMessage{{Role: "user", Content: ext.Content{Type: "text", Text: a.Args}}}, + MaxTokens: 50, + }) + var be *ext.BotError + switch { + case errors.As(err, &be): + return ext.Text(fmt.Sprintf("refused %d", be.Code)), nil + case errors.Is(err, context.DeadlineExceeded): + return ext.Text("gave up"), nil + case err != nil: + return ext.Text("failed"), nil + } + return ext.Text(r.Role + ": " + r.Content.Text + " (" + r.Model + ", " + r.StopReason + ")"), nil + }, + }, + { + Name: "caps", Visibility: []string{"bot"}, + Call: func(context.Context, *ext.Context, json.RawMessage) (ext.Result, error) { + return ext.Text(fmt.Sprint(s.CanSample(), s.WatchReplies())), nil + }, + }, + { + Name: "round", Visibility: []string{"bot"}, + Call: func(_ context.Context, c *ext.Context, _ json.RawMessage) (ext.Result, error) { + if err := s.Queue(ext.Op{Op: "post", Chat: c.Chat, Text: "Question 2"}); err != nil { + return ext.Result{}, err + } + r := ext.Text("Question 1") + r.Meta = &ext.ResultMeta{Watch: &ext.Watch{ID: "q", Replies: true, Until: time.Now().Add(time.Hour).Format(time.RFC3339), Tool: "answer"}} + return r, nil + }, + }, + { + Name: "answer", Visibility: []string{"bot"}, Schema: json.RawMessage(`{"type":"object","properties":{"text":{"type":"string"}}}`), + Call: func(context.Context, *ext.Context, json.RawMessage) (ext.Result, error) { + return ext.Result{Content: []ext.Content{{Type: "text", Text: "noted"}}, Meta: &ext.ResultMeta{React: "✅"}}, nil + }, + }, + }}) + if err := s.Run(context.Background(), os.Stdin, os.Stdout); err != nil { + os.Exit(1) + } + os.Exit(0) +} + +// quizConfig is MCP_CONFIG for the package addon "quiz" in group A, with +// model as its addon block's "model" setting ("" for none). +func quizConfig(model string) string { + block := `{"chats":["` + groupA + `"],"post":true,"react":true,"watch":true` + if model != "" { + block += `,"model":` + model + } + entry := strings.Replace(addonServer("sample", block+`}`, `,"chat_commands":{"ask":{"tool":"ask","direct":true},"caps":{"tool":"caps","direct":true},`+ + `"round":{"tool":"round","direct":true}}`), "TestAddonProcess", "TestSampleAddonProcess", 1) + return `{"mcpServers":{"quiz":` + entry + `}}` +} + +// modelAPI is a model API for the bot's side: it answers each prompt by +// echoing it, except "slow", which waits for release, and "cancel" and +// "crash", which answer after the addon has given up or exited, saying on +// ended whether their ctx had ended by then. +type modelAPI struct { + called chan string + release chan struct{} + ended chan string +} + +func newModelAPI() *modelAPI { + return &modelAPI{called: make(chan string, 16), release: make(chan struct{}), ended: make(chan string, 16)} +} + +func (m *modelAPI) call(ctx context.Context, _ string, body map[string]any) (json.RawMessage, error) { + msgs := body["messages"].([]map[string]string) + prompt := msgs[len(msgs)-1]["content"] + m.called <- prompt + switch prompt { + case "slow": + <-m.release + case "cancel", "crash": + time.Sleep(time.Second) + m.ended <- fmt.Sprint(prompt, " ", ctx.Err()) + } + b, _ := json.Marshal(prompt + "!") + return json.RawMessage(`{"model":"x/test-model","choices":[{"message":{"content":` + string(b) + `},"finish_reason":"stop"}]}`), nil +} + +// An addon allowed the model is offered sampling and reply watches, and +// its requests, with string IDs, are answered, one at a time; one it +// cancels, or that it exits during, still has its model call run to the +// end and charged to the chat. +func TestPackageAddonSample(t *testing.T) { + defer func(d time.Duration) { restartDelay = d }(restartDelay) + restartDelay = 10 * time.Millisecond + api := newModelAPI() + h, log := startAddon(t, quizConfig(`{}`), func(h *featuretest.Host) { h.API = api.call }) + ctx := context.Background() + if got := h.Message(ctx, in(inA, "/caps")); got.Answer != "true true" { + t.Fatalf("caps: %+v", got) + } + if got := h.Message(ctx, in(inA, "/ask hello")); got.Answer != "assistant: hello! (x/test-model, endTurn)" { + t.Fatalf("ask: %+v", got) + } + if c := h.Charged(); len(c) != 1 || c[0] != inA { + t.Fatalf("charged %+v", c) + } + <-api.called + if got := h.Message(ctx, in(inA, "/ask nochat")); got.Answer != "refused -32602" { + t.Fatalf("no chat: %+v", got) + } + + // A second request while one is in flight is refused at once. + slow := make(chan feature.Action) + go func() { slow <- h.Message(ctx, in(inA, "/ask slow")) }() + if p := <-api.called; p != "slow" { + t.Fatalf("called with %q", p) + } + if got := h.Message(ctx, in(inA, "/ask hello")); got.Answer != "refused -32000" { + t.Fatalf("a second in flight: %+v", got) + } + close(api.release) + if got := <-slow; got.Answer != "assistant: slow! (x/test-model, endTurn)" { + t.Fatalf("slow: %+v", got) + } + + // The addon gives up: the bot's call still runs, and is charged. + if got := h.Message(ctx, in(inA, "/ask cancel")); got.Answer != "gave up" { + t.Fatalf("cancel: %+v", got) + } + select { + case p := <-api.ended: + if p != "cancel <nil>" { + t.Fatalf("ended %q", p) + } + case <-time.After(10 * time.Second): + t.Fatal("the model call didn't end") + } + <-api.called + // The cancelled request is served until its call returns, just after. + eventually(t, "the cancelled request's end", func() bool { + return h.Message(ctx, in(inA, "/ask hello")).Answer == "assistant: hello! (x/test-model, endTurn)" + }) + <-api.called + + // The addon exits mid-request: the call still runs, and the addon, + // started again, is answered. + h.Message(ctx, in(inA, "/ask crash")) + select { + case p := <-api.ended: + if p != "crash <nil>" { + t.Fatalf("ended %q", p) + } + case <-time.After(10 * time.Second): + t.Fatal("the model call didn't end when the addon exited") + } + <-api.called + eventually(t, "the restart", func() bool { + return h.Message(ctx, in(inA, "/ask again")).Answer == "assistant: again! (x/test-model, endTurn)" + }) + eventually(t, "the charges", func() bool { + n := 0 + for _, c := range h.Charged() { + if c == inA { + n++ + } + } + return n >= 6 // hello, slow, cancel, hello, crash, again + }) + for _, s := range []string{"hello", "slow!", "again"} { + if strings.Contains(log.String(), s) { + t.Fatalf("%q reached the log: %q", s, log.String()) + } + } +} + +// Without the permission, or with no model, sampling isn't offered, and a +// request is refused as unsupported. +func TestPackageAddonNoSample(t *testing.T) { + for name, before := range map[string]func(*featuretest.Host){ + "no permission": func(*featuretest.Host) {}, + "no model": func(h *featuretest.Host) { h.Bot.Model, h.Bot.CallsTools = "", false }, + } { + t.Run(name, func(t *testing.T) { + model := `{}` + if name == "no permission" { + model = "" + } + h, _ := startAddon(t, quizConfig(model), before, func(h *featuretest.Host) { + h.API = func(context.Context, string, map[string]any) (json.RawMessage, error) { + t.Error("the model was called") + return nil, errors.New("no") + } + }) + if got := h.Message(context.Background(), in(inA, "/caps")); got.Answer != "false true" { + t.Fatalf("caps: %+v", got) + } + }) + } +} + +// A request that comes before the addon is ready waits for it, and one to +// a gate opened with no addon is refused, not called unsupported. +func TestSampleGate(t *testing.T) { + a, _, _ := sampler(&modelConfig{PerHour: 30, MaxTokens: 100}) + a.lease(inA) + g := &gate{ready: make(chan struct{})} + got := make(chan *rpcError, 1) + go func() { + _, rerr := g.sample(context.Background(), ask(a.chatID(inA), "hi", 10)) + got <- rerr + }() + select { + case rerr := <-got: + t.Fatalf("answered before the addon was ready: %+v", rerr) + case <-time.After(50 * time.Millisecond): + } + g.open(a) + g.open(nil) // only the first counts + if rerr := <-got; rerr != nil { + t.Fatal(rerr) + } + + g = &gate{ready: make(chan struct{})} + g.open(nil) + if _, rerr := g.sample(context.Background(), ask(a.chatID(inA), "hi", 10)); rerr == nil || rerr.Code != -32000 { + t.Fatalf("no addon: %+v", rerr) + } + g = &gate{ready: make(chan struct{})} + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, rerr := g.sample(ctx, ask(a.chatID(inA), "hi", 10)); rerr == nil || rerr.Code != -32000 { + t.Fatalf("cancelled while waiting: %+v", rerr) + } + var none *gate + none.open(a) // does nothing +} + +// A request the addon cancels still has its model call run, and charged +// to the chat, and gets no answer. +func TestSampleCancelledCharges(t *testing.T) { + a, h, _ := sampler(&modelConfig{PerHour: 30, MaxTokens: 100}) + a.lease(inA) + ctx, cancel := context.WithCancel(context.Background()) + api := h.API + var callErr error + h.API = func(c context.Context, path string, body map[string]any) (json.RawMessage, error) { + cancel() + callErr = c.Err() + return api(c, path, body) + } + if _, rerr := a.sample(ctx, ask(a.chatID(inA), "hi", 10)); rerr == nil { + t.Fatal("a cancelled request was answered") + } + if callErr != nil { + t.Fatalf("the model call was cancelled: %v", callErr) + } + if c := h.Charged(); len(c) != 1 || c[0] != inA { + t.Fatalf("charged %+v", c) + } +} + +// A request with a string ID gets an answer with that ID, and a cancel +// naming it cancels it; requests other than sampling and ping are still +// refused. +func TestServeRequests(t *testing.T) { + r, w, _ := os.Pipe() + defer r.Close() + c := &stdioConn{name: "quiz", stdin: w, life: context.Background(), done: make(chan struct{})} + started, ended := make(chan json.RawMessage, 1), make(chan error, 1) + c.serveRequests(func(ctx context.Context, params json.RawMessage) (any, *rpcError) { + started <- params + if strings.Contains(string(params), "wait") { + <-ctx.Done() + ended <- ctx.Err() + return nil, &rpcError{Code: -32603, Message: "cancelled"} + } + return map[string]string{"role": "assistant"}, nil + }) + lines := make(chan string, 16) + go func() { + buf := make([]byte, 1<<16) + var acc string + for { + n, err := r.Read(buf) + acc += string(buf[:n]) + for { + i := strings.IndexByte(acc, '\n') + if i < 0 { + break + } + lines <- acc[:i] + acc = acc[i+1:] + } + if err != nil { + return + } + } + }() + next := func() string { + select { + case l := <-lines: + return l + case <-time.After(5 * time.Second): + t.Fatal("no line") + return "" + } + } + c.dispatch([]byte(`{"jsonrpc":"2.0","id":"q.1","method":"sampling/createMessage","params":{"x":1}}`)) + <-started + if got := next(); got != `{"jsonrpc":"2.0","id":"q.1","result":{"role":"assistant"}}` { + t.Fatalf("answer %s", got) + } + c.dispatch([]byte(`{"jsonrpc":"2.0","id":"q.2","method":"sampling/createMessage","params":{"wait":1}}`)) + <-started + c.dispatch([]byte(`{"jsonrpc":"2.0","id":7,"method":"sampling/createMessage","params":{}}`)) + if got := next(); got != `{"jsonrpc":"2.0","id":7,"error":{"code":-32000,"message":"busy: one request at a time"}}` { + t.Fatalf("second in flight: %s", got) + } + c.dispatch([]byte(`{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"q.2"}}`)) + if err := <-ended; !errors.Is(err, context.Canceled) { + t.Fatalf("ended with %v", err) + } + c.dispatch([]byte(`{"jsonrpc":"2.0","id":"q.3","method":"roots/list"}`)) + if got := next(); got != `{"jsonrpc":"2.0","id":"q.3","error":{"code":-32601,"message":"method not supported"}}` { + t.Fatalf("roots/list: %s (a cancelled request was answered?)", got) + } + c.dispatch([]byte(`{"jsonrpc":"2.0","id":"p","method":"ping"}`)) + if got := next(); got != `{"jsonrpc":"2.0","id":"p","result":{}}` { + t.Fatalf("ping: %s", got) + } + eventually(t, "the cancelled request to end", func() bool { c.mu.Lock(); defer c.mu.Unlock(); return c.serving == nil }) + c.dispatch([]byte(`{"jsonrpc":"2.0","id":"q.4","method":"sampling/createMessage","params":{}}`)) + <-started + if got := next(); got != `{"jsonrpc":"2.0","id":"q.4","result":{"role":"assistant"}}` { + t.Fatalf("after a cancel: %s", got) + } + w.Close() +} + +// --- reply watches ------------------------------------------------------------ + +// A reply watch takes only addressed replies to the addon's messages sent +// while it lives, and their edits; with a pattern, only those it matches. +// It knows the last maxSent, keeps them through a restart, and ends. +func TestReplyWatch(t *testing.T) { + var log logx.Buffer + t.Cleanup(logx.SetOutput(&log, &log, true)) + a, now := unitAddon(everything) + cmd := said(inA, "alice-id", 1000, "/quiz") + replies := func(id, pattern string) ext.Watch { + return ext.Watch{ID: id, Pattern: pattern, Replies: true, Until: now.Add(time.Minute).Format(time.RFC3339), Tool: "guess"} + } + if a.watch(cmd, ext.Watch{ID: "x", Until: now.Add(time.Minute).Format(time.RFC3339), Tool: "guess"}) != nil { + t.Fatal("a watch with no pattern and no replies was taken") + } + if a.watch(cmd, replies("q", "")) == nil { + t.Fatalf("refused: %s", log.String()) + } + a.replied(inA, []int64{5000}) + a.replied(inB, []int64{6000}) // no reply watch there + + answer := replyTo(said(inA, "bob-id", 1001, "Paris"), 5000) + for _, m := range []feature.Message{answer, edit(answer, 1002, "Lyon"), replyTo(said(inA, "alice-id", 1003, "lol"), 5000)} { + if !a.claim(m).Done { + t.Fatalf("%q not taken", m.Text) + } + } + unaddressed := said(inA, "bob-id", 1004, "Rome") + unaddressed.Quote = &feature.Quote{Bot: true, Sent: 5000} + notBot := to(said(inA, "bob-id", 1005, "Rome")) + notBot.Quote = &feature.Quote{Sent: 5000} + for _, m := range []feature.Message{ + replyTo(said(inA, "bob-id", 1006, "Rome"), 7000), // another of the bot's messages + to(said(inA, "bob-id", 1007, "Rome")), // no reply + said(inA, "bob-id", 1008, "Rome"), + unaddressed, + notBot, + replyTo(said(inB, "bob-id", 1009, "Rome"), 6000), + } { + if !a.claim(m).IsZero() { + t.Fatalf("taken: %+v", m) + } + } + + stamps := make([]int64, 100) + for i := range stamps { + stamps[i] = int64(10000 + i) + } + a.replied(inA, stamps) + s := a.state() + if len(s.Watches) != 1 || len(s.Watches[0].Sent) != maxSent || s.Watches[0].Sent[0] != 10036 || !s.Watches[0].Replies { + t.Fatalf("saved %+v", s.Watches) + } + if !a.claim(replyTo(said(inA, "bob-id", 1010, "Rome"), 10099)).Done || !a.claim(replyTo(said(inA, "bob-id", 1011, "Rome"), 5000)).IsZero() { + t.Fatal("not the last maxSent") + } + + b, later := unitAddon(everything) // the bot started again + *later = *now + b.restore(s) + if !b.claim(replyTo(said(inA, "bob-id", 1012, "Oslo"), 10050)).Done { + t.Fatal("not taken after a restart") + } + *later = later.Add(time.Minute) + if !b.claim(replyTo(said(inA, "bob-id", 1013, "Oslo"), 10050)).IsZero() { + t.Fatal("taken after the watch ended") + } + + c, _ := unitAddon(everything) + *now = time.Unix(1800000000, 0) + c.now = func() time.Time { return *now } + if c.watch(cmd, replies("p", `(?i)^\s*[a-d]\s*$`)) == nil { + t.Fatalf("a pattern refused: %s", log.String()) + } + c.replied(inA, []int64{5000}) + if !c.claim(replyTo(said(inA, "bob-id", 1014, " B "), 5000)).Done || !c.claim(replyTo(said(inA, "bob-id", 1015, "Paris"), 5000)).IsZero() { + t.Fatal("the pattern wasn't applied") + } +} + +// Through the addon package: the command's answer and the addon's post +// both take replies, which go to the watch's tool, and the bot started +// again still knows them. +func TestPackageAddonReplies(t *testing.T) { + dir := t.TempDir() + start := func() *featuretest.Host { + h, _, err := register(t, quizConfig(""), func(h *featuretest.Host) { h.Settings["STATE_DIRECTORY"] = dir }) + if err != nil { + t.Fatal(err) + } + return h + } + h := start() + ctx := context.Background() + act := h.Message(ctx, in(inA, "/round")) + if act.Answer != "Question 1" || act.OnSent == nil { + t.Fatalf("round: %+v", act) + } + act.OnSent([]int64{5000}, false) + eventually(t, "the post", func() bool { return len(h.Posts()) == 1 }) + h.Posts()[0].OnSent([]int64{6000}, false) + for i, sent := range []int64{5000, 6000} { + if got := h.Message(ctx, replyTo(said(inA, "bob-id", int64(1001+i), "Paris"), sent)); !got.Done { + t.Fatalf("a reply to %d: %+v", sent, got) + } + } + eventually(t, "the reactions", func() bool { return len(h.Reactions()) == 2 }) + if got := h.Message(ctx, replyTo(said(inA, "bob-id", 1003, "Paris"), 7000)); !got.IsZero() { + t.Fatalf("a reply to another message: %+v", got) + } + h.Stop() + + h = start() + if got := h.Message(ctx, replyTo(said(inA, "bob-id", 1004, "Rome"), 6000)); !got.Done { + t.Fatalf("after a restart: %+v", got) + } + eventually(t, "the reaction", func() bool { return len(h.Reactions()) == 1 }) +} diff --git a/internal/features/mcp/watch.go b/internal/features/mcp/watch.go index 4ac9ecc..213a960 100644 --- a/internal/features/mcp/watch.go +++ b/internal/features/mcp/watch.go @@ -20,6 +20,7 @@ import ( // A watch's limits. const ( maxWatches = 8 // live in one chat, per addon + maxSent = 64 // the addon's messages a reply watch knows replies to maxPattern = 1 << 10 // a pattern's size, in characters, as addon/schema.json counts maxWatchID = 64 // an ID's size, in characters maxGuard = 500 // a guard's size, in runes @@ -35,7 +36,9 @@ var watchRate = rateConfig{PerMinute: 120, Burst: 20} // watch is a live watch: an addon's claim, until Until, on the messages // matching Pattern in one chat that the bot gets while it lasts, and the -// edits of those sent from Since on. +// edits of those sent from Since on. With Replies, only addressed replies +// to the addon's own messages sent while it lives, in Sent, are taken, and +// Pattern may be empty. type watch struct { ID string `json:"id"` Chat string `json:"chat"` // the chat's pseudonym; its lease names the chat @@ -45,6 +48,8 @@ type watch struct { Since int64 `json:"since"` // the Timestamp of the command that made it, by its sender's clock: only for edits Until time.Time `json:"until"` Pictures []int64 `json:"pictures,omitempty"` // when the bot's messages with the command's pictures were sent, as Quote.Sent names them + Replies bool `json:"replies,omitempty"` + Sent []int64 `json:"sent,omitempty"` // a reply watch's: when the addon's messages were sent, as Quote.Sent names them; the last maxSent key string // the chat's key re *regexp.Regexp // Pattern @@ -126,14 +131,14 @@ func (a *addon) watch(m feature.Message, spec ext.Watch) *watch { if re, err = regexp.Compile(spec.Pattern); err != nil { return refuse("its pattern isn't RE2") } - if ordinary(re) { + if !spec.Replies && ordinary(re) { // a reply to the addon's own message is meant for it return refuse("its pattern matches ordinary chat") } if latest := now.Add(a.cfg.watchMax); until.After(latest) { until = latest } w := &watch{ID: spec.ID, Chat: a.chatID(m.Chat), Pattern: spec.Pattern, Tool: spec.Tool, Guard: txt.Clamp(strings.TrimSpace(spec.Guard), maxGuard), - Since: m.Timestamp, Until: until, key: m.Chat.Key(), re: re} + Since: m.Timestamp, Until: until, Replies: spec.Replies, key: m.Chat.Key(), re: re} a.mu.Lock() tomb := w.Chat + "\x00" + w.ID if t, ok := a.tombs[tomb]; ok && now.Before(t) { @@ -163,6 +168,46 @@ func (a *addon) guarding(w *watch, sent []int64) { a.changed() } +// replied records that the addon's messages in chat went out at sent, on +// each of the chat's live reply watches, so they take replies to them. +func (a *addon) replied(chat feature.Chat, sent []int64) { + if len(sent) == 0 { + return + } + now := a.now() + found := false + a.mu.Lock() + for _, w := range a.watches[chat.Key()] { + if w.Replies && now.Before(w.Until) { + w.Sent = append(w.Sent, sent...) + w.Sent = w.Sent[max(len(w.Sent)-maxSent, 0):] + found = true + } + } + a.mu.Unlock() + if found { + a.changed() + } +} + +// takes reports whether w takes m, apart from when: a reply watch only an +// addressed reply to one of the addon's messages it knows, and its pattern, +// if it has one, must match. +func (a *addon) takes(w *watch, m feature.Message) bool { + if w.Replies { + if !m.Addressed || m.Quote == nil || !m.Quote.Bot || m.Quote.Sent == 0 { + return false + } + a.mu.Lock() + known := slices.Contains(w.Sent, m.Quote.Sent) + a.mu.Unlock() + if !known { + return false + } + } + return w.re.MatchString(m.Text) +} + // claim is the Action for m if one of the addon's watches takes it: Done, // with m sent to the watch worker. So is an edit of a message one took. An // addressed message that quotes the pictures of a watch with a guard, even @@ -173,7 +218,7 @@ func (a *addon) guarding(w *watch, sent []int64) { // An original is taken whenever the bot gets it while a watch lasts, not by // its Timestamp: on Signal that is its sender's clock, which may be behind. // An edit's original must be from Since on, so an older message's edit is -// never taken. +// never taken. A reply watch takes only what takes says. func (a *addon) claim(m feature.Message) feature.Action { if !a.allows(m.Chat) { return feature.Action{} @@ -196,7 +241,7 @@ func (a *addon) claim(m feature.Message) feature.Action { a.mu.Unlock() } for _, w := range live { - if got.tool == "" && now.Before(w.Until) && (m.Edited == 0 || m.Timestamp >= w.Since) && w.re.MatchString(m.Text) { + if got.tool == "" && now.Before(w.Until) && (m.Edited == 0 || m.Timestamp >= w.Since) && a.takes(w, m) { got.tool = w.Tool } } @@ -359,6 +404,16 @@ func newLimiter(rate rateConfig) *limiter { return &limiter{every: time.Minute / time.Duration(max(rate.PerMinute, 1)), burst: float64(max(rate.Burst, 1)), buckets: map[string]*bucket{}} } +// hourly is a limiter of m.PerHour tokens an hour, all of them at once if +// saved up; nil if m is. +func hourly(m *modelConfig) *limiter { + if m == nil { + return nil + } + n := max(m.PerHour, 1) + return &limiter{every: time.Hour / time.Duration(n), burst: float64(n), buckets: map[string]*bucket{}} +} + // fill is chat's bucket at now, with what came back since. l.mu is held. func (l *limiter) fill(chat string, now time.Time) *bucket { if len(l.buckets) > 1000 { diff --git a/internal/model/model.go b/internal/model/model.go index 5bc52bb..34d3334 100644 --- a/internal/model/model.go +++ b/internal/model/model.go @@ -344,7 +344,7 @@ func (c *Client) Ask(ctx context.Context, r Request) (Reply, error) { } // spend is what tools spent through the API during one Ask, which counts -// toward the reply's cost. +// toward the reply's cost, or what Calls with a ctx from Meter spent. type spend struct { mu sync.Mutex cost float64 @@ -353,7 +353,8 @@ type spend struct { type spendKey struct{} -// add counts cost, if the API reported one, to the Ask ctx belongs to. +// addSpend counts cost, if the API reported one, to the Ask or meter ctx +// belongs to. func addSpend(ctx context.Context, cost float64, costed bool) { if s, ok := ctx.Value(spendKey{}).(*spend); ok { s.mu.Lock() @@ -362,6 +363,21 @@ func addSpend(ctx context.Context, cost float64, costed bool) { } } +// Metered reports whether what a Call with ctx costs is counted: toward +// the reply, for a tool's ctx during an Ask, or by a meter from Meter. +func Metered(ctx context.Context) bool { + _, ok := ctx.Value(spendKey{}).(*spend) + return ok +} + +// Meter is ctx with a meter for what Calls made with it cost, outside an +// Ask, and a func that returns what they cost since it was last called, +// and whether the API reported a cost, for a caller that counts it itself. +func Meter(ctx context.Context) (context.Context, func() (float64, bool)) { + s := &spend{} + return context.WithValue(ctx, spendKey{}, s), s.take +} + // take returns what was spent since it was last taken. func (s *spend) take() (float64, bool) { s.mu.Lock() @@ -389,22 +405,30 @@ func (c *Client) Provider() string { return "" } -// Call posts body to path at the API, for a tool, and returns the -// response. On OpenRouter it asks for providers that don't collect the -// data, as every request does; the cost the response reports is added to -// the reply of the Ask whose tool called it. Outside a tool there is no -// reply to count it toward, so it refuses. +// Call posts body to path at the API, for a tool or a ctx from Meter, and +// returns the response. On OpenRouter it asks for providers that don't +// collect the data, as every request does; the cost the response reports +// is added to the reply of the Ask whose tool called it, or to ctx's +// meter. Without either there is nothing to count it toward, so it +// refuses. For "/chat/completions" the model is the client's own, whatever +// body names, and on OpenRouter the cost is asked for. func (c *Client) Call(ctx context.Context, path string, body map[string]any) (json.RawMessage, error) { - if _, ok := ctx.Value(spendKey{}).(*spend); !ok { - return nil, errors.New("the model's API is called only from a tool") + if !Metered(ctx) { + return nil, errors.New("the model's API is called only from a tool, or metered") } - if !apiPath.MatchString(path) || path == "/chat/completions" { + if !apiPath.MatchString(path) { return nil, fmt.Errorf("not an endpoint a tool may call: %q", path) } body = maps.Clone(body) if body == nil { body = map[string]any{} } + if path == "/chat/completions" { + body["model"] = c.model // never a dearer one + if c.openRouter { + body["usage"] = map[string]bool{"include": true} + } + } if c.openRouter { p := map[string]any{} // the body's provider settings, of whatever Go type, as a JSON object if v, ok := body["provider"]; ok && v != nil { diff --git a/internal/model/model_test.go b/internal/model/model_test.go index 20a5dbb..39a0865 100644 --- a/internal/model/model_test.go +++ b/internal/model/model_test.go @@ -696,7 +696,7 @@ func TestCall(t *testing.T) { t.Error("called outside a tool") } inTool := context.WithValue(context.Background(), spendKey{}, &spend{}) - for _, path := range []string{"/chat/completions", "images", "/images?x=1", "/../keys", ""} { + for _, path := range []string{"images", "/images?x=1", "/../keys", "", "/chat/completions?x=1"} { if _, err := c.Call(inTool, path, map[string]any{}); err == nil { t.Errorf("called %q", path) } @@ -723,6 +723,62 @@ func TestCall(t *testing.T) { } } +// Outside a tool, a Call with a ctx from Meter is made and its cost read +// from the meter. A chat completion gets the client's own model, whatever +// the body names, and on OpenRouter asks for the cost and for providers +// that don't collect the data; on another API only the model is set. +func TestCallMetered(t *testing.T) { + var logs logx.Buffer + t.Cleanup(logx.SetOutput(&logs, &logs, false)) + var mu sync.Mutex + var called map[string]any + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + mu.Lock() + defer mu.Unlock() + called = nil + json.Unmarshal(b, &called) + io.WriteString(w, text("a secret answer").body) + })) + t.Cleanup(srv.Close) + c := client(t, srv.URL, true) + if Metered(context.Background()) { + t.Fatal("a plain ctx is metered") + } + ctx, spent := Meter(context.Background()) + if !Metered(ctx) { + t.Fatal("a meter's ctx isn't metered") + } + body := map[string]any{"model": "x/dearer", "messages": []any{map[string]any{"role": "user", "content": "a secret question"}}, "max_tokens": 100} + got, err := c.Call(ctx, "/chat/completions", body) + if err != nil || !strings.Contains(string(got), "a secret answer") { + t.Fatalf("got %s, %v", got, err) + } + if cost, ok := spent(); cost != 0.002 || !ok { + t.Errorf("cost %v, %v", cost, ok) + } + if cost, ok := spent(); cost != 0 || ok { + t.Errorf("taken twice: %v, %v", cost, ok) + } + if body["model"] != "x/dearer" { + t.Error("the caller's body was changed") + } + if called["model"] != "x/model" || !reflect.DeepEqual(called["usage"], map[string]any{"include": true}) || + !reflect.DeepEqual(called["provider"], map[string]any{"data_collection": "deny"}) || called["max_tokens"] != 100.0 { + t.Errorf("request %v", called) + } + if l := logs.String(); !strings.Contains(l, "api /chat/completions ") || strings.Contains(l, "secret") { + t.Errorf("logged %q", l) + } + other := client(t, srv.URL, false) + if _, err := other.Call(ctx, "/chat/completions", map[string]any{"model": "x/dearer"}); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(called, map[string]any{"model": "x/model"}) { + t.Errorf("another API got %v", called) + } +} + // A picture a tool made goes out, alone, when the request after it fails. func TestPicturesKeptOnLaterFailure(t *testing.T) { c, _, logs := start(t, calls("draw"), served{status: 500, body: `{"error":{"message":"upstream"}}`}) From ad732c19469ba831d97cad61e564c45b498b7fad Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 21 Nov 2026 03:28:42 +0000 Subject: [PATCH 20/26] docs: give addons their full path in the MCP file Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- docs/FILES_LINKS_TOOLS_MCP.md | 8 ++++---- examples/signalbot-mcp.json | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/FILES_LINKS_TOOLS_MCP.md b/docs/FILES_LINKS_TOOLS_MCP.md index 856c755..0574cda 100644 --- a/docs/FILES_LINKS_TOOLS_MCP.md +++ b/docs/FILES_LINKS_TOOLS_MCP.md @@ -55,12 +55,12 @@ The model can call tools from [MCP](https://modelcontextprotocol.io) servers, re } }, "geo": { - "command": "/addons/geoguess", + "command": "/opt/signalbot-addons/geoguess", "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m", "timeout": "60s"}}, "addon": {"chats": ["all"], "dms": false, "post": true, "react": true, "watch": true, "watch_max": "1h"} }, "quiz": { - "command": "/addons/quiz", + "command": "/opt/signalbot-addons/quiz", "chat_commands": {"quiz": {"tool": "quiz", "direct": true, "example": "/quiz 80s music", "timeout": "90s"}}, "addon": {"chats": ["all"], "post": true, "react": true, "watch": true, "model": {"per_hour": 30, "max_tokens": 4000}} }, @@ -111,7 +111,7 @@ An addon written in Go can use the package [`github.com/robdevops/signalbot/addo ```jsonc "geo": { - "command": "/addons/geoguess", + "command": "/opt/signalbot-addons/geoguess", "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m", "timeout": "60s"}}, "addon": { "chats": ["<group ID>"], @@ -150,7 +150,7 @@ Each permission is off unless set. For an addon, `chats`, `dms` and these permis - **Settings.** An addon has no `env` block. It gets `PATH`, `HOME`, the bot's time zone (`TZ`) and proxy settings (`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, and `SSL_CERT_FILE` or `SSL_CERT_DIR` for a custom CA) if set, and every variable in the bot's environment (`/etc/signalbot.env`) that starts with its server's name in capitals, anything but letters and digits as `_`, then `_`: the server `geo` gets `GEO_STATE_DIR`, `GEO_MAPILLARY_TOKEN` and so on, and never the bot's own keys. A name whose prefix starts one of the bot's settings (such as `model`, `signal` or `mcp`) is a config error. If an addon keeps files, give it a directory under its prefix and create it, writable by the bot's user. - **Logs.** The bot logs an addon's commands, calls and drops by name, outcome, time and size, never what was said. An addon's stderr is counted ("addon geo wrote 3 lines (210 bytes) to stderr", at most once a minute and once more when it exits), never logged, since it may echo a message. To debug an addon, run it on its own with stderr going to your own file. - **State.** The bot keeps an addon's watches, the messages they took, the chats it may post in and how far it has read its outbox in `mcp.json`, so a restart of either doesn't lose a round. See [PRIVACY.md](../PRIVACY.md#addons). -- **Docker.** The image has no shell or runtimes, so an addon must be a static binary (`CGO_ENABLED=0 go build`), mounted read-only, such as `- /opt/signalbot-addons:/addons:ro` in `compose.yaml`. The state directory must be writable by user 65532 for `mcp.json`, and so must any directory the addon keeps files in. Addons share the container's or unit's memory and process limits, so raise `mem_limit` or `MemoryMax` to suit; `GOMEMLIMIT` isn't passed on, so a Go addon takes its limit from its own setting (GeoGuess: `GEO_MEMLIMIT`). +- **Docker.** The image has no shell or runtimes, so an addon must be a static binary (`CGO_ENABLED=0 go build`), mounted read-only at the same path, such as `- /opt/signalbot-addons:/opt/signalbot-addons:ro` in `compose.yaml`, so its `command` is the same under Docker and systemd (whose `ProtectSystem=strict` leaves `/opt` readable). The state directory must be writable by user 65532 for `mcp.json`, and so must any directory the addon keeps files in. Addons share the container's or unit's memory and process limits, so raise `mem_limit` or `MemoryMax` to suit; `GOMEMLIMIT` isn't passed on, so a Go addon takes its limit from its own setting (GeoGuess: `GEO_MEMLIMIT`). --- diff --git a/examples/signalbot-mcp.json b/examples/signalbot-mcp.json index 7d291ef..4c6f0f3 100644 --- a/examples/signalbot-mcp.json +++ b/examples/signalbot-mcp.json @@ -11,12 +11,12 @@ } }, "geo": { - "command": "/addons/geoguess", + "command": "/opt/signalbot-addons/geoguess", "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m", "timeout": "60s"}}, "addon": {"chats": ["all"], "dms": false, "post": true, "react": true, "watch": true, "watch_max": "1h"} }, "quiz": { - "command": "/addons/quiz", + "command": "/opt/signalbot-addons/quiz", "chat_commands": {"quiz": {"tool": "quiz", "direct": true, "example": "/quiz 80s music", "timeout": "90s"}}, "addon": {"chats": ["all"], "post": true, "react": true, "watch": true, "model": {"per_hour": 30, "max_tokens": 4000}} }, From f5a542f095fb5bbd1721f75a1ac38a9629a74f80 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 21 Nov 2026 04:02:30 +0000 Subject: [PATCH 21/26] Addons get a state directory by default, and can reply to their own posts - An addon whose <PREFIX>STATE_DIR isn't set gets <state dir>/addons/<name>, which it creates itself. - feature.Post.ReplyTo sends a post as a reply to one of the bot's own earlier messages: a quote on Signal, reply_parameters on Telegram. - An outbox post op's replyTo names an earlier post op of the addon's; the bot remembers 256 of them for 24 hours, in mcp.json. Replies are never merged, and wait for a dropped target. addon.Server.QueueIDs returns the IDs given. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- PRIVACY.md | 5 +- TECHNICAL.md | 8 +- addon/schema.json | 6 +- addon/schema_test.go | 5 + addon/server.go | 16 ++- addon/server_test.go | 8 +- addon/types.go | 17 +-- docs/CONFIGURATION.md | 2 +- docs/FILES_LINKS_TOOLS_MCP.md | 6 +- internal/bot/answer.go | 8 +- internal/bot/bot.go | 9 +- internal/bot/fakes_test.go | 5 +- internal/bot/host.go | 6 +- internal/bot/host_test.go | 15 +++ internal/feature/feature.go | 1 + internal/features/mcp/addon.go | 41 ++++++- internal/features/mcp/addon_test.go | 74 +++++++++++- internal/features/mcp/conn.go | 3 +- internal/features/mcp/keep.go | 30 ++++- internal/features/mcp/mcp.go | 8 ++ internal/features/mcp/outbox.go | 147 ++++++++++++++++++++--- internal/features/mcp/watch_test.go | 175 +++++++++++++++++++++++++++- internal/signal/client_test.go | 24 ++-- internal/signal/markdown_test.go | 4 +- internal/signal/send.go | 20 +++- internal/signal/send_test.go | 8 +- internal/telegram/send.go | 41 ++++--- internal/telegram/telegram_test.go | 62 +++++++--- 28 files changed, 631 insertions(+), 123 deletions(-) diff --git a/PRIVACY.md b/PRIVACY.md index cb34c20..bc1a4b0 100644 --- a/PRIVACY.md +++ b/PRIVACY.md @@ -36,7 +36,7 @@ Every request to OpenRouter tells it to use only model providers that do not col - **No swap or core dumps.** The included systemd unit and Docker command forbid both, so history cannot reach disk that way. - **Memory is freed, not wiped.** An expired message is dropped and Go's garbage collector reclaims its memory, but the bytes may linger until overwritten, and someone with root access to the host could read them from the running process. - **What features save, on disk.** Features save state only through the core, one file each in the state directory (`/var/lib/private/signalbot`), so everything the bot keeps on disk is listed here. -- **Schedules are kept on disk.** Each `/schedule` saves, in `schedules.json` in the state directory (`/var/lib/private/signalbot`), the scheduling user's ID, the group's ID and its name when scheduled (if it's for a group), the time and repeat, and the text to post, until the user deletes it with `/schedule del`. The file also keeps, for each user who has scheduled, the last schedule number they were given, so numbers are never reused; it stays after their schedules are deleted. A one-off dropped because the bot was down is deleted, and its user is told in their DM, with the first 80 characters of its text. Besides today's spending and, with an addon, `mcp.json` (both below), nothing else the bot keeps is written to disk. +- **Schedules are kept on disk.** Each `/schedule` saves, in `schedules.json` in the state directory (`/var/lib/private/signalbot`), the scheduling user's ID, the group's ID and its name when scheduled (if it's for a group), the time and repeat, and the text to post, until the user deletes it with `/schedule del`. The file also keeps, for each user who has scheduled, the last schedule number they were given, so numbers are never reused; it stays after their schedules are deleted. A one-off dropped because the bot was down is deleted, and its user is told in their DM, with the first 80 characters of its text. Besides today's spending and, with an addon, `mcp.json` (both below), nothing else the bot keeps is written to disk; an addon's own `addons/<name>` directory is the addon's (below). - **Today's spending, on disk.** With a daily budget (`DAILY_BUDGET`, on by default), `budget.json` in the state directory holds today's date and, for each chat that used the model today, what it spent and whether it was told it reached the limit. Chats are stored under a SHA-256 hash of their ID, so the file holds no phone numbers, account IDs or group IDs as such. A hash of a phone number could be matched by trying every number, so treat the file as you would the schedules. Each day's file replaces the last. - **Addon state, on disk.** With an MCP server configured as an addon, `mcp.json` in the state directory holds what is listed under [Addons](#addons). Without one, the file is never written. - **Recent attachments, in memory only.** So that "@bot summarise this" in reply to someone's file can fetch the original, the bot remembers, for each group message and each DM from an allowed sender with attachments, the attachments' IDs, file names, types and sizes, never their content, under the chat, sender and time. Each is forgotten after a day, or sooner when 2,000 newer messages are remembered, and a restart clears them all. On Signal the bot also keeps a copy of each picture it sent (a chart, a picture it made), content and all, for at most a day and 32 MB in all, since signal-cli keeps none: a reply quoting it then shows the model the picture rather than Signal's small thumbnail. A delete of that message from the account's linked device drops it, and a restart clears them all. @@ -91,7 +91,7 @@ An addon is a program the bot runs on its own machine, as an [MCP server](docs/F - `global_ids` gives a person the same pseudonym in every chat, so the addon can link them across groups; - `post` and `react` send nothing: they let it post and react, only in a chat where it was used in the last day; - `model` lets it ask the bot's model, with the bot's key: the addon's prompts, and whatever it put in them from the chat, go to the model provider, as chat with the bot does, and what they cost counts toward that chat's `DAILY_BUDGET`. The bot logs only each request's outcome, time, size and cost, never the prompt or the answer. -- **What the addon keeps** is its own, in whatever directory you give it (GeoGuess: `GEO_STATE_DIR`), outside what this page lists for the bot. Read its own documentation. +- **What the addon keeps** is its own, outside what this page lists for the bot, in the directory its `…_STATE_DIR` names (GeoGuess: `GEO_STATE_DIR`): by default `addons/<server name>` in the state directory (`/var/lib/private/signalbot/addons/geo`), which the addon creates and writes, never the bot. Read its own documentation. - **Deletes and edits are not passed on.** A message an addon took stays with the addon if its sender later deletes it for everyone. An edit of one is passed on, as a new version. - **Taken messages are kept nowhere by the bot:** not in history, not as context (so `GROUP_CONTEXT=false` makes no difference to them), not in the log. The addon still gets them. - **What it posts** is kept in history as the bot's own words, labelled with the addon's name (`[GeoGuess] …`) and cut to 500 characters, so later model requests can see it but it never poses as a person. @@ -104,6 +104,7 @@ An addon is a program the bot runs on its own machine, as an [MCP server](docs/F | Live watches: the chat's pseudonym, the pattern, and the times of the bot's messages with the command's pictures, and for a reply watch of the addon's messages | Until the watch ends, at most `watch_max` (24 hours at most) | | Messages a watch took: the chat's ID, the sender's pseudonym and the message's time, never its text | 48 hours, so a later edit is taken too | | How far the bot has read each addon's outbox, and the last 1,000 outbox entries' IDs | Replaced on each save; dropped once the server is no longer an addon | + | An addon's last 256 posts, for a later post to reply to: the post's ID, the chat's pseudonym and the time (on Telegram, the ID) of the bot's message, never its text | 24 hours | Refs to messages (for reactions, a day), display names (a day) and posts waiting to go out are kept in memory only. diff --git a/TECHNICAL.md b/TECHNICAL.md index ef55ed6..3536932 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -137,7 +137,7 @@ The core's lifecycle has four stages. Each port is one stage; nothing else is a - anything else the bot posts as written, with @Name linked against the group's members (never an ambiguous name), and history keeps it as the sender's message, "<name>: <text>", not as something the bot chose to say. These rules are what "as if its sender had just posted it" means for any feature, not just `/schedule`, so the host applies them rather than each feature. The membership check calls the network, so it runs in the message's slot; a feature's timer callback has no slot to make that call in. -- `Post(Post)`: the bot posts `Text`, with any `Pictures` (the caption rule applies), to a group or a DM, as written, never through the model, through that chat's mailbox. In the slot, `Network.Reachable` must say the bot may still post there, or it is dropped and logged at info. `@Name` is linked against the chat's known names. With a `Label`, history keeps the post as the bot's own entry, `[Label] text` (the pictures' notes in place of text they replaced), clamped to 500 characters, so a feature's text can never pose as a person; with none, or with no model, nothing is kept. `OnSent`, if set, is called once, with the timestamps sent, or with dropped set when it never goes out (a full mailbox, an unreachable chat, shutdown, a send that failed and returned no timestamps). `/schedule` uses it, with no label, to tell an owner in their DM that a one-off was dropped. +- `Post(Post)`: the bot posts `Text`, with any `Pictures` (the caption rule applies), to a group or a DM, as written, never through the model, through that chat's mailbox. In the slot, `Network.Reachable` must say the bot may still post there, or it is dropped and logged at info. `@Name` is linked against the chat's known names. With a `Label`, history keeps the post as the bot's own entry, `[Label] text` (the pictures' notes in place of text they replaced), clamped to 500 characters, so a feature's text can never pose as a person; with none, or with no model, nothing is kept. `OnSent`, if set, is called once, with the timestamps sent, or with dropped set when it never goes out (a full mailbox, an unreachable chat, shutdown, a send that failed and returned no timestamps). `ReplyTo`, if set, is one of those timestamps from an earlier post or answer of the bot's in the same chat, and the post goes as a reply to it: the core passes it to `Network.Send`, whose first message sent replies to that message (Signal: `send` with `quoteTimestamp` and `quoteAuthor`, the bot's own account; Telegram: `reply_parameters` with `message_id` and `allow_sending_without_reply`, so a deleted message doesn't stop the post). signal-cli quotes by timestamp and author alone, whether or not it still has the message, so a recipient without it sees a quote of a message not found. Every other send passes 0, for none. `/schedule` uses it, with no label, to tell an owner in their DM that a one-off was dropped. - `React(chat, msg, emoji)`: the bot puts `emoji` on `msg`, through the chat's mailbox at low priority (see the per-chat mailbox): a later reaction to the same message replaces a waiting one, at most 16 wait per chat, and one to a message deleted or replaced by an edit since is skipped. `chat` mirrors `Network.React`; `msg`'s own `Chat` is ignored. A message the bot made (`Timestamp` 0) can't be reacted to; nothing happens. - `Groups(ctx, user)`: the groups the bot shares with a user, with their names (`listGroups`). - `Redact(text)`: text with every name and ID the bot knows for anyone but itself, and any UUID or phone number, replaced with "redacted", for logging text the bot doesn't control (a local MCP server's output). @@ -239,7 +239,7 @@ In `features.go` order, which is the order hooks run in and of the tools line an - **`img.Safe`** (`kit/img`) checks any image from a server before it is sent: only PNG, JPEG, GIF or WebP, read from the header alone, at most 8,192 pixels a side and 40 megapixels, so a small file claiming a huge canvas never reaches phones; a JPEG loses its EXIF (keeping its orientation), XMP, IPTC, comments and anything after the image, by walking its segments without decoding pixels, since signal-cli sends attachments as they are and GPS tags would say where a photo was taken. - **Addons** are local MCP servers with an `addon` block (the extension's wire format, which the feature and every addon written in Go share, is the public package `addon`, in [Layout](#layout)) in `MCP_CONFIG` that also advertise `io.github.robdevops.signalbot/addon` at version 1 in their `initialize` result's `capabilities.experimental`. The bot offers the same key in its `initialize` request with the chat network it is on, `{"version": 1, "network": "signal"}` (`Info.Network`, which each network names itself with `Network.Name`), so an addon can word its messages for that network, and, to a server with an addon block, `"watchReplies": true`, so it knows it may ask for a reply watch. To an addon with `model`, while `Info.Model` is set and the store is open, it also offers MCP's `capabilities.sampling: {}`. One with the block that doesn't advertise it runs as a plain server, with a warning. They are part of `mcp`: no port of the core names them. - **Config:** the block's keys are `chats` (group IDs exactly as Signal or Telegram shows them, a Telegram topic counting as its group, or `["all"]` alone; anything else is an error asking for the group's ID), `dms`, `post`, `react`, `watch` (each off unless set), `watch_max` (1s to 24h, default 1h), `names`, `global_ids`, `rate` (`per_minute`, default 20, and `burst`, default 5) and `model` (`per_hour`, default 30, and `max_tokens`, default 4000, at most 32,000; off unless set, `{}` for the defaults; neither below 0). Unknown keys get the same error as a server's. An addon must be local (`command`), can't have an `env` block, and its server's name can't make a prefix (below) that one of the bot's own settings starts with (the names in `docs/CONFIGURATION.md`'s table, plus `STATE_DIRECTORY`, a list a test keeps in step); a `direct` chat command without an addon block is an error. Its error text and its start, initialize and call failures are logged by code only, never the server's words. - - **Environment:** an addon gets `PATH`, `HOME`, those of `TZ`, `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` (and their lowercase forms), `SSL_CERT_FILE` and `SSL_CERT_DIR` that are set, so it keeps the bot's time zone and reaches the internet as the bot does, and every variable of the bot's environment that starts with its prefix: its server's name in capitals, anything but letters and digits as `_`, then `_` (`geo` gets `GEO_…`). Nothing else, so the bot's keys never reach it. These are read with `os.Environ`, not `Env`, so each addon documents its own. + - **Environment:** an addon gets `PATH`, `HOME`, those of `TZ`, `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY` (and their lowercase forms), `SSL_CERT_FILE` and `SSL_CERT_DIR` that are set, so it keeps the bot's time zone and reaches the internet as the bot does, and every variable of the bot's environment that starts with its prefix: its server's name in capitals, anything but letters and digits as `_`, then `_` (`geo` gets `GEO_…`). Nothing else, so the bot's keys never reach it. When `<PREFIX>STATE_DIR` isn't set, it gets one: `addons/<server name>` in `STATE_DIRECTORY`'s first directory, made absolute, the convention for where an addon keeps its files (it creates the directory, 0700; the bot writes nothing there, as features write only through `Store`). None when `STATE_DIRECTORY` isn't set, or for a name that isn't letters, digits, `.`, `_` and `-` (up to 64, not starting with `.`), so no name reaches outside `addons`; `STATE_DIRECTORY` is read only when some server is an addon. These are read with `os.Environ`, not `Env`, so each addon documents its own. - **Stderr:** an addon's is never logged, since it may write what it was sent: only "addon <name> wrote N lines (M bytes) to stderr", at most once a minute, and once more when it exits for what was counted since, so a crash's output is never left uncounted. - **The store:** with any addon configured, `mcp` opens its `Store` (`mcp`, `mcp.json`), so MCP without addons needs no state directory. It holds a 32-byte random secret, made once, and each addon's state (below). If the store can't be opened, or the secret read or saved, addons run as plain servers, with an error at startup, rather than with a new secret that would change every pseudonym. A damaged secret is an error too. One saver goroutine writes the document whenever told something changed (a non-blocking send on a 1-buffered channel), and once at shutdown, so a hook never waits on the disk and a burst is one write; a failed save is logged once, the state stays in memory, and the next change tries again. The state of a server no longer configured as an addon is dropped at the first save. - **Pseudonyms:** an addon never sees a phone number, account ID or group ID. Each addon has its own key, HMAC-SHA256 of the secret and its server's name. A chat is `c_` and HMAC(key, `chat\0` + chat key); a sender `u_` and HMAC(key, `user\0` + chat key + `\0` + ID), so the same person is someone else in each chat, or with `global_ids` HMAC(key, `user\0` + ID), the same everywhere; each cut to 128 bits and written in lowercase base32. A ref, `r_` and 128 random bits, names one message, for a reaction, and is kept in memory for 24 hours. @@ -248,9 +248,9 @@ In `features.go` order, which is the order hooks run in and of the tools line an - **Watches:** a direct command's result may ask, in `_meta["io.github.robdevops.signalbot/watch"]`, for a watch on the chat the command came from (the only way to make one, so an addon can't watch a chat it wasn't used in): an `id` (at most 64 characters), an RE2 `pattern` (at most 1,024 characters), `until` (RFC 3339, cut to `watch_max` from now and never extended), the `tool` to call with each match (one the bot may call) and an optional `guard` (at most 500 characters). It needs `watch`, and at most 8 are live in a chat per addon (one with the same ID is replaced). A pattern that matches the empty string or any of about 200 ordinary chat lines in `corpus.go` is refused, so no watch is a feed of the chat; a refusal is logged by reason, never the pattern. One `OnMessage` hook, registered after the chat commands, checks each message with text in an allowed chat against the chat's live watches, on both paths: unaddressed ones on the reader goroutine (only a map lookup and the patterns, under a mutex held briefly), addressed ones (a reply to the bot, a DM, an @mention, a command) in their slot. A watch matches any message the bot gets while it lasts, by when the bot got it, not by its `Timestamp` (on Signal the sender's clock, which may be behind); an edit, unless its original was claimed, only if its original's `Timestamp` is at or after the command's, so an older message's edit isn't taken. An addressed message with no text (a bare mention, or a reply with only a picture) is still checked for the guard. A match is `Done`, so it is never answered, sent to the model or kept in history, and `groupctx` never sees it; it is claimed for 48 hours (chat key, sender's pseudonym, sent time), so a later edit of it goes the same way, to the same tool, whether or not the watch is still live; and it is passed without waiting to the addon's watch worker, whose queue holds 256 (when full, "addon <name>: watch queue full, a matched message dropped", still `Done`). The worker calls the watch's tool with `{"text": …}` and the context, within 120 calls a minute per chat (bursts of 20; a match past it waits its turn in the worker's queue, while other chats' matches go ahead), and keeps a match whose call found the server down (not running, or exited before answering) at the head of the queue until the server has started again (or a minute has passed), dropping it with a warning after 3 such calls, and if the result's `_meta["io.github.robdevops.signalbot/react"]` is one emoji, reacts with it (`React`), which needs `react` and counts against the addon's rate. A watch whose command answered with pictures records, through `OnSent`, the timestamps of the messages they went out in; while it lives, an addressed message quoting one of them gets the `guard` as its `Answer`, so nobody can ask the model about the picture. - **Reply watches:** a watch with `replies` takes only addressed messages whose `Quote.Bot` is set and whose `Quote.Sent` is the timestamp of one of the addon's own messages in the chat sent while it lives: a direct command's answer (any answer, through the `Action`'s `OnSent`) and each outbox post (through the `Post`'s `OnSent`), recorded on every live reply watch in the chat, the last 64 each. Its `pattern`, if set, must match too; it may be empty, and isn't checked against `corpus.go`, since a reply to the addon's own message is meant for it. Claims, edits, the worker, its rate and queue work as for any watch. Without `replies`, a watch works as above, and an empty pattern is refused. - **Leases:** an addon may post or react only in a chat where it had a direct command or a watch match in the last 24 hours; the lease maps the chat's pseudonym to the chat. - - **Outbox:** if the server advertises `resources.subscribe`, the bot sends `resources/subscribe` for `signalbot://outbox` after each (re)start's `initialize`, then reads it; otherwise the outbox is off, with a warning. Any `notifications/resources/updated` from the server marks the outbox as having news (whatever the URI, which may be under the one subscribed). One reader goroutine per addon reads `resources/read` of `signalbot://outbox/<cursor>` (`0` at first), page by page while `more` is true, up to 100 pages, so two reads never race and news during a read is read after it. A page is one text content holding `{"cursor", "more", "ops"}`; a not-found error (-32002, or the Go SDK's -32602) is logged as no outbox. Ops are applied once each by `id`, the last 1,000 IDs remembered, and are `post` (`chat`, Markdown `text` with placeholders, up to 2 `images` as `{data, mimeType, name}`, 2 MB together), needing `post`; `react` (`ref`, `emoji`), needing `react`; and `unwatch` (`chat`, `watch`), which, for a watch not yet made, stops it being made for 10 minutes. A post or reaction needs a live lease in a chat the addon is still allowed, and counts against `rate` per chat. A post goes through `Post` with the addon's title as its `Label`, so history keeps it as `[Title] …`, the bot's own words. At most one of an addon's posts waits in a chat's mailbox: until its `OnSent`, later posts for that chat are held, each merged into the one held before it while their pictures together stay within 2 and 2 MB and their texts together within 4,000 characters, so a merge never cuts one, and sent in turn. Delivery is at least once: a post counts as applied, and the cursor moves past it, only once its `OnSent` says it was sent. A send that fails counts as dropped, so a post whose send timed out after it went out may be posted twice, rather than lost. Until then each read starts from the cursor before it and skips it while it waits; one dropped before it was sent (as while the bot stops, or before the network is up at startup, when `Post` gives up on the chat) is posted again by a read 10s later, then 20s, doubling to 5 minutes, not counted against `rate` again, and given up with a warning after 6 tries. A page with `more` waits for its posts before the next is read, since reading past the cursor lets the addon forget them. A read that fails, is malformed, or stops at 100 pages is tried again after 10s, doubling to 5 minutes, without waiting for news. What a read drops is counted in one warning by reason, never content. + - **Outbox:** if the server advertises `resources.subscribe`, the bot sends `resources/subscribe` for `signalbot://outbox` after each (re)start's `initialize`, then reads it; otherwise the outbox is off, with a warning. Any `notifications/resources/updated` from the server marks the outbox as having news (whatever the URI, which may be under the one subscribed). One reader goroutine per addon reads `resources/read` of `signalbot://outbox/<cursor>` (`0` at first), page by page while `more` is true, up to 100 pages, so two reads never race and news during a read is read after it. A page is one text content holding `{"cursor", "more", "ops"}`; a not-found error (-32002, or the Go SDK's -32602) is logged as no outbox. Ops are applied once each by `id`, the last 1,000 IDs remembered, and are `post` (`chat`, Markdown `text` with placeholders, up to 2 `images` as `{data, mimeType, name}`, 2 MB together, and optionally `replyTo`), needing `post`; `react` (`ref`, `emoji`), needing `react`; and `unwatch` (`chat`, `watch`), which, for a watch not yet made, stops it being made for 10 minutes. A post or reaction needs a live lease in a chat the addon is still allowed, and counts against `rate` per chat. A post goes through `Post` with the addon's title as its `Label`, so history keeps it as `[Title] …`, the bot's own words. At most one of an addon's posts waits in a chat's mailbox: until its `OnSent`, later posts for that chat are held, each merged into the one held before it while their pictures together stay within 2 and 2 MB and their texts together within 4,000 characters, so a merge never cuts one, and sent in turn. A post with `replyTo`, the `id` of an earlier post op of the addon's, is never merged, in either direction, so it stays its own message and a later post a new one. As each post is sent, its op IDs (a merged post's every one) are remembered with the chat's pseudonym and the first timestamp `OnSent` gave, for 24 hours, the last 256 by when they expire. When a post with `replyTo` is put in the mailbox, after any held before it in its chat went out, a remembered target in the same chat becomes the `Post`'s `ReplyTo`; an unknown, expired or other chat's target leaves it a plain post. While its target was dropped and waits to be posted again, a reply waits too, without counting a try, and is posted after it. Delivery is at least once: a post counts as applied, and the cursor moves past it, only once its `OnSent` says it was sent. A send that fails counts as dropped, so a post whose send timed out after it went out may be posted twice, rather than lost. Until then each read starts from the cursor before it and skips it while it waits; one dropped before it was sent (as while the bot stops, or before the network is up at startup, when `Post` gives up on the chat) is posted again by a read 10s later, then 20s, doubling to 5 minutes, not counted against `rate` again, and given up with a warning after 6 tries. A page with `more` waits for its posts before the next is read, since reading past the cursor lets the addon forget them. A read that fails, is malformed, or stops at 100 pages is tried again after 10s, doubling to 5 minutes, without waiting for news. What a read drops is counted in one warning by reason, never content. - **Sampling:** an addon offered sampling may send MCP's `sampling/createMessage`. The stdio client reads every message's ID as raw JSON, so a server's request may use a string ID, answered with the same one. `dispatch` hands the request to the addon's handler on a goroutine of its own, never the reader's, so a slow model call never holds up replies; one is served at a time per addon, and a second gets -32000 at once. The handler is installed before `initialize`, behind a `gate` that holds a request until the addon is set up after `tools/list`, and refuses it with -32000 if it never is (as when the server turns out not to speak the extension), so a request is never called unsupported while sampling is offered. An incoming `notifications/cancelled` naming it, or the process exiting, cancels its ctx, and a cancelled request gets no answer; an answer to a process that has since restarted is dropped. The model call doesn't take that cancel: it runs under `context.WithoutCancel` with its own 2 minutes, so a call the provider bills is always charged to the chat, and the addon can't spend outside `DAILY_BUDGET` by cancelling or exiting. Any other request, or this one from an addon without it, gets -32601, and `ping` `{}`, as before. The handler (`sample.go`) takes text messages only, `user` or `assistant`, at most 16 and 32 KB of text with the system prompt, and a `maxTokens` of at least 1, capped at `max_tokens`; `temperature` (0 to 2) is passed on, and `modelPreferences` and `includeContext` are ignored. `_meta["io.github.robdevops.signalbot/chat"]` must name a chat the addon holds a live lease in and is still allowed, and `per_hour` (a `limiter`, all of the addon's chats as one bucket) must have room; a refusal is -32602 or -32000 with a short message. It posts `{"messages": [system, …], "max_tokens", "temperature"}` to `/chat/completions` through `CallAPI` with `feature.ChargeTo` that chat, so the core sets its own model, refuses a chat over `DAILY_BUDGET` and charges it, within 2 minutes, and answers `{role: "assistant", content: {type: "text", text}, model, stopReason}` from `choices[0].message.content`, `model` and `finish_reason` (`stop` as `endTurn`, `length` as `maxTokens`). A failure is -32603, "the model couldn't answer", never the API's text. It logs the outcome, time, the request's text size, the answer's tokens and the cost, never the prompt or the answer. - - **What is saved,** per addon, in `mcp.json`: live watches (with their guard pictures' timestamps, and a reply watch's messages' timestamps), claims, leases, the outbox cursor and the last 1,000 applied op IDs. Anything expired is left out. At startup they are restored, leaving out a watch whose chat is no longer allowed or whose pattern no longer passes, so a restart of the bot or the addon never lets a match fall through to history. Refs, names, tombstones and held posts are in memory only. + - **What is saved,** per addon, in `mcp.json`: live watches (with their guard pictures' timestamps, and a reply watch's messages' timestamps), claims, leases, the outbox cursor, the last 1,000 applied op IDs, and the posts a later one may reply to (`posted`: op ID to chat pseudonym, timestamp and expiry). Anything expired is left out. At startup they are restored, leaving out a watch whose chat is no longer allowed or whose pattern no longer passes, so a restart of the bot or the addon never lets a match fall through to history. Refs, names, tombstones and held posts are in memory only. - **`groupctx`** (`GROUP_CONTEXT`, on by default) comes after `mcp`, so an earlier hook can claim a message (`Done`) before it is kept, and keeps each other unaddressed group message as context: `Name: text`, capped at 2,000 characters, with photos, stickers and files noted as `[image]`, `[sticker]` and `[file "name"]` but never fetched. The core keeps it like any history entry, marked as context, and never logs it. - **`schedule`** is `/schedule` ([below](#schedule)). diff --git a/addon/schema.json b/addon/schema.json index bcc16b6..91d4989 100644 --- a/addon/schema.json +++ b/addon/schema.json @@ -101,14 +101,16 @@ "images": {"description": "A post's images: at most 2, and 2 MiB in all.", "type": "array", "items": {"$ref": "#/$defs/Image"}, "maxItems": 2}, "ref": {"description": "The message a reaction is for: a context's ref.", "type": "string", "pattern": "^r_[a-z2-7]{26}$"}, "emoji": {"description": "A reaction's: one emoji.", "type": "string", "minLength": 1}, - "watch": {"description": "The ID of the watch an unwatch ends.", "type": "string", "minLength": 1, "maxLength": 64} + "watch": {"description": "The ID of the watch an unwatch ends.", "type": "string", "minLength": 1, "maxLength": 64}, + "replyTo": {"description": "A post's: the ID of an earlier post op of the addon's, such as a question, so the post is sent as a reply to it. The bot remembers the ID of each post op it sent (every op of a merged post), with its chat, for 24 hours, the last 256 IDs; a post whose replyTo it doesn't know, or that was sent in another chat, is sent as an ordinary post. A post with replyTo is never merged with another.", "type": "string", "minLength": 1} }, "required": ["id", "op"], "additionalProperties": false, "allOf": [ {"if": {"properties": {"op": {"const": "post"}}}, "then": {"required": ["chat"], "anyOf": [{"required": ["text"], "properties": {"text": {"pattern": "\\S"}}}, {"required": ["images"], "properties": {"images": {"minItems": 1}}}]}}, {"if": {"properties": {"op": {"const": "react"}}}, "then": {"required": ["ref", "emoji"]}}, - {"if": {"properties": {"op": {"const": "unwatch"}}}, "then": {"required": ["chat", "watch"]}} + {"if": {"properties": {"op": {"const": "unwatch"}}}, "then": {"required": ["chat", "watch"]}}, + {"if": {"required": ["replyTo"]}, "then": {"properties": {"op": {"const": "post"}}}} ] }, "Image": { diff --git a/addon/schema_test.go b/addon/schema_test.go index a117915..4f5921e 100644 --- a/addon/schema_test.go +++ b/addon/schema_test.go @@ -425,6 +425,7 @@ func TestSchemaSamples(t *testing.T) { {"Op", Op{ID: "2", Op: "post", Chat: chatID, Images: []Image{{Data: "aGk=", MimeType: "image/png", Name: "a.png"}}}}, {"Op", Op{ID: "3", Op: "react", Ref: refID, Emoji: "🎯"}}, {"Op", Op{ID: "4", Op: "unwatch", Chat: chatID, Watch: "r1"}}, + {"Op", Op{ID: "6", Op: "post", Chat: chatID, Text: "It was Paris.", ReplyTo: "a1b2.1"}}, {"Page", Page{Cursor: "a1b2.4", Ops: []Op{post}}}, {"Page", Page{Cursor: "a1b2.0", More: true, Ops: []Op{}}}, {"Held", Held{Op: post, Queued: time.Now()}}, @@ -472,6 +473,10 @@ func TestSchemaSamples(t *testing.T) { {"Op", "a reaction to a chat", Op{ID: "1", Op: "react", Ref: chatID, Emoji: "🎯"}}, {"Op", "an unwatch without its watch", Op{ID: "1", Op: "unwatch", Chat: chatID}}, {"Op", "a group ID for a chat", Op{ID: "1", Op: "unwatch", Chat: "group.abc=", Watch: "r1"}}, + {"Op", "an empty replyTo", map[string]any{"id": "1", "op": "post", "chat": chatID, "text": "hi", "replyTo": ""}}, + {"Op", "a replyTo that isn't a string", map[string]any{"id": "1", "op": "post", "chat": chatID, "text": "hi", "replyTo": 1}}, + {"Op", "a reaction with a replyTo", Op{ID: "1", Op: "react", Ref: refID, Emoji: "🎯", ReplyTo: "a1b2.1"}}, + {"Op", "an unwatch with a replyTo", Op{ID: "1", Op: "unwatch", Chat: chatID, Watch: "r1", ReplyTo: "a1b2.1"}}, {"Page", "no cursor", map[string]any{"more": false, "ops": []any{}}}, {"Page", "a bad op", Page{Cursor: "x.1", Ops: []Op{{ID: "1", Op: "post"}}}}, {"Held", "no time", map[string]any{"op": post}}, diff --git a/addon/server.go b/addon/server.go index 6c7f619..fa45e3f 100644 --- a/addon/server.go +++ b/addon/server.go @@ -243,27 +243,35 @@ func (s *Server) settle(m message) { // reach the bot: a post with more than MaxImages images, or an op too big // for a page as it is sent. func (s *Server) Queue(ops ...Op) error { + _, err := s.QueueIDs(ops...) + return err +} + +// QueueIDs is Queue, returning the ID it gave each op, in order, such as +// for a later post's ReplyTo. +func (s *Server) QueueIDs(ops ...Op) (ids []string, err error) { for _, o := range ops { switch { case len(o.Images) > MaxImages: - return fmt.Errorf("a post has %d images; the most is %d", len(o.Images), MaxImages) + return nil, fmt.Errorf("a post has %d images; the most is %d", len(o.Images), MaxImages) case sentSize(o) > pageSize: - return fmt.Errorf("an op is %d bytes as sent; the most is %d", sentSize(o), pageSize) + return nil, fmt.Errorf("an op is %d bytes as sent; the most is %d", sentSize(o), pageSize) } } if len(ops) == 0 { - return nil + return nil, nil } s.mu.Lock() now := s.cfg.Now() for _, o := range ops { s.seq++ o.ID = s.nonce + "." + strconv.FormatInt(s.seq, 10) + ids = append(ids, o.ID) s.outbox = append(s.outbox, held{Held: Held{Op: o, Queued: now}, seq: s.seq}) } s.mu.Unlock() s.poke() - return nil + return ids, nil } // sentSize is o's size as the bot gets it: JSON inside the JSON string of diff --git a/addon/server_test.go b/addon/server_test.go index 364e6b7..5ff2963 100644 --- a/addon/server_test.go +++ b/addon/server_test.go @@ -251,7 +251,7 @@ func TestCancel(t *testing.T) { // The outbox: a subscribed bot hears of new ops, a read gets them with a // cursor, a read at that cursor lets go of them, and a cursor the server -// doesn't know gets everything still held. +// doesn't know gets everything still held. QueueIDs gives the IDs. func TestOutbox(t *testing.T) { now := time.Date(2026, 11, 21, 9, 0, 0, 0, time.UTC) var mu sync.Mutex @@ -290,9 +290,9 @@ func TestOutbox(t *testing.T) { } mu.Unlock() - s.Queue(Op{Op: "post", Chat: "c_one", Text: "again"}) - if p := read("other.5"); len(p.Ops) != 1 || p.Ops[0].Text != "again" { - t.Errorf("an unknown cursor %+v", p) + ids, err := s.QueueIDs(Op{Op: "post", Chat: "c_one", Text: "again"}) + if p := read("other.5"); err != nil || len(p.Ops) != 1 || p.Ops[0].Text != "again" || len(ids) != 1 || p.Ops[0].ID != ids[0] { + t.Errorf("an unknown cursor %+v, IDs %v", p, ids) } resp, _ := c.reply(c.request("resources/read", uriParams{"signalbot://elsewhere"})) if resp.Error == nil || resp.Error.Code != codeNotFound { diff --git a/addon/types.go b/addon/types.go index 9bfb003..0965f7c 100644 --- a/addon/types.go +++ b/addon/types.go @@ -117,14 +117,15 @@ func Text(s string) Result { return Result{Content: []Content{{Type: "text", Tex // Op is one thing an addon's outbox asks the bot to do. type Op struct { - ID string `json:"id"` - Op string `json:"op"` // "post", "react" or "unwatch" - Chat string `json:"chat,omitempty"` // a post's or unwatch's chat pseudonym - Text string `json:"text,omitempty"` // a post's, with {u_…} placeholders the bot fills in with names - Images []Image `json:"images,omitempty"` // a post's: at most 2, 2 MB in all - Ref string `json:"ref,omitempty"` // a reaction's message - Emoji string `json:"emoji,omitempty"` // a reaction's - Watch string `json:"watch,omitempty"` // the ID of the watch an unwatch ends + ID string `json:"id"` + Op string `json:"op"` // "post", "react" or "unwatch" + Chat string `json:"chat,omitempty"` // a post's or unwatch's chat pseudonym + Text string `json:"text,omitempty"` // a post's, with {u_…} placeholders the bot fills in with names + Images []Image `json:"images,omitempty"` // a post's: at most 2, 2 MB in all + Ref string `json:"ref,omitempty"` // a reaction's message + Emoji string `json:"emoji,omitempty"` // a reaction's + Watch string `json:"watch,omitempty"` // the ID of the watch an unwatch ends + ReplyTo string `json:"replyTo,omitempty"` // a post's: the ID of an earlier post of the addon's in the same chat, which it is sent as a reply to } // Image is an image in a post. diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md index a3f9643..507de4a 100644 --- a/docs/CONFIGURATION.md +++ b/docs/CONFIGURATION.md @@ -26,7 +26,7 @@ Every setting, read from the environment (`/etc/signalbot.env` in the install). | `INTRO` | built-in sentence | Overrides the self-introduction; `{name}`, `{model}` (without any OpenRouter `provider/` prefix) and `{tools}` (the names of the tools, or `none`) are substituted | | `MAX_CONCURRENCY` | `32` | Conversations in flight at once; messages beyond this are dropped, with a warning | | `MCP_CONFIG` | empty | Path of an MCP servers file; see [MCP connectors](FILES_LINKS_TOOLS_MCP.md#mcp-connectors) | -| `<SERVER>_…` | none | An [addon's](FILES_LINKS_TOOLS_MCP.md#addons) own settings, read by the addon, not the bot. An addon server gets every variable that starts with its name in capitals, anything but letters and digits as `_`, then `_` (the server `geo` gets `GEO_STATE_DIR` and the rest), plus `PATH`, `HOME` and, if set, `TZ`, `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, `SSL_CERT_FILE` and `SSL_CERT_DIR`, and nothing else, so none of the other settings above reach it. A server whose prefix one of the settings above starts with (such as `model` or `mcp`) is a config error. Each addon documents its own, such as [GeoGuess's](https://github.com/robdevops/chat-plugin-geoguess#settings) | +| `<SERVER>_…` | none | An [addon's](FILES_LINKS_TOOLS_MCP.md#addons) own settings, read by the addon, not the bot. An addon server gets every variable that starts with its name in capitals, anything but letters and digits as `_`, then `_` (the server `geo` gets `GEO_STATE_DIR` and the rest; `GEO_STATE_DIR`, if not set, is `addons/geo` in `STATE_DIRECTORY`, which the addon creates), plus `PATH`, `HOME` and, if set, `TZ`, `HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, `SSL_CERT_FILE` and `SSL_CERT_DIR`, and nothing else, so none of the other settings above reach it. A server whose prefix one of the settings above starts with (such as `model` or `mcp`) is a config error. Each addon documents its own, such as [GeoGuess's](https://github.com/robdevops/chat-plugin-geoguess#settings) | | `STATE_DIRECTORY` | working directory | Where features save their state, one file each, such as `/schedule`'s `schedules.json`, `mcp.json` when an MCP server is an [addon](FILES_LINKS_TOOLS_MCP.md#addons) (and the core its `budget.json`); the bot won't start if a feature that saves can't list and write it. Set by systemd's `StateDirectory=signalbot` (`/var/lib/private/signalbot`) and by the Docker image (`/data`, which must be writable by user 65532) | | `TOOL_LINGER_ROUNDS` | `2` | Replies a keyword-gated tool group (charts, an MCP server with `keywords`) stays offered after the last one that matched its keywords or used its tools; `0` offers it only on a matching message. Any use or match starts the count again, so a run of follow-ups keeps it. Capped at `HISTORY_MAX`. See [How tools are offered](FILES_LINKS_TOOLS_MCP.md#how-tools-are-offered) | | `TZ` | `UTC` in Docker, the host's under systemd | Time zone for `/schedule` times without an offset and for `DARKMODE` hours, e.g. `Australia/Sydney`; addons get it too, for the times they write (GeoGuess's round deadline) | diff --git a/docs/FILES_LINKS_TOOLS_MCP.md b/docs/FILES_LINKS_TOOLS_MCP.md index 0574cda..78be97d 100644 --- a/docs/FILES_LINKS_TOOLS_MCP.md +++ b/docs/FILES_LINKS_TOOLS_MCP.md @@ -146,10 +146,10 @@ Each permission is off unless set. For an addon, `chats`, `dms` and these permis - **Hidden tools.** A tool whose `_meta` says it is for the bot alone (`io.github.robdevops.signalbot/visibility` without `"model"`, or MCP Apps' `ui.visibility` without `"model"`) is never offered to the model or listed as one of its tools, so tools that read chat text stay out of its hands. - **Watches.** A direct command's answer can ask for a watch on its chat: a pattern, such as map links, until a time at most `watch_max` away. While it lasts, a message there that matches goes to the addon instead: it isn't answered, isn't sent to the model, and isn't kept in history, even as group context; so does an edit of it later. The addon may react to it, so people see it was counted. A pattern that would match ordinary chat ("lol", "see you at 5", a news link, …) is refused, so a watch can't become a feed of everything said; at most 8 run in a chat at once. While a watch lasts, a reply to the command's pictures that asks the bot gets the addon's set answer (GeoGuess's "No hints during a round 😉"), not the model's. A reply watch (`"replies": true`) takes instead only replies to the addon's own messages in the chat while it lasts, the command's answer and its posts, that ask the bot, such as a quiz's free-text answers; its pattern, if it has one, must match them too, and isn't held to the ordinary-chat rule, since such a reply is meant for the addon. - **Model.** With `model`, an addon may ask the bot's model for text, through MCP's standard sampling request (`sampling/createMessage`): it sends the prompt, and the bot runs it on its own model, with its own key, and sends back the answer. The addon needs no key or provider of its own. The bot offers this only to an addon with `model`, and only while it has a model; MCP suggests a person approve each request, and here the `model` setting is that approval. Each request names the chat it is for, one the addon may post in now, and is charged to that chat's `DAILY_BUDGET`: one over its budget is refused, and so is one past `per_hour`. A request is text only, at most 16 messages and 32 KB, with one in flight per addon at a time. Only its outcome, time, size, tokens and cost are logged, never the prompt or the answer. -- **Outbox.** An addon posts when it likes by queueing posts, reactions and the end of a watch in its outbox, an MCP resource the bot subscribes to (`signalbot://outbox`), and saying it changed; the bot reads it at once. It may post or react only in a chat where it was used, by a command or a watch, in the last 24 hours, and only within `rate`. Its posts go through the chat's queue like any message, never more than one at a time, and history keeps them as the bot's, labelled with the addon's name (`[GeoGuess] …`), so what an addon writes never poses as a person. -- **Settings.** An addon has no `env` block. It gets `PATH`, `HOME`, the bot's time zone (`TZ`) and proxy settings (`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, and `SSL_CERT_FILE` or `SSL_CERT_DIR` for a custom CA) if set, and every variable in the bot's environment (`/etc/signalbot.env`) that starts with its server's name in capitals, anything but letters and digits as `_`, then `_`: the server `geo` gets `GEO_STATE_DIR`, `GEO_MAPILLARY_TOKEN` and so on, and never the bot's own keys. A name whose prefix starts one of the bot's settings (such as `model`, `signal` or `mcp`) is a config error. If an addon keeps files, give it a directory under its prefix and create it, writable by the bot's user. +- **Outbox.** An addon posts when it likes by queueing posts, reactions and the end of a watch in its outbox, an MCP resource the bot subscribes to (`signalbot://outbox`), and saying it changed; the bot reads it at once. It may post or react only in a chat where it was used, by a command or a watch, in the last 24 hours, and only within `rate`. Its posts go through the chat's queue like any message, never more than one at a time, and history keeps them as the bot's, labelled with the addon's name (`[GeoGuess] …`), so what an addon writes never poses as a person. A post can be a reply to one of the addon's earlier posts in the same chat, named by that post's ID (`replyTo`), so a quiz can answer a question under it; the Go package's `QueueIDs` gives the IDs. The bot remembers the IDs of the addon's last 256 post ops for 24 hours (a merged post uses one for each op); a reply to one it doesn't know, or in another chat, goes as an ordinary post. A reply is always a message of its own, never merged with the addon's other posts. On Signal it quotes the post; on Telegram it replies to it, and goes anyway if the post was deleted. +- **Settings.** An addon has no `env` block. It gets `PATH`, `HOME`, the bot's time zone (`TZ`) and proxy settings (`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, and `SSL_CERT_FILE` or `SSL_CERT_DIR` for a custom CA) if set, and every variable in the bot's environment (`/etc/signalbot.env`) that starts with its server's name in capitals, anything but letters and digits as `_`, then `_`: the server `geo` gets `GEO_STATE_DIR`, `GEO_MAPILLARY_TOKEN` and so on, and never the bot's own keys. A name whose prefix starts one of the bot's settings (such as `model`, `signal` or `mcp`) is a config error. An addon that keeps files takes its directory from `<PREFIX>STATE_DIR` (`GEO_STATE_DIR`) and creates it itself, mode 0700. Unless the bot's environment sets it, the bot sets it to `addons/<server name>` in the bot's state directory (`/var/lib/private/signalbot/addons/geo`, or `/data/addons/geo` in Docker), so an addon's files are kept with the bot's; it creates nothing there itself. With `STATE_DIRECTORY` unset, or a server name that isn't only letters, digits, `.`, `_` and `-` (up to 64, not starting with `.`), there is no default, and the addon falls back on its own. - **Logs.** The bot logs an addon's commands, calls and drops by name, outcome, time and size, never what was said. An addon's stderr is counted ("addon geo wrote 3 lines (210 bytes) to stderr", at most once a minute and once more when it exits), never logged, since it may echo a message. To debug an addon, run it on its own with stderr going to your own file. -- **State.** The bot keeps an addon's watches, the messages they took, the chats it may post in and how far it has read its outbox in `mcp.json`, so a restart of either doesn't lose a round. See [PRIVACY.md](../PRIVACY.md#addons). +- **State.** The bot keeps an addon's watches, the messages they took, the chats it may post in, how far it has read its outbox and the posts a later one may reply to in `mcp.json`, so a restart of either doesn't lose a round. See [PRIVACY.md](../PRIVACY.md#addons). - **Docker.** The image has no shell or runtimes, so an addon must be a static binary (`CGO_ENABLED=0 go build`), mounted read-only at the same path, such as `- /opt/signalbot-addons:/opt/signalbot-addons:ro` in `compose.yaml`, so its `command` is the same under Docker and systemd (whose `ProtectSystem=strict` leaves `/opt` readable). The state directory must be writable by user 65532 for `mcp.json`, and so must any directory the addon keeps files in. Addons share the container's or unit's memory and process limits, so raise `mem_limit` or `MemoryMax` to suit; `GOMEMLIMIT` isn't passed on, so a Go addon takes its limit from its own setting (GeoGuess: `GEO_MEMLIMIT`). --- diff --git a/internal/bot/answer.go b/internal/bot/answer.go index eeda4ec..357740e 100644 --- a/internal/bot/answer.go +++ b/internal/bot/answer.go @@ -75,7 +75,7 @@ func (b *Bot) respond(msg feature.Message, act feature.Action, text string, refs return case act.Answer != "" || len(act.Pictures) > 0: text, _ := captioned(act.Answer, act.Pictures) - sent := b.net.Send(msg.Chat, text, act.Pictures, b.chats.Names(msg.Chat.Key())) + sent := b.net.Send(msg.Chat, text, act.Pictures, b.chats.Names(msg.Chat.Key()), 0) if act.OnSent != nil { act.OnSent(sent, len(sent) == 0) } @@ -90,7 +90,7 @@ func (b *Bot) respond(msg feature.Message, act feature.Action, text string, refs if over, left := b.budget.over(key); over { if b.budget.markTold(key) { // once a day; then a ⏳ until midnight logx.Warnf("a chat reached its daily budget; it is answered again at midnight") - b.net.Send(msg.Chat, limitNotice(left), nil, b.chats.Names(key)) + b.net.Send(msg.Chat, limitNotice(left), nil, b.chats.Names(key), 0) } else if msg.Timestamp != 0 { // a scheduled post can't be reacted to b.net.React(msg.Chat, msg, waiting) } @@ -109,7 +109,7 @@ func (b *Bot) respond(msg feature.Message, act feature.Action, text string, refs for { if act.ToolChoice != "" && !b.callsTools.Load() { stop() - b.net.Send(msg.Chat, noTools, nil, b.chats.Names(key)) + b.net.Send(msg.Chat, noTools, nil, b.chats.Names(key), 0) return } if t = b.buildTurn(msg, text); t.empty(msg) { @@ -149,7 +149,7 @@ func (b *Bot) respond(msg feature.Message, act feature.Action, text string, refs if errors.Is(err, model.ErrTooManyRounds) { answer = tooManyRounds } - b.net.Send(msg.Chat, answer, nil, b.chats.Names(key)) + b.net.Send(msg.Chat, answer, nil, b.chats.Names(key), 0) return } b.followUp(key, offered, msg.Text, reply.ToolsUsed) diff --git a/internal/bot/bot.go b/internal/bot/bot.go index 5b399cb..4951db4 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -38,8 +38,11 @@ type Network interface { WaitID(ctx context.Context) string // Send posts a reply, split as the network needs, and returns the // timestamps of the messages sent, which name them for a later delete; - // a send that fails returns no timestamps. - Send(chat feature.Chat, text string, pics []feature.Picture, known map[string]string) (sent []int64) + // a send that fails returns no timestamps. If replyTo isn't 0, the + // first message sent replies to the bot's own message in chat that an + // earlier Send returned it for; one the network can't find is sent + // without it. + Send(chat feature.Chat, text string, pics []feature.Picture, known map[string]string, replyTo int64) (sent []int64) // React puts emoji on msg in chat, as a reaction from the bot. React(chat feature.Chat, msg feature.Message, emoji string) Typing(chat feature.Chat) (stop func()) @@ -242,7 +245,7 @@ func (b *Bot) pending() chats.Ref { // and returns Send's timestamps. History is kept first so a message // arriving while the send is out lands after the turn, not before it. func (b *Bot) sendKept(key string, p chats.Ref, chat feature.Chat, text string, pics []feature.Picture, known map[string]string) []int64 { - sent := b.net.Send(chat, text, pics, known) + sent := b.net.Send(chat, text, pics, known, 0) b.chats.Retag(key, p.ID, botRefs(sent)) return sent } diff --git a/internal/bot/fakes_test.go b/internal/bot/fakes_test.go index ca79be7..3eec716 100644 --- a/internal/bot/fakes_test.go +++ b/internal/bot/fakes_test.go @@ -65,6 +65,7 @@ type sent struct { text string images []feature.Picture known map[string]string + reply int64 } func (n *fakeNet) Watch(w Watch) { @@ -90,11 +91,11 @@ func (n *fakeNet) WaitID(ctx context.Context) string { // Send returns one timestamp per call, counting up from 5000, or none // while fail is set. -func (n *fakeNet) Send(chat feature.Chat, text string, images []feature.Picture, known map[string]string) []int64 { +func (n *fakeNet) Send(chat feature.Chat, text string, images []feature.Picture, known map[string]string, replyTo int64) []int64 { if n.fail.Load() { return nil } - n.sent <- sent{chat, text, images, known} + n.sent <- sent{chat, text, images, known, replyTo} return []int64{5000 + n.sends.Add(1)} } diff --git a/internal/bot/host.go b/internal/bot/host.go index e6d0a7b..cd185e9 100644 --- a/internal/bot/host.go +++ b/internal/bot/host.go @@ -189,13 +189,13 @@ func (b *Bot) say(p feature.Post) { key := p.Chat.Key() text, kept := captioned(p.Text, p.Pictures) if p.Label == "" || b.ai == nil { // with no model, nothing would read it - sent := b.net.Send(p.Chat, text, p.Pictures, b.chats.Names(key)) + sent := b.net.Send(p.Chat, text, p.Pictures, b.chats.Names(key), p.ReplyTo) p.OnSent(sent, len(sent) == 0) return } ref := b.pending() b.chats.Add(key, b.now(), 0, chats.Entry{Role: "assistant", Content: txt.Clamp("["+p.Label+"] "+kept, maxPostKept), Refs: []chats.Ref{ref}}) - sent := b.net.Send(p.Chat, text, p.Pictures, b.chats.Names(key)) + sent := b.net.Send(p.Chat, text, p.Pictures, b.chats.Names(key), p.ReplyTo) if len(sent) == 0 { b.chats.Withdraw(key, ref.ID) // the chat never saw it, and it may be posted again } else { @@ -273,7 +273,7 @@ func (b *Bot) event(e feature.Event) { for _, p := range people { chats.Claim(known, p.Name, p.ID) } - b.net.Send(e.Chat, reply, nil, known) + b.net.Send(e.Chat, reply, nil, known, 0) return } } diff --git a/internal/bot/host_test.go b/internal/bot/host_test.go index b5b4b37..de103d8 100644 --- a/internal/bot/host_test.go +++ b/internal/bot/host_test.go @@ -755,6 +755,21 @@ func TestPost(t *testing.T) { r, _ = h.ask(dm("anything else?")) equal(t, "DM history", contents(r), []string{"user: anything else?"}) + // A reply to an earlier post reaches the network, labelled or not; a + // plain post has none. + for _, p := range []feature.Post{{Chat: group, Label: "Label", Text: "the answer", ReplyTo: 5002}, {Chat: group, Text: "a reply", ReplyTo: 7}} { + post(p) + if s := h.nextSend(); s.reply != p.ReplyTo || s.text != p.Text { + t.Fatalf("sent %+v", s) + } + next() + } + post(feature.Post{Chat: group, Text: "plain"}) + if s := h.nextSend(); s.reply != 0 { + t.Fatalf("sent %+v", s) + } + next() + for _, chat := range []feature.Chat{{User: strangerID}, {GroupID: "other"}} { post(feature.Post{Chat: chat, Label: "Label", Text: "never sent"}) if d := next(); !d.dropped || d.sent != nil { diff --git a/internal/feature/feature.go b/internal/feature/feature.go index 3fb5e9a..b86be68 100644 --- a/internal/feature/feature.go +++ b/internal/feature/feature.go @@ -220,6 +220,7 @@ type Post struct { Text string // Markdown, as written; @Name is linked to the chat's known names Pictures []Picture // sent with Text; captions as for a tool's pictures OnSent func(sent []int64, dropped bool) // if set, called once: with the timestamps sent, or dropped + ReplyTo int64 // if set, sent as a reply to the bot's own earlier message in Chat that an OnSent gave this timestamp; sent plainly if the network can't find it } // Group is a group chat. diff --git a/internal/features/mcp/addon.go b/internal/features/mcp/addon.go index 1a0642f..35bec51 100644 --- a/internal/features/mcp/addon.go +++ b/internal/features/mcp/addon.go @@ -11,6 +11,7 @@ import ( "errors" "fmt" "os" + "path/filepath" "regexp" "slices" "strings" @@ -171,21 +172,52 @@ var shared = []string{"TZ", "HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_pr // addonEnv is an addon's whole environment: PATH, HOME, the shared // variables that are set, and the bot's variables that start with prefix. -func addonEnv(prefix string) []string { +// stateDir, if not "", is the addon's <prefix>STATE_DIR unless the bot's +// environment sets one that isn't blank; the addon makes the directory +// itself. +func addonEnv(prefix, stateDir string) []string { env := []string{"PATH=" + os.Getenv("PATH"), "HOME=" + os.Getenv("HOME")} for _, name := range shared { if v, ok := os.LookupEnv(name); ok { env = append(env, name+"="+v) } } + // A blank <prefix>STATE_DIR counts as unset, as the bot's own settings do. + own := strings.TrimSpace(os.Getenv(prefix+"STATE_DIR")) != "" for _, kv := range os.Environ() { - if strings.HasPrefix(kv, prefix) { - env = append(env, kv) + if !strings.HasPrefix(kv, prefix) { + continue } + if !own && stateDir != "" && strings.HasPrefix(kv, prefix+"STATE_DIR=") { + continue + } + env = append(env, kv) + } + if !own && stateDir != "" { + env = append(env, prefix+"STATE_DIR="+stateDir) } return env } +// safeDirName is a server name that can be a directory's name as it is. +var safeDirName = regexp.MustCompile(`^[A-Za-z0-9_-][A-Za-z0-9._-]{0,63}$`) + +// addonStateDir is where an addon server called name keeps its own files by +// default: addons/<name> in the bot's state directory, the first in +// stateDirectory (STATE_DIRECTORY's value), made absolute. It is "" when +// STATE_DIRECTORY isn't set, or the name isn't letters, digits, ., _ and - +// (up to 64, not starting with .), so no name can reach outside addons. +func addonStateDir(stateDirectory, name string) string { + dir, _, _ := strings.Cut(stateDirectory, ":") + if dir == "" || !safeDirName.MatchString(name) { + return "" + } + if abs, err := filepath.Abs(dir); err == nil { + dir = abs + } + return filepath.Join(dir, "addons", name) +} + // saved is the mcp store's document. type saved struct { Secret []byte `json:"secret"` // the key every pseudonym is made from @@ -266,6 +298,7 @@ type addon struct { sending map[string]bool // the IDs of post ops held or in a mailbox failed map[string]failure // post ops dropped before they were sent, by ID waiting map[string][]*outgoing // by chat pseudonym, while a post of its waits in the chat's mailbox: those held to send after it, in turn + posted map[string]posted // the post ops it sent, by ID, for a later post's replyTo } // ref is the message a ref stands for: who sent it, where and when. @@ -289,7 +322,7 @@ func newAddon(server, title string, cfg addonConfig, secret []byte, c conn, bot matches: make(chan match, maxMatches), posts: newLimiter(cfg.Rate), calls: newLimiter(watchRate), asks: hourly(cfg.Model), refs: map[string]ref{}, names: map[string]seen{}, watches: map[string][]*watch{}, claims: map[claimKey]claim{}, leases: map[string]lease{}, tombs: map[string]time.Time{}, done: map[string]bool{}, - sending: map[string]bool{}, failed: map[string]failure{}, waiting: map[string][]*outgoing{}} + sending: map[string]bool{}, failed: map[string]failure{}, waiting: map[string][]*outgoing{}, posted: map[string]posted{}} } // allows reports whether the addon may be used in chat. diff --git a/internal/features/mcp/addon_test.go b/internal/features/mcp/addon_test.go index 662c351..695084d 100644 --- a/internal/features/mcp/addon_test.go +++ b/internal/features/mcp/addon_test.go @@ -308,9 +308,9 @@ func TestAddonLoad(t *testing.T) { } } -// An addon gets PATH, HOME, the time zone and proxy settings, and the -// bot's variables with its prefix, never the bot's own; it is offered -// signalbot's extension in the handshake. +// An addon gets PATH, HOME, the time zone and proxy settings, the bot's +// variables with its prefix, never the bot's own, and its state directory; +// it is offered signalbot's extension in the handshake. func TestAddonEnv(t *testing.T) { t.Setenv("MODEL_API_KEY", "secret-key") t.Setenv("GAME_TOKEN", "t") @@ -319,12 +319,78 @@ func TestAddonEnv(t *testing.T) { t.Setenv(name, "x") } h, _ := startAddon(t, `{"mcpServers":{"game":`+addonServer("addon", `{"dms":true}`, direct)+`}}`) - want := strings.Join(slices.Sorted(slices.Values(append([]string{"GAME_TOKEN", "HOME", "PATH"}, shared...))), ",") + want := strings.Join(slices.Sorted(slices.Values(append([]string{"GAME_STATE_DIR", "GAME_TOKEN", "HOME", "PATH"}, shared...))), ",") if got := h.Message(context.Background(), in(inDM, "/env")); got.Answer != want { t.Fatalf("env %+v", got) } } +// An addon's default state directory is addons/<name> in the bot's first +// state directory, made absolute; none without STATE_DIRECTORY, or for a +// name that isn't safe as a directory's name. +func TestAddonStateDir(t *testing.T) { + wd, err := os.Getwd() + if err != nil { + t.Fatal(err) + } + for _, c := range []struct{ stateDirectory, name, want string }{ + {"/var/lib/signalbot", "quiz", "/var/lib/signalbot/addons/quiz"}, + {"/var/lib/signalbot:/other", "geo.v2", "/var/lib/signalbot/addons/geo.v2"}, + {"/data/", "my-quiz_1", "/data/addons/my-quiz_1"}, + {"state", "quiz", filepath.Join(wd, "state", "addons", "quiz")}, + {"", "quiz", ""}, + {":/other", "quiz", ""}, + {"/data", "", ""}, + {"/data", ".", ""}, + {"/data", "..", ""}, + {"/data", ".hidden", ""}, + {"/data", "a/b", ""}, + {"/data", "../x", ""}, + {"/data", `a\b`, ""}, + {"/data", "a b", ""}, + {"/data", "quiz\x00", ""}, + {"/data", "jeu-é", ""}, + {"/data", strings.Repeat("a", 64), "/data/addons/" + strings.Repeat("a", 64)}, + {"/data", strings.Repeat("a", 65), ""}, + } { + if got := addonStateDir(c.stateDirectory, c.name); got != c.want { + t.Errorf("%q, %q: got %q, want %q", c.stateDirectory, c.name, got, c.want) + } + } +} + +// An addon's STATE_DIR is the default given, unless the bot's environment +// sets its own, which wins; with no default, it gets none. +func TestAddonEnvStateDir(t *testing.T) { + stateDirs := func(env []string) []string { + var out []string + for _, kv := range env { + if strings.HasPrefix(kv, "QUIZ_STATE_DIR=") { + out = append(out, kv) + } + } + return out + } + if got := stateDirs(addonEnv("QUIZ_", "/data/addons/quiz")); !slices.Equal(got, []string{"QUIZ_STATE_DIR=/data/addons/quiz"}) { + t.Errorf("default: %q", got) + } + if got := stateDirs(addonEnv("QUIZ_", "")); len(got) != 0 { + t.Errorf("no state directory: %q", got) + } + for _, blank := range []string{"", " "} { + t.Setenv("QUIZ_STATE_DIR", blank) + if got := stateDirs(addonEnv("QUIZ_", "/data/addons/quiz")); !slices.Equal(got, []string{"QUIZ_STATE_DIR=/data/addons/quiz"}) { + t.Errorf("blank %q: %q", blank, got) + } + } + t.Setenv("QUIZ_STATE_DIR", "/home/alice/quiz") + for _, def := range []string{"/data/addons/quiz", ""} { + if got := stateDirs(addonEnv("QUIZ_", def)); !slices.Equal(got, []string{"QUIZ_STATE_DIR=/home/alice/quiz"}) { + t.Errorf("own value, default %q: %q", def, got) + } + } +} + // What an addon writes to stderr is counted, and what was counted since the // last count logged is logged when it exits. func TestAddonStderr(t *testing.T) { diff --git a/internal/features/mcp/conn.go b/internal/features/mcp/conn.go index 8ca16db..b76d2b1 100644 --- a/internal/features/mcp/conn.go +++ b/internal/features/mcp/conn.go @@ -75,6 +75,7 @@ type stdioConn struct { cfg server redact func(string) string // scrubs names and IDs from its output before it is logged prefix string // an addon's: it gets the bot's variables that start with this, and its stderr is only counted + state string // an addon's default <prefix>STATE_DIR; "" for none updated chan struct{} // an addon's: marked, without waiting, when it says a resource was updated ready func(context.Context, handshake) // an addon's: called each time it has started again and initialized @@ -111,7 +112,7 @@ func (c *stdioConn) start(ctx context.Context) error { // addon's prefixed variables, never the bot's own, which hold the API // key. if c.prefix != "" { - cmd.Env = addonEnv(c.prefix) + cmd.Env = addonEnv(c.prefix, c.state) } else { cmd.Env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + os.Getenv("HOME")} for k, v := range c.cfg.Env { diff --git a/internal/features/mcp/keep.go b/internal/features/mcp/keep.go index 29b36df..7c8f04c 100644 --- a/internal/features/mcp/keep.go +++ b/internal/features/mcp/keep.go @@ -18,13 +18,15 @@ import ( const maxApplied = 1000 // addonState is what is saved of an addon: its live watches, the messages -// they took, the chats it may post in, and how far its outbox was read. +// they took, the chats it may post in, how far its outbox was read, and +// the posts it sent that a later post may reply to. type addonState struct { - Watches []watch `json:"watches,omitempty"` - Claims []claim `json:"claims,omitempty"` - Leases map[string]lease `json:"leases,omitempty"` // by chat pseudonym - Cursor string `json:"cursor,omitempty"` - Applied []string `json:"applied,omitempty"` // oldest first + Watches []watch `json:"watches,omitempty"` + Claims []claim `json:"claims,omitempty"` + Leases map[string]lease `json:"leases,omitempty"` // by chat pseudonym + Cursor string `json:"cursor,omitempty"` + Applied []string `json:"applied,omitempty"` // oldest first + Posted map[string]posted `json:"posted,omitempty"` // by post op ID } // keeper keeps the mcp store's document: the pseudonyms' secret and each @@ -124,6 +126,16 @@ func (a *addon) state() addonState { delete(a.tombs, id) } } + for id, p := range a.posted { + if !now.Before(p.Expires) { + delete(a.posted, id) + continue + } + if s.Posted == nil { + s.Posted = map[string]posted{} + } + s.Posted[id] = p + } // In a fixed order, so an unchanged state saves the same. slices.SortFunc(s.Watches, func(x, y watch) int { return cmp.Or(x.Until.Compare(y.Until), strings.Compare(x.Chat, y.Chat), strings.Compare(x.ID, y.ID)) @@ -159,6 +171,12 @@ func (a *addon) restore(s addonState) { w.key, w.re, w.Sent = l.Chat.Key(), re, w.Sent[max(len(w.Sent)-maxSent, 0):] a.watches[w.key] = append(a.watches[w.key], &w) } + for id, p := range s.Posted { + if now.Before(p.Expires) { + a.posted[id] = p + } + } + a.trimPosted() a.cursor = s.Cursor for _, id := range s.Applied[max(len(s.Applied)-maxApplied, 0):] { a.remember(id) diff --git a/internal/features/mcp/mcp.go b/internal/features/mcp/mcp.go index 464afad..e2b926d 100644 --- a/internal/features/mcp/mcp.go +++ b/internal/features/mcp/mcp.go @@ -377,6 +377,13 @@ func start(ctx context.Context, h feature.Host, path string, servers map[string] taken := map[string]owner{} // the model's names for tools, and whose they are var cmds []string // for the startup line var gates []*gate // opened on return, so no request waits on one for good + stateDirectory := "" // read only with an addon, so MCP without one reads only MCP_CONFIG + for _, s := range servers { + if s.Addon != nil { + stateDirectory = h.Env("STATE_DIRECTORY", "") + break + } + } defer func() { for _, g := range gates { g.open(nil) @@ -396,6 +403,7 @@ func start(ctx context.Context, h feature.Host, path string, servers map[string] s := &stdioConn{name: name, cfg: cfg, bot: self, redact: h.Redact} if cfg.Addon != nil { s.prefix, s.updated = envPrefix(name), make(chan struct{}, 1) + s.state = addonStateDir(stateDirectory, name) } if self.sample { // Sampling is offered from initialize on, so its requests are diff --git a/internal/features/mcp/outbox.go b/internal/features/mcp/outbox.go index a20c7c0..2f7dc4e 100644 --- a/internal/features/mcp/outbox.go +++ b/internal/features/mcp/outbox.go @@ -216,6 +216,8 @@ func (a *addon) apply(o ext.Op) (why string) { case again: case o.Op == "post" && failed && now.Before(f.retry): again, a.missed = true, true // not yet: a later read posts it + case o.Op == "post" && a.waitsToPost(o.ReplyTo): + again, a.missed = true, true // after the post it replies to case o.Op != "post": a.remember(o.ID) } @@ -258,6 +260,13 @@ func (a *addon) apply(o ext.Op) (why string) { return "" } +// waitsToPost reports whether the post op called id was dropped and waits +// to be posted again. a.mu is held. +func (a *addon) waitsToPost(id string) bool { + _, failed := a.failed[id] + return id != "" && failed && !a.sending[id] +} + // post posts o in its chat, if the addon may. One posted again, after it // was dropped, isn't counted against the rate again. func (a *addon) post(o ext.Op, again bool) (why string) { @@ -276,7 +285,7 @@ func (a *addon) post(o ext.Op, again bool) (why string) { b64 = append(b64, im.Data) } out := &outgoing{Post: feature.Post{Chat: l.Chat, Label: a.title, Text: txt.Clamp(a.fill(l.Chat, strings.TrimSpace(o.Text)), maxAnswer), Pictures: a.pictures(b64)}, - ops: []string{o.ID}} + ops: []string{o.ID}, replyTo: o.ReplyTo} switch { case out.Text == "" && len(out.Pictures) == 0: return "empty posts" @@ -287,15 +296,22 @@ func (a *addon) post(o ext.Op, again bool) (why string) { return "" } -// outgoing is a post of the addon's, and the ops it carries. +// outgoing is a post of the addon's, the ops it carries, and the ID of +// the post op it replies to, if any. type outgoing struct { feature.Post - ops []string + ops []string + replyTo string } // fits reports whether p can join o in one post: their pictures, and // their texts whole, so a merge never cuts a post that fit on its own. +// A reply joins no other post, and none joins it, so it stays a message +// of its own and a later post a new one. func (o *outgoing) fits(p *outgoing) bool { + if o.replyTo != "" || p.replyTo != "" { + return false + } size := 0 for _, pic := range append(slices.Clone(o.Pictures), p.Pictures...) { size += len(pic.Data) @@ -334,29 +350,98 @@ func (a *addon) send(id string, out *outgoing) { a.mail(id, out) } -// mail puts out in its chat's mailbox. +// mail puts out in its chat's mailbox, as a reply to the post it replies +// to if that was sent in the same chat and is still remembered; otherwise +// as an ordinary post. Posts in a chat are mailed in turn, so a post sent +// before this one is remembered by now. A reply to a post that was dropped +// and waits to be posted again waits too, and is posted after it. func (a *addon) mail(id string, out *outgoing) { p := out.Post + if out.replyTo != "" { + a.mu.Lock() + pending, retry := a.waitsToPost(out.replyTo), a.failed[out.replyTo].retry + if t, ok := a.posted[out.replyTo]; ok && t.Chat == id && a.now().Before(t.Expires) { + p.ReplyTo = t.Sent + } + a.mu.Unlock() + if pending { + a.postpone(out.ops, retry) + a.mailNext(id) + return + } + } p.OnSent = func(sent []int64, dropped bool) { if !dropped { a.replied(p.Chat, sent) + a.rememberPosted(id, out.ops, sent) } a.sent(out.ops, !dropped) - a.mu.Lock() - held := a.waiting[id] - if len(held) == 0 { - delete(a.waiting, id) - } else { - a.waiting[id] = held[1:] - } - a.mu.Unlock() - if len(held) > 0 { - a.mail(id, held[0]) - } + a.mailNext(id) } a.host.Post(p) } +// mailNext mails the next post held for the chat whose pseudonym is id, if +// one is. +func (a *addon) mailNext(id string) { + a.mu.Lock() + held := a.waiting[id] + if len(held) == 0 { + delete(a.waiting, id) + } else { + a.waiting[id] = held[1:] + } + a.mu.Unlock() + if len(held) > 0 { + a.mail(id, held[0]) + } +} + +// posted is a post op the addon sent: the pseudonym of its chat, the first +// of the timestamps it went out in, which a reply names, and until when a +// later post may reply to it. +type posted struct { + Chat string `json:"chat"` + Sent int64 `json:"sent"` + Expires time.Time `json:"expires"` +} + +// How long a post op is remembered for a later post's replyTo, and how +// many are. +const ( + postedLife = 24 * time.Hour + maxPosted = 256 +) + +// rememberPosted records that the post carrying ops went out in the chat whose +// pseudonym is chat, first as sent[0], so a later post may reply to it. +func (a *addon) rememberPosted(chat string, ops []string, sent []int64) { + if len(sent) == 0 { + return + } + until := a.now().Add(postedLife) + a.mu.Lock() + for _, id := range ops { + a.posted[id] = posted{Chat: chat, Sent: sent[0], Expires: until} + } + a.trimPosted() + a.mu.Unlock() +} + +// trimPosted forgets the posts that expire soonest past maxPosted. a.mu is +// held. +func (a *addon) trimPosted() { + if len(a.posted) <= maxPosted { + return + } + ids := slices.SortedFunc(maps.Keys(a.posted), func(x, y string) int { + return cmp.Or(a.posted[x].Expires.Compare(a.posted[y].Expires), strings.Compare(x, y)) + }) + for _, id := range ids[:len(ids)-maxPosted] { + delete(a.posted, id) + } +} + // sent records that the post carrying ops was sent, or dropped before it // was: a dropped one is read and posted again later, until it has been // tried maxPostTries times. @@ -392,10 +477,34 @@ func (a *addon) sent(ops []string, ok bool) { time.AfterFunc(retry, a.poke) } if settled { - select { - case a.settled <- struct{}{}: - default: - } + a.signalSettled() + } +} + +// postpone puts the post carrying ops back, to be read and posted again +// from until, without counting a try: the post it replies to wasn't sent +// yet, and is posted again then. +func (a *addon) postpone(ops []string, until time.Time) { + a.mu.Lock() + for _, id := range ops { + delete(a.sending, id) + a.failed[id] = failure{a.failed[id].tries, until} + } + a.missed = true + settled := len(a.sending) == 0 + a.mu.Unlock() + a.changed() + if settled { + a.signalSettled() + } +} + +// signalSettled tells a read waiting for its posts that none is being +// sent. +func (a *addon) signalSettled() { + select { + case a.settled <- struct{}{}: + default: } } diff --git a/internal/features/mcp/watch_test.go b/internal/features/mcp/watch_test.go index 630ead0..62307fb 100644 --- a/internal/features/mcp/watch_test.go +++ b/internal/features/mcp/watch_test.go @@ -3,6 +3,7 @@ package mcp import ( "bufio" "bytes" + "cmp" "context" "encoding/json" "fmt" @@ -504,12 +505,12 @@ func TestWatchRestarts(t *testing.T) { // Posts go to a chat the addon has a lease in, one waiting at a time, the // rest held and merged; one dropped before it was sent is posted again; an // op read again is applied once, even from the start of an unknown cursor; -// reactions go to known messages. +// reactions go to known messages; a reply goes as one. func TestOutbox(t *testing.T) { d := retryDelay t.Cleanup(func() { retryDelay = d }) // after the addon stops retryDelay = 50 * time.Millisecond - h, log := startGame(t, gameConfig(""), t.TempDir()) + h, log := startGame(t, gameConfig(`,"rate":{"per_minute":600,"burst":50}`), t.TempDir()) ctx := context.Background() c := chatID(t, h, inA) // a lease, and a ref post := func(id, text string) map[string]any { @@ -571,6 +572,15 @@ func TestOutbox(t *testing.T) { if len(h.Posts()) != 5 || strings.Contains(log.String(), "hello") { t.Fatalf("posts %d, log %q", len(h.Posts()), log.String()) } + + // A reply to the first post, which went out at 1. + reply := post("9", "a reply") + reply["replyTo"] = "1" + queue(t, h, 1, reply) + eventually(t, "the reply", func() bool { return len(h.Posts()) == 6 }) + if p := h.Posts()[5]; p.Text != "a reply" || p.ReplyTo != 1 { + t.Fatalf("reply %+v", p) + } } // A post goes as a merged post only while their pictures fit in one; the @@ -664,6 +674,167 @@ func TestOutboxMergeKeepsTexts(t *testing.T) { } } +// A post with replyTo is sent as a reply to the post op it names, if that +// was sent in the same chat in the last 24 hours, else plainly; it is never +// merged with another post, either way. What was sent is kept over a +// restart, the last maxPosted of it. +func TestOutboxReplies(t *testing.T) { + cfg := everything + cfg.Rate = rateConfig{6000, 1000} + a, now := unitAddon(cfg) + h := featuretest.New() + a.host = h + a.lease(inA) + a.lease(inB) + idA, idB := a.chatID(inA), a.chatID(inB) + n := 0 + post := func(chat, text, replyTo string) ext.Op { + n++ + return ext.Op{ID: strconv.Itoa(n), Op: "post", Chat: chat, Text: text, ReplyTo: replyTo} + } + apply := func(ops ...ext.Op) { + t.Helper() + for _, o := range ops { + if why := a.apply(o); why != "" { + t.Fatalf("%s: %s", o.ID, why) + } + } + } + sent := 0 + // next is the next post mailed, said to be sent at ts and ts+1. + next := func(ts int64) feature.Post { + t.Helper() + if len(h.Posts()) <= sent { + t.Fatalf("no post %d", sent+1) + } + p := h.Posts()[sent] + sent++ + p.OnSent([]int64{ts, ts + 1}, false) + return p + } + expect := func(ts int64, text string, replyTo int64) { + t.Helper() + if p := next(ts); p.Text != text || p.ReplyTo != replyTo { + t.Fatalf("post %q replying to %d; want %q replying to %d", p.Text, p.ReplyTo, text, replyTo) + } + } + + question := post(idA, "What is the capital of France?", "") + apply(question) + expect(100, question.Text, 0) + // Held behind a waiting post: a reply isn't merged into the post held + // before it, nor a later post into the reply. + apply(post(idA, "Waiting", ""), post(idA, "Held", ""), post(idA, "It was Paris.", question.ID), post(idA, "Next question", "")) + expect(200, "Waiting", 0) + expect(300, "Held", 0) + expect(400, "It was Paris.", 100) + expect(500, "Next question", 0) + if len(h.Posts()) != sent { + t.Fatalf("%d posts", len(h.Posts())) + } + // An op the bot doesn't know, or one sent in another chat: plainly. + apply(post(idA, "unknown", "nope")) + expect(600, "unknown", 0) + apply(post(idB, "elsewhere", question.ID)) + expect(700, "elsewhere", 0) + + // After a restart, as saved. + data, err := json.Marshal(a.state()) + if err != nil { + t.Fatal(err) + } + var st addonState + if err := json.Unmarshal(data, &st); err != nil { + t.Fatal(err) + } + if p := st.Posted[question.ID]; p.Chat != idA || p.Sent != 100 { + t.Fatalf("saved %+v", st.Posted) + } + a, _ = unitAddon(cfg) + a.now = func() time.Time { return *now } + a.host = h + a.restore(st) + apply(post(idA, "Paris, again.", question.ID)) + expect(800, "Paris, again.", 100) + + // 24 hours on, forgotten. + *now = now.Add(postedLife) + a.lease(inA) + apply(post(idA, "Too late", question.ID)) + if len(a.state().Posted) != 0 { + t.Fatalf("kept %+v", a.state().Posted) + } + expect(900, "Too late", 0) + + // Only the last maxPosted are kept, and restored. + first := "" + for i := range maxPosted + 3 { + o := post(idA, "post", "") + first = cmp.Or(first, o.ID) + apply(o) + next(int64(1000 + i)) + *now = now.Add(time.Second) + } + st = a.state() + if len(st.Posted) != maxPosted || st.Posted[first].Sent != 0 || st.Posted[strconv.Itoa(n)].Sent != int64(1000+maxPosted+2) { + t.Fatalf("%d kept", len(st.Posted)) + } + for i := range 10 { + st.Posted["extra"+strconv.Itoa(i)] = posted{Chat: idA, Sent: 1, Expires: now.Add(postedLife + time.Duration(i)*time.Second)} + } + a.restore(st) + if len(a.posted) != maxPosted || a.posted["extra0"].Sent != 1 || a.posted[strconv.Itoa(n-maxPosted+10)].Sent != 0 || a.posted[strconv.Itoa(n-maxPosted+11)].Sent == 0 { + t.Fatalf("%d restored", len(a.posted)) + } +} + +// A reply whose post was dropped before it was sent waits for it, without +// counting a try, and is sent after it, as a reply to it. +func TestOutboxReplyWaitsForDropped(t *testing.T) { + a, now := unitAddon(everything) + h := featuretest.New() + a.host = h + a.lease(inA) + id := a.chatID(inA) + waiting := ext.Op{ID: "w", Op: "post", Chat: id, Text: "Waiting"} + question := ext.Op{ID: "q", Op: "post", Chat: id, Text: "Question"} + answer := ext.Op{ID: "r", Op: "post", Chat: id, Text: "Answer", ReplyTo: "q"} + read := func() { + t.Helper() + for _, o := range []ext.Op{waiting, question, answer} { + if why := a.apply(o); why != "" { + t.Fatalf("%s: %s", o.ID, why) + } + } + } + read() + h.Posts()[0].OnSent([]int64{100}, false) + h.Posts()[1].OnSent(nil, true) + if len(h.Posts()) != 2 { + t.Fatalf("reply sent before its post: %q", h.Posts()[2].Text) + } + read() // too soon: neither is posted + if len(h.Posts()) != 2 { + t.Fatalf("%d posts", len(h.Posts())) + } + *now = now.Add(retryDelay) + read() + if len(h.Posts()) != 3 || h.Posts()[2].Text != "Question" { + t.Fatalf("%d posts", len(h.Posts())) + } + h.Posts()[2].OnSent([]int64{200}, false) + if len(h.Posts()) != 4 || h.Posts()[3].Text != "Answer" || h.Posts()[3].ReplyTo != 200 { + t.Fatalf("%d posts", len(h.Posts())) + } + if f := a.failed["r"]; f.tries != 0 { + t.Fatalf("reply tried %d times", f.tries) + } + h.Posts()[3].OnSent([]int64{201}, false) + if len(a.failed) != 0 || len(a.sending) != 0 { + t.Fatalf("failed %v, sending %v", a.failed, a.sending) + } +} + // One reader per addon: a burst of news never makes two reads at once, a // read misses nothing that came during it, and news the addon never sent is // read with the next. diff --git a/internal/signal/client_test.go b/internal/signal/client_test.go index 2f7aa80..6c6dff8 100644 --- a/internal/signal/client_test.go +++ b/internal/signal/client_test.go @@ -253,7 +253,7 @@ func TestStalledWriteReconnects(t *testing.T) { } sent := make(chan error) go func() { - _, err := c.send(feature.Chat{User: aliceID}, strings.Repeat("x", 8<<20), nil, nil, nil) + _, err := c.send(feature.Chat{User: aliceID}, strings.Repeat("x", 8<<20), nil, nil, nil, 0) sent <- err }() receive(srv, `{"sourceUuid":"`+aliceID+`","dataMessage":{"message":"hi"}}`) @@ -270,7 +270,8 @@ func TestStalledWriteReconnects(t *testing.T) { } // A reply loses the bot's own @name, links @Name to the names it is given, -// and carries its images, each named and encoded for signal-cli. +// and carries its images, each named and encoded for signal-cli; a reply +// quotes the bot's own message. func TestSendAndTyping(t *testing.T) { captureLogs(t) f := newFake(t) @@ -279,10 +280,10 @@ func TestSendAndTyping(t *testing.T) { run(t, c, f) group, dm := feature.Chat{GroupID: groupID}, feature.Chat{User: aliceID} png := []byte("\x89PNG\r\n\x1a\n") - if ts := c.Send(group, "@signalbot hi @Alice", []feature.Picture{{Data: png, Name: "NVDA vs AMD, 1 month"}, {Data: png}}, map[string]string{"alice": aliceID}); !slices.Equal(ts, []int64{1001}) { + if ts := c.Send(group, "@signalbot hi @Alice", []feature.Picture{{Data: png, Name: "NVDA vs AMD, 1 month"}, {Data: png}}, map[string]string{"alice": aliceID}, 0); !slices.Equal(ts, []int64{1001}) { t.Fatalf("sent %v", ts) } - c.Send(dm, "plain @Alice", nil, nil) + c.Send(dm, "plain @Alice", nil, nil, 0) eventually(t, "two sends", func() bool { return len(f.calls("send")) == 2 }) s := f.calls("send") if s[0]["groupId"] != groupID || s[0]["message"] != "hi @Alice" || fmt.Sprint(s[0]["mention"]) != "[3:6:"+aliceID+"]" || @@ -292,6 +293,15 @@ func TestSendAndTyping(t *testing.T) { if fmt.Sprint(s[1]["recipient"]) != "["+aliceID+"]" || s[1]["mention"] != nil || s[1]["attachments"] != nil { t.Errorf("DM send %v", s[1]) } + if s[0]["quoteTimestamp"] != nil || s[1]["quoteAuthor"] != nil { + t.Errorf("a plain send quotes: %v", s) + } + // A reply quotes the bot's own message by its timestamp. + c.Send(group, "the answer", nil, nil, 1001) + eventually(t, "the reply", func() bool { return len(f.calls("send")) == 3 }) + if r := f.calls("send")[2]; r["quoteTimestamp"] != float64(1001) || r["quoteAuthor"] != botID || r["message"] != "the answer" || r["groupId"] != groupID { + t.Errorf("reply send %v", r) + } stop := c.Typing(dm) eventually(t, "typing repeated", func() bool { return len(f.calls("sendTyping")) >= 3 }) @@ -465,11 +475,11 @@ func TestSendResults(t *testing.T) { f := newFake(t) c := newClient(f.sock, nil, nil) run(t, c, f) - if ts := c.Send(feature.Chat{User: aliceID}, strings.Repeat("word ", 500), nil, nil); len(ts) != 1 { + if ts := c.Send(feature.Chat{User: aliceID}, strings.Repeat("word ", 500), nil, nil, 0); len(ts) != 1 { t.Fatalf("a long reply returned %v", ts) } f.set("send", `{"timestamp":77,"results":[{"type":"NETWORK_FAILURE"}]}`) - if ts := c.Send(feature.Chat{User: aliceID}, "hi", nil, nil); !slices.Equal(ts, []int64{77}) { + if ts := c.Send(feature.Chat{User: aliceID}, "hi", nil, nil, 0); !slices.Equal(ts, []int64{77}) { t.Fatalf("returned %v", ts) } if !strings.Contains(logs.String(), "signal-cli send not delivered: NETWORK_FAILURE") { @@ -479,7 +489,7 @@ func TestSendResults(t *testing.T) { func TestCallsFailWhenNotConnected(t *testing.T) { c := newClient("x", nil, nil) - if _, err := c.send(feature.Chat{User: aliceID}, "hi", nil, nil, nil); err == nil { + if _, err := c.send(feature.Chat{User: aliceID}, "hi", nil, nil, nil, 0); err == nil { t.Error("send while not connected") } if _, err := c.groups(context.Background(), aliceID); err == nil { diff --git a/internal/signal/markdown_test.go b/internal/signal/markdown_test.go index 1717a7f..afa6844 100644 --- a/internal/signal/markdown_test.go +++ b/internal/signal/markdown_test.go @@ -84,7 +84,7 @@ func TestSendStyles(t *testing.T) { f := newFake(t) c := newClient(f.sock, nil, nil) run(t, c, f) - c.Send(feature.Chat{User: aliceID}, "**\U0001F389 big** news, @Alice: see `x`", nil, map[string]string{"alice": "u-a"}) + c.Send(feature.Chat{User: aliceID}, "**\U0001F389 big** news, @Alice: see `x`", nil, map[string]string{"alice": "u-a"}, 0) eventually(t, "a send", func() bool { return len(f.calls("send")) == 1 }) s := f.calls("send")[0] if s["message"] != "\U0001F389 big news, @Alice: see x" { @@ -96,7 +96,7 @@ func TestSendStyles(t *testing.T) { if got := fmt.Sprint(s["mention"]); got != "[13:6:u-a]" { t.Errorf("mentions %v", got) } - c.Send(feature.Chat{User: aliceID}, "plain", nil, nil) + c.Send(feature.Chat{User: aliceID}, "plain", nil, nil, 0) eventually(t, "a second send", func() bool { return len(f.calls("send")) == 2 }) if _, ok := f.calls("send")[1]["textStyle"]; ok { t.Errorf("styles on plain text") diff --git a/internal/signal/send.go b/internal/signal/send.go index 03d407a..3154982 100644 --- a/internal/signal/send.go +++ b/internal/signal/send.go @@ -34,9 +34,10 @@ func (c *Client) Prompt() string { // Send posts text to chat as one message, as prepare makes it, with each // @Name in known (lowercased name to ID), and in a group the bot's own // @name, made a real mention, and with the images, each named after its -// Name or else image_<local time>. A failure is logged, as is a message -// signal-cli says it could not deliver. -func (c *Client) Send(chat feature.Chat, text string, pics []feature.Picture, known map[string]string) (sent []int64) { +// Name or else image_<local time>, quoting the bot's own message sent at +// replyTo if it isn't 0. A failure is logged, as is a message signal-cli +// says it could not deliver. +func (c *Client) Send(chat feature.Chat, text string, pics []feature.Picture, known map[string]string, replyTo int64) (sent []int64) { if n := utf8.RuneCountInString(text); n > maxReply { logx.Warnf("reply truncated from %d chars", n) } @@ -70,7 +71,7 @@ func (c *Client) Send(chat feature.Chat, text string, pics []feature.Picture, kn return nil } body := string(msg.Runes) - ts, err := c.send(chat, body, mentions(body, known), textStyles(msg), attachments) + ts, err := c.send(chat, body, mentions(body, known), textStyles(msg), attachments, replyTo) if err != nil { logx.Errorf("send failed: %v", err) return nil @@ -103,10 +104,17 @@ func fileName(name string) string { // send posts one message and returns its timestamp, which names it on // Signal (for a delete from a linked device), waiting up to a minute for -// signal-cli; a recipient it wasn't delivered to is logged. -func (c *Client) send(chat feature.Chat, text string, mentions, styles, attachments []string) (int64, error) { +// signal-cli; a recipient it wasn't delivered to is logged. With quote, it +// replies to the bot's own message sent then: a quote names its message by +// author and timestamp alone, and signal-cli sends it whether or not it +// still has the message, so a recipient whose app doesn't shows the quote +// as not found, and the reply still goes. +func (c *Client) send(chat feature.Chat, text string, mentions, styles, attachments []string, quote int64) (int64, error) { p := target(chat) p["message"] = text + if self := c.self(); quote != 0 && self != "" { + p["quoteTimestamp"], p["quoteAuthor"] = quote, self + } if len(mentions) > 0 { p["mention"] = mentions } diff --git a/internal/signal/send_test.go b/internal/signal/send_test.go index 0286c02..a7f4c1d 100644 --- a/internal/signal/send_test.go +++ b/internal/signal/send_test.go @@ -17,7 +17,7 @@ func TestSendOneMessageAndCaps(t *testing.T) { c := newClient(f.sock, nil, nil) run(t, c, f) dm := feature.Chat{User: aliceID} - c.Send(dm, strings.Repeat("z ", 6000), []feature.Picture{{Data: []byte("PNG")}}, nil) + c.Send(dm, strings.Repeat("z ", 6000), []feature.Picture{{Data: []byte("PNG")}}, nil, 0) eventually(t, "a send", func() bool { return len(f.calls("send")) == 1 }) if s := f.calls("send")[0]; s["attachments"] == nil || len([]rune(s["message"].(string))) != maxReply || !strings.HasSuffix(s["message"].(string), "[…truncated]") { t.Errorf("send %d chars, attachments %v", len([]rune(fmt.Sprint(s["message"]))), s["attachments"] != nil) @@ -25,13 +25,13 @@ func TestSendOneMessageAndCaps(t *testing.T) { if !strings.Contains(logs.String(), "reply truncated from 12000 chars") { t.Errorf("logs %q", logs) } - c.Send(dm, " ", nil, nil) - c.Send(dm, "", []feature.Picture{{Data: []byte("PNG")}}, nil) + c.Send(dm, " ", nil, nil, 0) + c.Send(dm, "", []feature.Picture{{Data: []byte("PNG")}}, nil, 0) eventually(t, "the pictures alone", func() bool { return len(f.calls("send")) == 2 }) if s := f.calls("send")[1]; s["message"] != "" || s["attachments"] == nil { t.Errorf("pictures sent as %v", s) } - newClient("x", nil, nil).Send(dm, "secret words", nil, nil) + newClient("x", nil, nil).Send(dm, "secret words", nil, nil, 0) if out := logs.String(); !strings.Contains(out, "empty reply, nothing sent") || !strings.Contains(out, "send failed: not connected") || strings.Contains(out, "secret") { t.Errorf("logs %q", out) } diff --git a/internal/telegram/send.go b/internal/telegram/send.go index 2116b54..81c7dfe 100644 --- a/internal/telegram/send.go +++ b/internal/telegram/send.go @@ -48,9 +48,10 @@ type sentMsg struct { // Send posts a reply to chat: its Markdown as Telegram's entities, a link // under its own text, each @Name in known (lowercased name to ID) a text // mention, split at Telegram's limit, the pictures first with the reply as -// their caption when it fits. It returns the IDs of the messages sent. A -// failure is logged. -func (c *Client) Send(ch feature.Chat, text string, pics []feature.Picture, known map[string]string) (sent []int64) { +// their caption when it fits, the first message a reply to the bot's own +// message replyTo if it isn't 0 (sent anyway if that message is gone). It +// returns the IDs of the messages sent. A failure is logged. +func (c *Client) Send(ch feature.Chat, text string, pics []feature.Picture, known map[string]string, replyTo int64) (sent []int64) { if n := utf8.RuneCountInString(text); n > maxReply { logx.Warnf("reply truncated from %d chars", n) } @@ -65,8 +66,8 @@ func (c *Client) Send(ch feature.Chat, text string, pics []feature.Picture, know } ctx, cancel := context.WithTimeout(context.Background(), time.Minute) defer cancel() - note := func(msgID int64) { - sent = append(sent, msgID) + note := func(msgID int64) { // only the first message sent replies + sent, replyTo = append(sent, msgID), 0 c.noteSent(c.dest(ch).chat, msgID) // at a group's new ID, if the send found it moved } if len(pics) > 0 { @@ -75,7 +76,7 @@ func (c *Client) Send(ch feature.Chat, text string, pics []feature.Picture, know c := t caption = &c } - ids, err := c.sendPhotos(ctx, ch, pics, caption, known) + ids, err := c.sendPhotos(ctx, ch, pics, caption, known, replyTo) if err != nil { logx.Errorf("send failed: pictures: %v", err) // the text still goes } else if caption != nil { @@ -94,6 +95,9 @@ func (c *Client) Send(ch feature.Chat, text string, pics []feature.Picture, know var m sentMsg d := c.dest(ch) params := d.params(map[string]any{"text": string(p.Runes), "entities": entities(p, known)}) + if replyTo != 0 { + params["reply_parameters"] = replyParams(replyTo) + } send := func() error { return c.call(ctx, "sendMessage", params, &m) } move := func(to string) { params["chat_id"] = to } err := c.retrying(ctx, d.chat, move, send) @@ -110,6 +114,12 @@ func (c *Client) Send(ch feature.Chat, text string, pics []feature.Picture, know return sent } +// replyParams are Telegram's reply_parameters for a reply to the message +// id in the same chat, sent without the reply if that message is gone. +func replyParams(id int64) map[string]any { + return map[string]any{"message_id": id, "allow_sending_without_reply": true} +} + // refusedEntities reports whether err is Telegram refusing a message's // entities, so it can go without them. func refusedEntities(err error) bool { @@ -203,9 +213,10 @@ func utf16Slice(rs []rune, u []int, start, n int) []rune { } // sendPhotos sends pics, one as a photo or several as an album, with -// caption on the first, without its entities if Telegram refuses them, and -// returns the IDs of the messages sent. -func (c *Client) sendPhotos(ctx context.Context, ch feature.Chat, pics []feature.Picture, caption *mdstyle.Text, known map[string]string) ([]int64, error) { +// caption on the first, without its entities if Telegram refuses them, as +// a reply to replyTo if it isn't 0, and returns the IDs of the messages +// sent. +func (c *Client) sendPhotos(ctx context.Context, ch feature.Chat, pics []feature.Picture, caption *mdstyle.Text, known map[string]string, replyTo int64) ([]int64, error) { pics = pics[:min(len(pics), 10)] // an album's limit files := map[string][]byte{} for i, p := range pics { @@ -215,14 +226,14 @@ func (c *Client) sendPhotos(ctx context.Context, ch feature.Chat, pics []feature if caption != nil { ents = append(ents, entities(*caption, known)...) } - ids, err := c.sendPhotosOnce(ctx, ch, pics, files, caption, ents) + ids, err := c.sendPhotosOnce(ctx, ch, pics, files, caption, ents, replyTo) if caption != nil && len(ents) > 0 && refusedEntities(err) { - ids, err = c.sendPhotosOnce(ctx, ch, pics, files, caption, []outEntity{}) + ids, err = c.sendPhotosOnce(ctx, ch, pics, files, caption, []outEntity{}, replyTo) } return ids, err } -func (c *Client) sendPhotosOnce(ctx context.Context, ch feature.Chat, pics []feature.Picture, files map[string][]byte, caption *mdstyle.Text, ents []outEntity) ([]int64, error) { +func (c *Client) sendPhotosOnce(ctx context.Context, ch feature.Chat, pics []feature.Picture, files map[string][]byte, caption *mdstyle.Text, ents []outEntity, replyTo int64) ([]int64, error) { text := "" if caption != nil { text = string(caption.Runes) @@ -247,6 +258,10 @@ func (c *Client) sendPhotosOnce(ctx context.Context, ch feature.Chat, pics []fea mj, _ := json.Marshal(media) method, fields, out = "sendMediaGroup", d.fields(map[string]string{"media": string(mj)}), &album } + if replyTo != 0 { + rj, _ := json.Marshal(replyParams(replyTo)) + fields["reply_parameters"] = string(rj) + } err := c.retrying(ctx, d.chat, func(to string) { fields["chat_id"] = to }, func() error { return c.upload(ctx, method, fields, files, out) }) if err != nil { return nil, err @@ -274,7 +289,7 @@ func (c *Client) React(ch feature.Chat, msg feature.Message, emoji string) { switch { case err == nil: case errors.As(err, &ae) && ae.Code == 400 && strings.Contains(ae.Desc, "REACTION_INVALID"): - c.Send(ch, emoji, nil, nil) + c.Send(ch, emoji, nil, nil, 0) default: logx.Errorf("reaction failed: %v", err) } diff --git a/internal/telegram/telegram_test.go b/internal/telegram/telegram_test.go index 46764da..5a832a3 100644 --- a/internal/telegram/telegram_test.go +++ b/internal/telegram/telegram_test.go @@ -296,7 +296,7 @@ func TestEdits(t *testing.T) { func TestSend(t *testing.T) { f := newFake(t) c := connected(f.client()) - ids := c.Send(feature.Chat{GroupID: groupS}, "🎉 **big** news, see [docs](https://x.example) and @Alice", nil, map[string]string{"alice": "1111111"}) + ids := c.Send(feature.Chat{GroupID: groupS}, "🎉 **big** news, see [docs](https://x.example) and @Alice", nil, map[string]string{"alice": "1111111"}, 0) if !reflect.DeepEqual(ids, []int64{500}) { t.Fatalf("ids %v", ids) } @@ -309,7 +309,7 @@ func TestSend(t *testing.T) { if string(got) != want { t.Fatalf("entities\n got %s\n want %s", got, want) } - c.Send(feature.Chat{User: "1111111"}, strings.Repeat("word ", 1700), nil, nil) + c.Send(feature.Chat{User: "1111111"}, strings.Repeat("word ", 1700), nil, nil, 0) if n := len(f.callsTo("sendMessage")); n != 3 { // 8500 chars, capped at 8000: two messages t.Fatalf("a long reply in %d messages", n-1) } @@ -320,7 +320,7 @@ func TestSend(t *testing.T) { } // Entities Telegram refuses: the text alone. f.errs["sendMessage"] = `{"ok":false,"error_code":400,"description":"Bad Request: can't parse entities"}` - if ids := c.Send(feature.Chat{User: "1111111"}, "**x**", nil, nil); len(ids) != 1 { + if ids := c.Send(feature.Chat{User: "1111111"}, "**x**", nil, nil, 0); len(ids) != 1 { t.Fatalf("fallback ids %v", ids) } if last := f.callsTo("sendMessage"); last[len(last)-1].Params["entities"] != nil || last[len(last)-1].Params["text"] != "x" { @@ -336,14 +336,14 @@ func TestSendPictures(t *testing.T) { f.results["sendMediaGroup"] = `[{"message_id":602},{"message_id":603}]` c := connected(f.client()) png := []byte("\x89PNG\r\n\x1a\nxx") - if ids := c.Send(feature.Chat{User: "1111111"}, "NVDA ▼ 15.2%", []feature.Picture{{Data: png}}, nil); !reflect.DeepEqual(ids, []int64{601}) { + if ids := c.Send(feature.Chat{User: "1111111"}, "NVDA ▼ 15.2%", []feature.Picture{{Data: png}}, nil, 0); !reflect.DeepEqual(ids, []int64{601}) { t.Fatalf("ids %v", ids) } ph := f.callsTo("sendPhoto")[0] if ph.Params["caption"] != "NVDA ▼ 15.2%" || string(ph.Files["p0"]) != string(png) || len(f.callsTo("sendMessage")) != 0 { t.Fatalf("photo %v", ph.Params) } - if ids := c.Send(feature.Chat{GroupID: groupS}, "", []feature.Picture{{Data: png}, {Data: png}}, nil); !reflect.DeepEqual(ids, []int64{602, 603}) { + if ids := c.Send(feature.Chat{GroupID: groupS}, "", []feature.Picture{{Data: png}, {Data: png}}, nil, 0); !reflect.DeepEqual(ids, []int64{602, 603}) { t.Fatalf("album ids %v", ids) } if mg := f.callsTo("sendMediaGroup")[0]; len(mg.Files) != 2 || !strings.Contains(mg.Params["media"].(string), `"attach://p1"`) { @@ -351,6 +351,38 @@ func TestSendPictures(t *testing.T) { } } +// A reply's first message, and only its first, carries reply_parameters, +// sent anyway if the message it replies to is gone: a long reply's first +// part, or its pictures. +func TestSendReply(t *testing.T) { + f := newFake(t) + f.results["sendPhoto"] = `{"message_id":601}` + c := connected(f.client()) + c.Send(feature.Chat{GroupID: groupS}, strings.Repeat("word ", 1700), nil, nil, 42) + msgs := f.callsTo("sendMessage") + if len(msgs) != 2 { + t.Fatalf("%d messages", len(msgs)) + } + if got, _ := json.Marshal(msgs[0].Params["reply_parameters"]); string(got) != `{"allow_sending_without_reply":true,"message_id":42}` { + t.Errorf("first part's reply_parameters %s", got) + } + if msgs[1].Params["reply_parameters"] != nil { + t.Errorf("second part replies too: %v", msgs[1].Params["reply_parameters"]) + } + png := []byte("\x89PNG\r\n\x1a\nxx") + c.Send(feature.Chat{User: "1111111"}, strings.Repeat("x", maxCaption+1), []feature.Picture{{Data: png}}, nil, 43) + if ph := f.callsTo("sendPhoto")[0]; ph.Params["reply_parameters"] != `{"allow_sending_without_reply":true,"message_id":43}` { + t.Errorf("photo's reply_parameters %v", ph.Params["reply_parameters"]) + } + if msgs := f.callsTo("sendMessage"); len(msgs) != 3 || msgs[2].Params["reply_parameters"] != nil { + t.Errorf("the text after the photo replies too: %v", msgs[len(msgs)-1].Params) + } + c.Send(feature.Chat{User: "1111111"}, "plain", nil, nil, 0) + if msgs := f.callsTo("sendMessage"); msgs[len(msgs)-1].Params["reply_parameters"] != nil { + t.Errorf("a plain send replies: %v", msgs[len(msgs)-1].Params) + } +} + // A reaction Telegram refuses is sent as a message. func TestReact(t *testing.T) { f := newFake(t) @@ -436,7 +468,7 @@ func TestTokenNeverLogged(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) defer cancel() c.Run(ctx, func(bot.Received) {}) - c.Send(feature.Chat{User: "1"}, "hi", nil, nil) + c.Send(feature.Chat{User: "1"}, "hi", nil, nil, 0) out := logs.String() if !strings.Contains(out, "getMe failed") || !strings.Contains(out, "send failed") || strings.Contains(out, "SECRET") { t.Fatalf("logs %q", out) @@ -527,8 +559,8 @@ func TestEvents(t *testing.T) { t.Fatal("an event with no hook") } c.Watch(bot.Watch{Events: true}) - c.groupAllowed(context.Background(), groupS) // Alice is in it - c.Send(feature.Chat{GroupID: groupS}, "hello", nil, nil) // message 500, the bot's + c.groupAllowed(context.Background(), groupS) // Alice is in it + c.Send(feature.Chat{GroupID: groupS}, "hello", nil, nil, 0) // message 500, the bot's r, _ := c.event(parse(t, `{"update_id":2,"message_reaction":{`+inGroup+`,"message_id":500,"user":{"id":1111111,"first_name":"Alice"},"old_reaction":[{"type":"emoji","emoji":"👍"}],"new_reaction":[]}}`)) e := r.(bot.Happened).Event if e.Reaction == nil || e.Reaction.Emoji != "👍" || !e.Reaction.Removed || !e.Reaction.Bot || e.By.ID != "1111111" || e.Reaction.Sent != 500 { @@ -608,14 +640,14 @@ func TestSendPicturesFail(t *testing.T) { c := connected(f.client()) png := []byte("\x89PNG\r\n\x1a\nxx") f.errs["sendPhoto"] = `{"ok":false,"error_code":400,"description":"Bad Request: PHOTO_INVALID_DIMENSIONS"}` - if ids := c.Send(feature.Chat{User: "1111111"}, "**the** caption", []feature.Picture{{Data: png}}, nil); !reflect.DeepEqual(ids, []int64{500}) { + if ids := c.Send(feature.Chat{User: "1111111"}, "**the** caption", []feature.Picture{{Data: png}}, nil, 0); !reflect.DeepEqual(ids, []int64{500}) { t.Fatalf("ids %v", ids) } if s := f.callsTo("sendMessage"); len(s) != 1 || s[0].Params["text"] != "the caption" { t.Fatalf("text %v", s) } f.errs["sendPhoto"] = `{"ok":false,"error_code":400,"description":"Bad Request: can't parse entities"}` - if ids := c.Send(feature.Chat{User: "1111111"}, "**the** caption", []feature.Picture{{Data: png}}, nil); !reflect.DeepEqual(ids, []int64{601}) { + if ids := c.Send(feature.Chat{User: "1111111"}, "**the** caption", []feature.Picture{{Data: png}}, nil, 0); !reflect.DeepEqual(ids, []int64{601}) { t.Fatalf("ids %v", ids) } ph := f.callsTo("sendPhoto") @@ -632,12 +664,12 @@ func TestSendRetries(t *testing.T) { c := connected(f.client()) f.errs["sendMessage"] = `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}` start := time.Now() - if ids := c.Send(feature.Chat{GroupID: groupS}, "hi", nil, nil); !reflect.DeepEqual(ids, []int64{500}) || time.Since(start) < time.Second { + if ids := c.Send(feature.Chat{GroupID: groupS}, "hi", nil, nil, 0); !reflect.DeepEqual(ids, []int64{500}) || time.Since(start) < time.Second { t.Fatalf("ids %v after %s", ids, time.Since(start)) } f.errs["sendMessage"] = `{"ok":false,"error_code":400,"description":"Bad Request: group chat was upgraded to a supergroup chat","parameters":{"migrate_to_chat_id":-1009999999999}}` - c.Send(feature.Chat{GroupID: "-4444444"}, "one", nil, nil) - c.Send(feature.Chat{GroupID: "-4444444"}, "two", nil, nil) + c.Send(feature.Chat{GroupID: "-4444444"}, "one", nil, nil, 0) + c.Send(feature.Chat{GroupID: "-4444444"}, "two", nil, nil, 0) var to []any for _, s := range f.callsTo("sendMessage")[2:] { to = append(to, s.Params["chat_id"]) @@ -677,7 +709,7 @@ func TestTopics(t *testing.T) { if m.Quote != nil || m.Text != "hi" { t.Fatalf("message %+v", m) } - c.Send(in.Chat, "hello", nil, nil) + c.Send(in.Chat, "hello", nil, nil, 0) if s := f.callsTo("sendMessage")[0].Params; s["chat_id"] != groupS || s["message_thread_id"] != float64(7) { t.Fatalf("sent %v", s) } @@ -707,7 +739,7 @@ func TestMigration(t *testing.T) { if gs, _ := c.Groups(context.Background(), "1111111"); len(gs) != 1 || gs[0].ID != "-1009999999999" { t.Fatalf("groups %v", gs) } - c.Send(feature.Chat{GroupID: "-4444444"}, "scheduled", nil, nil) + c.Send(feature.Chat{GroupID: "-4444444"}, "scheduled", nil, nil, 0) if s := f.callsTo("sendMessage")[0].Params; s["chat_id"] != "-1009999999999" { t.Fatalf("sent to %v", s["chat_id"]) } From a9aa407e4a8ad7bcb5e0beac7dba8f45c6cc6a5d Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sat, 21 Nov 2026 13:18:51 +0000 Subject: [PATCH 22/26] Guard an addon's later pictures too A post of the addon's with pictures, sent while a watch with a guard lives in its chat, joins the pictures the guard answers replies to, so a game's later rounds are guarded like its first. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- docs/FILES_LINKS_TOOLS_MCP.md | 2 +- internal/features/mcp/outbox.go | 3 +++ internal/features/mcp/watch.go | 23 +++++++++++++++++++++++ internal/features/mcp/watch_test.go | 19 +++++++++++++++++++ 4 files changed, 46 insertions(+), 1 deletion(-) diff --git a/docs/FILES_LINKS_TOOLS_MCP.md b/docs/FILES_LINKS_TOOLS_MCP.md index 78be97d..caaac46 100644 --- a/docs/FILES_LINKS_TOOLS_MCP.md +++ b/docs/FILES_LINKS_TOOLS_MCP.md @@ -144,7 +144,7 @@ Each permission is off unless set. For an addon, `chats`, `dms` and these permis - **Direct commands.** `"direct": true` on a chat command has the bot call the addon's tool itself, with the text after the command, and send what it answers (text, and up to 2 pictures) without the model. The tool must be marked for the bot, and is then never offered to the model. A call has 15 seconds, or the command's `timeout`, from 1s to 2m (`"timeout": "60s"`), for an addon that may take a while, such as GeoGuess finding a photo; while it runs the chat sees the bot typing. At most 2 run at once per addon; a third is told the addon is busy, so with a long `timeout`, two calls that wait (two chats each waiting for a GeoGuess photo) make even a quick command such as `/geo scores` wait for one to end. When it fails, the chat gets a short line ("GeoGuess couldn't do that just now."), never the addon's own error text. An addon with no tool for the model has its commands named in the prompt's list of what the bot has, so the model can point people to them. - **Hidden tools.** A tool whose `_meta` says it is for the bot alone (`io.github.robdevops.signalbot/visibility` without `"model"`, or MCP Apps' `ui.visibility` without `"model"`) is never offered to the model or listed as one of its tools, so tools that read chat text stay out of its hands. -- **Watches.** A direct command's answer can ask for a watch on its chat: a pattern, such as map links, until a time at most `watch_max` away. While it lasts, a message there that matches goes to the addon instead: it isn't answered, isn't sent to the model, and isn't kept in history, even as group context; so does an edit of it later. The addon may react to it, so people see it was counted. A pattern that would match ordinary chat ("lol", "see you at 5", a news link, …) is refused, so a watch can't become a feed of everything said; at most 8 run in a chat at once. While a watch lasts, a reply to the command's pictures that asks the bot gets the addon's set answer (GeoGuess's "No hints during a round 😉"), not the model's. A reply watch (`"replies": true`) takes instead only replies to the addon's own messages in the chat while it lasts, the command's answer and its posts, that ask the bot, such as a quiz's free-text answers; its pattern, if it has one, must match them too, and isn't held to the ordinary-chat rule, since such a reply is meant for the addon. +- **Watches.** A direct command's answer can ask for a watch on its chat: a pattern, such as map links, until a time at most `watch_max` away. While it lasts, a message there that matches goes to the addon instead: it isn't answered, isn't sent to the model, and isn't kept in history, even as group context; so does an edit of it later. The addon may react to it, so people see it was counted. A pattern that would match ordinary chat ("lol", "see you at 5", a news link, …) is refused, so a watch can't become a feed of everything said; at most 8 run in a chat at once. While a watch lasts, a reply to the command's pictures, or to pictures the addon posts while it lasts, that asks the bot gets the addon's set answer (GeoGuess's "No hints during a round 😉"), not the model's. A reply watch (`"replies": true`) takes instead only replies to the addon's own messages in the chat while it lasts, the command's answer and its posts, that ask the bot, such as a quiz's free-text answers; its pattern, if it has one, must match them too, and isn't held to the ordinary-chat rule, since such a reply is meant for the addon. - **Model.** With `model`, an addon may ask the bot's model for text, through MCP's standard sampling request (`sampling/createMessage`): it sends the prompt, and the bot runs it on its own model, with its own key, and sends back the answer. The addon needs no key or provider of its own. The bot offers this only to an addon with `model`, and only while it has a model; MCP suggests a person approve each request, and here the `model` setting is that approval. Each request names the chat it is for, one the addon may post in now, and is charged to that chat's `DAILY_BUDGET`: one over its budget is refused, and so is one past `per_hour`. A request is text only, at most 16 messages and 32 KB, with one in flight per addon at a time. Only its outcome, time, size, tokens and cost are logged, never the prompt or the answer. - **Outbox.** An addon posts when it likes by queueing posts, reactions and the end of a watch in its outbox, an MCP resource the bot subscribes to (`signalbot://outbox`), and saying it changed; the bot reads it at once. It may post or react only in a chat where it was used, by a command or a watch, in the last 24 hours, and only within `rate`. Its posts go through the chat's queue like any message, never more than one at a time, and history keeps them as the bot's, labelled with the addon's name (`[GeoGuess] …`), so what an addon writes never poses as a person. A post can be a reply to one of the addon's earlier posts in the same chat, named by that post's ID (`replyTo`), so a quiz can answer a question under it; the Go package's `QueueIDs` gives the IDs. The bot remembers the IDs of the addon's last 256 post ops for 24 hours (a merged post uses one for each op); a reply to one it doesn't know, or in another chat, goes as an ordinary post. A reply is always a message of its own, never merged with the addon's other posts. On Signal it quotes the post; on Telegram it replies to it, and goes anyway if the post was deleted. - **Settings.** An addon has no `env` block. It gets `PATH`, `HOME`, the bot's time zone (`TZ`) and proxy settings (`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, and `SSL_CERT_FILE` or `SSL_CERT_DIR` for a custom CA) if set, and every variable in the bot's environment (`/etc/signalbot.env`) that starts with its server's name in capitals, anything but letters and digits as `_`, then `_`: the server `geo` gets `GEO_STATE_DIR`, `GEO_MAPILLARY_TOKEN` and so on, and never the bot's own keys. A name whose prefix starts one of the bot's settings (such as `model`, `signal` or `mcp`) is a config error. An addon that keeps files takes its directory from `<PREFIX>STATE_DIR` (`GEO_STATE_DIR`) and creates it itself, mode 0700. Unless the bot's environment sets it, the bot sets it to `addons/<server name>` in the bot's state directory (`/var/lib/private/signalbot/addons/geo`, or `/data/addons/geo` in Docker), so an addon's files are kept with the bot's; it creates nothing there itself. With `STATE_DIRECTORY` unset, or a server name that isn't only letters, digits, `.`, `_` and `-` (up to 64, not starting with `.`), there is no default, and the addon falls back on its own. diff --git a/internal/features/mcp/outbox.go b/internal/features/mcp/outbox.go index 2f7dc4e..0f77408 100644 --- a/internal/features/mcp/outbox.go +++ b/internal/features/mcp/outbox.go @@ -373,6 +373,9 @@ func (a *addon) mail(id string, out *outgoing) { p.OnSent = func(sent []int64, dropped bool) { if !dropped { a.replied(p.Chat, sent) + if len(p.Pictures) > 0 { + a.guardPosted(p.Chat, sent) + } a.rememberPosted(id, out.ops, sent) } a.sent(out.ops, !dropped) diff --git a/internal/features/mcp/watch.go b/internal/features/mcp/watch.go index 213a960..eced97a 100644 --- a/internal/features/mcp/watch.go +++ b/internal/features/mcp/watch.go @@ -168,6 +168,29 @@ func (a *addon) guarding(w *watch, sent []int64) { a.changed() } +// guardPosted records that a post of the addon's with pictures went out +// in chat at sent, on each of the chat's live watches with a guard, so a +// reply to a later round's picture gets the guard too. +func (a *addon) guardPosted(chat feature.Chat, sent []int64) { + if len(sent) == 0 { + return + } + now := a.now() + found := false + a.mu.Lock() + for _, w := range a.watches[chat.Key()] { + if w.Guard != "" && now.Before(w.Until) { + w.Pictures = append(w.Pictures, sent...) + w.Pictures = w.Pictures[max(len(w.Pictures)-maxSent, 0):] + found = true + } + } + a.mu.Unlock() + if found { + a.changed() + } +} + // replied records that the addon's messages in chat went out at sent, on // each of the chat's live reply watches, so they take replies to them. func (a *addon) replied(chat feature.Chat, sent []int64) { diff --git a/internal/features/mcp/watch_test.go b/internal/features/mcp/watch_test.go index 62307fb..f259a43 100644 --- a/internal/features/mcp/watch_test.go +++ b/internal/features/mcp/watch_test.go @@ -1160,3 +1160,22 @@ func TestNotFound(t *testing.T) { t.Error("a timeout") } } + +// A later picture the addon posts while a guarded watch lives gets the +// guard too; a post in another chat, or after the watch, doesn't. +func TestGuardPosted(t *testing.T) { + a, now := unitAddon(everything) + s := specAt("g", now.Add(time.Minute)) + s.Guard = "No hints" + w := a.watch(said(inA, "alice-id", 1000, "/round"), s) + if w == nil { + t.Fatal("watch refused") + } + a.guardPosted(inA, []int64{777}) + a.guardPosted(inB, []int64{888}) + *now = now.Add(2 * time.Minute) + a.guardPosted(inA, []int64{999}) + if !slices.Equal(w.Pictures, []int64{777}) { + t.Errorf("pictures %v", w.Pictures) + } +} From a500bfe7637a13ac0649ca85765ff804dcd3ffdf Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sun, 22 Nov 2026 01:26:44 +0000 Subject: [PATCH 23/26] Posts can carry an audio clip, and addons can send one feature.Post.Audio is one MP3 clip sent to play, with no title of its own: on Signal an attachment named clip.mp3, on Telegram a voice message. Network.Send takes it as its last argument. An addon's post op may carry it as audio {data, mimeType: audio/mpeg}, at most 2 MB; such a post is never merged. Schema and docs follow. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- TECHNICAL.md | 4 +-- addon/schema.json | 13 ++++++- addon/schema_test.go | 3 ++ addon/types.go | 8 +++++ docs/FILES_LINKS_TOOLS_MCP.md | 2 +- internal/bot/answer.go | 8 ++--- internal/bot/bot.go | 7 ++-- internal/bot/fakes_test.go | 2 +- internal/bot/host.go | 11 +++--- internal/feature/feature.go | 1 + internal/features/mcp/outbox.go | 14 ++++++-- internal/features/mcp/watch_test.go | 36 +++++++++++++++++++ internal/signal/client_test.go | 10 +++--- internal/signal/markdown_test.go | 4 +-- internal/signal/send.go | 5 ++- internal/signal/send_test.go | 22 +++++++++--- internal/telegram/client.go | 6 +++- internal/telegram/send.go | 30 ++++++++++++++-- internal/telegram/telegram_test.go | 55 +++++++++++++++++++---------- 19 files changed, 188 insertions(+), 53 deletions(-) diff --git a/TECHNICAL.md b/TECHNICAL.md index 3536932..d3ff075 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -137,7 +137,7 @@ The core's lifecycle has four stages. Each port is one stage; nothing else is a - anything else the bot posts as written, with @Name linked against the group's members (never an ambiguous name), and history keeps it as the sender's message, "<name>: <text>", not as something the bot chose to say. These rules are what "as if its sender had just posted it" means for any feature, not just `/schedule`, so the host applies them rather than each feature. The membership check calls the network, so it runs in the message's slot; a feature's timer callback has no slot to make that call in. -- `Post(Post)`: the bot posts `Text`, with any `Pictures` (the caption rule applies), to a group or a DM, as written, never through the model, through that chat's mailbox. In the slot, `Network.Reachable` must say the bot may still post there, or it is dropped and logged at info. `@Name` is linked against the chat's known names. With a `Label`, history keeps the post as the bot's own entry, `[Label] text` (the pictures' notes in place of text they replaced), clamped to 500 characters, so a feature's text can never pose as a person; with none, or with no model, nothing is kept. `OnSent`, if set, is called once, with the timestamps sent, or with dropped set when it never goes out (a full mailbox, an unreachable chat, shutdown, a send that failed and returned no timestamps). `ReplyTo`, if set, is one of those timestamps from an earlier post or answer of the bot's in the same chat, and the post goes as a reply to it: the core passes it to `Network.Send`, whose first message sent replies to that message (Signal: `send` with `quoteTimestamp` and `quoteAuthor`, the bot's own account; Telegram: `reply_parameters` with `message_id` and `allow_sending_without_reply`, so a deleted message doesn't stop the post). signal-cli quotes by timestamp and author alone, whether or not it still has the message, so a recipient without it sees a quote of a message not found. Every other send passes 0, for none. `/schedule` uses it, with no label, to tell an owner in their DM that a one-off was dropped. +- `Post(Post)`: the bot posts `Text`, with any `Pictures` (the caption rule applies) and any `Audio`, one MP3 clip sent to play with no title of its own (on Signal an attachment named `clip.mp3`, on Telegram a voice message, sent first; history keeps "[sent an audio clip]"), to a group or a DM, as written, never through the model, through that chat's mailbox. In the slot, `Network.Reachable` must say the bot may still post there, or it is dropped and logged at info. `@Name` is linked against the chat's known names. With a `Label`, history keeps the post as the bot's own entry, `[Label] text` (the pictures' notes in place of text they replaced), clamped to 500 characters, so a feature's text can never pose as a person; with none, or with no model, nothing is kept. `OnSent`, if set, is called once, with the timestamps sent, or with dropped set when it never goes out (a full mailbox, an unreachable chat, shutdown, a send that failed and returned no timestamps). `ReplyTo`, if set, is one of those timestamps from an earlier post or answer of the bot's in the same chat, and the post goes as a reply to it: the core passes it to `Network.Send`, whose first message sent replies to that message (Signal: `send` with `quoteTimestamp` and `quoteAuthor`, the bot's own account; Telegram: `reply_parameters` with `message_id` and `allow_sending_without_reply`, so a deleted message doesn't stop the post). signal-cli quotes by timestamp and author alone, whether or not it still has the message, so a recipient without it sees a quote of a message not found. Every other send passes 0, for none. `/schedule` uses it, with no label, to tell an owner in their DM that a one-off was dropped. - `React(chat, msg, emoji)`: the bot puts `emoji` on `msg`, through the chat's mailbox at low priority (see the per-chat mailbox): a later reaction to the same message replaces a waiting one, at most 16 wait per chat, and one to a message deleted or replaced by an edit since is skipped. `chat` mirrors `Network.React`; `msg`'s own `Chat` is ignored. A message the bot made (`Timestamp` 0) can't be reacted to; nothing happens. - `Groups(ctx, user)`: the groups the bot shares with a user, with their names (`listGroups`). - `Redact(text)`: text with every name and ID the bot knows for anyone but itself, and any UUID or phone number, replaced with "redacted", for logging text the bot doesn't control (a local MCP server's output). @@ -248,7 +248,7 @@ In `features.go` order, which is the order hooks run in and of the tools line an - **Watches:** a direct command's result may ask, in `_meta["io.github.robdevops.signalbot/watch"]`, for a watch on the chat the command came from (the only way to make one, so an addon can't watch a chat it wasn't used in): an `id` (at most 64 characters), an RE2 `pattern` (at most 1,024 characters), `until` (RFC 3339, cut to `watch_max` from now and never extended), the `tool` to call with each match (one the bot may call) and an optional `guard` (at most 500 characters). It needs `watch`, and at most 8 are live in a chat per addon (one with the same ID is replaced). A pattern that matches the empty string or any of about 200 ordinary chat lines in `corpus.go` is refused, so no watch is a feed of the chat; a refusal is logged by reason, never the pattern. One `OnMessage` hook, registered after the chat commands, checks each message with text in an allowed chat against the chat's live watches, on both paths: unaddressed ones on the reader goroutine (only a map lookup and the patterns, under a mutex held briefly), addressed ones (a reply to the bot, a DM, an @mention, a command) in their slot. A watch matches any message the bot gets while it lasts, by when the bot got it, not by its `Timestamp` (on Signal the sender's clock, which may be behind); an edit, unless its original was claimed, only if its original's `Timestamp` is at or after the command's, so an older message's edit isn't taken. An addressed message with no text (a bare mention, or a reply with only a picture) is still checked for the guard. A match is `Done`, so it is never answered, sent to the model or kept in history, and `groupctx` never sees it; it is claimed for 48 hours (chat key, sender's pseudonym, sent time), so a later edit of it goes the same way, to the same tool, whether or not the watch is still live; and it is passed without waiting to the addon's watch worker, whose queue holds 256 (when full, "addon <name>: watch queue full, a matched message dropped", still `Done`). The worker calls the watch's tool with `{"text": …}` and the context, within 120 calls a minute per chat (bursts of 20; a match past it waits its turn in the worker's queue, while other chats' matches go ahead), and keeps a match whose call found the server down (not running, or exited before answering) at the head of the queue until the server has started again (or a minute has passed), dropping it with a warning after 3 such calls, and if the result's `_meta["io.github.robdevops.signalbot/react"]` is one emoji, reacts with it (`React`), which needs `react` and counts against the addon's rate. A watch whose command answered with pictures records, through `OnSent`, the timestamps of the messages they went out in; while it lives, an addressed message quoting one of them gets the `guard` as its `Answer`, so nobody can ask the model about the picture. - **Reply watches:** a watch with `replies` takes only addressed messages whose `Quote.Bot` is set and whose `Quote.Sent` is the timestamp of one of the addon's own messages in the chat sent while it lives: a direct command's answer (any answer, through the `Action`'s `OnSent`) and each outbox post (through the `Post`'s `OnSent`), recorded on every live reply watch in the chat, the last 64 each. Its `pattern`, if set, must match too; it may be empty, and isn't checked against `corpus.go`, since a reply to the addon's own message is meant for it. Claims, edits, the worker, its rate and queue work as for any watch. Without `replies`, a watch works as above, and an empty pattern is refused. - **Leases:** an addon may post or react only in a chat where it had a direct command or a watch match in the last 24 hours; the lease maps the chat's pseudonym to the chat. - - **Outbox:** if the server advertises `resources.subscribe`, the bot sends `resources/subscribe` for `signalbot://outbox` after each (re)start's `initialize`, then reads it; otherwise the outbox is off, with a warning. Any `notifications/resources/updated` from the server marks the outbox as having news (whatever the URI, which may be under the one subscribed). One reader goroutine per addon reads `resources/read` of `signalbot://outbox/<cursor>` (`0` at first), page by page while `more` is true, up to 100 pages, so two reads never race and news during a read is read after it. A page is one text content holding `{"cursor", "more", "ops"}`; a not-found error (-32002, or the Go SDK's -32602) is logged as no outbox. Ops are applied once each by `id`, the last 1,000 IDs remembered, and are `post` (`chat`, Markdown `text` with placeholders, up to 2 `images` as `{data, mimeType, name}`, 2 MB together, and optionally `replyTo`), needing `post`; `react` (`ref`, `emoji`), needing `react`; and `unwatch` (`chat`, `watch`), which, for a watch not yet made, stops it being made for 10 minutes. A post or reaction needs a live lease in a chat the addon is still allowed, and counts against `rate` per chat. A post goes through `Post` with the addon's title as its `Label`, so history keeps it as `[Title] …`, the bot's own words. At most one of an addon's posts waits in a chat's mailbox: until its `OnSent`, later posts for that chat are held, each merged into the one held before it while their pictures together stay within 2 and 2 MB and their texts together within 4,000 characters, so a merge never cuts one, and sent in turn. A post with `replyTo`, the `id` of an earlier post op of the addon's, is never merged, in either direction, so it stays its own message and a later post a new one. As each post is sent, its op IDs (a merged post's every one) are remembered with the chat's pseudonym and the first timestamp `OnSent` gave, for 24 hours, the last 256 by when they expire. When a post with `replyTo` is put in the mailbox, after any held before it in its chat went out, a remembered target in the same chat becomes the `Post`'s `ReplyTo`; an unknown, expired or other chat's target leaves it a plain post. While its target was dropped and waits to be posted again, a reply waits too, without counting a try, and is posted after it. Delivery is at least once: a post counts as applied, and the cursor moves past it, only once its `OnSent` says it was sent. A send that fails counts as dropped, so a post whose send timed out after it went out may be posted twice, rather than lost. Until then each read starts from the cursor before it and skips it while it waits; one dropped before it was sent (as while the bot stops, or before the network is up at startup, when `Post` gives up on the chat) is posted again by a read 10s later, then 20s, doubling to 5 minutes, not counted against `rate` again, and given up with a warning after 6 tries. A page with `more` waits for its posts before the next is read, since reading past the cursor lets the addon forget them. A read that fails, is malformed, or stops at 100 pages is tried again after 10s, doubling to 5 minutes, without waiting for news. What a read drops is counted in one warning by reason, never content. + - **Outbox:** if the server advertises `resources.subscribe`, the bot sends `resources/subscribe` for `signalbot://outbox` after each (re)start's `initialize`, then reads it; otherwise the outbox is off, with a warning. Any `notifications/resources/updated` from the server marks the outbox as having news (whatever the URI, which may be under the one subscribed). One reader goroutine per addon reads `resources/read` of `signalbot://outbox/<cursor>` (`0` at first), page by page while `more` is true, up to 100 pages, so two reads never race and news during a read is read after it. A page is one text content holding `{"cursor", "more", "ops"}`; a not-found error (-32002, or the Go SDK's -32602) is logged as no outbox. Ops are applied once each by `id`, the last 1,000 IDs remembered, and are `post` (`chat`, Markdown `text` with placeholders, up to 2 `images` as `{data, mimeType, name}`, 2 MB together, optionally one `audio` clip as `{data, mimeType: "audio/mpeg"}` of at most 2 MB, and optionally `replyTo`), needing `post`; `react` (`ref`, `emoji`), needing `react`; and `unwatch` (`chat`, `watch`), which, for a watch not yet made, stops it being made for 10 minutes. A post or reaction needs a live lease in a chat the addon is still allowed, and counts against `rate` per chat. A post goes through `Post` with the addon's title as its `Label`, so history keeps it as `[Title] …`, the bot's own words. At most one of an addon's posts waits in a chat's mailbox: until its `OnSent`, later posts for that chat are held, each merged into the one held before it while their pictures together stay within 2 and 2 MB and their texts together within 4,000 characters, so a merge never cuts one, and sent in turn. A post with audio, or with `replyTo`, the `id` of an earlier post op of the addon's, is never merged, in either direction, so it stays its own message and a later post a new one. As each post is sent, its op IDs (a merged post's every one) are remembered with the chat's pseudonym and the first timestamp `OnSent` gave, for 24 hours, the last 256 by when they expire. When a post with `replyTo` is put in the mailbox, after any held before it in its chat went out, a remembered target in the same chat becomes the `Post`'s `ReplyTo`; an unknown, expired or other chat's target leaves it a plain post. While its target was dropped and waits to be posted again, a reply waits too, without counting a try, and is posted after it. Delivery is at least once: a post counts as applied, and the cursor moves past it, only once its `OnSent` says it was sent. A send that fails counts as dropped, so a post whose send timed out after it went out may be posted twice, rather than lost. Until then each read starts from the cursor before it and skips it while it waits; one dropped before it was sent (as while the bot stops, or before the network is up at startup, when `Post` gives up on the chat) is posted again by a read 10s later, then 20s, doubling to 5 minutes, not counted against `rate` again, and given up with a warning after 6 tries. A page with `more` waits for its posts before the next is read, since reading past the cursor lets the addon forget them. A read that fails, is malformed, or stops at 100 pages is tried again after 10s, doubling to 5 minutes, without waiting for news. What a read drops is counted in one warning by reason, never content. - **Sampling:** an addon offered sampling may send MCP's `sampling/createMessage`. The stdio client reads every message's ID as raw JSON, so a server's request may use a string ID, answered with the same one. `dispatch` hands the request to the addon's handler on a goroutine of its own, never the reader's, so a slow model call never holds up replies; one is served at a time per addon, and a second gets -32000 at once. The handler is installed before `initialize`, behind a `gate` that holds a request until the addon is set up after `tools/list`, and refuses it with -32000 if it never is (as when the server turns out not to speak the extension), so a request is never called unsupported while sampling is offered. An incoming `notifications/cancelled` naming it, or the process exiting, cancels its ctx, and a cancelled request gets no answer; an answer to a process that has since restarted is dropped. The model call doesn't take that cancel: it runs under `context.WithoutCancel` with its own 2 minutes, so a call the provider bills is always charged to the chat, and the addon can't spend outside `DAILY_BUDGET` by cancelling or exiting. Any other request, or this one from an addon without it, gets -32601, and `ping` `{}`, as before. The handler (`sample.go`) takes text messages only, `user` or `assistant`, at most 16 and 32 KB of text with the system prompt, and a `maxTokens` of at least 1, capped at `max_tokens`; `temperature` (0 to 2) is passed on, and `modelPreferences` and `includeContext` are ignored. `_meta["io.github.robdevops.signalbot/chat"]` must name a chat the addon holds a live lease in and is still allowed, and `per_hour` (a `limiter`, all of the addon's chats as one bucket) must have room; a refusal is -32602 or -32000 with a short message. It posts `{"messages": [system, …], "max_tokens", "temperature"}` to `/chat/completions` through `CallAPI` with `feature.ChargeTo` that chat, so the core sets its own model, refuses a chat over `DAILY_BUDGET` and charges it, within 2 minutes, and answers `{role: "assistant", content: {type: "text", text}, model, stopReason}` from `choices[0].message.content`, `model` and `finish_reason` (`stop` as `endTurn`, `length` as `maxTokens`). A failure is -32603, "the model couldn't answer", never the API's text. It logs the outcome, time, the request's text size, the answer's tokens and the cost, never the prompt or the answer. - **What is saved,** per addon, in `mcp.json`: live watches (with their guard pictures' timestamps, and a reply watch's messages' timestamps), claims, leases, the outbox cursor, the last 1,000 applied op IDs, and the posts a later one may reply to (`posted`: op ID to chat pseudonym, timestamp and expiry). Anything expired is left out. At startup they are restored, leaving out a watch whose chat is no longer allowed or whose pattern no longer passes, so a restart of the bot or the addon never lets a match fall through to history. Refs, names, tombstones and held posts are in memory only. - **`groupctx`** (`GROUP_CONTEXT`, on by default) comes after `mcp`, so an earlier hook can claim a message (`Done`) before it is kept, and keeps each other unaddressed group message as context: `Name: text`, capped at 2,000 characters, with photos, stickers and files noted as `[image]`, `[sticker]` and `[file "name"]` but never fetched. The core keeps it like any history entry, marked as context, and never logs it. diff --git a/addon/schema.json b/addon/schema.json index 91d4989..bc9e216 100644 --- a/addon/schema.json +++ b/addon/schema.json @@ -99,6 +99,7 @@ "chat": {"description": "A post's or unwatch's chat.", "type": "string", "pattern": "^c_[a-z2-7]{26}$"}, "text": {"description": "A post's text, with {u_…} placeholders the bot fills in with names; at most 4000 characters, names filled in. A post with neither text nor images is dropped.", "type": "string"}, "images": {"description": "A post's images: at most 2, and 2 MiB in all.", "type": "array", "items": {"$ref": "#/$defs/Image"}, "maxItems": 2}, + "audio": {"description": "A post's clip to play, MP3, at most 2 MiB: sent with no title of its own. A post with audio is never merged with another.", "$ref": "#/$defs/Audio"}, "ref": {"description": "The message a reaction is for: a context's ref.", "type": "string", "pattern": "^r_[a-z2-7]{26}$"}, "emoji": {"description": "A reaction's: one emoji.", "type": "string", "minLength": 1}, "watch": {"description": "The ID of the watch an unwatch ends.", "type": "string", "minLength": 1, "maxLength": 64}, @@ -107,12 +108,22 @@ "required": ["id", "op"], "additionalProperties": false, "allOf": [ - {"if": {"properties": {"op": {"const": "post"}}}, "then": {"required": ["chat"], "anyOf": [{"required": ["text"], "properties": {"text": {"pattern": "\\S"}}}, {"required": ["images"], "properties": {"images": {"minItems": 1}}}]}}, + {"if": {"properties": {"op": {"const": "post"}}}, "then": {"required": ["chat"], "anyOf": [{"required": ["text"], "properties": {"text": {"pattern": "\\S"}}}, {"required": ["images"], "properties": {"images": {"minItems": 1}}}, {"required": ["audio"]}]}}, {"if": {"properties": {"op": {"const": "react"}}}, "then": {"required": ["ref", "emoji"]}}, {"if": {"properties": {"op": {"const": "unwatch"}}}, "then": {"required": ["chat", "watch"]}}, {"if": {"required": ["replyTo"]}, "then": {"properties": {"op": {"const": "post"}}}} ] }, + "Audio": { + "description": "A clip in a post, to play.", + "type": "object", + "properties": { + "data": {"description": "The MP3's bytes, in base64.", "type": "string", "minLength": 1, "contentEncoding": "base64"}, + "mimeType": {"type": "string", "const": "audio/mpeg"} + }, + "required": ["data", "mimeType"], + "additionalProperties": false + }, "Image": { "description": "An image in a post. The bot reads its bytes, whatever mimeType says.", "type": "object", diff --git a/addon/schema_test.go b/addon/schema_test.go index 4f5921e..a3fc029 100644 --- a/addon/schema_test.go +++ b/addon/schema_test.go @@ -51,6 +51,7 @@ var wireTypes = map[string]reflect.Type{ "ResultMeta": reflect.TypeFor[ResultMeta](), "Op": reflect.TypeFor[Op](), "Image": reflect.TypeFor[Image](), + "Audio": reflect.TypeFor[Audio](), "Page": reflect.TypeFor[Page](), "Held": reflect.TypeFor[Held](), @@ -423,6 +424,7 @@ func TestSchemaSamples(t *testing.T) { {"Result", Result{Content: []Content{{Type: "text", Text: "no"}}, IsError: true, Meta: &ResultMeta{React: "📍"}}}, {"Op", post}, {"Op", Op{ID: "2", Op: "post", Chat: chatID, Images: []Image{{Data: "aGk=", MimeType: "image/png", Name: "a.png"}}}}, + {"Op", Op{ID: "6", Op: "post", Chat: chatID, Audio: &Audio{Data: "SUQz", MimeType: "audio/mpeg"}}}, {"Op", Op{ID: "3", Op: "react", Ref: refID, Emoji: "🎯"}}, {"Op", Op{ID: "4", Op: "unwatch", Chat: chatID, Watch: "r1"}}, {"Op", Op{ID: "6", Op: "post", Chat: chatID, Text: "It was Paris.", ReplyTo: "a1b2.1"}}, @@ -470,6 +472,7 @@ func TestSchemaSamples(t *testing.T) { {"Op", "three images", Op{ID: "1", Op: "post", Chat: chatID, Images: slices.Repeat([]Image{{Data: "aGk=", MimeType: "image/png"}}, MaxImages+1)}}, {"Op", "an image without its type", map[string]any{"id": "1", "op": "post", "chat": chatID, "images": []any{map[string]any{"data": "aGk="}}}}, {"Op", "a reaction without an emoji", Op{ID: "1", Op: "react", Ref: refID}}, + {"Op", "audio that isn't MP3", Op{ID: "1", Op: "post", Chat: chatID, Audio: &Audio{Data: "T2dn", MimeType: "audio/ogg"}}}, {"Op", "a reaction to a chat", Op{ID: "1", Op: "react", Ref: chatID, Emoji: "🎯"}}, {"Op", "an unwatch without its watch", Op{ID: "1", Op: "unwatch", Chat: chatID}}, {"Op", "a group ID for a chat", Op{ID: "1", Op: "unwatch", Chat: "group.abc=", Watch: "r1"}}, diff --git a/addon/types.go b/addon/types.go index 0965f7c..7691d92 100644 --- a/addon/types.go +++ b/addon/types.go @@ -126,6 +126,14 @@ type Op struct { Emoji string `json:"emoji,omitempty"` // a reaction's Watch string `json:"watch,omitempty"` // the ID of the watch an unwatch ends ReplyTo string `json:"replyTo,omitempty"` // a post's: the ID of an earlier post of the addon's in the same chat, which it is sent as a reply to + Audio *Audio `json:"audio,omitempty"` // a post's: one clip to play, MP3, at most 2 MB +} + +// Audio is a clip in a post, sent to play, with no title of its own: on +// Telegram a voice message, on Signal an attachment named clip.mp3. +type Audio struct { + Data string `json:"data"` // base64 + MimeType string `json:"mimeType"` // "audio/mpeg" } // Image is an image in a post. diff --git a/docs/FILES_LINKS_TOOLS_MCP.md b/docs/FILES_LINKS_TOOLS_MCP.md index caaac46..73a65f9 100644 --- a/docs/FILES_LINKS_TOOLS_MCP.md +++ b/docs/FILES_LINKS_TOOLS_MCP.md @@ -146,7 +146,7 @@ Each permission is off unless set. For an addon, `chats`, `dms` and these permis - **Hidden tools.** A tool whose `_meta` says it is for the bot alone (`io.github.robdevops.signalbot/visibility` without `"model"`, or MCP Apps' `ui.visibility` without `"model"`) is never offered to the model or listed as one of its tools, so tools that read chat text stay out of its hands. - **Watches.** A direct command's answer can ask for a watch on its chat: a pattern, such as map links, until a time at most `watch_max` away. While it lasts, a message there that matches goes to the addon instead: it isn't answered, isn't sent to the model, and isn't kept in history, even as group context; so does an edit of it later. The addon may react to it, so people see it was counted. A pattern that would match ordinary chat ("lol", "see you at 5", a news link, …) is refused, so a watch can't become a feed of everything said; at most 8 run in a chat at once. While a watch lasts, a reply to the command's pictures, or to pictures the addon posts while it lasts, that asks the bot gets the addon's set answer (GeoGuess's "No hints during a round 😉"), not the model's. A reply watch (`"replies": true`) takes instead only replies to the addon's own messages in the chat while it lasts, the command's answer and its posts, that ask the bot, such as a quiz's free-text answers; its pattern, if it has one, must match them too, and isn't held to the ordinary-chat rule, since such a reply is meant for the addon. - **Model.** With `model`, an addon may ask the bot's model for text, through MCP's standard sampling request (`sampling/createMessage`): it sends the prompt, and the bot runs it on its own model, with its own key, and sends back the answer. The addon needs no key or provider of its own. The bot offers this only to an addon with `model`, and only while it has a model; MCP suggests a person approve each request, and here the `model` setting is that approval. Each request names the chat it is for, one the addon may post in now, and is charged to that chat's `DAILY_BUDGET`: one over its budget is refused, and so is one past `per_hour`. A request is text only, at most 16 messages and 32 KB, with one in flight per addon at a time. Only its outcome, time, size, tokens and cost are logged, never the prompt or the answer. -- **Outbox.** An addon posts when it likes by queueing posts, reactions and the end of a watch in its outbox, an MCP resource the bot subscribes to (`signalbot://outbox`), and saying it changed; the bot reads it at once. It may post or react only in a chat where it was used, by a command or a watch, in the last 24 hours, and only within `rate`. Its posts go through the chat's queue like any message, never more than one at a time, and history keeps them as the bot's, labelled with the addon's name (`[GeoGuess] …`), so what an addon writes never poses as a person. A post can be a reply to one of the addon's earlier posts in the same chat, named by that post's ID (`replyTo`), so a quiz can answer a question under it; the Go package's `QueueIDs` gives the IDs. The bot remembers the IDs of the addon's last 256 post ops for 24 hours (a merged post uses one for each op); a reply to one it doesn't know, or in another chat, goes as an ordinary post. A reply is always a message of its own, never merged with the addon's other posts. On Signal it quotes the post; on Telegram it replies to it, and goes anyway if the post was deleted. +- **Outbox.** An addon posts when it likes by queueing posts (text, up to 2 pictures, or one MP3 clip to play, which shows no title: a voice message on Telegram, `clip.mp3` on Signal), reactions and the end of a watch in its outbox, an MCP resource the bot subscribes to (`signalbot://outbox`), and saying it changed; the bot reads it at once. It may post or react only in a chat where it was used, by a command or a watch, in the last 24 hours, and only within `rate`. Its posts go through the chat's queue like any message, never more than one at a time, and history keeps them as the bot's, labelled with the addon's name (`[GeoGuess] …`), so what an addon writes never poses as a person. A post can be a reply to one of the addon's earlier posts in the same chat, named by that post's ID (`replyTo`), so a quiz can answer a question under it; the Go package's `QueueIDs` gives the IDs. The bot remembers the IDs of the addon's last 256 post ops for 24 hours (a merged post uses one for each op); a reply to one it doesn't know, or in another chat, goes as an ordinary post. A reply is always a message of its own, never merged with the addon's other posts. On Signal it quotes the post; on Telegram it replies to it, and goes anyway if the post was deleted. - **Settings.** An addon has no `env` block. It gets `PATH`, `HOME`, the bot's time zone (`TZ`) and proxy settings (`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, and `SSL_CERT_FILE` or `SSL_CERT_DIR` for a custom CA) if set, and every variable in the bot's environment (`/etc/signalbot.env`) that starts with its server's name in capitals, anything but letters and digits as `_`, then `_`: the server `geo` gets `GEO_STATE_DIR`, `GEO_MAPILLARY_TOKEN` and so on, and never the bot's own keys. A name whose prefix starts one of the bot's settings (such as `model`, `signal` or `mcp`) is a config error. An addon that keeps files takes its directory from `<PREFIX>STATE_DIR` (`GEO_STATE_DIR`) and creates it itself, mode 0700. Unless the bot's environment sets it, the bot sets it to `addons/<server name>` in the bot's state directory (`/var/lib/private/signalbot/addons/geo`, or `/data/addons/geo` in Docker), so an addon's files are kept with the bot's; it creates nothing there itself. With `STATE_DIRECTORY` unset, or a server name that isn't only letters, digits, `.`, `_` and `-` (up to 64, not starting with `.`), there is no default, and the addon falls back on its own. - **Logs.** The bot logs an addon's commands, calls and drops by name, outcome, time and size, never what was said. An addon's stderr is counted ("addon geo wrote 3 lines (210 bytes) to stderr", at most once a minute and once more when it exits), never logged, since it may echo a message. To debug an addon, run it on its own with stderr going to your own file. - **State.** The bot keeps an addon's watches, the messages they took, the chats it may post in, how far it has read its outbox and the posts a later one may reply to in `mcp.json`, so a restart of either doesn't lose a round. See [PRIVACY.md](../PRIVACY.md#addons). diff --git a/internal/bot/answer.go b/internal/bot/answer.go index 357740e..85833bb 100644 --- a/internal/bot/answer.go +++ b/internal/bot/answer.go @@ -75,7 +75,7 @@ func (b *Bot) respond(msg feature.Message, act feature.Action, text string, refs return case act.Answer != "" || len(act.Pictures) > 0: text, _ := captioned(act.Answer, act.Pictures) - sent := b.net.Send(msg.Chat, text, act.Pictures, b.chats.Names(msg.Chat.Key()), 0) + sent := b.net.Send(msg.Chat, text, act.Pictures, b.chats.Names(msg.Chat.Key()), 0, nil) if act.OnSent != nil { act.OnSent(sent, len(sent) == 0) } @@ -90,7 +90,7 @@ func (b *Bot) respond(msg feature.Message, act feature.Action, text string, refs if over, left := b.budget.over(key); over { if b.budget.markTold(key) { // once a day; then a ⏳ until midnight logx.Warnf("a chat reached its daily budget; it is answered again at midnight") - b.net.Send(msg.Chat, limitNotice(left), nil, b.chats.Names(key), 0) + b.net.Send(msg.Chat, limitNotice(left), nil, b.chats.Names(key), 0, nil) } else if msg.Timestamp != 0 { // a scheduled post can't be reacted to b.net.React(msg.Chat, msg, waiting) } @@ -109,7 +109,7 @@ func (b *Bot) respond(msg feature.Message, act feature.Action, text string, refs for { if act.ToolChoice != "" && !b.callsTools.Load() { stop() - b.net.Send(msg.Chat, noTools, nil, b.chats.Names(key), 0) + b.net.Send(msg.Chat, noTools, nil, b.chats.Names(key), 0, nil) return } if t = b.buildTurn(msg, text); t.empty(msg) { @@ -149,7 +149,7 @@ func (b *Bot) respond(msg feature.Message, act feature.Action, text string, refs if errors.Is(err, model.ErrTooManyRounds) { answer = tooManyRounds } - b.net.Send(msg.Chat, answer, nil, b.chats.Names(key), 0) + b.net.Send(msg.Chat, answer, nil, b.chats.Names(key), 0, nil) return } b.followUp(key, offered, msg.Text, reply.ToolsUsed) diff --git a/internal/bot/bot.go b/internal/bot/bot.go index 4951db4..ebe7dee 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -41,8 +41,9 @@ type Network interface { // a send that fails returns no timestamps. If replyTo isn't 0, the // first message sent replies to the bot's own message in chat that an // earlier Send returned it for; one the network can't find is sent - // without it. - Send(chat feature.Chat, text string, pics []feature.Picture, known map[string]string, replyTo int64) (sent []int64) + // without it. audio, if not nil, is one MP3 clip sent with the text, + // as audio to play, with no title of its own. + Send(chat feature.Chat, text string, pics []feature.Picture, known map[string]string, replyTo int64, audio []byte) (sent []int64) // React puts emoji on msg in chat, as a reaction from the bot. React(chat feature.Chat, msg feature.Message, emoji string) Typing(chat feature.Chat) (stop func()) @@ -245,7 +246,7 @@ func (b *Bot) pending() chats.Ref { // and returns Send's timestamps. History is kept first so a message // arriving while the send is out lands after the turn, not before it. func (b *Bot) sendKept(key string, p chats.Ref, chat feature.Chat, text string, pics []feature.Picture, known map[string]string) []int64 { - sent := b.net.Send(chat, text, pics, known, 0) + sent := b.net.Send(chat, text, pics, known, 0, nil) b.chats.Retag(key, p.ID, botRefs(sent)) return sent } diff --git a/internal/bot/fakes_test.go b/internal/bot/fakes_test.go index 3eec716..d16d2c0 100644 --- a/internal/bot/fakes_test.go +++ b/internal/bot/fakes_test.go @@ -91,7 +91,7 @@ func (n *fakeNet) WaitID(ctx context.Context) string { // Send returns one timestamp per call, counting up from 5000, or none // while fail is set. -func (n *fakeNet) Send(chat feature.Chat, text string, images []feature.Picture, known map[string]string, replyTo int64) []int64 { +func (n *fakeNet) Send(chat feature.Chat, text string, images []feature.Picture, known map[string]string, replyTo int64, audio []byte) []int64 { if n.fail.Load() { return nil } diff --git a/internal/bot/host.go b/internal/bot/host.go index cd185e9..63c8247 100644 --- a/internal/bot/host.go +++ b/internal/bot/host.go @@ -156,7 +156,7 @@ func (b *Bot) Deliver(msg feature.Message) { func (b *Bot) Post(p feature.Post) { p.OnSent = once(p.OnSent) switch { - case b.closing.Load(), p.Text == "" && len(p.Pictures) == 0: + case b.closing.Load(), p.Text == "" && len(p.Pictures) == 0 && len(p.Audio) == 0: p.OnSent(nil, true) default: b.post(Outgoing{Post: p}) @@ -188,14 +188,17 @@ func (b *Bot) say(p feature.Post) { } key := p.Chat.Key() text, kept := captioned(p.Text, p.Pictures) + if len(p.Audio) > 0 { + kept = strings.TrimSpace(kept + " [sent an audio clip]") + } if p.Label == "" || b.ai == nil { // with no model, nothing would read it - sent := b.net.Send(p.Chat, text, p.Pictures, b.chats.Names(key), p.ReplyTo) + sent := b.net.Send(p.Chat, text, p.Pictures, b.chats.Names(key), p.ReplyTo, p.Audio) p.OnSent(sent, len(sent) == 0) return } ref := b.pending() b.chats.Add(key, b.now(), 0, chats.Entry{Role: "assistant", Content: txt.Clamp("["+p.Label+"] "+kept, maxPostKept), Refs: []chats.Ref{ref}}) - sent := b.net.Send(p.Chat, text, p.Pictures, b.chats.Names(key), p.ReplyTo) + sent := b.net.Send(p.Chat, text, p.Pictures, b.chats.Names(key), p.ReplyTo, p.Audio) if len(sent) == 0 { b.chats.Withdraw(key, ref.ID) // the chat never saw it, and it may be posted again } else { @@ -273,7 +276,7 @@ func (b *Bot) event(e feature.Event) { for _, p := range people { chats.Claim(known, p.Name, p.ID) } - b.net.Send(e.Chat, reply, nil, known, 0) + b.net.Send(e.Chat, reply, nil, known, 0, nil) return } } diff --git a/internal/feature/feature.go b/internal/feature/feature.go index b86be68..35a0be2 100644 --- a/internal/feature/feature.go +++ b/internal/feature/feature.go @@ -219,6 +219,7 @@ type Post struct { Label string // history keeps the post as the bot's, as "[Label] text"; "" keeps nothing Text string // Markdown, as written; @Name is linked to the chat's known names Pictures []Picture // sent with Text; captions as for a tool's pictures + Audio []byte // one MP3 clip sent with Text, as audio to play, with no title OnSent func(sent []int64, dropped bool) // if set, called once: with the timestamps sent, or dropped ReplyTo int64 // if set, sent as a reply to the bot's own earlier message in Chat that an OnSent gave this timestamp; sent plainly if the network can't find it } diff --git a/internal/features/mcp/outbox.go b/internal/features/mcp/outbox.go index 0f77408..f9b97a8 100644 --- a/internal/features/mcp/outbox.go +++ b/internal/features/mcp/outbox.go @@ -3,6 +3,7 @@ package mcp import ( "cmp" "context" + "encoding/base64" "encoding/json" "errors" "fmt" @@ -286,8 +287,15 @@ func (a *addon) post(o ext.Op, again bool) (why string) { } out := &outgoing{Post: feature.Post{Chat: l.Chat, Label: a.title, Text: txt.Clamp(a.fill(l.Chat, strings.TrimSpace(o.Text)), maxAnswer), Pictures: a.pictures(b64)}, ops: []string{o.ID}, replyTo: o.ReplyTo} + if o.Audio != nil { + clip, err := base64.StdEncoding.DecodeString(o.Audio.Data) + if err != nil || o.Audio.MimeType != "audio/mpeg" || len(clip) == 0 || len(clip) > maxPictureBytes { + return "audio that isn't an MP3 of at most 2 MB" + } + out.Audio = clip + } switch { - case out.Text == "" && len(out.Pictures) == 0: + case out.Text == "" && len(out.Pictures) == 0 && len(out.Audio) == 0: return "empty posts" case !again && !a.posts.allow(l.Chat.Key(), now): return "posts over the rate limit" @@ -309,8 +317,8 @@ type outgoing struct { // A reply joins no other post, and none joins it, so it stays a message // of its own and a later post a new one. func (o *outgoing) fits(p *outgoing) bool { - if o.replyTo != "" || p.replyTo != "" { - return false + if o.replyTo != "" || p.replyTo != "" || len(o.Audio) > 0 || len(p.Audio) > 0 { + return false // a reply, or a clip, is a message of its own } size := 0 for _, pic := range append(slices.Clone(o.Pictures), p.Pictures...) { diff --git a/internal/features/mcp/watch_test.go b/internal/features/mcp/watch_test.go index f259a43..a506930 100644 --- a/internal/features/mcp/watch_test.go +++ b/internal/features/mcp/watch_test.go @@ -5,6 +5,7 @@ import ( "bytes" "cmp" "context" + "encoding/base64" "encoding/json" "fmt" "os" @@ -1179,3 +1180,38 @@ func TestGuardPosted(t *testing.T) { t.Errorf("pictures %v", w.Pictures) } } + +// A post's audio clip reaches the chat as its own message, never merged; +// one that isn't an MP3 of at most 2 MB is dropped. +func TestOutboxAudio(t *testing.T) { + cfg := everything + cfg.Rate = rateConfig{6000, 1000} + a, _ := unitAddon(cfg) + h := featuretest.New() + a.host = h + a.lease(inA) + id := a.chatID(inA) + clip := base64.StdEncoding.EncodeToString([]byte("ID3 clip")) + for _, o := range []ext.Op{ + {ID: "1", Op: "post", Chat: id, Text: "first"}, + {ID: "2", Op: "post", Chat: id, Text: "🎵 Song 1", Audio: &ext.Audio{Data: clip, MimeType: "audio/mpeg"}}, + {ID: "3", Op: "post", Chat: id, Text: "after"}, + } { + if why := a.apply(o); why != "" { + t.Fatalf("%s: %s", o.ID, why) + } + } + for i := 0; i < len(h.Posts()); i++ { + h.Posts()[i].OnSent([]int64{int64(i + 1)}, false) + } + posts := h.Posts() + if len(posts) != 3 || string(posts[1].Audio) != "ID3 clip" || posts[1].Text != "🎵 Song 1" || len(posts[2].Audio) != 0 { + t.Fatalf("posts %+v", posts) + } + for _, bad := range []*ext.Audio{{Data: clip, MimeType: "audio/ogg"}, {Data: "!!", MimeType: "audio/mpeg"}, + {Data: base64.StdEncoding.EncodeToString(make([]byte, maxPictureBytes+1)), MimeType: "audio/mpeg"}} { + if why := a.apply(ext.Op{ID: "x" + bad.MimeType + bad.Data[:2], Op: "post", Chat: id, Audio: bad}); why == "" { + t.Errorf("audio %s taken", bad.MimeType) + } + } +} diff --git a/internal/signal/client_test.go b/internal/signal/client_test.go index 6c6dff8..d681c37 100644 --- a/internal/signal/client_test.go +++ b/internal/signal/client_test.go @@ -280,10 +280,10 @@ func TestSendAndTyping(t *testing.T) { run(t, c, f) group, dm := feature.Chat{GroupID: groupID}, feature.Chat{User: aliceID} png := []byte("\x89PNG\r\n\x1a\n") - if ts := c.Send(group, "@signalbot hi @Alice", []feature.Picture{{Data: png, Name: "NVDA vs AMD, 1 month"}, {Data: png}}, map[string]string{"alice": aliceID}, 0); !slices.Equal(ts, []int64{1001}) { + if ts := c.Send(group, "@signalbot hi @Alice", []feature.Picture{{Data: png, Name: "NVDA vs AMD, 1 month"}, {Data: png}}, map[string]string{"alice": aliceID}, 0, nil); !slices.Equal(ts, []int64{1001}) { t.Fatalf("sent %v", ts) } - c.Send(dm, "plain @Alice", nil, nil, 0) + c.Send(dm, "plain @Alice", nil, nil, 0, nil) eventually(t, "two sends", func() bool { return len(f.calls("send")) == 2 }) s := f.calls("send") if s[0]["groupId"] != groupID || s[0]["message"] != "hi @Alice" || fmt.Sprint(s[0]["mention"]) != "[3:6:"+aliceID+"]" || @@ -297,7 +297,7 @@ func TestSendAndTyping(t *testing.T) { t.Errorf("a plain send quotes: %v", s) } // A reply quotes the bot's own message by its timestamp. - c.Send(group, "the answer", nil, nil, 1001) + c.Send(group, "the answer", nil, nil, 1001, nil) eventually(t, "the reply", func() bool { return len(f.calls("send")) == 3 }) if r := f.calls("send")[2]; r["quoteTimestamp"] != float64(1001) || r["quoteAuthor"] != botID || r["message"] != "the answer" || r["groupId"] != groupID { t.Errorf("reply send %v", r) @@ -475,11 +475,11 @@ func TestSendResults(t *testing.T) { f := newFake(t) c := newClient(f.sock, nil, nil) run(t, c, f) - if ts := c.Send(feature.Chat{User: aliceID}, strings.Repeat("word ", 500), nil, nil, 0); len(ts) != 1 { + if ts := c.Send(feature.Chat{User: aliceID}, strings.Repeat("word ", 500), nil, nil, 0, nil); len(ts) != 1 { t.Fatalf("a long reply returned %v", ts) } f.set("send", `{"timestamp":77,"results":[{"type":"NETWORK_FAILURE"}]}`) - if ts := c.Send(feature.Chat{User: aliceID}, "hi", nil, nil, 0); !slices.Equal(ts, []int64{77}) { + if ts := c.Send(feature.Chat{User: aliceID}, "hi", nil, nil, 0, nil); !slices.Equal(ts, []int64{77}) { t.Fatalf("returned %v", ts) } if !strings.Contains(logs.String(), "signal-cli send not delivered: NETWORK_FAILURE") { diff --git a/internal/signal/markdown_test.go b/internal/signal/markdown_test.go index afa6844..4f8e63b 100644 --- a/internal/signal/markdown_test.go +++ b/internal/signal/markdown_test.go @@ -84,7 +84,7 @@ func TestSendStyles(t *testing.T) { f := newFake(t) c := newClient(f.sock, nil, nil) run(t, c, f) - c.Send(feature.Chat{User: aliceID}, "**\U0001F389 big** news, @Alice: see `x`", nil, map[string]string{"alice": "u-a"}, 0) + c.Send(feature.Chat{User: aliceID}, "**\U0001F389 big** news, @Alice: see `x`", nil, map[string]string{"alice": "u-a"}, 0, nil) eventually(t, "a send", func() bool { return len(f.calls("send")) == 1 }) s := f.calls("send")[0] if s["message"] != "\U0001F389 big news, @Alice: see x" { @@ -96,7 +96,7 @@ func TestSendStyles(t *testing.T) { if got := fmt.Sprint(s["mention"]); got != "[13:6:u-a]" { t.Errorf("mentions %v", got) } - c.Send(feature.Chat{User: aliceID}, "plain", nil, nil, 0) + c.Send(feature.Chat{User: aliceID}, "plain", nil, nil, 0, nil) eventually(t, "a second send", func() bool { return len(f.calls("send")) == 2 }) if _, ok := f.calls("send")[1]["textStyle"]; ok { t.Errorf("styles on plain text") diff --git a/internal/signal/send.go b/internal/signal/send.go index 3154982..ae91607 100644 --- a/internal/signal/send.go +++ b/internal/signal/send.go @@ -37,7 +37,7 @@ func (c *Client) Prompt() string { // Name or else image_<local time>, quoting the bot's own message sent at // replyTo if it isn't 0. A failure is logged, as is a message signal-cli // says it could not deliver. -func (c *Client) Send(chat feature.Chat, text string, pics []feature.Picture, known map[string]string, replyTo int64) (sent []int64) { +func (c *Client) Send(chat feature.Chat, text string, pics []feature.Picture, known map[string]string, replyTo int64, audio []byte) (sent []int64) { if n := utf8.RuneCountInString(text); n > maxReply { logx.Warnf("reply truncated from %d chars", n) } @@ -57,6 +57,9 @@ func (c *Client) Send(chat feature.Chat, text string, pics []feature.Picture, kn mime, name, strings.TrimPrefix(mime, "image/"), base64.StdEncoding.EncodeToString(p.Data))) kept = append(kept, attachment{ContentType: mime, Filename: name + "." + strings.TrimPrefix(mime, "image/"), Size: len(p.Data), data: p.Data}) } + if len(audio) > 0 { // named plainly, so the file gives nothing away + attachments = append(attachments, "data:audio/mpeg;filename=clip.mp3;base64,"+base64.StdEncoding.EncodeToString(audio)) + } msg, ok := prepare(text, c.BotName()) if id := c.self(); id != "" && chat.GroupID != "" { // in a group, "@" and its own name mentions the bot k := maps.Clone(known) diff --git a/internal/signal/send_test.go b/internal/signal/send_test.go index a7f4c1d..8201d17 100644 --- a/internal/signal/send_test.go +++ b/internal/signal/send_test.go @@ -17,7 +17,7 @@ func TestSendOneMessageAndCaps(t *testing.T) { c := newClient(f.sock, nil, nil) run(t, c, f) dm := feature.Chat{User: aliceID} - c.Send(dm, strings.Repeat("z ", 6000), []feature.Picture{{Data: []byte("PNG")}}, nil, 0) + c.Send(dm, strings.Repeat("z ", 6000), []feature.Picture{{Data: []byte("PNG")}}, nil, 0, nil) eventually(t, "a send", func() bool { return len(f.calls("send")) == 1 }) if s := f.calls("send")[0]; s["attachments"] == nil || len([]rune(s["message"].(string))) != maxReply || !strings.HasSuffix(s["message"].(string), "[…truncated]") { t.Errorf("send %d chars, attachments %v", len([]rune(fmt.Sprint(s["message"]))), s["attachments"] != nil) @@ -25,13 +25,13 @@ func TestSendOneMessageAndCaps(t *testing.T) { if !strings.Contains(logs.String(), "reply truncated from 12000 chars") { t.Errorf("logs %q", logs) } - c.Send(dm, " ", nil, nil, 0) - c.Send(dm, "", []feature.Picture{{Data: []byte("PNG")}}, nil, 0) + c.Send(dm, " ", nil, nil, 0, nil) + c.Send(dm, "", []feature.Picture{{Data: []byte("PNG")}}, nil, 0, nil) eventually(t, "the pictures alone", func() bool { return len(f.calls("send")) == 2 }) if s := f.calls("send")[1]; s["message"] != "" || s["attachments"] == nil { t.Errorf("pictures sent as %v", s) } - newClient("x", nil, nil).Send(dm, "secret words", nil, nil, 0) + newClient("x", nil, nil).Send(dm, "secret words", nil, nil, 0, nil) if out := logs.String(); !strings.Contains(out, "empty reply, nothing sent") || !strings.Contains(out, "send failed: not connected") || strings.Contains(out, "secret") { t.Errorf("logs %q", out) } @@ -70,3 +70,17 @@ func TestFileName(t *testing.T) { } } } + +// An audio clip goes as an MP3 attachment named only clip.mp3, so its file +// gives nothing away. +func TestSendAudio(t *testing.T) { + f := newFake(t) + c := newClient(f.sock, nil, nil) + run(t, c, f) + c.Send(feature.Chat{User: aliceID}, "🎵 Song 1", nil, nil, 0, []byte("ID3 clip")) + eventually(t, "a send", func() bool { return len(f.calls("send")) == 1 }) + att, _ := f.calls("send")[0]["attachments"].([]any) + if len(att) != 1 || att[0] != "data:audio/mpeg;filename=clip.mp3;base64,SUQzIGNsaXA=" { + t.Errorf("attachments %v", att) + } +} diff --git a/internal/telegram/client.go b/internal/telegram/client.go index 733640b..dcffd2a 100644 --- a/internal/telegram/client.go +++ b/internal/telegram/client.go @@ -122,7 +122,11 @@ func (c *Client) upload(ctx context.Context, method string, fields map[string]st w.WriteField(k, v) } for name, data := range files { - fw, err := w.CreateFormFile(name, name+".png") + ext := ".png" // pictures are sent as PNG; a voice message is MP3 + if name == "voice" { + ext = ".mp3" + } + fw, err := w.CreateFormFile(name, name+ext) if err != nil { return err } diff --git a/internal/telegram/send.go b/internal/telegram/send.go index 81c7dfe..d801559 100644 --- a/internal/telegram/send.go +++ b/internal/telegram/send.go @@ -51,7 +51,7 @@ type sentMsg struct { // their caption when it fits, the first message a reply to the bot's own // message replyTo if it isn't 0 (sent anyway if that message is gone). It // returns the IDs of the messages sent. A failure is logged. -func (c *Client) Send(ch feature.Chat, text string, pics []feature.Picture, known map[string]string, replyTo int64) (sent []int64) { +func (c *Client) Send(ch feature.Chat, text string, pics []feature.Picture, known map[string]string, replyTo int64, audio []byte) (sent []int64) { if n := utf8.RuneCountInString(text); n > maxReply { logx.Warnf("reply truncated from %d chars", n) } @@ -86,8 +86,16 @@ func (c *Client) Send(ch feature.Chat, text string, pics []feature.Picture, know note(i) } } + if len(audio) > 0 { // a voice message: it shows no title or performer + id, err := c.sendVoice(ctx, ch, audio, replyTo) + if err != nil { + logx.Errorf("send failed: audio: %v", err) // the text still goes + } else { + note(id) + } + } parts := mdstyle.Split(t, maxChars) - if len(parts) == 0 && len(pics) == 0 { + if len(parts) == 0 && len(pics) == 0 && len(audio) == 0 { logx.Warnf("empty reply, nothing sent") return nil } @@ -276,6 +284,22 @@ func (c *Client) sendPhotosOnce(ctx context.Context, ch feature.Chat, pics []fea return ids, nil } +// sendVoice sends audio, an MP3 clip, as a voice message, which plays in +// the chat and shows no title or performer, and returns its message ID. +func (c *Client) sendVoice(ctx context.Context, ch feature.Chat, audio []byte, replyTo int64) (int64, error) { + d := c.dest(ch) + fields := d.fields(map[string]string{}) + if replyTo != 0 { + rj, _ := json.Marshal(replyParams(replyTo)) + fields["reply_parameters"] = string(rj) + } + var m sentMsg + err := c.retrying(ctx, d.chat, func(to string) { fields["chat_id"] = to }, func() error { + return c.upload(ctx, "sendVoice", fields, map[string][]byte{"voice": audio}, &m) + }) + return m.MessageID, err +} + // React puts emoji on msg, as a reaction from the bot. Telegram allows only // some emoji as reactions, so one it refuses as such is sent as a message // instead. @@ -289,7 +313,7 @@ func (c *Client) React(ch feature.Chat, msg feature.Message, emoji string) { switch { case err == nil: case errors.As(err, &ae) && ae.Code == 400 && strings.Contains(ae.Desc, "REACTION_INVALID"): - c.Send(ch, emoji, nil, nil, 0) + c.Send(ch, emoji, nil, nil, 0, nil) default: logx.Errorf("reaction failed: %v", err) } diff --git a/internal/telegram/telegram_test.go b/internal/telegram/telegram_test.go index 5a832a3..4cddf9a 100644 --- a/internal/telegram/telegram_test.go +++ b/internal/telegram/telegram_test.go @@ -296,7 +296,7 @@ func TestEdits(t *testing.T) { func TestSend(t *testing.T) { f := newFake(t) c := connected(f.client()) - ids := c.Send(feature.Chat{GroupID: groupS}, "🎉 **big** news, see [docs](https://x.example) and @Alice", nil, map[string]string{"alice": "1111111"}, 0) + ids := c.Send(feature.Chat{GroupID: groupS}, "🎉 **big** news, see [docs](https://x.example) and @Alice", nil, map[string]string{"alice": "1111111"}, 0, nil) if !reflect.DeepEqual(ids, []int64{500}) { t.Fatalf("ids %v", ids) } @@ -309,7 +309,7 @@ func TestSend(t *testing.T) { if string(got) != want { t.Fatalf("entities\n got %s\n want %s", got, want) } - c.Send(feature.Chat{User: "1111111"}, strings.Repeat("word ", 1700), nil, nil, 0) + c.Send(feature.Chat{User: "1111111"}, strings.Repeat("word ", 1700), nil, nil, 0, nil) if n := len(f.callsTo("sendMessage")); n != 3 { // 8500 chars, capped at 8000: two messages t.Fatalf("a long reply in %d messages", n-1) } @@ -320,7 +320,7 @@ func TestSend(t *testing.T) { } // Entities Telegram refuses: the text alone. f.errs["sendMessage"] = `{"ok":false,"error_code":400,"description":"Bad Request: can't parse entities"}` - if ids := c.Send(feature.Chat{User: "1111111"}, "**x**", nil, nil, 0); len(ids) != 1 { + if ids := c.Send(feature.Chat{User: "1111111"}, "**x**", nil, nil, 0, nil); len(ids) != 1 { t.Fatalf("fallback ids %v", ids) } if last := f.callsTo("sendMessage"); last[len(last)-1].Params["entities"] != nil || last[len(last)-1].Params["text"] != "x" { @@ -336,14 +336,14 @@ func TestSendPictures(t *testing.T) { f.results["sendMediaGroup"] = `[{"message_id":602},{"message_id":603}]` c := connected(f.client()) png := []byte("\x89PNG\r\n\x1a\nxx") - if ids := c.Send(feature.Chat{User: "1111111"}, "NVDA ▼ 15.2%", []feature.Picture{{Data: png}}, nil, 0); !reflect.DeepEqual(ids, []int64{601}) { + if ids := c.Send(feature.Chat{User: "1111111"}, "NVDA ▼ 15.2%", []feature.Picture{{Data: png}}, nil, 0, nil); !reflect.DeepEqual(ids, []int64{601}) { t.Fatalf("ids %v", ids) } ph := f.callsTo("sendPhoto")[0] if ph.Params["caption"] != "NVDA ▼ 15.2%" || string(ph.Files["p0"]) != string(png) || len(f.callsTo("sendMessage")) != 0 { t.Fatalf("photo %v", ph.Params) } - if ids := c.Send(feature.Chat{GroupID: groupS}, "", []feature.Picture{{Data: png}, {Data: png}}, nil, 0); !reflect.DeepEqual(ids, []int64{602, 603}) { + if ids := c.Send(feature.Chat{GroupID: groupS}, "", []feature.Picture{{Data: png}, {Data: png}}, nil, 0, nil); !reflect.DeepEqual(ids, []int64{602, 603}) { t.Fatalf("album ids %v", ids) } if mg := f.callsTo("sendMediaGroup")[0]; len(mg.Files) != 2 || !strings.Contains(mg.Params["media"].(string), `"attach://p1"`) { @@ -358,7 +358,7 @@ func TestSendReply(t *testing.T) { f := newFake(t) f.results["sendPhoto"] = `{"message_id":601}` c := connected(f.client()) - c.Send(feature.Chat{GroupID: groupS}, strings.Repeat("word ", 1700), nil, nil, 42) + c.Send(feature.Chat{GroupID: groupS}, strings.Repeat("word ", 1700), nil, nil, 42, nil) msgs := f.callsTo("sendMessage") if len(msgs) != 2 { t.Fatalf("%d messages", len(msgs)) @@ -370,14 +370,14 @@ func TestSendReply(t *testing.T) { t.Errorf("second part replies too: %v", msgs[1].Params["reply_parameters"]) } png := []byte("\x89PNG\r\n\x1a\nxx") - c.Send(feature.Chat{User: "1111111"}, strings.Repeat("x", maxCaption+1), []feature.Picture{{Data: png}}, nil, 43) + c.Send(feature.Chat{User: "1111111"}, strings.Repeat("x", maxCaption+1), []feature.Picture{{Data: png}}, nil, 43, nil) if ph := f.callsTo("sendPhoto")[0]; ph.Params["reply_parameters"] != `{"allow_sending_without_reply":true,"message_id":43}` { t.Errorf("photo's reply_parameters %v", ph.Params["reply_parameters"]) } if msgs := f.callsTo("sendMessage"); len(msgs) != 3 || msgs[2].Params["reply_parameters"] != nil { t.Errorf("the text after the photo replies too: %v", msgs[len(msgs)-1].Params) } - c.Send(feature.Chat{User: "1111111"}, "plain", nil, nil, 0) + c.Send(feature.Chat{User: "1111111"}, "plain", nil, nil, 0, nil) if msgs := f.callsTo("sendMessage"); msgs[len(msgs)-1].Params["reply_parameters"] != nil { t.Errorf("a plain send replies: %v", msgs[len(msgs)-1].Params) } @@ -468,7 +468,7 @@ func TestTokenNeverLogged(t *testing.T) { ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) defer cancel() c.Run(ctx, func(bot.Received) {}) - c.Send(feature.Chat{User: "1"}, "hi", nil, nil, 0) + c.Send(feature.Chat{User: "1"}, "hi", nil, nil, 0, nil) out := logs.String() if !strings.Contains(out, "getMe failed") || !strings.Contains(out, "send failed") || strings.Contains(out, "SECRET") { t.Fatalf("logs %q", out) @@ -559,8 +559,8 @@ func TestEvents(t *testing.T) { t.Fatal("an event with no hook") } c.Watch(bot.Watch{Events: true}) - c.groupAllowed(context.Background(), groupS) // Alice is in it - c.Send(feature.Chat{GroupID: groupS}, "hello", nil, nil, 0) // message 500, the bot's + c.groupAllowed(context.Background(), groupS) // Alice is in it + c.Send(feature.Chat{GroupID: groupS}, "hello", nil, nil, 0, nil) // message 500, the bot's r, _ := c.event(parse(t, `{"update_id":2,"message_reaction":{`+inGroup+`,"message_id":500,"user":{"id":1111111,"first_name":"Alice"},"old_reaction":[{"type":"emoji","emoji":"👍"}],"new_reaction":[]}}`)) e := r.(bot.Happened).Event if e.Reaction == nil || e.Reaction.Emoji != "👍" || !e.Reaction.Removed || !e.Reaction.Bot || e.By.ID != "1111111" || e.Reaction.Sent != 500 { @@ -640,14 +640,14 @@ func TestSendPicturesFail(t *testing.T) { c := connected(f.client()) png := []byte("\x89PNG\r\n\x1a\nxx") f.errs["sendPhoto"] = `{"ok":false,"error_code":400,"description":"Bad Request: PHOTO_INVALID_DIMENSIONS"}` - if ids := c.Send(feature.Chat{User: "1111111"}, "**the** caption", []feature.Picture{{Data: png}}, nil, 0); !reflect.DeepEqual(ids, []int64{500}) { + if ids := c.Send(feature.Chat{User: "1111111"}, "**the** caption", []feature.Picture{{Data: png}}, nil, 0, nil); !reflect.DeepEqual(ids, []int64{500}) { t.Fatalf("ids %v", ids) } if s := f.callsTo("sendMessage"); len(s) != 1 || s[0].Params["text"] != "the caption" { t.Fatalf("text %v", s) } f.errs["sendPhoto"] = `{"ok":false,"error_code":400,"description":"Bad Request: can't parse entities"}` - if ids := c.Send(feature.Chat{User: "1111111"}, "**the** caption", []feature.Picture{{Data: png}}, nil, 0); !reflect.DeepEqual(ids, []int64{601}) { + if ids := c.Send(feature.Chat{User: "1111111"}, "**the** caption", []feature.Picture{{Data: png}}, nil, 0, nil); !reflect.DeepEqual(ids, []int64{601}) { t.Fatalf("ids %v", ids) } ph := f.callsTo("sendPhoto") @@ -664,12 +664,12 @@ func TestSendRetries(t *testing.T) { c := connected(f.client()) f.errs["sendMessage"] = `{"ok":false,"error_code":429,"description":"Too Many Requests","parameters":{"retry_after":1}}` start := time.Now() - if ids := c.Send(feature.Chat{GroupID: groupS}, "hi", nil, nil, 0); !reflect.DeepEqual(ids, []int64{500}) || time.Since(start) < time.Second { + if ids := c.Send(feature.Chat{GroupID: groupS}, "hi", nil, nil, 0, nil); !reflect.DeepEqual(ids, []int64{500}) || time.Since(start) < time.Second { t.Fatalf("ids %v after %s", ids, time.Since(start)) } f.errs["sendMessage"] = `{"ok":false,"error_code":400,"description":"Bad Request: group chat was upgraded to a supergroup chat","parameters":{"migrate_to_chat_id":-1009999999999}}` - c.Send(feature.Chat{GroupID: "-4444444"}, "one", nil, nil, 0) - c.Send(feature.Chat{GroupID: "-4444444"}, "two", nil, nil, 0) + c.Send(feature.Chat{GroupID: "-4444444"}, "one", nil, nil, 0, nil) + c.Send(feature.Chat{GroupID: "-4444444"}, "two", nil, nil, 0, nil) var to []any for _, s := range f.callsTo("sendMessage")[2:] { to = append(to, s.Params["chat_id"]) @@ -709,7 +709,7 @@ func TestTopics(t *testing.T) { if m.Quote != nil || m.Text != "hi" { t.Fatalf("message %+v", m) } - c.Send(in.Chat, "hello", nil, nil, 0) + c.Send(in.Chat, "hello", nil, nil, 0, nil) if s := f.callsTo("sendMessage")[0].Params; s["chat_id"] != groupS || s["message_thread_id"] != float64(7) { t.Fatalf("sent %v", s) } @@ -739,7 +739,7 @@ func TestMigration(t *testing.T) { if gs, _ := c.Groups(context.Background(), "1111111"); len(gs) != 1 || gs[0].ID != "-1009999999999" { t.Fatalf("groups %v", gs) } - c.Send(feature.Chat{GroupID: "-4444444"}, "scheduled", nil, nil, 0) + c.Send(feature.Chat{GroupID: "-4444444"}, "scheduled", nil, nil, 0, nil) if s := f.callsTo("sendMessage")[0].Params; s["chat_id"] != "-1009999999999" { t.Fatalf("sent to %v", s["chat_id"]) } @@ -818,3 +818,22 @@ func TestEventsAfterExpiry(t *testing.T) { } waitCalls(t, f, "getChatMember", 1) } + +// An audio clip goes as a voice message, which shows no title, before the +// text, and it is the one that replies. +func TestSendVoice(t *testing.T) { + f := newFake(t) + f.results["sendVoice"] = `{"message_id":701}` + c := connected(f.client()) + ids := c.Send(feature.Chat{GroupID: groupS}, "🎵 Song 1", nil, nil, 42, []byte("ID3 clip")) + v := f.callsTo("sendVoice") + if len(v) != 1 || v[0].Params["reply_parameters"] != `{"allow_sending_without_reply":true,"message_id":42}` { + t.Fatalf("sendVoice %+v", v) + } + if msgs := f.callsTo("sendMessage"); len(msgs) != 1 || msgs[0].Params["reply_parameters"] != nil { + t.Errorf("the text %+v", msgs) + } + if len(ids) != 2 || ids[0] != 701 { + t.Errorf("ids %v", ids) + } +} From fe518917ad74dba7256a1fd2b4688031c88275d4 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sun, 22 Nov 2026 06:04:08 +0000 Subject: [PATCH 24/26] Watches can take reactions to the addon's own messages A watch with reactions also takes reactions put on, or taken off, the command's answer and the addon's posts while it lives: each a call of its tool with {reaction, removed} and the reactor's context, through the watch worker, as matched messages are. The bot offers watchReactions. For games whose players join by reacting to the intro. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- addon/schema.json | 6 ++-- addon/server.go | 10 ++++++ addon/types.go | 12 +++++-- docs/FILES_LINKS_TOOLS_MCP.md | 2 +- internal/features/mcp/mcp.go | 10 +++++- internal/features/mcp/watch.go | 56 ++++++++++++++++++++++++++--- internal/features/mcp/watch_test.go | 44 ++++++++++++++++++++++- 7 files changed, 127 insertions(+), 13 deletions(-) diff --git a/addon/schema.json b/addon/schema.json index bc9e216..88a3c10 100644 --- a/addon/schema.json +++ b/addon/schema.json @@ -10,7 +10,8 @@ "properties": { "version": {"description": "The extension's version.", "const": 1}, "network": {"description": "The bot's chat network, as it names itself.", "type": "string", "examples": ["signal", "telegram"]}, - "watchReplies": {"description": "The bot's: it takes a watch with replies. A bot without it refuses one.", "type": "boolean"} + "watchReplies": {"description": "The bot's: it takes a watch with replies. A bot without it refuses one.", "type": "boolean"}, + "watchReactions": {"description": "The bot's: it takes a watch with reactions.", "type": "boolean"} }, "required": ["version"] }, @@ -50,7 +51,8 @@ "until": {"description": "An RFC 3339 time, in the future.", "type": "string", "format": "date-time"}, "tool": {"description": "A tool for the bot, called with each message the watch takes, as {\"text\": …}, with its context.", "type": "string", "minLength": 1}, "guard": {"description": "While the watch lasts, the answer to a message addressed to the bot that replies to the command's pictures; at most 500 characters.", "type": "string", "maxLength": 500}, - "replies": {"description": "Take only messages in the chat that reply to the command's answer or to the addon's posts there while the watch lives. Only for a bot whose capability has watchReplies; the bot doesn't check such a pattern against ordinary chat.", "type": "boolean"} + "replies": {"description": "Take only messages in the chat that reply to the command's answer or to the addon's posts there while the watch lives. Only for a bot whose capability has watchReplies; the bot doesn't check such a pattern against ordinary chat.", "type": "boolean"}, + "reactions": {"description": "Also take reactions put on, or taken off, the command's answer and the addon's posts in the chat while the watch lives: each a call of tool with {\"reaction\": emoji, \"removed\": bool} and the reactor's context. Only for a bot whose capability has watchReactions. On Telegram the bot sees reactions only as a group's admin.", "type": "boolean"} }, "required": ["id", "until", "tool"], "additionalProperties": false, diff --git a/addon/server.go b/addon/server.go index fa45e3f..23a796e 100644 --- a/addon/server.go +++ b/addon/server.go @@ -55,6 +55,7 @@ type Server struct { network string sampling bool // the bot offered sampling in initialize watchReplies bool // the bot takes a watch with Replies + watchReacts bool // the bot takes a watch with Reactions subscribed bool outbox []held // ops the bot hasn't read past, oldest first seq int64 // the last op's sequence number @@ -139,6 +140,14 @@ func (s *Server) WatchReplies() bool { return s.watchReplies } +// WatchReactions reports whether the bot said in initialize that it takes +// a watch with Reactions. +func (s *Server) WatchReactions() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.watchReacts +} + // BotError is the bot's error answer to a request of the addon's, such as // a sampling request it refused. type BotError struct { @@ -630,6 +639,7 @@ func (s *Server) methods() map[string]handler { s.mu.Lock() s.network = addon.Network s.watchReplies = addon.WatchReplies + s.watchReacts = addon.WatchReactions s.sampling = p.Capabilities.Sampling != nil s.mu.Unlock() r := initializeResult{ProtocolVersion: Protocol, ServerInfo: serverInfo{Name: s.cfg.Name, Title: s.cfg.Title, Version: s.cfg.Version}} diff --git a/addon/types.go b/addon/types.go index 7691d92..50ccc8f 100644 --- a/addon/types.go +++ b/addon/types.go @@ -42,9 +42,10 @@ const ( // KeyAddon. The bot offers its chat network and what it can do; an addon // answers with the version alone. type Capability struct { - Version int `json:"version"` - Network string `json:"network,omitempty"` // the bot's chat network, as it names itself: "signal", "telegram" - WatchReplies bool `json:"watchReplies,omitempty"` // the bot's: it takes a watch with Replies + Version int `json:"version"` + Network string `json:"network,omitempty"` // the bot's chat network, as it names itself: "signal", "telegram" + WatchReplies bool `json:"watchReplies,omitempty"` // the bot's: it takes a watch with Replies + WatchReactions bool `json:"watchReactions,omitempty"` // the bot's: it takes a watch with Reactions } // Context is the message a call the bot makes came from, in the call's @@ -76,6 +77,11 @@ type Watch struct { Tool string `json:"tool"` // called with each message it matches, as {"text": …} Guard string `json:"guard,omitempty"` // the answer, while it lasts, to a message addressed to the bot that quotes the command's pictures Replies bool `json:"replies,omitempty"` // only replies to the command's answer and the addon's posts in the chat while it lives + // Reactions: also reactions put on, or taken off, the command's answer + // and the addon's posts in the chat while it lives, each a call of Tool + // with {"reaction": emoji, "removed": bool} and the reactor's context. + // Offer it only to a bot whose Capability has WatchReactions. + Reactions bool `json:"reactions,omitempty"` } // Content is one block of a tool's result: text, or an image. diff --git a/docs/FILES_LINKS_TOOLS_MCP.md b/docs/FILES_LINKS_TOOLS_MCP.md index 73a65f9..72057d2 100644 --- a/docs/FILES_LINKS_TOOLS_MCP.md +++ b/docs/FILES_LINKS_TOOLS_MCP.md @@ -144,7 +144,7 @@ Each permission is off unless set. For an addon, `chats`, `dms` and these permis - **Direct commands.** `"direct": true` on a chat command has the bot call the addon's tool itself, with the text after the command, and send what it answers (text, and up to 2 pictures) without the model. The tool must be marked for the bot, and is then never offered to the model. A call has 15 seconds, or the command's `timeout`, from 1s to 2m (`"timeout": "60s"`), for an addon that may take a while, such as GeoGuess finding a photo; while it runs the chat sees the bot typing. At most 2 run at once per addon; a third is told the addon is busy, so with a long `timeout`, two calls that wait (two chats each waiting for a GeoGuess photo) make even a quick command such as `/geo scores` wait for one to end. When it fails, the chat gets a short line ("GeoGuess couldn't do that just now."), never the addon's own error text. An addon with no tool for the model has its commands named in the prompt's list of what the bot has, so the model can point people to them. - **Hidden tools.** A tool whose `_meta` says it is for the bot alone (`io.github.robdevops.signalbot/visibility` without `"model"`, or MCP Apps' `ui.visibility` without `"model"`) is never offered to the model or listed as one of its tools, so tools that read chat text stay out of its hands. -- **Watches.** A direct command's answer can ask for a watch on its chat: a pattern, such as map links, until a time at most `watch_max` away. While it lasts, a message there that matches goes to the addon instead: it isn't answered, isn't sent to the model, and isn't kept in history, even as group context; so does an edit of it later. The addon may react to it, so people see it was counted. A pattern that would match ordinary chat ("lol", "see you at 5", a news link, …) is refused, so a watch can't become a feed of everything said; at most 8 run in a chat at once. While a watch lasts, a reply to the command's pictures, or to pictures the addon posts while it lasts, that asks the bot gets the addon's set answer (GeoGuess's "No hints during a round 😉"), not the model's. A reply watch (`"replies": true`) takes instead only replies to the addon's own messages in the chat while it lasts, the command's answer and its posts, that ask the bot, such as a quiz's free-text answers; its pattern, if it has one, must match them too, and isn't held to the ordinary-chat rule, since such a reply is meant for the addon. +- **Watches.** A direct command's answer can ask for a watch on its chat: a pattern, such as map links, until a time at most `watch_max` away. While it lasts, a message there that matches goes to the addon instead: it isn't answered, isn't sent to the model, and isn't kept in history, even as group context; so does an edit of it later. The addon may react to it, so people see it was counted. A pattern that would match ordinary chat ("lol", "see you at 5", a news link, …) is refused, so a watch can't become a feed of everything said; at most 8 run in a chat at once. While a watch lasts, a reply to the command's pictures, or to pictures the addon posts while it lasts, that asks the bot gets the addon's set answer (GeoGuess's "No hints during a round 😉"), not the model's. A reply watch (`"replies": true`) takes instead only replies to the addon's own messages in the chat while it lasts, the command's answer and its posts, that ask the bot, such as a quiz's free-text answers; its pattern, if it has one, must match them too, and isn't held to the ordinary-chat rule, since such a reply is meant for the addon. A watch with `"reactions": true` also takes reactions put on, or taken off, the command's answer and the addon's posts while it lasts, each a call of its tool with `{"reaction": emoji, "removed": true|false}` and the reactor's context, such as a game's players joining by reacting to its intro. On Telegram the bot sees reactions only where it is an admin. - **Model.** With `model`, an addon may ask the bot's model for text, through MCP's standard sampling request (`sampling/createMessage`): it sends the prompt, and the bot runs it on its own model, with its own key, and sends back the answer. The addon needs no key or provider of its own. The bot offers this only to an addon with `model`, and only while it has a model; MCP suggests a person approve each request, and here the `model` setting is that approval. Each request names the chat it is for, one the addon may post in now, and is charged to that chat's `DAILY_BUDGET`: one over its budget is refused, and so is one past `per_hour`. A request is text only, at most 16 messages and 32 KB, with one in flight per addon at a time. Only its outcome, time, size, tokens and cost are logged, never the prompt or the answer. - **Outbox.** An addon posts when it likes by queueing posts (text, up to 2 pictures, or one MP3 clip to play, which shows no title: a voice message on Telegram, `clip.mp3` on Signal), reactions and the end of a watch in its outbox, an MCP resource the bot subscribes to (`signalbot://outbox`), and saying it changed; the bot reads it at once. It may post or react only in a chat where it was used, by a command or a watch, in the last 24 hours, and only within `rate`. Its posts go through the chat's queue like any message, never more than one at a time, and history keeps them as the bot's, labelled with the addon's name (`[GeoGuess] …`), so what an addon writes never poses as a person. A post can be a reply to one of the addon's earlier posts in the same chat, named by that post's ID (`replyTo`), so a quiz can answer a question under it; the Go package's `QueueIDs` gives the IDs. The bot remembers the IDs of the addon's last 256 post ops for 24 hours (a merged post uses one for each op); a reply to one it doesn't know, or in another chat, goes as an ordinary post. A reply is always a message of its own, never merged with the addon's other posts. On Signal it quotes the post; on Telegram it replies to it, and goes anyway if the post was deleted. - **Settings.** An addon has no `env` block. It gets `PATH`, `HOME`, the bot's time zone (`TZ`) and proxy settings (`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, and `SSL_CERT_FILE` or `SSL_CERT_DIR` for a custom CA) if set, and every variable in the bot's environment (`/etc/signalbot.env`) that starts with its server's name in capitals, anything but letters and digits as `_`, then `_`: the server `geo` gets `GEO_STATE_DIR`, `GEO_MAPILLARY_TOKEN` and so on, and never the bot's own keys. A name whose prefix starts one of the bot's settings (such as `model`, `signal` or `mcp`) is a config error. An addon that keeps files takes its directory from `<PREFIX>STATE_DIR` (`GEO_STATE_DIR`) and creates it itself, mode 0700. Unless the bot's environment sets it, the bot sets it to `addons/<server name>` in the bot's state directory (`/var/lib/private/signalbot/addons/geo`, or `/data/addons/geo` in Docker), so an addon's files are kept with the bot's; it creates nothing there itself. With `STATE_DIRECTORY` unset, or a server name that isn't only letters, digits, `.`, `_` and `-` (up to 64, not starting with `.`), there is no default, and the addon falls back on its own. diff --git a/internal/features/mcp/mcp.go b/internal/features/mcp/mcp.go index e2b926d..a87b3a0 100644 --- a/internal/features/mcp/mcp.go +++ b/internal/features/mcp/mcp.go @@ -137,6 +137,14 @@ func Register(h feature.Host) error { } return feature.Action{} }) + h.OnEvent(func(_ context.Context, e feature.Event) string { + for _, a := range k.addons { + if a.reacted(e) { + break + } + } + return "" + }) h.Go(k.run) } return nil @@ -292,7 +300,7 @@ type botInfo struct { // server said of itself. func initialize(ctx context.Context, c conn, self botInfo) (handshake, error) { caps := map[string]any{"experimental": map[string]any{ - ext.KeyAddon: ext.Capability{Version: ext.Version, Network: self.network, WatchReplies: self.addon}, + ext.KeyAddon: ext.Capability{Version: ext.Version, Network: self.network, WatchReplies: self.addon, WatchReactions: self.addon}, }} if self.sample { caps["sampling"] = map[string]any{} diff --git a/internal/features/mcp/watch.go b/internal/features/mcp/watch.go index eced97a..c618e0f 100644 --- a/internal/features/mcp/watch.go +++ b/internal/features/mcp/watch.go @@ -49,7 +49,8 @@ type watch struct { Until time.Time `json:"until"` Pictures []int64 `json:"pictures,omitempty"` // when the bot's messages with the command's pictures were sent, as Quote.Sent names them Replies bool `json:"replies,omitempty"` - Sent []int64 `json:"sent,omitempty"` // a reply watch's: when the addon's messages were sent, as Quote.Sent names them; the last maxSent + Reacts bool `json:"reactions,omitempty"` // also reactions to the addon's messages it knows + Sent []int64 `json:"sent,omitempty"` // a reply watch's: when the addon's messages were sent, as Quote.Sent names them; the last maxSent key string // the chat's key re *regexp.Regexp // Pattern @@ -85,6 +86,43 @@ type match struct { first int64 // for an edit, when the bot got the original, in Unix seconds; 0 if unknown due time.Time // when the worker may call its tool, within its chat's rate tries int // calls that failed with the server down + // reaction, for a reaction a watch took: the call's arguments are it, + // and msg is the message reacted to, from the reactor. + reaction *feature.Reaction +} + +// reacted passes a reaction to one of the addon's own messages to the +// first of the chat's live watches that takes reactions and knows the +// message, and reports whether one did. +func (a *addon) reacted(e feature.Event) bool { + r := e.Reaction + if r == nil || !r.Bot || r.Sent == 0 || e.By.ID == "" || !a.allows(e.Chat) { + return false + } + now := a.now() + tool := "" + a.mu.Lock() + for _, w := range a.watches[e.Chat.Key()] { + if w.Reacts && now.Before(w.Until) && slices.Contains(w.Sent, r.Sent) { + tool = w.Tool + break + } + } + if tool != "" { + a.leases[a.chatID(e.Chat)] = lease{e.Chat, now.Add(leaseLife)} + } + a.mu.Unlock() + if tool == "" { + return false + } + a.changed() + m := feature.Message{Chat: e.Chat, Sender: e.By.ID, Name: e.By.Name, Timestamp: r.Sent} + select { + case a.matches <- match{msg: m, tool: tool, at: now, reaction: r}: + default: + logx.Warnf("addon %s: watch queue full, a reaction dropped", a.server) + } + return true } // A match whose call finds the server down waits for it to start again, up @@ -138,7 +176,7 @@ func (a *addon) watch(m feature.Message, spec ext.Watch) *watch { until = latest } w := &watch{ID: spec.ID, Chat: a.chatID(m.Chat), Pattern: spec.Pattern, Tool: spec.Tool, Guard: txt.Clamp(strings.TrimSpace(spec.Guard), maxGuard), - Since: m.Timestamp, Until: until, Replies: spec.Replies, key: m.Chat.Key(), re: re} + Since: m.Timestamp, Until: until, Replies: spec.Replies, Reacts: spec.Reactions, key: m.Chat.Key(), re: re} a.mu.Lock() tomb := w.Chat + "\x00" + w.ID if t, ok := a.tombs[tomb]; ok && now.Before(t) { @@ -201,7 +239,7 @@ func (a *addon) replied(chat feature.Chat, sent []int64) { found := false a.mu.Lock() for _, w := range a.watches[chat.Key()] { - if w.Replies && now.Before(w.Until) { + if (w.Replies || w.Reacts) && now.Before(w.Until) { w.Sent = append(w.Sent, sent...) w.Sent = w.Sent[max(len(w.Sent)-maxSent, 0):] found = true @@ -371,7 +409,7 @@ func (a *addon) forward(ctx context.Context, m match) (down bool) { start := time.Now() res, err := a.conn.call(ctx, "tools/call", map[string]any{ "name": m.tool, - "arguments": map[string]string{"text": m.msg.Text}, + "arguments": args(m), "_meta": map[string]any{ext.KeyContext: c}, }) var r toolResult @@ -385,7 +423,7 @@ func (a *addon) forward(ctx context.Context, m match) (down bool) { outcome = "an error result" } logx.Infof("MCP server %s: a watch called %s: %s in %dms, %d bytes", a.server, m.tool, outcome, time.Since(start).Milliseconds(), len(res)) - if outcome == "ok" && r.Meta.React != "" { + if outcome == "ok" && r.Meta.React != "" && m.reaction == nil { // never a reaction to the bot's own message msg := feature.Message{Chat: m.msg.Chat, Sender: m.msg.Sender, Timestamp: m.msg.Timestamp, Edited: m.msg.Edited} // without its text if why := a.react(msg, r.Meta.React); why != "" { logx.Warnf("addon %s: a reaction dropped: %s", a.server, why) @@ -394,6 +432,14 @@ func (a *addon) forward(ctx context.Context, m match) (down bool) { return errors.Is(err, errNotRunning) || errors.Is(err, errExited) } +// args are a watch call's arguments: a message's text, or a reaction. +func args(m match) map[string]any { + if r := m.reaction; r != nil { + return map[string]any{"reaction": r.Emoji, "removed": r.Removed} + } + return map[string]any{"text": m.msg.Text} +} + // react puts emoji on msg, if the addon may, and returns why not if not. func (a *addon) react(msg feature.Message, emoji string) (why string) { switch { diff --git a/internal/features/mcp/watch_test.go b/internal/features/mcp/watch_test.go index a506930..5897eb7 100644 --- a/internal/features/mcp/watch_test.go +++ b/internal/features/mcp/watch_test.go @@ -1024,7 +1024,7 @@ func (c *fakeConn) call(_ context.Context, _ string, params any) (json.RawMessag c.fails++ return nil, errNotRunning } - c.texts = append(c.texts, params.(map[string]any)["arguments"].(map[string]string)["text"]) + c.texts = append(c.texts, params.(map[string]any)["arguments"].(map[string]any)["text"].(string)) return json.RawMessage(`{"content":[]}`), nil } @@ -1215,3 +1215,45 @@ func TestOutboxAudio(t *testing.T) { } } } + +// A reaction to one of the addon's own messages that a watch with +// reactions knows goes to its tool, as {"reaction", "removed"}, from the +// reactor; one to another message, or by the bot, or with no such watch, +// doesn't. +func TestWatchReactions(t *testing.T) { + a, now := unitAddon(everything) + s := specAt("lobby", now.Add(time.Minute)) + s.Reactions = true + if a.watch(said(inA, "alice-id", 1000, "/round"), s) == nil { + t.Fatal("watch refused") + } + a.replied(inA, []int64{555}) + ev := func(sent int64, bot bool, removed bool) feature.Event { + return feature.Event{Chat: inA, By: feature.Person{ID: "bob-id", Name: "Bob"}, Reaction: &feature.Reaction{Emoji: "👍", Bot: bot, Sent: sent, Removed: removed}} + } + if !a.reacted(ev(555, true, false)) { + t.Fatal("a reaction to the addon's message wasn't taken") + } + m := <-a.matches + if m.tool != "guess" || m.msg.Sender != "bob-id" || m.msg.Timestamp != 555 { + t.Errorf("match %+v", m) + } + if got := args(m); got["reaction"] != "👍" || got["removed"] != false { + t.Errorf("args %v", got) + } + if !a.reacted(ev(555, true, true)) || args(<-a.matches)["removed"] != true { + t.Error("a reaction taken back") + } + for _, e := range []feature.Event{ev(556, true, false), ev(555, false, false), {Chat: inB, By: feature.Person{ID: "bob-id"}, Reaction: &feature.Reaction{Emoji: "👍", Bot: true, Sent: 555}}} { + if a.reacted(e) { + t.Errorf("taken: %+v", e.Reaction) + } + } + *now = now.Add(2 * time.Minute) + if a.reacted(ev(555, true, false)) { + t.Error("taken after the watch ended") + } + if got := args(match{msg: feature.Message{Text: "hi"}}); got["text"] != "hi" { + t.Errorf("a message's args %v", got) + } +} From f84f64a34578964d84155649a5675db768666477 Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sun, 22 Nov 2026 13:24:57 +0000 Subject: [PATCH 25/26] In a DM, a reply watch takes every message MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A DM is the player's own chat with the bot, so a game there needs no replies: a plain answer was otherwise sent to the model, which played along ("Locked in…") while the game never saw it. In a group, a reply watch still takes only replies to the addon's messages. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- addon/schema.json | 2 +- addon/types.go | 2 +- docs/FILES_LINKS_TOOLS_MCP.md | 2 +- internal/features/mcp/watch.go | 10 ++++++---- internal/features/mcp/watch_test.go | 19 +++++++++++++++++++ 5 files changed, 28 insertions(+), 7 deletions(-) diff --git a/addon/schema.json b/addon/schema.json index 88a3c10..b27b8f6 100644 --- a/addon/schema.json +++ b/addon/schema.json @@ -51,7 +51,7 @@ "until": {"description": "An RFC 3339 time, in the future.", "type": "string", "format": "date-time"}, "tool": {"description": "A tool for the bot, called with each message the watch takes, as {\"text\": …}, with its context.", "type": "string", "minLength": 1}, "guard": {"description": "While the watch lasts, the answer to a message addressed to the bot that replies to the command's pictures; at most 500 characters.", "type": "string", "maxLength": 500}, - "replies": {"description": "Take only messages in the chat that reply to the command's answer or to the addon's posts there while the watch lives. Only for a bot whose capability has watchReplies; the bot doesn't check such a pattern against ordinary chat.", "type": "boolean"}, + "replies": {"description": "Take only messages in the chat that reply to the command's answer or to the addon's posts there while the watch lives; in a DM, every message. Only for a bot whose capability has watchReplies; the bot doesn't check such a pattern against ordinary chat.", "type": "boolean"}, "reactions": {"description": "Also take reactions put on, or taken off, the command's answer and the addon's posts in the chat while the watch lives: each a call of tool with {\"reaction\": emoji, \"removed\": bool} and the reactor's context. Only for a bot whose capability has watchReactions. On Telegram the bot sees reactions only as a group's admin.", "type": "boolean"} }, "required": ["id", "until", "tool"], diff --git a/addon/types.go b/addon/types.go index 50ccc8f..5b20892 100644 --- a/addon/types.go +++ b/addon/types.go @@ -76,7 +76,7 @@ type Watch struct { Until string `json:"until"` // RFC 3339 Tool string `json:"tool"` // called with each message it matches, as {"text": …} Guard string `json:"guard,omitempty"` // the answer, while it lasts, to a message addressed to the bot that quotes the command's pictures - Replies bool `json:"replies,omitempty"` // only replies to the command's answer and the addon's posts in the chat while it lives + Replies bool `json:"replies,omitempty"` // only replies to the command's answer and the addon's posts in the chat while it lives; in a DM, every message // Reactions: also reactions put on, or taken off, the command's answer // and the addon's posts in the chat while it lives, each a call of Tool // with {"reaction": emoji, "removed": bool} and the reactor's context. diff --git a/docs/FILES_LINKS_TOOLS_MCP.md b/docs/FILES_LINKS_TOOLS_MCP.md index 72057d2..c9ec76e 100644 --- a/docs/FILES_LINKS_TOOLS_MCP.md +++ b/docs/FILES_LINKS_TOOLS_MCP.md @@ -144,7 +144,7 @@ Each permission is off unless set. For an addon, `chats`, `dms` and these permis - **Direct commands.** `"direct": true` on a chat command has the bot call the addon's tool itself, with the text after the command, and send what it answers (text, and up to 2 pictures) without the model. The tool must be marked for the bot, and is then never offered to the model. A call has 15 seconds, or the command's `timeout`, from 1s to 2m (`"timeout": "60s"`), for an addon that may take a while, such as GeoGuess finding a photo; while it runs the chat sees the bot typing. At most 2 run at once per addon; a third is told the addon is busy, so with a long `timeout`, two calls that wait (two chats each waiting for a GeoGuess photo) make even a quick command such as `/geo scores` wait for one to end. When it fails, the chat gets a short line ("GeoGuess couldn't do that just now."), never the addon's own error text. An addon with no tool for the model has its commands named in the prompt's list of what the bot has, so the model can point people to them. - **Hidden tools.** A tool whose `_meta` says it is for the bot alone (`io.github.robdevops.signalbot/visibility` without `"model"`, or MCP Apps' `ui.visibility` without `"model"`) is never offered to the model or listed as one of its tools, so tools that read chat text stay out of its hands. -- **Watches.** A direct command's answer can ask for a watch on its chat: a pattern, such as map links, until a time at most `watch_max` away. While it lasts, a message there that matches goes to the addon instead: it isn't answered, isn't sent to the model, and isn't kept in history, even as group context; so does an edit of it later. The addon may react to it, so people see it was counted. A pattern that would match ordinary chat ("lol", "see you at 5", a news link, …) is refused, so a watch can't become a feed of everything said; at most 8 run in a chat at once. While a watch lasts, a reply to the command's pictures, or to pictures the addon posts while it lasts, that asks the bot gets the addon's set answer (GeoGuess's "No hints during a round 😉"), not the model's. A reply watch (`"replies": true`) takes instead only replies to the addon's own messages in the chat while it lasts, the command's answer and its posts, that ask the bot, such as a quiz's free-text answers; its pattern, if it has one, must match them too, and isn't held to the ordinary-chat rule, since such a reply is meant for the addon. A watch with `"reactions": true` also takes reactions put on, or taken off, the command's answer and the addon's posts while it lasts, each a call of its tool with `{"reaction": emoji, "removed": true|false}` and the reactor's context, such as a game's players joining by reacting to its intro. On Telegram the bot sees reactions only where it is an admin. +- **Watches.** A direct command's answer can ask for a watch on its chat: a pattern, such as map links, until a time at most `watch_max` away. While it lasts, a message there that matches goes to the addon instead: it isn't answered, isn't sent to the model, and isn't kept in history, even as group context; so does an edit of it later. The addon may react to it, so people see it was counted. A pattern that would match ordinary chat ("lol", "see you at 5", a news link, …) is refused, so a watch can't become a feed of everything said; at most 8 run in a chat at once. While a watch lasts, a reply to the command's pictures, or to pictures the addon posts while it lasts, that asks the bot gets the addon's set answer (GeoGuess's "No hints during a round 😉"), not the model's. A reply watch (`"replies": true`) takes instead only replies to the addon's own messages in the chat while it lasts, the command's answer and its posts, that ask the bot (in a DM, every message, as the chat is the player's own with the bot), such as a quiz's free-text answers; its pattern, if it has one, must match them too, and isn't held to the ordinary-chat rule, since such a reply is meant for the addon. A watch with `"reactions": true` also takes reactions put on, or taken off, the command's answer and the addon's posts while it lasts, each a call of its tool with `{"reaction": emoji, "removed": true|false}` and the reactor's context, such as a game's players joining by reacting to its intro. On Telegram the bot sees reactions only where it is an admin. - **Model.** With `model`, an addon may ask the bot's model for text, through MCP's standard sampling request (`sampling/createMessage`): it sends the prompt, and the bot runs it on its own model, with its own key, and sends back the answer. The addon needs no key or provider of its own. The bot offers this only to an addon with `model`, and only while it has a model; MCP suggests a person approve each request, and here the `model` setting is that approval. Each request names the chat it is for, one the addon may post in now, and is charged to that chat's `DAILY_BUDGET`: one over its budget is refused, and so is one past `per_hour`. A request is text only, at most 16 messages and 32 KB, with one in flight per addon at a time. Only its outcome, time, size, tokens and cost are logged, never the prompt or the answer. - **Outbox.** An addon posts when it likes by queueing posts (text, up to 2 pictures, or one MP3 clip to play, which shows no title: a voice message on Telegram, `clip.mp3` on Signal), reactions and the end of a watch in its outbox, an MCP resource the bot subscribes to (`signalbot://outbox`), and saying it changed; the bot reads it at once. It may post or react only in a chat where it was used, by a command or a watch, in the last 24 hours, and only within `rate`. Its posts go through the chat's queue like any message, never more than one at a time, and history keeps them as the bot's, labelled with the addon's name (`[GeoGuess] …`), so what an addon writes never poses as a person. A post can be a reply to one of the addon's earlier posts in the same chat, named by that post's ID (`replyTo`), so a quiz can answer a question under it; the Go package's `QueueIDs` gives the IDs. The bot remembers the IDs of the addon's last 256 post ops for 24 hours (a merged post uses one for each op); a reply to one it doesn't know, or in another chat, goes as an ordinary post. A reply is always a message of its own, never merged with the addon's other posts. On Signal it quotes the post; on Telegram it replies to it, and goes anyway if the post was deleted. - **Settings.** An addon has no `env` block. It gets `PATH`, `HOME`, the bot's time zone (`TZ`) and proxy settings (`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, and `SSL_CERT_FILE` or `SSL_CERT_DIR` for a custom CA) if set, and every variable in the bot's environment (`/etc/signalbot.env`) that starts with its server's name in capitals, anything but letters and digits as `_`, then `_`: the server `geo` gets `GEO_STATE_DIR`, `GEO_MAPILLARY_TOKEN` and so on, and never the bot's own keys. A name whose prefix starts one of the bot's settings (such as `model`, `signal` or `mcp`) is a config error. An addon that keeps files takes its directory from `<PREFIX>STATE_DIR` (`GEO_STATE_DIR`) and creates it itself, mode 0700. Unless the bot's environment sets it, the bot sets it to `addons/<server name>` in the bot's state directory (`/var/lib/private/signalbot/addons/geo`, or `/data/addons/geo` in Docker), so an addon's files are kept with the bot's; it creates nothing there itself. With `STATE_DIRECTORY` unset, or a server name that isn't only letters, digits, `.`, `_` and `-` (up to 64, not starting with `.`), there is no default, and the addon falls back on its own. diff --git a/internal/features/mcp/watch.go b/internal/features/mcp/watch.go index c618e0f..56160e4 100644 --- a/internal/features/mcp/watch.go +++ b/internal/features/mcp/watch.go @@ -251,11 +251,13 @@ func (a *addon) replied(chat feature.Chat, sent []int64) { } } -// takes reports whether w takes m, apart from when: a reply watch only an -// addressed reply to one of the addon's messages it knows, and its pattern, -// if it has one, must match. +// takes reports whether w takes m, apart from when: a reply watch, in a +// group, only an addressed reply to one of the addon's messages it knows, +// and in a DM any message; its pattern, if it has one, must match. func (a *addon) takes(w *watch, m feature.Message) bool { - if w.Replies { + // In a DM a reply watch takes every message: the chat is the player's + // own with the bot, so there is no group chat to keep out of the game. + if w.Replies && m.Chat.GroupID != "" { if !m.Addressed || m.Quote == nil || !m.Quote.Bot || m.Quote.Sent == 0 { return false } diff --git a/internal/features/mcp/watch_test.go b/internal/features/mcp/watch_test.go index 5897eb7..672e8b2 100644 --- a/internal/features/mcp/watch_test.go +++ b/internal/features/mcp/watch_test.go @@ -1257,3 +1257,22 @@ func TestWatchReactions(t *testing.T) { t.Errorf("a message's args %v", got) } } + +// In a DM a reply watch takes every message, not only replies; in a group, +// only replies to the addon's messages. +func TestReplyWatchInDM(t *testing.T) { + a, now := unitAddon(everything) + s := ext.Watch{ID: "q", Until: now.Add(time.Minute).Format(time.RFC3339), Tool: "guess", Replies: true} + dm := feature.Chat{User: "alice-id"} + w := a.watch(said(dm, "alice-id", 1000, "/quiz"), s) + if w == nil { + t.Fatal("watch refused") + } + if !a.takes(w, said(dm, "alice-id", 1001, "Brown eyes")) { + t.Error("a plain message in a DM wasn't taken") + } + g := a.watch(said(inA, "alice-id", 1000, "/quiz"), s) + if g == nil || a.takes(g, to(said(inA, "bob-id", 1001, "Brown eyes"))) { + t.Error("a message that isn't a reply was taken in a group") + } +} From ec18ac92d2bc4152697647cc466dd22ea69f512e Mon Sep 17 00:00:00 2001 From: Claude <noreply@anthropic.com> Date: Sun, 22 Nov 2026 22:07:52 +0000 Subject: [PATCH 26/26] A watch's over text answers replies to a finished game For an hour after a watch ends, by an unwatch, its time or a new watch, a message to the bot that replies to one of the addon's messages it knew gets the watch's over text ("That game is over.") instead of the model's answer, which otherwise played along with late answers. Kept in memory only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RsqJnxrLp5eK6VJuiCDqCK --- addon/schema.json | 1 + addon/types.go | 4 +++ docs/FILES_LINKS_TOOLS_MCP.md | 2 +- internal/features/mcp/addon.go | 1 + internal/features/mcp/keep.go | 8 ++++- internal/features/mcp/outbox.go | 3 ++ internal/features/mcp/watch.go | 56 +++++++++++++++++++++++++++-- internal/features/mcp/watch_test.go | 42 ++++++++++++++++++++++ 8 files changed, 113 insertions(+), 4 deletions(-) diff --git a/addon/schema.json b/addon/schema.json index b27b8f6..fc189bc 100644 --- a/addon/schema.json +++ b/addon/schema.json @@ -52,6 +52,7 @@ "tool": {"description": "A tool for the bot, called with each message the watch takes, as {\"text\": …}, with its context.", "type": "string", "minLength": 1}, "guard": {"description": "While the watch lasts, the answer to a message addressed to the bot that replies to the command's pictures; at most 500 characters.", "type": "string", "maxLength": 500}, "replies": {"description": "Take only messages in the chat that reply to the command's answer or to the addon's posts there while the watch lives; in a DM, every message. Only for a bot whose capability has watchReplies; the bot doesn't check such a pattern against ordinary chat.", "type": "boolean"}, + "over": {"description": "The answer, for an hour after the watch ends, to a message addressed to the bot that replies to one of the addon's messages the watch knew, in place of the model's, such as \"That game is over.\"; at most 500 characters.", "type": "string", "maxLength": 500}, "reactions": {"description": "Also take reactions put on, or taken off, the command's answer and the addon's posts in the chat while the watch lives: each a call of tool with {\"reaction\": emoji, \"removed\": bool} and the reactor's context. Only for a bot whose capability has watchReactions. On Telegram the bot sees reactions only as a group's admin.", "type": "boolean"} }, "required": ["id", "until", "tool"], diff --git a/addon/types.go b/addon/types.go index 5b20892..98d9cdc 100644 --- a/addon/types.go +++ b/addon/types.go @@ -82,6 +82,10 @@ type Watch struct { // with {"reaction": emoji, "removed": bool} and the reactor's context. // Offer it only to a bot whose Capability has WatchReactions. Reactions bool `json:"reactions,omitempty"` + // Over is the answer, for an hour after the watch ends, to a message + // addressed to the bot that replies to one of the addon's messages it + // knew, in place of the model's: "That game is over." + Over string `json:"over,omitempty"` } // Content is one block of a tool's result: text, or an image. diff --git a/docs/FILES_LINKS_TOOLS_MCP.md b/docs/FILES_LINKS_TOOLS_MCP.md index c9ec76e..e94c40e 100644 --- a/docs/FILES_LINKS_TOOLS_MCP.md +++ b/docs/FILES_LINKS_TOOLS_MCP.md @@ -144,7 +144,7 @@ Each permission is off unless set. For an addon, `chats`, `dms` and these permis - **Direct commands.** `"direct": true` on a chat command has the bot call the addon's tool itself, with the text after the command, and send what it answers (text, and up to 2 pictures) without the model. The tool must be marked for the bot, and is then never offered to the model. A call has 15 seconds, or the command's `timeout`, from 1s to 2m (`"timeout": "60s"`), for an addon that may take a while, such as GeoGuess finding a photo; while it runs the chat sees the bot typing. At most 2 run at once per addon; a third is told the addon is busy, so with a long `timeout`, two calls that wait (two chats each waiting for a GeoGuess photo) make even a quick command such as `/geo scores` wait for one to end. When it fails, the chat gets a short line ("GeoGuess couldn't do that just now."), never the addon's own error text. An addon with no tool for the model has its commands named in the prompt's list of what the bot has, so the model can point people to them. - **Hidden tools.** A tool whose `_meta` says it is for the bot alone (`io.github.robdevops.signalbot/visibility` without `"model"`, or MCP Apps' `ui.visibility` without `"model"`) is never offered to the model or listed as one of its tools, so tools that read chat text stay out of its hands. -- **Watches.** A direct command's answer can ask for a watch on its chat: a pattern, such as map links, until a time at most `watch_max` away. While it lasts, a message there that matches goes to the addon instead: it isn't answered, isn't sent to the model, and isn't kept in history, even as group context; so does an edit of it later. The addon may react to it, so people see it was counted. A pattern that would match ordinary chat ("lol", "see you at 5", a news link, …) is refused, so a watch can't become a feed of everything said; at most 8 run in a chat at once. While a watch lasts, a reply to the command's pictures, or to pictures the addon posts while it lasts, that asks the bot gets the addon's set answer (GeoGuess's "No hints during a round 😉"), not the model's. A reply watch (`"replies": true`) takes instead only replies to the addon's own messages in the chat while it lasts, the command's answer and its posts, that ask the bot (in a DM, every message, as the chat is the player's own with the bot), such as a quiz's free-text answers; its pattern, if it has one, must match them too, and isn't held to the ordinary-chat rule, since such a reply is meant for the addon. A watch with `"reactions": true` also takes reactions put on, or taken off, the command's answer and the addon's posts while it lasts, each a call of its tool with `{"reaction": emoji, "removed": true|false}` and the reactor's context, such as a game's players joining by reacting to its intro. On Telegram the bot sees reactions only where it is an admin. +- **Watches.** A direct command's answer can ask for a watch on its chat: a pattern, such as map links, until a time at most `watch_max` away. While it lasts, a message there that matches goes to the addon instead: it isn't answered, isn't sent to the model, and isn't kept in history, even as group context; so does an edit of it later. The addon may react to it, so people see it was counted. A pattern that would match ordinary chat ("lol", "see you at 5", a news link, …) is refused, so a watch can't become a feed of everything said; at most 8 run in a chat at once. While a watch lasts, a reply to the command's pictures, or to pictures the addon posts while it lasts, that asks the bot gets the addon's set answer (GeoGuess's "No hints during a round 😉"), not the model's. A reply watch (`"replies": true`) takes instead only replies to the addon's own messages in the chat while it lasts, the command's answer and its posts, that ask the bot (in a DM, every message, as the chat is the player's own with the bot), such as a quiz's free-text answers; its pattern, if it has one, must match them too, and isn't held to the ordinary-chat rule, since such a reply is meant for the addon. A watch with `"reactions": true` also takes reactions put on, or taken off, the command's answer and the addon's posts while it lasts, each a call of its tool with `{"reaction": emoji, "removed": true|false}` and the reactor's context, such as a game's players joining by reacting to its intro. A watch's `over` text answers, for an hour after the watch ends, a message to the bot that replies to one of the addon's messages it knew, in place of the model ("That game is over."), so a late answer isn't played along with. On Telegram the bot sees reactions only where it is an admin. - **Model.** With `model`, an addon may ask the bot's model for text, through MCP's standard sampling request (`sampling/createMessage`): it sends the prompt, and the bot runs it on its own model, with its own key, and sends back the answer. The addon needs no key or provider of its own. The bot offers this only to an addon with `model`, and only while it has a model; MCP suggests a person approve each request, and here the `model` setting is that approval. Each request names the chat it is for, one the addon may post in now, and is charged to that chat's `DAILY_BUDGET`: one over its budget is refused, and so is one past `per_hour`. A request is text only, at most 16 messages and 32 KB, with one in flight per addon at a time. Only its outcome, time, size, tokens and cost are logged, never the prompt or the answer. - **Outbox.** An addon posts when it likes by queueing posts (text, up to 2 pictures, or one MP3 clip to play, which shows no title: a voice message on Telegram, `clip.mp3` on Signal), reactions and the end of a watch in its outbox, an MCP resource the bot subscribes to (`signalbot://outbox`), and saying it changed; the bot reads it at once. It may post or react only in a chat where it was used, by a command or a watch, in the last 24 hours, and only within `rate`. Its posts go through the chat's queue like any message, never more than one at a time, and history keeps them as the bot's, labelled with the addon's name (`[GeoGuess] …`), so what an addon writes never poses as a person. A post can be a reply to one of the addon's earlier posts in the same chat, named by that post's ID (`replyTo`), so a quiz can answer a question under it; the Go package's `QueueIDs` gives the IDs. The bot remembers the IDs of the addon's last 256 post ops for 24 hours (a merged post uses one for each op); a reply to one it doesn't know, or in another chat, goes as an ordinary post. A reply is always a message of its own, never merged with the addon's other posts. On Signal it quotes the post; on Telegram it replies to it, and goes anyway if the post was deleted. - **Settings.** An addon has no `env` block. It gets `PATH`, `HOME`, the bot's time zone (`TZ`) and proxy settings (`HTTPS_PROXY`, `HTTP_PROXY`, `NO_PROXY`, and `SSL_CERT_FILE` or `SSL_CERT_DIR` for a custom CA) if set, and every variable in the bot's environment (`/etc/signalbot.env`) that starts with its server's name in capitals, anything but letters and digits as `_`, then `_`: the server `geo` gets `GEO_STATE_DIR`, `GEO_MAPILLARY_TOKEN` and so on, and never the bot's own keys. A name whose prefix starts one of the bot's settings (such as `model`, `signal` or `mcp`) is a config error. An addon that keeps files takes its directory from `<PREFIX>STATE_DIR` (`GEO_STATE_DIR`) and creates it itself, mode 0700. Unless the bot's environment sets it, the bot sets it to `addons/<server name>` in the bot's state directory (`/var/lib/private/signalbot/addons/geo`, or `/data/addons/geo` in Docker), so an addon's files are kept with the bot's; it creates nothing there itself. With `STATE_DIRECTORY` unset, or a server name that isn't only letters, digits, `.`, `_` and `-` (up to 64, not starting with `.`), there is no default, and the addon falls back on its own. diff --git a/internal/features/mcp/addon.go b/internal/features/mcp/addon.go index 35bec51..1b188f1 100644 --- a/internal/features/mcp/addon.go +++ b/internal/features/mcp/addon.go @@ -290,6 +290,7 @@ type addon struct { claims map[claimKey]claim // messages its watches took leases map[string]lease // the chats it may post in, by pseudonym tombs map[string]time.Time // unwatches before their watch, by chat pseudonym, "\x00", watch ID: until when + over map[string][]ended // finished watches' set answers, by chat key; in memory only cursor string // where its outbox was read and delivered up to; "" for the start next string // where the last read of its outbox ended: the cursor once its posts are sent missed bool // a post read from the outbox wasn't sent: read it again before the cursor moves diff --git a/internal/features/mcp/keep.go b/internal/features/mcp/keep.go index 7c8f04c..0beebe0 100644 --- a/internal/features/mcp/keep.go +++ b/internal/features/mcp/keep.go @@ -95,7 +95,13 @@ func (a *addon) state() addonState { defer a.mu.Unlock() s := addonState{Leases: map[string]lease{}, Cursor: a.cursor, Applied: slices.Clone(a.applied)} for key, ws := range a.watches { - ws = slices.DeleteFunc(ws, func(w *watch) bool { return !now.Before(w.Until) }) + ws = slices.DeleteFunc(ws, func(w *watch) bool { + gone := !now.Before(w.Until) + if gone { + a.endedLocked(w, now) + } + return gone + }) if len(ws) == 0 { delete(a.watches, key) continue diff --git a/internal/features/mcp/outbox.go b/internal/features/mcp/outbox.go index f9b97a8..e23188e 100644 --- a/internal/features/mcp/outbox.go +++ b/internal/features/mcp/outbox.go @@ -527,6 +527,9 @@ func (a *addon) unwatch(chat, id string) { for key, ws := range a.watches { a.watches[key] = slices.DeleteFunc(ws, func(w *watch) bool { gone := w.Chat == chat && w.ID == id + if gone { + a.endedLocked(w, a.now()) + } found = found || gone return gone }) diff --git a/internal/features/mcp/watch.go b/internal/features/mcp/watch.go index 56160e4..5739fac 100644 --- a/internal/features/mcp/watch.go +++ b/internal/features/mcp/watch.go @@ -51,6 +51,7 @@ type watch struct { Replies bool `json:"replies,omitempty"` Reacts bool `json:"reactions,omitempty"` // also reactions to the addon's messages it knows Sent []int64 `json:"sent,omitempty"` // a reply watch's: when the addon's messages were sent, as Quote.Sent names them; the last maxSent + Over string `json:"over,omitempty"` // the answer, for overLife after it ends, to a reply to the addon's messages it knew key string // the chat's key re *regexp.Regexp // Pattern @@ -175,7 +176,7 @@ func (a *addon) watch(m feature.Message, spec ext.Watch) *watch { if latest := now.Add(a.cfg.watchMax); until.After(latest) { until = latest } - w := &watch{ID: spec.ID, Chat: a.chatID(m.Chat), Pattern: spec.Pattern, Tool: spec.Tool, Guard: txt.Clamp(strings.TrimSpace(spec.Guard), maxGuard), + w := &watch{ID: spec.ID, Chat: a.chatID(m.Chat), Pattern: spec.Pattern, Tool: spec.Tool, Guard: txt.Clamp(strings.TrimSpace(spec.Guard), maxGuard), Over: txt.Clamp(strings.TrimSpace(spec.Over), maxGuard), Since: m.Timestamp, Until: until, Replies: spec.Replies, Reacts: spec.Reactions, key: m.Chat.Key(), re: re} a.mu.Lock() tomb := w.Chat + "\x00" + w.ID @@ -184,7 +185,13 @@ func (a *addon) watch(m feature.Message, spec ext.Watch) *watch { a.mu.Unlock() return refuse("the addon ended it before it began") } - live := slices.DeleteFunc(a.watches[w.key], func(o *watch) bool { return o.ID == w.ID || !now.Before(o.Until) }) + live := slices.DeleteFunc(a.watches[w.key], func(o *watch) bool { + gone := o.ID == w.ID || !now.Before(o.Until) + if gone { + a.endedLocked(o, now) + } + return gone + }) if len(live) >= maxWatches { a.watches[w.key] = live a.mu.Unlock() @@ -339,9 +346,54 @@ func (a *addon) guard(m feature.Message, live []*watch, now time.Time) feature.A return feature.Action{Answer: w.Guard} } } + // A reply to a finished watch's messages: its set answer, not the model's. + for _, w := range live { // ended by its time, not yet let go of + if w.Over != "" && !now.Before(w.Until) && now.Before(w.Until.Add(overLife)) && + (slices.Contains(w.Sent, m.Quote.Sent) || slices.Contains(w.Pictures, m.Quote.Sent)) { + return feature.Action{Answer: w.Over} + } + } + for _, e := range a.over[m.Chat.Key()] { + if now.Before(e.until) && slices.Contains(e.sent, m.Quote.Sent) { + return feature.Action{Answer: e.text} + } + } return feature.Action{} } +// ended is a finished watch's set answer to replies to the addon's +// messages it knew, until when. +type ended struct { + sent []int64 + text string + until time.Time +} + +// How long a finished watch's set answer lasts, and how many a chat keeps. +const ( + overLife = time.Hour + maxOver = 8 +) + +// endedLocked keeps w's set answer, if it has one, for overLife after it +// ends: in memory only. a.mu is held. +func (a *addon) endedLocked(w *watch, now time.Time) { + if w.Over == "" { + return + } + if a.over == nil { + a.over = map[string][]ended{} + } + key := w.key + until := w.Until + if now.Before(until) { // ended early, by an unwatch or a new watch + until = now + } + list := slices.DeleteFunc(a.over[key], func(e ended) bool { return !now.Before(e.until) }) + list = append(list, ended{slices.Concat(w.Sent, w.Pictures), w.Over, until.Add(overLife)}) + a.over[key] = list[max(len(list)-maxOver, 0):] +} + // work passes each matched message to its watch's tool, until ctx ends: in // each chat in turn and within the chat's rate, a match past the rate // waiting its turn without holding up other chats'. A match whose call finds diff --git a/internal/features/mcp/watch_test.go b/internal/features/mcp/watch_test.go index 672e8b2..a91cc96 100644 --- a/internal/features/mcp/watch_test.go +++ b/internal/features/mcp/watch_test.go @@ -1276,3 +1276,45 @@ func TestReplyWatchInDM(t *testing.T) { t.Error("a message that isn't a reply was taken in a group") } } + +// A finished watch with Over answers replies to the addon's messages it +// knew with Over, for an hour, whether it ended by an unwatch or by its +// time; other messages pass to the model as before. +func TestWatchOver(t *testing.T) { + a, now := unitAddon(everything) + reply := func(sent int64) feature.Message { + m := to(said(inA, "bob-id", 2000, "losing my religion")) + m.Quote = &feature.Quote{Bot: true, Sent: sent} + return m + } + s := ext.Watch{ID: "g1", Until: now.Add(time.Minute).Format(time.RFC3339), Tool: "guess", Replies: true, Over: "That game is over."} + if a.watch(said(inA, "alice-id", 1000, "/song"), s) == nil { + t.Fatal("watch refused") + } + a.replied(inA, []int64{555}) + a.unwatch(a.chatID(inA), "g1") + if got := a.claim(reply(555)); got.Answer != "That game is over." { + t.Errorf("a reply after the unwatch: %+v", got) + } + if got := a.claim(reply(556)); !got.IsZero() { + t.Errorf("a reply to another message: %+v", got) + } + if got := a.claim(to(said(inA, "bob-id", 2001, "hello"))); !got.IsZero() { + t.Errorf("a message that isn't a reply: %+v", got) + } + *now = now.Add(overLife + time.Second) + if got := a.claim(reply(555)); !got.IsZero() { + t.Errorf("a reply after the hour: %+v", got) + } + + // Ended by its time, not yet let go of. + s.ID, s.Until = "g2", now.Add(time.Minute).Format(time.RFC3339) + if a.watch(said(inA, "alice-id", 3000, "/song"), s) == nil { + t.Fatal("watch refused") + } + a.replied(inA, []int64{777}) + *now = now.Add(2 * time.Minute) + if got := a.claim(reply(777)); got.Answer != "That game is over." { + t.Errorf("a reply after the watch's time: %+v", got) + } +}