diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 92d70f0..222272a 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, 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 ``` @@ -24,11 +25,12 @@ 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 | -| The model is asked | `OnTurn` (a note on the message, images) and `Tools` (a `ToolGroup`) | +| 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 `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`, `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. @@ -53,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/PRIVACY.md b/PRIVACY.md index 1533cb6..bc1a4b0 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; an addon's own `addons/` 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. - **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: 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 @@ -71,8 +74,40 @@ 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](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_…`). +- **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. 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; + - `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, outside what this page lists for the bot, in the directory its `…_STATE_DIR` names (GeoGuess: `GEO_STATE_DIR`): by default `addons/` 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. +- **`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, 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. + ## 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..d97c780 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,10 @@ 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](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 b94fa9c..d3ff075 100644 --- a/TECHNICAL.md +++ b/TECHNICAL.md @@ -17,14 +17,14 @@ 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. 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. -- **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. +- **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. @@ -62,10 +62,10 @@ 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. -- **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. @@ -89,13 +89,14 @@ 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, 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 ``` - 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. -- **`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. +- **`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 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,29 +105,29 @@ 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 | |---|---|---| -| 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 "" | **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. +- 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. **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, `.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,17 +137,19 @@ 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) 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). - `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 Additions struct{ Note, HistoryNote string; Images []string; Files []File } +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; 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) } ``` @@ -210,29 +213,45 @@ 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`, `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` | - **`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 (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. When `STATE_DIR` isn't set, it gets one: `addons/` 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 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), `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": ""}`. 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 " 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, 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. - **`schedule`** is `/schedule` ([below](#schedule)). ### `/schedule` @@ -258,7 +277,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 +322,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/addon/schema.json b/addon/schema.json new file mode 100644 index 0000000..fc189bc --- /dev/null +++ b/addon/schema.json @@ -0,0 +1,203 @@ +{ + "$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 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"]}, + "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"] + }, + "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. 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. 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}, + "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"], + "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.", + "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": "text"}}}, "then": {"required": ["text"]}}, + {"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": "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": { + "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, 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}, + "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}}}, {"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", + "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 + }, + "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", + "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..a3fc029 --- /dev/null +++ b/addon/schema_test.go @@ -0,0 +1,582 @@ +package addon + +import ( + "context" + "encoding/json" + "fmt" + "go/ast" + "go/parser" + "go/token" + "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](), + "Audio": reflect.TypeFor[Audio](), + "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 +// 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)) + for name := range d { + if _, ok := wireTypes[name]; !ok && name != "ToolMeta" { + t.Errorf("$defs/%s has no Go type", 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) + 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 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) + } + } + // 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 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) + } + 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" + case reflect.Float64: + return "number" + } + 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 "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) + } + 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)) + case "number": + _, ok := v.(float64) + return ok + } + 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"} + 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 + }{ + {"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 😉"}}, + {"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"}}}}, + {"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: "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"}}, + {"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{}}, + {"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 { + 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"}}, + {"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"}}}}, + {"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}}, + {"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"}}, + {"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}}, + {"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 { + 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/server.go b/addon/server.go new file mode 100644 index 0000000..23a796e --- /dev/null +++ b/addon/server.go @@ -0,0 +1,815 @@ +package addon + +import ( + "bufio" + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "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. It + // can run on several goroutines at once, so saving must allow that. + 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, +// 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, op ID and request ID + dirty chan struct{} // the outbox gained ops: tell the bot + + mu sync.Mutex + 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 + 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, +// 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 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; 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. +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), pending: map[string]chan answer{}} + 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 +} + +// 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 +} + +// 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 { + 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 +// 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 nil, fmt.Errorf("a post has %d images; the most is %d", len(o.Images), MaxImages) + case 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, 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 ids, 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. +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. 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. +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 (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) + 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 { + s.poke() + } + 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 + for { + var line []byte + select { + case <-ctx.Done(): + return ctx.Err() + case err := <-failed: + if errors.Is(err, io.EOF) { + return nil + } + return err + case line = <-lines: + } + 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 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) + 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 (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. +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. Once +// closed, when Run returns, it writes nothing. +type wire struct { + mu sync.Mutex + w io.Writer + closed bool +} + +func (w *wire) send(v any) error { + data, err := json.Marshal(v) + if err != nil { + return err + } + 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) + +// 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"` + 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 = 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}} + 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"} + } + 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 { + 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 := sentSize(h.Op) + if len(page.Ops) > 0 && size+data > pageSize { + page.More = true + break + } + size += 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..5ff2963 --- /dev/null +++ b/addon/server_test.go @@ -0,0 +1,705 @@ +package addon + +import ( + "bufio" + "context" + "encoding/json" + "errors" + "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. 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 + 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() + + 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 { + 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) +} + +// 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) + } +} + +// 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 new file mode 100644 index 0000000..98d9cdc --- /dev/null +++ b/addon/types.go @@ -0,0 +1,200 @@ +// 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, 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 ( + "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. +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), 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 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 + 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 +// _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. 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,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; 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. + // 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. +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"` +} + +// 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"` + 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"` // a watch's call's only: an emoji for the message it took +} + +// 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 + 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. +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"` +} + +// 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 153035b..507de4a 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 | @@ -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; `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` | +| `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..e94c40e 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,16 @@ The model can call tools from [MCP](https://modelcontextprotocol.io) servers, re "alerts": {"tool": "get_alerts"} } }, + "geo": { + "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": "/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}} + }, "files": { "command": "uvx", "args": ["some-mcp-server"], @@ -71,7 +82,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, 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 | **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 +98,60 @@ 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](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 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. + +```jsonc +"geo": { + "command": "/opt/signalbot-addons/geoguess", + "chat_commands": {"geo": {"tool": "geo", "direct": true, "example": "/geo 3m", "timeout": "60s"}}, + "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} + // "model": {"per_hour": 30, "max_tokens": 4000}, only for an addon that asks the model + } +} +``` + +| 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) | +| `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. + +**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, 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. 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. +- **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). +- **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`). + --- [Back to README.md](../README.md) 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/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..4c6f0f3 100644 --- a/examples/signalbot-mcp.json +++ b/examples/signalbot-mcp.json @@ -10,6 +10,16 @@ "alerts": {"tool": "get_alerts"} } }, + "geo": { + "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": "/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}} + }, "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..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/bot/answer.go b/internal/bot/answer.go index bad01a2..85833bb 100644 --- a/internal/bot/answer.go +++ b/internal/bot/answer.go @@ -56,18 +56,29 @@ 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, 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 +// 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) { + 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.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()), 0, nil) + if act.OnSent != nil { + act.OnSent(sent, len(sent) == 0) + } return case b.ai == nil: return // no model: no typing, no reply @@ -79,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, nil) } else if msg.Timestamp != 0 { // a scheduled post can't be reacted to b.net.React(msg.Chat, msg, waiting) } @@ -98,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, nil) return } if t = b.buildTurn(msg, text); t.empty(msg) { @@ -138,21 +149,10 @@ 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, nil) 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 +164,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..ebe7dee 100644 --- a/internal/bot/bot.go +++ b/internal/bot/bot.go @@ -30,19 +30,33 @@ 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. - Send(chat feature.Chat, text string, pics []feature.Picture, known map[string]string) (sent []int64) + // timestamps of the messages sent, which name them for a later delete; + // 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. 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()) // 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 + // 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 @@ -53,6 +67,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 } @@ -97,6 +117,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") @@ -139,7 +160,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() @@ -166,8 +187,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 +214,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 +242,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, 0, nil) + b.chats.Retag(key, p.ID, botRefs(sent)) + return sent } // botRefs names the messages the bot sent, by Send's timestamps. @@ -288,11 +311,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.OnSent(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.OnSent(nil, true) + } } } @@ -300,9 +355,11 @@ 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, 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() { @@ -320,8 +377,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 +391,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.OnSent(nil, true) // if shutdown began first + return + case Reacted: + alone(func() { b.react(r) }) return case Incoming: p = r @@ -347,8 +409,11 @@ 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.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) { @@ -478,13 +543,50 @@ 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 } } 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, 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 { + 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() + } + }() + 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. type introLine struct { text string diff --git a/internal/bot/bot_test.go b/internal/bot/bot_test.go index 7a4cffd..7d26c2d 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) { @@ -423,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 a5142be..d16d2c0 100644 --- a/internal/bot/fakes_test.go +++ b/internal/bot/fakes_test.go @@ -53,8 +53,11 @@ 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 + fail atomic.Bool // while set, Send fails: nothing is sent + watch Watch // what Watch was told } type sent struct { @@ -62,9 +65,14 @@ type sent struct { text string images []feature.Picture known map[string]string + reply int64 } -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 @@ -81,9 +89,13 @@ func (n *fakeNet) WaitID(ctx context.Context) string { } } -// Send returns one timestamp per call, counting up from 5000. -func (n *fakeNet) Send(chat feature.Chat, text string, images []feature.Picture, known map[string]string) []int64 { - n.sent <- sent{chat, text, images, known} +// 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, audio []byte) []int64 { + if n.fail.Load() { + return nil + } + n.sent <- sent{chat, text, images, known, replyTo} return []int64{5000 + n.sends.Add(1)} } @@ -96,7 +108,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) { @@ -113,6 +129,15 @@ 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) Name() string { return "fake" } func (n *fakeNet) BotName() string { return "Botty" } // Prompt is Signal's, so the golden prompt holds with no features. @@ -314,6 +339,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 08f9d35..63c8247 100644 --- a/internal/bot/host.go +++ b/internal/bot/host.go @@ -8,12 +8,16 @@ 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" + "github.com/robdevops/signalbot/internal/model" ) // The ports. Features call them while they register, before Run. @@ -89,7 +93,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 = "" @@ -103,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) }) } @@ -128,19 +151,108 @@ 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 OnSent is called +// once, whatever happens to it. +func (b *Bot) Post(p feature.Post) { + p.OnSent = once(p.OnSent) + switch { + case b.closing.Load(), p.Text == "" && len(p.Pictures) == 0 && len(p.Audio) == 0: + p.OnSent(nil, true) + default: + b.post(Outgoing{Post: p}) + } +} + +// 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 onSent != nil { + onSent(sent, dropped) + } + }) } } -// 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) +// 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, 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: its chat isn't reachable") + return + } + 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, 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, p.Audio) + 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. +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 + 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 +} + +// 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) + } } } @@ -164,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) + b.net.Send(e.Chat, reply, nil, known, 0, nil) return } } @@ -184,7 +296,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.hooked(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..de103d8 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" @@ -147,6 +148,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 @@ -614,3 +619,369 @@ 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 mu sync.Mutex // OnSent runs on the chat's worker + var sentAt [][]int64 + 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} + }) + 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") + } + mu.Lock() + defer mu.Unlock() + 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. OnSent is called once: when it is sent, or dropped. +func TestPost(t *testing.T) { + h := start(t, options{}) + type outcome struct { + sent []int64 + dropped bool + } + outcomes := make(chan outcome, 16) + post := func(p feature.Post) { + p.OnSent = func(sent []int64, dropped bool) { outcomes <- outcome{sent, dropped} } + h.b.Post(p) + } + next := func() outcome { + t.Helper() + select { + case d := <-outcomes: + return d + case <-time.After(5 * time.Second): + t.Fatal("OnSent never called") + return outcome{} + } + } + 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("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 { + 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?"}) + + // 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 { + t.Fatalf("OnSent got %+v", d) + } + } + post(feature.Post{Chat: group}) // nothing to send + if d := next(); !d.dropped { + t.Fatalf("OnSent got %+v", d) + } + h.settle() + h.noSend() + if len(outcomes) != 0 { + t.Fatalf("OnSent called again: %+v", <-outcomes) + } + 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") { + 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 OnSent 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", OnSent: func(_ []int64, d bool) { dropped <- d }}) + if !<-dropped { + 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) + } + h.release() + for range 2 { + if s := h.nextSend(); s.text != "ok" { + t.Fatalf("sent %+v", s) + } + } + h.settle() + 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 +// 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) + } +} + +// 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/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..e5c5412 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, 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) + switch { + case c == nil: + return errFull + case c.busy && len(c.low) > 0: + c.low[0] = merge(c.low[0], m) + 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) @@ -331,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 c60efc0..edb1f07 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(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); 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); 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) + 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) { @@ -329,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/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/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..35a0be2 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 @@ -42,7 +56,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. @@ -104,18 +118,28 @@ 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, 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 +} + +// 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.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 } @@ -171,6 +195,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 @@ -188,6 +213,17 @@ 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 + 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 +} + // Group is a group chat. type Group struct { ID, Name string @@ -197,7 +233,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,16 +280,29 @@ 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. 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) - // 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/feature_test.go b/internal/feature/feature_test.go new file mode 100644 index 0000000..03140fa --- /dev/null +++ b/internal/feature/feature_test.go @@ -0,0 +1,43 @@ +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{{}}}, + "ToolChoice": {ToolChoice: "t"}, + "Context": {Context: "c"}, + "Done": {Done: true}, + } { + if a.IsZero() { + 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, 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) + } + 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..e856c9d 100644 --- a/internal/feature/featuretest/featuretest.go +++ b/internal/feature/featuretest/featuretest.go @@ -37,8 +37,10 @@ type Host struct { more []string timers []*Timer delivered []feature.Message - told []Told + 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 @@ -160,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 @@ -200,20 +215,39 @@ 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. 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() + h.posts = append(h.posts, p) +} + +// Posts is the posts passed to Post, in order. +func (h *Host) Posts() []feature.Post { h.mu.Lock() defer h.mu.Unlock() - h.told = append(h.told, Told{user, text}) + return slices.Clone(h.posts) +} + +// Reaction is a reaction passed to React. +type Reaction struct { + Chat feature.Chat + Message feature.Message + Emoji string } -// Told is a text passed to Tell. -type Told struct{ User, Text 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 +290,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..3d80cd2 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() @@ -105,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/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..1b188f1 --- /dev/null +++ b/internal/features/mcp/addon.go @@ -0,0 +1,403 @@ +package mcp + +import ( + "cmp" + "crypto/hmac" + "crypto/rand" + "crypto/sha256" + "encoding/base32" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "regexp" + "slices" + "strings" + "sync" + "time" + + ext "github.com/robdevops/signalbot/addon" + "github.com/robdevops/signalbot/internal/feature" + "github.com/robdevops/signalbot/internal/kit/txt" +) + +// 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"` + 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, rateSettings its +// rate's and modelSettings its model's. +var ( + 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 +// (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) + } + 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: + 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) + 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 +} + +// 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. +// 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) { + 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 + 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 + asks *limiter // its requests to the model, all chats as one; nil without the permission + + 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 + 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 + 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 + 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. +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), 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{}, posted: map[string]posted{}} +} + +// 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) +} + +// 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) ext.Context { + 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 := 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 + } + 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..695084d --- /dev/null +++ b/internal/features/mcp/addon_test.go @@ -0,0 +1,775 @@ +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" + + 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" +) + +// 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.Method == "notifications/cancelled" { + fakeLog("cancelled " + string(sc.Bytes())) + } + if req.ID == nil { + continue + } + id, p := *req.ID, req.Params + switch req.Method { + case "initialize": + caps := `{"tools":{}}` + 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"}}`) + 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]ext.Context + json.Unmarshal(p.Meta, &meta) + reply(id, text("you said "+p.Arguments["args"]+"\n{"+meta[ext.KeyContext].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},"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}) || 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}) || 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, 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) + 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, 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") + 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_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) { + 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]ext.Context + if err := json.Unmarshal([]byte(got.Answer), &meta); err != nil { + t.Fatalf("ctx %q: %v", got.Answer, err) + } + 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 || + 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") { + 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 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) { + 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]ext.Context + json.Unmarshal([]byte(h.Message(context.Background(), in(inDM, "/ctx")).Answer), &meta) + return meta[ext.KeyContext].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") +} + +// 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") + } +} diff --git a/internal/features/mcp/conn.go b/internal/features/mcp/conn.go index 3784b48..b76d2b1 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" @@ -34,91 +35,248 @@ 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") +) + +// 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, // 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 + 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 + 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 nextID atomic.Int64 - mu sync.Mutex // guards stdin, pending and done + 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 } +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, c.state) + } 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.stdin, c.pending, c.done, c.life = stdin, map[int64]chan rpcMsg{}, done, ctx 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) 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) }() 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 +297,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.bot) 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) + } } } @@ -159,22 +321,115 @@ 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 { + case c.updated <- struct{}{}: + default: + } + } +} + +// 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 { @@ -185,7 +440,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,28 +452,37 @@ 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() 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 { case m, ok := <-ch: if !ok { - return nil, errors.New("server exited") + return nil, errExited } if m.Error != nil { return nil, m.Error } 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}) } @@ -228,9 +492,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 @@ -247,7 +512,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) @@ -257,7 +522,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 } @@ -347,7 +612,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() @@ -355,9 +620,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/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..fa441c9 --- /dev/null +++ b/internal/features/mcp/direct.go @@ -0,0 +1,158 @@ +package mcp + +import ( + "cmp" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "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" + "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, 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 + +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 string, c chatCommand, 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) + 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": c.Tool, + "arguments": map[string]string{"args": args}, + "_meta": map[string]any{ext.KeyContext: cc}, + }) + 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, c.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) + var w *watch + if r.Meta.Watch != nil { + 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() { + 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/interop_test.go b/internal/features/mcp/interop_test.go new file mode 100644 index 0000000..897a9e5 --- /dev/null +++ b/internal/features/mcp/interop_test.go @@ -0,0 +1,87 @@ +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 + } + 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 + }, + }, + { + 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/keep.go b/internal/features/mcp/keep.go new file mode 100644 index 0000000..0beebe0 --- /dev/null +++ b/internal/features/mcp/keep.go @@ -0,0 +1,204 @@ +package mcp + +import ( + "cmp" + "context" + "maps" + "regexp" + "slices" + "strings" + "unicode/utf8" + + "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, 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 + Posted map[string]posted `json:"posted,omitempty"` // by post op ID +} + +// 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 { + gone := !now.Before(w.Until) + if gone { + a.endedLocked(w, now) + } + return gone + }) + if len(ws) == 0 { + delete(a.watches, key) + continue + } + a.watches[key] = ws + for _, w := range ws { + c := *w + c.Pictures, c.Sent = slices.Clone(w.Pictures), slices.Clone(w.Sent) + 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) + } + } + 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)) + }) + 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: a reply watch's pattern isn't checked against ordinary chat. +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 || utf8.RuneCountInString(w.Pattern) > maxPattern || !w.Replies && ordinary(re) || + len(a.watches[l.Chat.Key()]) >= maxWatches { + continue + } + 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) + } +} + +// 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..a87b3a0 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 ( @@ -17,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" @@ -47,15 +51,22 @@ 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. +// 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 @@ -63,8 +74,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", "timeout"} ignored = []string{"type", "transport", "timeout", "alwaysAllow", "autoApprove", "description"} ) @@ -75,24 +86,68 @@ 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.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 } func load(path string) (map[string]server, error) { @@ -140,6 +195,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) } + 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 == ""): @@ -147,6 +217,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 +278,63 @@ 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 +} + +// 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 + 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, 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, WatchReactions: 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{}, - "clientInfo": map[string]string{"name": "signalbot", "version": version}, + "capabilities": caps, + "clientInfo": map[string]string{"name": "signalbot", "version": self.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 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)), + addon: addon, + subscribe: r.Capabilities.Resources.Subscribe, + }, c.notify(ctx, "notifications/initialized", nil) } // tool is a tool as a server lists it. @@ -221,8 +342,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,29 +368,64 @@ 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") + 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 + 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) + } + }() 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} + 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 != "" { - c = &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) + s.state = addonStateDir(stateDirectory, name) + } + 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, sent, 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: %v", name, err) + gt.open(nil) + 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 +436,33 @@ 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, ext.Version) + 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]) + 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, 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 +487,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 +531,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 +577,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 +599,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, args) } return feature.Action{ToolChoice: model} }) @@ -385,18 +618,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, self botInfo) ([]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, self) if err != nil { - return nil, "", err + return nil, handshake{}, err } var tools []tool cursor := "" @@ -407,19 +641,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 +681,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 +709,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 *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 70f1dec..67580ea 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" @@ -89,6 +90,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 +105,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[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 { @@ -177,7 +185,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 +194,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,9 +256,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)`, - `{"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","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 { @@ -398,12 +409,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 { @@ -479,12 +490,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 +512,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 +574,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 +663,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 +678,9 @@ 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) != 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 new file mode 100644 index 0000000..e23188e --- /dev/null +++ b/internal/features/mcp/outbox.go @@ -0,0 +1,542 @@ +package mcp + +import ( + "cmp" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "maps" + "slices" + "strings" + "time" + "unicode/utf8" + + 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" +) + +// 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": ext.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) + } + } +} + +// 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": ext.OutboxURI + "/" + cursor}) + cancel() + var r struct { + Contents []struct { + Text string `json:"text"` + } `json:"contents"` + } + var p ext.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 ext.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.waitsToPost(o.ReplyTo): + again, a.missed = true, true // after the post it replies to + 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 "" +} + +// 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) { + 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}, 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 && len(out.Audio) == 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, the ops it carries, and the ID of +// the post op it replies to, if any. +type outgoing struct { + feature.Post + 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 != "" || 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...) { + size += len(pic.Data) + } + 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 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) { + 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 = merged(last.Text, out.Text) + 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, 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) + if len(p.Pictures) > 0 { + a.guardPosted(p.Chat, sent) + } + a.rememberPosted(id, out.ops, sent) + } + a.sent(out.ops, !dropped) + 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. +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 { + 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: + } +} + +// 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 + if gone { + a.endedLocked(w, a.now()) + } + 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/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 new file mode 100644 index 0000000..5739fac --- /dev/null +++ b/internal/features/mcp/watch.go @@ -0,0 +1,582 @@ +package mcp + +import ( + "context" + "encoding/json" + "errors" + "regexp" + "slices" + "strings" + "sync" + "time" + "unicode/utf8" + + 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 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 + 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} + +// 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. 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 + 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 + 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 +} + +// 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 + // 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 +// 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 ext.Watch) *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 == "" || 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 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): + return refuse("its until has passed") + } + if re, err = regexp.Compile(spec.Pattern); err != nil { + return refuse("its pattern isn't RE2") + } + 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), 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 + 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 { + 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() + 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() +} + +// 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) { + if len(sent) == 0 { + return + } + now := a.now() + found := false + a.mu.Lock() + for _, w := range a.watches[chat.Key()] { + 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 + } + } + a.mu.Unlock() + if found { + a.changed() + } +} + +// 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 { + // 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 + } + 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 +// 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. 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{} + } + 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) && a.takes(w, m) { + 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} + } + } + // 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 +// 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": args(m), + "_meta": map[string]any{ext.KeyContext: 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 != "" && 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) + } + } + 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 { + 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{}} +} + +// 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 { + 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..a91cc96 --- /dev/null +++ b/internal/features/mcp/watch_test.go @@ -0,0 +1,1320 @@ +package mcp + +import ( + "bufio" + "bytes" + "cmp" + "context" + "encoding/base64" + "encoding/json" + "fmt" + "os" + "path/filepath" + "regexp" + "slices" + "strconv" + "strings" + "sync" + "testing" + "time" + "unicode/utf8" + + 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" +) + +// --- 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]ext.Context + json.Unmarshal(meta, &m) + line, _ := json.Marshal(guessed{args["text"], m[ext.KeyContext]}) + 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, ext.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 ext.Context +} + +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(ext.Watch{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}, false) + } + 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) ext.Context { + t.Helper() + 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[ext.KeyContext] +} + +// 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,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) + } + } + + // 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; 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(`,"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 { + 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.OnSent == 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].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) + } + + // Dropped before it was sent, as while the bot stops: posted again, + // one by one, as nothing waits. + h.Posts()[1].OnSent(nil, true) + eventually(t, "the post again", func() bool { return len(h.Posts()) == 3 }) + h.Posts()[2].OnSent([]int64{2}, false) + eventually(t, "the next post again", func() bool { return len(h.Posts()) == 4 }) + 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) + } + + // 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].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. + 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 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 +// 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 := []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 []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) + } + } + 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].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) + } + 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.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) + } + *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()) + } +} + +// 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 + }()) + } +} + +// 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. +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) 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) { + 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]any)["text"].(string)) + 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") + } +} + +// 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) + } +} + +// 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) + } + } +} + +// 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) + } +} + +// 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") + } +} + +// 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) + } +} 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/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"}}`}) 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..d681c37 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, nil); !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, 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+"]" || @@ -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, 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) + } 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, 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); !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") { @@ -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 { @@ -531,7 +541,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 +603,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 +675,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 fafce92..5158ed7 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) { @@ -500,3 +512,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("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("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..d08d046 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,62 @@ 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}, + {"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); 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") + } + 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) { @@ -262,6 +310,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/signal/markdown_test.go b/internal/signal/markdown_test.go index 1717a7f..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"}) + 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) + 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/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/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/signal/send.go b/internal/signal/send.go index 03d407a..ae91607 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, audio []byte) (sent []int64) { if n := utf8.RuneCountInString(text); n > maxReply { logx.Warnf("reply truncated from %d chars", n) } @@ -56,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) @@ -70,7 +74,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 +107,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..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) + 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) - c.Send(dm, "", []feature.Picture{{Data: []byte("PNG")}}, nil) + 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) + 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 efbb089..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 } @@ -183,6 +187,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 != "" { @@ -197,8 +204,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/decode.go b/internal/telegram/decode.go index 548149e..2b7e182 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("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/send.go b/internal/telegram/send.go index 2116b54..d801559 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, audio []byte) (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 { @@ -85,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 } @@ -94,6 +103,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 +122,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 +221,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 +234,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 +266,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 @@ -261,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. @@ -274,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) + 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 40b58d7..4cddf9a 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) { @@ -268,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, nil) if !reflect.DeepEqual(ids, []int64{500}) { t.Fatalf("ids %v", ids) } @@ -281,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, 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) } @@ -292,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, 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" { @@ -308,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, 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); !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"`) { @@ -323,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, nil) + 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, 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, 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) + } +} + // A reaction Telegram refuses is sent as a message. func TestReact(t *testing.T) { f := newFake(t) @@ -408,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, nil) out := logs.String() if !strings.Contains(out, "getMe failed") || !strings.Contains(out, "send failed") || strings.Contains(out, "SECRET") { t.Fatalf("logs %q", out) @@ -450,6 +510,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) { @@ -478,9 +558,9 @@ 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.groupAllowed(context.Background(), groupS) // Alice is in it - c.Send(feature.Chat{GroupID: groupS}, "hello", nil, nil) // message 500, the bot's + 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, 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 { @@ -560,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, 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); !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") @@ -584,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, 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) - c.Send(feature.Chat{GroupID: "-4444444"}, "two", nil, nil) + 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"]) @@ -629,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, nil) if s := f.callsTo("sendMessage")[0].Params; s["chat_id"] != groupS || s["message_thread_id"] != float64(7) { t.Fatalf("sent %v", s) } @@ -659,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, nil) if s := f.callsTo("sendMessage")[0].Params; s["chat_id"] != "-1009999999999" { t.Fatalf("sent to %v", s["chat_id"]) } @@ -730,7 +810,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 { @@ -738,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) + } +} 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..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" { @@ -1251,13 +1265,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 +2006,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})