Skip to content
Projects

Pretend-to/mio-chat-backend

View on GitHub

About

🤖 MioChat — 开源的 Agent 操作系统。Agent / Session / SubAgent 三级上下文模型、V3 Hook 切面、MCP + Skills 双标准工具生态、多渠道接入与定时自治。模型无关、自托管。

Systems & Infrastructure

How these counts are measured

Measured star growth

in 24h
0
in 7 days
Collecting history
in 15 days
Collecting history
in 1 month
Collecting history

Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.

README.en-US.md

Original

MioChat

MioChat Logo

MioChat — not just a chat relay, but the next-generation Agent OS.

An open-source, model-agnostic Agent runtime: a three-level context model of Agent / Session / SubAgent, V3 Hook aspects, a dual-standard tool ecosystem (MCP + Skills), multi-channel ingress, and scheduled autonomy that can run unattended.

License Node.js Version PM2 Ready Architecture UI Agent

Live Demo | Docs | QQ Group | 简体中文

🖥️ MioChat Frontend · 🎨 Mio-Previewer (MD Renderer) · 🔌 Plugin Marketplace


Mio-Chat is a complete Agent ecosystem built from multiple modules:

Module Repository Description
Backend Pretend-to/mio-chat-backend (this repo) core runtime, Hook architecture, plugin system
Frontend Pretend-to/mio-chat-frontend immersive agent UI built on Vue 3 + Element Plus
Renderer Pretend-to/mio-previewer Markdown rendering engine deeply customized for AI, with Artifacts support
Plugins Pretend-to/awesome-miochat-plugins official & community plugin / Skill / Hook collections

Why it exists

Agent = Model + Harness — the position this project is built on

Traditional AI chat platforms are little more than "API relay stations". MioChat is an Agent Operating System designed for complex production environments. Through precise context management, bidirectional security authorization, Multi-Agent orchestration and aspect-oriented Hook interception, it lets AI operate on the physical world autonomously and safely.

The core agent loop everyone uses is five lines of ReAct. The observable differences live entirely outside the loop: context management, permissions, tool contracts, streaming reliability, memory. MioChat owns all of those layers directly — model-agnostic, self-hosted, with nothing between the code and your machine. ~174k lines across both repositories (tests included, build output excluded) are the difference between a demo and a system that runs unattended tasks without losing context, messages, or trust.

Demo

MioChat demo — one prompt → multi-model routing → tool execution → rendered UI

Architecture

MioChat — Agent Ecosystem architecture

Highlights

📊 Unified Admin Settings & Observability Dashboard

Enterprise-grade global configuration management and full-link observability — no more black boxes or tangled config files.

  • Global System & Storage Engine: Zero-downtime hot-switching between Local storage and S3-compatible Object Storage (AWS S3 / Cloudflare R2 / MinIO); system configs are persisted in SQLite and applied immediately via Web UI and REST API.
  • Dynamic Model Management: Built-in LiteLLM dynamic sync engine (covering 3,200+ frontier and open-source models), supporting custom Providers, API Keys, Base URLs, context windows, and real-time Temperature tuning.
  • Observability Dashboard: Real-time visual monitoring of throughput, Token consumption metrics (Prompt / Completion breakdown), latency distributions, and per-Agent conversation activities.
MioChat Admin Settings & Observability Dashboard

🔌 Hot-Pluggable Tools & Modern Plugin Architecture

Uniting cross-language open ecosystems with zero-downtime runtime extensibility.

  • Standardized Plugin Layout: Clean separation of metadata, tools, and lifecycle hooks:
    my-plugin/
    ├── plugin.json       # Plugin metadata (name, version, dependencies, permissions)
    ├── index.js          # Entrypoint (extends MioPlugin, manages lifecycle)
    ├── tools/            # Tools catalog (extends MioFunction, with Zod validation & final run guard)
    └── hooks/            # Interceptors mounted across 16 system-wide lifecycle hooks
    
  • Zero-Downtime Hot-Reload: Dynamically load, unload, or hot-swap plugin code without restarting the backend; paired with the frontend Tools Manager to toggle individual tools or plugin packs per conversation.
  • Three-Layer Seamless Fusion: Open standard Agent Skills (scans .claude/, .cursor/, .gemini/) + MCP (Model Context Protocol) adapter + native high-performance tools.

🤖 OneBot (QQ) integration

Bring the QQ ecosystem into the same agent runtime.

  • Outbound long connection with visible state — the backend dials the configured OneBot implementation (go-cqhttp / NapCat / Lagrange, …) and the admin panel shows the live phase (online / connecting / offline / incomplete config), the last connection attempt with its result, the attempt count and the last error.
  • Save-and-reconnect — saving the config immediately rebuilds the connection (old socket closed gracefully), and the panel offers a manual reconnect.
  • Same pipeline — group/private messages, images, forwarded bundles and recalls share the same contacts, message chain and tooling as Web.

📱 Multi-Platform Channels (Beta — WeChat First)

Seamlessly embed Agents into real-world IM apps. Currently in Beta stage, debuting with full native WeChat (iLink Bot) integration.

  • WeChat iLink Instant Connect: Generates a login QR code on the frontend. Once confirmed on your phone, the backend automatically establishes credentials and spins up long-polling within seconds — zero manual launch required.
  • Full Multimodal Decryption & Consumption:
    • 🖼️ Image Decryption: AES-128-ECB ciphertext download and decipher -> Local/S3 storage -> Structured multimodal arrays with multi-turn image history playback.
    • 📄 File Processing: PDF / Word / Excel / code files ciphertext decipher -> Automatic Markdown links that drive the parse tool for autonomous deep extraction.
    • 🎙️ Native Voice ASR: Reads Tencent's native server-side ASR transcription text directly for millisecond-latency streaming responses.
  • 1.2s Intelligent Debouncing Queue: Tailored for high-frequency WeChat burst pushes — aggregates multi-image bursts, file-before-text, and split prompts into single unified requests, eliminating AI pre-replying and out-of-order execution.
  • Independent Soul & Memory Persistence: Each Channel is mapped to a dedicated AgentId with isolated Soul persona, GlobalMem long-term facts, and session Crystal memories, supported by /soul, /model, and /sessions Slash commands.
MioChat WeChat Channel Management & Multi-channel Gateway

🧬 Agent · Session · SubAgent: a three-level context model

Turning "one bot bound to one window" into an orchestratable, isolatable, long-running agent runtime.

① The Agent is the subject; a Channel is only ingress

  • An Agent owns its name, avatar, soul/persona, model, tools, skills and long-term memory. Messages, chunks, tool calls, crystals and pending memories all belong to an Agent through a Session.
  • A Channel stores only platform, credentials, connection state and protocol capabilities. It owns no Agent, no model, no persona, and no chat history.
  • The relation is many-to-many: one Agent can appear on Web and WeChat at the same time, and one endpoint can host several Agents — which is exactly the foundation of "Multi-Agent hybrid groups" below.

② A Session is the context unit; child Sessions form a tree

One Agent can hold many Sessions, and parentSessionId derives them into a directed tree. Child Sessions carry SubAgents and any isolated execution context. They share the Agent and Channel with their parent, yet independently hold their own MessageChain, run FIFO and lock, LLM call history, tool-call records, and timeout/cancel signals.

Agent
└── Session (main)            ← user-visible main message chain
    ├── Session (child): market research   ← own context, never eats the main window
    │   └── Run: 09-05 / 09-06 / 09-07
    └── Session (child): daily report editor
        └── Run: 09-05 / 09-06 / 09-07

③ SubAgent is a two-level orchestration: RunGroup / Run

  • A RunGroup is one orchestration transaction; a Run is a single execution unit. Multiple Runs are parallel by default — declare dependsOn to turn them into a serial DAG.
  • Every Run uses its own child Session and never creates a permanent Agent. Tool permissions are a subset of the parent Agent's effective tools, frozen at Run creation time.
  • sessionPolicy controls context continuity: fresh gives full isolation each time, while persistent reuses the same child Session so continue appends a new round to the tail — long-lived jobs therefore get better the longer they run.
  • On completion the SubAgent only wakes the main Agent with a groupId/runId, without injecting the result body. The main Agent pulls it via read_result. By default a parent Session sees only the final summary or artifact references, never the child's full search and tool-call trace.

Why split it this way: keeping the main Session's message chain stable is what keeps hitting the Prompt Cache, while heavy and dirty work stays in child contexts so the main window is never crowded out. That is the difference between "a demo" and "a week of unattended runs without losing context".

🧠 Multi-Agent hybrid groups

Break the single-agent silo; run a swarm of heterogeneous LLMs and personas together.

  • Add multiple Agents driven by different Channels into one group chat, side by side.
  • @-directed responses or ordered/conditional multi-agent rounds — cross-perspective review for complex engineering problems.
  • One shared message chain, N per-member context views (see Frontend).
Multi-Agent group discussion

❄️ Context engineering: "crystallization"

Solves the industry pain point of token explosion and context overflow in long conversations.

  • 5 structured XML zones: user profile, short-term goals, current plan, file-architecture deltas, and global constraints — isolated and normalized.
  • Stateless crystallization + prefix cache: dynamically watches the token watermark, scans turn boundaries, distills redundant history into read-only memory fragments — engineered to hit Gemini/Claude prompt caches, cutting 80%+ token cost and first-token latency to milliseconds.
Memory crystallization & context compression

🛡 Safety: interactive tool suspension

Solves the loss-of-control problem when AI executes dangerous tools (shell commands, file deletion, public publishing).

  • Aspect-oriented mounting: interception points exposed across the whole LLM + ReAct tool lifecycle.
  • Deferred-Promise suspension: for sensitive operations the backend pauses the ReAct loop and pushes a second-confirmation card over WebSocket; the loop resumes only after the admin approves.
Sensitive-tool second confirmation card

⏰ Autonomous tasks & scheduled inspection

Offline autonomy with a visual inspection dashboard.

  • Flexible scheduling: standard Cron expressions, relative time, or one-shot (once) triggers with built-in anti-repetition guards.
  • Visual Task panel + secure sandbox: inspect execution logs, wake tasks manually; per-task prompts and shell-command allowlists keep the agent from idling.
Scheduled tasks & background agent inspection

🎨 Artifacts & dynamic tool management

  • Artifacts canvas with mio-previewer: independent preview of code, HTML, SVG, Mermaid diagrams and dynamic UI components — side-by-side interaction.
  • Tools Manager: toggle tools / plugin groups in real time from the conversation UI.

Taxonomy & scale

Numbers are taken from the current repository — keep this section in sync. Conventions and hard rules live in AGENTS.md.

Dimension Count Notes
Built-in plugins 9 lib/plugins/: ai / agent-manager / anyui / config / edge-tts / file-editor / mcp / terminal-pty / web
Workspace plugin packages 3 plugins/ (pnpm workspace): custom / email-plugin / note-plugin
Declared tools 43 lib/plugins/*/tools/; MCP dynamic tools and Skills excluded
Hook mount points 16 9 built-in hooks in lib/hooks/builtins/
LLM adapter implementations 7 openai / openai-responses / anthropic / gemini / gemini-oauth / xai / agent-platform (plus many OpenAI-compatible vendors)
Search adapters 5 baidu / bing / duckduckgo / tavily / volcengine, plus a browser bridge
Image generation adapters 6 openai / google / sd-webui / siliconflow / tukuai / volcengine
Channel adapters 1 WeChat iLink (native + onebots runtimes); the registry is definition-driven
Prisma models 40 prisma/schema.prisma
HTTP routes 126 lib/server/http/index.js
Socket protocols 4 llm / onebot / system / logs

Agent self-management separates profile, long-term persona, and default delivery. Background Agents can schedule their next work using their default external channel. See self-management and delivery.

Hooks

Mio-Chat V3 is built around aspect-oriented interception. The 7 core mount points (16 in total system-wide) let you control every step of the agent:

Mount point Purpose Typical use
LLM_BEFORE_CHAT conversation interception sensitive-word filter, balance deduction, context injection
LLM_BEFORE_RECURSION recursion-turn interception dynamically adjust the tool list per turn, inject turn context
TOOL_BEFORE_LOAD load audit validate tool-name safety, prevent plugin conflicts
TOOL_BEFORE_EXECUTE execution intervention dynamic permission (RBAC), auto param repair, suspend interception
LLM_AFTER_CHAT result audit token usage persistence, response desensitization
LLM_TOOL_RESULTS tool-call audit record tool arguments & outputs after batch execution
TOOL_NOT_FOUND smart fallback strip MD5 suffix, lookup resolution, user guidance

Backed by 9 built-in hooks (audit, rate-limit, response-size cap, permission checks, model permissions, param validation, …). Every tool runs through MioFunction.run() — guarded, content-hashed, timeout-bounded, and impossible to bypass via subclassing. See Hooks guide.

Frontend & Plugins

  • Frontend — the render layer of the harness (streaming reliability, group-context isolation, client-side memory, hand-written PWA) lives in the mio-chat-frontend repo.
  • Plugin / Skill / Hook collections — official & community: awesome-miochat-plugins.

Quick start

git clone --depth 1 https://github.com/Pretend-to/mio-chat-backend.git
cd mio-chat-backend
pnpm install
pnpm start
pm2 logs mio-chat-backend

First launch auto-initializes the database and schema (built into app.js initialization). Then open the web UI and configure your LLM adapters / OneBot / plugins from the admin panel — all settings live in SQLite, surfaced through the UI & API.

Frontend (separate repo, syncs with backend models automatically):

git clone https://github.com/Pretend-to/mio-chat-frontend.git
cd mio-chat-frontend && pnpm install && pnpm dev

Testing

pnpm test:unit         # day-to-day: unit tests (isolated, never touches your real DB)
pnpm test:integration  # integration / OneBot cases; needs the backend on http://localhost:3080
pnpm test              # full suite

pnpm test:unit runs inside an isolated workspace and hands the test process a copy of the current database — your data/app.db is never written to. Integration cases target http://localhost:3080 by default; override the target with BASE_URL and ADMIN_CODE.

Documentation

Category Links
🚀 Quick Start & Deploy Deployment Guide | PM2 | Docker | Config API
🧠 Core Mechanics Context Crystallization | Hooks | Socket Protocol
🛠️ Development Plugin Guide | Skill Spec | Adapter Template
🗄️ Archive Architecture Migration | Q&A

Contributing

Mio-Chat evolves community-driven. Any contribution is welcome:

  1. Contribute a Plugin — give agents the ability to operate new domains.
  2. Contribute a Skill — crystallize expert knowledge for a specific domain.
  3. Contribute a Hook — harden the defense & audit system.

🙏 Acknowledgements

Developed with JetBrains' Open Source Development License — free professional JetBrains IDE licenses provided for this open-source project.

JetBrains

License

MIT — © 2026 MioChat contributors

Explore related projects

Loading…