# How Dictator is built The pieces, what isolates the agent, and the VM's storage. ## Pieces To add a plugin, a tool, a chat control or a Telegram action, see [CONTRIBUTING.md](../CONTRIBUTING.md). What the agent can do in Telegram is the catalog `packages/LocalAgent/Sources/LocalAgent/Resources/telegram-tools.json`; `scripts/telegram-coverage.py` prints it as a table. Dictator loads the bundled Telegram action catalog and derives its MCP schemas once per process. - This repository, checked out by Telegram for macOS as the submodule `tools/agent-harness`: - `HarnessCore` is the VM, proxy, sockets, action queue, policies and Mac scripts. For a reconnecting chat client it keeps up to 400,000 UTF-8 bytes of streamed reply text per turn. The replay ends on a complete Unicode scalar. The connected client still receives each full update. - On-device media and language tools cancel their worker task when the caller's deadline expires. Audio extraction for transcription removes its temporary output if the export fails or is cancelled. Concurrent attachment briefs for the same content and MIME type share one local analysis. Each attachment still gets its own entry in the message. - `AgentHarnessApp` is the app (a window plus a menu bar item): Connect to Telegram, start and stop, VM setup, plugins, the model provider and key, Telegram and Mac permissions, approval alerts for Mac scripts, and the activity log. `HarnessController` holds the app state; its plugin and MCP, secret and memory actions are in `HarnessController+Plugins.swift`, `+Secrets.swift` and `+Memory.swift`. Every view only calls the controller, and the controller only calls `HarnessCore`, so the same work stays reachable from chat. With macOS Reduce Motion on, the Settings header changes position and scrolls to the top without animation. - Before pasting dictated text, Dictator checks the clipboard formats so it can restore ordinary contents afterward. If any item declares `org.nspasteboard.ConcealedType`, Dictator skips reading and restoring the clipboard contents. - During cold start, readiness polling stops when the VM has stopped and its link is no longer current. - Chat session mappings and run IDs are written in order so overlapping updates survive a restart. - `agent-harness` is the same core as a command line tool, for scripting and tests. - `third-party/agent-desktop` is a submodule: [agent-desktop](https://github.com/vercel-labs/agent-desktop) by Vercel Labs (Apache-2.0). `build.sh` builds it and ships it inside the app with its license, and the built-in Mac apps plugin runs it to see and operate apps on the Mac. Mac app commands keep up to 256 KiB of helper stdout. Larger output is drained and reported with the same truncation marker used for the 60,000-character limit. - `packages/LocalAgent` is the Telegram transport: - `LocalAgentClient` talks to the socket (status, providers, pairing, credentials, messages, voice) and refuses any socket that isn't served by a binary signed as `org.telegram.agent-harness` by team `6N38VWS5BX`. - `LocalAgentActionService` runs the agent's Telegram actions. - `packages/AIAssistantUI` is the Telegram UI: - `AIAssistantService` polls `/v1/status` every 2 seconds. When the harness asks to pair, Telegram shows `AIAssistantConnectController` (the permission sheet). - `AIAssistantChatContents` is the pinned chat (`ChatCustomContentsKind.aiAssistant`). History is stored in the account folder (`ai-assistant/history.json`). Voice messages are sent as audio and transcribed by the Whisper plugin in the VM. Whisper decodes the uploaded bytes in memory without staging a temporary audio file. `/new` or `/reset` starts a fresh conversation. When Dictator hands a reply off for delivery as a separate chat message, the live turn keeps its delivery marker and releases its copy of the final reply body. - `AIAssistantSettingsController` is Settings → AI Assistant: status, model, provider and key, clear history and disconnect. - Telegram actions follow the policy in the app (Settings → Telegram). Each action is set to Allow, Ask or Never; out of the box reading and searching are allowed and everything that writes (sending, reacting, pinning, deleting) asks first. Full access is off by default. Turned on, what the user asks for runs without asking, sending included (replies, silent, scheduled, files, forwards), while deleting, editing, blocking, leaving chats, privacy and admin changes and starting a live location share still ask, and so does anything a hook or an automation writes. An "on" stored before the permissions file had `"version": 2` is not carried over, because Full Access used to be the default and still asked before sending. The app sends the policy with every action, and Telegram applies it with rules no setting can change: - secret chats and service notifications (777000) are never available; - blocked chats are refused. - The name lookup used for Telegram routing reads chats, then contacts. If the user declines either read, the current lookup stops and automatic name refreshes for that account pause until Dictator restarts. - Clearing Telegram Activity discards any refresh that began before the log was cleared. The page then reads new activity from disk. - Video analysis samples frames through AVFoundation. Samples that resolve to the same source timestamp reuse the Vision result within that request. Each sample still appears in the response. - Widgets: ask for weather, a chart, a tracker or a game and the agent builds an interactive widget that appears right in the AI Assistant chat. Widgets are written in Loom (see "Loom widgets" below) and drawn natively by Telegram. Widgets can call back into the VM for live data (a refresh button), and the agent keeps each widget's source and handler in the VM to reuse or redesign later. - Changing Telegram itself: ask for a panel, a button on messages, a badge on chats, a tab, a widget, a settings page, a /command or an automation ("make me a panel that shows unread mentions from work chats") and the agent builds it as an add-on, tests it on a sample account, shows a preview and applies it live after one confirmation in the AI chat. Ask to change one of Telegram's own screens ("put the chat list on the right") and it edits that screen; the change follows app and screen updates. Sign-in, passcode, proxy, recovery, payments, wallet and privacy screens can't be changed. Each change can be undone; Settings → Plugins lists the add-ons the assistant made. See [docs/building-ui.md](building-ui.md). - Removing an app hook also removes its queued message batches from the local hook inbox. Removing an agent's hooks clears only the batches owned by those hooks. - The Computer overview waits for the current VM stats request before starting another poll and discards results from a previous VM run. - A plugin install completes only after Dictator saves its registration. If registration fails, Dictator reports that failure and ends the current startup attempt. - Settings refreshes time-sensitive labels once per second while its window is visible. The ticker pauses when the window is fully covered and refreshes the page when it becomes visible again. - When the macOS user session becomes inactive, Dictator suspends the dictation shortcut and microphone readiness. Dictation uses its usual availability checks when the session becomes active again. - Queued app hook batches are checked against the hook’s current explicit chat list before running or retrying delivery. - The Desktop view forwards keyboard input to the guest only while Take Over is enabled. The preview thumbnail stays passive. - Background tasks: ask the agent to do something in the background and keep chatting. It runs in its own session and the report appears in the AI Assistant chat when it's done. When a task reaches the restart limit, Dictator saves its failed state before notifying Telegram, and the task list stays readable while the notification waits. - Secrets (Settings → Secrets): the agent asks for keys by name, you paste them in Agent Harness, and they reach the VM as environment variables, never through the chat. The proxy strips them from model requests. - Terminal commands in the VM run without Hermes approval prompts (Settings → Model → Run commands without asking). - Remote control bot (Settings → Telegram, at the top; off by default): reach Dictator from your phone through a Telegram bot of your own. Create one with @BotFather (`/newbot`), paste its token (kept in the Keychain as `telegram-bot-token`, never in `config.json` or the journal), turn the switch on, press **Pair** and send the bot `/pair ` from your account within 10 minutes. Dictator long-polls the Bot API from the Mac (never from the VM), checks the token with `getMe` first, and runs one poller at a time (`TelegramBotRunner`). - Only the paired account, in its own private chat with the bot, is heard. Groups, channels, edits, other bots and other people are ignored without any reply (no message, button answer, inline result or typing), and nothing they send is downloaded, read or logged beyond their user id once in 10 minutes. Forwarded and via-bot messages from the owner are not run either, nor are messages a Business chatbot or an away message sent for the owner's account. A code works once; wrong codes get no reply, only arguments that could be a code count, they are limited per sender and 20 of them burn the code (Settings says so). Unpair, a new token or Remove forget the owner, stop a running bot answer and close its open questions. If another program polls the same token, Settings keeps saying so for 3 hours. - The owner's text goes through the same `/v1/message` stream as the AI Assistant chat (in process, chat `-268268`, titled "Telegram bot"), so it gets the same rules, goal and plan commands and journal lines, and is untrusted input like any typed message. The answer streams back while "typing…" shows: one message, sent after 0.6 s or 40 characters and edited at most every 1.2 s, continued in a new message at a paragraph, line or word break before 4096 characters; the final answer replaces what streamed. Telegram's rich thinking block (a draft showing the agent's latest tool steps) shows until the first text. Markdown arrives formatted (bold, italic, code blocks with their language, links, quotes, lists, tables as monospaced blocks); a table or a long structured answer goes as one Telegram rich message. `/stop` stops it and ends the message with a note. Background reports and late answers for that chat go to the bot, not to Telegram. - Everything else the owner sends goes the same way as in the AI Assistant chat: a voice note is transcribed (`audio`, needs the Whisper plugin; Whisper chooses among the Mac's languages and keyboards plus the owner's Telegram language, and is forced to one only when the Mac has just one); photos (largest size), files, videos, round videos, GIFs, stickers and audio files are downloaded with `getFile` (up to 20 MB each, 40 MB and 10 files per message, kept in memory) and sent as `files`; captions are the owner's own words; locations, places, contacts (with the vCard), polls and dice become short text notes. An album is one message: its parts are collected until 0.8 s pass without a new one or another message arrives. A file over the limit gets a clear reply; the rest of the message still runs. - Dictator strips Unicode directional controls from attachment names on intake and from filenames prepared for outgoing bot uploads. This prevents a filename from overriding the display order of its extension. - What the agent sends to that chat comes to the bot too: `send_file` as a photo, voice note, audio, video, GIF or document (multipart upload; a photo Telegram refuses goes as a document; a caption over 1024 characters follows as text), widgets as a short note that only Telegram on the Mac can show them, and timers, automations and app hooks for that chat as text. - Cancelling a timer while delivery is pending prevents a failed delivery attempt from adding it to the outbox. - While a bot turn runs, a confirmation that may be answered remotely also comes to the bot with ✅/✖️ buttons; the first answer, on the Mac or in the bot, counts and the other side shows the outcome. Remote kinds: sending a Telegram message, file or edit as you (`POST /v1/confirm` from Telegram), a Gmail send and giving the agent a file from the Mac. Everything else (deleting, money, Lockdown asks, auto-approve, VM internet, Claude Code, MCP tools, Blender, scripts) and every "Always" answer is given only on the Mac; for those the bot just says one is waiting there. A Telegram send that can wait (the app sends `lifetime`) keeps its bot buttons for up to 12 hours: after 170 s the desk answers `waiting` instead of `expired`, Telegram asks again with `resume: true` (same question, never posted twice), and a tap made in between is handed to the next poll. The agent's tool call has already returned `awaiting_approval` by then; Telegram runs the request and tells the agent when the user answers. - Every Mac confirmation except the Accessibility prompt and a combined guard card has an **Always** checkbox. Allow with it ticked answers yes from then on, Don't Allow answers no (`RememberedAnswers`, `remembered-answers.json`; MCP tools and Claude Code keep their own allow rule). The answer is keyed by the confirmation's kind and title, or by the host or exact address for guard web and network asks, and it is applied before any card goes to Telegram, the bot or the Mac. In Lockdown Mode a remembered allow is set aside and Dictator asks. Settings → Mac lists the remembered answers with Forget. An answer disappears after Dictator saves the change. If saving fails, the answer stays listed and Settings shows the error so the user can retry. Allow has no default Return shortcut on the Mac confirmation. Escape still declines it. - Mac scripts (Settings → Mac Scripts) are fixed AppleScripts in `MacScripts.swift`. The agent only supplies values, which are validated (lengths, ranges, https links only) and passed as `osascript` arguments, never as code. Each script is Allow, Ask me or Never. Ask me shows an alert from Agent Harness with the exact values. - Automatic Xcode workspace discovery gives its AppleScript helper one minute, including time to answer the first macOS Automation prompt. If the lookup times out, provide the workspace path directly. - A Claude Code job can be stopped as soon as it appears in the job list. If the stop reaches Dictator before launch, Dictator records the job as stopped and skips launching the local helper. - While there are unfinished video or audio uploads on the Mac, the media tool checks for abandoned chunks every 15 minutes. Chunks older than one hour are eligible for removal even if no new upload starts. - Temporary chats can use the Telegram phrasebook for direct replies. Their requests do not add phrases, increment phrase usage, or contribute language observations. - Phone Calls checks the connection again after approval. Disconnecting invalidates an outstanding request even if the service is reconnected before the user answers the prompt. - The Settings evaluation summary reads the newest run and its preceding run from the same suite from the end of the local log. - Tool learning: the harness watches every turn's tool calls through the proxy. - **Shortcuts.** Calls that worked are kept as shortcuts (`recipes.json`), and a similar request gets them up front, so it skips searching for and describing tools. - **Lessons.** A failed call becomes a lesson (`tool-learning.json`): a fix lesson when a later, similar call to the same tool got past the error, and a pitfall lesson once the same error repeats. Lessons are keyed by tool and error, and a new sighting updates the entry instead of rewriting it. Hermes's `` wrapper is removed before a result is judged. - **What isn't learned.** Errors about the user or the app (declined, not connected, switching accounts, read-only evaluation chats, permissions) never become lessons. Transient errors (try again, timeouts) only teach that retrying the same call worked. - **Which lessons a request gets.** A request gets at most 4, and only for the tools it is likely to use. A tool is predicted when the request's words mostly point to it: for each word, the share of past requests containing that word that used the tool. Words every request shares (like the evaluation preamble) count for little, and new words count against a match. Calls to sending tools keep only argument names. - **Credit and retirement.** A successful call clears earlier failure-only lessons for that tool. Lessons with a working fix can earn credit. A lesson is blamed if the same error comes back and dropped once blamed twice and more often than it helped. The same tool and error then aren't learned again for 90 days or until the tool's schema changes. A shortcut whose calls keep failing is dropped the same way. - **Schema changes.** When a tool's schema changes, its lessons and shortcuts are dropped. - **Scope.** User chats and evaluation chats learn; internal turns (background tasks, other agents) don't. - **Commands.** `/tools learned` shows the lessons and each tool's call count, failure rate and average time. `/tools learned off` stops sending lessons and shortcuts while learning continues; `/tools learned on` turns them back on, and `/tools learned reset` clears the saved lessons, tool profiles, and shortcuts, including shortcut candidates waiting for a turn to finish. It keeps the on/off choice. - **Measuring it.** `agent-harness eval --suite tools` and `--suite tools-again` run the same read-only tool tasks with different values. They are built from errors the agent really hit: bare `python`, `get_messages` without `message_ids`, `batch` calls missing `name`, a missing mission, and a busy web search. The table counts tool errors per case and marks with `*` the requests that got lessons or a shortcut. To compare, run `tools` to train, then `tools-again` with `/tools learned off` and with it on. - App Intents in Telegram (Shortcuts and Siri) cover ask, open chat, draft and unread count. Telegram no longer has an AppleScript dictionary. Mac MCP subprocesses use one JSON object per line. Dictator keeps partial lines between reads, scans incoming bytes for line endings, and decodes each complete line once before routing notifications and responses. ## What isolates the agent - Internet access is on by default: the VM gets a NAT network device so the agent can browse and download. Turn it off in Agent Harness → Model → Internet access, or with `agent-harness config set internet off`; the VM then has no network device at all. Changing it restarts the VM. - Either way, the host's channels are vsock ports only: the proxy (8080) for model calls, logs, tools and actions, and the agent API (8642) that only the host can open. The real model key never enters the VM, even with internet on. - The VM holds a placeholder model key. The host adds the real OpenRouter key from the Keychain. - Provider key checks and other host API calls that use the same transport, including Gmail requests, use a dedicated ephemeral HTTP session. Callers supply credentials explicitly. The session disables automatic cookies, credential storage and response caching. - The proxy allows only `chat/completions`, `models`, `generation` and `key`. It rewrites any model outside `model` + `allowedModels` to `model`, caps `max_tokens` and enforces a daily request limit. - The Hermes API server needs a key that is random on every boot and known only to the host. - `agent.sock` has mode 0600, and Telegram checks the code signature of the process serving it. A team-signed Dictator checks the other side too: it answers only Telegram (build 283390 or newer) and its own apps signed by the Telegram team, and a Developer ID build must also carry the hardened runtime and no `get-task-allow`, so an old or unhardened copy can't be used to carry someone else's code to the socket. The journal names the rule a refused process broke. - Dictator checks one delivered archive per build at a time. If Telegram delivers that build again while it is being checked, the original check keeps ownership of its staging folder. - A Dictator update is installed only when its archive carries the DSA signature from the appcast and the app inside is the announced build signed by the Telegram team. Once `Resources/keys/ed25519_pub.txt` is in the tree, builds made from it also ask for an Ed25519 signature (`sparkle:edSignature`) and never offer an item without one. `swift buildbox/ed25519-sign.swift generate ` makes the pair and prints the public key; CI signs with `ed25519_priv.txt` beside the DSA key and refuses to publish an update it can't sign. - The VM can ask for a Telegram action or a Mac script, but it can't change the policies: they live on the Mac, in files only your user can edit, behind the app's settings. - Every request is written to `~/Library/Application Support/AgentHarness/journal.log` (Settings → Activity). - If a run doesn't stop cleanly, the next one starts from the clean snapshot instead of reusing a possibly damaged disk. As a second layer, create a dedicated OpenRouter key with a spend limit. ## VM storage When recovery or a rebuild saves the working disk as a reset copy, the copies earlier resets kept stay: up to three are kept (`disk-before-reset.raw`, `disk-before-reset-2.raw`, `disk-before-reset-3.raw`), each for a week. Only when all three are in use does the new copy atomically replace the newest one, so the oldest disks are never the ones lost. If the rename fails, Dictator stops the reset or rebuild and preserves every disk. During guest startup, Dictator moves a database aside for repair only when SQLite finds corruption. A database that is busy or temporarily unreadable stays in place. Computer → Virtual machine → Storage shows where the VM lives and lets you move it to a folder on another drive (Change…) or back to this Mac (Use This Mac). Only the big files move: the VM disks, console logs and the image cache, into a `Dictator VM` folder there; settings, the journal, keys and memory stay in Application Support. `config.json`'s `vmLocation` holds the path (empty for this Mac). - Moving asks first, stops the agent, copies with clones or sparse copies (a sparse disk stays small on APFS), checks every file before switching and removes the old copy only after that. It refuses folders inside Dictator's own data, read-only drives, and formats such as FAT32 whose file-size limit is too small for the VM. On APFS it budgets the allocated bytes. On exFAT and HFS+ it budgets the full file sizes. Moves reserve another 1 GB, and setup checks that both the clean snapshot and working disk will fit on a volume without sparse files. - On volumes that support access permissions, Dictator sets the POSIX mode of its `vm` and `cache` directories to 0700 before copying files. Preparing an existing store also removes group and other-user permissions where the folder allows it; a folder that refuses is used as it is. - Ejecting the drive stops the agent first. While it's unplugged Dictator says so and never sets up a new VM in its place; plugging it back in starts the agent again.