* feat(bot): support direct binding of plugin commands (LANG-240) Co-authored-by: multica-agent <github@multica.ai> * fix(bot): address review feedback on command routing and migration (LANG-240) - Remove redundant cmd_mgr.is_admin call in routing layer - Move legacy YAML command config migration to startup build_app stage with idempotency flag - Validate that command_settings.plugins are installed in current workspace - Cache bot command_settings in memory via platform_mgr helper - Wrap command matching and execution inside _run_event_delivery for cloud tenant scope - Preserve original launcher_id type in session resolution Co-authored-by: multica-agent <github@multica.ai> * style(bot): apply ruff format to command routing changes (LANG-240) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * wip(command): command processor instances and per-command config (LANG-238) Work in progress handed off for completion; backend and tests are done, web pieces are partially written and not yet type-checked. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(command): complete command processor configuration UI Co-authored-by: multica-agent <github@multica.ai> * fix(command): retain saved bot command settings when editing Co-authored-by: multica-agent <github@multica.ai> * test(command): exclude command instances from runner operations Co-authored-by: multica-agent <github@multica.ai> * test(command): verify bot prefixes and manage async test lifecycle Co-authored-by: multica-agent <github@multica.ai> * feat(platform): register Telegram and Discord plugin commands Co-authored-by: multica-agent <github@multica.ai> * fix(platform): align registration metadata and selected command diagnostics Co-authored-by: multica-agent <github@multica.ai> * fix(plugin): keep platform command refresh best-effort after runner refresh Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * refactor(web): simplify bot event routing card with tabs Split routes, plugin commands and plugin processors into tabs, collapse the supported events panel into a dialog, keep rule rows on a stable two-line grid, and show bound commands as compact chips. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * refactor(web): move command prefixes behind a small popover button Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * refactor(web): show commands, routes and plugin processors as separate routing layers Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(command): record command processor runs and support debugging Bot command executions and debug runs are written to the run ledger as command_processor runs, so processors get run history and traces. Debug runs a command line once with admin privilege without platform delivery. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(web): command processor logs, debug and plugin marketplace select Group plugin processors and command processors under a From plugin option on the processor creation page, redraw the processor type diagrams, add logs and debugging to the command processor detail page, list installed and marketplace command plugins with one-click install, and use a Remix icon for command processors in the sidebar. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * test(web): count new command processor locale keys Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(web): illustrate processor types with animated scenes Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * revert(web): restore original processor line diagrams and add a command one Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * test(web): count command diagram locale keys Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(web): progressive plugin options and a code-bearing plugin processor diagram Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * fix(web): command plugin wording in the plugin selector Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * test(web): count command plugin selector locale keys Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * test(pipeline): pin outer-stage behaviour before moving it to the message policy Baseline cases state a legacy pipeline config and the behaviour it must produce (group respond rules, access control, ignore rules, content filter, rate limit, long text, sending, user notices, aggregation). They reach the stages only through outer_stage_harness, so the same cases keep guarding behaviour once the configuration moves to the bot. Co-Authored-By: Claude <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(message-policy): add the bot message policy schema, runtime and manager A message policy says which messages a bot answers (trigger), what is checked on the way in and out (safety) and how replies are sent (output). It keeps the key names these settings had inside a Messaging (pipeline) config. - schema: neutral and default policies, bot + route merge, validation, and the single legacy conversion (split_legacy_config / restore_legacy_config). - runtime: the logic of the outer stages, compiled per effective policy (admission, group rules, rate limit, content filter, long text, sending). - manager: resolves the policy of a bot route and caches the compiled runtime per bot and route; the debug chat and unknown bots get the neutral policy. Group respond rules and the rate limit gain an explicit enabled switch so a policy can express "do nothing"; converted legacy settings state it as on. Co-Authored-By: Claude <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(message-policy): store policies on bots and migrate them out of Messaging - bots.message_policy (JSON) and an optional policy override on each route in event_bindings; BotService validates both. A route resubmitted without the policy key keeps its stored override, so older clients cannot drop it. - Migration 0049: existing bots get the neutral policy and every route to a Messaging processor receives that processor's former settings as its override; the moved keys are kept verbatim in legacy_pipelines.message_policy_backup and restored on downgrade. - Messaging writes accept and ignore trigger / safety / general output keys; its template and form metadata keep only AI, speech and AI-specific output. - New bots start with the defaults new Messaging processors used to get. - GET /api/v1/platform/bots/_/message-policy/metadata serves the form metadata; MCP bot tools describe message_policy and route overrides. - The group-filter migration helper reads and updates the route policy. Co-Authored-By: Claude <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * refactor(pipeline): run the outer stages through the message policy runtime Stage order and position are unchanged. The group rule, access control, content filter, rate limit, long text and send stages become thin shells over the policy runtime of the route a message matched; user notices and the scheduler's steering gate use it too. The effective policy is laid over query.pipeline_config under the legacy key names, so plugins reading those keys keep working. Message aggregation reads the policy as well. The matched route id travels from routing through the aggregator to the query (_message_route_id, host-reserved). Messages that reach Messaging without one (web page widget, form callbacks) use the bot's first route to that processor. The baseline cases now run on legacy configs converted the way the migration converts them. Co-Authored-By: Claude <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * chore(persistence): renumber message policy migrations after master (0054-0056) Master added 0047-0053, so the bot command settings, platform command sync and bot message policy migrations now follow 0053_knowledge_artifact_sources. Also bind a message policy in the agent run recovery test, whose replayed output stages now read output and safety settings from the bot route. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(sdk): expose command processor configuration in execution contexts Co-authored-by: multica-agent <github@multica.ai> * feat(bot): dispatch plugin lifecycle hooks with route-scoped query and policy Co-authored-by: multica-agent <github@multica.ai> * fix(messaging): dispatch received hooks for direct pipeline queries Co-authored-by: multica-agent <github@multica.ai> * fix(messaging): tolerate queries without bound plugins in the received-hook fallback Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(messaging): apply bot policies to agent delivery Co-authored-by: multica-agent <github@multica.ai> * feat(web): bot plugins and message policy tabs, Chat rename - Bot event routing becomes three tabs: Routes, Plugins, Message policy. - Plugins tab: message lifecycle strip (received → command → admission → before reply → process → after reply → send) with the enabled plugins acting at each step; one row per plugin with its switch, command tags and hook tags. Hooks a route cannot use are struck through with the reason (prompt hooks on Agent routes, observe-only after-reply hook when streaming). Enable-all switch plus manual selection, as on Chat. Command settings and plugin processors live in the same tab. - Message policy tab: entry / safety / reply forms from the policy metadata, bot default or per-route override (use default / custom), route overview, "make bot default" which also clears routes left identical to it. - New routes show a hint that they inherit the bot policy. - Chat editor drops Trigger and Safety; Output keeps AI-only options with a pointer to the bot policy; the plugin list is "Tools the AI can call". - Installing a plugin with commands or listeners reports on how many bots it is enabled, or offers to go enable it. - User-visible "Pipeline/流水线" renamed to "Chat/聊天" in all eight WebUI locales (identifiers, paths and keys unchanged). - plugin-registrations (HTTP and MCP) accepts include_disabled to list every installed plugin for the editor. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(i18n): call the pipeline Chat in backend user-facing text Default name, runner authorization notice, operation catalog labels and summaries, alert email rule label, adapter streaming descriptions and MCP tool descriptions say Chat (pipeline). Identifiers keep pipeline. The group filter migration tools describe the message-policy at-bot rule. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(web): finish the Chat rename in locales and the migration dialog Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * chore(sdk): regenerate workspace proxy for monitoring.sessions launcher_id Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * docs: message lifecycle events, bot message policy and the Chat rename - Plugin docs: 'Pipeline events' become message lifecycle events with the lifecycle order, where plugins are enabled, which processors each hook applies to, known limits and platform notifications. - Command docs: matching before routes, route policy, *CommandSent. - Bots page: event routing tabs, plugin enablement, message policy. - Chat page and the rest of docs/ (zh/en/ja, regenerated recipes) use Chat instead of Pipeline; URLs and identifiers are unchanged. - langbot-mcp-ops skill, ARCHITECTURE.md and dev-docs/architecture/ message-policy.md describe the new contracts. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * fix(bot): keep the platform command clear in update_bot after the master merge The merge carried the branch's platform-command check into master's new _apply_bot_configuration, where update_data does not exist, so every runtime-affecting bot update returned 500. Run the check in update_bot before applying. Command admin checks now pass the sender ID. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * test(persistence): register all entities in the startup command migration test The test created bots without the tables its foreign keys reference and only passed when other tests had imported those entities first. Also apply prettier to AgentCreateContent. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * fix(messaging): use one listener list per query when no bot policy applies Queries entering a Chat without a bot (debug chat, pipeline.run) bound the neutral policy, so later hooks went to every plugin while the fallback *MessageReceived used the Chat's plugin list. Use the Chat's list for all hooks there. The contract test now carries the plugin selection the way migration 0060 stores it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(bots): move plugin command settings into the plugin list Drop the separate plugin command binding section from the bot's Plugins tab. The command switch and prefixes now sit in the plugin list header, per-bot command settings open from a plugin's row (only when its commands declare spec.config), and platform command registration follows the enabled plugins. Duplicate command names now resolve in the order of the bot's effective plugin list, the same order lifecycle hooks run in; the WebUI keeps that list in display order. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(bots): mark plugin hook badges with the event listener icon Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(bots): explain AI routes versus plugin handling on the bot tabs Routes now say they send events to configurable LangBot processors that use AI, and that a plugin-only bot can delete or disable its routes. The Plugins tab explains that plugins handle their lifecycle steps as each plugin defines. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(bots): optional route notes and auto-described routes Routes get an optional note, edited in the route's expanded panel and shown under the route. Wherever routes are listed (scope picker, policy route list) a second line now says when the route applies, derived from its conditions, plus its target when the name is a note, so routes stay distinguishable without any user input. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(bots): compact route cards and labelled message template routes Saved routes collapse to a two-line summary (note or processor, then event, conditions and target); event, conditions, processor and note are edited in the expanded card. Unsaved routes open expanded. The "Reply to messages" template and the setup wizard now label their routes as private messages and group messages that mention the bot. Also move the plugin processor compatibility e2e onto the Plugins tab, where plugin processors live since the message policy refactor. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(bots): keep bot-wide command settings read-only on route scope The plugin command switch, prefixes and per-plugin command settings apply to the whole bot, so they are read-only (with a hint) while a route is selected. Turning commands off crosses out every command badge. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * style(bots): make the crossed-out command badges easier to see Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(agents): stop offering command processors on the create page Command settings are created from a plugin's row on the bot's Plugins tab. The "From plugin" card now selects plugin processors directly; existing command processors keep their detail page. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(bots): install plugin processors from the marketplace in place The add-plugin-processor dialog's new-configuration tab keeps the installed processor list (with event compatibility) and adds a marketplace picker for plugins that declare processor support; installing one selects it. Bound and existing processors show their plugin icon, and the empty state points to the marketplace. Plugin-subscription e2e now opens the Plugins tab. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(plugins): point command and listener plugins to bots after install Commands and event listeners are enabled on a bot's Plugins tab now, so the post-install next step for them links to bots; tools still lead to a Chat. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(bots): pick plugin processors from a single picker The new-configuration tab drops the separate installed-processor list: one picker lists installed processors and marketplace plugins (installable in place), and the chosen processor's events and compatibility show below it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(plugins): show next steps on first visit and reload after confirming permissions - The plugin detail page opens a next-steps dialog the first time a ready plugin is visited (remembered per plugin). - After permissions are confirmed, the page polls until the plugin is mounted and remounts its settings, readme and log panels, so no manual refresh is needed. - The install dialog shows next steps under the permission-review link instead of hiding them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(plugins): say why plugin settings and docs are unavailable While a plugin waits for permission confirmation its settings and docs cannot load; show a dedicated notice pointing to Plugin permissions (or a starting indicator while it boots) instead of the generic load error. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(plugins): confirm permissions inside the install dialog A plugin awaiting permission review now shows the permission card in the install dialog; granting there opens the usual confirmation, and the dialog then switches to the success banner with its next steps. The first-visit next-steps popup on the plugin page is removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * fix(plugins): show next steps right after granting in the install dialog The plugin restarts after a grant, so re-reading it could fail or still report pending, leaving the dialog on the review banner. Trust the successful grant, keep the already loaded manifest, and retry loading it if it was missing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * fix(plugins): treat initialized plugins as running on the detail page The runtime moves plugins unmounted -> mounted -> initialized; initialized is the ready state. The detail page only accepted mounted, so running plugins showed "starting" forever. Also fix the misspelled status in the type. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * fix(plugins): re-read the plugin until it lists components before showing install next steps A plugin awaiting permissions is not started and reports no components, so the post-grant guide stayed empty. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(web): add bot plugins from a list and the Marketplace; rename event listeners to chat event hooks The bot Plugins tab now lists added plugins as cards (all of them when 'enable all' is on) instead of per-plugin switches, with an Add plugin dialog for installed plugins and Marketplace plugins that provide commands or chat event hooks. EventListener is shown as 'Chat event hook' in the UI. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(web): with all plugins enabled, the bot plugin list offers installing new plugins only Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(web): bot plugin Marketplace tab lists only uninstalled or updatable plugins Installed plugins with a newer Marketplace version get an inline Update. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * fix(web): no 'not enabled on any bot' toast for plugins installed from a bot's plugin list Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(web): move plugin dev docs link from the routing help popover to the Plugins tab Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(web): open a plugin's settings page from its card in the bot plugin list Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(web): describe commands, chat event hooks and plugin processors by how each handles events Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(web): drop the route overview list from the bot message policy tab The scope selector already marks which routes are customised. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(web): regroup bot message policy settings by what the owner decides The policy tab now groups settings into who gets replies, how messages are read, safety and rate limits, how the bot replies, and what happens on errors. Each setting shows a plain-language summary and expands to purpose- built controls; stored trigger/safety/output keys are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * refactor(web): use shadcn Button and Label for this branch's new UI Replace raw button, link and label elements added on this branch with shadcn Button (ghost / link / asChild) and Label. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(commands): add bot system commands and sender permissions Co-authored-by: multica-agent <github@multica.ai> * fix(commands): honor session model, replay text turns and gate denial replies Co-authored-by: multica-agent <github@multica.ai> * feat(web): one-page Chat settings with prompt, tools and knowledge up front Replace the Chat editor's section tabs with a single page: the runner, then primary blocks for model, prompt, tools (summary + side sheet) and knowledge, then folded rows with one-line summaries for context, run limits, sandbox, speech, reply content, notices, advanced and manage. Runner fields are placed by type and name, so any runner works; values and stored keys are unchanged. Folded rows stay mounted so invalid drafts still block saving. SettingRow/SettingGroup are shared with the bot policy tab. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * fix(web): keep folded setting rows mounted but hidden Radix forceMount forces content open; render the row body ourselves with the hidden attribute so folded rows stay collapsed while their fields keep validating. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(web): system commands and command permissions in the bot Plugins tab A small 'System commands · n/m' entry in the command bar opens a sheet with the admin list (person_ IDs, /whoami hint), the no-permission reply, every built-in command's switch and permission grouped by session/info/admin, and per-command permissions for enabled plugins' commands. Admin-only plugin commands show a lock on their chips; the lifecycle Command step marks the system commands. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(web): one-page Agent settings matching the Chat layout Replace the Agent editor's Runner / Events & tools tabs with one page: the runner, then model and prompt, the events the Agent handles, a tool access summary (editing in a side sheet), knowledge and runner settings, then folded rows for context, run limits, sandbox and advanced fields. The runner field layout is shared with Chat (runner-layout/RunnerConfigLayout). Loading fills the active runner's schema defaults before the clean snapshot, so required-field status and revert-to-clean keep working. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(web): 'Plugins & commands' tab with its own Commands section Rename the bot tab to Plugins & commands. Commands get their own section above plugins: one global switch, the shared prefixes (with an example, as they apply to system and plugin commands alike), the system commands entry and the plugin command list. Admins are no longer edited in the system commands sheet; it shows the bot admin count and links to the session monitor where admins are managed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(web): give system and plugin commands their own sheets The System commands sheet now lists only built-in commands; plugin command access moves to a 'Set access' sheet on the plugin commands row. Admins and the no-permission reply apply to both kinds, so they become rows of the Commands section instead of living in the system sheet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * fix(web): keep dividers between command access rows Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(web): link plugin processor dev docs from the processors section Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * fix(commands): use session monitoring admins for command permissions Co-authored-by: multica-agent <github@multica.ai> * chore(web): drop retired command_settings.admins from the bot command type Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * Record message policy decisions and add workspace upgrade checks Co-authored-by: multica-agent <github@multica.ai> * fix(message-policy): queue EssentialCommands uninstall through plugin.delete task The upgrade-check action called the plugin connector directly, skipping the tenant-scoped fence and task tracking used by the regular uninstall path. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * feat(web): message policy monitoring badges, timeline, route counts and upgrade checks - Monitoring: handling badges (system/plugin command, denied, policy drop, plugin interception), a handling filter (AI / command / plugin / policy) and a message policy timeline in the execution detail. - Backend: executions accept handling= (HTTP + MCP, not plugin-visible) and rows carry handling, policy_layer/item, command and hook facts. - Bot routes show last-24h handling counts. - Upgrade check banner + Sheet on bot and Chat pages with one-click actions, per-item and acknowledge-all; eight locales. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * fix(monitoring): name layer and rule for policy drops recorded before structured fields Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * fix(web): name command/policy/plugin ingress rows and dedupe output actions Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * fix(message-policy): preserve drop notices, Windows fallback, 0060 enabled filter, and ignore-rules hint Co-authored-by: multica-agent <github@multica.ai> * docs(message-policy): update trilingual user, upgrade, telemetry and command docs Co-authored-by: multica-agent <github@multica.ai> * Document bot command permissions and Chat event hooks in skills Co-authored-by: multica-agent <github@multica.ai> * Distinguish Chat debugging from bot admission tests Co-authored-by: multica-agent <github@multica.ai> * Navigate to Chats from Processors in skills and QA flows Co-authored-by: multica-agent <github@multica.ai> * Restore bot ingress tracing and align CI with route-owned message policies Co-authored-by: multica-agent <github@multica.ai> * fix(web): stop the bot plugins tab crashing without runtime registrations; align e2e with the Chat UI pluginCommandList read descriptorMap before its declaration, so the Plugins & commands tab threw a TDZ error whenever an enabled plugin had no Runtime registration (older Runtimes). Compute it after the map. Update stale Playwright specs to the current UI: Chat migration labels, one-page Chat editor (no AI tab, Runner field), 'Create processor' heading, and the in-dialog permission review after plugin installation. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * fix(telemetry): count builtin_disabled_bots only for built-ins turned off from their default /model is off by default, so counting any disabled built-in counted every bot and the heartbeat field carried no signal. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * fix(migration): preserve empty legacy chat settings on downgrade Co-authored-by: multica-agent <github@multica.ai> * fix(migration): initialize bot policies when resuming 0059 Co-authored-by: multica-agent <github@multica.ai> * test(commands): exercise LocalAgent over signed HTTP ingress Co-authored-by: multica-agent <github@multica.ai> * fix(api): report ignored legacy settings in chat copy requests Co-authored-by: multica-agent <github@multica.ai> * test(commands): cover alternate prefixes and unrouted group commands Co-authored-by: multica-agent <github@multica.ai> * fix(web): policy timeline says MessageReceived already ran when admission blocks MessageReceived fires at the bot entry before admission, so a policy drop still ran it. The hooks step now says so instead of 'not run'. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * fix(commands): consume silently denied commands before primary routing Co-authored-by: multica-agent <github@multica.ai> * Test upgrade assistant actions and command telemetry against a local Core Co-authored-by: multica-agent <github@multica.ai> * Verify lifecycle hooks and command bypass during message aggregation Co-authored-by: multica-agent <github@multica.ai> * Verify native Agent reply chunks and proactive delivery through signed callbacks Co-authored-by: multica-agent <github@multica.ai> * Cover subscriber replies on denied ingress and concurrent command rate limits Co-authored-by: multica-agent <github@multica.ai> * Verify LocalAgent records missing model failures for signed messages Co-authored-by: multica-agent <github@multica.ai> * Skip runtime synchronization for empty event selections after validating workspace scope Co-authored-by: multica-agent <github@multica.ai> * Verify route access overrides, removal and telemetry using signed bot messages Co-authored-by: multica-agent <github@multica.ai> * Exercise signed command admission and reply policies in a running Core Co-authored-by: multica-agent <github@multica.ai> * Compare dashboard debug chat with signed messages on the same Chat Co-authored-by: multica-agent <github@multica.ai> * Validate unavailable Agent runners and verify native quotes and Agent policy traces Co-authored-by: multica-agent <github@multica.ai> * Correlate successful Agent output with telemetry and exercise command hook order Co-authored-by: multica-agent <github@multica.ai> * Honor Chat exception policy for Runner failures and verify streaming observers Co-authored-by: multica-agent <github@multica.ai> * Verify OneBot membership events bypass message admission and reply policies Co-authored-by: multica-agent <github@multica.ai> * Exercise command name precedence and processor instance isolation in runtime Co-authored-by: multica-agent <github@multica.ai> * Accept ISO source times in runner events and verify long-text boundaries Co-authored-by: multica-agent <github@multica.ai> * Compare Chat output filtering on OneBot and HTTP Bot Co-authored-by: multica-agent <github@multica.ai> * Trace matched deliveries intercepted by message listeners Co-authored-by: multica-agent <github@multica.ai> * Record Chat execution owner with the first success update Co-authored-by: multica-agent <github@multica.ai> * Admit matched commands before recording listener interception Co-authored-by: multica-agent <github@multica.ai> * Handle stop on a Chat without a Runner and verify built-in command permissions Co-authored-by: multica-agent <github@multica.ai> * Link command processor runs to ingress routes and identify denied plugin commands Co-authored-by: multica-agent <github@multica.ai> * Report ignored legacy operation keys and limit Runner error replies to a redacted summary Co-authored-by: multica-agent <github@multica.ai> * style(web): wrap long monitoring timeline strings for prettier Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> * Dispatch QA Runner by envelope type and verify remaining command conflicts after uninstall Co-authored-by: multica-agent <github@multica.ai> * fix(persistence): chain bot command settings after master's 0057 migration master added 0057_agent_event_index on top of 0056, which left two Alembic heads. Run 0057_bot_command_settings after it; revision ids are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: multica-agent <github@multica.ai> --------- Co-authored-by: multica-agent <github@multica.ai> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
36 KiB
Architecture
This document is a map of LangBot's moving parts. It is intentionally more stable than a feature guide and more concrete than the README: when you need to change behavior, start here, then follow the file references into the code.
For agent-specific working rules, see AGENTS.md. For plugin-runtime and Box-runtime implementation details, also read the SDK map in sdk/ARCHITECTURE.md.
What LangBot Is
LangBot is an open-source platform for building production IM bots backed by LLMs, agents, RAG, plugins, MCP tools, and a web management panel.
At runtime, one LangBot process owns:
- a Quart/Hypercorn HTTP service and the built web UI on
:5300; - messaging-platform adapters such as Discord, Telegram, Slack, WeChat, QQ, WeCom, Lark, DingTalk, KOOK, LINE, Satori, Matrix, and HTTP/WebSocket bots;
- a pipeline engine that turns inbound platform messages into LLM/tool/plugin work and replies;
- persistence, storage, vector database, telemetry, monitoring, and configuration managers;
- bridges to the Plugin Runtime and Box Runtime provided by the plugin SDK (
sdk/, packagelangbot-plugin); - an MCP server at
/mcpexposing a curated agent-facing subset of the service layer.
Repository Boundary
LangBot is a monorepo whose parts are released independently.
LangBot/is the main product: backend, web UI, platform adapters, pipeline engine, HTTP API, MCP server, RAG, persistence, skills integration, and the bridge code that talks to runtimes.LangBot/plugins/contains the official plugin catalog (Runner/,KnowledgeEngine/,misc/). Sources share this checkout; each plugin retains independent tests, dependencies, versioning, packaging and Marketplace publication. Core wheels, sdists, Docker contexts, release ZIPs and fnOS packages exclude this tree. Seeplugins/RELEASING.mdandplugins/MIGRATION.md.LangBot/sdk/is published independently to PyPI aslangbot-plugin(tagssdk/vX.Y.Z, no GitHub Release). Core'suvsource maps its exact package requirement to editablesdk/; checkouts, Docker, release ZIPs and fnOS use this coordinated source. The standalone Core wheel excludes SDK code and retains the published PyPI dependency. The SDK contains plugin developer APIs, shared entities,lbp, the Plugin Runtime (lbp rt), and the Box Runtime (lbp box). Seesdk/RELEASING.md. It was imported from the archivedlangbot-app/langbot-plugin-sdkrepository at v0.7.24 (sdk/SOURCE.json).langbot-cliis a separately releasedlbctlclient for managing a running Workspace through the HTTP Service API; it is not part of the LangBot server or the SDK'slbpCLI.- Plugins import SDK APIs from
langbot_plugin.*; the LangBot main process imports the same package for shared entities and runtime protocols.
If a change modifies SDK entities, component APIs, action protocols, lbp rt, or lbp box, change sdk/ and the Core bridge in one PR, run the SDK tests in sdk/, and test Core through standard root uv sync. Source deployments can use the coordinated change immediately; publishing the standalone Core PyPI package still requires a matching SDK release and Core pin. Independently deployed Runtimes and plugins retain their own installation and compatibility requirements.
Startup Path
The process entrypoint is small and layered:
main.pydelegates tolangbot.__main__.main().src/langbot/__main__.pyparses--standalone-runtime,--standalone-box, and--debug, checks dependencies, generates missing config/data files, and callspkg.core.boot.main().pkg/core/boot.pyexecutes startup stages in order:LoadConfigStage,GenKeysStage,SetupLoggerStage,BuildAppStage,ShowNotesStage.BuildAppStageconstructs theApplicationobject by wiring managers, services, runtime connectors, and controllers.Application.run()starts the platform manager, query controller, HTTP controller, telemetry/cleanup loops, and plugin initialization.
The central runtime object is pkg/core/app.py::Application. It is a service locator for long-lived managers. That is not elegant, but it is the current architectural center; most subsystems receive ap: Application and collaborate through it.
Top-Level Layout
LangBot/
├── main.py # Entrypoint shim
├── pyproject.toml # Python package, deps, local SDK source
├── src/langbot/
│ ├── __main__.py # CLI entrypoint and boot handoff
│ ├── pkg/
│ │ ├── core/ # Application, boot stages, task manager
│ │ ├── api/ # HTTP API + MCP server mount
│ │ ├── platform/ # IM adapters and runtime bot manager
│ │ ├── pipeline/ # Message routing and pipeline stages
│ │ ├── provider/ # Model providers and Host-owned tools
│ │ ├── agent/ # Agent/Runner orchestration and run state
│ │ ├── plugin/ # LangBot-side Plugin Runtime connector/handler
│ │ ├── box/ # LangBot-side Box service/connector
│ │ ├── skill/ # Skill metadata/activation integration
│ │ ├── rag/ , vector/ # Knowledge-base and vector DB integration
│ │ ├── persistence/ # SQLAlchemy/SQLModel and Alembic migrations
│ │ ├── storage/ # Local/S3 file storage abstraction
│ │ └── config/, entity/, utils/, telemetry/, survey/
│ ├── libs/ # Vendored third-party platform SDKs
│ └── templates/ # Default config and component metadata
├── web/ # Vite + React Router + shadcn/ui + Tailwind SPA
├── docker/ # Deployment manifests
├── skills/ # In-repo agent skills, single source of truth
└── tests/ # Unit/integration/e2e/manual tests
The Runtime Graph
The most useful mental model is this graph:
Platform adapter
→ RuntimeBot
→ MessageAggregator
→ QueryPool
→ Controller
→ RuntimePipeline
→ PipelineStage chain
→ Runner orchestrator / ToolManager / PluginRuntimeConnector / BoxService
→ response via adapter
The HTTP and MCP surfaces are parallel entrypoints into the same service layer:
HTTP client / Web UI
→ Quart route group
→ api/http/service/*
→ Application managers / persistence / runtime connectors
MCP client
→ /mcp mount
→ api/mcp/server.py tools
→ the same service layer directly
Message Flow
Inbound platform messages enter through adapter-specific SDK callbacks. The common path is:
- A platform adapter under
pkg/platform/sources/converts platform-specific events into SDK message/event entities. RuntimeBotinpkg/platform/botmgr.pyselects the route, creates the entryQuery, binds the bot message policy and fires*MessageReceived. Plugin commands match next and run directly; other messages are discarded, pushed to webhooks, handed to an Agent, or sent to the message aggregator for a Chat (pipeline). See Bot message policy and message lifecycle.MessageAggregatorbatches/normalizes messages before adding aQuerytoQueryPool.Controllerinpkg/pipeline/controller.pyselects queries subject to global pipeline concurrency and per-session concurrency.RuntimePipelineinpkg/pipeline/pipelinemgr.pyruns configured pipeline stages using a responsibility-chain style executor that supports generator stages.- The chat stage emits plugin events and projects the current query into the Runner Host orchestrator. The selected plugin Runner returns streaming or final results while the Host owns authorization, tools, telemetry, and conversation history.
- Output stages send text, cards, chunks, files, or error notices back through the original platform adapter.
Pipeline components are registered by decorators and package import side effects. When adding a new stage, loader, runner, or adapter, check the corresponding preregistration mechanism instead of inventing a second registry.
Platform Layer
Platform code lives under pkg/platform/.
botmgr.pyowns runtime bots, routing rules, event logging, webhook pushing, and adapter lifecycle.- Bots store
message_policy(trigger, safety, general output and plugin enablement; routes may override it) and exclusive Agent/Pipeline routes inevent_bindingsand independent plugin subscriptions inplugin_processors(processor_uuid,enabled). Subscriptions resolve event patterns from the installed Runner and fan out alongside the primary route. Configuration, state, debug and run logs belong to the reusable processor instance. sources/contains adapter implementations. Each adapter subclasseslangbot_plugin.api.definition.abstract.platform.adapter.AbstractMessagePlatformAdapterfrom the SDK.- Platform entities such as
MessageChain,Image,At,Voice, and events come from the SDK (sdk/,langbot_plugin), not from Core. pkg/platform/image_urls.pyrenews image references in authorized monitoring/history responses and before Host model attempts without downloading. The shared resource URL catalog persists renewed URLs behind stable references. OneBot connection-local state inadapters/aiocqhttp/image_urls.pyidentifies the implementation lazily and reuses NapCat credentials until their returned TTL expires. Other implementations use standardget_msgwhen the URL's creation or last successful check is at least 30 minutes old. URLs can be shared across Workspaces; bot ownership checks, credentials and original message identities remain scoped to their connection.
The platform layer should translate between external platform APIs and LangBot's shared message/event model. It should not contain LLM-provider logic or pipeline business logic.
Pipeline Layer
Pipeline code lives under pkg/pipeline/.
Important pieces:
pool.py::QueryPoolstores pending queries and cached in-flight queries for plugin backward-compatible calls.controller.py::Controllerschedules query processing and enforces concurrency.pipelinemgr.py::RuntimePipelinematerializes database pipeline config into a runtime stage chain.process/handlers/chat.py::ChatMessageHandleris the main LLM conversation handler.- Stage families include response rules, banned sessions, content filters, preprocessors, rate limits, message truncation, long text handling, response-back, and wrappers. Response rules, access control, filters, rate limits, long text and response-back delegate to the shared
pkg/message_policy/runtime so Agent and command delivery apply the same bot policy. - The pipeline is called Chat in user-facing text; identifiers keep
pipeline.
Pipelines are configuration-driven. Prefer adding a stage or extending an existing stage family over hard-coding behavior in platform adapters.
Agents, Providers, RAG, and Tools
Agent orchestration lives under pkg/agent/; model providers and tools live under pkg/provider/.
modelmgr/manages configured model providers and requesters.pkg/agent/runner/discovers plugin Runner components, resolves bindings, constructs run-scoped context/resources, and records execution state.tools/toolmgr.pyaggregates tools from native tools, plugin tools, external MCP servers, and skill-authoring tools.tools/loaders/mcp.pyis the MCP client side: external MCP servers that LangBot connects to for agent tools.- RAG lives across
pkg/rag/,pkg/vector/, model services, and plugin KnowledgeEngine actions.
Do not confuse LangBot's MCP client side with LangBot's own MCP server at /mcp; they are different surfaces.
Plugin System
The plugin system crosses the repo boundary.
In this repo:
pkg/plugin/connector.pyconnects LangBot to the Plugin Runtime over stdio or WebSocket.pkg/plugin/handler.pyexposes LangBot actions to the runtime and calls runtime actions for plugin operations.pkg/provider/tools/loaders/plugin.pyexposes plugin Tool components to LLM runners.- EventListener hooks are bot message lifecycle hooks:
RuntimeBotemits*MessageReceived/*CommandSentand platform notifications, Chat stages and Agent delivery emit normal-message and response events, and only Chat emits prompt-processing events. Plugins are enabled per bot throughmessage_policy.plugins. - Certified plugin policy defines Core's archive-fact, admission, and tenant-log-visibility boundary; the SDK remains responsible for certificate verification.
In sdk/:
src/langbot_plugin/api/definesBasePlugin, component base classes, message/event entities, contexts, proxies, and manifests.src/langbot_plugin/runtime/implementslbp rt, plugin discovery, dependency installation, process launching, and control/debug connections.src/langbot_plugin/entities/io/defines the action protocol shared by LangBot, runtime, and plugin processes.
The Plugin Runtime supports stdio and WebSocket control transports. Direct local LangBot runs spawn the runtime over stdio on every OS, Windows included. Containerized/standalone deployments connect over WebSocket using plugin.runtime_ws_url and --standalone-runtime.
Box Runtime and Skills
Runner plugins own sandbox policy: enablement, reuse-key interpolation, acquisition,
binding, and explicit file import/export. The Host exposes authenticated resource
APIs (get_box_status, list_boxes, acquire_box) and run-bound operations
(bind_box, import_box_attachments, export_box_files, reply_files). Box Runtime
owns atomic capacity enforcement and container reuse/lifecycle. Reusing an existing
Box is allowed when no additional capacity remains.
A run binds one Box before native sandbox tools or file transfer. The Host does not
choose a conversation scope or stage attachments before starting the Runner. Input
references retain the original attachment metadata; import yields paths specific to
the run. Output export requires explicit normalized absolute sandbox file paths and returns
opaque handles scoped to that run. The selected files are validated as one batch
before registration; successful export removes only those files, and cleanup
failure is a warning with accepted handles retained. Writing an outbox file alone
does not deliver it. Core and Plugin Runtime must provide the selected-path API;
LocalAgent CI verifies this contract against the latest stable published SDK.
message.completed.file_ids attaches explicitly exported files to Pipeline output;
Agents send them explicitly with ctx.reply_files(), subject to event reply permission.
The Pipeline wrapper never scans a Box. Binding ends with the run; the reusable Box
remains subject to Runtime idle expiry. Legacy shared workspace files survive expiry.
In explicit network mode Runtime owns the workspace and removes it after the backend
has stopped; reusable session files last only for that session.
Network runs bind a Runtime session generation. Bound execution and transfer
cannot use a replacement with the same Box ID; stale cleanup leaves that
replacement intact. A new run must acquire and bind explicitly.
Self-hosted Docker network Boxes can request administrator-configured mount
names. The Runtime authorizes each name for the Workspace and mounts its source
read-only under /datasets. The mount set is part of Box reuse compatibility.
Box is the optional sandbox subsystem used by native execution tools, stdio MCP servers, agent-side skill authoring, and managed processes. Skill storage and read-only access are Core responsibilities and remain available without Box.
In this repo:
pkg/box/service.pyis the application-facing facade for exec, sessions, managed processes, status, reconnects, quotas, generic mounts, and sandbox profiles.- Its internal
prepare_skill_artifactseam checks a pinned repository publication and prepares the Runtime's own verified cache over authenticated RPC. In explicit network mode each execution composes artifact references from authorized run pins; user execution payloads cannot choose cache digests or host mounts. See Runtime artifact cache. - Outbox export failures documents bounded reads, permission fallback, and cleanup after Runner acceptance.
pkg/box/connector.pyconnects to the Box Runtime over stdio when Core launches it (Windows, Linux and macOS alike), or over WebSocket for Docker,--standalone-box, or an explicitbox.runtime.endpoint. The rule is shared with the Plugin Runtime connector throughManagedRuntimeConnector.select_runtime_transport().- Core-launched Box subprocesses receive a stable
LANGBOT_BOX_INSTANCE_ID: explicitbox.instance_id, then the environment override, then Core's instance UUID. Standalone Box identity is fixed before RPC initialization; configure it at launch with--instance-idorLANGBOT_BOX_INSTANCE_ID, or persist its generated identity withLANGBOT_BOX_DATA_DIR. Compose and Kubernetes keep this directory under the shared Box root. Each deployment needs its own root and identity. The runtime holds an identity lock, so Kubernetes uses Recreate rather than overlapping two owners during rollout. INIT cannot reassign Box ownership. The SDK implementation requires the instance-scoped cleanup change; the pinned SDK version is unchanged here. pkg/provider/tools/loaders/native.pyis the Core orchestration seam: the Skill loader supplies generic read-only mounts in legacy mode and pinned artifact references in network mode.mcp_stdio.pyand execution-backed tools depend on Box availability.pkg/skill/repository.pyis the fenced Workspace boundary for filesystem or database persistence. Database catalogs and retained versions live inskill_registry/skill_versions; package bytes use the shared database/named-S3pkg/storage/content.pystore. Metadata reads do not touch local packages. Legacy resource reads and execution snapshots rebuild a verified cache underskills.root/.database-cache. Network mode reads verified publication resources without restoring a tree and sends exact publications to Box without that cache. Updates use a databasebase_revisionCAS in the same tenant transaction as version/content writes. The filesystem backend retains the SDKSkillStorebehavior. See Skill persistence.pkg/skill/manager.pycaches the Core repository catalog for progressive disclosure. Activation and read-only resource tools do not require Box; script execution and Workspace mutation still do.
Legacy durable Box Workspace storage is shared across placement generations, but sandbox sessions and managed processes are generation-scoped. LangBot validates the current execution binding before an MCP stdio relay attach and sends the Workspace/generation binding in authenticated headers, so a placement cutover retires stale processes and closes already-attached relays.
In sdk/:
src/langbot_plugin/box/server.pyimplementslbp boxand the WebSocket endpoints on:5410.src/langbot_plugin/box/runtime.pyowns sandbox sessions, generic read-only mounts, and managed processes.backend.py,nsjail_backend.py, ande2b_backend.pyimplement sandbox backends.src/langbot_plugin/skill_store.pyis consumed by Core, not Box. Activation pins the first revision for a run in Host-owned run ledger metadata; instructions, resource reads, execution mounts, and revision-scoped dependency state use that exact publication. A new run refreshes the Workspace catalog and resolves the current revision, ignoring old conversation activation state. Lost in-memory pins in an active authorized run are reloaded from its ledger. After a Core process restart, expired run sessions cannot call tools: the Host rejects them rather than silently resolving a new version. This does not add automatic run resumption. Core mounts only activated and authorized Skills. Published trees are never agent write targets: authoring happens in Workspace drafts and an explicit registration/update atomically publishes the next revision. Core turns those package roots or authorized content digests into generic read-only mounts; Box does not understand Skill names, metadata, revisions, files, or CRUD.
Skill execution paths include the publication digest (/opt/langbot-artifacts/<digest>).
Docker/Podman mount a read-only cache when creating the Box and atomically add
verified packages before execution; E2B seals and verifies a private staging copy
before publishing a stable projection. nsjail applies the requested mounts in a
separate namespace for each execution. Activating a Skill after acquiring a Box
therefore does not recreate the session or stop its managed processes. Ordinary
host mount changes still fail explicitly on fixed-mount backends.
A shared Box remains a Workspace filesystem sharing boundary: its commands can
see previously materialized packages. Run pins prevent revision switching; they
are not access isolation between mutually untrusted programs in the same Box.
Use package-relative script paths or the path returned by activation. Core tools
translate legacy /workspace/.skills/<name> command paths to the run's digest
path, but do not rewrite paths embedded inside scripts. Published packages remain
read-only; use writable drafts and the existing per-run outbox for output.
Skill storage uses skills.root. Box execution config lives under box::
box.enabled, box.backend, box.runtime.endpoint, and box.local.*. The old
box.local.skills_root key is read only as an online-upgrade fallback and is
marked for removal in the next major version. Start LangBot with
--standalone-box when connecting to an externally launched Box runtime.
box.file_transfer_mode: network removes Core's shared workspace/root
requirement. Runtime must acknowledge network workspace support during INIT and
keeps its own independently configured local roots. Draft registration archives a
bounded, link-free directory inside Box, downloads it through the authenticated
file protocol, then validates and publishes once with the existing revision CAS.
Run completion removes only that run's inbox, outbox and snapshots through Runtime;
drafts and other runs remain. Fresh-install defaults and offline legacy import are
selected during startup as described in the persistence contract.
HTTP API, Web UI, and MCP Server
The Application API foundation provides versioned Workspace and execution-context operations for future consumer adoption. Existing HTTP/MCP/assistant entrypoints retain their current service paths.
pkg/api/http/controller/main.py builds a Quart app, registers route groups, serves the built SPA, and wraps the ASGI app with the MCP dispatcher.
- HTTP route groups live under
pkg/api/http/controller/groups/. - Service-layer logic lives under
pkg/api/http/service/. - The built web UI is served from the frontend build path with SPA fallback.
- The MCP server lives under
pkg/api/mcp/and is mounted at/mcp. - The MCP mount binds authenticated request identity only. Each tool opens its own Workspace persistence scope in the session manager's execution task, before language lookup or service access; database scopes must not be inherited from the ASGI dispatcher.
The MCP server intentionally exposes a curated subset of the API. Tools call service classes directly rather than making HTTP requests back into LangBot.
Maintenance rule: when adding, removing, or changing an HTTP endpoint that should be agent-accessible, update the matching MCP tool and the relevant in-repo skill under skills/ in the same pass.
Persistence and Configuration
Persistence is centered on pkg/persistence/mgr.py.
- SQLite is the default database; PostgreSQL is supported.
- Every SQLite connection sets a 30-second
busy_timeoutfor concurrent writer bursts and a 64 MiBjournal_size_limit, including connections recreated after migration or pool disposal. SQLite's default automatic checkpoint policy and synchronous setting remain unchanged. The limit reduces retained WAL space when the WAL resets; it does not cap active transactions or WAL pinned by readers. Online maintenance does not periodically force checkpoints or truncate WAL files. Diagnose persistent excess growth by checking checkpoint progress and actual transaction lifetimes, then shorten the responsible transaction rather than forcing readers to finish. - After schema initialization and migration, every SQLite startup completes
wal_checkpoint(TRUNCATE)before runtime setup and producers start. Lock waits allow up to 60 seconds; checkpoint I/O may take longer. An incomplete checkpoint fails startup without undoing successful migrations, and the next startup retries even at schema head. The connection busy timeout is restored afterward. PostgreSQL is unaffected. - SQLite files use incremental auto-vacuum. Migration
0042_sqlite_incremental_vacuumconverts existing files before producers start, with a verified backup and restoration on conversion failure when a full rebuild is required. Fresh files enable the format before creating tables. Monitoring cleanup reclaims free pages in independent adaptive batches (1–512 pages, starting at 8, targeting 25 ms), pausing 250 ms between batches and starting no new batches after a two-second round budget. Busy writers take priority. No fullVACUUMor forced WAL checkpoint runs during online cleanup. - Models live under
pkg/entity/persistence/. pkg/persistence/media.py::MediaReferenceTextvalidates bound conversation payloads on ORM/Core writes while preserving the existing TEXT schema and string API. It rejects recognized structured inline images: retained images go throughMediaCache.externalize_chain_dump()before serialization, while metadata-only snapshots and transcripts useredact_inline_images(). Reads and comparisons preserve historical values for incremental cleanup. Runtime/adapter messages, arbitrary diagnostic text, and opaque strings are outside this contract.pkg/persistence/resource_urls.pyinterns structured resource URL fields in retained messages, history and monitoring at the typed SQL boundary, in the source transaction.MediaReferenceJSONpreserves native JSON monitoring details. Payloads store opaque references to the globalresource_urlscatalog; typed SQL reads and comparisons expand them to current URLs, preserving API shapes and source-record authorization. Configuration URLs and URLs in free text are excluded. Catalog lookups use only the primary-key and URL-hash unique indexes. Successful refreshes overwrite the current URL and persist the check time even when standardget_msgreturns the same URL. Converging URLs retain only ID redirects, with no old URL. PostgreSQL row locks serialize concurrent refreshes. SQLite serializes refreshes per engine without holding a write transaction during upstream calls, then checks the catalog snapshot in a short immediate write transaction so another engine's newer result is not overwritten. Bounded in-memory aliases let reused Runner payloads resolve old URLs without retaining those URLs in the database. Migration0041_resource_urlsnormalizes existing payloads using their source creation timestamps before producers start; downgrade expands references before dropping the catalog.- Timezone-less SQL
DateTimecolumns store UTC-naive values on both backends. Normalize aware values withpkg/persistence/datetime_utils.py::as_naive_utcat the bind boundary, including deadlines, leases, event times, and query/retention cutoffs; do not merely strip an offset. Existing naive rows represent UTC. Restore UTC awareness for application comparisons and epoch serialization. Runner ledger/event/transcript stores follow this existing schema contract without a data migration or changes to journal/tenant authorization. - Fresh schemas are created from current metadata, then Alembic migrations run to head. LangBot 4.x does not upgrade 3.x databases.
- New schema changes use Alembic under
pkg/persistence/alembic/versions/; there is no legacy migration chain in 4.x.
Configuration starts from src/langbot/templates/config.yaml and is generated into data/config.yaml on first run. Fresh files select database Skill/content persistence and network Box transfer; old explicit choices and missing-key legacy behavior remain compatible. Before producers start, scoped legacy publications and local assets import with database-owned progress and fencing, retaining old sources; see Skill persistence. Most long-lived managers read from ap.instance_config.data.
Storage maintenance applies storage.media_cache.retention_days to both CAS files and historical inline images. Inline image expiry uses the owning record's creation time and preserves text, URLs, and record identity. It does not backfill CAS. pkg/storage/inline_media_cleanup.py processes one payload row at a time, with a per-table limit of 100 indexed candidates or 8 MiB of JSON characters per maintenance pass (one oversized row may exceed the latter limit). Run events lack a Workspace column, so their candidate cursor also advances past foreign or missing records; payloads are loaded only after checking Workspace ownership. Durable Workspace metadata cursors and timestamp/identity indexes keep completed history out of subsequent scans; newly written history must retain its actual creation timestamp. Updates and cursor advancement commit together. Invalid historical JSON is preserved. SQLite pages become reusable after payload removal; the database file is not automatically vacuumed by this task.
Conversation summary boundary
MonitoringService delegates all interactive session lists to SessionSummaryReader in pkg/persistence/. The reader selects public columns from monitoring_sessions without history joins or repairs, keeping list cost independent of historical payload size. Sessions describe conversations, not executions; API filter semantics are documented in LangBot MCP Operations.
SessionSummaryWriter updates summaries in the source write's Workspace transaction. Each distinct message record counts once, including assistant and failure records. A platform message.received event contributes only while no non-assistant message matches its event ID or legacy message ID. Replays add no credit; late links retire ingress credit once, including across group/topic sessions. Observed start/activity timestamps never shrink the session's time range. Live writes and offline initialization share the same source mapping.
All display fields come from one source snapshot, including empty values. Missing names display the user ID instead of inheriting another record's name. Non-assistant sources outrank assistant sources, followed by timestamp and binary source-key order. Processor filters match the selected snapshot. Immutable message winners fold into base_snapshot; uncovered ingress retains a replaceable candidate_snapshot on its receipt. Covering or transferring ingress restores the remaining winner atomically, without reading history.
Receipts and event anchors are Workspace-scoped and expire in bounded batches under history retention. Expiry preserves counters and seals any uncovered ingress snapshot into the base in the same transaction. Summaries are deleted only after their receipts are gone. Deduplication and late linking are guaranteed within this retention window.
Migration 0040_session_summaries marks historical Workspaces as pending. OSS startup automatically completes SessionSummaryBackfill before starting HTTP or message producers, then continues in the same process; no manual backfill or additional container restart is needed. Batches and progress commit together, so an interrupted startup resumes from its cursor. Initialization is bounded, never selects message bodies or variables, and preserves historical counts as a lower bound when source history has expired. Invalid or oversized required metadata stops startup for diagnosis. Fresh databases and completed initialization skip history scanning; pending source writes remain blocked. There is no request-time or background repair.
Cloud runtimes retain the initialization gate because other instances may write concurrently. For Cloud deployment or manual maintenance, stop all writers, back up the database, apply the migration, and run the command below for each pending Workspace before starting services. Set the named environment variable to a sqlite+aiosqlite or postgresql+asyncpg database URL; SQLite must point to an existing file. The connection must have access to the migrated schema and Workspace.
uv run python -m langbot.pkg.persistence.session_summary_backfill \
--workspace WORKSPACE_UUID --writers-stopped \
--database-url-env LANGBOT_SUMMARY_DATABASE_URL
Frontend
The frontend lives in web/ and is a Vite SPA using React Router 7, shadcn/ui, Tailwind CSS, and pnpm. It is not Next.js, despite some historical filenames.
In development, pnpm dev serves the UI on :3000 and reads VITE_API_BASE_URL to call the backend on :5300. In production, the built frontend is packaged into the Python distribution and served by the backend.
Keep frontend API behavior aligned with pkg/api/http/service/ and route groups. User-facing strings must go through the existing i18n setup.
Agent-Facing Surfaces
LangBot is deliberately agent-friendly. The agent-facing surfaces are part of the architecture, not extra docs.
skills/is the single source of truth for in-repo skills.pkg/api/mcp/server.pyexposes the LangBot MCP server at/mcp.lbctlcalls the authenticated HTTP Service API from a terminal; its source and releases live inlangbot-cli.api.global_api_keyauthenticates API/MCP access without a browser login.AGENTS.mdandARCHITECTURE.mdtell coding agents how the repo works.
When one of these changes, update the others if the behavior or contract changed. API, MCP tools, and skills are one system; drift is a bug.
Where to Change Things
- New HTTP API: add/adjust a service in
pkg/api/http/service/, a route group inpkg/api/http/controller/groups/, tests, and MCP/skills if agent-accessible. - New platform adapter: add a
pkg/platform/sources/*adapter, component metadata/templates as needed, i18n, docs, and tests/smoke coverage. - New pipeline behavior: add or extend a pipeline stage family under
pkg/pipeline/; avoid putting pipeline rules in adapters. - New LLM provider/requester: work under
pkg/provider/modelmgr/and related service/UI surfaces. - New LLM tool source: extend
pkg/provider/tools/loaders/andToolManagerintentionally. - New plugin component/API/protocol: change
sdk/in the same PR as the LangBot bridge code; release the SDK before publishing the standalone Core PyPI package that needs it. - New Box capability: change both
pkg/box/andsdk/src/langbot_plugin/box/, plus config and tests. - New database schema: add an Alembic migration.
Design Biases
- Keep platform translation, pipeline orchestration, provider execution, and runtime protocols separate.
- Reuse existing registries and service layers instead of adding parallel paths.
- Prefer small, explicit agent surfaces over exposing every internal API.
- Treat cross-repo contracts with the SDK as public interfaces.
- Test behavior at the narrowest useful layer first, then add integration/e2e coverage for runtime or platform changes.
Documentation repositories
The public documentation site lives in docs/ and is built with Node.js 24 and Fumapress. Internal design and review notes live in dev-docs/. The landing site keeps its docs submodule path but tracks LangBot master, building from the nested docs/ directory. The old langbot-app/langbot-docs repository can be archived; publication never writes to it. See dev-docs/DOCS_MIGRATION.md for publication and cutover details.