# MothX Documentation (Full)

> This file is generated by `docs/scripts/generate-llms.py`. Do not edit it manually.

## MothX Documentation

Source: https://mothx.net/en/README.md

# MothX Documentation

<p align="center">
  <img src="assets/mothx-small.png" alt="MothX" width="128" height="128">
</p>

<p align="center">
  <strong>🚀 One Binary to Rule Them All — Your AI Coding Assistant in the Terminal</strong>
</p>

<p align="center">
  <em>Make OSCHINA Tokens Harness eXecution</em>
</p>

<p align="center">
  Stop switching between Claude Code, Codex, Claw, and Channels.<br>
  MothX packs everything into a single file — providers, tools, sandbox, sessions, skills, and more.
</p>

<p align="center">
  <a href="https://www.npmjs.com/package/mothx-installer"><img src="https://img.shields.io/npm/dm/mothx-installer.svg" alt="npm downloads"></a>
  <a href="https://pypi.org/project/mothx-installer/"><img src="https://img.shields.io/pypi/v/mothx-installer.svg" alt="PyPI version"></a>
  <a href="https://github.com/oschina/mothx/releases/latest"><img src="https://img.shields.io/github/release/oschina/mothx.svg" alt="GitHub release"></a>
  <a href="https://opensource.org/licenses/MIT"><img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License: MIT"></a>
  <a href="https://goreportcard.com/report/github.com/oschina/mothx"><img src="https://goreportcard.com/badge/github.com/oschina/mothx" alt="Go Report Card"></a>
  <a href="https://pkg.go.dev/github.com/oschina/mothx"><img src="https://pkg.go.dev/badge/github.com/oschina/mothx?status.svg" alt="GoDoc"></a>
  <a href="https://github.com/oschina/mothx/network/dependencies"><img src="https://img.shields.io/librariesio/release/github/oschina/mothx" alt="Dependencies"></a>
  <a href="https://awesomemygo.dev/apps/mothx-native"><img src="https://awesomemygo.dev/badge.svg" alt="Listed on Awesome MyGo"></a>
</p>

> **Rename notice:** MothX was formerly known as VibeCoding. The `vibecoding` command and old installer package names remain compatibility aliases. Configuration is read only from `.mothx` project directories and the MothX global configuration directory; legacy directories are neither read nor migrated.

---

Welcome to the MothX Documentation Center!

## ✨ Why MothX?

**The Problem:** You're juggling multiple AI coding tools — Claude Code for one thing, Codex for another, Claw for something else. Each has its own setup, its own quirks, its own dependencies.

**The Solution:** MothX is the **all-in-one terminal AI coding assistant** that does it all. One binary. One config. Zero hassle.


![MothX vs Competitors](assets/image/comparison-en.webp)

### 🎯 Key Highlights

| Feature | What It Means for You |
|---------|----------------------|
| **🤖 Multi-Provider** | DeepSeek, OpenAI, Anthropic, Volcengine/Doubao, LongCat, and 60+ built-in provider presets — switch models instantly |
| **⚡ Lightning Fast** | SSE streaming, real-time token delivery, cache hit optimization |
| **🧠 Think Mode** | Extended reasoning for complex problems (DeepSeek, o1, Claude) |
| **🛡️ Sandboxed** | bwrap process isolation — safe file ops, network control, approval gates |
| **📝 Sessions** | Persistent SQLite-backed history with interactive picker, branching, compaction, and tree structure |
| **🧩 Skills** | Reusable prompt snippets for project conventions — share across teams |
| **📊 Stats Dashboard** | Usage statistics with charts, per-provider/model breakdowns, and CLI mode |
| **🔄 Workflows** | JavaScript DSL for multi-phase, parallel, multi-agent orchestration |
| **💻 IDE Ready** | ACP protocol for VS Code, Zed, JetBrains — native editor integration |
| **🌐 Serve** | OpenAI Chat/Responses APIs, Web UI, MCP, approvals, and durable background runs |
| **🖥️ Desktop** | Electron ACP client with chat, approvals, artifacts, Expert Teams, and knowledge bases — no Serve process |
| **📚 Knowledge Bases** | Rebuildable, read-only directory indexes queried through a standard Knowledge MCP server |
| **🌳 Worktrees** | Isolated git worktrees shared by the CLI, Desktop, and sub-agents |
| **📱 Messaging** | WeChat, Feishu, and WebSocket event streams with durable sessions |
| **🤝 Multi-Agent** | Async sub-agents with `--multi-agent`, blocking delegation with `--delegate`, and A2A master mode |
| **🎨 Rich TUI** | Markdown rendering, syntax highlighting, thinking display, tool modals, multiline input |
| **🔒 Security** | Project-level bash auto-approval rules, bashBlacklist > whitelist, interactive approval dialog |

---

## 📚 Documentation

### 🚀 Getting Started
- [5-Minute Quick Start](quick-start-tutorial.md) — Skip the long docs, just start coding!
- [Quick Start](getting-started.md) — Installation, configuration, first run
- [CLI Reference](cli-reference.md) — All commands and flags

### ✨ Core Features
- [Features Overview](features-overview.md) — Multi-provider, sandbox, sessions, skills, and more
- [Expert Teams](expert-teams.md) — Reusable lead identities and member teams
- [Native Desktop Client](native.md) — primary self-drawn Go desktop app (pure ACP)
- [Desktop Client (deprecated)](desktop.md) — legacy Electron ACP desktop app
- [Knowledge Bases](knowledge-bases.md) — Index a directory and search it through MCP

### 🎯 Use Cases
- [Use Cases & Real-World Examples](use-cases.md) — From daily development to enterprise deployment

### ⚙️ Configuration
- [Configuration Guide](configuration.md) — Settings, env vars, authentication

### 🏗️ Architecture
- [System Architecture](architecture.md) — Core components, data flow
- [Tool System](tools.md) — Built-in tools guide
- [Skills System](skills.md) — Reusable prompt snippets
- [Online Skill Marketplace](skillhub.md) — 源盾 / SkillHub / ClawHub integration
- [Session Management](sessions.md) — Session storage and management
- [Workflow Mode](workflow.md) — JavaScript DSL for multi-agent orchestration
- [SDK Integration](sdk.md) — Embed MothX agent in your Go applications
- [Adding a Provider](provider-guide.md) — Add or customise a provider
- [Provider & Model Catalog](../provider-model-list.md) — Every built-in provider and model

### 🔒 Security
- [Security & Sandbox](security.md) — Sandbox modes, permissions, approval

### 💻 IDE Integration
- [ACP Protocol](acp.md) — VS Code, Zed, JetBrains integration

### 🌐 Serve Mode
- [Serve Mode](serve.md) — OpenAI-compatible HTTP API, Web UI, and messaging channels
- [A2A Protocol](a2a.md) — Agent-to-Agent protocol

### 📖 Tutorials
- [Scenarios & Walkthroughs](scenarios.md) — Practical examples
- [FAQ](faq.md) — Common questions answered

### 🇨🇳 中文文档
- [中文文档首页](../zh/README.md) — 完整中文文档

---

## 🚀 Quick Install

```bash
# npm (recommended)
npm install -g mothx-installer

# Compatibility package for this transition release
npm install -g vibecoding-installer

# PyPI
pipx install mothx-installer

# One-line install (Linux/macOS)
curl -fsSL https://mothx.net/install.sh | bash
```

```bat
:: One-line install (Windows Command Prompt)
curl.exe -fsSL https://mothx.net/install.bat -o install.bat && install.bat
```

```bash
# Docker (GHCR, Linux amd64/arm64)
docker run --rm -it --entrypoint bash ghcr.io/oschina/mothx:latest
docker run --rm -it -v "$PWD:/workspace" -w /workspace ghcr.io/oschina/mothx:latest

# Go install
go install github.com/oschina/mothx/cmd/mothx@latest
```

## 🗑️ Uninstall

```bash
# npm
npm uninstall -g mothx-installer

# Compatibility package, if installed before the rename
npm uninstall -g vibecoding-installer

# PyPI
pipx uninstall mothx-installer

# Linux/macOS (one-line install)
curl -fsSL https://mothx.net/install.sh | bash -s -- --uninstall

# Windows (one-line install)
npm uninstall -g mothx-installer
```

## 🎮 Three Modes for Every Situation

```
🗒️  Plan    → Read-only analysis & planning. Safe, sandboxed, no surprises.
🔧  Agent   → Standard read/write. Bash approval required.
🚀  YOLO    → Full system access. No restrictions. (Default)
```

Switch modes anytime with `/mode plan|agent|yolo` or press `Tab`.


![Three Safety Modes](assets/image/modes-en.webp)

## 🎯 Use Cases

### 💻 Daily Development
```bash
mothx -P "Refactor this function to use generics"
mothx -P "Write tests for the UserService struct"
mothx -P "Explain what this regex does"
```

### 🔍 Code Review
```bash
mothx --mode plan "Review this PR and suggest improvements"
```

### 🚀 CI/CD Integration
```bash
mothx -p "Generate changelog from git log" > CHANGELOG.md
```

### 🌐 API Server
```bash
mothx serve  # Start OpenAI-compatible HTTP server
```

### 📱 Chatbot
```bash
mothx serve   # Deploy as WeChat/Feishu bot
```

## 🛠️ Built-in Tools

| Tool | Description |
|------|-------------|
| `read` | Read file content (supports images) |
| `write` | Create/overwrite files (atomic) |
| `edit` | Precise multi-replacement text edits |
| `bash` | Execute shell commands (sync/async, default 45s timeout) |
| `grep` | Search file content (pure-Go ripgrep) |
| `find` | Find files by pattern (pure-Go fd) |
| `ls` | List directory contents |
| `plan` | Publish task plans with steps |
| `question` | Ask user multiple-choice questions |
| `jobs` | Manage background jobs |
| `kill` | Stop background jobs |
| `skill_ref` | Load skill reference files |
| `delegate_subagent` | Blocking single sub-agent delegation |
| `workflow_run` | Run JavaScript workflow orchestration |

## Getting Help

- Use the `/help` command for interactive help
- Check the [CLI Reference](cli-reference.md) for all commands
- Read the [FAQ](faq.md) for common questions

---

## A2A Protocol (Agent-to-Agent)

Source: https://mothx.net/en/a2a.md

# A2A Protocol (Agent-to-Agent)

## Overview

The A2A (Agent-to-Agent) protocol enables different AI agents to discover, communicate, and collaborate with each other. MothX implements the A2A protocol as a standalone server.

## Quick Start

```bash
# Standalone mode
mothx a2a start

# Check status
mothx a2a status

# View Agent Card
mothx a2a card

# Send task to another A2A server
mothx a2a send "list all Go files" --target http://remote:8093

# Discover remote Agent Card
mothx a2a discover http://remote:8093

# Check whether the server is reachable. This command does not terminate it.
mothx a2a stop
```

## Running Mode

Runs a dedicated A2A HTTP server on a separate port (default: `127.0.0.1:8093`).

```bash
# Configure the host in `a2a.json` (global `~/.mothx/a2a.json` or project `.mothx/a2a.json`), then start:
mothx a2a start --port 8093 --work-dir /path/to/project
```

The CLI does not provide a `--host` flag. Set `host`, `port`, and optionally `auth_token` in `a2a.json`; the default host is `127.0.0.1`.

## Protocol Details

- **Transport**: JSON-RPC 2.0 over HTTP
- **Streaming**: SSE (Server-Sent Events) for real-time updates
- **Task Lifecycle**: `submitted` → `working` → `completed`/`failed`/`canceled`

## Agent Card

The Agent Card describes the agent's capabilities and is served at `/.well-known/agent.json`.

```json
{
  "name": "MothX",
  "description": "AI coding assistant with file editing, terminal, and search capabilities",
  "url": "http://localhost:8093/a2a",
  "version": "0.1.31",
  "capabilities": {
    "streaming": true,
    "pushNotifications": false
  },
  "skills": [
    {
      "id": "code-edit",
      "name": "Code Editing",
      "description": "Read, write, and edit code files with precise text replacement"
    },
    {
      "id": "terminal",
      "name": "Terminal Execution",
      "description": "Execute shell commands, run tests, build projects"
    },
    {
      "id": "code-search",
      "name": "Code Search",
      "description": "Search codebases with ripgrep and fd"
    }
  ]
}
```

## JSON-RPC Methods

### `message/send`

Send a message to create or continue a task.

**Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "message/send",
  "params": {
    "task_id": "task_123",  // optional, omit to create new task
    "message": {
      "role": "user",
      "parts": [
        {"type": "text", "text": "Help me refactor main.go"}
      ]
    }
  },
  "id": 1
}
```

**Response (sync):**
```json
{
  "jsonrpc": "2.0",
  "result": {
    "id": "task_123",
    "state": "completed",
    "artifacts": [
      {
        "name": "response",
        "parts": [{"type": "text", "text": "I've analyzed main.go..."}]
      }
    ]
  },
  "id": 1
}
```

**SSE Streaming (add `Accept: text/event-stream` header):**
```
data: {"task_id":"task_123","state":"working","message":{"role":"agent","parts":[{"type":"text","text":"Let me"}]}}

data: {"task_id":"task_123","state":"working","message":{"role":"agent","parts":[{"type":"text","text":" analyze the code..."}]}}

data: {"task_id":"task_123","state":"completed","artifact":{"name":"response","parts":[{"type":"text","text":"Here's the refactored version..."}]}}
```

### `task/get`

Get the current state of a task.

**Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "task/get",
  "params": {
    "task_id": "task_123"
  },
  "id": 2
}
```

### `task/cancel`

Cancel a running task.

**Request:**
```json
{
  "jsonrpc": "2.0",
  "method": "task/cancel",
  "params": {
    "task_id": "task_123"
  },
  "id": 3
}
```

## REST Endpoints

For simpler integration, REST-style endpoints are also available:

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/.well-known/agent.json` | GET | Agent Card |
| `/a2a` | POST | JSON-RPC 2.0 endpoint |
| `/a2a/send` | POST | Submit task (sync or SSE) |
| `/a2a/task?task_id=xxx` | GET | Get task state |
| `/a2a/task/cancel` | POST | Cancel task |
| `/a2a/events?task_id=xxx` | GET | SSE event stream |

## Task States

```
submitted ─► working ─► completed
                    ─► failed
                    ─► canceled
```

## Examples

### Submit Task (curl)

```bash
# Sync response
curl -X POST http://localhost:8093/a2a \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "message/send",
    "params": {
      "message": {
        "role": "user",
        "parts": [{"type": "text", "text": "List all Go files in the project"}]
      }
    },
    "id": 1
  }'

# SSE streaming
curl -X POST http://localhost:8093/a2a \
  -H "Content-Type: application/json" \
  -H "Accept: text/event-stream" \
  -d '{
    "jsonrpc": "2.0",
    "method": "message/send",
    "params": {
      "message": {
        "role": "user",
        "parts": [{"type": "text", "text": "Explain the project structure"}]
      }
    },
    "id": 1
  }'
```

### REST API

```bash
# Submit task
curl -X POST http://localhost:8093/a2a/send \
  -H "Content-Type: application/json" \
  -d '{"message": {"role": "user", "parts": [{"type": "text", "text": "Hello"}]}}'

# Get task
curl http://localhost:8093/a2a/task?task_id=task_123

# Cancel task
curl -X POST http://localhost:8093/a2a/task/cancel \
  -H "Content-Type: application/json" \
  -d '{"task_id": "task_123"}'
```

## Security

- **Auth Token**: Bearer token authentication from `a2a.json` or the `--auth-token` flag
- **Agent Card**: Publicly accessible (no auth required)
- **Protected Endpoints**: `/a2a`, REST A2A routes, and `/a2a/events` require auth when `auth_token` is configured

When auth is configured, clients must send:

```bash
Authorization: Bearer <auth_token>
```

## A2A Client

Send tasks to other A2A servers.

```bash
# Send a task
mothx a2a send "explain the project structure" --target http://remote:8093

# Send with auth token
mothx a2a send "run tests" --target http://remote:8093 --auth-token xxx

# Discover what a server can do
mothx a2a discover http://remote:8093
```

## A2A Scheduling

Cron jobs can send tasks to A2A servers instead of running local agents.

```bash
# Schedule a daily task to a remote A2A server
mothx serve cron add "daily-review" "review recent changes" \
  --schedule "@daily" \
  --a2a-target http://review-agent:8093

# Schedule with auth
mothx serve cron add "ci-check" "run CI tests" \
  --schedule "@every 1h" \
  --a2a-target http://ci-agent:8093 \
  --a2a-token ${CI_TOKEN}
```

The cron scheduler will send the prompt to the A2A server instead of spawning a local agent.

## A2A Master Mode

A2A Master mode lets you manage multiple remote A2A agents from a single MothX instance and dispatch tasks to them via the `a2a_dispatch` tool.

### Quick Start

```bash
# 1. Generate sample config
mothx --init-a2a-master-config

# 2. Edit a2a-list.json with your remote agent details
#    Location: ~/.mothx/a2a-list.json or .mothx/a2a-list.json

# 3. Enable master mode
mothx --enable-a2a-master
```

### Configuration

`a2a-list.json` structure:

```json
{
  "agents": [
    {
      "name": "code-reviewer",
      "url": "http://localhost:8093"
    },
    {
      "name": "ci-agent",
      "url": "http://ci-server:8093",
      "auth_token": "your-secret-token"
    }
  ]
}
```

| Field | Type | Description |
|-------|------|-------------|
| `name` | string | Agent name (unique identifier, used in tool calls) |
| `url` | string | A2A server URL |
| `auth_token` | string | Bearer token (optional) |

Config file locations (low to high priority):
- `~/.mothx/a2a-list.json` (global)
- `.mothx/a2a-list.json` (project-level, overrides global)

### a2a_dispatch Tool

When enabled, the LLM gets an `a2a_dispatch` tool to send tasks to registered remote agents:

**Parameters:**
| Parameter | Type | Description |
|-----------|------|-------------|
| `agent_name` | string | Target agent name (auto-enumerated from config) |
| `message` | string | Task message |

**Examples:**
```
a2a_dispatch(agent_name="code-reviewer", message="review main.go for bugs")
a2a_dispatch(agent_name="ci-agent", message="run all unit tests")
```

### CLI Flags

| Flag | Description |
|------|-------------|
| `--enable-a2a-master` | Enable A2A Master mode (off by default) |
| `--init-a2a-master-config` | Generate sample `a2a-list.json` |
| `--force` | Overwrite existing config file |

---

## Agent Client Protocol (ACP)

Source: https://mothx.net/en/acp.md

# Agent Client Protocol (ACP)

## Overview

MothX implements the **Agent Client Protocol (ACP)**, a JSON-RPC based protocol that allows AI coding agents to be integrated directly into IDEs and editors. ACP enables a client-server architecture where your IDE acts as the client and MothX runs as a background agent.

## Supported IDEs

### Visual Studio Code (VS Code)

MothX can be used as an ACP agent in VS Code through compatible extensions. To configure, add the following to your VS Code settings:

```json
{
  "your-acp-extension.servers": {
    "mothx": {
      "type": "agent",
      "command": "mothx",
      "args": ["acp"],
      "env": {}
    }
  }
}
```

Make sure `mothx` is available in your `PATH`, or use the full path to the binary.

### JetBrains IDEs (IntelliJ IDEA, GoLand, WebStorm, etc.)

JetBrains IDEs also support ACP agents. Configure in your IDE settings:

```json
{
  "acpAgentServers": {
    "mothx": {
      "command": "mothx",
      "args": ["acp"]
    }
  }
}
```

## Using ACP Mode

### Starting the ACP Server

```bash
# Basic ACP server (stdin/stdout)
mothx acp

# With specific provider and model
mothx acp --provider deepseek-openai --model deepseek-v4-flash

# With sandbox enabled
mothx acp --sandbox

# Specify mode
mothx acp --mode agent

# Enable multi-agent tools
mothx acp --multi-agent
```

### ACP Command Flags

| Flag | Short | Default | Description |
|------|-------|---------|-------------|
| `--provider` | `-p` | Default from config | LLM provider |
| `--model` | `-m` | Default from config | Model ID |
| `--mode` | `-M` | `yolo` | Run mode (plan, agent, yolo, os); falls back to `settings.json` `defaultMode` |
| `--thinking` | `-t` | From config | Thinking level |
| `--sandbox` | - | false | Enable sandbox |
| `--verbose` | - | false | Verbose output |
| `--debug` | - | false | Debug logging and local pprof |
| `--multi-agent` | - | false | Enable sub-agent tools and multi-agent workflows |
| `--delegate` | - | false | Enable blocking single sub-agent delegation |
| `--workflows` | - | false | Enable JavaScript workflow tools |
| `--web-search` | - | false | Enable configured local web search tools |
| `--browser` | - | false | Enable browser automation |
| `--artifact` | - | false | Enable generated artifact publishing for Desktop/ACP |
| `--permission-timeout` | - | `5m` | Approval timeout for `session/request_permission` (Go duration; env `MOTHX_ACP_PERMISSION_TIMEOUT`) |
| `--question-timeout` | - | `5m` | Question timeout for ACP question requests (Go duration; env `MOTHX_ACP_QUESTION_TIMEOUT`) |

## Protocol Details

ACP uses JSON-RPC 2.0 over stdio and follows the ACP v1 schema. MothX-specific behavior is isolated in `mothx/*` and `_mothx/*` methods plus `_meta` extension declarations; standard ACP objects receive no non-extension custom fields.

### Methods

| Method | Description |
|--------|-------------|
| `initialize` | Handshake and capability negotiation |
| `mothx/doctor` | Return machine-readable installation/provider diagnostics; does not require a session |
| `session/new` | Create a new session |
| `session/load` | Load an existing session and replay history |
| `session/list` | List persisted sessions, optionally filtered by working directory |
| `session/resume` | Restore a session without replaying history |
| `session/fork` | Fork a session at its current state |
| `session/prompt` | Send a prompt to the agent |
| `session/cancel` | Cancel an active prompt |
| `session/close` | Cancel active work and release session runtime resources |
| `session/delete` | Delete an inactive session from persisted session history |
| `session/set_mode` | Change the session run mode |
| `session/set_config_option` | Change a session configuration option (provider, model, mode, thinking, sandbox, browser, web search) |
| `mothx/session/history` | Page through persisted session history |
| `mothx/session/draft-config-options` | Read the initial config options for a new-session draft |
| `mothx/session/setTitle` | Set a session title |
| `mothx/session/setWorkDir` | Change a session working directory |
| `mothx/session/setMeta` | Set canonical session metadata used by Desktop/WebUI |
| `mothx/session/listAll` | List sessions across all working directories |
| `mothx/session/delete` | Delete a session (alias of `session/delete`) |
| `mothx/projects/list` | List Desktop/WebUI projects |
| `mothx/projects/create` | Create a project |
| `mothx/projects/rename` | Rename a project |
| `mothx/projects/delete` | Delete a project |
| `mothx/attachment/list` | List attachments owned by a session |
| `mothx/attachment/fetch` | Fetch attachment bytes |
| `mothx/subagent/list` | List child agents and their state |
| `mothx/subagent/messages` | Read a child agent's transcript |
| `mothx/worktree/list` | List managed git worktrees |
| `mothx/worktree/create` | Create a managed worktree |
| `mothx/worktree/reset` | Reset a worktree to its default branch |
| `mothx/worktree/remove` | Remove a managed worktree |
| `mothx/worktree/status` | Read worktree status |
| `mothx/workspace/extend` | Add a directory to the workspace without restarting ACP |
| `mothx/manage/*` | Management projections; see [Management projections](#management-projections) |
| `$/cancel_request` | Cancel an in-flight request by JSON-RPC request ID |
| `session/update` | Server notification: session state changes |

### Capabilities

MothX advertises the following ACP capabilities during initialization:

- **Load Session**: Load and continue previous sessions
- **Prompt Capabilities**: Text, `resource_link`, image, audio, and embedded resource/context content; the Runtime normalizes all of them through the shared input contract
- **Session Capabilities**: Load, list, resume, fork, close, delete, and additional directories
- **MCP Capabilities**: stdio / http / sse transport supported
- **Multi-Agent Workflows**: Available when the ACP server is started with `--multi-agent`; delegate mode uses `--delegate`, workflows use `--workflows`
- **MothX extensions**: Advertised through `initialize._meta["mothx.dev"].features`; clients must gate optional methods, panels, and projections on those keys

### Notifications

The server sends `session/update` notifications with the following event types:

| Update Type | Description |
|-------------|-------------|
| `agent_message_chunk` | text delta from the agent |
| `agent_thought_chunk` | thinking/reasoning delta |
| `user_message_chunk` | historical user message |
| `tool_call` | tool being called |
| `tool_call_update` | tool status update (pending/in_progress/completed/failed) |
| `usage_update` | Current context usage, context window size, and cumulative cost; plus the additive cache projection below |

`usage_update` keeps the standard ACP shape. When `initialize._meta["mothx.dev"].features` advertises `usageCacheProjection`, the notification additionally carries `_meta["mothx.dev"]` with the session-cumulative `cacheRead`, `cacheWrite`, and `totalInputTokens`; the cache hit ratio is `cacheRead / totalInputTokens`, the same denominator the Runtime uses for `Usage.TotalInputTokens`. Both the cumulative cost and these totals are rebuilt from the canonical persisted history on `session/load`, and the extension is omitted until the first usage event.

`session/load` replays the full conversation history before returning.

## MothX Extensions

MothX keeps non-standard interactions separate from ACP. Clients use these methods only after the matching capability appears in `agentCapabilities._meta["mothx.dev"]`; ACP clients that do not support the extension can ignore it without affecting the standard session flow.

`initialize.agentInfo` identifies the product as `mothx` / `MothX` and carries the build version. The top-level `initialize._meta["mothx.dev"]` (also mirrored in `agentCapabilities._meta` for compatibility) advertises the stable feature list and `doctor: true`. `mothx/doctor` accepts `{}` or `{ "cwd": "/absolute/path" }` and returns `{ ok, version, summary, checks }`; checks use stable IDs and never include API key values. `mothx doctor --json` emits that same response as its only stdout output. If ACP exits before initialization, stderr includes one `MOTHX_ACP_ERROR { ... }` line with a stable error code and a short fix.

| Method | Purpose |
|------|------|
| `mothx/requestQuestion` | Multiple-choice question request; clients return `{ "answer": "option text" }`. Pre-initialize replay uses the legacy `_mothx/request_question` name. |
| `_mothx/session_event` | MothX runtime status, turn, context-compaction, retry, and artifact events |

### Management projections

`mothx/manage/*` is an additive, capability-gated projection of shared Runtime and Serve services. Desktop uses it instead of reading `settings.json`, the sessions database, or Serve configuration directly.

| Group | Methods |
|-------|---------|
| Application/settings | `application/get`, `application/patch`, `settings/get`, `settings/patch`, `env/get`, `env/patch` |
| Serve/channels | `serve/get`, `serve/patch`, `channels/get`, `channels/patch` |
| Providers | `providers/list`, `providers/save`, `providers/delete`, `providers/test`, `providers/discover` |
| Skills | `skills/list`, `skills/set`, `skillhub/*` |
| MCP | `mcp/list`, `mcp/set` |
| Automation | `cron/*`, `deliveries/list`, `deliveries/retry`, `memory/get`, `memory/put`, `stats/summary`, `stats/timeseries` |
| Experts | `experts/list`, `experts/get`, `experts/create`, `experts/update`, `experts/delete` |
| Knowledge bases | `knowledge-bases/*` (list, get, create, update, delete, scan, status, query, mcp/apply, runs, sources, schedule, clear) |

Responses and logs mask provider keys and sensitive headers. Management calls never make Desktop the owner of session, run, credential, or scheduling state.

## MCP Server Integration

MothX supports connecting to **MCP (Model Context Protocol)** servers during ACP sessions. This allows the agent to access external tools and data sources.

ACP sessions use the same MCP connection and tool-registration runtime as normal CLI/TUI sessions. The difference is that ACP clients pass `mcpServers` during session creation/loading, while normal CLI/TUI sessions load `mcp.json` at process startup.

### Configuring MCP Servers

MCP servers are configured by the IDE client and passed to MothX when creating or loading sessions. The configuration format:

```json
{
  "mcpServers": [
    {
      "name": "my-database",
      "type": "stdio",
      "command": "mcp-server",
      "args": ["--port", "8080"],
      "env": [
        {"name": "DB_URL", "value": "postgres://localhost/mydb"}
      ]
    },
    {
      "name": "remote-tools",
      "type": "http",
      "url": "https://mcp.example.com",
      "headers": [
        {"name": "Authorization", "value": "Bearer ${TOKEN}"}
      ]
    },
    {
      "name": "legacy-sse",
      "type": "sse",
      "url": "https://legacy.example.com/sse",
      "messageUrl": "https://legacy.example.com/messages"
    }
  ]
}
```

### MCP Tool Registration

When an MCP server is connected, MothX automatically discovers and registers all tools exposed by the server. The tools are registered with the naming convention `mcp_<server_name>_<tool_name>`, allowing the agent to use them alongside built-in tools.

Registration happens before the agent freezes its system prompt and tool definitions for the session. MCP server changes therefore require creating/loading a new ACP session with the updated `mcpServers` payload.

In addition to `tools/*`, MothX now also discovers:

- `resources/*`: exposed as MCP resource read tools
- `prompts/*`: exposed as MCP prompt rendering tools

### MCP Transport Support

Supported transports:

- `stdio`: `command` may be an executable name resolved through `PATH`, or a direct path; use `args` for command arguments
- `http`: streamable HTTP endpoint via `url`
- `sse`: legacy SSE stream via `url` plus `messageUrl` for client POSTs

Additional notes:

- MCP server names must be unique within one session
- `headers` can be passed for `http` / `sse` transports
- `sampling/createMessage` is bridged to the current ACP provider/model and returns assistant text content
- MCP progress/logging/cancel notifications are surfaced as structured ACP `tool_call_update` events

## Permission System

In ACP mode, the agent can request user permissions for tool execution. The IDE client receives `session/request_permission` notifications and can respond with allow/reject decisions.

```
Client                                    Server (mothx acp)
  │                                           │
  │  ── session/request_permission ────────▶  │
  │      (tool_call_id, title, options)       │
  │                                           │
  │  ◀── JSON-RPC response ─────────────────  │
  │      (outcome: allow-once / reject-once)  │
```

## Example: VS Code Integration

### Step 1: Install MothX

```bash
npm install -g mothx-installer
# or
go install github.com/oschina/mothx/cmd/mothx@latest
```

### Step 2: Configure VS Code

Add to your VS Code `settings.json`:

```json
{
  "acp.agents": {
    "mothx": {
      "command": "mothx",
      "args": ["acp", "--mode", "agent"],
      "description": "MothX AI Assistant"
    }
  }
}
```

### Step 3: Start using

Open your project in VS Code, launch the ACP agent, and start asking questions or requesting code changes directly from your editor.

## Example: JetBrains IDE Integration

### Step 1: Install MothX

```bash
npm install -g mothx-installer
```

### Step 2: Configure in JetBrains IDE

Navigate to `Settings → Tools → ACP Agents` and add a new agent:

- **Name**: MothX
- **Command**: `mothx`
- **Arguments**: `acp --mode agent`

Or add to `.idea/workspace.xml`:

```xml
<component name="ACPSettings">
  <option name="agents">
    <list>
      <ACPAgentSetting>
        <option name="name" value="Vibecoding" />
        <option name="command" value="mothx" />
        <option name="args" value="acp --mode agent" />
      </ACPAgentSetting>
    </list>
  </option>
</component>
```

### Step 3: Start using

Use the ACP tool window in your JetBrains IDE to interact with MothX.

---

## System Architecture

Source: https://mothx.net/en/architecture.md

# System Architecture

![MothX Architecture Overview](assets/image/architecture-en.webp)

> All entry points (TUI, CLI, WebUI/Serve, Desktop/ACP, and messaging channels) feed one front-end-neutral Agent Runtime, which owns sessions, runs, decisions, input/content, attachments/artifacts, MCP, skills, and policy resolution, and reuses one core Agent loop plus the provider abstraction, SQLite sessions, sandbox, stats, memory, and workflow infrastructure.


## Project Structure

```
mothx/
├── agent/                       # Public SDK types (Agent, Provider, Builder)
├── bootstrap/                   # Public SDK wiring into internal implementations
├── cmd/mothx/                   # CLI entry point and subcommands
├── desktop/                     # Electron desktop client (pure ACP projection; deprecated)
├── native/                      # Primary desktop client: pure-Go MyGo app (pure ACP projection)
├── ui/                          # Svelte Web UI embedded into Serve
├── internal/
│   ├── agent/                   # Core Agent loop, events, prompts, sub-agent tools
│   ├── agentruntime/            # Shared front-end-neutral Runtime: SessionRuntime,
│   │                            # ExecutionRuntime, decisions, artifacts, MCP,
│   │                            # knowledge bases, experts, worktrees
│   ├── acp/                     # ACP v1 server + mothx.dev extensions
│   ├── a2a/                     # A2A server and remote-agent master dispatch
│   ├── architecture/            # Static architecture guard tests
│   ├── browser/                 # vibe-browser automation tool
│   ├── config/                  # settings.json / serve.json schemas and defaults
│   ├── context/, contextfiles/  # Token budget and AGENTS.md/CLAUDE.md loading
│   ├── cron/                    # Scheduled task store and scheduler
│   ├── dao/                     # Sole owner of SQL/query builders/row mapping
│   ├── db/                      # Connection, transaction, and migration lifecycle
│   ├── esm/                     # Enable Supervisor Mode objective loop
│   ├── expert/                  # Expert Team bundle discovery and validation
│   ├── imageproc/               # Image normalization and resizing
│   ├── mcp/                     # MCP client/server integration
│   ├── memory/                  # memory.md tool for messaging channels
│   ├── messaging/               # WeChat/Feishu platform abstraction
│   ├── platform/                # Cross-platform helpers and embedded assets
│   ├── provider/                # Protocol providers, vendor adapters, factory
│   ├── sandbox/                 # Sandbox abstraction (bwrap, none)
│   ├── serve/                   # OpenAI API, Web UI, channels, hooks, cron, memory
│   ├── session/                 # Session domain, migrations, event store,
│   │                            # attachments, knowledge store
│   ├── skills/, skillhub/       # Skills and online marketplace
│   ├── stats/                   # Usage statistics dashboard and queries
│   ├── systeminit/              # AGENTS.md generation
│   ├── tools/                   # Built-in tool implementations
│   ├── tui/                     # Bubble Tea terminal UI
│   └── workflow/                # JavaScript workflow runtime
├── example/                     # Public SDK examples
└── docs/                        # Bilingual docs, generated indexes, site
```

## Running Modes

MothX supports 6 running modes, all sharing the same Agent, Provider, Tools,
and Session infrastructure:

```
┌─────────────────────────────────────────────────────────────────────────┐
│                        MothX Running Modes                         │
├─────────────────────────────────────────────────────────────────────────┤
│                                                                         │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐                  │
│  │  TUI (default)│  │  Print Mode   │  │  ACP stdio   │                  │
│  │  mothx   │  │  mothx   │  │  mothx   │                  │
│  │              │  │  -p "..."     │  │  acp          │                  │
│  └──────────────┘  └──────────────┘  └──────────────┘                  │
│                                                                         │
│  ┌──────────────┐  ┌──────────────┐  ┌────────────┐                  │
│  │ Serve Mode   │  │ A2A Standalone│  │ A2A Master │                  │
│  │ mothx serve  │  │ mothx a2a     │  │ --enable-  │                  │
│  │              │  │ start         │  │ a2a-master │                  │
│  └──────────────┘  └──────────────┘  └────────────┘                  │
│                                                                         │
└─────────────────────────────────────────────────────────────────────────┘
```

## Core Components

### 0. Shared Agent Runtime

The Agent Runtime is the single boundary between front ends and the Agent Core.
TUI, CLI, WebUI/API, Desktop/ACP, WeChat/Feishu, Cron, ESM, and A2A adapters decode
their own protocol and project events; they do not own execution semantics.

- **Construction:** `SessionRuntime.BuildAgent`, `BuildTransientAgent`, and
  `agentruntime.NewAgentManager` are the only production Agent construction paths.
- **Policy:** source, effective mode, capabilities, tools, sandbox, approval,
  MCP, skills, reasoning, and run policy are resolved once through
  `ResolveSource`/`ResolvePolicy`. Product default mode is `yolo`.
- **Execution:** `ExecutionRuntime` + `RunStore` own durable run begin, reattach,
  update, cancel, finish, recovery, and the single canonical terminal event.
- **Decisions:** `DecisionService`/`DecisionRecord` own approval and question
  identity, deadlines, first-response-wins, replay, and expiry.
- **Input and artifacts:** all text/image/audio/file input normalizes into the
  Runtime input contract; attachments and generated artifacts are Runtime-owned
  and backed by `internal/session`.
- **Resources:** context/skills/rules, Expert Teams, MCP clients, knowledge
  services, worktrees, and coordinated shutdown are owned by the Runtime.
- **Admission:** one per-session submission coordinator and fenced execution
  lease decide whether a new run may start; adapters may only project that state.

### 1. Provider System

Provider is an abstraction layer for interacting with LLM APIs. All running modes
use `internal/provider/factory` for provider creation, which applies vendor adapter
defaults before constructing the generic OpenAI-compatible or Anthropic-compatible
protocol provider.

```
┌─────────────────────────────────────────────────────────────┐
│                      Provider Interface                      │
├─────────────────────────────────────────────────────────────┤
│  Chat(ctx, params) <-chan StreamEvent                       │
│  Models() []*Model                                          │
│  GetModel(id string) *Model                                 │
│  Name() string                                              │
└─────────────────────────────────────────────────────────────┘
                              │
                              │
            ┌─────────────────┴─────────────────┐
            ▼                                   ▼
    ┌───────────────────┐             ┌───────────────────┐
    │ Vendor Adapters   │             │ Generic Fallback  │
    │ vendor_*.go       │             │ openai/anthropic  │
    └───────────────────┘             └───────────────────┘
```

Vendor resolution order:

1. Explicit `vendor` field in provider config
2. Base URL detection
3. Generic fallback based on `api`

#### StreamEvent Types

```go
type StreamEvent struct {
    Type        EventType
    TextDelta   string      // Text delta
    ThinkingDelta string    // Thinking delta
    ToolCall    *ToolCall   // Tool call
    Usage       *Usage      // Token usage
    Error       error       // Error
}
```

### 2. Agent Loop

Agent is the core logic that coordinates Provider, Tools, and Session. All running
modes reuse the same Agent loop — the difference is only the input source (terminal,
HTTP, messaging, A2A, stdio) and output target.

```
┌─────────────────────────────────────────────────────────────┐
│                       Agent Loop                             │
├─────────────────────────────────────────────────────────────┤
│  1. Build system prompt (mode + tools + context files + skills)
│  2. Send messages to Provider                               │
│  3. Process stream events (text, thinking, tool calls)      │
│  4. Execute tools and collect results                       │
│  5. Add tool results to messages                            │
│  6. Repeat until complete                                   │
└─────────────────────────────────────────────────────────────┘
```

#### Execution Flow

```
User Input (TUI / CLI / HTTP / Messaging / A2A / ACP stdio / Desktop)
    │
    ▼
┌───────────────┐
│ Build Context │ ← System Prompt + Tools + Context Files + Skills
└───────┬───────┘
        │
        ▼
┌───────────────┐
│  Provider     │ ← LLM API (OpenAI/Anthropic)
│  Chat()       │
└───────┬───────┘
        │
        ▼
┌───────────────┐     ┌───────────────┐
│ Stream Events │────▶│ Tool Calls?   │
└───────┬───────┘     └───────┬───────┘
        │                     │
        │                     ▼
        │              ┌───────────────┐
        │              │ Execute Tools │
        │              └───────┬───────┘
        │                     │
        │                     ▼
        │              ┌───────────────┐
        └──────────────│ Append Results│
                       └───────────────┘
```

### 3. Multi-Agent Runtime

Multi-agent mode is opt-in with `--multi-agent`. When enabled, the main agent
gets the `subagent_spawn`, `subagent_status`, `subagent_send`, and
`subagent_destroy` tools. Child agents have isolated messages, context, session,
registry, and job manager state.

```
Main Agent
    │
    ├── agentruntime.NewAgentManager creates child agents
    ├── EventRouter routes events by AgentID
    └── subagent_* tools manage async child work
```

Child agents cannot create nested sub-agents because their registries filter out
the `subagent_*` tools.

### 4. A2A Protocol

The A2A (Agent-to-Agent) protocol enables different AI agents to discover,
communicate, and collaborate with each other.

```
┌───────────────────────────────────────────────────────────────────┐
│                     A2A Protocol Architecture                      │
├───────────────────────────────────────────────────────────────────┤
│                                                                   │
│  ┌──────────────────┐          ┌──────────────────┐              │
│  │   A2A Server     │          │   A2A Client     │              │
│  │  (mothx)    │ ◄──────► │  (any agent)     │              │
│  │                  │  JSON-RPC │                  │              │
│  │  /a2a            │  2.0     │  SendMessage()   │              │
│  │  /a2a/send       │  + SSE   │  GetTask()       │              │
│  │  /a2a/task       │          │  CancelTask()    │              │
│  │  /a2a/events     │          │  GetAgentCard()  │              │
│  └──────────────────┘          └──────────────────┘              │
│                                                                   │
│  Task lifecycle: submitted → working → completed/failed/canceled   │
│                                                                   │
│  Run with: mothx a2a start (default port 8093)                    │
│                                                                   │
└───────────────────────────────────────────────────────────────────┘
```

#### A2A Master Mode

A2A Master mode is enabled via `--enable-a2a-master`. It loads a remote agent
list from `a2a-list.json` and registers an `a2a_dispatch` tool for the LLM
to automatically dispatch tasks.

```
┌───────────────────────────────────────────────────────────────┐
│                   A2A Master Mode                              │
├───────────────────────────────────────────────────────────────┤
│                                                               │
│  a2a-list.json                                                │
│  ┌─────────────────────────────────────────┐                  │
│  │ agents:                                 │                  │
│  │   - name: code-reviewer                 │                  │
│  │     url: http://review:8093             │                  │
│  │   - name: ci-agent                      │                  │
│  │     url: http://ci:8093                 │                  │
│  └─────────────────────────────────────────┘                  │
│           │                                                   │
│           ▼                                                   │
│  ┌──────────────────┐                                         │
│  │   A2AManager     │ ← loads agent list                      │
│  └────────┬─────────┘                                         │
│           │                                                   │
│           ▼                                                   │
│  ┌──────────────────┐                                         │
│  │  a2a_dispatch    │ ← registered as LLM tool                │
│  │  (agent_name,    │                                         │
│  │   message)       │                                         │
│  └────────┬─────────┘                                         │
│           │                                                   │
│           ▼                                                   │
│  ┌──────────────────┐  ┌──────────────────┐                  │
│  │  code-reviewer   │  │  ci-agent        │                  │
│  │  http://review   │  │  http://ci       │                  │
│  │  :8093           │  │  :8093           │                  │
│  └──────────────────┘  └──────────────────┘                  │
│                                                               │
└───────────────────────────────────────────────────────────────┘
```

### 5. Serve Mode

`internal/serve/openaiapi/` implements the OpenAI-compatible HTTP API used by
serve mode.

```
┌─────────────────────────────────────────────────────────────┐
│                    Serve Architecture                       │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  OpenAI-compatible clients (curl, SDK, any tool)             │
│       │                                                     │
│       ▼                                                     │
│  ┌──────────────────────────────────────────┐               │
│  │  HTTP API (net/http)                   │               │
│  │  POST /v1/chat/completions               │               │
│  └──────────────────────────────────────────┘               │
│       │                                                     │
│       ▼                                                     │
│  ┌──────────────────────────────────────────┐               │
│  │  Agent Loop (shared)                     │               │
│  │  + Tools + Session + Sandbox + Skills     │               │
│  └──────────────────────────────────────────┘               │
│                                                             │
│  Config: serve.json (global ~/.mothx/ or project .mothx/)  │
│  Security: Bearer token + allowedWorkDirs + sandbox          │
│                                                             │
└─────────────────────────────────────────────────────────────┘
```

### 6. Channels Messaging Serve

`internal/serve/channels/` implements the messaging channel runtime for WeChat,
Feishu, and WebSocket.

```
┌─────────────────────────────────────────────────────────────┐
│                    Channels Architecture                        │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐                  │
│  │  WeChat   │  │  Feishu   │  │ WebSocket │                  │
│  └─────┬────┘  └─────┬────┘  └─────┬────┘                  │
│        │             │             │                         │
│        └─────────────┼─────────────┘                         │
│                      ▼                                       │
│  ┌──────────────────────────────────────────┐               │
│  │  Channels Dispatcher                       │               │
│  │  (per-user session, yolo mode default)   │               │
│  └──────────────────────────────────────────┘               │
│       │                                                     │
│       ▼                                                     │
│  ┌──────────────────────────────────────────┐               │
│  │  Agent Loop (shared)                     │               │
│  │  + Tools + Session + Sandbox + Skills     │               │
│  └──────────────────────────────────────────┘               │
│                                                             │
│  Config: serve.json                                         │
│  Session: <sessionDir>/channels/<platform>/<user_id>/        │
│                                                             │
└─────────────────────────────────────────────────────────────┘
```

### 7. Cron Scheduler

The `internal/cron` package provides a `sessions.db`-backed cron store and
scheduler. Jobs are stored in the `cron_jobs` table, bound to sessions, and can
execute through agent tools or remote A2A servers.

```
┌─────────────────────────────────────────────────────────────┐
│                    Cron Scheduler                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  ┌──────────────────┐                                       │
│  │  CronStore       │ ← sessions.db / cron_jobs             │
│  │  (SQLiteCronStore)                                      │
│  └────────┬─────────┘                                       │
│           │                                                 │
│           ▼                                                 │
│  ┌──────────────────┐                                       │
│  │  Scheduler       │ ← periodic polling (default 30s)      │
│  └────────┬─────────┘                                       │
│           │                                                 │
│     ┌─────┴─────┐                                           │
│     ▼           ▼                                           │
│  ┌───────┐  ┌───────────┐                                   │
│  │SubAgent│  │A2A Server │                                   │
│  │(local) │  │(remote)   │  ← --a2a-target flag              │
│  └───────┘  └───────────┘                                   │
│                                                             │
└─────────────────────────────────────────────────────────────┘
```

### 8. Tool System

Tools are the way Agent interacts with the external world. All running modes
share the same tool registry.

```
┌─────────────────────────────────────────────────────────────┐
│                    Tool Interface                            │
├─────────────────────────────────────────────────────────────┤
│  Name() string                                              │
│  Description() string                                       │
│  Parameters() json.RawMessage                               │
│  Execute(ctx, params) (*ToolResult, error)                  │
└─────────────────────────────────────────────────────────────┘
                              │
        ┌─────────────────────┼─────────────────────┐
        │                     │                     │
        ▼                     ▼                     ▼
┌───────────────┐   ┌───────────────┐   ┌───────────────┐
│  File Tools   │   │  Search Tools │   │  System Tools │
│  - read       │   │  - grep       │   │  - bash       │
│  - write      │   │  - find       │   │  - ls         │
│  - edit       │   │               │   │  - jobs       │
└───────────────┘   └───────────────┘   │  - kill       │
                                        └───────────────┘
┌───────────────┐   ┌───────────────┐   ┌───────────────┐
│  Planning     │   │  Skills       │   │  A2A Master   │
│  - plan       │   │  - skill_ref  │   │  - a2a_       │
│               │   │               │   │    dispatch   │
└───────────────┘   └───────────────┘   └───────────────┘
```

### 9. Session Management

Sessions use SQLite storage with tree structure and branching support.

```
┌─────────────────────────────────────────────────────────────┐
│                    Session Storage                          │
├─────────────────────────────────────────────────────────────┤
│  sessions.db                                                │
│  ├── sessions                                               │
│  │   ├── id                                                 │
│  │   ├── cwd                                                │
│  │   ├── timestamp                                          │
│  │   ├── parent_session                                     │
│  │   └── version                                            │
│  └── entries                                                │
│      ├── seq                                                │
│      ├── session_id                                         │
│      ├── id                                                 │
│      ├── type                                               │
│      ├── parent_id                                          │
│      ├── timestamp                                          │
│      └── data                                               │
└─────────────────────────────────────────────────────────────┘
```

#### Session Types

| type | Description |
|------|-------------|
| `session` | Session metadata |
| `message` | User/assistant messages |
| `model_change` | Model change record |
| `compaction` | Context compression record |
| `label` | Session label |

### 10. Sandbox System

Sandbox implements process isolation through bubblewrap (bwrap).

```
┌─────────────────────────────────────────────────────────────┐
│                     Sandbox Manager                          │
├─────────────────────────────────────────────────────────────┤
│  SetLevel(level)                                            │
│  GetActive() *Sandbox                                       │
│  Execute(cmd) (stdout, stderr, error)                       │
└─────────────────────────────────────────────────────────────┘
                              │
        ┌─────────────────────┼─────────────────────┐
        │                     │                     │
        ▼                     ▼                     ▼
┌───────────────┐   ┌───────────────┐   ┌───────────────┐
│  LevelNone    │   │ LevelStandard │   │  LevelStrict  │
│ (Unrestricted)│   │ (Project R/W) │   │ (Project R/O) │
└───────────────┘   └───────────────┘   └───────────────┘
```

### 11. TUI System

Terminal user interface based on Bubble Tea.

```
┌─────────────────────────────────────────────────────────────┐
│                        TUI App                              │
├─────────────────────────────────────────────────────────────┤
│  Startup Header                                             │
│  Vibe logo │ version │ provider/model │ cwd                 │
├─────────────────────────────────────────────────────────────┤
│  Native terminal scrollback                                 │
│  Completed transcript blocks are printed with Program.Println│
├─────────────────────────────────────────────────────────────┤
│  Managed live view                                          │
│  Live assistant/thinking stream, sticky plan todos, loading  │
│  indicator, prompt input, footer, and multi-agent tab bar    │
├─────────────────────────────────────────────────────────────┤
│  Tool details modal                                         │
│  Ctrl+O opens a scrollable full-screen details view          │
└─────────────────────────────────────────────────────────────┘
```

Key TUI behaviors:

- Completed messages are printed to the terminal's native scrollback so the terminal owns history scrolling and text selection.
- The managed Bubble Tea view focuses on live streaming content, multiline input, footer status, loading state, and active plan/todo context.
- The input editor supports multiline prompt composition: `Enter` submits, `Alt+Enter` / `Ctrl+J` insert newlines, and `Up` / `Down` move within the input before browsing history at boundaries.
- The default TUI transcript is a simple event view: each tool call is one concise line, routine lifecycle events are hidden, and a running tool is replaced by its completed summary. `Ctrl+G` switches to the full event view; `Ctrl+O` opens the latest tool/details modal with raw arguments, output, diffs, and activity timeline.
- In multi-agent mode, a tab bar shows active agents and their status when more than one agent exists.

## Configuration Files

| File | Location | Purpose |
|------|----------|---------|
| `settings.json` | `~/.mothx/` or `.mothx/` | Core settings (provider, model, mode, etc.) |
| `serve.json` | `~/.mothx/` or `.mothx/` | Unified serve configuration |
| `a2a.json` | `~/.mothx/` or `.mothx/` | A2A server configuration |
| `a2a-list.json` | `~/.mothx/` or `.mothx/` | A2A Master remote agent list |
| `mcp.json` | `~/.mothx/` or `.mothx/` | MCP server configuration |
| `memory.md` | project root or `~/.mothx/` | Persistent memory |
| `sessions.db` | session directory | Sessions, stats, events, and session-bound cron jobs |

## Data Flow

### Complete Request Flow

```
1. User input (from TUI / HTTP / Messaging / A2A / ACP stdio)
   │
   ▼
2. Input layer captures
   │
   ▼
3. Agent.Run(ctx, input)
   │
   ▼
4. Build system prompt
   ├── Mode prompt (plan/agent/yolo)
   ├── Tool definitions (JSON Schema)
   ├── Context files (AGENTS.md, CLAUDE.md)
   └── Skills context
   │
   ▼
5. Build message history
   ├── Historical messages (from Session)
   └── New user message
   │
   ▼
6. Provider.Chat(ctx, params)
   │
   ▼
7. SSE streaming response
   ├── TextDelta → Display text
   ├── ThinkingDelta → Display thinking
   └── ToolCall → Execute tool (incl. a2a_dispatch)
   │
   ▼
8. Tool execution (via Sandbox)
   │
   ▼
9. Collect tool results
   │
   ▼
10. Continue conversation (back to step 5)
   │
   ▼
11. Complete, save session
```

## Key Design Decisions

### 1. Interface Abstraction

Use interface abstraction for Provider and Tool, facilitating extension and testing.

### 2. Stream Processing

Use Channel for streaming responses, providing real-time feedback.

### 3. Session Tree

Use tree structure for session storage, supporting branching and restoration.

### 4. Layered Configuration

Support global and project configuration, with project configuration overriding global.

### 5. Sandbox Isolation

Implement process-level isolation through bubblewrap, protecting system security.

### 6. Public SDK Package

The `agent/` package exposes public Go types (`Agent`, `Provider`, `Builder`) so
external applications can embed an Agent without depending on internal packages.
`bootstrap/` wires those public interfaces to the internal Runtime. See
[SDK Integration Guide](sdk.md) for usage details.

### 7. Shared Agent Runtime and Agent Loop

All running modes (TUI, CLI, WebUI/Serve, Channels, A2A, ACP, Desktop) reuse the
same Agent Runtime and Agent loop. Adapters differ only in protocol decoding and
event projection. Resource ownership, run lifecycle, decisions, and policy live
in the Runtime so behavior cannot drift between entry points.

---

## Changelog

Source: https://mothx.net/en/changelog.md

# Changelog

## v1.3.109

### 💥 Behavior Changes

- **Desktop (Electron) is deprecated; MothX Native is the primary desktop client.** The `desktop-release.yml` workflow no longer runs on version tags and remains only as a manual compatibility bridge that can never mark a release as latest; `native-release.yml` is the sole automatic publisher of desktop artifacts (Linux binary/deb/tar.gz/PKGBUILD, macOS dmg, Windows exe/setup). The root Makefile help lists Native first and marks the Desktop targets deprecated. New bilingual guides (`docs/en/native.md`, `docs/zh/native.md`) cover installation, the feature surface, and migration; `desktop.md` carries a deprecation banner with a named removal condition (delete `desktop/` and its entry points once a full release cycle ships no Desktop assets and no manual compatibility build was needed). No canonical data moves: sessions, transcripts, and configuration stay in the shared Runtime, so Desktop users switch shells without migration.

### ✨ New Features

- **A Router ACP profile can set the external worker's default model.** `acpAgents` now accepts an optional `model` field, applied by the Runtime when it creates the remote worker session. MothX uses the standard ACP `configOptions` model option (`category: "model"`) and falls back to the deprecated `models`/`session/set_model` wire only for a worker that advertises no modern option. Leaving `model` empty preserves the third-party Agent's own default behavior. A configured model that the worker does not offer fails the delegation with the available choices instead of silently running a different model, and a resumed session with no returned catalog keeps the Agent's persisted selection. The profile's model is editable from the TUI `/router` panel, the WebUI Router Worker settings, and Desktop Router Workers, and is projected in the shared Runtime catalog.
- **Router now has one worker-management signature and a loopback MCP bridge.** Router mode registers exactly one tool, `delegate_worker_mgr`, whose `delegate`/`spawn`/`status`/`list`/`send`/`wait`/`destroy`/`integrate`/`answer` actions cover the whole external ACP worker lifecycle; the local `delegate_subagent` and `subagent_*` tools no longer appear in Router and no longer advertise Router-only fields. A local stdio worker can receive one MCP server, `mothx-worker`, in `session/new|load|resume`, authenticated by an in-memory per-child bearer token. Its single `worker_mgr` tool supports `context`, `report` (notice/progress/finding), and `ask` (durable `DecisionQuestion` answered by the lead through `delegate_worker_mgr(action=answer)`), with bounded bodies, per-child rate limiting, dedupe keys, and session-scoped JSONL evidence (`worker-messages/<sessionId>/worker_messages.jsonl`, removed with the session). Findings enter lead context as `[WORKER_FINDING]` and may wake an idle lead; notice/progress never do. The bridge binds `tcp4 127.0.0.1:0` lazily, never uses stdio/SSE/public URLs, projects `mcpBridge=unavailable|unreachable|disabled` without blocking a task, including when bridge registration or listener startup fails. A token lives for the worker's remote session, not one turn: a post-terminal bridge call returns a `child_terminal` MCP tool error and the next `send` re-enables the same credential, while destroy/close, session shutdown, or process exit revokes it. The `delegate_worker_mgr` description publishes a capability summary derived from the same resolved state (report/ask, attachments, write, terminal, resume) and names why the bridge is unavailable. Worker activity is projected read-only in the TUI `/router` panel, ACP `mothx/worker/messages`, WebUI `GET /api/sessions/<id>/router`, and the Desktop Router composer; only the lead can answer a question. Profile `driver`, `mcpBridge`, and `capabilityOverrides` are editable from the TUI panel, WebUI Router Worker settings (`PATCH /api/acp/profiles`), and Desktop Router Workers settings (`mothx/manage/acp/profiles/patch`). `mothx doctor` now also verifies that the listener closes after its last token. See `docs/en/tools.md` and `docs/en/configuration.md`.

- **New Gitee/Moark Model: `hy4`**
  - Added `hy4` to the `gitee` and `moark` providers: a reasoning model with a 1M context window and text-only input, using the `deepseek-v4.1` reasoning-effort scale with no default max_tokens.

- **New Volcengine Model: `deepseek-v4.1-flash-economy`**
  - Added `deepseek-v4.1-flash-economy` to all three Volcengine providers — `volcengine`, `volcengine-agentplan`, and `volcengine-codingplan` — with a 1M context window, reasoning support, and text+image input. The standard channel sends 262K max_tokens; the two plan channels send 100K.

- **New Volcengine Model: `glm-5.4`**
  - Added `glm-5.4` to all three Volcengine providers — `volcengine`, `volcengine-agentplan`, and `volcengine-codingplan` — with a 1M context window, reasoning support, and text+image input; it sends no default max_tokens, so the provider default applies.

- **The Tencent Cloud plan now exposes only `hy4` and `hy4-flash`.**
  - The `tencent-hy-plan` and `tencent-hy-plan-anthropic` presets now list `hy4` and `hy4-flash` instead of `hy3`. `hy4` is text-only and `hy4-flash` accepts text and images; both support reasoning, carry a 1M context window, and keep a 65,536-token output ceiling.

- **The Alibaba Cloud Token Plan preset now targets the Qwen AI endpoint and a refreshed catalog.**
  - `alibaba-token-plan` now uses `https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1` and ships `auto`, `qwen4-max`, `qwen3.8-max`, `qwen3.8-flash`, `deepseek-v4.1-flash-1017`, `deepseek-v4.1-flash`, and `glm-5.3` instead of the previous Qwen/Kimi/DeepSeek/GLM/MiniMax list. The Qwen and DeepSeek entries accept text and image input with a 1M context window, `qwen4-max` uses the native Qwen thinking switch, and `glm-5.3` keeps a 131,072-token output ceiling. The built-in `bailian` vendor adapter also detects the new domain automatically.

- **DeepSeek sessions can use native conversation titles.** When the resolved provider targets `api.deepseek.com`, the first model request of a titleless session now opts into DeepSeek's in-band `title` extension across the Chat Completions, Responses, and Anthropic Messages protocols. Agent Core captures the returned title (or falls back to the first user message when a refusal or error omits it), and the shared Runtime persists it once as an `auto` session title. Serve publishes `title_updated`; TUI, CLI, WebUI/API, ACP/Desktop, channels, and the public SDK all reuse the same Runtime path, so no adapter gains a second title request or generator. Serve keeps its existing separate title call for providers without the extension.

- **MothX Native closes the remaining Desktop parity gaps and fixes background layering.** Native now projects the canonical `subagent` lifecycle events into inline child cards, a per-session live roster (bounded at 200, running children kept) with a running/total header count and failure dot, and re-reads the authoritative `mothx/subagent/list` on terminal events and session load; background teams keep updating their own cached session. Plans carry the Runtime's `mothx.dev` title/note annotation into the side panel, card, and export; a collapsed streaming thought shows a compact live tail preview; tool text/diff ingestion is bounded like Desktop (20k/40k chars). Appearance gains the app-wide/home-only background scope with a readable theme veil, the launch quick-start scratch directory plus recent-directory picker history in the composer workspace menu, and automatic rollback when a user-selected runtime binary fails to start or initialize. Acceptance renders over a busy photo-like background caught and fixed a paint-order bug (MyGo paints absolute children above flow siblings, so the background layer hid the whole shell); negative ZIndex layering plus pixel-probe and headless regressions now pin image/veil/shell order in both themes and scopes.
- **MothX Native matches Desktop's New Task directory contract and completes elicitation forms.** A New Task draft no longer inherits the previous directory: it stays unset until the native picker (or a worktree action) supplies one, the shell asks at creation and again at send time, and cancelling keeps the draft instead of sending into an unknown cwd; the launch quick-start scratch remains the only no-ask default. While the draft has no directory, the provider/model menu is projected from `mothx/manage/providers/list` (configured providers first, catalog order kept, draft > existing > default preference) because `draft-config-options` requires a cwd. Multi-property `elicitation/create` schemas now render one input/enum field per property and answer with content keyed by property name; single-property and replayed object-enum schemas keep working, and an empty form declines.

### ♻️ Runtime and Architecture

- **ACP worker capabilities are now a typed, resolved model.** `internal/agentruntime/workerdriver` owns `WorkerCapabilities`, an explicit `generic-acp` adapter, and the profile ∩ advertised ∩ policy resolver; business code reads capabilities instead of probing raw `agentCapabilities` maps. Profiles gain optional `driver`, `mcpBridge`, and tighten-only `capabilityOverrides`. Resolved capabilities, degradations, and bridge state are persisted on `session_child_runs` (migration 58) and projected in child metadata. `mothx doctor` now checks loopback `tcp4` bindability and profile driver/bridge/override validity. `internal/architecture` guards the workerdriver leaf boundary and forbids driver-identity branches in business code. Real interop on 2026-11-10 verified OpenCode 2.0.16 and codex-acp 0.16.0 against the loopback bridge (OpenCode produced a real `worker_mgr` finding, codex-acp completed the MCP handshake); both were described by `generic-acp`, so no unverified flavor was added.

### 🐛 Bug Fixes

- **Gateway-hosted MiMo models replay `reasoning_content` with tool calls.** MiMo requires an assistant message that carries `tool_calls` to replay its `reasoning_content` on the next request. The requirement was previously detected only from the `xiaomimimo` base URL, so `mimo-*` models served by aggregators (B.AI, Gitee/Moark, OpenRouter, ...) could omit the field when the session had no recorded reasoning. MiMo model IDs are now recognized too, even when the gateway catalog does not list the model, and replayed assistant messages receive an empty `reasoning_content` placeholder when no reasoning was recorded.

- **Thinking switches and reasoning effort now match each vendor's documented contract.** An explicit thinking-off now sends `thinking: {type: "disabled"}` for DeepSeek Chat Completions/Anthropic Messages and `enable_thinking: false` for Qwen hybrid models instead of silently leaving thinking on, DeepSeek V4.1 uses `reasoning_effort: "none"` on the Responses API, and GLM effort maps to `low`/`high`/`max` so `medium` is never sent. DeepSeek effort follows its documented scale (`minimal`/`low` → `low`, `medium`/`high`/`xhigh` → `high`, `max` → `max`), gateway Qwen3.5+ and GLM model IDs are detected for thinking-format resolution, and a configured model list no longer inherits `compat` from the built-in preset at the same slice index.

- **MothX Native run and transport reliability fixes.** Session load and session-list responses now carry a connection generation, so a slow or failed load for a session the user already left cannot clear another session or reuse its cached transcript, and a session-list refresh requested while one is in flight is re-queued instead of silently dropped. The ACP client stores its child pointer atomically, bounds ordinary requests with a 5-minute deadline (`session/prompt` stays unbounded), and closes the child through the owned `os.Process` handle so a reused PID cannot be killed. Stale provider/draft-config responses are ignored after reconnect, and SkillHub icon fetches reject loopback/private/link-local targets at both URL validation and dial time. Native feature packages gained guard tests, and a cross-module wire test now executes the real management handlers and checks that every Native response key still matches the Runtime contract.

- **TUI queued prompts now have one scheduler and a stable session binding.** The TUI no longer keeps a second queue/scheduler next to Runtime's `SubmissionCoordinator`: every interactive prompt is registered synchronously before the run starts, prompts staged during the first-session bootstrap are flushed into the coordinator once the session activates, slash commands are rejected while busy instead of being queued and sent to the model as text, and staged attachments stay with the prompt that owned them. A session change retires the old coordinator and clears its projections, so a queued prompt can never run in a different session.

## v1.3.108

### 💥 Behavior Changes

- **Router no longer uses profile-level `roles` or `writeRoots`.** Role is now an optional per-delegation semantic hint (default: `investigate`), and `write_scope` is optional task metadata used for prompting, audit, and overlap checks. A write role no longer requires a scope, but MothX's optional `fs/write_text_file` bridge is offered only when a task declares a non-empty scope. This is a correctness fix, not a claim of containment: an external ACP Agent runs its own tools, so neither setting can confine its writes. Managed per-child worktrees plus `subagent_integrate` remain the real write-isolation path, and base-workspace parallelism remains explicit operator trust. Existing `settings.json` values still parse but are ignored and no longer appear in the TUI, Runtime catalog, WebUI, or Desktop. A MothX self-ACP worker can now be configured with just its command, enabled flag, and permission policy.
- **The lead agent loop's iteration budget starts at 400 turns and can be renewed up to 600.** The main loop's default initial iteration limit is now 400 (previously 200) and its renewal ceiling is 600, so a long task that keeps making progress runs twice as long before the budget-pressure notice appears. The `extend_budget` policy keeps two grants, and the per-grant step is now derived from the Soft->Hard headroom so the grants exactly fill it (400 -> 500 -> 600); a run that never renews simply stops at 400. The companion limits scale with it: the stuck-detection silent-turn threshold is now 195 (was 95), channel runs default to `maxTurns` 180 (was 90), and sub-agent / workflow-worker `max_iterations` defaults to 100 (was 50). A caller that supplies an explicit soft limit still gets the conventional 2x hard ceiling.

### ✨ New Features

- **Twelve role-based expert teams now ship as built-in bundles.** The built-in catalog now includes backend-platform, web-frontend, mobile-crossplatform, systems-lowlevel, enterprise-jvm-dotnet, qa-testing, security-compliance, devops-sre, data-ml-ai, product-architecture, docs-research, and agent-platform, adding 58 duty-named roles (for example `Backend Lead` or `Database & Migration Lead`) alongside the existing software-company and frontend-developer bundles. Each team lead receives the same roster and scheduling discipline as the original software team; member display names use duty labels rather than personal names. The embedded assets add roughly 142 KB to the binary, and no ECC skill scripts are copied: each team ships one original, focused `SKILL.md` distilled from the same practices, while role guidance lives in bounded personas. The WebUI also localizes the built-in category labels used by these bundles.
- **Added the SenseNova (商汤日日新) provider.** The built-in `sensenova` preset targets the SenseNova token-plan endpoint `https://token.sensenova.cn/v1` with the OpenAI-compatible `openai-chat` API, reads `${SENSENOVA_API_KEY}`, registers a `sensenova` vendor adapter for `sensenova.cn` base-URL auto-detection, and ships `sensenova-6.8-flash` and `sensenova-6.8-flash-lite`, each with a 1,000,000-token context window, a 131,072-token output ceiling, reasoning support, and `text`/`image` multimodal input.
- **Router mode is still a beta (preview) mode.** Router and the `acpAgents` profiles that feed it are evaluation features, not a production contract: the tool surface, the profile schema, and the lifecycle may change in any release without a compatibility migration path, and Router stays deliberately excluded from `defaultMode` (a stray `defaultMode: router` still resolves to read-only `plan`). Use Router to try external ACP workers on a scratch session, and do not depend on it for unattended or production workflows. The TUI, CLI, WebUI, and Desktop entry points all project the same Runtime-owned behavior, so the evaluation covers every entry point equally. Every Router surface now says so: the TUI status bar, mode cycle, `/router` panel, and `/mode` output, plus the WebUI and Desktop composers, all carry a beta / preview marker.

- **Desktop can now enter Router mode.** The composer gained a Router control that lists the configured external ACP workers and binds the selected ones to the session. Desktop stays a pure ACP projection: the catalog comes from the existing `mothx/manage/acp/profiles/list` and the activation from the new additive `mothx/manage/router/activate`, both of which delegate to the shared Runtime activation path, so Desktop cannot reach a Router state the TUI, CLI, or WebUI could not. The control is gated on the new `manageRouter` feature key and the selection never enters Electron-owned storage.
- **The WebUI can now enter Router mode.** The composer gained a Router button that lists the configured external ACP workers and binds the selected ones to the session. The catalog comes from `GET /api/acp/profiles`, which is the same Runtime catalog the TUI panel renders, so eligibility and the validation verdict stay one fact instead of being recomputed in the browser. Activation goes through `POST /api/sessions/<id>/router`, which delegates to the shared Runtime activation path, so the WebUI cannot reach a Router state the TUI or CLI could not: the profile validation, the non-blocking approval strategy, the idle fence, the source policy, and the durable mode entry all stay Runtime-owned. Channel sessions remain excluded by design, because WeChat and Feishu are source-forced to yolo and can never select Router.
- **A Router profile can opt into parallel base-workspace writers.** An ACP profile may set `allowParallelBaseWorkspaceWrites` to let write-role workers that target the session workspace run concurrently instead of taking it exclusively. The default stays exclusive, so every existing `settings.json` profile keeps its current behavior. This is explicit executable trust rather than a performance default: an external ACP Agent runs its own tools, so MothX cannot confine its writes to the declared `write_scope` and two workers can still touch the same file. The configured `maxConcurrentChildren` ceiling still applies, the Runtime still refuses a parallel writer whose declared `write_scope` overlaps a live base writer because that overlap is statically visible, and `mothx doctor` and the `/router` panel report the opt-in so the residual risk stays visible. Per-child worktrees plus `subagent_integrate` remain the safer default.
- **Router mode can now be activated from the TUI and CLI for a configured external ACP worker.** `/router` opens the ACP worker panel (list, add, edit, delete, and activate profiles); `/router <profile>` and `mothx --router --acp-agent <profile>` activate directly, and all of them call the same Runtime activation path: the profile must exist in `acpAgents`, be enabled, and use a non-interactive permission policy; the session must be idle and not source-forced to yolo; and the Router binding is persisted before the mode entry, so a failed activation leaves a non-Router session. The panel writes only through the single `config.SaveACPAgentProfiles` validator/owner, so an empty `command[0]`, duplicate ID, or malformed transport/URL is rejected before anything is stored. Activation only names the worker; Runtime records the non-blocking approval strategy from the profile and rejects a contradictory one. A hand-edited or legacy `defaultMode: router` is normalized to the read-only `plan` mode at load and resolution time instead of failing every new session's Agent construction; the fallback never widens to full access. A generic mode switch cannot select `router` without that binding: `router` is excluded from the Tab mode cycle and the `defaultMode` cycle, and Agent construction fails closed if a Router lead would be built with no eligible binding, so a persisted default or stale adapter value cannot produce a Router tool surface whose delegation can only fail. Every TUI mode write (`/mode`, the Tab cycle, `/systeminit`, a `defaultMode` settings change) now goes through the shared Runtime, so the adapter can no longer switch locally and then replay the old mode on reopen. A session reopened from another adapter or resumed without a mode flag replays its persisted mode, including Router. Editing `settings.json` remains supported and equally deliberate; external delegation is available through Router.

- **Router mode can delegate to a configured external ACP coding agent.** A Router-bound `delegate_subagent` launches one blocking external worker through the shared Runtime: Agent Core gets only an event/input proxy, while the Runtime owns profile policy, the bounded task contract, the single terminal event, and process containment. The Router lead sees streamed text, thought, tool, plan, and usage projections with `agent` identity; the blocking result carries bounded `worker` metadata labeled `worker-reported`, while the live child event projection keeps the complete streamed text and the lead receives only a bounded envelope. Remote `session/request_permission` requests are recorded through the shared decision ledger and answered immediately with the profile's `auto_allow_once`/`auto_reject` strategy, selecting only an offered one-time option. Cancellation sends `session/cancel`, answers pending requests as cancelled, and reaps the entire process tree (Unix process group, Windows Job Object). The external child transport has no persistence, provider, or adapter dependencies, and `mothx doctor` now validates profile shape and executable availability without launching a worker. An ACP profile's `maxConcurrentChildren` is enforced per session: read-only roles may fan out up to the configured ceiling, while an `implement` worker in a Runtime-managed per-child worktree may coexist with readers; a base-workspace writer remains exclusive. `mothx doctor` and the `/router` panel report the configured and enforced ceilings.

- **Router mode now supports asynchronous external ACP workers.** In addition to blocking `delegate_subagent`, Router exposes `subagent_spawn`, `subagent_status`, `subagent_wait`, `subagent_send`, and `subagent_destroy`. Spawn accepts the same bound `agent` allowlist and bounded role/scope/deliverable/verification contract and returns a manager handle immediately. The Runtime reserves the role-aware permit during child construction, so a spawn that conflicts with a live writer, or a writer that conflicts with any live reader, fails synchronously; read-only workers fan out to the profile ceiling. `subagent_wait(handle: ...)` waits on the existing manager status rather than requiring a team mailbox, and `subagent_send` continues the same remote session with one follow-up turn. External completions also enter the session mailbox keyed by the child handle. Local-only parameters (`member`, `mode`, `work_dir`, `worktree`, `tools`, `max_iterations`) are rejected; `subagent_answer` remains unavailable because ACP decisions use the parent `DecisionService`. Router and an Expert Team are mutually exclusive; a solo expert remains compatible.
- **Idle sessions now wake automatically when external workers complete.** The Runtime coalesces a burst of mailbox completions into one canonical lead Run (25ms debounce, 500ms cap), admits it through the shared submission coordinator and `ExecutionRuntime`, and seeds it with system-injected context instead of a fake user message. TUI, ACP, and Serve/WebUI project the same Run events; the Runtime writes the wake Run's terminal state once, and cancellation, approvals, and questions continue through the existing execution/decision paths. No adapter-local queue, timer, or event stream is created.
- **A Router session can bind an ordered allowlist of external ACP workers.** `/router id1,id2` and `mothx --router --acp-agent id1,id2` persist every selected profile with its own non-blocking approval strategy; the first profile is the default target. `delegate_subagent` and `subagent_spawn` accept any bound ID (a single worker remains a schema `const`, multiple workers become a schema `enum`), while configured-but-unbound profiles are rejected with correction context. `ACPChildBackend` resolves the requested profile instead of assuming the primary one, and the task contract records the actually selected target.
- **Router reuses one ACP process across isolated remote sessions, negotiates attachments, and exposes bounded filesystem/terminal bridges.** The Runtime connection pool initializes at most one process per profile/workdir and creates independent remote sessions, routing `session/update` and reverse permission requests by `sessionId`; shutdown closes the pool exactly once. Router tools accept Runtime input resource IDs in `attachments`; the Runtime verifies ownership, size, and SHA-256 before sending ACP image, audio, or embedded-resource blocks only when the Agent advertised the matching `promptCapabilities`. Embedded resources carry an opaque Runtime URN, never a `file://` path into a worktree that does not contain the session attachment. Unsupported content is disclosed with its Runtime resource ID and session-relative path instead of being silently dropped. When a Runtime Registry is attached, the client advertises `fs.readTextFile` and serves bounded UTF-8 reads through the same workspace-root and symlink fence as local read tools. A write-role task with a non-empty `write_scope` may use `fs/write_text_file`; profiles with `"terminal": true` get the contained terminal bridge. `additionalDirectories` is sent only when the Agent advertises that session capability.
- **ACP transport correctness and child history are now uniform.** Reverse `$/cancel_request` notifications cancel only the matching in-flight request and return ACP's `-32800`; `session/close` treats an already-closed/unknown session as success. `session/resume` is preferred for reconnect when advertised, with `session/load` as the history-replay fallback. Local child backends now persist to the same `session_child_runs` record as ACP children, including transcript, parent Run, workdir, status, and timestamps.
- **External ACP workers can use the standard remote transport.** An `acpAgents` profile may set `transport` to `websocket` or `http` and provide one administrator-configured `url`; omitting it keeps the existing contained stdio launch. The transport-only ACP client supports the remote RFD's cookie affinity, HTTP/2 requirement for `https://`, synchronous `initialize` plus asynchronous POST responses, one connection-scoped and one session-scoped SSE stream, `Acp-Connection-Id`/`Acp-Session-Id` routing (including reverse-request responses), bounded frames, JSON-RPC batch rejection, and DELETE shutdown. Remote profiles reject `command`, `environment`, embedded credentials, and scheme mismatches. The Runtime connection pool keys by transport and endpoint, so remote sessions reuse one initialized connection without sharing stdio workers; policy, decisions, child identity, canonical events, and terminalization stay Runtime-owned.
- **One ACP connection now serves read-only and write-role sessions together.** The pool no longer keys by the per-task write flag. A Registry-backed connection advertises `fs.writeTextFile` as part of its capability union even when the first task is read-only, while each session handler independently enforces its own task role, non-empty write scope, workspace fence, and symlink-resolved path. The same applies to terminal/read capabilities: the connection advertises what the Runtime can enforce, while a session that is not allowed to use it receives `-32601`. This preserves ACP's normal one-process/one-connection, many-isolated-sessions model instead of starting another worker for each role.
- **External ACP workers now honor managed per-child worktrees and retain bounded change sets.** A worktree resolved by `AgentManager` is passed to the ACP backend as trusted construction metadata instead of being ignored in favor of the session directory. The worker's `fs/read_text_file`, scoped `fs/write_text_file`, and `terminal/*` bridges use an isolated registry and sandbox rooted at that worktree, so they cannot read or write the main session workspace; the shared file lock and atomic write path remain in force. On every terminal path the Runtime captures a bounded snapshot with base/head revisions, changed-path statuses, a unified/binary patch, and bounded untracked content with SHA-256 digests. Migration 56 persists `worktree_id`, `base_revision`, `change_set_json`, and `change_set_error` in `session_child_runs`; truncated or failed snapshots are explicit and are never silently integrated. Router's `subagent_integrate` applies selected snapshots through one exclusive Runtime lane: it re-verifies the digest, successful terminal status, truncation state, and managed-worktree identity before applying the tracked patch and untracked bytes, returns git conflicts as structured evidence, and records `integration_id`, `integration_digest`, `integration_status`, `integration_error`, and `integrated_at` (migration 57). A multi-selection is transactional: when a later snapshot conflicts, snapshots applied by the same request are reversed and their evidence is updated. Uncapturable untracked entries (symlinks, special files, unreadable paths) mark the snapshot truncated instead of being silently omitted. Repeated `{handle, digest}` selections are idempotent.


- **Serve Web UI gains a dynamic multi-session workbench.** `/chat` now supports session tabs, up to four split panes with menu/drag splitting, per-pane composers and model/draft state, persisted layout, and a single-pane mobile projection. A single app-wide `session-stream` dispatcher is the only `/ws/runs` consumer and owns the SSE fallback, so background sessions keep streaming when another pane is closed. Panes render canonical `sessionRunStates` directly, and overflowing tabs are reachable through an explicit all-tabs menu; approvals and questions resolve in their owning pane's overlay, while background decisions surface only as tab and global attention badges without stealing focus; layout changes beyond the four-pane or tab limit are rejected with a visible reason. The legacy single-session fallback and its `?workbench=0`/Settings switch have been removed; `/chat` is always the workbench. A read-only Plan dock projects the focused session's latest plan message without adding storage, a tool, or a backend endpoint. Composer text survives tab switches; attachments with a `providerRef` are restored after a refresh, while dataUrl-only attachments prompt the user to select them again. Tab-strip dragging now reorders tabs instead of being mistaken for an edge split, and a second browser tab restores the shared last layout with last-write-wins recovery. Per-session scroll positions survive tab switches, and closing a tab whose task is still running shows a one-time background notice instead of silently dropping it. The workbench tab strip and icon-only toolbar are now compact and theme-aware, and the composer mirrors Desktop: the collapsed model+mode entry expands to plan/agent/yolo/os mode, Work/Code display mode, and provider/model/expert selection, while the session workdir sits in the chat header.

- **Serve gains an authenticated interactive terminal.** `features.terminal` exposes an xterm.js PTY panel backed by `internal/terminal` (creack/pty on Unix, ConPTY on Windows) over `/api/terminals` and `/ws/terminals/`. Terminals bind to the focused session's cwd, inherit the serve environment, support resize/replay/takeover, and are gated by loopback-or-authenticated-listener policy; they create no Run, transcript entry, or Runtime lease and remain outside the sandbox. On Linux the shell also carries `Pdeathsig`, so it cannot outlive the serve process, and a Windows-only ConPTY round-trip test is the real-runner gate. Terminal settings round-trip through `serve.json` saves, including an explicit `enabled: false`, shell, limits, and allowed origins. The status bar surfaces server-side output backpressure instead of treating it as a disconnect, and serve logs only terminal lifecycle metadata (create/exit/kill), never input or output.

- **The TUI status bar reports live generation speed.** While an agent streams, the footer now shows an estimated `tok/s` rate next to the elapsed time. The reading is derived from streamed output deltas over a short rolling window and disappears when no tokens are arriving, for example while a tool runs or an approval is pending. The loading line also shows the run's estimated generated-token total.

- **The TUI gains an in-place MCP manager, and remote MCP follows the current Streamable HTTP revision.** `/mcpmgr [project|global]` opens a panel over the scoped `mcp.json` that adds, edits, deletes, enables, and disables servers one field at a time (transport first, then name, endpoint or command, args, env, headers, and enabled state), replacing the previous `/init_mcp` and `/mcps` commands; changes are configuration-only and take effect after `/reload`. HTTP MCP clients now negotiate the protocol revision during `initialize`, send it in `MCP-Protocol-Version`, advertise `Accept: application/json, text/event-stream`, reject responses that are neither JSON nor `text/event-stream`, and no longer follow redirects on a configured endpoint, so credentials and request bodies cannot leak to another origin. `tools/call` results preserve `structuredContent` plus standard `resource`/`resource_link` blocks as model-readable text instead of dropping them.

### 🐛 Bug Fixes

- **Toggling default-off switches in the TUI `/settings` panel now sticks.** The panel cycled optional booleans through an "auto" (`nil`) state, but `config.LoadSettings()` materializes a missing value from `DefaultSettings`, so the first toggle wrote `nil` and reloaded as the default `false`. `webSearch.enabled` (and the same-shaped `imageGeneration.enabled` and `enableArtifact`) could therefore never be turned on from the TUI. Each toggle now flips the effective value and always persists an explicit boolean.
- **Activating a Router ACP profile no longer freezes the TUI.** Activation previously ran `SessionRuntime.ActivateRouter` inline on the Bubble Tea update loop, so the Runtime's pre-activation session reload and the binding/mode writes blocked input, rendering, and cancellation for the whole reload — seconds on a large `sessions.db`. Activation now runs as a `tea.Cmd`: the update loop stays responsive, the panel shows an in-flight state, other panel keys and concurrent submissions are rejected until the result lands, and the adapter applies the Runtime-resolved mode and tool surface only through the completion message. Runtime remains the sole owner of validation, the idle fence, source policy, persistence, and write ordering.
- **A Router session can now spawn an external ACP worker.** The lead agent was only registered into the `AgentManager` when the adapter's multi-agent, delegate, or workflow capability was enabled, but Router mode installs the same delegation surface without any of those flags. Every spawn therefore failed with `create sub-agent: parent agent agent-master not found`, so a correctly configured and activated worker was never reached. The Runtime now owns the decision through `ManagerBackedToolsEnabled`, which counts Router alongside the ordinary capabilities, and every entry point (TUI, CLI, WebUI/API, ACP/Desktop) registers the lead through it. The TUI, WebUI, and ACP tool-group synchronization also resolve the mode from the Runtime instead of the adapter's own field, so a resumed or freshly activated Router session installs the Router delegation surface rather than the wrong one, and a Router session in ACP/Desktop gets the session-scoped manager its per-session worker binding requires.
- **Manager creation and tool-group synchronization after activation now have one Runtime entry point.** TUI, CLI, WebUI/API, ACP, and channels each open-coded the same "decide whether a manager is needed, build or reuse it, then install/remove the manager-backed tool groups" sequence, so a newly activated Router session could install `delegate_subagent` without a manager that owned the session (or reuse a stale manager after an expert transition). `SessionRuntime.ReconcileManagerBackedTools` now owns that whole decision: it applies the shared capability predicate (including a bound team and Router), builds only when required or explicitly rebuilt, preserves the current handle when construction fails, and reconciles the tool groups against the exact returned manager. Adapters supply only their capability policy, current handle, and construction factory; the TUI/CLI keep a manager for root-agent, ESM, and cron bookkeeping through an explicit `RequireManager` policy rather than a second implementation.
- **The TUI `/browser` command now actually enables browser automation.** The command previously only mutated the TUI-local tool registry, so the browser tool was silently removed again as soon as the first prompt created and bound a session: the shared Runtime reloaded its resources from the stale capability state and unregistered the tool before the Agent was built. The command now goes through the Runtime's own capability path, so the tool, its skill prompt, and the persisted session capability stay one fact. The Runtime also keeps the browser capability consistent across build, attach, capability updates, and resource refresh, and a browser toggle applied before the first prompt is persisted onto the session that prompt creates, so reopening that session keeps browser support enabled.
- **MCP servers no longer require a client restart, and a remote server pinned to an older protocol revision now connects.** Registering or editing an MCP server previously only wrote `mcp.json`, so the change reached the Agent only after a full client restart; the TUI `/mcpmgr` panel, the Serve Web UI `/api/mcp` endpoint, and the ACP `mothx/manage/mcp/set` method now reconnect the affected servers in place through the shared Runtime. MCP tools are owned by their server, so a reconnect replaces exactly that server's tool surface and removes the tools of a server that was deleted or disabled, without disturbing other servers' tools or the built-in ones. A run that is already in flight keeps the tool set it froze at build time, and the change applies to the next run. A failed reload leaves the previous working configuration connected instead of tearing it down. The protocol negotiation also no longer requires the newest revision: a server that answers `initialize` with `2025-06-18`, `2025-03-26`, or `2024-11-05` is accepted, and the `MCP-Protocol-Version` header is only sent for the revisions that define it. An unknown revision is still refused rather than falsely claimed as compatible.
- **Router's external ACP worker path is hardened.** The ACP client no longer closes its notification channel while a transport reader may be sending, so a worker exit or cancellation cannot panic on a concurrent send; the final response is also preferred over the transport's terminal error when both become ready together. Inbound frames are read in bounded fragments, rejecting an oversized line before allocating the whole payload. A single Router worker remains a schema `const`; a multi-worker binding becomes a bound-only `enum`. Local-child parameters (`mode`, `work_dir`, `worktree`, `tools`, `max_iterations`) are rejected instead of silently ignored. ACP permission cancellation now goes through `DecisionService`, failed resolution commits discard the in-memory pending row after recording a terminal one, output truncation preserves UTF-8, and Windows workers start suspended until they join the Job Object.
- **An asynchronously spawned external worker is no longer cancelled with the lead turn that created it.** A worker started through `subagent_spawn` derived its run context from the spawning lead's run, and that context is cancelled when the lead run reaches its terminal state. Every spawned worker was therefore cancelled the moment the lead finished its own turn, so a fan-out never actually ran to completion and the workers reported `canceled` instead of their result. The spawned worker now runs on a context detached from the lead's cancellation while keeping its values, and it stays cancellable through the manager, so `subagent_destroy` and Runtime shutdown still reach it. The blocking `delegate_subagent` path is unchanged: it is meant to end with the lead turn. This affects every entry point, because the lifecycle lives in the shared Agent Core rather than in one adapter.
- **External worker completions now carry their canonical child handle in the session mailbox.** A spawned ACP worker previously enqueued a completion with an empty member ID, making the mailbox item unactionable and its error hint point at a nonexistent local member. The completion now uses the child handle, is marked external, and points follow-up guidance at `subagent_status`/`subagent_send`; it still flows through the existing manager monitor and mailbox drain without a second child state machine.
- **External worker terminal metadata is no longer stale.** `subagent_status` and `subagent_wait` previously projected metadata captured when the child was created, so a finished worker never showed its `changeSetDigest`, truncation flag, or change-set capture error. The shared manager now refreshes backend metadata on status transitions, letting `subagent_integrate` use the exact evidence without relying only on the blocking delegate envelope.
- **TUI cancellation and quit paths no longer duplicate an automatic continuation's terminal state.** The Runtime owns the terminal transaction for a mailbox-wake Run, so the adapter's `finish` projection is now a no-op for that Run even when `abortPendingRequest`/`finalizeForQuit` reach it through `resetAgent`. Cancellation still stops the same `ExecutionRuntime` Run; only the second terminal write is removed.

- **ESM objective edits survive concurrent coordinator writes, and orphaned runs no longer block controls.** All ESM objective read-modify-write paths now run in `BEGIN IMMEDIATE` transactions, so a worker-progress write can no longer restore the objective text it read before a user edit committed. Pause/resume/clear also tolerate a canonical Run that has no live lease and is waiting for recovery, so an interrupted local admission can no longer leave an objective permanently uncontrollable. Terminal controls additionally report unsupported platforms as `501 terminal_unsupported` instead of `terminal_disabled`, and the Unix PTY build tag now matches the supported platform set so `aix` and other unsupported targets compile to the explicit `ErrUnsupported` implementation.

- **Interactive terminal lifecycle is race-free, follows focus, and always shows its safety boundary.** PTY read/wait loops now receive their handle at creation and the finish path clears the terminal handle under lock, eliminating both the data race and a nil-handle window that could panic when a short-lived shell exited during startup; listing/attaching a terminal reads its geometry through the locked `Size()` accessor instead of unsynchronized fields. Switching the focused workbench session now releases the old session's shell and creates one for the new cwd instead of leaving a stale terminal bound to the previous session, and a lost terminal id (for example after a serve restart) stops retrying and lets Reconnect create a fresh shell. The terminal status bar now continuously states that the shell is outside the sandbox and inherits the serve process user/environment, and surfaces the placeholder-auth-token warning reported by `/api/status`; the browser smoke test asserts the notices and the focus rebind. Closing a live shell now waits for the process to exit and only escalates to SIGKILL after the grace period instead of always sleeping two seconds, cookie-authenticated browsers no longer receive a long-lived terminal token, a rejected config update no longer applies terminal limits or kills shells before it rolls back, and the Windows ConPTY wrapper now closes handles exactly once and assigns the shell to a kill-on-close Job Object so background descendants cannot outlive the terminal.

- **Interactive terminal recovery, focus, and warnings are now complete.** The terminal dock always discloses that it shares the focused session's cwd with a possibly running Agent, and escalates the warning when the canonical execution snapshot is running locally or in another process. A page reload reattaches the detached shell recorded for that tab instead of leaking it and creating a second terminal, while an exited or lost terminal lets Reconnect create a fresh one. xterm's stylesheet is loaded, `@xterm/xterm`/`@xterm/addon-fit` are pinned exactly, and the PTY read loop waits for `cmd.Wait` before publishing an exit frame so a non-zero exit code is not reported as 0. Workbench tests also gained a 1000-operation property test, which fixed draft trajectory-mode persistence, focus repair after group removal/preset changes, exact split-weight clamping, paginated session-tab reconciliation, duplicate command-suggestion DOM ids, and mobile context-menu targeting.

- **A Draft created outside `/chat` survives the workbench remount.** Workbench hydration is now a one-shot startup step instead of re-reading `localStorage` whenever the lazily loaded Chat view mounts. A new Draft created from Sidebar/Sessions before the 300 ms persistence debounce fired could previously be replaced by the older stored layout; the in-memory workbench is now authoritative once the app has started, while a newly opened page still inherits the shared last layout. Browser and unit regression tests cover the remount and delayed-hydration paths.

- **Session content writes now have one authority, and split stores are repairable without data loss.** Every transcript write — messages, tool results, mode/thinking/title changes, and conversation turn boundaries — now resolves the persisted `sessions.content_store` instead of trusting this handle's in-memory mode, so a process that opened a session before another process migrated it adopts the committed event log instead of writing into the retired SQLite transcript or raising a false `session was modified by another process`. Opening a session is read-only: it no longer retires legacy payload rows, flips the store, or resets the log; legacy duplicate rows are removed only by a fenced, coverage-checked retire under a content lease, after a post-flip grace window. Rows a legacy build appends after the flip are detected as a split store and preserved. `mothx doctor` reports split sessions and, separately, sessions whose event-store turn boundaries address no matching turn marker (content lost before the event log owned it: those turns still read but cannot be forked, and `doctor` says so instead of reporting a clean store). `mothx doctor --repair-session-content [all|SESSION_ID]` adopts the uncovered delta, translates turn boundaries, and then retires the covered duplicate idempotently; `--json` reports per-session results. Architecture guards now reject a second content-store router, an open that reaches a store mutation, and any write branch on the in-memory mode. **Upgrade every MothX binary together and restart every running process (TUI, serve, and Desktop's bundled `mothx acp`) before repairing.** A mixed-build window cannot be prevented from the new build, but it no longer loses content: the new build keeps both stores until the repair entry adopts the difference.

## v1.3.107

### ✨ New Features

- **源盾 (Yuandun) is now the default SkillHub marketplace.** MothX adds a native 源盾 client for search, detail, files, security audit, and downloads, registers it ahead of SkillHub.cn and ClawHub.ai, and migrates the legacy `skillhub.cn` default. The market is projected through ACP, Serve, the TUI, the Web UI, and Desktop, which also gain a refreshed marketplace layout and a right-side detail drawer. Downloads identify MothX with `X-Client-Source: MothX`, and archives carrying `X-Skill-SHA256` are verified before extraction. Suspected (not confirmed) security findings use an amber warning tone so they stay distinct from risky results.

- **`mothx maintenance` inspects and compacts the session database.** `status` reports transcript/tool-record counts, database size, and reclaimable free pages; `vacuum` runs SQLite VACUUM and reports the result, with `--dry-run` to preview. The command never deletes messages or prunes tool-execution records; the scheduled maintenance job remains the only path that can bound terminal tool records and backfill the search index.

- **New Gitee/Moark Models: `kimi-k3.1-pro` and `kimi-k3.1-pro-highspeed`**
  - Added `kimi-k3.1-pro` and `kimi-k3.1-pro-highspeed` to the `gitee` and `moark` providers: thinking is enabled by default with Kimi's `low`/`high`/`max` effort scale (MothX's `minimal`/`low` map to `low`, `medium`/`high` to `high`, and `xhigh`/`max` to `max`), a 1M context window, and text+image input. Both use the verified `reasoning_effort` parameter through the `kimi` thinking format.

- **New Gitee/Moark Model: `MiniMax-M3.1-Flash`**
  - Added `MiniMax-M3.1-Flash` to the `gitee` and `moark` providers: thinking is enabled by default through the standard `reasoning_effort` parameter, with a 1M context window and text+image+video input; no default max_tokens is sent.

### 💥 Behavior Changes

- **Gitee/Moark model lists are reordered for discoverability.** The `gitee` and `moark` presets now lead with `deepseek-v4.1-flash-1017` and `deepseek-v4.1-flash`, followed by `qwen3.8-flash`, `qwen3.8-max`, `glm-5.3-flash`, `glm-5.3`, `MiniMax-M3.1-Flash`, `step-3.7-flash`, and `auto`; the remaining models follow in natural alphabetical order. Because preset order is also the fallback when no default model is configured, an unconfigured Gitee/Moark session now defaults to `deepseek-v4.1-flash-1017`.

- **The Serve session list is bounded by default.** `/api/sessions` without `limit` now returns the first 100 sessions plus `total`, `limit`, `offset`, and `hasMore`; pass `limit`/`offset` to page through history. `scope=active` and `/api/sessions/active` project only the in-memory session pool instead of loading all history, and per-session MCP configuration resolves its working directory by ID.

- **Session storage maintenance is scheduled without deleting transcript messages.** MothX now projects a daily `mothx-maintenance:session-storage` job that preserves every `entries`/`sub_entries` transcript row forever. It may prune only completed/abandoned `tool_execution_records` older than `maintenance.toolExecutionRetentionDays` (default `0`, keep forever), always keeps running/interrupted/retry-requested records so uncertain tool side effects stay fenced, runs `PRAGMA optimize`, and optionally runs `VACUUM` when `maintenance.vacuumSessionStorage` is enabled.

- **SQLite startup integrity checks are now explicitly opt-out.** MothX keeps running `PRAGMA quick_check` by default before using the session database. Very large databases can skip the fixed opening cost with `MOTHX_SQLITE_QUICK_CHECK=off`; `mothx doctor` still runs an on-demand read-only integrity check and reports `sessions.integrity`.

- **Non-hosted web search now uses DeepSeek Search/Fetch.** The old `webSearch` provider/type/model configuration that registered a provider-backed search tool was replaced by local `web_search` and `web_fetch` tools backed by DeepSeek's official `POST /v1/tools/search` and `POST /v1/tools/fetch` endpoints. Provider-native hosted search for OpenAI Responses is unchanged, and Anthropic Messages uses its native hosted search while `webSearch` is enabled; both take precedence over the local `web_search` function. `webSearch` now configures `provider`, `baseUrl`, and `token` (with the provider API key as fallback); both tools are read-only and available in plan mode.

- **Tencent Yuanbao search backend added.** `webSearch.backend` selects `deepseek` (official Search/Fetch APIs) or `yuanbao` (Tencent Yuanbao SearchPro at `POST /SearchPro`). The Yuanbao backend sends `{"Query": ...}`, normalizes the returned `Pages` into title/URL/site/date/score/passage results, authenticates with `webSearch.token` or `${TENCENTCLOUD_WSA_APIKEY}`, and currently provides search only, so `web_fetch` remains available only with the DeepSeek backend.

### ⚡ Performance

- **Opening and listing sessions no longer rescans the whole store.** A current database reads its migration ledger once and opens without a write transaction or writer lock; EventStore inspection is reused per open; execution facts, list metadata, and message counts are batched; cascade, export, and stats projections stop opening every session; and search uses one read-only scan that preserves compaction and content-override semantics.

- **User background mode lowers large-area backdrop blur.** When a user background image is active, the app surface veil, control/titlebar surfaces, composer, and home quick cards use smaller blur radii, reducing continuous GPU compositing cost while keeping the semi-transparent surfaces readable.

- **Repeated searches reuse unchanged EventStore projections.** A fingerprint-keyed, byte-bounded cache avoids replaying the same EventStore session on every search; an append or segment rotation invalidates it.

- **Repeated session searches reuse the completed page.** A query/page cache sits in front of the candidate scan, so a repeated Desktop/WebUI history query performs no list query and no content replay. Cache entries are keyed by the durable store-wide write version, which SQLite triggers bump on session, legacy payload, EventStore projection, and project-membership writes; an append, title/binding/cwd change, delete, or write from another process invalidates the page instead of serving stale results.

- **Session list rows no longer scan the EventStore at startup.** First-user preview, latest title, and binding metadata are persisted in a small SQLite display projection, written with each committed batch, copied on fork, rebuilt with the event projection, and backfilled by maintenance. List and bindings reads use the row when present and fall back to the canonical EventStore scan when it is missing.

- **Desktop settings panels no longer re-render on every background chunk.** All 16 settings panels now select only the connection/store fields they display instead of subscribing to the whole app state.

- **Session content search now narrows work through a derived FTS5 index.** Searches ask a trigram full-text index for candidate sessions before replaying anything; the canonical replay still decides the final match, so compaction-discarded content and content overrides keep their exact semantics. The index is written in the same transaction as each append, rebuilt with the event projection, copied on fork, and backfilled when a pre-index session is attached. Short queries, index errors, and not-yet-indexed sessions fall back to the previous full scan, and search itself remains read-only. The daily session-storage maintenance pass also backfills up to 512 unindexed sessions, newest first, so existing history becomes searchable without opening every session.

- **Desktop streaming and long-list scrolling no longer re-render the whole shell.** Renderer state notifications are coalesced into one commit per frame, transcript items are replaced immutably so unchanged Markdown/tool cards skip rendering, the sidebar/status bar/composer/plan panel subscribe only to the state slices they display, offscreen transcript blocks can skip layout/paint, and chat auto-scroll is coalesced with the commit that paints the chunk.

- **The initial Desktop task list no longer scans every session sequentially.** ACP list rows now use a structural-only EventStore projection that decodes just the first user preview and latest title/bindings, and the page prefetches those projections with a bounded worker pool. Canonical session open still verifies every batch digest and fails closed.

- **Electron no longer forces software rendering on every packaged Linux desktop.** GPU compositing is kept when `DISPLAY`/`WAYLAND_DISPLAY` exists (with an explicit `MOTHX_DESKTOP_DISABLE_GPU` escape hatch), and the `/dev/shm` fallback is applied only when that mount is missing, unwritable, or smaller than 128 MB. ACP events are also coalesced into one IPC delivery per frame, and live diagnostic logs cross IPC only while the log viewer is open.

- **Desktop no longer starts transition/animation storms on hover, theme changes, or scroll reveals.** Tailwind `duration-*` no longer accompanies `animate-in` (which made every hovered sidebar row transition all inherited properties), transcript cards no longer replay entrance animations when `content-visibility` reveals them during scrolling, the sidebar scrollbar keeps a constant 8 px width, and theme switches temporarily suppress transitions on inherited colors.

- **Long-lived Desktop windows stay bounded.** The live transcript renders a 300-item tail window (expandable locally), status/retry/compaction notices update in place instead of accumulating, session/search/subagent/run-status caches are capped, progress polling cannot overlap, transcript lookup uses an index instead of scanning every chunk, oversized tool output is capped in the display copy, and `desktop.log` rotates at 8 MB between launches.

### 🐛 Bug Fixes

- **Stuck detection no longer stops reasoning-only progress, and the terminal error keeps its reason.** Turns that produce reasoning output now count as progress, so a reasoning model that keeps calling tools without user-facing text is no longer treated as stuck; the silent-turn guard still stops a loop with neither text nor reasoning. `ErrAgentStuck` now carries the silent-turn count and is projected through the Run result and error event, so Runtime `ErrorInfo` and every adapter can report why the loop guard stopped.

- **A partially applied session-list migration now converges.** Some databases recorded schema version 49 before the Run index was added to that migration body, so `idx_session_runs_session_status_started` stayed missing forever: recorded versions are skipped, not re-inspected. Version 50 re-asserts the index with `CREATE INDEX IF NOT EXISTS`, converging those databases on the next start while leaving fresh ones unchanged.

- **Stopping a Responses background task during attachment now stays cancelled.** Concurrent WAL reads can let a stop mark the Run cancelling before the background coordinator attaches its Agent. That path previously fell through to the default `failed` terminal status and could orphan the provider-side task. It now preserves `cancelled` and explicitly cancels the remote Responses task.

## v1.3.106

### 🐛 Bug Fixes

- **Desktop chat and home backgrounds no longer render the canvas dot mesh.** The decorative dot overlay was removed so background images and surface treatments stay clean on both views.

## v1.3.105

### 🐛 Bug Fixes

- **Desktop hides the window-style switch and aligns platform defaults.** macOS hosts now resolve to the macOS frame and Windows/Linux hosts to the Windows 11 frame before `desktop-store.json` loads, and the manual switch is hidden behind a feature flag while its implementation is retained for later reuse.

## v1.3.105-pre-7

### 🐛 Bug Fixes

- **Runs that stop on a tool-call turn now reach a terminal state.** When the assistant payload and tool results were already committed, the terminal turn-end was re-parented under an earlier entry and rejected by the leaf fence, leaving the Run terminalizing and its execution lease unreleased. The turn-end now anchors at the manager's current leaf, and the TUI maps incomplete tasks to the canonical `RunStateIncomplete` state.

## v1.3.105-pre-6

### ✨ New Features

- **Desktop shows and inspects sub-agents.** The chat header now reports how many sub-agents the session has and whether they are running; opening it shows a read-only panel listing every child with its status and renders one child's transcript with the ordinary chat message, tool-card, and reasoning styles. ACP adds the read-only `mothx/subagent/list` and `mothx/subagent/messages` projections plus the `subagentPanel` capability key, so Desktop no longer relies on isolated started/terminal cards.

### 🐛 Bug Fixes

- **Stop handling now projects one Runtime decision across TUI and ACP, with race and recovery fixes.** ACP `session/cancel` snapshots the Run ID under `cancelMu` instead of racing the prompt handler, and the shared stop projection is bounded so it cannot stall the JSON-RPC read loop. TUI abort/reset moves the canonical stop and terminal write off the Bubble Tea update loop (quit waits for completion), so the UI no longer freezes; a canonical Run terminalized by another owner is adopted locally even when the terminal state differs, with the full terminal broadcast, instead of leaving the session permanently busy. A stopped recovered Responses background task now terminalizes as `cancelled` rather than `failed`.

## v1.3.105-pre-5

### 💥 Behavior Changes

- **The embedded Windows BusyBox now requires Windows 10 or later.** `busybox-windows-x86.exe` and `busybox-windows-x86_64.exe` are rebuilt from the fork's UTF-8 configs (`mingw64u_defconfig` for x86_64, `mingw32w_defconfig` for x86) and carry a UTF-8 application manifest (`activeCodePage=UTF-8`) together with `FEATURE_UTF8_INPUT`, `FEATURE_UTF8_CONSOLE`, `FEATURE_UTF8_AUTODETECT`, `FEATURE_UTF8_CHILD_ENV` and `UNICODE_SUPPORT`. Non-ASCII `sh -c` command text now reaches argv as UTF-8 instead of being down-converted to the system ANSI code page (GBK on zh-CN Windows), and the child environment keeps the UTF-8 baseline. The build sets `FEATURE_FAIL_IF_UTF8_MANIFEST_UNSUPPORTED=y`, so on Windows 7/8 BusyBox refuses to start; the `bash` tool then falls back to PowerShell exactly as it does whenever BusyBox is unavailable, so commands keep working (without the UTF-8 baseline). MothX continues to document Windows 10/11 as its supported Windows floor.

### 🐛 Bug Fixes

- **Captured Windows output is normalized at the capture boundary.** Child processes choose their pipe encoding independently — Python, Java, the C runtime and shell builtins often use the ANSI code page (GBK on zh-CN Windows) while Go, Rust, Node.js and most CLIs write UTF-8, and a single command can mix both. Rather than injecting a per-runtime environment variable, the `bash` tool now normalizes captured stdout/stderr through `platform.DecodeProcessOutput`: bytes that are not valid UTF-8 are decoded with the active code page, valid UTF-8 is trusted, and mixed output is resolved per maximal non-ASCII run. `MOTHX_WIN_OUTPUT_ENCODING=utf-8` forces UTF-8, and a numeric value such as `936` forces that code page.

- **Genuine UTF-8 text is no longer re-read as GBK.** The two encodings overlap on two-byte sequences, and the previous whole-block heuristic could decide once for an entire capture, re-decoding real UTF-8 text into unrelated Han characters (`Привет` → `袩褉懈胁械褌`, and a mixed line into `涓枃`). Ambiguity is now resolved per non-ASCII run and only when the stream carries no stronger UTF-8 signal: a stream whose UTF-8 reading contains CJK characters or any 3- or 4-byte sequence is never second-guessed, and only short runs of two-byte pairs are eligible. Byte-identical legacy fragments (for example a lone GBK `写`) still decode as before.

- **The extracted Windows BusyBox is refreshed when the embedded asset changes.** A previously extracted copy is compared with the embedded asset by SHA-256 and replaced atomically when they differ, so an upgraded MothX never keeps running an old shell. If a running BusyBox holds the executable image locked, the old copy is kept for that run and the refresh is retried on the next startup.

## v1.3.105-pre-1

### ✨ New Features

- **New Gitee/Moark Model: `deepseek-v4.1-flash-1017`**
  - Added `deepseek-v4.1-flash-1017` to the `gitee` and `moark` providers, directly after `deepseek-v4.1-flash` and with identical parameters: a 1M context window, reasoning support, and text+image input; no default max_tokens is sent.

- **New MiniMax Model: `MiniMax-M3.1-Flash`**
  - Added `MiniMax-M3.1-Flash` to the `minimax` provider: reasoning support with thinking intensity via the Anthropic-compatible `output_config.effort` scale (adaptive thinking format; `minimal` and `low` map to `low`, the rest map one-to-one to `medium`/`high`/`xhigh`/`max`), a 1M context window, and text+image+video input. The preset declares a 1M output ceiling (the full context window), while requests still use MothX's normal output-token default unless you raise it explicitly.

- **Volcengine Retired Models Removed.** Volcengine has taken `kimi-k2.7-code`, `doubao-seed-2.1-turbo`, and `minimax-m3` offline, so the `volcengine`, `volcengine-agentplan`, and `volcengine-codingplan` presets no longer list them (including the standard channel's `doubao-seed-2-1-turbo-260628` snapshot). The same IDs remain available on other providers such as Gitee/Moark. Because preset order is also the fallback when no default model is configured, an unconfigured standard `volcengine` session now defaults to `doubao-seed-evolving` instead of the retired snapshot.

- **DeepSeek V4.1 Thinking Intensity.** DeepSeek V4.1 models in the Gitee/Moark and Volcengine presets now use the verified `reasoning_effort` parameter instead of only a thinking switch. MothX's `minimal`, `low`, `medium`, `high`, `xhigh`, and `max` levels map one-to-one to the gateway scale, while `off` sends `none` to disable these gateways' think-by-default behavior. Gitee/Moark and Volcengine Agent Plan were validated live across the complete accepted enum. All DeepSeek V4.1 model IDs default to this format, including third-party gateways; a deployment that only accepts the older thinking switch can opt out with `thinkingFormat: "thinking-only"`.

- **Unsupported `reasoning_effort` falls back automatically.** If an OpenAI-compatible endpoint rejects `reasoning_effort`, MothX retries immediately without the field (keeping the DeepSeek V4.1 thinking switch), shows the reason in the retry notice, and records `thinkingFormat: "thinking-only"` plus `supportsReasoningEffort: false` for that model so later runs omit it. The fallback does not consume a retry attempt.

- **Sessions reject unusable working directories early.** `internal/session` is the single owner of working-directory validation, with the Runtime API delegating to it. Session creation, reopening, rebinding, ACP `mothx/session/setWorkDir`, and channel session resolution now require an existing absolute directory before persisting or assembling sandbox and tool resources. An ACP same-directory request no longer detaches a usable runtime when its directory has disappeared, and a channel run validates the bound session's persisted cwd rather than the platform default.
- **Desktop uses an explicit draft-directory model.** The legacy workspace-default fallback and settings panel were removed. Quick-start drafts receive one process-local `mkdtemp` scratch directory, while a New Task draft remains unset until its native picker or worktree action supplies a directory. Picker history is only a convenience for the next dialog; draft state carries a generation so a stale quick-start, picker, or ACP completion cannot overwrite a newer New Task.
- **Runtime coordinates local session submissions.** `SessionRuntime` owns one `(database identity, session ID)` FIFO `SubmissionCoordinator`, and `ExecutionRuntime.Completion` is the authoritative completion barrier. TUI queued input, ACP prompt admission, Channel/Cron/ESM/Knowledge admission handoffs, shutdown, cancellation, and structured local/external busy classification now share that lifecycle instead of polling lease errors or starting a successor from an Agent finish event.

### 🐛 Bug Fixes

- **Session transcript storage now has an EventStore migration path.** Runtime-bound sessions can keep canonical message, tool, compaction, turn, and terminal payloads in a session-scoped append-only EventStore while SQLite retains fenced Run/lease/decision/turn control state and rebuildable metadata projections. The path includes intent reconciliation, bounded/fsynced batches, EventStore paging/fork/recovery support, and fail-closed corruption handling; legacy sessions remain readable through the named compatibility bridge. Reading the store is kept strictly separate from repairing it: only the lease-holding append path may truncate an incomplete tail or materialise the rebuildable manifest, while observation (`EventStore.Inspect`, and therefore session load, reconciliation, and every adapter read) classifies corruption identically but never writes to the directory — so opening a session can no longer mutate its stored bytes, race a concurrent owner's fsync, or leave directories behind on teardown.

- **Migrated sessions keep their turn boundaries addressable.** Legacy `entries.seq` is a database-global AUTOINCREMENT that interleaves every session sharing `sessions.db`, so it can numerically land inside another store's range and prove nothing about where a row lives. Migration now rebuilds transcript order from the persisted parent chain and translates each `conversation_turns` interval into EventStore positions inside the same fenced commit transaction, so fork resolution and open-turn recovery still point at real markers. Projection `turn_id`/`run_id` are derived from the decoded marker payload instead of the batch envelope (migration exports markers with an empty envelope, which previously left every migrated marker without turn identity and silently broke the COALESCE fallback in turn state reads and `ListOpenTurns`). Reconciliation is no longer a side effect of binding a session: it moved into the shared load path as `ConvergeEventStore`, so every entry point that merely opens a session — serve/chat, the background run coordinator, channels, ESM, ACP and the TUI resume path — now retires a leftover legacy payload duplicate and heals control rows on its own instead of replaying a transcript the EventStore already owns. `MigrateToEventStore` split accordingly into convergence plus the one irreversible export step (`exportLegacyTranscript`), and `Manager.Reload()` reloads through the locked body so adopting another path's flip cannot self-deadlock on the non-reentrant manager mutex. Sessions flipped by an earlier build therefore heal on their next open rather than their next bind, and an entry type the store cannot replay (`custom`/`custom_message`) fails the export closed rather than dropping it from the transcript.

- **Server shutdown no longer races a run it promised to drain.** A background run used to be admitted durably and only then handed to a goroutine, so a `Shutdown` landing between those two steps left an active Run that nothing drained while the process was already closing its session databases. `SessionPool` now separates reserving a drain slot from starting work: `ReserveBackground` claims the slot before the durable admit and `LaunchBackground` moves that ownership onto the executor goroutine, so the slot is held continuously from admission until the executor returns, and `Shutdown` waits for the caller either to launch or to give it back. The release is split in two layers — `runtimeRelease` (runtime pin plus concurrency slot) and `handOffRelease` (the drain hand-off) — and each executor registers `handOffRelease` first, making it the outermost defer so the artifact collector close, run-context cancel, fallback terminal write and `FinalizeRun` all finish inside the drain. Orphaned Responses runs recovered by reattach follow the same barrier. `LaunchBackground` deliberately does not derive a cancellable context from the stop signal the way `GoCtx` does: a durable Run owns a fenced execution lease and must reach its own terminal transition, so cancelling here would orphan it instead. `Shutdown`'s drain wait is now bounded by the caller's context and reports `ctx.Err()` rather than blocking forever, because a task that never returns (an agent awaiting an approval nobody will answer, a provider stream ignoring its context) is an availability problem, not a reason to make the process unkillable; ownership still lives in the fenced lease, so returning early never terminalizes a live run. The ordering invariant cannot be expressed in types and cannot be pinned end-to-end — an approval-blocking fixture provably never reaches the executor's deferred tail, while a fast-terminalizing fixture makes the assertion vacuous — so `internal/architecture/drain_release_guard_test.go` holds it statically, walking every `LaunchBackground` site through its wrapper-to-executor delegation chain and checking that the drain parameter sits at the position derived from the callee's own signature and that the executor defers it first; four mutations confirm the guard is not vacuous.

- **Corrupted session databases now show recovery guidance.** The TUI no longer dumps SQLite's full b-tree error as an unexplained session-creation failure. It identifies the database, confirms that it was left untouched, and points to the archival `mothx pure --force` recovery path after other processes have been stopped.

- **Rotating a bound channel session preserves its durable directory.** Rotation inherits the existing session's persisted cwd instead of falling back to the platform default, and its fenced compare-and-set compares canonical paths so an equivalent stored form such as a trailing separator still succeeds while a real concurrent change is rejected.
- **Feishu tool-image cleanup is concurrency-safe.** Each delivery materializes images beneath a unique private temporary directory and removes the whole directory on every exit path, preventing parallel runs from collecting one another's files and leaving no image bytes behind in the work directory.
- **Session EventStore migration has one unified entry point.** Migrating an old session to the EventStore used to happen only from `SessionRuntime.BindSession`, so entry points that assemble sessions directly — ACP/Desktop, channels, ESM, and background runs — left old sessions on the legacy SQLite transcript and kept new sessions on the `sqlite` content store. `BindSession`, `AttachSessionResources`, and `Builder.Build` now call the same migration entry point, `Manager.MigrateToEventStore`, with no per-site wrapper or special handling: an existing session is exported to the session-scoped EventStore and a new one is flipped to it regardless of which adapter opened it, with no divergence in content ownership. The entry is now safe to call unconditionally — while another owner is running the session it is a successful no-op instead of an attach-blocking error, the self-consistent legacy store keeps serving, and a later idle attach completes the migration; only corrupt or unreplayable legacy data fails closed.
- **Stopping a session no longer fails while its run is terminalizing.** A terminal write that failed after the durable Run entered the committed `terminalizing` window left its row in a state only a terminal transition may advance, yet the Web UI stop path still tried to force `terminalizing` -> `cancelling`, which the run store rejects — so the request returned `persist run cancellation: invalid session run transition "terminalizing" -> "cancelling"` and the run looked permanently uncancellable. `ExecutionRuntime.CancelDurable` and the shutdown cancel path now detect a prepared/terminalizing terminal transaction, skip the illegal cancelling write, accept the cancellation (still cancelling the loop), and restart the prepared terminal write when its retry had stopped, so an interrupted run can still reach a terminal state.
- **Appending to a session's EventStore is no longer quadratic in transcript size.** EventStore appends used to re-read the whole log several times per batch — a health inspection, an idempotency scan, a next-sequence scan, and a commit-time validity scan — so append cost grew with the session's accumulated content (512 entries: 3.8 ms → 178 ms per batch, 5.7 s cumulative) while the legacy SQLite path stayed flat. The health gate now trusts the process-local append-state cache whenever it is fresh for the current physical revision and checks only that every SQLite intent is committed; `NextSequence` reads the cached cursor; the idempotency probe uses the projection index and reads the full committed transcript only on a real retry; and `CommitEventIntent` accepts the just-fsynced batch instead of rescanning. Appends are now constant-time in transcript size (same probe: ~3 ms per batch, 0.30 s cumulative, about 19x faster), with the intent/lease protocol, fencing, and recovery verification unchanged. A deterministic regression test pins that appending to a warm session performs no whole-log scans.
- **Opening a brand-new Web UI session no longer reports `session_not_found`.** A server-allocated Web UI session is persisted only when its first run starts, but the run-event, capability-event, and sub-agent lookups rejected that still-unpersisted id, so the Web UI surfaced `session_not_found` while creating a session. Those three lookups now project an empty result for an allocated id — matching the trajectory, capabilities, runtime, and message lookups — while an arbitrary unknown id is still rejected.
- **EventStore migration is bounded and self-healing.** The one-time export of an old session's transcript is now written in batches of 64 entries instead of a single unbounded batch, so one fsync and one SQLite projection transaction stay bounded no matter how large the transcript is. The export also no longer wedges on stale or interrupted state: because the content store stays SQLite until the flip, any EventStore bytes or intents a previous interrupted attempt left behind are discarded and the transcript is re-exported, instead of refusing the migration and failing the attach.

## v1.3.104

### ✨ New Features

- **StepFun Step 5 Preview model.** The StepFun provider catalog now includes `step-5-preview`.
- **Feishu delivers tool-generated images.** Supported PNG, JPEG, GIF, and WebP images produced during a Feishu-bound run are materialized through the Runtime artifact pipeline and sent as image messages alongside the textual response.

### 🐛 Bug Fixes

- **ACP conversations retain their session history.** ACP builds a fresh Agent for each prompt but previously omitted the shared replay-seeding step, so every follow-up message was processed as a new conversation. Prompt handling now reloads the session manager and loads its canonical replay state into the newly built Agent while preserving the Runtime-owned current user entry, avoiding both amnesia and duplicate transcript rows. Regression coverage exercises two real stdio ACP prompts and both serve chat and WebUI run-submission paths.
- **A live session owner can survive transient database stalls.** Recovery defers takeover when the synchronized lease bus reports a fresh announcement from another live owner, even if its SQLite lease row has expired; a same-process lease that is still live but could not renew is reported as busy instead of being reclaimed. Database unavailability or wall-clock expiry alone therefore remains an availability problem, not evidence of ownership loss. Fenced CAS takeover and explicit release remain the only ways to displace a live owner.
- **Long-running provider turns keep their retry budget.** Stream transport and timeout recovery counters reset after a successful turn. Independent transient failures no longer accumulate across an entire run and exhaust continuation budget, while the per-turn cap still bounds growth from a repeatedly stuck turn.
- **An ACP cancel in the final registration window takes effect.** After the Run becomes registered but before its cancellation handle is installed, the admission context is rechecked so a narrowly timed cancel terminates the prompt instead of starting a Run the client already abandoned.
- **New WebUI sessions open without a false not-found error.** A server-allocated deferred session ID that has not yet been persisted by its first run now projects default capabilities and an empty trajectory from `/api/sessions/{id}/runtime`, `/capabilities`, and `/trajectory`. Unknown, mistyped, and deleted IDs still return 404 rather than masquerading as a blank new session.

## v1.3.103

### 💥 Breaking Changes

- **Inbound webhook support removed.** The serve inbound webhook feature (`channels.webhooks` configuration, `/webhook/*` routing, and its agent-task handler) has been removed entirely; webhook events are no longer accepted, and a `webhooks` section in existing configuration files is ignored. Use the OpenAI-compatible API or the WeChat/Feishu messaging channels instead.

### ✨ New Features

- **Cross-process session ownership is now synchronized across local processes over the lease bus**
  - The loopback UDP `SessionLeaseBus` no longer only wakes peers: notifications carry a canonical `DatabaseIdentity`, a per-origin `Seq`, and the owner PID/run, and every process keeps a global in-memory ownership view keyed by `(DatabaseIdentity, sessionId)`. Owners re-announce held leases every 10s (`ownership_snapshot`) so a lost acquire self-heals and an otherwise-silent owner stays fresh within a 30s liveness window. Receivers drop duplicate/out-of-order messages via `Seq`, mark an origin's entries uncertain on a sequence gap or an epoch conflict, and fall back to SQLite on any miss, staleness, or uncertainty — notifications never authorize admission or cancellation.
  - `agentruntime.InspectSessionExecution` now answers a fresh, remote execution lease from the synchronized cache (marked `source: "cache"`) and otherwise reads SQLite and refreshes the view; the snapshot projection is a single shared function so the two paths cannot diverge. `session.RuntimeLeaseBusMetrics()` exposes sent/send-failed/received/invalid/self-skipped/duplicate/applied/gap/uncertain counters. The wire version is 3 and the datagram limit 4096 bytes.

- **TUI queued messages are now visibly rendered while a run is active**
  - Submitting input while a run owns the session has always queued it for ordered delivery, but the queue was invisible: the input box cleared with zero feedback until the run finished. The live view now renders a styled "⏸ N queued" section below the spinner with a one-line preview per pending submission (at most 3 shown, overflow as "+N …"; multi-line input is flattened and truncated to the terminal width). The section disappears as the queue drains, and each prompt still renders its canonical "You:" transcript line when it actually starts — the indicator is pure managed-view state and never enters scrollback or session history.
  - The header is bilingual (zh/en) through the existing i18n catalog, and the new rendering is covered by focused unit tests (empty queue, counts/previews, visible cap, width bounding).

- **Cross-process session ownership is now visible in TUI and ACP before admission fails**
  - TUI and ACP previously only cancelled their own in-process runs; a session owned by another live process, an orphaned run left by a crashed owner, or a detached remote run stayed invisible until the next prompt admission rejected it. Both adapters now project the canonical Runtime snapshot (`agentruntime.InspectSessionExecution`) instead of growing local ownership state.
  - TUI: the sessions dialog and `/sessions` list render a compact ownership badge per session (running / running elsewhere / interrupted / remote / reserved / recovery failed), and activating a session prints one status line explaining a non-idle cross-process state (with the owner PID when known). A new bounded batch projector `agentruntime.InspectSessionExecutions` backs list/page views; unreadable sessions degrade to “unknown” instead of failing the listing.
  - ACP: the additive feature key `sessionExecutionState` advertises the new projection. `session/load` and `session/resume` responses carry an optional `execution` snapshot when the session is not idle, and `session/list`/`listAll` pages include `_meta.execution` for non-idle sessions only. Standard ACP semantics are unchanged; clients without the feature key can ignore the fields. Desktop-side consumption of the key is a follow-up.

- **Knowledge Base Usability Completion**
  - **Ignore rules and discovery diagnostics.** A knowledge base now accepts an `ignoreGlobs` list, merged with the fixed ignore directories and the suggested patterns read from the source root's `.gitignore`/`.mothxignore` (read-only). Every scan records a bounded discovery projection (`discovered`/`ignored`/`skipped` with per-path reasons) on the snapshot, so a file that is never indexed is explained instead of silently dropped. Files that are oversized, binary/non-UTF-8, or unreadable are marked `skipped` with a reason and are not handed to the model.
  - **Incremental diff summary.** Each rebuilt snapshot persists an `added`/`modified`/`removed`/`unchanged` projection with bounded path samples; a fully unchanged scan keeps the existing snapshot-reuse event and now carries the all-zero diff in its event data.
  - **Richer graph and query.** `knowledge_nodes` gained a `fact`/`candidate` status with `confidence`, a new `knowledge_entity_aliases` table merges a file node's basename with its path label, and Markdown links produce deterministic, locally verified `references` edges while a code file's conventional test file is linked with a deterministic `tested_by` edge and its import statements produce deterministic `imports` edges to module nodes, and a code symbol declaration is a `declares` edge rather than a generic `contains`, while a code file that references a present config file gets a deterministic `configured_by` edge, and a symbol that invokes another symbol declared in the same file gets a deterministic `calls` edge, while a document definition or an RFC 2119 requirement produces a deterministic `defines`/`requires` edge, and a document that states it supersedes another present document gets a deterministic `supersedes` edge. Queries now traverse up to two bounded hops (≤64 nodes, ≤96 edges), rank by relation weight, evidence count, and query hit, drop evidence-free candidates, and return structured `uncertainties` plus a `truncated` flag. The Indexer Agent may additionally propose candidate entities: a label that literally occurs in a cited chunk is stored as a grounded `candidate` node (never a fact), while an ungrounded one is stored evidence-free and hidden from default results. The Knowledge MCP `search_knowledge_base` result adds `relationType`/`confidence` per excerpt and projects `uncertainties`/`truncated`.
  - **Management surface.** New additive ACP methods and HTTP endpoints expose canonical index Run history (`runs/list`, `runs/get`), file-level source browsing (`sources/list`, no contents, with per-file chunk counts), index clearing (`clear`, keeps configuration and the source directory), and scheduled-state projection (`schedule`, reusing the shared Cron store for next-run, last result, and pause/resume). New capability keys `knowledgeRuns` and `knowledgeSources` gate the Desktop panels. Scheduled reindex plans are invalidated when a base's root directory is unavailable.
  - **Stable index error code.** An index pass that cannot build the configured Indexer provider/model now fails with a stable `knowledge_base_model_unavailable` code recorded on the canonical Run's structured error info and projected as `errorCode` in the run history; the ACP/HTTP management surfaces map the same code instead of a generic operation failure.
  - **Scan trigger coalescing.** A reindex trigger that arrives while a scan is already running is no longer dropped: it is coalesced into exactly one follow-up pass (the most recent trigger source wins) instead of starting a parallel scan or queueing one run per trigger. Time-window debounce is not implemented.
  - **Desktop and Web UI panels.** The Desktop knowledge panel and the Web UI knowledge view now surface index run history, source browsing, and a clear-index action, gated by the `knowledgeRuns`/`knowledgeSources` capability keys; the Web UI also exposes the schedule and ignore-glob fields.
  - **Cross-entry consistency.** The Web UI no longer forces `schedule=manual` or `thinkingLevel=none`: it reflects the persisted cadence, preserves an existing Desktop schedule on save, and sends ignore globs. An architecture guard pins the remaining legacy knowledge-context bridge (`KnowledgeCapsule`/`WithKnowledgeContext`/`knowledgeBaseRefs`) to the Runtime owner and the single ACP caller, with a documented removal condition.
  - **Quality baseline.** A controlled benchmark (`make knowledge-benchmark`) indexes a deterministic fixture and enforces documented regression thresholds for index duration, MCP query p50/p95, tool-result size, citation coverage, uncertainty coverage, and token estimate.
  - Knowledge-store schema version advances to 4; existing snapshots stay readable (added columns carry safe defaults) and are rebuilt on the next scan.

- **Context Guard Preserves Omitted Oversized Tool Outputs**
  - When a provider request would exceed the model input budget, the context guard no longer discards the oversized tool result for good: the full output is first saved to `<workDir>/.mothx/tmp/context-guard/` (private `0700`/`0600` permissions, the same staging convention as `.mothx/tmp/inputs`), and the guard tool-result message carries the file path with total line/byte counts, explicitly steering the model to page through the saved file with `read` offset/limit or search it with `grep` instead of re-running a possibly non-idempotent command (deploys, migrations, one-off scripts).
  - When the output cannot be saved (no working directory, write failure), the guard falls back to the previous omit-only wording. The staging area is pruned best-effort to the newest 50 files, and the guard status event now also surfaces the saved path.

- **Desktop Bundles the MothX Runtime and Supports Choosing the Runtime Binary**
  - **Every desktop package now ships a runnable `mothx` CLI.** The desktop release build vendors one source-built runtime per packaged architecture (macOS arm64 and x64, Windows/Linux x64) and injects the architecture-matching binary into `<resources>/app/vendor/mothx/bin/` after packing, before code signing seals the macOS bundle. Until now the macOS x64 package received the build host's arm64 runtime, so the Intel Mac client could not start its ACP runtime at all; the packaging step now verifies the bundled binary's ELF/Mach-O/PE architecture (including little-endian and fat Mach-O headers) and fails the build on a mismatch instead of shipping a broken client. Windows/Linux artifacts no longer carry a second copy of the runtime beside the app directory.
  - **Runtime binary setting.** The desktop settings (运行时 → MothX 运行时二进制) let the user switch between the bundled `mothx` executable (default) and a custom `mothx` binary path. Selection and validation live in the privileged Electron main process, the ACP runtime restarts on the switch, an unavailable custom path falls back to the bundled runtime with a visible notice, and a custom binary that fails to start rolls the selection back so the client stays usable. The `MOTHX_BINARY` environment variable remains the highest-priority development override.

### 🐛 Bug Fixes

- **Interactive TUI no longer freezes on slow MCP servers at startup**
  - Configured MCP servers were connected sequentially and strictly before the TUI came up: one unhealthy or slow server (for example an `npx` server downloading on first run, or an unreachable remote host) blocked first paint for up to its 15s handshake timeout, and any failure aborted the whole launch. `/reload` re-execs the process, so it paid the same cost again.
  - Connections now run concurrently, so a set of slow servers costs the slowest one rather than their sum, and the group can be bounded with an overall timeout that caps connection startup only: a deadline never tears down an already-connected server. The interactive TUI now defers MCP entirely: the runtime comes up immediately, the TUI connects configured servers in the background after the program starts, tolerates individual failures (surfaced as a warning instead of aborting), and rebuilds the next agent so its tool surface picks up the newly connected servers. Non-interactive `--print` keeps the strict, synchronous behavior.

- **ACP keeps cancel reachable while a session is loading and serializes a cascaded close against a child prompt**
  - Session-scoped ACP requests run on an async per-session lane, so a slow `session/new`/`load`/`fork` no longer head-of-line blocks the JSON-RPC read loop and `$/cancel_request`/`session/cancel` stay reachable. `session/prompt` now runs on that lane too; because it can block on execution admission (including the same-process draining wait) before the Run registers its cancel handle, its admission context is registered synchronously and is cancellable, so a cancel arriving before or during admission aborts the prompt instead of starting a Run the client already cancelled.
  - `session/close` now closes each cascaded descendant session on that session's own lane, so a concurrent prompt for a descendant cannot interleave with its shutdown. Note the response ordering: `session/prompt` is answered asynchronously, so a request issued immediately after a prompt (including `session/list`) is no longer guaranteed to observe the just-started Run — use the `run_status` event or retry.

- **Runtime lease bus listener no longer disables itself after a last-subscriber race**
  - When the final subscriber unsubscribed while the UDP listener was still binding, the listener returned before its deferred cleanup, leaving its `started`/`listening` state set and the closed socket cached, so the process silently stopped hearing cross-process ownership events until restart. The early return now resets the listener state so the next subscription rebinds.

- **Advisory UDP bus hardening: rebuild-notice scoping, receive-side coalescing, and a cheaper publish path**
  - The unauthenticated loopback lease bus accepted `database_rebuilt` notices for any path, so a forged or stale packet could make every peer process run a close/checkpoint attempt and surface a user-facing "database was replaced" warning for a file it never opened. The watcher now acts only on paths with a live cached connection in `internal/db` (new `IsCached` probe); genuinely rebuilt files are still retired exactly as before, and files this process never opened are ignored silently.
  - The wire validator no longer accepts the `renewed` type: heartbeat renewals were never published, and keeping the dead entry invited a future publisher to silently reintroduce one broadcast per session every heartbeat tick. A regression test pins both behaviors, and the Windows socket variant now documents that `SO_REUSEADDR` port hijacking can at worst degrade the advisory bus to durable SQLite polling.
  - Receive-side amplification is now bounded: serve and ACP wake handlers go through the shared `session.SessionWakeCoalescer`, which keeps at most one in-flight projection per session plus one trailing re-run (so bursts still converge on the latest durable state) instead of spawning one goroutine and one full DB re-read per datagram.
  - Publishing no longer dials a fresh UDP socket per message: one cached sender socket per broadcast address with a 200ms write deadline and a 5s dial backoff keeps lease release/run terminalization off the pathological latency path while preserving synchronous, exit-safe delivery and per-process ordering.

- **Session ownership mutation policy is now one shared path across ACP and serve**
  - Administrative mutations were forked: serve expert/capability patches reconciled orphaned runs through `agentruntime.AcquireSessionMutation`, while ACP (`withSessionMutationLease`, delete cascade) and serve session Delete/Bind/Unbind/Transfer called the raw `session.AcquireMutation(s)`. A session orphaned by a crashed owner (active run row, no live lease) therefore auto-recovered for one WebUI path but permanently failed with "session already has an active run" / `session_running` conflicts for ACP configuration changes and WebUI delete/bind/unbind/transfer.
  - These call sites now use the shared Runtime wrappers — including the new `agentruntime.AcquireSessionMutationUnlessHeld` (single owner for the "a live in-process lease is already the authority" skip, previously hand-written in both ACP and serve) and `AcquireSessionMutationGroup` (sorted, deadlock-safe multi-session acquisition with per-session orphan reconciliation) — so every entry point applies the same fenced takeover and recovery policy. The Responses-run admin paths in `responses_run_api.go` remain a documented bridge: a cancel/abandon must not trigger recovery of the very run it targets.
  - ACP prompt-admission and admin-mutation errors no longer collapse every cause into one opaque "session already has an active run"; the underlying reason (lease busy, recovery required, detached remote execution) is preserved in the wrapped error.
  - The architecture guard now rejects new adapter-level direct `session.AcquireMutation`/`AcquireMutations` calls outside the documented bridge, and regression tests cover unless-held acquisition, orphan-run recovery on delete, and group acquire/release semantics.

- **WebUI mode/capability patch no longer fails with "session runtime lease was lost" on sessions previously owned by another process**
  - Capability persistence (`SaveSessionCapabilities`) and its change events are lease-fenced writes. A session that was ever executed by another process — for example created and run in the TUI, which was then closed — keeps a released/expired `session_runtime_leases` row, so a later cold WebUI PATCH (`/api/sessions/{id}/capabilities`, `/api/sessions/{id}/runtime`) validated against a lease nobody held and always failed with `session runtime lease was lost`.
  - The idle capability-patch path now reclaims the session through the shared Runtime mutation lease (`agentruntime.AcquireSessionMutation`, the same fenced epoch-bump takeover the expert-binding patch already used), so patches succeed after a TUI/serve handoff while a live external owner still surfaces as contention. When the current process already holds the lease (an in-run patch), it remains the authority and no second acquisition is attempted.
  - Lease contention on these endpoints now maps to HTTP 409 instead of a 500, and a regression test covers patching a session whose lease was acquired and released by a previous owner.

- **ACP no longer becomes wholly unusable when the default provider lacks a key**
  - `mothx acp` used to treat an unusable default provider (missing API key, unknown provider, no usable model) as a fatal startup error: the process exited with the structured startup line, so initialize, sessions, and the entire management plane (`mothx/manage/*`) were unavailable — clients such as Desktop could not even reach the settings needed to configure a provider.
  - ACP now starts normally with a single stderr warning; management, settings, session history, skills, and knowledge bases stay available, and only execution entry points (`session/new`, `session/prompt`) return structured RPC errors carrying `code`/`fix` (for example `provider_unusable`: "default provider x has no API key"). Sessions bound to another usable provider keep working.
  - Management writes (`mothx/manage/providers/save`, `providers/delete`, and `settings/patch` touching `defaultProvider`/`defaultModel`/`providers`) now rebuild the provider catalog inside the running process, so configuring a key takes effect without restarting ACP.

- **Desktop home background no longer silently fails for large images**
  - The selected background used to be injected into the shell CSS variable `--app-user-image` as a base64 data URL, but Chromium silently drops CSS custom-property values larger than 2MiB: any wallpaper above ~1.5MB encoded past the limit and left `background-image` empty without any error, while the Home logo (rendered through `<img src>`) was unaffected — exactly the "logo works, background doesn't" symptom.
  - The renderer now converts the authorized data URL into a `blob:` object URL before injecting it into the CSS variable, keeping the injected value a short string regardless of image size, and revokes the previous object URL whenever the background is replaced or cleared. A regression test asserts the conversion and revocation path.

- **Context Compaction No Longer Fails with "max iterations (1) exceeded"**
  - Compaction summarizes the conversation through a child Agent built with `MaxIterations: 1` — exactly one LLM turn for the summary. Recovery retries inside the loop (empty-response retry, output-limit escalation and continuation, content rejection, context-overflow recovery, and Responses remote-state replay) each issued a fresh provider request without spending the logical iteration counter, so any single recovery consumed the only iteration and the whole compaction aborted with `generate summary: max iterations (1) exceeded`. Because a failed compaction leaves the oversized context in place, the error then repeated on every subsequent turn.
  - These recovery attempts no longer consume the logical iteration budget — each path keeps its own bounded retry counter (2 empty-response retries, 3 output continuations, 2 content-rejection stages), so `MaxIterations` now means "productive LLM turns" and a summarizer survives empty or truncated provider responses instead of dying. This aligns the loop with the existing transport-recovery rule and the shared principle that recovery must not consume the iteration budget.
  - The summarizer child keeps a limit of 3 as a safety margin for a stray phantom tool-call turn (its tool set stays empty), and the misleading "tool result summarization returned empty result" error was renamed to "summarization returned empty result".
  - Regression tests cover empty-response and output-limit recovery within a 1-iteration budget and the summarizer child recovering from empty provider responses.

- **Desktop Tasks Run and Switch Independently**
  - Desktop described "a task is running" with one global `promptInFlight` flag, so a second task could not be started while the first ran, the new-task composer was disabled whenever any other task ran, and clicking another task in the sidebar only answered "当前任务还在运行" until the user pressed "new task" again. Run state is now projected per session (`runningSessions`): a background task never marks the active one busy, never blocks a task switch, and never overwrites the active task's status. Reopening a session that is still running keeps showing it as running instead of freezing on the load state.
  - Streamed content is routed by a single rule — content belongs to the session that owns the transcript — so a task created while another one was streaming no longer mixes both conversations into one view, and a failure in the active session always explains itself in its own transcript instead of only moving the status dot.
  - Sending is single-flight: pressing Enter twice (or key repeat) can no longer create two sessions or send the same message twice.

- **Desktop Task Lists Never Keep a Deleted Session**
  - Deleting a task now drops it from every cached projection before the refresh, and a page load requested while an older one is still in flight is chained behind it instead of being answered from the stale response, so a deleted (or regrouped, or renamed) task cannot survive in an expanded project branch. A failed task-list refresh is now surfaced as a toast instead of silently freezing the list on old rows.
  - `session/delete` and `mothx/session/delete` are now idempotent: deleting an already removed session succeeds instead of failing with `session "…" not registered in DB`.

- **Task Provider Picker Shows Usable Providers, in Usage Order**
  - The Desktop task composer ignored the `apiKeyConfigured` flag that `mothx/manage/providers/list` already projects, so providers without an API key sat in the new-task and in-session pickers next to the ones that work. Both pickers now render only the providers the Runtime reports as configured, and a runtime that projects none of them (or an older runtime without the flag) keeps a selectable menu instead of an empty one.
  - Provider order is now one authoritative projection instead of a hardcoded vendor list: `mothx/manage/providers/list` orders providers by the default provider first, then by most recent recorded request, then by the stable catalog priority for providers that were never used, and reports `usageCount`/`lastUsedAt` next to each entry. Recency leads because a provider a person just added is also the one they just started running, while a pure request count would bury a new provider behind long-lived favourites. The Desktop picker consumes that order, and a session picker shows the same providers first as the next-task picker.

- **`mothx --continue` Continues the Session You Last Used**
  - `sessions.cwd` was compared byte-for-byte, so a session created through the Desktop directory picker — which stores the real on-disk casing — was invisible to a shell that spelled the same directory differently, and `mothx --continue` silently continued some other session. Session listings now match a working directory case-insensitively on Windows and macOS and keep exact matching on case-sensitive file systems.
  - "Most recent" meant most recently *created*: `SessionInfo.ModTime`, which every listing already treats as last used (the TUI's age column, Serve's `LastUsed`, the Desktop `updatedAt`), was filled with the creation timestamp. It now carries the newest persisted entry time, `CreatedAt` keeps the creation time separately, and the virtual session handle stays keyed by creation time, so session identity is unchanged. `--continue` therefore continues the session a person actually last worked in.
  - **New `mothx --list-sessions`.** Lists recent sessions across every working directory (ID, last used, message count, work directory, title), which is how a conversation started from Desktop, Serve, or a messaging channel can be found. `--list-sessions-limit` sets how many rows are printed (default 20) and `--list-sessions-cwd` narrows the list to one directory.

- **Documentation: Whether a ChatGPT/Codex Subscription Can Be Used in MothX**
  - New FAQ entry and configuration section: a ChatGPT Plus/Pro subscription **cannot** be pointed at MothX. It is served by Codex's internal backend (`chatgpt.com/backend-api/codex/responses`) and authenticated with a ChatGPT OAuth access token that OpenAI refreshes on its own schedule, neither of which fits MothX's provider credential model (plain value / `${ENV}` / `!command`), and routing subscription access into a third-party client is not what the subscription is sold for. The docs also explain why Codex CLI itself can send a ChatGPT login to a custom `base_url`, and give the two supported alternatives: the per-token OpenAI API (the built-in `openai` provider is already configured for the Codex model family with the Responses API and the Codex user agent), or any self-hosted/corporate gateway that speaks the OpenAI Responses API.
  - Configuration gains a "pointing MothX at a self-hosted or gateway endpoint" section covering `api: "openai-responses"` with `baseUrl`, declaring `models` explicitly, the supported credential forms, the `openai-chat` fallback, and verifying a gateway with `mothx doctor`/`mothx speedtest`.

- **`make desktop-dev` now exits completely on Ctrl+C**
  - The dev runner only closed its Vite renderer watcher when Electron happened to exit first. After Ctrl+C it had already marked itself as exiting, so that branch was skipped: the watcher stayed open and kept `npm run dev` — and the `make` process waiting on it — alive indefinitely. The watcher is now closed on every exit path, including the interrupt path, and the close is awaited before the process exits so it cannot be truncated.
  - Shutdown is an explicit, bounded state machine instead of a single `child.kill()`: the first interrupt terminates Electron and arms a 4-second grace period, a process that has not exited by then is killed, and a second interrupt skips the wait and exits at once. A spawn failure is reported the same way instead of surfacing as an unhandled `error` event. The exit code follows the 128 + signal convention (130/143/129) so `make` reports the interrupt.
  - Electron is spawned in its own process group on POSIX and terminated as a whole tree (`SIGTERM`/`SIGKILL` to the group, `taskkill /T` and `taskkill /T /F` on Windows), so the renderer/GPU/utility children no longer survive as headless background processes. `SIGHUP` (a closed terminal window) is handled like the other interrupts.

- **Desktop dev runner explains a missing display instead of showing a white window**
  - On a Linux host without a usable display (an SSH session, a stopped X server, X11 forwarding that never connected), Chromium aborts during platform initialization and dies on SIGSEGV. Because the window is frameless with a white background, the only symptom was a blank white window followed by a crash line, after waiting through a full build. `npm run dev` now checks for a display server first and exits within a second with an actionable explanation, without building anything, and recognises the same failure from Chromium's own stderr when `DISPLAY` is set but cannot be connected to — a case no environment check can predict. Chromium's original diagnostics are still printed unchanged, and the message lists the ways forward: a real desktop session, `ssh -X`, a virtual display (`Xvfb`, optionally under VNC/x11vnc), or the TUI / `mothx serve` Web UI for terminal-only work on a headless host.

- **Skill references can no longer escape the skill directory**
  - Reference paths parsed from SKILL.md content (`### Label (path) [已加载]` headers or Markdown links) were joined onto the skill directory without a containment check, so a third-party or skillhub-installed skill could auto-load arbitrary `.md`/`.txt` files from outside the skill directory (for example `../../../…`) into the system prompt. Parsed references now go through the same containment check as on-demand `skill_ref` loading; absolute paths and escaping paths are rejected.

- **File-tool path resolution now enforces a symlink fence**
  - `read`/`write`/`edit`/`insert`/`grep`/`find`/`ls` validated workspace containment lexically only, so a symlink inside the workspace pointing outside the session roots passed the check and let the unsandboxed host process read or write beyond the fence. `ResolvePath` now canonicalizes symlinks for both the target path and the session roots (including the not-yet-existing tail of new files) and re-checks containment on the canonical paths.

- **In-stream SSE error events now go through the provider retry loop**
  - A provider stream that emits an in-band error event/chunk mid-stream (Anthropic `event: error` such as `overloaded_error`, Google `error` chunks such as `UNAVAILABLE`/`RESOURCE_EXHAUSTED`, OpenAI-compatible `{"error":…}` chunks) previously terminated the run immediately — OpenAI chat streams even silently ignored error chunks and reported the truncated stream as a normal completion. These errors are now returned to the caller's retry classification: they are retried with bounded backoff while no visible output has been produced, and surface as a regular stream error otherwise. `IsRetryable` additionally matches `unavailable`, `resource_exhausted`, and `internal error` substrings.

- **Queued TUI prompts no longer fail with "lease is held by another process"**
  - When a run reached its terminal state and the fenced terminal-persistence write needed a retry, the Runtime kept the execution lease (by design) while it retried in the background; a TUI prompt queued behind that run immediately tried its admission and was rejected with `session runtime lease is held by another process` — a misleading cross-process error for a same-process drain window, and the queued input was dropped.
  - Shared execution admission now distinguishes draining from contention: a busy lease still held by the current process for an execution that already selected its terminal state makes queued successors (admission and session mutation) wait for the Runtime-owned release, so the session stays in this process and the queued input runs. A genuinely active same-process execution or another process's lease still fails fast for callers that did not opt into waiting.

- **Desktop cancel and decision state now converges on the canonical Runtime terminal state**
  - After cancelling a task, Desktop tracks a live `cancelling` run status that keeps blocking submission until the Runtime publishes a canonical terminal state; a late `running` pulse, a resolved decision, or a prompt response no longer reopens the session as submittable.
  - Background reverse approval/question requests are retained per session until the session is opened, materialized once on open (deduplicated against ACP replay by request ID, cleared on terminal state), so approvals from background tasks are no longer lost; background available-commands updates are ignored.
  - `session/load` is guarded against a delayed load overwriting the active session's config, mode, and transcript. ACP child spawn/restart is fenced: stale error/exit/stdout/stderr events from a replaced child cannot touch the new child's state, and an explicit start/restart clears any pending automatic restart timer.
  - A non-empty home background image path can only be set through the privileged native chooser — the generic renderer store channel may only clear it — and the previous blob object URL is revoked when the background image changes.
  - The default new-task directory moves from `~/projects` to `~/MothX`.

- **A cancelled ACP prompt queued behind session/load no longer starts after the load completes**
  - When `session/cancel` arrived while a prompt was still queued behind `session/load` (its admission context registered but the runtime not yet installed in the session table), the cancel was rejected as an unknown session and the prompt started as soon as the load completed. Cancellation now acts on the in-flight admission context first and answers successfully, so the cancelled prompt never starts.
  - Binding a run to its execution lease (Bind) now treats lease expiry as an advisory recovery boundary: it keeps the same owner/epoch/token CAS as Renew and no longer requires `expires_at` to be in the future. A live owner that missed heartbeats while SQLite was briefly unavailable can no longer be turned into a false ownership loss by a delayed admission; ownership is still decided only by a fenced epoch takeover.

- **The Desktop macOS titlebar no longer slides under the traffic lights**
  - The darwin titlebar offset rule lived in `@layer components`, so Tailwind's `pl-3` utility (utilities layer) overrode it and the logo/version badge slid under the native traffic lights. The offset rule moved into the utilities layer, and the test now asserts the rule's layer to catch regressions.

- **Windows bundled busybox assets switch to startvibecoding/agentbusybox**
  - The busybox executables embedded for Windows replace the rmyorston/busybox-w32 assets with startvibecoding/agentbusybox release builds (`busybox-windows-x86.exe`/`busybox-windows-x86_64.exe`); embedded asset names, arch mapping, provenance README, and tests are updated together. The binaries are vendored assets and are not hand-edited.

## v1.3.102

### 💥 Breaking Changes

- **Repository Moved to the `oschina` Organization**
  - The project moved from `github.com/startvibecoding/mothx` to `github.com/oschina/mothx`. Go importers must update the module path and their imports (`github.com/oschina/mothx/...`); `go install github.com/oschina/mothx/cmd/mothx@latest` replaces the previous install path.
  - Documentation, install snippets, the container image (`ghcr.io/oschina/mothx`), badges, the Gitee mirror (`gitee.com/oschina/mothx`), and installer metadata now point at the new organization. The `mothx`/`vibecoding` commands and the npm/PyPI package names are unchanged, so existing installs keep working.

### ✨ New Features

- **Native Audio/Video Input for Multimodal Models**
  - Models that declare `audio`/`video` input (for example `qwen3.8-omni-flash`) now receive attached audio and video files as native provider media content — OpenAI-compatible `input_audio`/`video_url` for chat (and `input_audio`/`input_video` for Responses), `inlineData` for Gemini — instead of workspace paths only. TUI, CLI, WebUI/API, ACP, and WeChat/Feishu share the same Runtime intake and conversion path; only transport decoding differs per adapter.
  - Audio/video intake is normalized in the Runtime (generic file uploads carrying `audio/*` or `video/*` payloads become media inputs), validated against their declared kind, and inlined up to a 7MB per-file limit; larger recordings stay workspace files with an explicit manifest note. Models without audio/video support keep the path-only manifest, and a mid-session switch to a text-only model replaces unsupported media blocks with a visible placeholder instead of failing the request.
  - The Serve chat-completions API accepts `input_audio` (raw base64 or data URL, with `format`) and `video_url` (data URL) content parts; remote media URLs are rejected and never fetched. Assistant messages remain text-only; audio output is not part of this change.

- **Serve: Placeholder API Token Warnings**
  - `mothx serve init-config` ships a well-known template token, which is equivalent to publishing the API key once auth is enabled — and nothing said so. The token is now a single named constant (`serve.PlaceholderAuthToken`) with explicit detection (`IsPlaceholderAuthToken`/`UsesPlaceholderAuthToken`), and a replacement warning is printed wherever the template is created (`mothx serve init-config` and the `--init-serve` CLI path) and again on `mothx serve` startup while `api.auth.enabled` is true and the token is still in place.
  - The startup check only fires for an enabled auth block, so the default template (auth disabled, loopback only) stays quiet and a replaced token is never flagged. `serve init-config` now writes through the command's own stderr, so the warning travels with the command output.

- **Members Wait for Their Lead on Interactive Surfaces**
  - A session that can spawn members but is not bound to an expert team now keeps its run open for still-running members on interactive surfaces (TUI, Web UI, ACP), so a member's completion or question is handled within the same run instead of waiting for the next lead run. Headless and asynchronous sources (CLI, cron, WeChat/Feishu) still end the turn normally and deliver member notifications at their next iteration or next run; a bound expert team always waits.

- **Bound Teams Keep the Full Sub-Agent Tool Set**
  - A bound expert team always exposes the complete canonical sub-agent tool set (`subagent_spawn`, `subagent_status`, `subagent_send`, `subagent_wait`, `subagent_answer`, `subagent_destroy`). Per-tool toggles that disable individual sub-agent tools apply only to non-team multi-agent sessions; the team capability is authoritative and never drops tools.

- **New Gitee/Moark Model: `auto`**
  - Added `auto` to the `gitee` and `moark` providers: an auto-routing model with a 1M context window, reasoning support, and text+image input; no default max_tokens is sent.

- **New Gitee/Moark Model: `deepseek-v4.1-flash`**
  - Added `deepseek-v4.1-flash` to the `gitee` and `moark` providers with a 1M context window and text+image input; no default max_tokens is sent.

- **New Xiaomi MiMo Models: `mimo-v2.6-pro` and `mimo-v2.6-flash`**
  - Added `mimo-v2.6-pro` and `mimo-v2.6-flash` to the `xiaomi` provider and all three MiMo token-plan channels (`xiaomi-token-plan-ams`, `xiaomi-token-plan-cn`, `xiaomi-token-plan-sgp`). Both declare a 1M-token context window, a 128K-token maximum output, reasoning support, and multimodal (`text,image`) input.

- **New Gitee/Moark Model: `qwen3.8-omni-flash`**
  - Added `qwen3.8-omni-flash` to the `gitee` and `moark` providers with a 1M context window, a 128K max output, and multimodal input (`text,image,audio,video`).

- **New Volcengine Model: `deepseek-v4.1-flash`**
  - Added `deepseek-v4.1-flash` to all three Volcengine providers — `volcengine`, `volcengine-agentplan`, and `volcengine-codingplan` — with a 1M context window, reasoning support, and text+image input. The standard channel sends 262K max_tokens; the two plan channels send 100K.

- **Gitee/Moark Model Order Leads With Flagships**
  - The `gitee` and `moark` built-in model lists now lead with the flagship models (`deepseek-v4.1-flash`, `qwen3.8-flash`, `glm-5.3-flash`, `qwen3.8-max-0902`, `glm-5.3`, `kimi-k3`, `minimax-m3`), followed by the remaining models ordered by context window (then max output) descending. Because the preset order is also the fallback when no default model is configured, an unconfigured `gitee`/`moark` session now defaults to `deepseek-v4.1-flash` instead of `auto`.

- **Xiaomi MiMo Channels Now Ship V2.6 Only**
  - The `xiaomi` provider and the three MiMo token-plan channels (`xiaomi-token-plan-ams`, `xiaomi-token-plan-cn`, `xiaomi-token-plan-sgp`) now list only `mimo-v2.6-flash` and `mimo-v2.6-pro`, with `mimo-v2.6-flash` first. The `mimo-v2.5`, `mimo-v2.5-pro`, and `mimo-v2.5-pro-ultraspeed` entries were removed, so an unconfigured Xiaomi session defaults to `mimo-v2.6-flash`.

- **New Provider Channel: B.AI (`bai`)**
  - Added a built-in `bai` provider preset for the OpenAI-compatible B.AI aggregator at `https://api.b.ai/v1` (API key `${BAI_API_KEY}`) with automatic base-URL vendor detection. The model catalog mirrors the live `https://api.b.ai/v1/models` listing — 49 chat models across OpenAI, Claude, Gemini, DeepSeek, Kimi, GLM, Qwen, MiniMax, Hunyuan, and MiMo families (the image-generation-only `gpt-image-2` is excluded) — with capability fields (context window, max output, input modalities) filled from known model specs.

- **New Agnes AI Providers (International + China)**
  - Added `agnes` (`https://apihub.agnes-ai.com/v1`, `${AGNES_API_KEY}`) and `agnes-cn` (`https://api.agnes-ai.cn/v1`, `${AGNES_CN_API_KEY}`) through a new OpenAI-compatible `agnes` vendor adapter. Both expose `agnes-2.5-flash` (200K context), `agnes-2.5-pro` (256K context), and `agnes-3.0-flash` (512K context, 65535 max output tokens).
  - Every model is declared reasoning-capable and multimodal (`text,image`). `agnes-2.5-flash` and `agnes-2.5-pro` send no default `max_tokens` of their own, so the provider default applies; `agnes-3.0-flash` caps output at 65535 tokens.

- **Cross-Process Notice When a Database Is Rebuilt**
  - A process that backs up and rebuilds a database after a schema migration failure now announces it over the existing advisory UDP bus (`database_rebuilt`). Every other mothx process sharing that session directory retires its cached connection — otherwise it would keep reading and writing the replaced file through its open handle — logs the recovery, and shows the notice to the user in the TUI. The notice carries only the replaced file path; the reason and the backup stay with the recovering process.
  - The bus stays host-only: a directed broadcast on the loopback /8 network that only accepts loopback sources, so it reaches this host's other mothx processes and never leaves the machine.

- **Model-Visible, Renewably Bounded Iteration Budget**
  - The agent loop's `MaxIterations` was a hidden hard counter: the budget-pressure event was rendered by adapters but never reached the model, and nothing inside a run could raise the limit, so a long task that was genuinely progressing still ended as `incomplete` at exactly 200 turns, with no chance for the model to converge or explain.
  - The budget is now injected into the run context as a transient, tail-appended system message when the remaining turns cross the pressure threshold, so the model sees the countdown. The notice is never persisted to the transcript and cache markers skip it, so it costs no prompt-cache prefix. A Runtime-clamped `extend_budget` tool then lets the model request more turns with a concrete reason, and the Runtime decides the grant.
  - `IterationBudgetPolicy` (soft/hard limit, renew factor, max renewals, minimum interval, 16-hour wall clock) is normalized in the shared Runtime and wired only for a session's conversational lead: transient builds, auxiliary roles, sub-agents, and expert-team members keep their capability ceiling and never receive the tool. Every exit path still emits exactly one terminal event, and the channel run-watchdog and durable background-polling defaults are raised to 57600s to match the wall-clock budget.

- **`mothx pure` Archives the Sessions Database and Starts Fresh**
  - Starting over previously meant deleting `sessions.db` by hand, which is both destructive and easy to get wrong: a leftover `-wal` or `-shm` sidecar can be picked up by the next database. The new `mothx pure` subcommand moves the shared `sessions.db` and its sidecars aside and creates a fresh, migrated database in its place. Nothing is deleted: each moved file is renamed to `sessions.db.pure-<timestamp>.bak` beside the new database (sidecars keep their suffix), so its sessions stay recoverable. `--session-dir` targets a specific directory; the default is the configured session directory.
  - Sidecars whose database is already gone - from an interrupted reset or a hand-deleted file - are archived the same way, so the fresh database never inherits a stale write-ahead log and its startup does not depend on how SQLite chooses to treat the leftover.
  - The command refuses to reset while another process holds an active session run in that directory, naming the session, the owning pid, and the run; `--force` overrides the refusal. A database this process cannot read is an unknown ownership state, not proof that no one is writing, so it also refuses without `--force`.
  - `pure` now also states what it left in place, and the reason differs per directory: `channels/` holds separate session roots with their own `sessions.db`, each `knowledge-bases/<id>.db` is that knowledge base's own authoritative store, and only `artifacts/` content becomes unreachable once its rows are archived. Only the last is reclaimable, so it is listed with its size while the others are reported as data the reset must not treat as garbage.
  - When the fresh database cannot be created after the previous files were moved, the error names the archive paths, so a failed reset no longer reads like lost data.

- **Unreferenced Attachment Storage Is Reclaimed**
  - Attachment bytes were only ever removed through the row-driven expiry path, so storage left behind by a deleted session, by an intake whose row write failed after its content was committed, or by an archived database stayed unreachable and occupied disk forever. The Runtime now also reconciles its private store from the directory side - on the attachment intake path (at most once an hour per process) and once a day through a Runtime-owned cron maintenance job (`mothx-maintenance:artifact-storage`, which is deliberately absent from user cron listings because it is host housekeeping rather than an authored automation) - and removes only directories that no row references **and** that were last written before the attachment retention window plus a 24-hour grace period, which is what keeps reclamation from destroying anything a restored archive could still serve. It fails closed when the sessions database cannot be read, never follows symbolic links, and only considers directories shaped like its own generated identifiers, so unrelated data can never be interpreted as attachment storage. `mothx pure --prune-unreferenced` runs the same pass on demand and reports what it reclaimed and what it kept as too young; `channels/` and `knowledge-bases/` are outside its scope.
  - The new optional `maintenance` section of `settings.json` controls it: `reclaimAttachmentStorage` (default `true`, so existing files keep the new behavior) and `storageReconcileSchedule` (default `@daily`, validated by the scheduler, falling back to the default with a log line when unparseable). Disabling removes the scheduled job at the next scheduler start and makes a stale job row refuse to delete anything; changing the cadence keeps the job's run counters and status.

### 🐛 Bug Fixes

- **Runtime Lease Reclamation Requires a Live Reference Check**
  - A same-process reclamation could take a lease away from a session that still held a live execution reference merely because the `owner_instance_id` matched, which could fence away an execution that was still running. Reclamation now proves that no live execution reference remains (`hasLiveRuntimeLease`) before it may reclaim, so a retained reference is never displaced.

- **Knowledge-Base Snapshots Publish Only Against the Configuration They Indexed**
  - A knowledge base could be reconfigured while an indexer was running, letting a graph built from the old configuration become the active snapshot. The knowledge database schema now carries a `config_revision`; base updates bump it and snapshot activation compares the revision the indexer loaded (`BaseConfigRevision`), so a stale indexer fails with `ErrKnowledgeBaseConfigurationChanged` instead of publishing a graph that no longer matches the base.

- **Fork and Project Metadata Are Written Atomically**
  - A fork's idempotency fingerprint now includes a non-nil expert override, so re-forking with a different expert is no longer deduplicated into the first request, and the fork transaction helpers propagate the caller's context. Project session metadata is upserted in one transaction guarded by reference `EXISTS` checks with `DeleteWithMetadata` realizing `ON DELETE SET NULL`, and session binding/cwd changes hold the write lock across the database operation instead of rolling back in memory.

- **Provider Stream Timeouts Recover Consistently Across Runs**
  - A caller deadline, including one applied around an ESM role, could be surfaced as a provider response timeout and misleadingly claim that it had retried zero times. Caller cancellation and deadlines now remain cancelled runs, never provider transport failures.
  - ESM worker, critic, and audit roles no longer impose a 30-minute deadline: the long-task objective continues until it finishes or is explicitly cancelled. The restricted recovery observer remains bounded.
  - When a provider stream genuinely stalls, Agent Core now retries with exponential backoff until cancellation. After partial text or reasoning it persists the safe partial response and uses a continuation instruction; retries do not consume the Agent iteration budget. This shared recovery path applies to ordinary, ESM, and other adapter runs without re-running emitted tool calls.

- **ESM Continues Long Objectives Instead of Tripping Internal Circuit Breakers**
  - Worker, critic, and audit roles now use the Agent Core's explicit unbounded-iteration policy. A role that ends `incomplete` is marked incomplete and recorded as recoverable work, never projected as success.
  - Recovery and rejected-completion counts remain visible for diagnosis, but neither count pauses an active ESM objective. A rejected completion means remaining work, so the next continuation resumes from persisted state.

- **Session Deletion Is Fenced by the Runtime Mutation Lease**
  - Deleting a session (TUI `/sessions`, ACP `session/delete`, Serve `/clear` and session deletion, and the CLI) removed its rows and handle without checking whether another process still owned it for execution, so a concurrent run could lose its session underneath it. Deletion now takes the shared Runtime mutation lease for that session and revalidates the fenced `owner`/`epoch`/`token` identity inside the deletion transaction; a multi-session cascade reuses the lease group it already holds instead of reacquiring a process-local lock per child.
  - The lease preflight used by `mothx pure` now opens the sessions database read-only, with no migrations, integrity repair, or WAL setup, so a safety check never modifies the database it is deciding whether to archive.

- **Unadvertised Tool Calls Are Rejected Before Execution**
  - A provider response is untrusted input: the agent ran any tool call the provider emitted even when the effective mode had not advertised it, so a hallucinated or injected call could still reach approval, durable claims, and the registry. Execution now checks the Run's frozen registration snapshot first and returns a tool error for a call that is not registered for that run, leaving Registry changes to a subsequent Agent build.

- **Session Identity Is Committed Only After Preparation Succeeds**
  - `BindSession` published the new session identity before loading the session's expert binding and context resources, so a load failure left the Runtime attached to a half-initialized session while the caller believed the bind had failed. The session-dependent resources are now resolved first and the identity is published only once they succeed, and the TUI's `activateSession` commits `session`/`cwd` only after decision recovery and Runtime binding both succeed, so a failed switch no longer leaves the adapter and the Runtime on different sessions.
  - Binding now rebuilds the Runtime-owned attachment and input services for the session being bound. A long-lived Runtime (the TUI reuses one across `/sessions`, and the CLI reuses one for `--shared-runtime` runs) therefore no longer keeps writing new uploads into the first session's attachment directory after a session switch.
  - Serve's `/clear` created a fresh session manager but left the session's Runtime bound to the deleted one, so the next prompt executed against a session that no longer existed. Clearing now rebinds the Runtime to the new manager before the session is reused.

- **SQLite: A Stale Secondary Index Is Repaired Instead of Blocking Startup**
  - An interrupted write could leave SQLite reporting `wrong # of entries in index` from `PRAGMA quick_check` even though every table page was intact, and the integrity check failed startup with no way forward. Index contents are derived from table rows, so this precise case is now repaired with `REINDEX` and re-verified before continuing; any other integrity failure still aborts startup, since it may affect canonical data.
  - A repair that cannot take the writer lock is reported as contention - another process still holds the database, so the index was not rebuilt - instead of reading like a failed repair of a corrupted file. It retries within the same busy budget every managed connection already carries, and the untouched database is repaired successfully once that lock is released.
  - A completed repair is now reported exactly once (a startup notice for the CLI and TUI, a log line for serve, ACP, and channels), because a database that needed one has already survived an interrupted write worth knowing about.

- **Session Runtime Leases Now Survive Transient Database Stalls**
  - Long runs could be interrupted by `session runtime lease was lost` even when no other process held the session. The per-directory heartbeat scheduler stopped whenever a tick observed an empty directory, even if a lease admitted moments earlier was still live: it left a registered-but-stopped entry in the scheduler registry that no later acquire could replace, so the lease was never renewed again and a later execution-path write found it expired. This was introduced when the per-lease heartbeats were coalesced into one scheduler per session directory.
  - The scheduler now exits only after it has actually unregistered itself for an idle directory, and a renewal that merely times out (a busy or unreachable session database) is retried on the next heartbeat tick instead of being reported as ownership loss. Ownership is decided by the fenced `owner`/`epoch`/`token` CAS, not by wall-clock expiry: taking over bumps the epoch, so a row that expired while still carrying our identity remains ours. Only a genuine fenced takeover or a released lease marks it lost. The heartbeat retry budget is derived from the shared `busy_timeout` (`db.BusyTimeout`) so a single tick can absorb a full contended begin, and lease loss is now logged with its reason.

- **Channel Sub-Agent Terminal Events Reach Observers After the Parent Run Ends**
  - A child agent spawned by a channel session can outlive its parent's event stream (for example when it is cancelled as the run ends). The dispatcher dropped the root-agent → session mapping as soon as the parent run finished, because it checked the dispatcher-wide manager instead of the session-scoped manager that actually owns the children. The late terminal event could then no longer be routed, so observers stayed on "running" forever and a completed or failed member was never reported. The mapping now survives while the root is still running or any child is still live, and is released once the root has finished and its last child reaches a terminal state.

- **Web UI: Knowledge Base Scans Keep Their Status Across Reloads**
  - Starting a scan from the Web UI knowledge page blocked the HTTP request until the entire index finished and recorded nothing about the in-flight job, so the base read as merely "not indexed" and reloading the page lost the scanning state entirely.
  - The serve handler now admits the scan as a background Runtime index job through the process-wide cached service and returns a running-job projection immediately, and list/get expose the live `indexing` progress (phase, files done/total) using the same projection ACP already publishes. The knowledge view renders the current phase and polls while a scan is running, so a reload resumes the status instead of dropping it.
  - The cached serve service now refreshes its settings snapshot when settings.json changes, so a later scan uses the updated Indexer provider/model without losing the in-flight background job registry.

- **Content-Inspected Images No Longer Kill the Session**
  - A provider content-policy refusal — for example DashScope/Qwen's `InternalError.Algo.DataInspectionFailed: Input image data may contain inappropriate content` — arrives as an HTTP 400, but every 4xx was treated as retryable. The same rejected image was re-sent through the provider's backoff retries plus the agent's stream-failure retries (minutes of "Retrying…"), and because a refusal is permanent the run finally failed; worse, the offending image stayed in the persisted history and was replayed on every later turn, so nothing could continue. Only starting a brand-new session recovered — not even `/clear`, which reloads the same history.
  - `provider.IsContentRejectionError` now classifies this narrow family (data inspection, content policy/moderation/filter, "inappropriate content") and `IsRetryable` returns false for it, so the failure surfaces immediately instead of burning the retry budget. Agent Core then recovers in place: it strips the refused images — first from the current turn, then, if the refusal persists, from the whole conversation — replacing each with a model-visible note that explains the provider's content filter blocked the image and that the pixels are unavailable, and records an append-only `content_override` session entry so replay (same process or after reload) never re-sends it. The run retries without the image and the session keeps working; a turn that already streamed output is healed but not re-run, so no output is duplicated.

- **Serve: Config Saves No Longer Fail with "Access is denied" on Windows**
  - On Windows (including portable setups running from exFAT drives), enabling the WeChat/Feishu channel from the Web UI or saving any `serve.json` change failed with `sync config directory: Access is denied`. The atomic config writer fsynced the parent directory after the rename — a POSIX durability idiom — but `FlushFileBuffers` on a read-only directory handle always returns `ERROR_ACCESS_DENIED` on Windows, on every filesystem including exFAT. Because the failure happened after the file had already been swapped into place, the API reported an error while the new config was never applied to the runtime.
  - The post-rename directory flush is now skipped on Windows (matching etcd/bolt practice); the config file itself is still fsynced before the rename, so durability is preserved and Unix behavior is unchanged.

- **MCP: Image Tool Results Reach the Model Instead of a Placeholder**
  - An MCP tool that returned image content reached the model as the literal string `[image content: image/png]`. The base64 payload was already present in the MCP response, but the client decoded every content block into text only, and the tool returned a text-only result, so a screenshot-style MCP server could report coordinates while the model never saw the picture. `resources/read` binary resources were worse: the `blob` field had no matching struct field, so the payload was dropped during decode and not even the placeholder appeared.
  - `tools/call` and `resources/read` now project image blocks into `tools.ToolResult.Contents` as real provider image content, reusing the same provider-aware preprocessing as the `read` and `browser` screenshot tools, and decode `blob`/`uri` resource fields. Results without images keep the historical text-only shape, so existing text MCP tools are unchanged. Malformed, oversized, or excess images (capped at 4 per result, matching the ACP projection limit) degrade to a text note instead of failing the call. The image capability gate in Agent Core still decides whether a non-vision model receives images at all.

- **SQLite: Transient Busy Transaction Begins Are Retried**
  - Several processes opening one session directory race onto the single writer lock. The DSN begins non-read-only transactions with `BEGIN IMMEDIATE`, so a begin can outlast the connection's `busy_timeout` while other processes keep committing under `synchronous(FULL)`, and a healthy database failed with `database is locked (5)`.
  - The retry policy now lives in `internal/db` next to the DSN ownership: `BeginTx` (Bun), `BeginSQLTx` (raw `*sql.DB`), and `RunInTx` retry only `SQLITE_BUSY`/`SQLITE_LOCKED` inside a bounded budget (90 s) with exponential backoff (200 ms up to a 2 s cap); non-transient errors are returned unchanged and a caller's context deadline still wins.
  - DAO `Begin`/`BeginTx`/`RunInTx` (including the bindings helpers), `internal/db.Write`, and the session schema initialization/migration boundary all use it, so concurrent startup and ordinary writes no longer turn a transient writer conflict into a hard failure.

- **Workflow: Runaway DSL Scripts Are Bounded by a Wall-Clock Budget**
  - A workflow source such as `while (true) {}` could pin the process forever whenever its caller passed a context without a deadline. Source evaluation — which only builds the node graph, since worker agents run natively afterwards — now runs under two bounds: the caller's context and a wall-clock budget, whichever fires first interrupts the VM.
  - The budgets are 30 s for a workflow run and 5 s for the interactive `workflow_lint` authoring check, which must fail fast; a timeout surfaces as the sentinel `ErrJSEvaluationTimeout` (the lint result carries a stable, readable error), while a caller cancellation keeps returning its context error. `Runner.EvalTimeout` lets callers tighten the budget, and the zero value keeps the documented defaults.

- **Cancelled or Expired Decisions No Longer Block Forking**
  - A session whose only decision had actually been cancelled or timed out was still treated as having a pending decision, so forking it was rejected as `source session is active`. Every decision-ledger reader now shares one vocabulary, so cancelled and timed-out decisions (and the legacy channel request name) clear correctly and the fork proceeds. The durable decision event name and its `{"decision": …}` envelope also gained a single owner each, so cross-entry decision recovery reads the same records regardless of which surface wrote them.

- **Mid-Stream Network Failures Retry Automatically Instead of Ending the Reply**
  - A provider stream that died with a transient transport error (`connection reset by peer`, unexpected EOF, gateway 5xx, ...) after text or thinking had already been streamed failed the whole run with `stream read error: ...`: provider-level retries only cover streams that break before any visible output, and the agent-level retry only covered idle-stream timeouts.
  - The agent loop now performs a bounded continuation retry (up to 2 attempts) for such transient errors. Already-streamed partial output is persisted into history and a continuation instruction quoting the exact suffix is injected, so the model resumes from the interruption point instead of duplicating what the user already saw; with no visible output yet, the turn simply re-runs. Turns with an already-emitted tool call, context overflow (dedicated compaction recovery), and idle-stream timeouts (dedicated timeout retry) keep their existing behavior, and Responses remote-state turns keep their existing failover path.

- **Desktop: The Skill Marketplace Now Defaults to SkillHub.cn Instead of ClawHub**
  - The Desktop skills view selected the first entry of the ACP market list, which is sorted alphabetically, so `clawhub.ai` beat `skillhub.cn` and the catalog defaulted to ClawHub even when the canonical `skillHub.defaultMarket` setting (product default SkillHub.cn) said otherwise. The default market is canonical configuration state, not something an adapter should guess from list ordering.
  - `mothx/manage/skillhub/markets` now additionally projects the settings-resolved `defaultMarket` (falling back to the product default `skillhub.cn` when blank), and the Desktop catalog bootstrap resolves user preference → ACP-projected default market → first market. The categories/search/detail/install fallbacks use the same resolver, so an explicitly blank configured value no longer fails with `unsupported skill market`.

- **Database Migration Failure Backs Up and Rebuilds Instead of Blocking Startup**
  - A `sessions.db` whose schema the current build cannot upgrade — an unappliable migration or a table missing required columns — failed every command with `database schema is incompatible`, leaving the user no way forward but deleting the database by hand. `internal/db` now recovers once per database: it snapshots the unrecoverable database next to the original (`sessions.db.migration-failed-<timestamp>.bak`, written with SQLite `VACUUM INTO` and falling back to a checkpoint plus raw file copies when VACUUM itself fails), deletes the old file set including `-wal`/`-shm`/`-journal`, and initializes a fresh empty database in its place.
  - The recovery is reported, not silent: `internal/db` logs it and the CLI/TUI print a "Database migration error" startup notice naming the backup file, which still holds the previous sessions. Only a schema owner (`internal/session`) can mark a failure as rebuildable, and writer contention, a cancelled migration, or a read-only file leave the database untouched with the reason appended to the error, so a healthy database under external pressure is never replaced.

- **Malformed Streamed Tool-Call Arguments Are Repaired, Never Guessed**
  - A provider can stream a tool call whose arguments are empty or not JSON, and Go 1.27's JSON v2 encoder validates `json.RawMessage` (`jsontext.Value`), so a non-nil empty value failed the whole entry at the session and replay boundaries with `unexpected end of JSON input`. `provider.NormalizeToolCallArguments`/`NormalizeMessage` now repair such a call into the safe empty object `{}` while preserving the original payload in `InvalidArguments` for diagnostics, and every persistence and replay path normalizes before storing — the Agent loop's user and message inputs, `AppendMessage`/`AppendMessages`/`AppendContentOverride`/clone, run user/assistant entries, and durable turn/message writes.
  - A malformed call is no longer replayed as a guessed side effect: the Agent records it as a failed tool result and injects a transient recovery notice so the next provider request reconstructs valid JSON arguments instead of assuming any side effect occurred. `marshalSessionEntry` retries a failed marshal after the repair as a last line of defense.

### 🔧 Improvements

- **Unified Provider/Model Catalog in `docs/provider-model-list.md`**
  - `docs/provider-model-list.md` is now the single provider/model reference: the former OpenRouter-snapshot `docs/models.md` was removed and merged into the built-in catalog. It is generated from `internal/config/settings.go` by `docs/scripts/generate-models.py` (`make docs-models`) and covers every built-in provider (API type, vendor, thinking format, base URL, API key env) plus per-model context window, max output, reasoning, input modalities, and pricing, alongside the Quick Reference and configuration-field guides.

- **Model Presets Seed New Models Consistently**
  - `config.PresetModelConfig` is now the single source of draft defaults for a model ID: the current provider's configuration wins, then an exact match elsewhere in the built-in catalog, then safe generic defaults (256K context, reasoning on, text input). Model discovery, the provider factory, the TUI auth settings, the WebUI provider editor, the Serve model catalog, and the ACP provider catalog all seed a newly entered model the same way, and the generic defaults are projected to clients through `modelDefaults` so a client editor starts from the same values.

- **Tool Registration Reconciled Through the Shared Runtime**
  - Installing, removing, and re-pointing the manager-backed tool groups (sub-agent tools, `delegate_subagent`, workflow tools) is now owned by `agentruntime.SynchronizeToolGroups`: TUI, CLI/WebUI (serve), channels, and ACP only pass policy and the current AgentManager handle. Manager swaps re-install the groups so tool instances always reference the current manager, per-tool switches survive re-registration, and a bound expert team keeps forcing the full canonical sub-agent toolset.
  - Registry assembly has one implementation: `agentruntime.BuildRegistry` now owns the plan/skill_ref/browser/image_generation/question tool policy, `Builder.Build` routes through it, and resource refresh reconciles the image-generation settings gate. ACP sessions therefore receive the `image_generation` tool when the setting is enabled (previously only TUI/WebUI/serve sessions had it).
  - Canonical tool names stop being hand-copied: `workflow.ToolNames()`/`workflow.RemoveTools` and one shared built-in factory list replace the duplicated registration/removal lists. A new `internal/architecture` guard rejects direct `tools.NewRegistry`/`NewRegistryWithConfig` calls outside the construction owners and one documented TUI `/btw` bridge.
  - `extend_budget` joins `plan` as a local-only tool: its calls no longer consume durable tool-execution records, matching their no-side-effect semantics. Content-block cloning now covers `FileContent` alongside image/audio/video everywhere.

- **SQLite: Three-Phase Write-Pressure Reduction for the Session Database**
  - The connection durability policy moves from `synchronous(FULL)` to the WAL-recommended `synchronous(NORMAL)`: a commit no longer fsyncs while holding the single writer lock (the fsync moves to checkpoint time), so writer-lock occupancy across processes sharing one session directory shrinks from fsync scale to page-cache scale, largely eliminating the recorded "another process keeps committing until begin exceeds busy_timeout and reports database is locked" scenario. Process crashes still lose nothing; an OS crash or power loss can roll back the seconds of commits since the last checkpoint (the database stays consistent, and a missing run terminal state converges through the existing lease-expiry → orphan → bounded-recovery path). `MOTHX_SQLITE_SYNCHRONOUS=FULL` restores the legacy durability per process, and mixed old/new processes sharing one database file is safe.
  - Tool results now persist in batches: the session domain gained `AppendMessages`, writing one agent iteration's tool results as a parent-chained single transaction (capped at 64 entries per transaction, chunked above that) with the lease fence and the leaf-conflict check still inside the write transaction; tool-heavy rounds drop from N+3 write transactions to about 3. The assistant message still persists before tool side effects, and a failed batch still fails the run with `session_save`.
  - Lease heartbeats are coalesced: instead of one goroutine committing a renewal transaction per active lease every 3 seconds, a single scheduler per session directory renews all of this process's leases for that database in one transaction (the per-lease owner/epoch/token CAS fence is unchanged, so a displaced or released lease still only loses itself); steady-state heartbeat writes drop from N transactions/3s to 1 transaction/3s/process. TTL, heartbeat interval, retry budget, and the 30-second bounded-recovery guarantee are untouched, and the scheduler retires after the last lease is released.
  - `internal/db` gained process-wide busy-retry and transaction-begin wait metrics (`BusyRetryStats`/`BeginWaitStats`), published through expvar as `mothx_sqlite` and readable on the `--debug` pprof server's `/debug/vars`, making cross-process writer contention observable.
  - Full plan, multi-process reasoning, and load-test matrix: `docs/proposal/sqlite-write-pressure-reduction-proposal.md`.

### ✅ Tests

- Database: `internal/db` pins the begin-retry policy — only SQLITE_BUSY/SQLITE_LOCKED are retried, other driver errors and an expiring context are surfaced unchanged, driver codes are classified through the error's own `Code()` method, and `RunInTx` keeps commit/rollback semantics.
- Workflow: a runaway script is interrupted by a 50 ms budget (previously that test hung), a successful evaluation behaves exactly as before, and the lint path reports an invalid result with the timeout message.
- Serve: the generated template keeps the same constant the detection uses, a whitespace-padded placeholder is still recognized while a real or empty token is not, and the `serve init-config` output must contain the warning.
- Agent loop: ten real `bash echo` calls run through one parallel batch (the rendezvous only closes once all ten workers are live), and ordered-start coverage pins the launch semantics — starts in the model's declared order, an in-flight call unaffected by an earlier approval wait, queued calls released when an earlier call fails, and the same ordered handle for background tool calls.
- Runtime: the cross-process takeover test now retries the expire-then-takeover pair inside a bounded budget and gives helper startup a load-tolerant window, so a loaded machine fails setup with a clear diagnosis instead of failing the invariant under test.
- Decision ledger: round-trip and replay coverage for the shared event name, envelope, and loaders; the legacy channel event name still decodes; and a cancelled decision no longer blocks a fork.
- Member wait: an interactive (TUI) non-team lead holds its run open for a running member, while a headless (CLI) one ends normally.
- Architecture: a guard rejects new use of the legacy session run/lease APIs or a low-level `agent.New` in adapter test files, with a documented allowlist for the remaining fixtures.
- `systeminit`: the shared `/systeminit` prompt is pinned — interactive-only question guidance, trimmed extra instructions before the final note, blank extra input ignored, and determinism.
- Stream-failure recovery: a mid-stream connection reset resumes through the continuation retry — partial output persists and continues from the exact suffix, no visible output re-runs the turn fresh, and exhausting the budget surfaces the original error — while a turn with an already-emitted tool call or a non-retryable error never retries.
- SQLite write pressure: `internal/db` pins the synchronous default (NORMAL), the `MOTHX_SQLITE_SYNCHRONOUS=FULL` override, and busy-retry counting that never charges permanent errors; session tests cover the `AppendMessages` parent chain and replay order, whole-batch stale-writer rejection persisting no rows, chunking above the transaction cap, and sub-agent table isolation; the heartbeat scheduler test covers one scheduler per directory, batched renewal, a displaced lease losing only itself while the survivor renews, and retirement after the last release. Plus write-pressure load shapes A/B/C (multi-process distinct-session writers, mixed FULL/NORMAL deployment, single-process many sessions with leases) reporting busy/begin contention metrics, scalable through `MOTHX_WRITE_PRESSURE_SCALE` for baseline runs.
- Tool-call arguments: `provider` pins the empty and non-JSON repair (the original payload is preserved in `InvalidArguments`), the Agent records a malformed call as a failed tool result and injects a recovery notice instead of executing a guessed side effect, and session append/replay keeps the repaired entry marshalable.
## v1.3.100

### ✨ New Features

- **Independent Artifact Publishing Switches**
  - TUI/CLI, WebUI/API, Desktop/ACP, and messaging channels now have separate artifact publishing switches, all disabled by default. Each entry point enables the shared Runtime-owned `publish_artifact` path without changing the others.

- **Expert Teams Across TUI, WebUI, and Desktop**
  - Sessions can bind a reusable expert bundle with `--expert <id>` or TUI `/expert list|show|bind|unbind|switch` commands. A team bundle injects its lead identity and roster and automatically enables member dispatch; a single-persona bundle changes only the lead identity.
  - Replacing an existing expert creates a fork instead of overwriting the source session. The WebUI expert panel and Desktop ACP **Expert** option use the same Runtime-owned binding and fork path.
  - Member lifecycle projections now carry the member name, emoji, role, and expert identity for TUI, WebUI, and Desktop cards. Member completion is delivered at a lead boundary and never starts a new run by itself.
  - ESM continues only from a genuinely idle, runnable objective. Pending input, decisions, or a member terminal event cannot bypass that gate.
  - Added the built-in `expert-creater` Skill. Activate it with `/skill expert-creater` in TUI/WebUI or `/expert-creater` in Desktop/ACP, then let the current Agent create and install a validated project team under `.mothx/experts/`.

- **WebUI: Slash Command Suggestions in the Chat Composer**
  - Typing `/` in the chat input now shows a suggestion dropdown covering every supported slash command (`/clear`, `/mode`, `/model`, `/defaultModel`, `/models`, `/sessions`, `/status`, `/compact`, `/delegate`, `/alloweditpath`, `/allowautoedit`, `/workflows`, `/skill`, `/skills`, `/rule`, `/esm`, `/help`), with a dedicated subcommand filter for `/esm` (objective/edit/pause/resume/clear/guide).
  - Navigate with ↑/↓, complete with Tab or Enter (Enter sends the prompt when the input already matches the selection), dismiss with Esc, or click an entry; accepting a suggestion places the cursor at the end of the inserted command. The composer keeps proper combobox/listbox ARIA state (`aria-expanded`, `aria-activedescendant`, `aria-selected`).
  - Suggestions are suppressed while a run is active, the API is disabled, or the input spans multiple lines.

- **WebUI: Runtime-Owned Knowledge Base Management**
  - The new **Knowledge** workspace lists, creates, edits, scans, queries, and deletes directory-backed knowledge bases through the same Runtime/session services used by ACP and Desktop. Directory selection falls back to the built-in browser when a native picker is unavailable; source files and index storage remain server-owned.

- **Desktop: Streamlined Home Presets and Prompt-Filling Quick Actions**
  - Home preset tabs are shortened to Work / Code / Create (办公 / 代码 / 创作) with tightened descriptions in both languages.
  - Quick-action chips now fill the composer with a complete, ready-to-send prompt (including editable `[topic]`-style placeholders) instead of a bare label, so one click can start a real task.

- **Desktop: Development Mode (`make desktop-dev` / `npm run dev`)**
  - New dev runner: watches `renderer/src/`, `renderer/index.html`, and `renderer/styles.css`, rebuilds `dist/renderer` on change, and reloads Electron without cache so the ACP child process does not restart; `main/` and `preload/` are built once at startup and require a manual restart after edits.
  - Dev mode (`MOTHX_DESKTOP_DEV=1`) opens DevTools automatically in a detached external window (never docked inside the app), binds the Chrome DevTools Protocol to `127.0.0.1:9223` only (change the local port with `MOTHX_DESKTOP_DEBUG_PORT`), and reloads the window when renderer assets change; it does not start `mothx serve` and adds no HTTP/API channel to the renderer.
  - The dev instance runs on an isolated user data directory (`desktop/.dev-user-data/`, overridable with `MOTHX_DESKTOP_USER_DATA`) so it never competes with an installed Desktop for the single-instance lock or reuses its local display state.

- **Desktop: Online Skill Marketplace (SkillHub Catalog)**
  - New ACP feature key `manageSkillHubCatalog` and an additive `mothx/manage/skillhub/*` method family (markets/categories/official/search/detail/targets/installed/install/activate/uninstall) as a pure ACP projection of the shared SkillHub service; every request must bind to an active session, so Desktop cannot pick arbitrary install directories.
  - The Desktop skills page gains a marketplace section: market/category filters, keyword search, official recommendations, and install/update/activate-into-session/uninstall into the session's project or global skills directory.
  - ACP sessions now track multiple active skills (previously activating a new skill replaced the previous one), so several skills can stay active in the same session.

- **Desktop: App-Wide Background Image Options**
  - Background images can now apply to the whole app or the home view only, with fit modes (cover / contain / stretch / tile) and anchor positions (center / left / right / top / bottom).
  - Background veils and surface blur fade adaptively with image opacity; with an app-wide background, the titlebar gains a readable contrast surface and text shadows so window controls stay legible.
  - Appearance settings move into a standalone Appearance category.

- **Expert Team Member Questions Reach the Lead**
  - A member that needs a decision asks the lead instead of the human: the question is queued in the session mailbox, delivered as a `[MEMBER_QUESTION]` steering message (or as a `subagent_wait` entry with status `question`), and answered with `subagent_answer(handle: "<member>", question_id: "…", answer: "…")`. The user only sees the question projected on the lead's stream.
  - The mailbox path works in every session that can spawn members — multi-agent, delegate, and workflow modes — not only in team-bound sessions, and `subagent_wait` now reports pending member activity there too. Only a team-bound session holds its run open for still-running members; other sessions end the turn normally and see the notification at their next iteration or next run.
  - Answering a question that is no longer pending (already answered, expired, or belonging to another member) reports an error instead of a silent success. A blocking `delegate_subagent` child cannot ask questions, because its caller is parked inside the tool call that would have to answer it.

- **Retry Failed Message Deliveries from Desktop and WebUI**
  - Desktop's Channels settings list the failed durable deliveries of the active session — platform, operation kind, status, failure code, attempt count, and last update — with a per-row retry; WebUI exposes the same Runtime-owned facts through `GET /api/deliveries/failures` and `POST /api/deliveries/retry` in its channel settings.
  - Both entries project the Runtime's own verdict: only a failed transport-level operation is offered a retry, while in-flight, delivered, and permanently failed operations are refused instead of being reopened into another doomed attempt (the refusal they report is the same rule the persistence fence enforces).

### 🐛 Bug Fixes

- **Browser: Built-in Skill No Longer Writes into Projects**
  - Browser guidance now ships as the built-in `vibe-browser` Skill. Enabling Browser in TUI, WebUI, Desktop, ACP, or a channel no longer creates `.skills/vibe-browser/SKILL.md`; intentionally created project or global skills with that name still override the built-in guidance.

- **Channels: Browser Selection Survives Runtime Rehydration**
  - A channel session's persisted Browser selection now drives both initial registry construction and Runtime resource rehydration. Explicitly enabling Browser no longer has the tool removed after the session Runtime attaches.

- **TUI: Prompts Submitted During an Active Run Are Queued Instead of Replacing It**
  - A session allows exactly one foreground execution at a time. Previously, submitting input while a run was active replaced the in-memory run handle, orphaning the active run's terminal cleanup and its runtime lease. Such submissions are now queued in the TUI, and the next queued prompt starts only after the preceding run reaches its canonical terminal state and releases its lease — across every terminal branch (success, failure, incomplete, and cancellation).
  - Queued prompts retain their Runtime-prepared attachments (`agentruntime.PreparedInput`) and re-enter through the same input contract, so attachments survive the delay unchanged.

- **TUI: `/defaultModel` Shares the `/model` Catalog Logic**
  - The `/defaultModel` picker now resolves each provider's model list through `providerfactory.ResolvedModels` — the same factory-resolved catalog (built-in presets merged with settings overrides) that backs `/model` and the WebUI picker — instead of re-parsing raw `settings.json` models. A provider whose settings entry declares only credentials or a partial model list no longer hides the remaining built-in models.

- **Cancelled Runs Report Cancellation Instead of Success**
  - A run cancelled while it waits for its members, or while its final turn is in flight, now ends as cancelled with the canonical `aborted` reason instead of being projected as a completed run; adapters that derive their state from the terminal event (ACP/Desktop) show the cancellation the user asked for.
  - A turn whose answer was cut off by the output limit but recovered by escalation or a continuation is no longer marked incomplete: the truncation flag is scoped to its own turn instead of leaking into the next one.
  - TUI: a retired event stream keeps being drained so an aborted run can always reach its terminal bookkeeping; an aborted cached Agent is discarded before the next submission; tool rows left running by an early run end are terminalized.

- **Messaging Channels: Bounded Delivery Retry Windows**
  - Durable delivery operations retry inside a configurable window (10 minutes by default) instead of being abandoned after a fixed attempt count. Transport-level failures are retried automatically, recovered by the serve reconnect path, or reopened by an operator through ACP `mothx/manage/deliveries/retry`.
  - Permanent failures (platform 4xx, unsupported media, broken projection) stay failed: the failure projection reports a `retryable` flag, the retry entry refuses operations that are not failed or not reopenable instead of clobbering them back into `retry_wait`, and the persistence layer enforces the same fence. Operations that failed only because their dependency did recover with it.

- **Channels: A Disabled Sub-Agent Tool Stays Disabled**
  - Re-pointing the sub-agent tools at the session-scoped manager (which owns the session mailbox) no longer resurrects tools the user switched off: an ordinary multi-agent selection keeps its per-tool choice, while a team binding stays authoritative and always exposes the full team toolset.

- **Parallel Tool Calls Report Their Starts in the Declared Order**
  - A parallel tool-call batch now reports each call's start in the order the model emitted them, so argument parsing and worker scheduling can no longer make a later call appear to start first. The ordering is start-only and never blocks execution: calls still run concurrently, each waits for its own approvals and durable execution records, and completions may finish in any order. Results, transcript order, and provider continuation messages keep their existing guaranteed order, and Responses background runs use the same ordered handle.

### ✅ Tests

- TUI: new coverage asserting that input during an active run queues without replacing the lease owner, and that the queued prompt starts only after the cancellation path finalizes the durable run and releases its lease.
- TUI: `/defaultModel` coverage asserting the dialog's model list matches the factory-created provider list (the `/model` path) for both partial-override and credential-only settings entries.
- Expert Teams: Runtime binding/fork, named-member events, TUI and Serve no-direct-run guards, ACP bind/fork process coverage, Desktop projection, and cross-entry ESM idle-gate coverage.
- Channels: an all-selectable-tools contract test verifies that every available persisted tool selection is present in the resolved session registry.
- Expert Teams: member question → lead → `subagent_answer` round trip, refusal of a question that is no longer pending, mailbox ownership (session lead vs. auxiliary roles, scheduled jobs, and a team-bound ESM worker), and non-team sessions delivering member notifications without holding the run open.
- Agent loop: terminal-state coverage for a run cancelled during the member wait, and for a truncated turn recovered by a follow-up turn.
- Channels: the session mailbox shared by the sub-agent tools and the lead, plus a partial tool selection that must not be resurrected by re-registration.
- Delivery: reopen refusal for permanent failures, verified through both the operator entry and the persistence fence.
- Delivery: the WebUI endpoints cover listing, a successful retry, and the permanent/in-flight/unknown refusals; the Desktop projection covers the same verdict and its bilingual strings.
- Runtime: the orphan-recovery concurrency test now proves overlapping workers with a rendezvous instead of a timing window, so it no longer flakes under load.

## v1.2.99

### ✨ New Features

- **Unified Server-Resolved Model Catalog Across WebUI and TUI**
  - A new `GET /api/models/catalog` endpoint resolves every selectable provider/model through `providerfactory.ResolvedModels`/`SortProviderIDs` — the same shared logic that builds the TUI's provider model lists — and returns canonical defaults plus the sorted provider list. The active provider stays selectable even when it comes from a built-in preset or a serve flag instead of the settings providers map.
  - `stores.js` migrates `models` → `modelCatalog`; the Chat new-session picker now consumes the server catalog instead of merging raw settings JSON client-side, dropping the local `buildModelCatalog`/settings-fallback derivation. Settings surfaces (default provider/model dropdowns, provider editor) consume the same store, and inherited built-in preset models get dedicated zh/en labels.
  - The TUI auth dialog's provider sort delegates to `providerfactory.ProviderSortPriority`, so TUI dialogs and the WebUI catalog share one ordering logic.

- **Enable Supervisor Mode (ESM): Slash-Command Control, Shared Guidance, and Evidence Tracking**
  - WebUI ESM control moves to the same `/esm` slash command as the TUI (`/esm <objective>`, `/esm status|edit|pause|resume|clear|guide`) instead of dedicated graphical controls — the 500-line `ESMControls` component is removed, and chat input and the ESM REST API share one server-side objective path.
  - New guidance module: `/esm guide <text>` queues user guidance stamped with the objective's current version; the Supervisor injects pending guidance into every non-recovery role prompt and consumes it exactly once after the role result is applied — one core-owned lifecycle shared by the TUI and WebUI adapters.
  - New evidence module: a shared `EvidenceTracker` accumulates tool-call evidence per role run (unique tool-call IDs, per-tool counts/errors), so the "tool-backed evidence" checks in `ApplyWorkerResult`/`ApplyReviewResult` cannot diverge between adapters.
  - ESM no longer enforces token/time budgets: the `budget_limited` status, `SetBudget`/budget prompts, and the TUI `/esm budget` subcommand are removed; `TokensUsed`/`TimeUsedMS` remain observability-only counters. The blocked-audit threshold is centralized as `BlockedAuditLimit` (the objective becomes blocked after 3 consecutive runs report the same blocker).
  - Unattended derived runs resolve their execution mode through `agentruntime.ResolveUnattendedMode`: only `os` is inherited from the session mode and every other session mode falls back to `yolo`, so ESM role sub-agents never stop on interactive approval (hard high-risk-command protections remain mode-independent).
  - The Supervisor now runs continuations against the base Run ID (role runs use suffixed IDs derived from it), owns the terminal `FinishRun` call for both adapters, and clears stale streaks left by earlier continuations when a continuation ends.

### 🐛 Bug Fixes

- **ESM: Failed Objectives Pause Instead of Silently Re-running**
  - A non-retryable role failure now pauses the objective and requires an explicit `/esm resume` before it can run again — queued guidance or a future trigger can no longer silently re-run a failed task. Timeouts and retryable transport errors still take the recovery path bounded by `RecoveryLimit`.
  - Serve startup no longer replays historically persisted "active" ESM objectives: a role may have failed just before the process exited, so `Create`/`Edit`/`ResumeESM` are now the only explicit execution entry points.
  - `esmCoordinator` gains `stop`/`stopAll` with done-channels and bounded waits; Serve shutdown cancels every ESM worker and waits for it to release session/runtime references (`SessionRuntime.Shutdown` remains the final resource boundary), and a closed coordinator refuses to start new workers.

- **Native Directory Picker on Headless Servers**
  - The Unix native picker reports itself unavailable when `DISPLAY`/`WAYLAND_DISPLAY` is absent instead of failing silently, letting the Web UI fall back to its built-in directory browser. Launch failures that print diagnostics on stderr now surface as errors instead of being mistaken for a dialog cancel.

### 🔧 Improvements

- **Directory Browser: Windows Drive Roots and Path-Aware Allowed Roots**
  - `/api/browse` allowed-root resolution now takes the requested path, and Windows drive roots are listed through a virtual browse root (drive roots share no common parent for navigation). `DirBrowser` gains an `initialPath` prop, one-shot open semantics, a server-provided `selectable` flag, and refresh support.

- **Tool Recovery Audit Trail**
  - `RequestToolExecutionRecoveryRecords` records explicit user confirmation and returns only matching interrupted calls; the records are retained as audit evidence while recovery starts as a fresh execution, and a new DAO listing (`ListRequestedToolRecoveries`) exposes requested recoveries to Serve. Terminal Runs are never reactivated to consume these records.

### ✅ Tests

- ESM: new/expanded coverage for the guidance lifecycle (version stamping, injection, one-time consumption), evidence tracking, pause-on-non-retryable-failure, base-Run-ID continuations, budget removal, `/esm` slash-command parity, and coordinator `stop`/`stopAll` (including closed-coordinator start refusal).
- Serve: a process-level test asserts startup never replays historical ESM objectives; browse-root tests cover allowed-root resolution and Windows drive-root listing; native picker tests cover the headless-unavailable and stderr-diagnostic cases.
- Provider factory: catalog resolution and provider ordering tests; settings: `qwen3.8-max-0902` preset assertions.
## v1.2.98

### ✨ New Features

- **New Gitee/Moark Model: `qwen3.8-max-0902`**
  - Added `qwen3.8-max-0902` to the `gitee` and `moark` providers with a 1M context window, 128K max tokens, and text+image input.

### 🔧 Improvements

- **TUI: Dead Code Cleanup and Decision Lifecycle Alignment**
  - Removed unused functions (`renderLiveAssistantMessage`, `renderPlanPanel`, `formatPlanForDisplay`, `normalizeHistoryLineEndings`, `resolveESMStoreDir`, `updateViewportContentWithFollow`) and trimmed the associated plan/ESM test coverage.
  - Question requests are now registered through `DecisionService`, so pending questions persist and replay like approvals; duplicate question requests are rejected.
  - Terminal decision status is mapped from the actual run state instead of always marking pending decisions `cancelled` — only an explicit cancellation records `cancelled`, any other terminal outcome records `timed_out`.
  - The deferred print loop gained a `stopPrintLoop` exit path used on quit and reload so queued transcript lines are drained before teardown.
  - The external status-line refresh is deferred to actual renders, coalescing event-dense bursts into a single refresh.
  - `sessionsDel` now resolves the session directory through the defensive `getSessionDir()` helper.

- **WebUI: Settings Model Lists Match the New-Session Picker**
  - The settings "Default Provider / Default Model" dropdowns now reuse the same server-resolved catalog behind the new-session model picker (`GET /api/models/catalog`), so built-in preset providers and their default models stay selectable there too; unsaved form edits are appended after the catalog entries so they can be chosen before saving.
  - The provider settings reuse the same catalog: the sidebar model-count badge shows the resolved count, and the model list additionally renders built-in preset models that are not written to settings as read-only rows (matching the new-session picker; they are not persisted on save — add a model with the same ID to override).

### 🐛 Bug Fixes

- **Serve Responses Recovery Preserves Terminal Runs**
  - Recovering confirmed interrupted tool calls no longer changes a completed or failed durable Run back to `queued` or reattaches its terminal remote Responses task. Serve now submits a fresh, idempotent recovery message through the normal Runtime input path and starts a new local AgentLoop Run; the previous Run remains immutable.
  - Removed the recovery-only terminal-to-active Run-store APIs so future callers cannot bypass the canonical monotonic lifecycle.

### ✅ Tests

- TUI: new tests cover question decision registration (pending kind, persistence, duplicate rejection) and ESM store directory resolution.
- Serve: Responses recovery tests verify that the terminal parent is preserved, a fresh AgentLoop receives the recovery message, and repeated recovery requests reconcile idempotently to the same new Run.
## v1.2.97

### ✨ New Features

- **Online Model Discovery for Providers**
  - Provider model discovery moved into `internal/provider` as shared helpers (`ModelsEndpoint`, `ResolveSecretRef`, `DiscoverModels`) that fetch and normalize a provider's `/models` listing into `DiscoveredModel`s. The OpenAI-compatible `/v1/provider/models` and model-test endpoints now call these shared helpers instead of duplicating probe plumbing.

- **TUI: Fetch and Search Online Models in the Auth Dialog**
  - A new "Fetch Online Models" entry in the provider model list and model settings views runs discovery against the draft provider's Base URL / API type on a background command and opens an "Add Model · Online List" view where fetched models can be added to or removed from the draft. Nothing is persisted until the provider is saved, and stale results after closing the dialog or switching providers are dropped, with loading/empty/error states and zh/en labels.
  - Typing in the online list filters fetched models, ranked exact > prefix > substring across model ID and display name while preserving discovery order within the same score; Esc clears the query, and a "No models match." hint shows when nothing matches.

### 🔧 Improvements

- **Public SDK Boundary: `agent/` Stays Internal-Free**
  - The provider bridge moved from the public `agent/` package into `bootstrap/` (which external modules already blank-import); it registers the provider resolution hook plus the concrete provider factories at init time.
  - `agent.Builder` no longer pre-resolves the platform session directory (the internal builder resolves the default at Build time) and reports a clear error when a hook is unregistered; the examples now blank-import `bootstrap` instead of internal packages.

- **Session Store Integrity Hardening**
  - `DeleteSession` now prunes child tables without a `session_id` column (`delivery_operations`, `attachment_deliveries`) through their session-owned parents, so deleting a session leaves no orphaned rows.
  - Schema migrations apply in ascending version order instead of slice order; forward table references no longer depend on FK enforcement being disabled.
  - Non-terminal/terminal Run status sets are centralized in `run_store.go` as the single source of truth; SQL literals, partial unique indexes, fork, trajectory, and recovery paths all derive from them.
  - `EndConversationTurn` is idempotent for already-closed turns; conversation entry IDs grow to 64-bit; `IdentityLocks` delegates to a ref-counted lock registry, and the runtime lease bus closes its UDP listener once the last handler unsubscribes.

### 🐛 Bug Fixes

- **TUI: Instant Submit for a Lone Enter**
  - A queued Enter was treated as line-break evidence, so every quick type-then-Enter send waited the full 120ms split-paste coalescing window. The extended idle window now applies only when the queue carries real paste evidence (newline-bearing rune chunks or Enter adjacent to text); a lone deferred Enter keeps the normal 16ms window and submits immediately.

- **Missing Error Reason on Abandoned Durable Runs**
  - A background run abandoned after interrupted tool execution could reach a terminal status without persisting the reason. A dedicated annotation boundary (`RunDAO.UpdateErrorIfEmpty` → `session.AnnotateSessionRunError` → `agentruntime.AnnotateDurableRunError`) now sets the error only while it is still empty — without changing run status, reviving terminal runs, or touching active runs, keeping the first recorded reason authoritative. The Responses API abandon path persists the reason through this boundary.

- **Duplicate User Entry in the Background Run Coordinator**
  - The durable user entry appended during admission is already in replay state after the manager reload; the coordinator now matches the deterministic `RunUserEntryID` and reuses it as the continuation message instead of appending a duplicate to the transcript and the provider request. The check stays idempotent across retries, recovery, and process restarts.

- **Channel Rotation Lease Target**
  - `AcquireRuntimeForRotate` now takes the session directory explicitly from the lifecycle owner (falling back to the dispatcher's configured directory when empty), so the mutation lease and the forced-release wait target the authoritative Session instead of whatever directory the dispatcher holds.

### ✅ Tests

- Architecture: `public_sdk_boundary_test` fails if the public `agent/` package or `example/` modules import internal packages again.
- New session tests: delete integrity (no orphaned rows), ascending migration order, Run status-set consistency, ref-counted lock registry, and lease-bus listener cleanup; widened orphan-recovery timing margins under `-race`.
- Regression tests for the fast lone-Enter submit path (split-paste continuation still protected) and durable-run error annotation.

## v1.2.96

### ✨ New Features

- **Runtime Workspace Input Materialization**
  - A single front-end-neutral input contract now owns user files for every entry point (CLI, TUI, WebUI/API, ACP, WeChat, Feishu). Adapters submit source streams; `internal/agentruntime` materializes accepted files into the project workspace and the first user message declares file paths plus metadata, letting the Agent decide how and whether to read each file.
  - Images are no longer auto-converted to provider image content on ingest; input resources persist via the `input_resources` table with a Runtime-owned lifecycle (`PrepareInput`/`AttachPreparedInput`, discard/delete/cleanup, `input_resource_events`).
  - TUI `/paste-image` now submits a stream the Runtime writes; the Web UI gained attachment upload/preview in chat; ACP prompt content (text/image/file/audio/video) and WeChat/Feishu inbound media all normalize through this same ingress.

- **Lease-Based Execution Admission and Orphaned Run Recovery**
  - The legacy `TryLockRuntime`/`TryLockRuntimes` path was replaced with explicit, purpose- and run-bound runtime leases across CLI, TUI, ACP, Serve, channels, and cron: ref-counted durable lease guards (`AcquireExecutionAdmission`/`AcquireFork`/`AcquireMutations` and run binding) plus recovery/reconciliation modes for stale or orphaned runs.
  - A new `RecoveryCoordinator` converges orphaned runs lease-first through a startup scan and periodic/wake-driven retries, backed by the `session_run_recoveries` table with durable state, retry accounting, and idempotent replay.
  - The session runtime snapshot surfaces admission/recovery facts (`reserved`, `local`, `external`, `detached_remote`, `orphaned`, `recovery_failed`, `inconsistent`); the Web UI shows matching status badges and disables delete/fork while a session is busy.

- **Durable Delivery Outbox**
  - Delivery intents and ordered operations (`delivery_intents`/`delivery_operations`) with deterministic `PlanDelivery` sequences (caption/upload/send/fallback), a Runtime claim/fence/retry coordinator, terminal-state atomic commit of assistant message/Run/turn/event/intent, and service-start recovery.
  - WeChat (image/video/file) and Feishu (image/file) outbound media deliver natively through frozen transport contexts; published artifacts moved into a private store outside the work directory with integrity verification (size + SHA-256) on open.

- **Idempotent Run Submissions**
  - New `runtime_submissions` table with reconcile-on-conflict handling: submit-key conflicts reuse the existing submission instead of creating duplicates, making Run admission retry-safe.

- **New Volcengine Model: `glm-5.3-flash`**
  - Added `glm-5.3-flash` to the `volcengine`, `volcengine-agentplan`, and `volcengine-codingplan` providers with a 1M context window and text+image input; like `glm-5.3`, no default max_tokens is sent.

- **New Gitee/Moark Model: `glm-5.3-flash`**
  - Added `glm-5.3-flash` to the `gitee` and `moark` providers with a 1M context window, 128K max tokens, and text+image input.

- **New AMD Radeon Provider Support**
  - Added the `amd-radeon` vendor with Base URL `https://developer.amd.com.cn/radeon/api/v1` using the OpenAI-compatible protocol.
  - Added `DeepSeek-V4-Flash` (1M context) and `Qwen3.8-Flash-Next` (1M context) models.

### 🔧 Improvements

- **DAO-Only SQL Migration**
  - `internal/db` now owns process-wide SQLite/Bun connection lifecycle and transaction boundaries; all session, cron, stats, ESM, and delivery SQL moved into `internal/dao` persistence objects.
  - Removed the `internal/commondb` compatibility package and the delivery legacy bridge; the architecture guard enforces the DAO-only boundary with a minimal migration-owner allowlist.

- **Web UI Loading and State Stability**
  - Route views (Chat/Sessions/Stats/Cron/Skills/Settings/Login) are lazy-loaded so only the active route's chunk is fetched; lucide/bits-ui/svelte dependencies are grouped into stable vendor chunks.
  - Session runtime state (load/PATCH/polling/mode switching) moved into a unit-testable manager, and loaded history snapshots merge field by field so stale or empty persisted projections never erase live assistant text.

### 🐛 Bug Fixes

- **Cached Input Token Double Charge**
  - Usage accounting now computes uncached input tokens (`UncachedInputTokens`) instead of charging cache reads twice across Anthropic, OpenAI-compatible, and Google wire formats.

- **ListSessionRuns Connection Deadlock**
  - `ListSessionRuns` queried `input_resources` inside the `session_runs` rows loop, blocking forever on the single-connection pool and hanging TUI startup for continued sessions with run records. The outer rows are now drained before a single batched query, with a regression test asserting completion.

- **Durable-Run Terminal Event Stability**
  - `RunExecutor.Finalize` no longer publishes the terminal stream event for durable runs; `FinalizeRun` remains the single publisher after `FinishDurable` commits the assistant message, so WebUI history reloads cannot race the database write. Durable identity is recovered from the canonical Run row when the in-memory marker is gone, and already-closed conversation turns are tolerated so idempotent retries still commit the final entry and terminal event.

### ✅ Tests

- Architecture: `input_contract_guard_test` enforces the single input contract across TUI, CLI, WebUI/API, ACP, and Channel entry points.
- Extended admission/recovery tests for lease-first orphan convergence, execution snapshots, stop handling, idempotency, and cross-process lease behavior; delivery process integration tests for claim/fence/retry and coordinator recovery.
- Regression tests for cached-input-token accounting and the `ListSessionRuns` deadlock.

## v1.2.95

### ✨ New Features

- **New Gitee/Moark model: `qwen3.8-flash`**
  - Supports a 1M context window and text/image input; no max-token limit is sent by default.

- **Durable CLI Runs**
  - CLI `runPrint` now persists canonical durable runs via `agentruntime.ExecutionRuntime`, aligning the CLI path with WebUI, channels, and ACP lifecycle tracking.

- **UDP Runtime Lease Bus**
  - Added best-effort UDP `SessionLeaseBus` for local-process wake-up on runtime lease and run-state changes.
  - Uses directed loopback broadcast with deduplication; SQLite leases and durable rows remain the sole authority.

- **Per-Run Provider/Model Selection (API & Web UI)**
  - `POST /v1/responses` runs accept an optional `provider` field; qualified `provider/model` IDs are parsed and validated (with a structured mismatch error when the provider does not own the model).
  - The run executes with the requested provider's agent built through the shared `SessionRuntime`; run policy snapshots and request fingerprints now record the provider.
  - `/v1/models` now reports each model's provider.

### 🔧 Improvements

- **ClawHub Ambiguous Skill Slug Resolution**
  - When ClawHub returns `409 AMBIGUOUS_SKILL_SLUG` for a bare skill slug, the client now auto-resolves the unique exact-slug match and retries once with the resolved owner, so installing skills like `clawhub.ai/custom-mail-fresh100` works without requiring the `@owner/slug` form.
  - When matches do not identify one candidate, a descriptive error lists every candidate ref instead of exposing the raw 409 payload.

- **Unified Bun Database Access**
  - Added a shared `internal/db` SQLite/Bun connection and transaction layer, with DAO persistence objects for cron, usage statistics, ESM objectives, and channel bindings.
  - Removed the `internal/commondb` compatibility package. Shared connections and shutdown now live in `internal/db`; Bun-backed DAOs own migrated table access, and session transaction helpers use the DAO-owned Bun handle.

- **Event Broker Resync**
  - Event broker now exposes `SubscribeWithResync`; subscriber overflow closes the WebSocket so the client reconnects and replays durable SQLite cursors.

- **Runtime Lease Heartbeat**
  - Lease heartbeat now retries transient SQLite failures for a bounded interval and publishes `acquired`/`released`/`lost` notifications.

- **Session Capabilities (Sandbox/Browser/Web Search)**
  - `SessionRuntime` gains `CapabilitySnapshot`, `ConfigureCapabilities`, and `SetCapabilityOption`; browser and web-search capabilities persist via `session_capabilities` and replay on load, with core tools synchronized accordingly.
  - ACP sessions restore persisted capabilities and additional directories under the runtime lease; sandbox remains process-policy-owned.

- **Web UI Provider-Aware Model Picker**
  - New searchable `ModelPicker` component with modality icons (text/image/audio/video/file) replaces the old model menu.
  - Chat composes a provider-cascading model catalog from `/v1/models` plus configured providers, so selecting a provider narrows to its models and submits the provider with each run.

- **ACP Session Extension Methods**
  - Added `session/fork` and `mothx/session/setTitle` handling, workspace-window negotiation (`cwd`/additional directories), a cascade delete across fork lineage, and an `available_commands_update` notification.
  - Optional editor context is injected as a bounded, untrusted context block; loading historical sessions with a released runtime lease no longer rewrites persisted bindings.

### 🐛 Bug Fixes

- **Background Run Optimistic Concurrency**
  - Reloaded the shared session manager after durable admission so the background coordinator appends the user message to the new leaf instead of failing its optimistic concurrency check.

- **WeChat iLink Inbound Connection Recovery**
  - The WeChat adapter now sends iLink start/stop lifecycle notifications, reports connected only after a successful `getupdates` poll, adopts the server's long-poll timeout, and persists the iLink sync cursor across restarts.
  - Requests now identify the MothX channel version and bot agent, and malformed iLink responses are surfaced instead of being silently treated as empty polls.

### ✅ Tests

- Acquired the runtime lease in `TestResponsesRunAPIAbandonMarksInterruptedToolsWithoutRetry` before inspecting the abandoned tool record, matching the production recovery caller pattern.
- Added ACP tests: loading a historical session with a released lease must not persist defaults, directory updates under the runtime lease, and title changes on historical sessions.
- Added serve tests for per-run provider selection, provider/model mismatch, and qualified-model parsing.

## v1.2.93

### 🐛 Bug Fixes

- **GHCR Image Builds Use Go 1.27**
  - The Docker builder image is now `golang:1.27.0-bookworm`, matching `go.mod`, so GHCR packaging no longer fails with `go.mod requires go >= 1.27 (running go 1.26.1; GOTOOLCHAIN=local)`.

- **Desktop Version Follows Git Tags**
  - Desktop `package.json` keeps a `0.0.0` placeholder instead of a hardcoded release number.
  - Packaging resolves the real version from `MOTHX_VERSION` if set, otherwise the current git tag (`git describe --tags --abbrev=0`), and writes it into `package.json`, `package-lock.json`, and `mothxRuntime.version` at build time.
  - Desktop CI no longer treats a branch name as the version; it uses an explicit tag override or the checkout's git tag.

### 🔧 Improvements

- **ACP Installation Diagnostics**
  - `initialize.agentInfo` now reports the real MothX identity and build version.
  - Added session-free `mothx/doctor`, `mothx doctor --json`, and structured `MOTHX_ACP_ERROR` startup diagnostics with secret-free checks.

- **CI Test Workflow Cleanup**
  - Removed the per-commit GitHub Actions test workflow so tests no longer run on every push.

## v1.2.92

### ✨ New Features

- **Session Fork & Message Branching**
  - Sessions can now fork from any message and branch into alternative continuations; execution intent is wired through fork paths with a runtime lock.
  - Session schema and migrations, run/response stores, entry handling, ESM guidance, the background run coordinator, and the dispatcher all support forks; TUI session commands/runtime and Web UI chat/sessions views are updated.

- **WebUI Trajectory View & Session Log Export**
  - A read-only trajectory projection in the Serve Web UI organizes session messages, tool events, and run events by run/turn/step without forking Agent/Runtime state.
  - Server-side session trajectory and export endpoints live under the existing session route, and the session header gains a log download action (optionally including descendant sessions).

- **WebUI Modernization with shadcn-svelte & lucide**
  - Added Tailwind CSS v4 and shadcn-svelte style components (button, badge, card, dialog, input, switch, tabs, tooltip) with the `$lib` alias and `cn()` utility.
  - Replaced text glyphs with lucide-svelte icons across the sidebar, sessions, settings, and list editor views; added a brand logo mark, a workspace filter menu (all/projects/ungrouped), and a Ctrl+Shift+K new-chat shortcut.

- **Authored-commit Co-Author Setting**
  - A new global "authored" setting (default off) appends the MothX co-author trailer to system prompts, guiding the model to include `Co-Authored-By: MothX <harness@mothx.net>` when creating git commits.
  - Wired through config persistence, the TUI settings dialog, and the Web UI settings form with bilingual labels.

- **New Provider Models**
  - DeepSeek (anthropic + openai): added `deepseek-v4-flash-vision-exp` with 1M context, text+image input, and no default max_tokens.
  - Volcengine codingplan: added `doubao-seed-evolving` with 1M context and text+image input.

### 🔧 Improvements

- **Default Mode is YOLO**
  - New installs and empty-mode fallbacks now use `yolo` instead of `agent`: `settings.json` `defaultMode`, Serve/API `DefaultMode`, CLI/TUI/ACP/WebUI, public SDK `Builder`, and `agentruntime` policy resolution.
  - Explicit `--mode`, persisted session mode, and WeChat/Feishu forced `yolo` still take precedence. Existing configs that set `defaultMode: "agent"` are unchanged.

- **Native Directory Picker for Serve**
  - Serve now opens the operating system's native directory picker (macOS, Windows, Unix) for selecting a working directory instead of typing a path.

- **Unified Settings Components**
  - Extracted shared `SettingsField`, `SettingsSection`, `SettingsSwitch`, and `ProviderEditorDetail` components and unified settings view layout/styling across AppSettings, ServeConfig, Channels, Env, Logs, Memory, Overview, SkillHub, and WorkDir.

### 🐛 Bug Fixes

- **WebUI Sidebar & Session ID Fixes**
  - Sidebar collapsed state now persists in localStorage, with collapse/expand labels.
  - Removed the unused trajectory timeline mode, state, translations, and layout helper.
  - Fixed `AllocateSessionID` to treat "not registered in DB" as available after `sessions.db` exists, with a regression test.

## v1.2.91

### ✨ New Features

- **ACP Session Admission Control**
  - ACP prompts now acquire the shared session runtime lock and check the durable active-run row before starting, serializing the ACP entry point with the TUI, WebUI, and channels.
  - The runtime lock is held for the full lifetime of an admitted run so no other adapter can race its terminal persistence with a new run; a session with an active run is rejected with `session already has an active run`.

- **WebUI Server-Allocated Session IDs**
  - The WebUI now requests its session ID from the server (`POST /api/session-id`) instead of generating one in the browser, making session identity canonical while preserving the delayed-creation "new chat" UX.
  - Server-side allocation deduplicates against reserved and existing session IDs and expires stale reservations after 10 minutes; browser-side random ID generation remains only for run request keys.

- **Session Duplicate ID Rejection**
  - Creating a session with an ID that already exists now fails with `ErrSessionIDExists` instead of silently merging the new header into the old session and forking the conversation.
  - Auto-generated IDs retry on collision (up to 8 attempts); the session header write uses a plain INSERT so duplicate IDs are detected reliably.

### 🔧 Improvements

- **Unified Session Creation**
  - TUI, serve, and CLI now create sessions through `agentruntime.CreateSession` instead of constructing `session.New(...).Init()` directly, centralizing session creation in the shared runtime.

## v1.2.90

### ✨ New Features

- **New Gitee/Moark model: `qwen3.8-27b`**
  - Supports a 1M context window and text/image/video input; no max-token limit is sent by default.

- **ACP Session Config Options**
  - ACP now supports `session/set_config_option` and `session/set_mode` RPC methods, enabling clients to change model, mode, and thinking level per session without rebuilding the agent or provider.
  - Each session carries a consistent `configOptions` catalog in `session/new`, `session/load`, and `session/resume` results, and `session/set_config_option` notifies all connected clients of the updated options.
  - Configuration is persisted to the session history (`model_change`, `mode_change`, `thinking_level_change` entries) and replayed on session load, so bindings survive restarts and survive across multiple adapters sharing the same session.
  - Stable streamed message IDs (`messageId` on `agent_message_chunk`, `agent_thought_chunk`, and `user_message_chunk` updates) group chunks into logical messages per prompt turn.

- **ACP Additional Directories**
  - `session/new`, `session/load`, and `session/resume` accept an `additionalDirectories` array of absolute workspace roots. The tool registry resolves paths within these roots, and the sandbox mounts them as read-only (strict mode) or writable paths.
  - Directory sets are persisted as `additional_directories` session entries and restored on reload.
  - The session list endpoint (`session/list`) exposes `additionalDirectories` per session.

- **ACP Standard Elicitation Form Protocol**
  - When the client advertises `elicitation.form` in client capabilities, question requests use the standard ACP `elicitation/create` method instead of the legacy `_mothx/request_question` extension, with a typed `requestedSchema` envelope.
  - Replay gracefully falls back to the legacy extension shape when a reconnecting client does not advertise form support.

- **ACP FileDiff Protocol Projection**
  - Tool call updates now include a `diff` content type with `path`, `oldText`, and `newText` fields for semantic diff representation, alongside the existing text content. `oldText` is `null` for newly created files.
  - Tool call updates carry `locations` with the affected file path when a diff is present.

### 🔧 Improvements

- **Session Mode and Thinking Level Persistence**
  - New `EntryModeChange` and `EntryAdditionalDirectories` session entry types record mode switches and directory bindings to the session history, enabling full replay and cross-session consistency.
  - The `SessionRuntime` owns `Model`, `Mode`, `ThinkingLevel`, and `AdditionalDirectories` as session-scoped bindings, with `ConfigureSession`, `ConfigSnapshot`, `SetConfigOption`, and `SetAdditionalDirectories` methods for atomic read/write.
  - `BuildAgent` inherits session-level model, mode, and thinking level when the adapter omits overrides, ensuring consistent agent construction across ACP, TUI, and WebUI.

- **ACP Strict JSON-RPC 2.0 Validation**
  - The ACP server now enforces: `initialize` must be called before any other method, `initialize` may only be called once, empty messages are silently skipped, responses to notifications (empty ID) are suppressed, and request IDs are validated as JSON-RPC scalar types.
  - `cancel` requires a `sessionId` parameter and returns an error for unknown sessions.

- **ACP Unique Run IDs Across Connections**
  - Prompt run IDs now include a random suffix, preventing run ID collisions when ACP SDK request IDs repeat across connections.

- **CI Release Notes from Changelog**
  - GitHub release workflows now use `docs/changelog_online_en.md` as the release body instead of auto-generated release notes, ensuring releases carry the curated changelog.

- **FileDiff Enriched with OldText/NewText**
  - `FileDiff` now retains the complete file contents (`OldText` and `NewText`) for protocol projections that require a semantic diff rather than a display patch. `OldText` is `nil` when the write created a previously absent file.

- **ContentBlock File Fields Extended**
  - `FileContent` now carries `Title`, `Description`, and `Size` fields, and the ACP `resource_link` prompt type maps these fields into the provider-neutral file representation.

### 🐛 Fixes

- **ACP Missing Prompt Body Rejection**
  - Prompts with only empty text are now rejected with an `empty prompt` error instead of proceeding to the agent loop.

- **ACP Flaky Test and CI Stability**
  - Fixed wrapped thinking text assertion and flaky Go tests in CI.

## v1.2.89

### 🐛 Fixes

- **Error Message Leak Protection**
  - Model discovery errors in the Serve API no longer reflect upstream response bodies, preventing credentials, private diagnostics, or arbitrary HTML from leaking to the client. The HTTP status code alone is sufficient to explain a model-discovery failure.
  - Preflight error info in run submission now clears the `Detail` field, so raw parser/storage diagnostics are never projected through `DisplayErrorMessage` to the adapter.

### 🔧 Improvements

- **ACP Session Model Configuration**
  - ACP now parses `HARBOR_ACP_REQUESTED_MODEL`, advertises session model/mode/thinking options, persists per-session bindings, and routes agent construction through the shared Session Runtime. Standard config/mode updates, capability-gated form elicitation and `session_info_update`, stable streamed message IDs, multi-session isolation, and invalid-model errors are covered by Go stdio process tests. Harbor compatibility validation remains an explicit external check and is not part of default tests or CI.

- **Version Resolution from CI Branch**
  - The `Makefile` now prefers the `GITEE_BRANCH` environment variable for version string resolution, falling back to `git describe` and then `dev`. This ensures CI builds carry the correct release tag.

## v1.2.88

### ✨ New Features

- **ModelScope Model List Refresh**
  - Expanded the `modelscope` provider to the full 45-model catalog served by `https://api-inference.modelscope.cn/v1`: DeepSeek V4 Pro / Pro-0813 / Flash-0731, Qwen3.5-27B / 35B-A3B / 122B-A10B / 397B-A17B, Qwen3.8-27B, the Qwen3 base / Instruct / Thinking / VL / Next / Coder series, Intern-S1 / S1-mini / S2-Preview, InternVL3.5-241B-A28B, MiniMax M1-80k / M3, GLM-4.7-Flash / GLM-5.2, Step 3.5 / 3.7 Flash, Tencent Hy3, ERNIE-4.5 PT series, and more — each with per-model context, reasoning, and input (text/image/video) capabilities.

### 🔧 Improvements

- **Provider Error Detail in Run Failures**
  - `ErrorInfo` now carries a `Detail` field that preserves the bounded (4KB max) and credential-redacted provider diagnostic alongside the safe fallback `Message`. A new `DisplayErrorMessage()` combines both for adapter consumption, so run failures never drop provider context.
  - The detail propagates through ACP, channels, TUI, the Serve API (events, chat handler, run executor, run API, and session stream), and the Web UI, where localized messages append the diagnostic output.
  - `IsRetryable` now treats all 4xx/5xx HTTP status codes as retryable, with numeric status matching in error strings.

### 🐛 Fixes

- **TUI Compact View Hides Thinking**
  - Fixed an issue where compact event display rendered thinking as empty strings, hiding reasoning content from the transcript. Thinking is now rendered in both compact and full event views, so reasoning is no longer lost and switching to the full view does not duplicate it.

- **Web UI Image Preview Accessibility**
  - Image thumbnails in messages are now keyboard-activatable buttons with proper labels instead of bare clickable images, and the lightbox overlay is keyboard-focusable with Enter/Space to close, resolving accessibility warnings and improving keyboard navigation.

- **Embedded Web UI on Fresh Checkout**
  - A placeholder is now tracked in `ui/dist` so the `//go:embed` directive always matches before the production UI has been built, and the dist ignore rules were anchored accordingly.

## v1.2.87

### ✨ New Features

- **Parallel Tool Execution with Configurable Concurrency**
  - Local function and custom tool calls within one agent turn now run through a bounded parallel worker pool. A new top-level `toolExecution` setting controls the behavior: `mode` (`"parallel"` or `"sequential"`) and `maxConcurrency` (default `10`; `1` runs serially).
  - The setting is exposed in the Web UI under Settings > Tools and in the TUI under `/settings` > Behavior, applies to TUI, Web UI/Serve, channels, and ACP runs, and is inherited by sub-agents and transient agents.
  - Tool completion events may stream out of order, while provider continuation messages are restored in the original call order.

- **TUI Compact Event View**
  - Compact event display is now enabled by default for new and existing sessions. Routine lifecycle, usage, hosted-item, and compaction details stay hidden until `Ctrl+G` switches to the full event view; active tool rows are replaced by their completed result.

- **OS Execution Mode**
  - Added `os` as a bash-only, no-sandbox execution mode across the shared runtime, TUI, WebUI, channels, ACP, and sub-agents. Normal bash calls auto-execute, configured blacklist rules still require approval, and hard high-risk command blocks remain enforced.

- **New Model: `deepseek-v4-pro-0813`**
  - Added the `deepseek-v4-pro-0813` snapshot to the Gitee and Moark providers. It carries a 1M context window, reasoning support, and no default max-token override (the max-token limit is published by the vendor and not sent by default).

- **Web UI Image Lightbox**
  - Added an image lightbox overlay with keyboard navigation (Esc/arrow keys), prev/next buttons, open-in-new-tab, and an image counter.
  - Message image thumbnails are now larger with a hover zoom-in affordance, and input-area image preview cards have been restyled.

### 🔧 Improvements

- **Provider Parallel Tool Call Support**
  - Anthropic, Google, and OpenAI adapters now request parallel tool calls where supported and honor `supportsParallelToolCalls: false` for gateways that reject the flag.

- **Anthropic Tool-Choice Compatibility Flag**
  - Added the `supportsToolChoice` compat flag; Anthropic Messages omits `tool_choice` entirely when the model sets it to `false` (for gateways that reject the field), independent of parallel-tool-call controls.

- **Settings Compat Deep-Copy Fix**
  - `cloneModelCompat` now deep-copies every compatibility field (`SupportsToolChoice`, `SupportsParallelToolCalls`, hosted tools, supported includes, reasoning-effort/strict-mode flags, etc.), so resolved model configs no longer alias the original settings.

- **Channel Approval Parity for OS Mode**
  - Channel runs in `os` mode now follow the same auto-approval rules as `yolo`; high-risk bash commands still require approval.

- **TUI Bash Tool Result Display**
  - Bash tool results now show command status inline: `(running)`, `(succeeded)`, or `(failed (exit code N))`.
  - Status is derived from tool execution state, error, and exit code for accurate feedback.

- **Tool Execution Protocol in System Prompt**
  - The system prompt now declares the tool execution protocol (parallel vs. sequential and the per-batch concurrency limit) so the model's tool-call grouping agrees with the local executor.
  - A single-item fast path in the bounded parallel worker pool skips goroutine/channel overhead for the common one-tool turn.

- **Approval/Question Snapshot Delivery**
  - Runtime snapshots are now published alongside approval/question events, so clients that missed the live frame (dropped WebSocket, late subscribe) still see pending decisions via the runtime projection.
  - A post-replay runtime snapshot is sent on WebSocket subscribe/resume to close the gap between durable replay and live event forwarding.
  - The active run ID is included in 409 conflict responses so clients can reconcile their view and surface the stop control.

- **Cross-Surface CI**
  - Added a GitHub Actions workflow with Go, Web UI, desktop, and installer jobs, plus `make test-all`/`test-ui`/`test-desktop`/`test-npm`/`test-pypi` targets.

### 🐛 Fixes

- **Approval Recording Self-Deadlock**
  - Approval requests are now persisted outside `approvalMu`, so recording approval no longer blocks the Agent on its own mutex.

- **Approval Auto-Deny on Run Cancellation**
  - When a run is cancelled during approval persistence, the pending request is auto-denied with a resolution record instead of leaking a pending state.

- **Session Execution Concurrency Hardening**
  - `APISession.Execution` is now guarded by an RWMutex via `ensureExecution()`/`executionRuntime()` accessors, so background tool progress and request handlers can no longer race on the session execution.
  - Added nil-safety for the agent manager in the ESM coordinator's `RunRole` and fixed SSE `readSSE` CR/LF chunk boundary handling in the Web UI.

## v1.2.86

### ✨ New Features

- **Provider Retry for OpenAI Background Runs**
  - OpenAI Responses background run requests now carry idempotency keys and retry retryable failures with exponential backoff, honoring the configured retry policy.

- **Channel Runtime Settings Sync**
  - Channel (WeChat/Feishu) runs and sub-agents now use the same provider/model/retry configuration as the Web UI; applying settings through the serve API rebuilds the channel dispatcher runtime.

### 🔧 Improvements

- **Immediate Retry Settings Application**
  - The TUI now applies retry settings to the active provider right after saving, without requiring a restart.

- **Serve Settings API Error Reporting**
  - The serve settings API now returns HTTP 500 with the error detail when applying settings fails, instead of only logging it.

- **GLM 5.3 Replaces GLM 5.2**
  - `glm-5.2` has been discontinued by most vendors and is replaced with `glm-5.3` across all affected providers: Z.AI (`zai`, `zai-coding-cn`), Gitee AI, Moark, Volcengine AgentPlan/CodingPlan (where only the existing `glm-5.3` entry remains), Alibaba Bailian Token Plan, Huawei ModelArts, JD Plan, Baidu Qianfan Token Plan, CodePlayz (`opencode-go`), OpenRouter (`z-ai/glm-5.3`), Vercel AI Gateway (`zai/glm-5.3`), and Cloudflare Workers AI (`@cf/zai-org/glm-5.3`). All remain text-only input models.

### 🐛 Fixes

- **TUI Esc Abort Finalizes the Durable Run**
  - Pressing Esc now cancels and finalizes the durable run before the next input is accepted, and run-start failures are surfaced as an error instead of silently stalling.
  - Stale events buffered on a cancelled run's stream are ignored once a new run installs its event channel, so they can no longer mutate or interrupt the next run.

- **Web UI Stale Run Event Filtering**
  - Delayed events from a superseded run are filtered after a replacement run is accepted or after a refresh, so an abandoned stream can no longer overwrite the active run's transcript or status.
  - Run lifecycle versioning guards history reloads, runtime snapshots, response-run polling, and stop handling against out-of-date responses.

## v1.2.83

### ✨ New Features

- **Unified Agent Runtime**
  - Introduced `internal/agentruntime` as the canonical runtime layer shared by TUI, Web UI/Serve, channels, ACP, and A2A.
  - Consolidated session lifecycle, durable run persistence, decision/approval state, run events, and delivery into one path.
  - Adapters now project canonical events to their respective protocols instead of maintaining parallel state machines.

- **Web UI Project Session Management**
  - Added project-scoped session list with search, rename, and delete actions.
  - Empty or unnamed sessions are filtered from history; generated session titles are persisted.
  - Session metadata is now stored and exposed through the serve API.

- **ESM Backend Task System**
  - Added Extended Streaming Mode backend tasks with unified runtime adapters.
  - ESM objectives, progress, and recovery state now flow through the shared runtime.

- **Web UI Cookie Authentication**
  - Serve now supports cookie-based authentication for the Web UI.

### 🔧 Improvements

- **Runtime Controls**
  - Added max thinking level configuration and stabilized runtime control state across reconnects.
  - Work progress is now shown while runs are starting.

- **Error Handling**
  - Unified error handling and retry logic across all adapters.

### 🐛 Fixes

- **SkillHub Preflight**
  - SkillHub install preflight now stays read-only.
- **Session Titles**
  - Latest generated session title is preserved correctly.

## v1.1.82

### ✨ New Features

- **Interactive TUI Internationalization**
  - Added `tuilang` configuration in `settings.json` with `auto`, `zh`, and `en` modes. `auto` selects Chinese only at UTC+08:00; the `/settings` menu supports global/project persistence and applies successful changes immediately.
  - Slash command syntax remains English regardless of the selected display language.

### 🔧 Improvements

- **Unified Run Terminal Status**
  - Every agent run now emits one canonical `EventRunFinished` event with a `TaskStatus` of `success`, `incomplete`, `failed`, or `canceled`.
  - TUI, Web UI/Serve, channels, A2A, ACP, sub-agents, and workflows now classify results from this event; legacy `EventDone`/`EventError` events remain available for compatibility.
  - Cancellation caused by user abort, timeout, or context cancellation is reported distinctly as `canceled`; the TUI shows a status notice instead of a red error.
  - Event consumers now report a protocol failure when a stream closes without a terminal event, instead of treating it as a successful completion.

- **Provider Reliability**
  - OpenAI Responses streams now retry eligible failures reported as stream events.

- **Debugging**
  - Interactive TUI runs now print the one-time pprof server address to the terminal at startup when `--debug` is set; continuous provider debug output remains in `debug.log` via `VIBECODING_DEBUG_LOG_ONLY`.

## v1.1.79

### 💥 Breaking Changes

- **Workflow DSL Migration to JavaScript**
  - Replaced Emacs Lisp-based workflow DSL with JavaScript implementation using goja runtime.
  - Removed `vibeEmacsLispVm` dependency and Elisp evaluator.
  - Provided built-in functions: `agent`, `phase`, `parallel`, `series` for workflow definitions.
  - **Breaking**: Workflow DSL syntax changed from Elisp to JavaScript. Users need to update their workflow definitions accordingly.
  - Preserved existing workflow semantics and API compatibility.

### 🐛 Bug Fixes

- **Channel Run-State Synchronization**
  - Fixed channel (WeChat/Feishu) run-state desynchronization: cancelling a channel run now also aborts the agent (matching the background runtime), so waits that ignore context cancellation can no longer hold the session runtime lock forever and make `/new` report a phantom active run.
  - Root-fixed lost sub-agent terminal events: `AgentManager` now exposes terminal lifecycle listeners, and the channel dispatcher maps each run's root agent to its session so `done`/`error` states of children that outlive the parent event stream (async `subagent_spawn`, run cancellation, forced rotation) are still delivered to observers instead of leaving sub-agents stuck on "running" forever; the external sub-agent sink deduplicates terminal events delivered through both the stream and the listener.
  - Fixed a test-fixture race where channel sub-agent test providers dispatched responses by global call order while the parent follow-up call and the child's first call race; providers now route by request content, making the sub-agent observer tests deterministic.

### ✨ New Features

- **Channel Run Management**
  - Added a channel run watchdog: runs with no agent events for `agent.run_stale_timeout_secs` (default 600s) or exceeding `agent.run_max_duration_secs` (default 4h) are force-stopped and their persisted run state converges to a terminal status.
  - Added the channel `/stop` command, `/new force` and `/clear force` (cancel the active run, wait a grace period, then rotate), a busy hint for non-forced rotation, run-state details in `/status`, and a queued-message notice when a previous message is still executing.
  - Channel rotation no longer blocks on the session runtime lock in the dispatcher fallback path; both rotation paths now share the same try-lock + force semantics.
  - Durable background polling now has a hard cap (`api.backgroundRunMaxSeconds`, default 6h) in both the live and post-restart recovery loops, so a remote run that never reaches a terminal state releases the session runtime lock as `incomplete`.
  - Agent question prompts now also return on context cancellation, so unattended runtimes never block a run forever waiting for an answer.

## v1.1.78

- Background `Idempotency-Key` submissions now record a non-sensitive request fingerprint in existing run events; reusing a key with a different message returns an explicit conflict while compatible retries still reuse the original run, with no schema change.
- Tool execution record reuse now verifies session/turn/provider/tool/argument identity and rejects execution-key collisions instead of reusing a potentially unsafe result.
- Tool result writes are now state-conditional, so late results from an old process cannot overwrite an abandoned or newly recovered record.
- The TUI now discovers non-terminal durable background runs from the shared session database and replays assistant text after the submission boundary when they finish, preserving results across restarts.
- Channels background completion events now retain the canonical assistant entry and a pending-delivery marker; after a dispatcher restart, the next inbound message reconciles the final text/attachments and records delivery to prevent duplicates.
- Restricted channel background tool start/end summaries are now persisted in run events and replayed in order before the final result after a restart.
- Channels now also receive restricted tool status through the existing `ProgressFunc` during live background execution, with run events remaining the reconnect fallback.
- Responses attachment normalization and the WebUI now reject localhost, private, loopback, and link-local HTTPS URLs while retaining provider references for audit.
- Added an optional provider-specific file resolver: Serve only downloads file refs archived in the session, and the WebUI exposes a file attachment download action without proxying arbitrary URLs or refs.
- Added a regression test proving the attachment route accepts an optional non-OpenAI resolver without changing the common Provider interface.
- OpenAI Responses hosted items now use a package-local descriptor registry for capability, resume, and attachment policy; unknown upstream types remain archived without guessed execution or downloads.
- Background Responses `incomplete` runs now preserve partial text, attachments, and `incomplete_reason` instead of being incorrectly converted to `failed`.
- Background poll/recovery now reuses native replay for explicit remote-state invalidation (permission, 404/410, lineage, or expiry); ordinary 429/5xx errors do not trigger fallback, and each local run is replayed at most once automatically.
- Code Interpreter now accepts MothX-private `mothx.maxCalls`/`mothx.timeoutSecs` inside the existing hosted config map; these fields are stripped before upstream requests, quota-limited background results remain `incomplete`, and timeouts cancel the runtime.
- Remote MCP hostnames now receive a confirmatory DNS private-network preflight; only confirmed private/loopback/link-local resolutions are rejected, while DNS failures/timeouts remain allowed and upstream egress remains authoritative.
- Code Interpreter file citations now retain `container_id` provenance and use the OpenAI container-file download endpoint; ordinary file refs retain their existing behavior.
- The WebUI now reads Responses attachment-download capability from `/api/capabilities`; it hides downloads only when the server explicitly reports unsupported, preserving unknown-provider availability.
- WebUI capability loading now degrades independently, so older servers or unavailable capability APIs do not block session and chat data loading.
- `/api/capabilities` now also exposes provider-neutral `attachmentDownload`, so non-OpenAI providers can advertise download support through the optional resolver.
### 🔧 Improvements

- **Responses hosted lifecycle and recovery auditability**
  - Hosted item added/done lifecycle now flows through the provider, agent, Serve, TUI, channels, WebUI, and public SDK; states are available over SSE/transcript and replayed through run events after reconnect.
  - Hosted state projections use a shared field allowlist, scalar checks, and length limits. Interrupted tool execution is reported as `interrupted` instead of an ordinary failure or implicit retry.
  - Tool recovery records whether it was automatic read-only recovery or explicitly user-confirmed; channels use scoped idempotency keys when a platform provides a stable message ID.

### 🧪 Tests

- Added hosted lifecycle fixtures, capability-profile, recovery-audit, cross-entry event-bridge, and race-test coverage.

### ✨ Features

- **Web UI MCP Configuration**
  - Added global MCP configuration editing in Settings and project-level MCP configuration from the active session, using the shared `mcp.json` schema.
  - Supports `stdio`, streamable HTTP, and legacy SSE transports, including command arguments, request headers, environment variables, templates, validation, and atomic persistence.
  - Newly created Serve sessions load the saved project/global MCP configuration and register MCP tools before the agent prompt is frozen.

- **Native OpenAI Responses Web Search**
  - OpenAI Responses providers now expose the native hosted `web_search` capability automatically, without requiring the MothX-local web-search setting.
  - Native provider tools are kept distinct from the configurable local search toggle and are deduplicated when both resolve to the same upstream hosted tool.

- **Large Tool Result Pre-Compaction Summaries**
  - Tool results exceeding the large-result threshold are summarized independently before conversation-wide compaction, preserving file paths, identifiers, commands, errors, decisions, and other continuation-critical facts.
  - Summaries run with bounded parallelism and retry transient rate-limit failures, reducing context pressure while keeping the original tool-result ordering and identity intact.

### 🔧 Improvements

- **Provider Stream Idle Timeout and Automatic Retry**
  - Streaming HTTP clients no longer impose a hard 30-minute wall-clock limit. They now time out only when the upstream stops sending data, so active long-lived SSE streams can continue indefinitely.
  - Agent turns that time out before producing visible output automatically retry up to twice, with progress surfaced to messaging channels and a friendly final error when retries are exhausted.

- **Compaction Timeout and Configuration Cleanup**
  - Compaction no longer uses a separate five-minute deadline; provider streaming timeout and caller cancellation remain authoritative.
  - Removed unused idle-compression settings and UI controls. Compaction now runs in response to context pressure or explicit requests only.

### 🧪 Tests

- Added coverage for stream idle-timeout handling, automatic retry and recovery, large tool-result compaction, rate-limit retries, and the updated compaction behavior.

### ✨ Features

- **Channel Sub-Agent Visibility in the Web UI**
  - Channel-owned sub-agent events are now bridged into the Web UI session runtime, so live progress, tool calls, results, completion states, and transcripts are available through the existing sub-agent views and APIs.
  - Added `/help` to channel commands and synchronized channel sub-agent lifecycle updates without transferring runtime ownership from the channel dispatcher.

### 🔧 Improvements

- **WeChat Message Delivery**
  - Long replies are now split safely at UTF-8 boundaries and include the remaining-delivery count. When the per-message push limit is reached, additional chunks are queued and can be fetched with `/more`.
  - Progress messages share the same delivery budget, and inbound WeChat message IDs are preserved for channel-scoped idempotency and delivery tracking.
  - Truncated HTTP/SSE responses (`io.ErrUnexpectedEOF`) are now treated as retryable provider failures.

### 🧪 Tests

- Added channel sub-agent integration, external sub-agent HTTP, dispatcher lifecycle, MCP editor, session view, WeChat chunking/delivery, and truncated-stream retry coverage.

## v1.1.77

### ✨ Features

- **`disableSamplingParams` Per-Model Compat Flag (Default: On)**
  - Added `compat.disableSamplingParams` (tri-state) to model config. It defaults to on: `temperature`/`top_p` are no longer sent to any model unless the model explicitly opts in with `"disableSamplingParams": false`.
  - Editable in the TUI (`/auth` → model → E. Compatibility → Disable Sampling Params, cycles auto → enabled → disabled) and in the Web UI settings model table (Sampling column, checked = send params).
  - Note: OpenAI-compatible clients that pass `temperature`/`top_p` to the serve API now need the model to opt in for those values to reach the provider.

### 🔧 Improvements

- **Web UI Historical Session Sorting and Timestamps**
  - Session lists are now sorted by last-used time in descending order, with the most recently replied-to session at the top.
  - The Web UI session-management page shows each session's last reply time; the sidebar history keeps the newest-first ordering without displaying an extra timestamp.

- **Sampling Params Suppressed for Thinking/Reasoning Models**
  - Anthropic: `temperature`/`top_p` are now dropped automatically when extended thinking is enabled, matching the API requirement that rejects sampling parameters alongside `thinking`.
  - OpenAI: chat-completions requests using OpenAI-style `reasoning_effort` and Responses-API requests with a `reasoning` block now omit `temperature`/`top_p`, which OpenAI reasoning models reject.

### 🧪 Tests

- Added coverage for sampling-param suppression across Anthropic, OpenAI (chat completions + Responses), and Google providers, including default-drop, explicit opt-in pass-through, and deepseek-format retention cases.

### 🐛 Fixes

- **Web UI Session Mode Updates Stay Responsive**
  - After changing a session's runtime mode or capabilities, the Web UI now applies the authoritative runtime response immediately instead of waiting for the session-list refresh to complete. The local session cache is updated at the same time, and a temporary refresh failure no longer leaves the mode controls blocked or visibly stale.

- **Long sessions stuck permanently after context-window overflow (notably WeChat/Feishu channels)**
  - When a provider rejects a request for exceeding the context window (possible when the token estimate underestimates real usage, e.g. Chinese-heavy chats), the agent now retries once after LLM compaction; if the summarization request itself overflows, it falls back to deterministic truncation (dropping the oldest messages, cutting only at user/assistant turn boundaries) instead of failing every subsequent message with `responses stream failed` until `/new`.
  - The context-guard error path (local estimate exceeds the input budget) uses the same recovery.
  - The truncation is persisted as a compaction entry so channel sessions (which rebuild the agent per message) do not reload the overflowing history.
  - OpenAI Responses API `response.failed` events now parse error details nested in `response.error` (where servers like Kimi put the failure reason) instead of showing only a generic `responses stream failed`; channel sessions also forward compaction/recovery progress to messaging platforms.

### ✨ Features

- **Complete OpenAI Responses Runtime**
  - Expanded `api: "openai-responses"` from basic streaming support into a full Responses runtime: native response-item replay, `previous_response_id` and conversation state modes, reasoning context/mode, prompt-cache controls, service tier, structured output, hosted tools, and tool-call controls are validated against the selected model's compatibility capabilities before requests are sent.
  - Responses are archived as native items and associated with local turns, preserving reasoning, citations/artifacts, tool inputs, and response lineage across session replay. Tool execution is idempotent per response turn, preventing duplicate execution when providers repeat function-call items.
  - Provider `responses.background: true` enables durable remote background Responses runs in Serve. MothX polls and resumes them after restart, executes local function/custom-tool calls, persists lifecycle events and results, and supports run inspection, cancellation, reconnect, and abandonment through the Responses run API.

- **`-P --json` Print-Mode Streaming NDJSON Output**
  - Adds a `--json` flag for use with `-P` (print mode) that streams the response as JSON Lines / NDJSON — one JSON object per line on stdout, so consumers can read events as they arrive instead of waiting for the run to finish.
  - Each agent event becomes its own line: `start` (provider/model/mode), `text_delta`, `think_delta`, `tool_call`, `tool_execution_start`, `tool_execution_end`, `tool_result` (with `name`/`arguments`/`result`/`error`/`diff`), `plan_update`, `usage` (tokens and cost), `context_usage`, `compaction_start`/`compaction_end`, and a terminating `done` or `error` event that signals stream completion. All progress, debug, and diagnostic output still goes to stderr so stdout stays pure NDJSON.
  - Useful for CI, automation scripts, and integration with external programs. To reassemble the assistant text, accumulate every `text_delta` line: `mothx -P --json "summarize" | jq -r 'select(.type=="text_delta").text' | tr -d '\n'`. To inspect the whole stream as typed objects: `mothx -P --json "summarize" | jq -s '.'`.

- **Web Search Availability in Serve Status and Capabilities**
  - The serve API now reflects web search availability from both `serve.json` and app-level `settings.json` in `/api/status`, session capabilities, and default session creation.
  - Web UI tool toggles and status snapshots stay in sync after saving settings or serve config changes.

- **Desktop Release Workflow**
  - Added `.github/workflows/desktop-release.yml` for building and publishing desktop packages on tag push.
  - Supports macOS code signing via `CSC_LINK` (base64 or file path), Windows, and Linux builds with `electron-builder`.
  - Generates SHA-256 checksums and uploads artifacts to GitHub Releases with prerelease detection and auto-generated release notes.

- **New Model: `deepseek-v4-flash-0731`**
  - Added the `deepseek-v4-flash-0731` snapshot to the Gitee and Moark providers. It carries a 1M context window and reasoning support (the max-token limit is published by the vendor).

### 🔧 Improvements

- **Responses Reliability and Retry Handling**
  - Responses stream failures are now classified for the shared provider retry policy rather than failing immediately. Cloudflare HTTP `524` origin timeouts are also retryable, improving resilience for transient upstream and gateway failures.

- **Web UI Settings Polish**
  - Refreshed settings views after saving provider, app, and serve config changes so feature flags and runtime status update immediately.
  - Added tool toggle title hints in the chat composer for clearer discoverability.

- **Desktop Build Hardening**
  - Increased Electron install retry attempts and added mirror fallback (`ELECTRON_MIRROR` → `npmmirror` → default) for CI reliability.
  - Fixed ESM path handling in build scripts and corrected macOS Electron executable path detection.
  - Added `version:set` script to sync `package.json`, `package-lock.json`, and runtime version metadata from the release tag.

- **Serve Session Creation Consistency**
  - Unified web search capability resolution across `getOrCreateSession`, `defaultSessionCapabilities`, and channel runtime status snapshots.

- **Channels Session Picker as Native Select**
  - Replaced the custom session dropdown in the Channels settings with a native `<select>` control, improving accessibility, keyboard navigation, and mobile behavior.

### 🧪 Tests

- Added coverage for web search availability from `settings.json` and serve config in `getOrCreateSession` and status handlers.

### 🐛 Fixes

- **Responses Tool Calls and Channel Session Picker**
  - Deduplicated native Responses function/custom-tool calls within each response turn, so repeated upstream items do not re-run a tool while legitimate identical calls in later turns still execute.
  - Fixed the Channels settings session picker visibility when switching channel configuration.

- **Web UI Chat and Background Runs**
  - Fixed background Web UI runs starting without persisted conversation history. Submitted runs now replay the session before invoking the provider, including after a runtime mode switch.
  - The submit-run request now honors optional `images`, `tools`, and `skills`: images are validated against model input capabilities, `tools` is treated as the authoritative session capability set, and unknown tools or skills return `400`. An explicit `mode` is persisted for later runs.
  - Refreshed sessions now remain busy while a server-side run is queued, running, cancelling, or terminalizing. Lifecycle events received from replay and live WebSocket streams are normalized consistently, so the Stop action and run state remain correct after reconnect.
  - Removed the redundant tool feed from the chat view; tool activity remains available through the session event and tool result views. The composer now shows a running-state placeholder while a run is active.

- **Web UI Settings and Model Picker**
  - Removed the redundant feature-toggle card from the settings overview; feature configuration remains available in Serve Config.
  - Fixed the default-model search selector reopening after an option is selected. The picker now closes reliably before the selection update and prevents focus from reopening it.

## v1.1.76

### ✨ Features

- **Empty Provider Response Detection & Retry**
  - The agent now detects empty responses from providers and automatically retries the request, avoiding dialogue interruptions caused by transient network or upstream issues.

- **vibe-browser v0.1.5**
  - Upgraded the browser automation skill with improved page interaction and screenshot capabilities.

### 🔧 Improvements

- **`insert` Tool Rendering in Web UI and Serve Surfaces**
  - Web UI now renders `insert` tool calls with a dedicated call view showing the target path, structured position (head/tail/before_line/after_line + line number), content size, and `dry_run`/`dedupe`/`create_if_missing` flags.
  - Serve API collapsed-mode tool formatting now renders `insert` diffs (previously only `edit`/`write`); messaging channel progress lines also include the `insert` path.

- **Unified Provider Preset Fallback**
  - Consolidated preset fallback logic across `ResolveKey`, `ResolveProviderHeaders`, and factory to ensure consistent provider detection and header injection behavior across all entry points.

- **Tencent HyPlan: Removed `hy3-preview`**
  - Dropped `hy3-preview` from `tencent-hy-plan` and `tencent-hy-plan-anthropic`; Tencent Cloud plan now only offers `hy3`.

- **Documentation Image Optimization**
  - Converted architecture, comparison, and mode promo images to WebP format, reducing documentation bundle size and improving load times.

### 🐛 Fixes

- **GLM-5.2 and Kimi K2.7 Code Are Text-Only Models**
  - Corrected the capability flags for `glm-5.2` and `kimi-k2.7-code` (including the `kimi-k2.7-code-highspeed` variant, the Fireworks `accounts/fireworks/models/kimi-k2p7-code` and `accounts/fireworks/routers/kimi-k2p7-code-fast` routers, and the routed IDs `moonshotai/kimi-k2.7-code`, `zai/glm-5.2`, `@cf/moonshotai/kimi-k2.7-code`, and `@cf/zai-org/glm-5.2`) across every provider that advertised them as multimodal. These models only accept text input, so their `Input` capability is now `text` only and image/attachment payloads are no longer routed to them. Updated `internal/config/settings.go`, `docs/provider-model-list.md`, and `docs/models.md` accordingly. The `glm-5v-turbo` vision model and other genuinely multimodal models are unchanged.

## v1.1.75

### ✨ Features

- **Output Token Truncation Auto-Recovery**
  - When the model hits the output token limit, the agent automatically retries with an escalated max_tokens cap (up to the model's native output limit), then falls back to a resume-from-suffix recovery loop (up to 3 attempts) that tells the model to continue mid-thought without repeating what was already written.
  - A conservative default output cap of 8192 tokens is used for all known models to avoid excessive token usage; user-explicit max_tokens values are always preserved exactly. Retries and truncation are surfaced as status events in TUI, serve API (SSE), and Web UI.

- **Merged Built-in + Custom Model Lists**
  - Provider model lists now merge built-in presets with user-configured models instead of replacing them entirely. Custom models take precedence by ID; built-in models not configured explicitly remain available with their full preset parameters.

### 🔧 Improvements

- **Legacy Config Migration Removal**
  - Removed the one-time `.vibe` → `.mothx` and `.vibecoding` → `.mothx` auto-migration logic. Project path helpers now live in `internal/config/paths.go` without migration side effects.

- **TUI and Web UI Truncation Status**
  - The TUI shows a warning when a response was truncated by the output token limit, and a status line when an auto-retry is in progress.
  - The Web UI displays retry/status events from the SSE stream in the chat run event list.
  - The serve API reports `finish_reason: "length"` for truncated completions instead of always `"stop"`.

- **`insert` Tool Rendering in Web UI and Serve Surfaces**
  - The Web UI now renders `insert` tool calls with a dedicated call view showing the target path, structural position (head/tail/before_line/after_line + line), content size, and `dry_run`/`dedupe`/`create_if_missing` flags, with a content preview mirroring `write`.
  - Serve API collapsed tool formatting now renders the `insert` diff (previously only `edit`/`write`), and messaging channel progress lines include the `insert` path.

- **Tencent Hunyuan Plan Model List**
  - Removed `hy3-preview` from `tencent-hy-plan` and `tencent-hy-plan-anthropic`; the Tencent Cloud plan now exposes only `hy3`.

## v1.1.74

### ✨ Features

- **Structured Text Insertion Tool: `insert`**
  - Added a dedicated insertion tool for adding content to the beginning or end of an existing UTF-8 text file, or before or after a specific line.
  - Supports boundary newline handling, `exact`/`trimmed`/`line` deduplication, `dry_run` previews, structured insertion metadata, and diffs.
  - Files larger than 32 MiB use streaming insertion with file locking, UTF-8/binary validation, concurrent-modification checks, `fsync`, and atomic rename to protect the original file.
  - Keeps a clear boundary with `edit`: text matching, replacement, and deletion remain `edit` responsibilities; `insert` does not provide match, regex, or occurrence modes.

### 🔧 Improvements

- **Volcengine Doubao Model Update**
  - Removed `doubao-seed-2-0-code` and `doubao-seed-2-0-pro` from AgentPlan / CodingPlan; added `doubao-seed-2.1-turbo`.
  - Added `doubao-seed` thinking format: `reasoning_effort` with `minimal` (no thinking), `low`, `medium`, `high` (default) for Doubao Seed 2.1 / Evolving models. Auto-detected by model ID.

- **npm Publish Proxy Visibility**
  - The npm publish-if-needed script now logs `use [proxy ...]` when it uses `all_proxy`, `https_proxy`, or `http_proxy` (including uppercase variants); proxy credentials are redacted from the log.

### 🐛 Fixes

- **Windows SQLite Session Paths**
  - Fixed Windows drive-letter paths being serialized as an invalid SQLite file URI authority, preventing `invalid uri authority: C:` errors when creating sessions.

## v1.1.73

### ✨ Features

- **MCP PATH-based Command Resolution and Robust Client Lifecycle**
  - stdio MCP server commands no longer require an absolute path; commands are resolved through `PATH` with proper environment merging (case-insensitive on Windows, no duplicates).
  - Added an inbound request queue with backpressure for sampling and notification messages.
  - JSON-RPC response IDs are now validated against request IDs; mismatched responses are rejected.
  - HTTP response body parsing is bounded to 16 MiB; SSE multi-line data payloads are joined with newlines.
  - Client lifecycle uses per-client context with cancellation; `Close` cancels inflight requests and closes idle HTTP connections.
  - Resource and prompt discovery errors (non method-not-found) now fail `ConnectServers` instead of being silently ignored.
  - MCP config files are now written atomically via temp file + rename with `0600` permissions.
  - ACP new-session MCP failures now roll back the persisted session.
  - SSE `messageUrl` values are validated to be `http`/`https`; arbitrary schemes are rejected.

### 🔧 Improvements

- **Unified Session Schema Management**
  - Replaced incremental migration logic (`migrations.go`) with a unified full schema definition in `schema.go`, using `EnsureCurrentSchema()` for idempotent initialization.
  - Implemented robust SQLite connection handling with WAL mode and busy timeout.
  - Added `CloseDatabases()` for proper cleanup on exit and reload, and `OpenStandaloneDB()` for caller-owned database connections.
  - Fixed the cron scheduler goroutine lifecycle with a `WaitGroup` to prevent premature exit.

- **Web UI Approval and Session Cancellation**
  - Cancelling a running Web UI session now aborts its active Agent, including approval waits that have not yet reached the pending queue, preventing sessions from remaining stuck in the running state.
  - Approval requests and terminal decisions are scoped to their session and run, persisted in `session.db`, and unresolved approvals are recorded as cancelled when their run ends.
  - The approval panel automatically selects the first pending approval and clears stale approval state when the queue becomes empty.
  - After refreshing or reopening a running session, the Stop button beside Send can still cancel the server-side run; once termination completes, the session can start a new conversation.

- **Installer Package Versioning**
  - Bumped the npm and PyPI installer packages and all platform-specific npm packages to version `1.1.72`.

- **Web UI Mobile Responsive Adaptation**
  - Sidebar collapses into a mobile drawer (hamburger menu pattern) on screens ≤ 900px, using Svelte-native `matchMedia` store + `{#if}` conditional rendering + `transition:fly`/`fade` animations; overlay and drawer only exist in the DOM when open, preventing click-blocking.
  - Stats page adapts to mobile: KPI grid switches to 2 columns, trend/rank grid stacks vertically, chart padding adjusts for narrow screens, and the recent-requests table renders as a card list.
  - Sessions page converts from table to card list on mobile, with compact metadata rows and inline action buttons.
  - Composer input adapts to mobile: controls wrap naturally without scroll containers (preventing select dropdown clipping), textarea uses 16px font to avoid iOS auto-zoom, and runtime/skill popup panels use `position: fixed` bottom-sheet pattern to prevent screen overflow.
  - AGENTS.md updated with WebUI-specific conventions documenting the Svelte-native mobile approach.

## v1.1.72

### ✨ Features

- **Expanded Project Skill Locations**
  - Project-local skills can now be loaded from `.agents/skills/<name>/SKILL.md`, alongside existing `.mothx/skills`, `.skills`, and `skills` locations.

- **Web UI Chat and Skill Controls**
  - Added a per-session active-skill picker in chat. Selected skills are sent with the completion request and immediately refresh the session context.
  - Added server-side session-run cancellation, so the Web UI Stop action also works after reconnecting or refreshing the page.
  - Streaming failures now emit structured SSE error events and appear in the chat transcript with failed-run status.
  - Added collapsible, syntax-highlighted code blocks with copy buttons in Markdown messages, skill references, and edit previews.

- **SkillHub Installation Targets**
  - The Web UI now lets users select an explicit project skill directory or the global skills directory before installing individual skills or skill sets.
  - Added SkillHub APIs for listing installation targets and replacing a session's active skill set.

### 🔧 Improvements

- **Runtime Sandbox Configuration**
  - Applying Serve configuration updates now refreshes the API server's sandbox manager and every live session's sandbox and tool registry without a restart.
  - Sandbox managers are now isolated by API session work directory, so alternate allowed work directories and their sub-agents retain the correct policy.

### 🐛 Fixes

- **Sandbox Git and Device Compatibility**
  - Git metadata remains visible to sandboxed commands when Git protection is enabled, preserving normal Git operation while retaining one-time Git access handling.
  - Avoided rebinding host `/dev` paths into Bubblewrap, preventing tools such as Git from receiving unusable read-only device files.
  - Corrected Linux `/home` deny-rule normalization so projects located below `/home` are not rejected by the default sandbox policy.

## v1.1.71

### ✨ Features

- **Expanded Provider Model Lists**
  - Synchronized `docs/provider-model-list.md` with `internal/config/settings.go` to reflect the latest model availability.
  - Added significant support for new models across multiple providers including:
    - **OpenAI**: Added `gpt-4o-2024-05-13` variant.
    - **Google Gemini**: Updated model list and counts.
    - **Gitee/Moark**: Added a dedicated section and expanded model list with `glm-5` series, `qwen3.x` series, and `kimi-k2.x` series.
    - **Alibaba Bailian**: Added `qwen3.8-max-preview`, `qwen3.7-plus`, and `glm-5.2` to Token Plan.
    - **Tencent Hunyuan**: Added `hy3` and `hy3-preview` models.
    - **Baidu Qianfan**: Added `Token Plan` subsection with expanded model support (`deepseek-v4`, `glm-5.2`, `kimi-k2.6`, `ernie-5.1`).
    - **Kimi Coding**: Added explicit `ThinkingFormat: kimi` support.
  - Updated the Quick Reference table to reflect accurate model counts and the new `kimi` thinking format.

### 🐛 Fixes

- **Explicit Zero max_tokens Support**
  - Fixed `maxTokens: 0` in model configuration being indistinguishable from an omitted value, which prevented users from disabling the output token limit.
  - Added `fieldSet` tracking to `ModelConfig` so explicitly set zero values are preserved through JSON marshal/unmarshal and correctly propagated to providers.
  - Anthropic provider sends `max_tokens` as `*int` with `omitempty`. Because the Anthropic Messages API requires `max_tokens` and rejects values above the model's output limit, an explicit zero falls back to the default of 16384 instead of omitting the field; OpenAI/Google-style endpoints omit the field and honor the disabled limit.
  - Updated `ResolveMaxTokens` and serve API handler to respect explicit zero and skip the fallback default; negative client-supplied `max_tokens` values are normalized to zero first.
  - Added TUI model editor support to preserve explicit zero max_tokens through the edit state round-trip.

- **Web UI Session History and Failure Visibility**
  - Fixed newly created Web UI chat sessions not appearing in the sidebar/history list immediately when starting from the default session.
  - Added optimistic session-list updates while a new Web UI session is starting, then reconciles with the persisted session list from the server.
  - Web UI task failures now appear directly in the chat transcript with the failure reason, including failed completion requests, session stream errors, and failed run events.
  - Added visual error styling for failed assistant messages so stopped/failed tasks are easier to identify.

## v1.1.69

### ✨ Features

- **Web UI Session Runtime Controls and Approvals**
  - Added per-session runtime controls for switching between `plan`, `agent`, and `yolo` modes without restarting Serve.
  - Added live capability state for browser, web search, delegate, multi-agent, workflows, and A2A master tools, including availability and disabled-reason reporting.
  - Added a Web UI Approval Center for pending bash, file write/edit, delete, and Git access requests, with one-time approval/denial and persistent command/path allow rules.
  - Added approval and tool execution events to the session stream, runtime snapshots, run-event audit records, and reconnect/session recovery handling.

### 🔧 Improvements

- **Kimi K3 Support**
  - Added Kimi K3 to the built-in Kimi and Kimi Coding provider model lists with 1M context support.
  - Added Kimi reasoning-level mapping for `low`, `high`, and `max` reasoning effort values.

- **Web UI and Stats Branding**
  - Added the MothX small favicon to the Web UI, Stats dashboard, and documentation assets.
  - Restored Web UI approval audit history from persisted session run events.

## v1.1.68

### 🐛 Fixes

- **Sandbox Isolation and Policy Consistency**
  - Applied configured sandbox policies to Linux Bubblewrap, including custom binary paths, network access, extra read/write paths, denied paths, environment-variable pass-through, and temporary filesystem size.
  - Isolated OpenAI-compatible API sandbox managers per session work directory, ensuring allowed alternate work directories are correctly mounted and sub-agents inherit the same restrictions.
  - Fixed Channels sub-agents bypassing an enabled sandbox by reusing each session's configured sandbox manager.
  - Prevented configured denied paths from being rebound through additional sandbox path options, and improved sandbox availability error messages.

### ✨ Features

- **SkillHub / ClawHub Marketplace Integration**
  - Added a built-in skill marketplace for browsing, searching, inspecting, viewing files and security evaluations, installing, updating, uninstalling, and activating SkillHub.cn / ClawHub.ai skills from the TUI (`/skillhub`) and the `mothx serve` Web UI.
  - Added a skill marketplace cache and registry factory for extensible market support; serve mode now exposes market, search, detail, install, skill-set, and session activation APIs.
  - The installer validates archive size, path traversal, absolute paths, Windows drive paths, and symbolic links, while protecting hand-written skill directories from being overwritten.

### 🔧 Improvements

- **Sandbox Policy and Git Protection**
  - Added sandbox policy normalization, allow/deny overlap validation, temporary filesystem size parsing, and Bubblewrap capability probing; strict sandbox failures now report their cause instead of silently downgrading.
  - Applied sandbox configuration consistently across CLI, ACP, A2A, Channels, serve API, and sub-agents; the serve API now defaults to sandbox disabled and uses per-session work-directory isolation when enabled.
  - When Git protection is enabled, `.git` metadata is denied by default; Git commands can receive a one-time approval to temporarily access it, preventing ordinary commands from modifying repository internals.
  - Simplified sandbox network configuration and TUI settings, and corrected Linux project-directory and `/proc` mount handling.

### 🐛 Fixes

- **SkillHub Session and Channel Support**
  - Fixed skill installation and activation in the serve Web UI and Channels to use the correct work directory and session state, while ensuring active skills are loaded by the current session and its sub-agents.

## v1.1.67

### ✨ Features

- **Unified Online Installer**
  - Online installation now uses `https://mothx.net/install.sh` on Unix-like systems and `https://mothx.net/install.bat` on Windows.
  - The scripts reuse an existing Node.js installation or install Node.js LTS when missing, then install the latest release with `npm install -g mothx-installer`.

### 🐛 Fixes

- **Corrupt Settings Recovery**
  - Invalid global or project-level `settings.json` files no longer prevent MothX from starting when the malformed file can be backed up successfully.
  - Malformed files are renamed to timestamped backups such as `settings.json.bak_20260715-143000`; name collisions receive a numeric suffix.
  - A warning reports the platform-native absolute backup path. Global failures fall back to defaults, while invalid project settings are ignored without discarding valid global settings.

- **TUI Managed Agent Status**
  - Fixed TUI managed-agent state tracking so main-agent runs in multi-agent, delegate, and workflow modes are marked `running` at turn start and `done` or `error` when the turn finishes.
  - Workflow-mode failures now update the managed agent status to `error` instead of leaving the tab/status UI stuck in `running`.

- **Delegate Sub-Agent Completion**
  - Added regression coverage ensuring the delegate sub-agent tool blocks until the child agent completes and returns the child's final result instead of returning early.

## v1.1.66

### ✨ Features

- **Fuzz Test Targets & Make Target**
  - Added fuzz tests for ESM report parsing (`internal/esm/report_fuzz_test.go`), MCP JSON-RPC message handling (`internal/mcp/mcp_fuzz_test.go`), and utility truncation (`internal/util/truncate_fuzz_test.go`).
  - Added `make fuzz` target that runs every registered fuzz target for a configurable duration (`FUZZTIME`, default `10s`), since Go fuzzing accepts only one package per invocation.

### 🔧 Improvements

- **Per-Model Output Token Limits**
  - Removed the global `maxOutputTokens` setting from `settings.json`. Output limits now always come from the active model's `maxTokens`, avoiding truncation or oversized outputs caused by a one-size-fits-all global cap across providers.
  - Simplified `agent.ResolveMaxTokens` to take only the model; dropped the `MaxTokensSet` gate so built-in model defaults apply automatically without requiring user configuration.
  - Updated CLI/print, ACP server, TUI (`/model` cycling, `ensureAgent`, `?` / BTW help), OpenAI-compatible API (`/compact` and chat completions), AgentFactory, and ESM sub-agent paths to use the new signature.
  - Removed the Max Output Tokens field from the TUI `/settings` Behavior panel; `SaveGlobalSettingsPatch` now strips legacy `maxOutputTokens` keys from existing sparse settings files.
  - Updated `docs/en/configuration.md`, `docs/en/faq.md`, and `README_zh.md` to remove the retired setting; the FAQ now points users at per-model `maxTokens`.

- **Volcengine Plan Default Max Tokens**
  - Lowered the default `MaxTokens` for every model under the `volcengine-agentplan` and `volcengine-codingplan` providers (Ark Code, Doubao Seed 2.0 series, GLM-5.2, Kimi K2.x, DeepSeek V4 Pro/Flash, MiniMax M3/M2.7) to 100K, matching current upstream limits and the CodingPlan model-set note.
  - Corrected the CodingPlan doc note (MiniMax M2.7 is excluded, not M3) and added a `TestVolcenginePlanModelsUseSharedMaxTokens` regression test.

- **TUI Debug Output Cleanup**
  - Interactive TUI runs no longer leak streaming JSON debug lines into the Bubble Tea view while `--debug` is on: debug output still goes to `debug.log` and the pprof server starts as before, but stderr chatter is suppressed via a new `VIBECODING_DEBUG_LOG_ONLY` env var.
  - CLI `--print` mode (and other non-TUI entry points) continues to print `[DEBUG]` lines and pprof status to stderr, and the startup "Debug logging enabled" banner is also limited to print mode.
  - `DebugCompleteResponse` now falls back to a structured string dump when `json.Marshal` fails (e.g. for tool calls that accumulated invalid `json.RawMessage` arguments mid-stream), so malformed payloads never disappear from `debug.log`.
  - `debugpprof.Start` accepts a writer for its log lines; added coverage for the marshal-failure debug path.

- **Test Suite Maintenance**
  - Updated stats dashboard migration expectation to 15 (post-ESM recovery columns).
  - TUI auth-dialog, settings-sparse, and zero-override tests rewritten to exercise `maxContextTokens` instead of the removed `maxOutputTokens` field.

## v1.1.65

### 🔧 Improvements

- **GitHub Release Automation**
  - Added `.github/workflows/release.yml` to automatically build and publish release artifacts when a Git tag is pushed.
  - Workflow builds the Web UI (Node.js 22) and Go binaries (via `make dist`), then creates a GitHub Release with tarballs, `.deb` packages, zip archives, and SHA-256 checksums attached.
  - Pre-release tags (containing `-`, e.g. `v1.1.65-pre`) are automatically marked as prereleases on GitHub; release notes are auto-generated from merged PRs.
- **GitHub npm Packages Publish Workflow**
  - Added `.github/workflows/github-npm-publish.yml` to build and publish the npm installer packages (binary wrappers + the `@scope/mothx` meta package) to GitHub Packages on every tag push, with a `workflow_dispatch` input for manual version overrides.
  - Includes an idempotent `publish_if_needed` check so re-running the workflow against an already-published version skips instead of failing.

### 🐛 Fixes

- **CI npm Package Build Path**
  - Fixed the GitHub npm publish workflow to resolve `package.json` paths correctly when packaging per-platform binary tarballs, preventing publish failures caused by an incorrect working directory.

## v1.1.63

### ✨ Features

- **ESM Automatic Recovery for Interrupted Roles**
  - Added `RecoveryObserver` read-only sub-agent that inspects repository state after an ESM role (worker, critic, or audit) is interrupted by timeout or transport failure.
  - Added `RecoveryObserverTaskPrompt`, `RecoveryReport`, and `ParseRecoveryReport` for structured recovery decision (`resume` / `blocked`).
  - TUI `recoverInterruptedESMRole` converts bounded, recoverable role failures into clean supervisor completions so the next ESM continuation can launch a fresh worker.
  - Timeout-triggered recovery spawns a RecoveryObserver (5 min timeout) to verify repo state and list concrete remaining work.
  - Transport failures (provider errors after built-in retries) are auto-recovered without spawning an observer; a fresh worker retries from current state.
  - DB migration 015 adds `recovery_count` and `recovery_reason` columns to `session_esm_objectives`.
  - `RecoveryLimit = 2` consecutive automatic recoveries permitted; further interruptions pause continuation until `/esm resume`.
  - Recovery state shown in TUI footer (`recover N/2`) and included in steering/worker prompts.
  - Worker progress resets recovery counters on successful continuation.
  - Recovery observer uses the same read-only tool restriction as critic/audit sub-agents.

### 🔧 Improvements

- **TUI ESM Panel & Tool Modal Enhancements**
  - Track `FullThink`, `FullText`, `FullResult`, `LastToolName`, and `LastToolArgs` in agent activity for complete sub-agent activity inspection in the ESM panel.
  - ESM panel now shows `Now / Progress / Next` status with pipeline stage count and remaining work items.
  - Tool modal renders raw assistant/thinking content directly for the main agent; activity timeline entries preserved without truncation.
  - Tool argument keys sorted alphabetically for deterministic display.

### 🐛 Fixes

- **OpenAI-Compatible Provider Tool Argument Parsing**
  - Fixed tool call failures against providers (e.g. Volcengine Ark) that stream tool arguments as raw JSON objects instead of the escaped JSON string returned by the OpenAI API.
  - Introduced `openAIToolArguments` with a custom `UnmarshalJSON` accepting both string-encoded and raw object forms, normalizing to raw JSON.
  - Stream raw argument bytes directly into tool call buffers; marshal back to the OpenAI string form on outbound messages to keep conversation history wire-compatible.
  - Added unit tests covering string, object, null, and streamed tool call round-trip cases.
  - Registered Volcengine Ark as a known provider default and listed it in the provider/model docs.

## v1.1.62

### ✨ Features

- **ESM (Supervisor Mode)**
  - Added `internal/esm` package providing Event State Memory for long-running objectives with persistent state.
  - Added `/esm` command with `edit`, `pause`, `resume`, `clear`, and `budget` subcommands.
  - Registered `get_esm` and `update_esm` tools when ESM objective is active.
  - ESM steering messages injected via `AgentLoopConfig.GetSteeringMessages`.
  - ESM status shown in TUI footer.
  - SQLite-backed storage with `session_esm_objectives` table (migration 010).

- **ESM Completion Review Workflow**
  - Added worker → critic → audit review pipeline for completion candidates.
  - Added `StatusCompleteCandidate` with structured `WorkerReport`/`AuditReport` parsing and validation.
  - Added `completion_review`, `completion_run_id`, `completion_reason`, `blocked_run_id` to Objective schema (migrations 011/012).
  - TUI ESM orchestrates the full review pipeline; only a passing audit marks objective complete.
  - Restricted critic/audit sub-agents to read-only tools and require concrete blockers in reports.
  - Suppressed noisy role-agent lifecycle events in the parent TUI stream for cleaner output.
  - AgentFactory tracks `providerName`/`Vendor` for sub-agent runtime sync.
  - Added `withRuntimeConfig` for flexible factory cloning.
  - Worker reports now accept both `remaining_work` and `missing_work`; any remaining work or blocker rejects a completion claim before critic review.
  - Persisted the current ESM phase, latest worker progress, structured remaining work, and consecutive completion rejection state.
  - Added a three-rejection circuit breaker that pauses automatic continuation until the user runs `/esm resume`.
  - Added a live, scrollable ESM progress panel opened with `Ctrl+E`, including pipeline phase, remaining work, blockers, review details, usage, and current sub-agent activity.

- **Context Compaction Improvements**
  - `/compact` now executes immediately across TUI, channels, and OpenAI API runtimes (was previously deferred).
  - Added `CompactForced` for explicit user-requested compaction that allows summary-only checkpoints when no older history exists outside the recent keep window.
  - Auto-compaction trigger moved before building the next request so plain-text turns cannot miss the trigger point.
  - Switched auto-compaction threshold to percentage-based (80% of context window) via `ShouldCompactPercent`.
  - Fixed session replay to handle summary-only compaction entries where `FirstKeptEntry` is empty.

- **Docker Support**
  - Added `Dockerfile` (Ubuntu default, Debian/Fedora/Alpine variants) with multi-stage build.
  - Added `.github/workflows/ghcr-publish.yml` for CI/CD publishing to GHCR.
  - Added `.dockerignore` for clean builds.
  - Added Docker installation docs to README and getting-started guides (zh/en).

- **Sub-Agent Session Isolation**
  - Added dedicated `sub_session` and `sub_entries` tables for sub-agent, cron, webhook, and ESM worker sessions (migration 013).
  - Added `IsSubAgent` flag to `AgentOptions`; factory automatically routes sub-agents to isolated storage so they no longer pollute the main session list.
  - Cron scheduler, webhook dispatcher, and ESM worker pipeline all opt in to sub-session storage.

### 🔧 Improvements

- **TUI Split-Paste Handling**
  - Disabled bracketed paste by default to prevent TUI freeze when terminals drop the end marker.
  - Improved split-paste Enter deferral: queue Enter only when text was recently typed (within idle delay window), instead of always queueing when buffer is non-empty.
  - Added macOS-specific `console_darwin.go` to keep `WithoutBracketedPaste` where bracketed-paste end markers are unreliable.
  - Removed `WithoutBracketedPaste` from generic Unix (`console_unix.go`) now that the input queue handles split pastes without disabling bracketed paste.
  - Added tests for split-paste coalescing after first-line flush and deferred Enter submit.

- **Web UI Sidebar Fixes**
  - Fixed sidebar: auto-hiding scrollbar for history list, flex-shrink fixes for layout stability.

- **AgentFactory Enhancements**
  - AgentFactory now tracks `providerName` and `Vendor` for sub-agent runtime synchronization.
  - Fix usage stats provider name extraction when `Vendor` is empty.

- **Serve API Security & Hardening**
  - Default listen address changed to loopback (`127.0.0.1:8080`), default mode changed to `agent`, sandbox enabled by default.
  - Public (non-loopback) listen now requires Bearer token auth unless `--unsafe` is passed.
  - Added symlink-safe `IsWithinPath` helper; work directory resolution and `allowedWorkDirs` checks reject symlink escape.
  - Persisted session working directories are re-validated on load to prevent stale-path escapes.
  - Sessions are pinned during request handling to prevent idle-eviction races; added locking to `Touch`/use counters to fix concurrent list/evict data races.

- **Sandbox Cleanup**
  - Added `CommandCleanupProvider` interface; macOS Seatbelt sandbox now cleans up temporary profiles after each command exits.
  - Bash tool invokes sandbox cleanup on both synchronous and asynchronous command paths.

- **Cron Scheduler Reliability**
  - Added atomic `ClaimDue` in the SQLite cron store to prevent duplicate job runs across scheduler instances.
  - Tracked in-memory claims to avoid overlapping ticks for the same job.

- **A2A Task Cancellation**
  - Registered per-run cancel so `tasks/cancel` propagates to the executor context.
  - Introduced `TaskStore.Finish`/`Cancel` helpers and added terminal-state tests.

- **Stats Dashboard Heatmap**
  - Replaced the 30-day bar chart with a 7-day / 2-hour bucket flame-style heatmap for a more intuitive view of usage intensity.

### 📚 Documentation

- Removed stale `docs/proposal/codex-goal-mode.md`.
- Added `docs/proposal/enable-supervisor-mode.md`.
- Updated configuration docs to reflect new `/compact` immediate execution and summary-only checkpoint behavior.

## v1.1.61

### ✨ Features

- **Per-Session Tool Capabilities**
  - Added `x_tools` extension to `/v1/chat/completions` for enabling webSearch, browser, a2aMaster, delegate, and multiAgent per session.
  - Added `GET /api/capabilities` and `GET/PATCH /api/sessions/{id}/capabilities` APIs for querying and updating session tool toggles.
  - Added `session_capabilities` persistence table (migration 007) in `sessions.db`.
  - Added CLI flags `--web-search`, `--browser`, `--enable-a2a-master` for serve mode.
  - Added `webSearch`, `browser`, `a2aMaster` fields to `serve.json` config.
  - Web UI session tool toggles in composer bar with PATCH to capabilities API.
  - Per-session settings injection for `webSearch` via `settingsForSession`.
  - Added `x_session_id` + `x_working_dir` cwd conflict detection (HTTP 409).
  - Added `/api/sessions?scope=all|active` and `/api/sessions/active` endpoints.
  - `/mode` and `/delegate` commands now persist capability changes per session.

- **Session Streaming & Stats Dashboard**
  - Added SSE-based session streaming for real-time chat updates (`session_stream.go`).
  - Added sequenced message/event replay for cursor-based streaming.
  - Added `/api/stats/` endpoints (summary, timeseries, by-provider, by-model, recent).
  - Track session running state and publish run/capability events to stream.
  - Added cache read/write tokens to usage tracking.
  - Web UI: SSE streaming in Chat view, Stats dashboard view, Channels/Logs settings.
  - Added `WorkingDir` → `DefaultWorkDir` rename in serve config.
  - Added legacy config dir normalization for session/skills dirs.

- **Run & Capability Event Tracking**
  - Added `session_run_events` and `session_capability_events` tables (migration 008).
  - Record run lifecycle events (started/finished/failed/canceled) for every chat completion.
  - Record capability change events for `/mode`, `/delegate`, `x_tools`, and PATCH API.
  - New endpoints: `GET /api/sessions/{id}/run-events`, `GET /api/sessions/{id}/capability-events`.
  - Web UI displays recent run and capability events.
  - Added `make serve` Makefile target.

- **Transcript SSE Events for Streaming**
  - Added `x_transcript` field to `ChatCompletionRequest` for enabling transcript-mode streaming.
  - When enabled, streaming handler emits `event: transcript` frames (`assistant_delta` and `message` types) instead of legacy `tool_status` events.
  - Web UI sends `x_transcript:true` and routes transcript events through shared `upsertTranscriptMessage` path.
  - Refactored streaming handler to branch on transcript flag with helper functions for building transcript toolCall/toolResult entries.

- **Embedded Web UI Assets**
  - Web UI assets are now embedded in the binary via `go:embed`, no longer requiring dist files on disk.
  - Added `ui` package with `DistFS()` and `fs.FS` abstraction for both embedded and override paths.
  - `--web-ui-dir` flag still supported for overriding embedded assets.

- **External Bind Address via --port**
  - `--port` now accepts full addresses (e.g. `0.0.0.0:8080`).
  - Removed `displayListenAddr` rewrite that overrode `0.0.0.0` to `127.0.0.1`.
  - Added `mothx serve --unsafe` to disable auth and expose loopback/default listens on all interfaces for the current process.

- **Web UI Keyboard Shortcuts & Pagination**
  - Sidebar: Cmd/Ctrl+K to focus search, Shift+Cmd/Ctrl+K for new chat.
  - Platform-aware shortcut labels (macOS vs other), Escape clears search.
  - Sessions view: paginated list (25 per page) with page navigation controls.

- **WeChat QR Login API & Channels Settings UI**
  - Added WeChat QR login API endpoints (login status, QR proxy, base64 mode).
  - Added `wechatLoginSession` for managing QR scan flow state.
  - Rewrote Channels.svelte with full WeChat QR login flow (polling, display, error handling).
  - Added Feishu config form (appId/appSecret/workspace/allowedUsers) and WebSocket channel toggle.
  - Added `ProviderSettings.svelte` wrapper and comprehensive i18n strings for channel settings.
  - Dispatcher nil-checks before starting platforms.

- **Sub-Agent Detach & Rule Guard Fix**
  - Added `DetachChild()` to `AgentManager` to remove child from parent's active list while retaining the child agent for later inspection.
  - Added `HasRunning()` to `AgentManager` to check if any agent is actively executing.
  - Changed `DelegateSubAgentTool` to use `DetachChild` instead of `Destroy` so completed delegated children remain inspectable via handle.
  - Delegate result now returns handle for tracking delegated child agents.
  - Fixed `/rule` command guard to use `HasRunning()` instead of `Count() > 0` so rule changes are allowed when only completed retained agents exist.

- **Cron Store Migration to SQLite**
  - Replaced `FileCronStore` (cron.json) with `SQLiteCronStore` (sessions.db) for reliable, transactional cron job persistence.
  - Added `SessionScopedStore` to bind cron jobs to sessions with per-session isolation and automatic workDir inheritance.
  - Added `--cron` CLI flag as independent option (separate from `--multi-agent`).
  - Cron now enabled by default in serve mode without requiring multi-agent.
  - Scheduler attaches scheduled local runs to existing sessions when `SessionID` is set.
  - Added `cron_jobs` table migration in sessions.go.
  - Cron tool supports `findJob` by name (with ambiguity detection) for enable, disable, delete, and run actions.
  - Dispatcher lazily initializes `AgentManager` for cron-only sessions.

- **Serve Settings Hot-Reload & Workflows Toggle**
  - Added `Server.ApplySettings()` to hot-reload provider/model after settings save.
  - Added `workflows` session tool option and feature flag in serve.
  - Added `nearestExistingBrowseDir` fallback when default work dir is missing.
  - Refactored truncation to `util.TruncateWithSuffix` (UTF-8 safe).

- **System Prompt Rename to MothX**
  - Renamed system prompt identity from VibeCoding to MothX.

### 🔧 Improvements

- **Web UI Settings Expansion**
  - Added `ListEditor` reusable component for editing string lists in settings.
  - Expanded `AppSettings` with full form-based editor for defaults, web search, context files, compaction, sandbox, retry, approval, and provider config.
  - Expanded `ServeConfig` with full form-based editor for features, API, cron, memory, security, agent, hooks, channels, and lobster mode settings.
  - Web UI: sessions table fixed columns with ellipsis layout.
  - Web UI: skill_ref and workflow_lint tool call/result display.
  - Web UI: simplified WeChat QR to open-in-new-tab instead of embed.
  - Web UI: `resetSelectedModelToDefault` on session switch and settings save.
  - Web UI: workdir settings refresh after save, cleaner restrict logic.
  - i18n: added zh/en strings for workflow and skill_ref tools.

- **Web UI Internationalization & Theme Support**
  - Added a complete i18n system for the Web UI with Chinese/English language switching.
  - Added a preference controls panel (`PreferenceControls`) for adjusting language and theme.
  - Replaced all hardcoded strings across views and components with translation keys.
  - Added a CSS variable-driven theme system supporting Dark/Light theme switching.

- **Web UI Tool Calls & Plan Card Rendering**
  - The Web UI chat interface now renders tool calls, tool results, and plan cards.
  - Tool calls are displayed as running/completed status chips; tool results are collapsible (summary shows first line, click to fetch full output on demand).
  - Plan tool invocations render as a live-updating todo checklist.
  - Backend added `/api/sessions/:id/tool-results/:callId` endpoint for lazy-loading full tool output.
  - `ListActiveSessions` now also returns historical sessions so the Sessions page shows all persisted conversations.

- **Richer Tool Status Streaming in Serve Mode**
  - SSE streaming events now carry richer tool status information, enabling the frontend to display real-time tool execution progress.
  - Tool status events include tool name, arguments, and execution results.

- **Debug Mode pprof Server**
  - Added `--debug` flag to start a local pprof profiling server across all entry points (CLI, TUI, Serve, ACP, A2A).

- **Speedtest Command**
  - Added `vibecoding speedtest` CLI subcommand for testing model response speed.

- **New StepFun Vendor Support**
  - Added `stepfun` vendor with Base URL `https://api.stepfun.com/step_plan/v1` using OpenAI-compatible protocol.
  - Added `step-3.7-flash` model with 256K context window and multimodal (text + image) input support.

- **Multimodal Image Input**
  - Serve mode now supports multimodal (image) input; images can be uploaded via API for conversations.
  - Improved session persistence to correctly store multimodal messages.

- **Serve init-config Subcommand**
  - Added `mothx serve init-config` subcommand for initializing global and project-level `serve.json` configuration.

- **TUI Input Queue On-Demand Start**
  - Input queue ticker now starts on demand and stops when idle, reducing unnecessary CPU usage.

- **TUI Backspace/Delete to Remove Auth Models**
  - Added Backspace/Delete shortcut in the auth dialog model list to delete a selected model entry.
  - Action rows like `+ Add Model` and `Done` are excluded from deletion.

- **Split-Paste Coalescing Configurable**
  - Split-paste event coalescing is now configurable via test parameters, facilitating unit test verification.

### 🔒 Security

- **Browse API Restriction**
  - Browse API is now restricted to `allowedWorkDirs` whitelist directories, rejecting out-of-bounds access.
  - Auth requests without tokens are now rejected to prevent unauthorized access.

- **Code Scanning Fix**
  - Fixed a potentially unsafe quoting issue (Code Scanning Alert #3).

### 🔄 Refactors

- **Merged Gateway & Hermes into Unified Serve Mode**
  - Removed `internal/gateway` and `internal/hermes` packages, merged into the unified `internal/serve/` architecture.
  - Removed `gateway`/`hermes` subcommands from CLI entry points.
  - Added `internal/serve/openaiapi` (OpenAI-compatible API runtime), `internal/serve/channels` (message channel dispatcher), `internal/serve/ws` (WebSocket channel runtime).
  - Removed Hermes built-in terminal WebSocket client.

- **WebUI Component Split**
  - Split monolithic `App.svelte` into separate components, views, and lib modules for improved maintainability.

### 📦 Dependencies

- Bumped `golang.org/x/image` from v0.36.0 to v0.41.0.

## v1.1.60

### ✨ Features

- **Unified Serve Mode with Web UI**
  - Added `mothx serve` CLI command to start a unified server exposing OpenAI-compatible APIs, a Web UI management panel, and messaging channels (WeChat/Feishu) simultaneously.
  - Added `internal/serve/` package to unify Serve, Channels channel, and Web UI configuration and runtime management.
  - Configuration via `serve.json` (global `~/.mothx/serve.json`, project `.mothx/serve.json`), supporting Serve, channels, Web UI, Cron, Memory, Security, Hooks, and Agent settings.
  - Built-in Svelte Web UI panel with Dark theme, health check, channel status, config editor, settings editor, and chat interface with SSE streaming.
  - Web UI now includes full management APIs: `/api/status`, `/api/sessions`, `/api/cron`, `/api/memory`, and `/ws/logs` for real-time log streaming.
  - WebSocket runtime mounted at `/ws`, reusing Channels event protocol for real-time communication.
  - Cron API supports CRUD operations with scheduler integration.
  - Serve SessionPool now has List/Delete management interfaces.
  - Added `--web-ui-dir` CLI flag to override the Web UI static assets directory.
  - Added Lobster mode (`--lobster`) that auto-enables yolo mode, disables sandbox, and turns on sub-agents.
  - Serve now supports an `ExtraRoutes` hook for Serve mode to inject custom API routes (`/api/serve/config`, `/api/settings`, `/api/channels`).

- **New Vendor Support**
  - Added Huawei Cloud vendor (`huawei`, `huawei-plan`) with 13 models total, including standard and Plan reasoning modes.
  - Added Moore Threads vendor (`mthreads-plan`) with GLM-4.7 model (1M context).
  - Added Tianyi Cloud vendor (`ctyun-plan`) with 3 models including GLM-5-Turbo.
  - Added JD Cloud vendor (`jd-plan`) with 10 models including JoyAI-LLM-Flash.
  - Added Kimi-K2.5 and MiMo-V2.5-Pro to Gitee/Moark providers; fixed JD Plan config with missing models.

### 🐛 Bug Fixes

- **TUI Split Paste Event Coalescing**
  - Some terminals split pasted text into separate key events. Added idle detection to wait for a quiet period before flushing the input queue.
  - Split paste events are now coalesced into a single paste when Enter appears within the stream followed by more text.
  - Extracted `handleInputSubmit()` for cleaner Enter key handling.

- **Legacy `VIBECODING_DIR` Handling**
  - `ConfigDir()` now falls back to the default `.mothx/` path when `VIBECODING_DIR` is set to the legacy default `~/.vibecoding`, avoiding an unintended override of the new config directory.
  - `ConfigDirOverridden()` no longer reports a custom override when `VIBECODING_DIR` equals the default legacy path.
  - The stats CLI now reads `sessionDir` from `config.LoadSettings()` instead of calling `platform.SessionDir()` directly, ensuring it respects the configured session directory.

### 🧪 Tests

- Added `TestConfigDirIgnoresLegacyDefaultEnvDir` and `TestConfigDirHonorsCustomLegacyEnvDir` to verify `ConfigDir` correctly ignores or honors `VIBECODING_DIR` based on whether it matches the legacy default.
- Added `TestLoadSettingsWithLegacyDefaultEnvCreatesMothXConfig` to verify settings migration creates `.mothx/` config when `VIBECODING_DIR` points to the legacy default.
- Added `TestOpenStatsDBUsesConfiguredSessionDir` to verify the stats command resolves the session database path from settings.

## v1.1.59

### ✨ Features

- **Tool Selection Rules in System Prompt**
  - Added a "Tool Selection Rules" section to the agent system prompt, instructing the model to prefer dedicated tools (`read`, `ls`, `grep`, `find`) over `bash` for file inspection and discovery.
  - Explicitly discourages running `cat`, `sed`, `awk`, `grep`, `find`, `ls`, `pwd` via `bash` when equivalent dedicated tools exist.

- **Directory Migration to `.mothx/`**
  - Install scripts (`install.sh`, `install.ps1`) now default to `~/.mothx/` (was `~/.vibecoding/`).
  - Added `MOTHX_INSTALL_DIR` env var; `VIBECODING_INSTALL_DIR` remains as a legacy fallback.
  - Uninstall checks both old (`~/.vibecoding/`, `./.vibe`) and new (`~/.mothx/`, `./.mothx`) directories for backward compatibility.
  - npm postinstall scripts and README updated to reference `~/.mothx/settings.json`.

### 🔧 Improvements

- **Bash Non-Interactive Subprocess & Process Group Kill**
  - Bash tool subprocesses now run in non-interactive mode: stdin is set to empty (`read` sees EOF instead of blocking), and non-interactive env defaults are injected (`GIT_TERMINAL_PROMPT=0`, `GIT_ASKPASS=true`, `SSH_ASKPASS=true`, `SSH_ASKPASS_REQUIRE=never`, `SUDO_ASKPASS=true`) unless the user has explicitly set them.
  - On Unix, `Setsid` gives the shell its own session; cancellation kills the entire process group via `kill(-pid)` so auth helpers and grandchildren do not linger.
  - Added `killCommandProcess` helper shared by `BashTool` and `JobManager` for unified process termination.

- **TUI Auth Dialog Refactor**
  - Auth input fields (API key, provider ID, model name, etc.) now use `SetMaxLines(1)` instead of `SetMaxLines(3)`, enforcing single-line input for credential and identifier fields.
  - Introduced `newAuthInput()` helper to centralize editor creation, reducing duplication across `auth_dialog.go`, `auth_model.go`, `auth_provider.go`, and `auth_settings_top.go`.
  - Removed redundant `editor` imports from files that now use the helper.

- **Tests**
  - Added `TestAuthAPIKeyInputStaysSingleLine` to verify auth input does not wrap into multiple lines.
  - Added `TestLoadSettingsCreatesMothXConfigDir` to verify settings creation uses `.mothx/` and does not create `.vibecoding/`.

## v1.1.58

### 🔧 Improvements

- Renamed npm platform binary packages from `mothx-*` to `mothx-installer-*` for consistent naming with the root `mothx-installer` package.
- Renamed the PyPI installer package from `vibecoding-installer` to `mothx-installer`; the Python wrapper now exposes `mothx` as the primary command while keeping `vibecoding` as a compatibility alias.

## v1.1.57

### ✨ Features

- **Image Preprocessing & Multimodal Enhancements**
  - Unified image preprocessing pipeline with metadata propagation across the tool chain.
  - Added image crop support, browser screenshot preprocessing, and OpenAI `detail` parameter passthrough for `auto`/`low`/`high` quality control.
  - Image output-size enforcement with provider-specific hints and coordinate mapping for bounding-box annotations.
  - Added Qwen-specific 28px patch image token estimation and multi-image accumulation for accurate token accounting.
  - Added `/paste-image` command with `Ctrl+R` preview support.

- **Stats Dashboard Improvements**
  - Added share button, token trend chart, and overall UI improvements.
  - Added 2.5h time bucket grouping and filtering on the recent requests page.

- **Auto-Open Auth Dialog on First Run**
  - The auth dialog now opens automatically on first run when no provider is configured.

- **MothX npm rename transition**
  - Added the new `mothx-installer` npm package as the forward-looking installer.
  - Kept `vibecoding-installer` as a compatibility package for this release, with migration notices pointing users to `npm install -g mothx-installer@latest`.
  - Renamed npm platform binary packages from `vibecoding-installer-*` to `mothx-installer-*`.

### 🔧 Improvements

- `MaxTokens` now resolves from model defaults and is clamped to the context window size.
- Added compaction timeout and summary token cap settings.
- Command suggestions and `/mode` / `/agent` descriptions clarified to avoid confusion.
- Added HTTP 500 to retryable status codes for provider requests.
- Updated `vibe-browser` to v0.1.3, removed local replace directive.
- Default settings file is now written more sparsely, omitting unset fields.

## v1.1.56

### ✨ Features

- **Interactive Sessions Dialog**
  - `/sessions` now opens an interactive picker dialog with Up/Down navigation, Enter-to-switch, `n` for a new session, and `d` for delete. Existing `/sessions ls`, `/sessions set <id>`, `/sessions clear`, and `/sessions del <id>` commands remain available.
  - TUI startup defers session creation until the first user message is sent, while `--continue`, `--resume`, `--session`, and `/sessions set` still bind to existing sessions.
  - Continuing or switching sessions in the TUI prints the loaded session history into normal terminal scrollback.

- **Stats Web Dashboard**
  - `mothx stats` starts a web dashboard on `127.0.0.1:7878` with charts and filtering.
  - Pure HTML/CSS/JS dashboard — no external dependencies. Charts drawn on `<canvas>`.
  - Displays overall summary (requests, tokens, cost, duration), time-series charts, per-provider/model breakdowns, and a paginated recent requests table.
  - Filters by time range (today/week/month/all), vendor, and protocol.
  - `mothx stats --cli` prints the same statistics directly in the terminal.
  - `mothx stats --db <path>` opens an alternate sessions.db.

- **Stats Dashboard: Protocol + Vendor Split**
  - The "Provider" column in the stats dashboard has been semantically split into **Vendor** (the company/provider name) and **Protocol** (the API protocol, e.g. `openai-chat`, `anthropic-messages`, `google-gemini`).
  - Added `Provider.API()` to the provider interface so the protocol type is recorded alongside the vendor name in `request_stats`.
  - New filter dropdowns for Vendor and Protocol; pie chart and table now show both dimensions.
  - Schema migration 006 adds the `protocol` column to `request_stats` (backfilled with empty string for existing rows).

- **LongCat Provider Support**
  - Added the `longcat` vendor adapter, supporting both OpenAI-compatible (`https://api.longcat.chat/openai`) and Anthropic-compatible (`https://api.longcat.chat/anthropic`) endpoints.
  - Registered two default providers in settings: `longcat` (OpenAI format, `LONGCAT_API_KEY`) and `longcat-anthropic` (Anthropic format, `LONGCAT_ANTHROPIC_API_KEY`).
  - Default model `LongCat-2.0`: 1M context window, 128K max output tokens.
  - TUI auth dialog offers selectable base URLs for OpenAI vs Anthropic format under the `longcat` provider.

- **Inline `<think>` Reasoning for OpenAI-Compatible Models**
  - Added a `parseReasoningInContent` model compat flag for OpenAI-compatible providers. When enabled, reasoning emitted inline in the content stream and wrapped in `<think>...</think>` tags is extracted and surfaced as thinking deltas instead of regular text.
  - The streaming parser correctly handles tags split across multiple SSE chunks and treats dangling partial tags as literal text at stream end.

- **Auth V2 Settings Tracking**
  - Added `fieldSet` tracking to `ProviderConfig` and `ModelConfig` via custom `UnmarshalJSON` implementations, enabling detection of explicitly set JSON fields for auth V2 merge behavior.
  - Custom `Settings.UnmarshalJSON` handles the map-style `providers` key without requiring struct field changes.

- **Project-Level Bash Auto-Approval Rules**
  - `allow.json` now supports `bashCommands` (exact match) and `bashPrefixes` (prefix match) for project-level bash auto-approval in agent mode.
  - The approval dialog offers "Always Allow Exact Command" and "Always Allow Command Prefix" options that persist rules to `.vibe/allow.json`.
  - Settings-level `bashBlacklist` takes precedence over project allow rules (blacklisted commands always require approval).
  - `autoEdit` in `allow.json` now defaults to `true` when no file exists, matching the typical developer workflow.

- **Full Settings Dialog via `/settings`**
  - `/settings` now opens a structured root menu instead of jumping directly into the provider list. Categories: Providers, Defaults, Behavior, Web Search, Context Files, Status Line, Compaction, Sandbox, Paths, Retry, and Approval.
  - Each top-level setting group has its own sub-menu with editable fields, boolean toggles, and list editors.
  - Top-level setting edits use `SaveGlobalSettingsPatch()` to update only the affected JSON key, preventing unrelated defaults from being expanded into `settings.json`.

- **Interactive Approval Dialog**
  - Replaced the inline "y/n" approval prompt with a dedicated dialog supporting ↑/↓ navigation, Enter to select, y/n shortcuts, and Esc to abort.
  - Approval dialog shows structured details per tool type: bash commands display with timeout/async metadata; edit/write show wrapped argument summaries.
  - The footer alert now reads "! APPROVAL REQUIRED: ↑/↓ Enter" to reflect the new interaction model.

### 🔧 Improvements

- Extracted ~1000 lines of embedded dashboard HTML from `internal/stats/dashboard.go` into `internal/stats/dashboard.html`, loaded via `go:embed`.
- Stats are recorded automatically by the agent loop after every LLM call. The stats server calls `session.ApplyMigrations()` on open to ensure the `request_stats` table exists.
- Updated Volcengine provider: added `agentplan` and `codingplan` vendors, unified gitee/moark adapters, and removed the `seed` vendor.
- Updated PyPI build with venv isolation (`.venv-build`) to decouple PyPI builds from system Python.
- Extracted `bashCommandArg()` helper to support both `command` and `cmd` argument keys consistently across the approval path.
- Refactored TUI Esc handling into `abortPendingRequest()` to properly clean up approval and question state.
- Fixed stale `ParamField` / `ParamFieldKey` carry-over when navigating auth dialog views; toggles and submenus no longer leave input mode active.
- Fixed indentation in default provider config model slices.
- Added tests for auth dialog and config field tracking.

## v1.1.54

### ✨ Features

- **Multi-Workspace Session Isolation in Serve**
  - Isolated default HTTP API sessions by work directory (`workDir`) rather than sharing a single global default. Multiple workspace clients no longer share fallback session history.
  - Added `OpenByIDExact` to load session metadata and reconstruction info directly by exact session UUID, ignoring current working directory constraints.
  - Serialized concurrent session creation inside the HTTP API server to safely handle rapid successive calls and prevent duplicates.
  - Improved `/sessions del` slash command to support prefix matching for session IDs and prevent deleting the currently active session.
  - Preserved the serve session slot on `/clear` while cleanly resetting all messages in the session manager.

- **PyPI Installer Packaging**
  - Added a PyPI package wrapper for `vibecoding-installer` that exposes the legacy `vibecoding` console command and ships platform-specific wheels with embedded native binaries.
  - Added `make pypi-*` release targets plus version-sync and wheel-build scripts, mirroring the npm release workflow while using pip's native platform wheel selection.
  - Updated installation and release documentation with `pipx install vibecoding-installer`.

### 💅 Improvements

- **Reliable Fallback Tool Call ID Generation**
  - Switched the fallback tool call ID generator to use a process-wide atomic counter combined with high-precision unique timestamps. This prevents Anthropic/OpenAI schema validation errors under heavy concurrent tool-calling loads.
  - Updated model lists and default configs for several providers, specifically resolving Gemini-specific tool-calling constraints.
  - Preserved customized model parameters in the TUI Auth Dialog on save instead of resetting them to vendor defaults.

### 🐛 Bug Fixes

- **Thinking Level Normalization**
  - Added a normalization step for provider `thinkingLevel`. If the value is empty or invalid, it gracefully falls back to `medium` instead of silently disabling thinking, ensuring reasoning models perform correctly by default.


## v1.1.53

### ✨ Features

- **Embeddable agent: host-provided external tools**
  - Added a public `agent.ExternalTool` interface so embedding applications can expose their own controlled capabilities to the agent alongside (or instead of) the built-in coding tools.
  - Added `ExternalToolResult` (text/error + optional rich `Contents` blocks) and the optional `ExternalToolPromptInfo` interface for contributing system-prompt hints (`PromptSnippet`, `PromptGuidelines`).
  - Added `Builder.WithExternalTools(...)` to register custom tools and `Builder.WithoutBuiltinTools()` to disable all built-in tools, enabling an agent that may only use host-provided tools.
  - External tools are wired through the internal factory via an `externalToolAdapter`, and the internal package now builds from public `Builder` config through `CreateFromPublicOptions`.
  - Added a `bootstrap` package: external modules blank-import `github.com/oschina/mothx/bootstrap` once to register the internal builder and provider resolution hooks (since internal packages cannot be imported directly).

### 💅 Improvements

- **Configured provider models honored end-to-end**
  - Threaded a `ModelID` field through the public and internal `ChatParams` so the selected model flows all the way to the provider request.
  - OpenAI- and Anthropic-compatible providers now resolve their model list and `compat` flags from the provider config when present, falling back to built-in defaults otherwise.
  - Provider factories are now registered through `init` hooks so `ResolveProvider` can construct providers by name via the global registry, with a simplified fallback chain that errors on an unsupported `api`.

- **Provider guide documentation**
  - Added a provider guide (`docs/en/provider-guide.md`, `docs/zh/provider-guide.md`) covering provider/vendor configuration.

- **Bash execution ergonomics**
  - Reduced the default synchronous `bash` timeout to 45s, kept `async=true` for background jobs, and clarified `timeout=0` as an explicit no tool-level deadline.
  - Updated `bash` guidance to steer long-running services to `async=true` and call out network probes and other commands that often need an explicit timeout.
  - In the TUI, tool execution now shows a separate "running" line before the final result line, so long commands are visible while they are still in flight.

- **Internal module split**
  - Split agent, TUI, and command files into focused modules (agent approval/context, TUI paste/render, session/statusline commands) for maintainability, with no behavior change.

### 🐛 Fixes

- **Custom provider auth flow**
  - Fixed the custom provider authentication flow to advance correctly from the API key step to the models step.

## v1.1.52

### 💅 Improvements

- **Provider HTTP/1.1 fallback option**
  - Added `providers.<name>.forceHTTP11` to disable HTTP/2 for a provider HTTP client.
  - This can help with proxies or API gateways that occasionally reset HTTP/2 SSE streams with errors such as `stream ID ... INTERNAL_ERROR`.

- **Retry early provider SSE read failures**
  - OpenAI-compatible, Anthropic, and Google streams now honor the configured `retry` settings when a transient stream read error occurs before any visible output is emitted.
  - HTTP/2 `INTERNAL_ERROR` stream resets are now classified as retryable network errors.
  - Once text, thinking, tool calls, or usage have been emitted, stream read errors still fail immediately to avoid duplicate output.

- **Removed embedded rg/fd binaries — switched to pure-Go SDKs**
  - Replaced the embedded `rg` binary with the [`go-ripgrep`](https://github.com/startvibecoding/go-ripgrep) packages. The `grep` tool now runs ripgrep-compatible search in-process as pure Go, without system `grep` fallback.
  - Replaced the embedded `fd` binary with the [`go-fd`](https://github.com/startvibecoding/go-fd) SDK (`gofd.Find()`). The `find` tool now runs fd-compatible file discovery in-process as pure Go, without system `find` fallback.
  - Deleted the entire `internal/vendored/` package (embed files, binary extraction, `RgPath`/`FdPath`/`Ensure` helpers) and all 12 platform-specific `rg`/`fd` binaries (~42 MB).
  - Removed `scripts/prepare-vendored.sh`, `scripts/extract-vendored-tool.sh`, `scripts/download-ripgrep.sh`, `scripts/download-fd.sh`, and the `pkgs/` directory (cached tarballs).
  - Removed `prepare-vendored` and `test-vendored` Makefile targets; `build`, `build-all`, and `test` no longer depend on binary extraction.
  - The `bash` tool no longer injects `~/.vibecoding/bin` into `PATH`, since there are no extracted binaries to expose.
  - Output format remains line-oriented for `grep` and `find`; invalid roots and search setup errors are reported directly as tool errors.

- **FreeBSD Builds & Packaging**
  - Added FreeBSD `amd64` and `arm64` to the build matrix (`make build-freebsd`), tarball distribution (`make dist-freebsd`), and the full `make dist` / `make build-all` flows.
  - Added FreeBSD platform npm packages (`vibecoding-installer-freebsd-x64`, `vibecoding-installer-freebsd-arm64`) as optional dependencies, with platform detection in the npm wrapper and `install.sh`.
  - FreeBSD uses the pure-Go `grep`/`find` implementations and falls back to the no-op sandbox, since bwrap/seatbelt are Linux/macOS only.

- **Embedded BusyBox for Windows**
  - Embedded `busybox32u.exe` and `busybox64u.exe` assets for Windows, extracted at runtime and used as the default shell for the `bash` tool.
  - Falls back to PowerShell when BusyBox is unavailable.
  - Bash tool output now includes a runtime label indicating whether BusyBox or the system shell is in use.

- **Interactive Model Picker**
  - `/model` without arguments now opens an interactive picker dialog instead of listing models as plain text.
  - Supports search/filter, arrow-key navigation, current-model indicator, and Enter to switch.

- **Native ccstatusline Support**
  - Added `statusLine` configuration (`type`, `command`, `padding`, `refreshInterval`, `timeoutMs`, `fallback`) for external status line renderers.
  - Executes the status line command with a Claude-compatible JSON stdin payload; supports multi-line output, ANSI colors, and OSC 8 hyperlinks.
  - Added `/statusline` slash command (`on`/`off`/`status`/`test`/`refresh`) for runtime control.

## v1.1.51

### ✨ Features

- **New Provider: Volcengine (火山引擎)**
  - Added Volcengine provider with Doubao Seed models via the Ark API platform.
  - Models: Doubao Seed 2.1 Turbo (`doubao-seed-2-1-turbo-260628`, 256K context, text), Doubao Seed Evolving (`doubao-seed-evolving`, 256K context, text+image), Doubao Seed 2.1 Pro (`doubao-seed-2-1-pro-260628`, 256K context, text+image).
  - Uses OpenAI-compatible API endpoint `https://ark.cn-beijing.volces.com/api/v3`.
  - Automatic vendor detection via `ark.cn-beijing.volces.com` domain.

- **SQLite Session Storage**
  - Standardized new and resumed sessions on SQLite (`modernc.org/sqlite`) for improved query performance and metadata management.
  - For CLI and Serve, all session metadata and entry logs are stored in a single, unified `sessions.db` database file under `sessionDir`, using virtual `.db` paths as handles for listing, switching, and deleting. Only Channels writes physical handle files (like `active.db` and archived `*_corrupt.db` files) under per-user directories.
  - Added fast exact/prefix matching in `OpenByID` and `OpenByPathOrID`, including ambiguity detection and direct session reconstruction from the unified SQLite database.
  - ACP history replay now streams tool execution events (`toolCall`/`toolResult`) while loading stored conversation history.
  - `DeleteSession` purges session/entry rows from SQLite, and deletes the physical handle file if present (as in Channels), while refusing to treat the shared `sessions.db` database as a session handle.
  - Channels now uses `active.db` physical session handles, archives corrupt sessions as `*_corrupt.db`, and no longer falls back to legacy `active.jsonl` paths.
  - Removed legacy JSONL load/write paths so new and resumed sessions use SQLite only.

### 🐛 Bug Fixes

- **ACP Systeminit Plan Mode Write Access**
  - Fixed ACP systeminit to allow file writes in plan mode, enabling the TUI/ACP to use `/systeminit` for generating `AGENTS.md` without mode restriction errors.

### ✨ Features

- **`/systeminit` and `/reload` commands**
  - Added `/systeminit` to generate or refresh a project `AGENTS.md` for AI agents. Available in the TUI, ACP, and as the `mothx systeminit` CLI subcommand. In the TUI and ACP the agent heuristically uses the `question` tool to ask a few clarifying questions first, then writes a higher-quality `AGENTS.md`; the CLI runs non-interactively. Optional trailing guidance is supported, e.g. `/systeminit ask me in Chinese, write AGENTS.md in English`.
  - The `question` tool is now also available in `agent` mode (previously plan-only) and is registered for the ACP server, which surfaces questions via the `session/request_permission` channel.
  - Added `/reload` (TUI): restarts as a fresh process with a brand-new session, reloading config, context files, skills, and MCP — equivalent to relaunching the program.

- **Mode boundary enhancements: `/btw` side questions + editable-path whitelist + full auto-edit**
  - Added `/btw <question>`: answer a quick side question without interrupting the main task. It inherits the main conversation history (read-only) into a one-shot sub-agent. The answer is shown in a temporary floating overlay, never written back to the main session, and does not consume the main task's context window or token budget. The sub-agent is read-only (read/grep/find/ls/skill_ref). A long main history is automatically truncated when injected to keep the side query lightweight.
  - Added `/alloweditpath [add <glob>|remove <glob>|clear]`: an auto-edit path whitelist (supports `**`/`*` globs). In agent mode, `write`/`edit` whose path matches the whitelist auto-approve without prompting.
  - Added `/allowautoedit [on|off] [global]`: full auto-edit in agent mode (effectively only bash still needs approval).
  - The whitelist and the auto-edit flag persist to a dedicated `allow.json`: `/alloweditpath` and `/allowautoedit` (default) write the project-level `.vibe/allow.json`; `/allowautoedit on global` writes the global `allow.json`. Loading is global→project override (`editPaths` is project-only). It is auto-loaded on startup.
  - These only relax the approval layer; sandbox / allowedWorkDirs boundaries and plan / yolo semantics are unchanged.

- **Update notifications via npm registry**
  - MothX now checks the npm registry (`vibecoding-installer`) for newer releases and shows a non-blocking reminder at startup when an update is available.
  - Network checks run in the background (at most once per 24h) and only refresh a local cache (`update-check.json`); the foreground never blocks on the network.
  - The reminder appears in the TUI initial message and on stderr in `--print` mode, suggesting `npm install -g vibecoding-installer@latest`.
  - Disable via config file with `"updateCheck": false` in `settings.json`, or with `VIBECODING_NO_UPDATE_CHECK=1`; override the registry with `VIBECODING_NPM_REGISTRY`.

### 📚 Documentation

- Updated session documentation, CLI examples, FAQ cleanup guidance, architecture diagrams, Channels docs, and README feature summaries to describe SQLite-backed storage, `.db` handle files, and `active.db` Channels sessions.
- Added configuration docs for the built-in Volcengine/Doubao provider and refreshed provider-adapter lists to include Volcengine, Mistral, GitHub Copilot, Cloudflare, and Amazon Bedrock adapters.

### 💅 Improvements

- **TUI header and footer polish**
  - Enlarged the ASCII logo and vertically centered it within the header.
  - Dimmed the footer separator and unified the mode/model/path colors for a cleaner look.

## v1.1.50

### ✨ Features

- **Streaming Delta Builder Optimization**
  - Replaced string concatenation with `strings.Builder` for accumulating assistant and thinking text deltas during streaming, avoiding O(n²) memory growth on long responses.
  - Builders are finalized before printing on turn end, approval, and error events to ensure consistent output.

- **New Provider: Mistral**
  - Added Mistral AI provider with models: Mistral Large, Mistral Medium 3.5, Mistral Small, Codestral, Devstral, Magistral Medium/Small, and Pixtral Large.
  - Uses OpenAI-compatible API endpoint `https://api.mistral.ai/v1`.

- **New Provider: GitHub Copilot**
  - Added GitHub Copilot provider with Claude Sonnet 4.6/4.5, Claude Opus 4.8, Claude Haiku 4.5, Claude Fable 5, GPT-5.5/5.4/5.2, Gemini 2.5 Pro, and Gemini 3.5 Flash models.
  - Uses OpenAI-compatible API endpoint `https://api.individual.githubcopilot.com`.

- **New Provider: Cloudflare AI Gateway**
  - Added Cloudflare AI Gateway provider with Claude, GPT, Gemini, and Llama 4 Scout models.
  - Supports routing through Cloudflare's AI Gateway with models from Anthropic, OpenAI, Google, and Meta.

- **New Provider: Cloudflare Workers AI**
  - Added Cloudflare Workers AI provider with Llama 4 Scout 17B, Llama 3.3 70B, Gemma 4 26B, Mistral Small 3.1 24B, GPT OSS 120B/20B, Kimi K2.7 Code, and GLM 5.2 models.
  - Uses Cloudflare's Workers AI inference endpoints.

- **New Provider: Amazon Bedrock**
  - Added Amazon Bedrock provider with Claude Sonnet 4.6/4.5, Claude Opus 4.8, Claude Haiku 4.5, Claude Fable 5, Amazon Nova Pro/Micro/Lite, and DeepSeek V3.2/R1 models.
  - Uses OpenAI-compatible cross-region inference endpoints.

- **Compact TUI Footer and Input Divider**
  - Merged mode, model, and path onto a single footer line (was 3 lines).
  - Added half-block divider between transcript and input area for visual separation.
  - Applied background color to editor cursor and placeholder styles.
  - Added npm postinstall script with quick start info.

### 🐛 Bug Fixes

- **TUI Input Box Width Alignment**
  - Aligned input box width with the gap divider above for consistent layout.
  - Set editor width to full terminal width to match gap divider.
  - Fixed double padding subtraction in editor Width calculation by using `m.width` for the final render Width.

- **TUI `compactBashOutput` Trailing Whitespace**
  - Fixed `compactBashOutput` writing the original untrimmed line instead of the trimmed version after blank-line dedup, which could preserve trailing whitespace.

- **TUI Duplicate Transcript in Program-Backed Scrollback**
  - Cleared managed live content when a Bubble Tea program is active so completed transcript blocks printed to native scrollback via `Program.Println` are not duplicated in the live view.

- **Sandbox Info Label**
  - Removed redundant "YOLO mode" text from the "no sandbox" status display.

---

## v0.1.47

### ✨ Features

- **Expanded Model Catalog**
  - Added new Anthropic models: Claude Opus 4.8, Claude Opus 4.1, Claude Opus 4, Claude Sonnet 4.0, Claude Haiku 4.5, Claude Fable 5, and legacy Claude 3 series models.
  - Added new OpenAI models: GPT-5.5, GPT-5.5 Pro, GPT-5.4 series, GPT-5.3 Codex/Spark, GPT-5.2 Pro/Codex, GPT-5.1 Codex variants, GPT-4.1 series, o4-mini, o3/o3-pro/o3-deep-research, o1-pro, and legacy GPT-4 variants.
  - Added OpenRouter provider models: Claude Sonnet 4.6/4.5, Claude Opus 4.8, Claude Haiku 4.5, GPT-5.5/5.5 Pro/5.4, Gemini 3.5 Flash/2.5 Pro, DeepSeek V4 Flash/Pro, Qwen 3.7 Plus, Kimi K2.7 Code, MiniMax M3, Llama 4 Scout, GLM 5/5.2, Grok 4.3, and GPT-OSS-120B (free).
  - Added Vercel AI Gateway models: Claude Sonnet 4.6/4.5, Claude Opus 4.8, Claude Haiku 4.5, GPT-5.5/5.4, Gemini 3.5 Flash, DeepSeek V4 Flash/Pro, Qwen3.6 Plus, MiniMax M3, Kimi K2.7 Code, Grok 4.3, and GLM 5.2.
  - Reordered Anthropic and OpenAI model lists to show newest models first.

### 🐛 Bug Fixes

- **TUI Approval Details Visibility in Live View**
  - Fixed queued approval requests not showing details in the live transcript while waiting for user input.
  - The current approval message index is now tracked so it stays visible during the approval prompt.
  - Index is properly cleared after approval is answered and reset on state/clear paths.

- **TUI Tool Modal Performance and Display**
  - Added line-level caching for tool modal rendered output to avoid re-parsing the full transcript on every render.
  - Added per-entry caching for expanded tool results to avoid repeated formatting.
  - `invalidateToolModalCache()` is now called at all transcript state mutation points to keep the cache consistent.
  - Fixed edit tool results duplicating diff excerpts in the expanded view by extracting a dedicated edit header formatter.
  - Tool modals now open at the top (offset 0) instead of scrolling to the bottom.

### 🧪 Tests

- Added regression test verifying expanded edit output does not duplicate diff excerpts.

---

## v0.1.46

### ✨ Features

- **Workflow Agent Instance Keys**
  - Added `:key` for repeated logical workflow agents, so bounded `while` loops can keep literal agent names while storing per-round results as `phase.agent[key]`.
  - Added `result-key` and `result-latest`, plus `(result "phase.agent" :key "r0")`, for explicit keyed result lookup and latest-instance lookup.
  - Keyed workflow workers use instance-aware runtime IDs such as `agent-worker[r0]`, preventing repeated loop workers from colliding while preserving the logical agent name.

- **Workflow Lint Tool**
  - Added `workflow_lint` to validate workflow JavaScript DSL without running worker agents.
  - Linting checks JavaScript syntax, workflow/phase/agent forms, keyword arguments, required prompts, and result references.
  - Registered the lint tool alongside workflow run/status/cancel tools and updated workflow prompt guidance to lint non-trivial generated or edited workflows before execution.

- **Configurable Context Compaction**
  - Added compaction settings for `tokenizer`, `tokenizerModel`, and `template`, wired through CLI, print mode, ACP, Serve, Channels, TUI mode switches, and delegated agent factories.
  - Added built-in compression summary templates: `default`, `code`, and `conversation`, so long sessions can preserve task-appropriate checkpoints.
  - Introduced a token estimator abstraction while preserving the existing generic chars/4 estimator for `auto` and `generic`.
  - Compaction entries now record summary version, previous compaction ID, and last summarized entry ID for better session replay/debugging.

### 🐛 Bug Fixes

- **Context Compaction Replay**
  - Print mode now restores replayed session history before running the agent, preserving prior conversation context.
  - Manual and forced compaction now check for genuinely compactable older history instead of compacting only recent context.
  - Replayed compacted messages strip stale usage metadata from kept messages to avoid leaking obsolete token accounting into future runs.

- **Concurrent File Writes**
  - Added a process-wide in-memory file lock manager shared by default tool registries.
  - `write` and `edit` now acquire per-file locks before reading and modifying files, preventing concurrent agents from interleaving writes to the same target.
  - Lock waits honor context cancellation/deadlines and report the current owner when interrupted.

### 🔧 Refactoring

- **Pre-release Packaging**
  - `npm-publish-pre` now syncs and builds npm packages with a `-pre` version suffix before publishing pre-release packages.
  - Updated npm package metadata and optional platform dependency versions to the pre-release version.

- **Named Workflow Worker Agents**
  - Workflow worker agents now use deterministic IDs derived from DSL agent names (`agent-<name>`), improving event attribution and background agent visibility.
  - Workflow skill guidance now documents the ID mapping and recommends unique agent names within a workflow.

### 📚 Documentation

- Updated Workflow mode docs, tool reference, and the `workflow-javascript` skill to document `:key`, keyed result lookup, and bounded while-loop patterns.
- Documented context compaction `tokenizer`, `tokenizerModel`, and `template` settings, including the built-in template choices and the current reserved/deprecated status of idle compaction settings.
- Clarified Ctrl+O details modal key hints for target switching, paging, scrolling, and closing.
- Documented the TUI scrollback trade-off: completed transcript blocks are printed to native terminal scrollback for stable selection/history, while user input should remain block-printed rather than unbuffered streaming to avoid interfering with Bubble Tea live rendering.

### 🧪 Tests

- Added workflow runner, lint, integration, and skill coverage for keyed repeated agents and keyed result lookup.
- Added context compaction tests for custom token estimators, template resolution, configured summary prompts, compaction metadata, compactability checks, and session replay usage cleanup.
- Added Serve and Channels coverage for `/compact` when only recent context can be kept.
- Added workflow lint tests for valid source collection and missing result reference errors.
- Added workflow integration coverage verifying DSL agent names are reflected in runtime worker agent IDs.
- Added file lock tests for wait/cancel behavior, shared default managers, and `write`/`edit` context handling.

---

## v0.1.45

### ✨ Features

- **Workflow Skill with Progressive References**
  - Extracted workflow JavaScript/DSL documentation from the system prompt into a dedicated `workflow-javascript` skill, reducing system prompt size.
  - Introduced progressive reference structure: skill index page lists 9 reference files loaded on demand, with core rules loaded by default.
  - Eight pattern guides: research & investigation, serial & parallel composition, decision routing, bounded while loops, horizontal multi-agent collaboration, master-slave small teams, evaluator-optimizer review passes, and governance & human checkpoints.
  - Each reference file includes copy-ready JavaScript skeleton examples and pattern selection guidance.
  - `EnsureProjectSkill` automatically creates the skill and all reference files under `.skills/workflow-javascript/` without overwriting user-customized content.
- **Workflow Timeout Control**
  - Added optional `timeoutSeconds` support to `workflow_run`, allowing bounded long workflows to choose an appropriate timeout and intentional continuous workflows to set `0` to avoid the default agent-level deadline.

- **goja v0.0.2 Upgrade**
  - Upgraded `goja` dependency from v0.0.1 to v0.0.2 with expanded JavaScript surface.
  - Added support for backquote/comma, `let*`/`while`/`cond`/`catch`/`throw`/`lambda`/`defun`/`defmacro`/`with-current-buffer`/`save-current-buffer` special forms.
  - Added builtins: `cons`/`car`/`cdr`/`nth`/`append`/`reverse`/`member`/`assoc`/`funcall`/`apply`/`macroexpand`, arithmetic and predicate functions, and in-memory buffer + marker builtins.
  - Added comprehensive test coverage for v0.0.2 JavaScript features.

### 🔧 Refactoring

- **Serve Session-Level Skills Support**
  - Serve sessions now support independent `SkillsMgr` and `ExtraContext`, so delegate sub-agents inherit per-session state.
  - `/skill` and `/skills` commands now operate on session-level skills instead of global server-level skills.

- **System Prompt Streamlining**
  - Detailed workflow JavaScript VM syntax and DSL form descriptions removed from the system prompt, replaced by a reference to the `workflow-javascript` skill.
  - Only key constraints and usage notes remain in the system prompt, significantly reducing token usage.

- **Workflow Skill Reference Clarity**
  - Renamed reference file titles for clarity: "Continuous Loops and Iterative Tasks" → "Bounded While Loops", "Evaluator-Optimizer and Critic Loops" → "Evaluator-Optimizer Review Passes".
  - Split pattern selection guidance: bounded while loops for runtime repetition with stop conditions; evaluator-optimizer for one-pass draft/critique/revise pipelines.
  - Added constraint: do not simulate loops with numbered phases.
  - Unified progressive reference status labels to English ("loaded" / "load on demand") for consistency.

### 📚 Documentation

- Added Workflow mode usage guide and best practices documentation (EN/ZH) covering quick start, core concepts, common patterns, and pitfalls.
- Synced workflow references across docs pages: added Dynamic Workflows section to features overview, workflow orchestration scenario to use cases, and cross-links from tools references.
- Clarified workflow hidden defaults and limits in the `workflow-javascript` skill and docs: worker `:max-iterations` default/failure behavior, `workflow_run timeoutSeconds`, `concurrency` default, inherited `:mode`, default `:tools`, current work directory behavior, disabled nested orchestration, and unsupported per-worker options.

### 🧪 Tests

- Added workflow skill tests verifying skill file and 8 reference file creation, non-overwrite behavior, and missing reference auto-creation.
  - Expanded workflow runner and JavaScript test coverage.
  - Added tests for reference content clarity and non-overlap of loop vs evaluator-optimizer patterns.

---

## v0.1.44

### ✨ Features

- **Dynamic Workflows**
  - Added `--workflows` mode for CLI, ACP, and Serve, independent from `--multi-agent`.
  - Added JavaScript workflow tools: `workflow_run`, `workflow_status`, and `workflow_cancel`.
  - Added workflow runtime support for phases, series/parallel execution, concurrency limits, worker-agent tasks, result fan-in, and run logs.
  - Added persistent workflow run state under the MothX workflow store and `/workflows` status commands in TUI and Serve.
  - Added in-process active-run cancellation so `workflow_cancel` and `/workflows cancel <id>` can interrupt running workflows.

- **Z.AI Vendor Adapter**
  - Added `vendor_zai.go` with a dedicated `zai` vendor adapter, registering domains `api.z.ai` and `open.bigmodel.cn` with `thinkingFormat: zai`.
  - Updated `zai` and `zai-coding-cn` provider configs: set `Vendor: "zai"`, `ThinkingFormat: "zai"`, updated base URL to the coding endpoint, added `glm-5v-turbo` vision model.

- **Kimi Provider Updates**
  - Added `api.kimi.com` domain to the `kimi` vendor adapter for automatic vendor detection.
  - Added `User-Agent: KimiCLI/1.5` header to the `kimi-coding` provider config.
  - Added Kimi K2.7 Code and K2.7 Code HighSpeed models to `moonshotai`, `moonshotai-cn`, `fireworks`, and `opencode-go` providers.

- **New Models**
  - Added `GLM-5.2` model to the `opencode-go` provider (1M context, 262K max output).
  - Added Kimi K2.7 Code Fast model to `fireworks` provider.

### 🐛 Bug Fixes

- **TUI Agent Event Handling**
  - Fixed partial response text not being committed to terminal scrollback when an error event occurs mid-stream, ensuring partial content is not lost.
  - Added regression test verifying stream indices and print queue behavior on error.

- **Version Strings**
  - Fixed `Makefile` to use `--abbrev=0` with `git describe` for clean tag versions without commit count/hash suffix.
  - Fixed `sync-npm-version.sh` to strip commit count and hash suffix from version strings.
  - Updated `npm/bin/mothx` to use GitHub raw URL for install script fallback.

### 🔧 Refactoring

- **Agent Manager Deterministic Ordering**
  - `AgentManager.List` now sorts agents by start time then ID for stable, deterministic ordering.
  - Extracted `resetAgent`/`abortAndResetAgent` helpers to reduce code duplication in TUI commands.
  - Agent ID is now set in config when creating agents in TUI.

### 📦 Dependencies

- Added `github.com/startvibecoding/goja v0.0.1` as the embedded JavaScript subset evaluator used by workflow DSL execution.

### 📚 Documentation

- Added the dynamic workflows JavaScript proposal under `docs/proposal/`.
- Updated English and Chinese tool docs with workflow tool usage, JavaScript-only DSL guidance, and cancellation scope.

### 🧪 Tests

- Added workflow runner/store/tool tests covering JavaScript execution, parallel workers, result fan-in, persistence, tool registration isolation, and active-run cancellation.
- Added prompt and CLI flag tests ensuring workflow mode does not leak into multi-agent mode, delegate mode, or worker-agent prompts.
- Added `VendorFromBaseURL` test cases for `api.kimi.com`, `api.z.ai`, and `open.bigmodel.cn`.
- Added agent manager tests verifying deterministic list ordering.

---

## v0.1.43

### 🐛 Bug Fixes

- **TUI Input Flush**
  - Fixed `flushInputQueue` in TUI app to properly return the queued input as a `tea.Cmd`, ensuring queued keystrokes are flushed before processing key events (`Enter`, `Tab`, `Up`, `Down`). Previously the command was called but its return value was discarded.

### 🔧 Refactoring

- **Remove Unused `mergeSettings`**
  - Removed the unused `mergeSettings()` function and its related tests. Project settings merging is now handled directly by `LoadSettings`.
  - Rewrote `settings_zero_test` to test via actual file I/O with `LoadSettings()` instead of direct JSON unmarshaling.

### 📦 Dependencies

- **GoStreamingMarkdown Update**
  - Updated `github.com/startvibecoding/GoStreamingMarkdown` from `v0.0.2` to `v0.0.3`.

### 🧪 Tests

- Added test verifying that `Enter` flushes queued input before applying command suggestions.

---

## v0.1.42

### ✨ Features

- **TUI Multiline Input**
  - Replaced the prompt input with the reusable TUI editor component, enabling true multiline prompt composition.
  - `Alt+Enter` and `Ctrl+J` now insert newlines; `Enter` still submits the prompt.
  - Small multiline pastes are preserved as multiline text instead of flattening newlines to spaces, while large pastes still use paste markers.
  - `Up` / `Down` now move within multiline input first and only browse prompt history at input boundaries.

### 🐛 Bug Fixes

- **TUI Input Editing**
  - `Home` / `End` editing keys now reach the input editor correctly instead of being swallowed by top-level TUI handling.
  - Restored draft-preserving prompt history navigation when queued keystrokes have not yet flushed.
  - `/clear` now resets printed-message bookkeeping after emitting the clear confirmation, avoiding stale transcript print state after clearing.

### 📚 Documentation

- Updated TUI keyboard shortcut documentation for multiline input, newline insertion, history navigation, and tool modal behavior.

### 🧪 Tests

- Added tests for multiline prompt input, `Alt+Enter` / `Ctrl+J`, small multiline paste preservation, prompt history boundary navigation, Home/End input editing, and `/clear` transcript state reset.

---

## v0.1.41

### ✨ Features

- **TUI Redesign**
  - Added a startup header with the Vibe logo, version, provider/model, and current working directory.
  - Added a redesigned footer showing mode, model, cwd, elapsed/last request duration, sandbox, context window usage, cache metrics, and key hints.
  - Added an inline loading indicator while the agent is running, with spinner, elapsed time, and cancel hint.
  - Added a sticky todo list for active non-done `plan` tool steps, so long-running tasks remain visible while the transcript scrolls.
  - Added a multi-agent tab bar showing active agents and their states when more than one agent is running.
  - Added compact tool display mode, toggled with `Ctrl+G`, to collapse tool outputs into one-line summaries while keeping details available through `Ctrl+O`.

- **Terminal Scrollback Transcript**
  - Completed transcript blocks are now printed to native terminal scrollback via Bubble Tea `Program.Println`, leaving only live streaming content inside the managed TUI view.
  - This improves mouse scrolling, terminal selection/copying, and behavior for long transcripts.

- **TUI Component Foundation**
  - Added reusable editor, suggestion list, and vertical scroll components under `internal/tui/components/` with CJK-aware buffer and rendering behavior.

- **Response Formatting Guideline**
  - Updated the system prompt to discourage excessive bold text, headers, and bullet lists unless structure is needed or requested.

### 🐛 Bug Fixes

- **TUI Tool Result Printing**
  - Tool result updates now go through one-time transcript printing instead of only refreshing in-memory live content, preventing completed tool output from disappearing from terminal scrollback.

- **Viewport Cleanup**
  - Removed obsolete viewport state resets after the TUI moved transcript history to terminal-native scrollback.

### 📦 Packaging

- Updated npm installer package metadata and optional platform package versions to `0.1.40`.

### 🧪 Tests

- Added component tests for the new TUI editor, suggestion list, and vertical scroll models.
- Updated TUI cache/render tests for header, footer, native scrollback transcript printing, compact display mode, and simplified viewport behavior.

---

## v0.1.40

### ✨ Features

- **GoStreamingMarkdown Renderer**
  - Replaced Glamour-based Markdown rendering with `github.com/startvibecoding/GoStreamingMarkdown` (`gsm`) for print mode, local TUI, and Channels remote TUI.
  - Removed the local module replacement and now depend on the remote `github.com/startvibecoding/GoStreamingMarkdown` module directly.

- **Delegate Mode (Blocking Single Sub-Agent Delegation)**
  - New `delegate_subagent` tool: runs one sub-agent synchronously, returns a summarized result, enforces a single concurrent delegate limit.
  - `--delegate` CLI flag for root, ACP, and serve commands.
  - `/delegate [on|off|status]` slash command for TUI and serve.
  - `enableDelegate` configuration option in serve config (`serve.json`).
  - Dedicated **Delegation Mode** section in system prompt with context-cost heuristics, good/bad examples, and result interpretation guidance.
  - `AgentFactoryOptions.DelegateEnabled` factory support for programmatic use.
  - Sub-agent system prompt now uses a structured reporting format (`Result`, `Evidence`, `Changes`, `Risks`) with guidelines on negative results, test execution, and conciseness.
  - `delegate_subagent` result includes `tool_calls` count and `tool_breakdown` per-tool-name map.

- **Sub-Agent Execution Mode Inheritance**
  - Both `subagent_spawn` and `delegate_subagent` now inherit the parent agent's execution mode (`plan`/`agent`/`yolo`) instead of hardcoding `agent`.
  - Parent mode is injected via context in `executeSingleToolCall`.
  - Sub-agent policy `AllowedModes` expanded from `["agent"]` to `["plan", "agent", "yolo"]`.

- **Multi-Agent Approval Handling Improvement**
  - Removed the deadlock-prone `newApprovalForwarder` (synchronous approval handler with Mutex-based pending map).
  - Sub-agent approval requests are now forwarded via event channel (`sendParentEvent`) without blocking.
  - TUI tracks `agentID` in `pendingApproval` and dispatches approval responses to the correct sub-agent via `handleApprovalResponse`.

### 🐛 Bug Fixes

- **TUI Abort Reason in Errors**
  - When a TUI agent session is aborted (user presses Esc or mode changes), the abort reason is now included in the error message, e.g., `"Error: aborted (reason: user pressed Esc)"`.
  - `pendingAbortReason` tracked on the TUI `App` struct and cleared on `EventError`.

### 🧪 Tests

- Updated TUI Markdown rendering assertions to match `gsm` behavior while preserving coverage for content integrity and viewport width limits.
- Added `TestDelegateSubAgentTool` and `TestDelegateSubAgentToolMissingTask` to verify blocking sub-agent delegation.
- Updated `TestSubAgentPolicyDefault` to expect expanded allowed modes `["plan", "agent", "yolo"]`.
- Updated `TestAgentManagerEnforcesSubAgentPolicy` to allow `yolo` mode by default.
- Added `TestAgentErrorIncludesAbortReason` for TUI abort reason rendering.

---

## v0.1.39

### ✨ Features

- **Sub-Agent Skills & Plan Tool Inheritance**
  - `AgentFactory` now accepts a `skillsMgr` parameter so sub-agents automatically inherit the `skill_ref` tool from the parent session.
  - Added `EnablePlanTool` to `RegistryConfig`; the `enablePlanTool` setting from `settings.json` is now propagated to sub-agent registries, ensuring consistent tool availability across parent and child agents.

- **Session Compaction Replay State Persistence**
  - Sessions now persist compaction replay state (`ReplayState`) so that compacted sessions can be correctly resumed across restarts.
  - `LoadHistoryState` / `GetHistoryState` track per-message session entry IDs, enabling the compaction boundary (`firstKeptEntryID`) to survive session reload.
  - Serve and Channels use `LoadHistoryState` instead of `LoadHistoryMessages` for accurate post-compaction replay.
  - TUI blocks user input during manual compaction and merges `agentStartMsg`/`compactionStartMsg` into a unified `agentStreamStartMsg`.

- **TUI Viewport Rewrite & CJK Support**
  - Replaced custom ANSI parsing and line-wrapping with `bubbles/viewport` and `charmbracelet/x/ansi`, fixing character interleaving issues with mixed CJK/ASCII text during fast streaming.
  - Think messages now render on a separate path from assistant messages.
  - Long paths and URLs are now word-wrapped correctly without mid-token breaks.
  - Markdown rendering no longer overflows the viewport width.
  - Added `renderutil` package with comprehensive test coverage for mixed CJK/ASCII wrapping, ANSI sequence integrity, and full-file rendering.

- **Grep Tool Output Limiting**
  - The `grep` tool now limits output size during streaming to prevent excessive context consumption from large result sets.

### 🐛 Bug Fixes

- **Google Tool Result Grouping**
  - Fixed tool result grouping logic for Google/Gemini providers to correctly pair tool calls with their results.

- **TUI Compact Command**
  - The `/compact` command now triggers compaction immediately instead of waiting for the next agent turn.

- **Agent Exit Path Consistency**
  - Extracted `agentEndEvent()` helper to eliminate duplicate event emission code across 8 exit paths.
  - Fixed missing `EventAgentEnd` on session-save error paths.
  - Added missing `usage`/`contextUsage` metadata to `EventDone` in the `ShouldStopAfterTurn` path.

### 🧪 Tests

- Added `TestAgentFactorySubAgentsRespectPlanToolSetting` to verify the `enablePlanTool` setting propagates to sub-agent registries.
- Added `TestAgentFactorySubAgentsRegisterSkillRef` to verify sub-agents inherit the `skill_ref` tool when a skills manager is configured.
- Added tests for `agentEndEvent` consistency and `ShouldStopAfterTurn` metadata.
- Added comprehensive TUI tests for fixed-height rendering, CJK wrapping, and ANSI integrity.

---

## v0.1.38

### ✨ Features

- **Custom Provider Model Fallback**
  - When a provider is explicitly requested (via CLI, Serve, or Channels) but no model ID is specified, the factory now automatically falls back to the provider's **first available model** instead of using `settings.DefaultModel` (which belongs to the default provider).
  - This prevents configuration mismatches and "model not found" errors when using non-default providers without a specified model.

- **Channels Configuration Default Resolution**
  - Updated Channels default model resolution so that when `DefaultProvider` is specified in `serve.json` but `DefaultModel` is left blank, the system correctly falls back to the custom provider's first available model instead of propagating the global `DefaultModel` from `settings.json`.

- **Refined Exposed Agent SDK Package & Examples**
  - Completed the mapping for all missing events and fields inside the top-level `agent` bridge (including `Messages`, `TurnMessage`, `TurnToolResults`, `Message`, `ToolCall`, `ToolDiff`, `ToolError`, `PartialResult`, `Plan`, `Usage`, and `ContextUsage`).
  - Fixed a critical enum misalignment on `StreamEventType` caused by internal-only types (like `StreamThinkSignature`), implementing explicit, robust mapping helpers.
  - Implemented `PublicProviderAdapter` to seamlessly bridge internal providers back to the public `agent.Provider` interface, and wired them up automatically to avoid package import cycles.
  - Added two rich top-level examples in the `example/` directory (`simple_agent` and `custom_provider`) with dual-language READMEs, showing custom provider and tool loop execution.

### 🧪 Tests

- Added `TestCreateFallbackToFirstModel` in `internal/provider/factory_test.go` to cover fallback behavior for both custom and built-in providers when the model ID is blank.
- Added test coverage in `internal/serve/channels/config_test.go` for `GetDefaultModel` when `DefaultProvider` is specified in Channels config but `DefaultModel` is empty.

---

## v0.1.37

### ✨ Features

- **Vertex AI API Key Authentication**
  - Added support for authenticating directly with Google Vertex AI using API keys (`x-goog-api-key`) instead of requiring gcloud OAuth tokens (`ya29.`).
  - When an API key is used, the default base URL automatically routes to `https://aiplatform.googleapis.com/v1/publishers/google/models` (which doesn't require project/location parameters).
  - Keeps backward compatibility with existing OAuth bearer tokens.

### 🐛 Bug Fixes

- **Google Tool Thought Signatures**
  - Correctly extract and forward Gemini reasoning/thought signatures in tool calls, preventing any misalignment or signature mismatches.

- **TUI Raw Bash Output Preservation**
  - Preserved ANSI escape codes and raw spacing/newlines in Bubble Tea TUI rendering for `bash` tool results, avoiding accidental italic style inheritance from the TUI framework.

---

## v0.1.36

### ✨ Features

- **Doctor Subcommand** (`mothx doctor`)
  - New diagnostic command that checks environment, configuration, providers, sandbox, MCP servers, sessions, skills, and context files
  - Reports OS/arch, Go version, shell, home/working directory
  - Validates settings, serve, and MCP config files with parse checks
  - Lists configured providers with masked API keys, models with context window/max tokens/reasoning flags
  - Checks bwrap sandbox availability and version
  - Shows MCP servers, session counts, skills directories, and discovered context files
  - Unconfigured providers (no API key) are silently skipped

### 🐛 Bug Fixes

- **TUI Session State**
  - Fixed `/clear` to reset transcript rendering state, tool results, assistant markdown caches, active stream indices, plan panel, and tool modal state consistently with session switching
  - Extracted shared transcript/input reset helpers to reduce divergent cleanup paths

- **TUI Mode Switching**
  - Pressing Tab to cycle mode now aborts an active request before changing mode, matching `/mode` behavior and preventing approval/question responses from targeting a stale agent

- **TUI Question Tool**
  - Numbered question selections now resolve to the selected option text instead of sending raw numbers back to the model
  - Clearing question state now also clears the current question metadata

- **TUI Warnings and Details Modal**
  - Context-pressure and budget-pressure agent events are now displayed in the TUI
  - Ctrl+O now reports when there is no conversation detail to show instead of opening an empty modal

- **Context Pressure Threshold Comparison**
  - Fixed Context Pressure threshold unit mismatch: `Percent` (0-100) was compared directly against `threshold` (0-1), causing the warning to fire at ~0.5% usage instead of the intended 55%
  - Fixed `InitChannelsConfig` project template to include explicit `context_pressure_threshold` and `budget_pressure_threshold` defaults, preventing them from being serialized as 0 (disabled)

- **Live Message Rendering**
  - Live assistant messages render fenced code blocks as Markdown while keeping normal prose on the plain-text wrapping path to avoid awkward word splitting

- **Model Validation and Compaction**
  - Pass `ModelID` in `ChatParams` so providers know the active model
  - Forward model to compaction/summary generation, preventing silent fallback to default model
  - Return errors with available model list when model is not found instead of silently falling back
  - Consistent model error messages across factory, serve, and TUI

- **Google/OpenAI Tool Result Text Extraction**
  - Fixed Google and OpenAI providers sending empty content when tool results use rich `Contents` blocks instead of plain `Content` string
  - Added `googleToolResultText()` to extract text from `Contents` blocks in Google provider
  - Fixed `responseToolOutput()` usage in OpenAI rich tool result branch

### 🧪 Tests

- Added regression coverage for `/clear` transcript cleanup, question state tracking, empty details modal handling, pressure warnings, live code-block rendering, and prose wrapping
- Added agent-level integration test (`TestToolResultIsIncludedInNextProviderTurn`) verifying tool results with rich `Contents` blocks reach the next provider turn
- Added provider-level unit tests for Google and OpenAI tool result text extraction from `Contents` blocks

## v0.1.35

### 🐛 Bug Fixes

- **TUI Print Ordering**
  - Replaced ad-hoc `go program.Println(...)` goroutines with a single drain goroutine (`printCh`) to prevent message interleaving on Bubble Tea's unbuffered channel
  - `flushPendingPrints` now uses `tea.Sequence` instead of `tea.Batch` to preserve print order

- **Display Width Accuracy**
  - `truncate()` now uses `lipgloss.Width` instead of byte length, so CJK characters (2 cells) and ANSI escape sequences (0 cells) align correctly in the TUI grid
  - Tool modal title separator uses `lipgloss.Width` for correct line width

- **Tool Output Improvements**
  - `ls` tool result now shows a compact summary (blank-line removal) in collapsed view, matching `bash` output behavior
  - Tool result rendering handles multiline summaries with a newline separator instead of forcing everything onto one line

### 🧪 Tests

- Added `formatters_test.go` with display-width-aware truncation tests for ASCII, CJK, and mixed content

## v0.1.34

### ✨ Features

- **Channels Remote TUI Client**
  - Replaced the plain-text WebSocket client with a full Bubble Tea TUI for the serve WebSocket channel
  - Markdown rendering with syntax highlighting via Glamour
  - Scrollable tool details modal (Ctrl+O), approval prompts (Enter/Esc), and question tool support
  - Plan update display, context pressure/budget warnings, and request timers
  - Native terminal scrollback for completed messages
  - Slash command support (`/clear`, `/mode`, `/model`, `/compact`, `/help`, etc.)
  - New `internal/serve/channels/remotetui` package: `app.go`, `render.go`, `input.go`, `remote.go`, `agent_events.go`, `approval.go`, `commands.go`, `formatters.go`, `tool_modal.go`, `events.go`

- **WebSocket Protocol Enhancements**
  - Added `question_request` / `question_response` events for plan-mode question tool over WebSocket
  - Added `plan_update` events with structured plan step data
  - Added `compaction_start` / `compaction_end` events for context compaction progress
  - `connected` event now includes `model` and `work_dir` metadata
  - `approval_request` event now carries `approval_tool` and `approval_args` for richer client-side display

- **Dispatcher Refactor**
  - Extracted `buildAgent()` from `runAgent()` for agent creation and cleanup, improving reuse between messaging and WebSocket paths

- **Provider Custom Headers**
  - Added `providers.<name>.headers` for custom HTTP headers on provider requests
  - Header values support the same `${ENV}` and opt-in `!cmd` resolution as `apiKey`

### 🧪 Tests

- Added WebSocket runtime server tests for connection, auth, chat, approval, question, and command flows

## v0.1.33

### ✨ Features

- **Multiple Project Skill Directories**
  - Skills manager now supports loading from both `.skills/` and `skills/` directories in the project root
  - Priority order: `.skills/` > `skills/` > global skills directory
  - New `NewManagerWithProjectDirs` constructor accepts explicit project dirs in priority order
  - New `ProjectSkillDirs` helper returns the standard project skill directory list
  - Updated all call sites: CLI, ACP, and serve
  - Added tests for multi-directory priority and plain `skills/` directory loading

## v0.1.32

### ✨ Features

- **Tool System Completeness**
  - Added full documentation for all registered tools: `jobs`, `kill`, `question`, `memory`, `cron`, and MCP dynamic tools
  - `jobs` tool: list and inspect background jobs started with `bash async=true`, with optional cleanup
  - `kill` tool: terminate a running background job by ID
  - `question` tool: AI can ask users multiple-choice questions during plan mode to clarify requirements
  - `memory` tool (Channels): persistent memory via `memory.md` with read/add/update/delete actions across sessions
  - `cron` tool (Channels/multi-agent): scheduled background tasks via sub-agents with `@daily`, `@weekly`, `@every N` schedules and one-shot support
  - MCP dynamic tools: tools/resources/prompts from MCP servers are auto-discovered and registered per session

- **Plan Mode Question Tool**
  - Added `question` tool, registered only in TUI + plan mode
  - AI can ask users multiple-choice questions; users select a preset option or type a custom answer
  - Helps clarify requirements before forming a plan, producing higher-quality proposals
  - Exposed via `QuestionHandler` optional interface (type assertion); does not pollute the public `Agent` interface

### 🐛 Bug Fixes

- **Bash Tool Output Safety**
  - Synchronous bash mode now enforces a 1 GB output limit using `limitedBuffer`, preventing OOM from unbounded `bytes.Buffer` growth

- **Channels `/compact` Command**
  - Implemented the `/compact` slash command for Channels messaging mode (previously a TODO stub)
  - Sets a `ForceCompact` flag on the session, consumed by the next agent run to trigger context compaction

- **Session Durability**
  - `writeEntry` now calls `f.Sync()` after writing, guaranteeing data survives crash or power loss
  - Corrupt session lines are now logged as warnings and skipped instead of blocking session load

- **Channels Approval Race Condition**
  - `ResolveApproval` now uses `select` to avoid writing to an already-consumed channel when timeout and approval race

- **Agent Sub-agent Panic Logging**
  - `sendParentEvent` now logs the panic value before recovering, aiding diagnosis of closed-channel races

- **Atomic File Write Cleanup**
  - `writeFileAtomic` no longer uses `defer os.Remove(tmpPath)` which would attempt to delete an already-renamed file; cleanup is now explicit on each error path

- **Agent Loop Detection Configurability**
  - `MaxConsecutiveNoText` (stuck-detection threshold) is now configurable via `AgentLoopConfig` (default 95)
  - Fixed incorrect error message that added pre- and post-warning counters together

- **Job Manager Auto-cleanup**
  - `AddJob` now garbage-collects finished jobs older than 30 minutes (checked every 5 minutes)

- **Cron Scheduler Error Logging**
  - `checkAndRun` now logs store errors instead of silently swallowing them

- **TUI Bash Output Display**
  - Compressed bash tool output summary by removing blank lines to prevent excessive vertical height in the TUI collapsed view

- **Vendored Search Tools**
  - Added fallback to system `grep` / `find` when embedded `rg` / `fd` are unavailable for the current architecture

### 📦 Distribution

- Added Linux LoongArch64 (`loong64`) build and packaging targets, including tarball, Debian, and npm package metadata

### ✅ Tests

- Added unit tests for `limitedBuffer` truncation, `JobManager` GC, `writeFileAtomic` cleanup, `sendParentEvent` panic recovery, `MaxConsecutiveNoText` configurability, session fsync durability, corrupt-line tolerance, and `QuestionTool` metadata/mode-filtering/execution/error-handling


## v0.1.31

### 🐛 Bug Fixes

- **Terminal Input**
  - Added Home/End cursor movement support in the TUI input box
  - Fixed the first submitted input being swallowed after canceling an approval prompt with Esc
  - Added command history navigation with Up/Down, including repeated selection through previous inputs

- **A2A Security and Reliability**
  - Changed the default A2A host from `0.0.0.0` to `127.0.0.1`
  - Added Bearer token authentication for `/a2a`, REST A2A routes, and SSE events while keeping the Agent Card public
  - Replaced timestamp-based A2A task IDs with collision-resistant random IDs
  - Made A2A task store reads and writes use cloned task snapshots to avoid accidental shared mutation

- **Path and Session Safety**
  - Fixed path containment checks to use path-aware boundaries instead of string prefix checks
  - Prevented context `extraFiles` from escaping the working directory
  - Encoded unsafe Channels session path components and enforced `allowed_work_dirs` during session creation
  - Restricted session deletion to `.db` files under the configured session directory

- **Auth, Approval, and Resource Limits**
  - Switched Channels HTTP/WebSocket token checks to constant-time comparison
  - Changed the Channels WebSocket client to send auth via `Authorization: Bearer ...` instead of query strings
  - Cleaned up pending ACP permission requests on timeout and propagated ACP write errors
  - Added request/body size limits for ACP, read-tool image files, WeChat responses, and cron A2A responses
  - Added timeouts to cron A2A HTTP calls

- **Memory, Context, and Concurrency**
  - Added locking to memory store operations
  - Fixed `memory.WriteAll()` path handling and kept memory update/delete scoped to the requested section
  - Cloned API model settings before per-request `temperature`/`top_p` overrides
  - Passed agent callback context/message snapshots instead of shared references
  - Serialized cron job state transitions through the job store

- **Configuration and Serve Hardening**
  - Gated `!command` API key resolution behind `VIBECODING_ALLOW_SHELL_CONFIG=1`
  - Fixed Serve CORS to echo only the allowed request origin
  - Added a startup warning when Serve listens beyond loopback in `yolo` mode without authentication
  - Hardened platform home/shell fallback behavior

### 🧪 Tests

- Added regression coverage for A2A auth, task ID uniqueness, task snapshot isolation, and persisted working task messages
- Added coverage for path traversal, unsafe session IDs, memory section operations, ACP cleanup, CORS behavior, UTF-8 truncation, and shell-config opt-in
- Ran focused package tests plus race tests for A2A, agent, serve, and cron

### 📝 Docs

- Updated A2A, Channels, Serve, configuration, and security docs for the new authentication and hardening behavior

## v0.1.30

### ✨ Features

- **Per-Provider HTTP Proxy**
  - Added `providers.<name>.httpProxy` to route individual providers through different HTTP proxies
  - Kept default environment proxy behavior when a provider does not set `httpProxy`

- **Google Gemini and Vertex Vendor Adapters**
  - Added native `google-gemini` and `google-vertex` providers using Google `streamGenerateContent`
  - Enabled base URL detection for Gemini API and Vertex AI native Gemini endpoints
  - Added default Google provider templates for Gemini API keys and Vertex bearer tokens
  - Updated provider documentation and lookup coverage for Google vendor names

- **Hosted Web Search Tool**
  - Added `--web-search` for CLI and ACP runs
  - Added top-level `webSearch` settings with `enabled`, `provider`, `providerType`, and `model`
  - Registered hosted `web_search` tools only when enabled, keeping them separate from local function tools
  - Added OpenAI Responses API mapping to `web_search`
  - Updated Responses web search mapping to provider-neutral `web_search`, so compatible custom providers are not required to be named `openai`
  - Added Anthropic Messages API mapping to `web_search_20250305`
  - Preserved `webSearch.model` as provider-neutral metadata for future routing and cost display

- **Default Provider Templates**
  - Added built-in default provider entries for OpenAI, Anthropic, and Xiaomi MiMo
  - Kept DeepSeek providers and `deepseek-openai` as the default provider/model
  - First-run `settings.json` now includes disabled web search configuration plus OpenAI/Anthropic/Xiaomi provider templates

### 🧪 Tests

- Added coverage for hosted web search tool serialization across OpenAI Responses and Anthropic Messages
- Added coverage for web search configuration defaults, CLI flag parsing, and hosted tool metadata propagation
- Added coverage for macOS default config directory resolution

### 🐛 Bug Fixes

- **macOS Config Directory**
  - Unified the default macOS global config directory with Linux at `~/.vibecoding`

- **Release Versioning**
  - Removed the default `dirty` suffix from npm and distribution package version detection
  - Normalized npm package metadata to `0.1.30`

## v0.1.29

### 🐛 Bug Fixes

- **NPM Package Wrapper**
  - Fixed `npm/bin/mothx` entry script to ensure installer packages ship the correct executable wrapper
  - Adjusted `build-npm.sh` and `build-npm-packages.sh` to include the wrapper consistently

## v0.1.28

### ✨ Features

- **Per-Model Temperature/Top-P Configuration**
  - Added `temperature` and `top_p` fields to `ModelConfig` and `Model` for per-model parameter tuning
  - Wired through OpenAI and Anthropic providers with `omitempty` — `nil` means use API default
  - Wired through provider factory, agent loop, and ACP mode
  - Serve supports per-request `temperature`/`top_p` override via `ChatParams`
  - When not configured, parameters are omitted entirely (no zero-value sent to API)

- **OpenAI Responses API Support**
  - Added a dedicated OpenAI Responses provider path under `api: "openai-responses"`
  - Supports Responses streaming, tool calls, reasoning summaries, and prompt cache parameters
  - Responses configuration is exposed under provider `responses` settings with default prompt cache enabled
  - Added model compat flags for `supportsPromptCacheKey` and `supportsReasoningSummary`

### 🧪 Tests

- Improved provider test coverage for OpenAI Responses API and Anthropic request parsing
- Reworked Anthropic tests to use in-memory HTTP mocks instead of port-binding test servers

### 📝 Docs

- Updated `AGENTS.md` version to v0.1.28

## v0.1.27

### ✨ Features

- **Serve Mode** (`mothx serve`)
  - New messaging channel mode for WeChat, Feishu, and WebSocket
  - Persistent per-user sessions with auto-archiving on `/new`
  - Default `yolo` mode for unattended operation
  - Smart approvals with tiered risk classification (low/medium/high)
  - User whitelist for platform access control
  - WebSocket streaming: real-time text_delta/think_delta/tool_call/tool_result/tool_diff/usage/done events

- **A2A Protocol** (`mothx a2a`)
  - New Agent-to-Agent protocol server (JSON-RPC 2.0 over HTTP + SSE streaming)
  - Standalone mode: `mothx a2a start` (port 8093)
  - Agent Card at `/.well-known/agent.json`
  - Task lifecycle: submitted → working → completed/failed/canceled
  - REST endpoints: `/a2a/send`, `/a2a/task`, `/a2a/task/cancel`, `/a2a/events`
  - **A2A Client**: `mothx a2a send <message>` to send tasks to other A2A servers
  - **A2A Discovery**: `mothx a2a discover <url>` to fetch remote Agent Cards
  - **A2A Scheduling**: Cron jobs support `--a2a-target` to schedule tasks to A2A servers

- **A2A Master Mode** (`--enable-a2a-master`)
  - Configure multiple remote A2A agents via `a2a-list.json`
  - Registers `a2a_dispatch` tool for the LLM to automatically dispatch tasks to remote agents
  - Supports global (`~/.vibecoding/a2a-list.json`) and project-level (`.vibe/a2a-list.json`) config
  - `--init-a2a-master-config` generates a sample config file
  - Disabled by default, requires explicit opt-in

- **A2A Config Initialization**
  - `mothx a2a --init-a2a-config` generates `a2a.json` config template
  - `mothx --init-serve` generates `serve.json` config template (existing)
  - `mothx --init-a2a-master-config` generates `a2a-list.json` config template
  - All `--init-*` flags support `--force` to overwrite existing files

- **Scenarios & Walkthroughs Documentation**
  - New `docs/scenarios.md` (zh + en) covering 9 practical usage scenarios
  - Covers: daily coding, CI integration, multi-agent, VS Code ACP, A2A server,
    A2A Master cross-machine dispatch, Serve HTTP, Channels messaging, combined modes

- **Documentation Overhaul**
  - `architecture.md`: added all missing modules (a2a/acp/serve/mcp/memory/messaging/vendored)
  - `tools.md`: added `a2a_dispatch` and `skill_ref` tool docs
  - `cli-reference.md`: added `--enable-a2a-master`, `--init-a2a-master-config`,
    `--init-serve`, `--force`, `a2a` subcommand docs
  - `README.md`: updated architecture diagram, added running modes overview

- **Pressure System**
  - Context Pressure: `EventContextPressure` fired at 55% context usage (configurable via `context_pressure_threshold`)
  - Budget Pressure: `EventBudgetPressure` fired at 20% remaining iterations (configurable via `budget_pressure_threshold`)
  - One-shot events: fire once per threshold crossing, not every turn
  - Messaging platforms receive pressure warnings via progress callback

- **Smart Approvals (Tiered Strategy)**
  - Low risk: auto-approve
  - Medium risk: auto-approve + notify user
  - High risk (WebSocket): send `approval_request`, wait for user `approval_response` (5min timeout)
  - High risk (messaging): auto-reject + notify user
  - Command risk classification: low/medium/high based on bash command patterns

- **Provider/Model Configuration**
  - `default_provider` / `default_model` in `serve.json` (overrides `settings.json`)
  - CLI flags `-p`/`--provider` and `-m`/`--model` for `mothx serve`
  - Priority: CLI flags > `serve.json` > `settings.json`

- **Multi-Agent Mode** (`--multi-agent`)
  - Enables sub-agent tools (spawn/status/send/destroy) in serve channel sessions
  - Configurable via `serve.json` `multi_agent` field or `--multi-agent` CLI flag

- **Sandbox Mode** (`--sandbox`)
  - Optional bwrap sandbox isolation (disabled by default)
  - Configurable via `serve.json` `sandbox` field or `--sandbox` CLI flag

- **MCP Integration**
  - Channels automatically loads MCP servers from global/project `mcp.json`
  - MCP tools registered per-session, connections auto-closed on session removal

- **Progress Events for Messaging Platforms**
  - Real-time tool execution progress sent to WeChat/Feishu during agent runs
  - Format: `[tool]: args ✅/❌` for tools, `💭 ...` for thinking process
  - Final summary sent after agent completes

- **Memory Tool**
  - `memory` tool with read/add/update/delete actions
  - Section-level operations (User Profile, Working Memory, Lessons Learned)
  - Defaults to `.vibe/memory.md` (project directory)
  - Lookup priority: `memory.path` config → `.vibe/memory.md` → `<GLOBAL_DIR>/memory.md`
  - `/api/memory` HTTP endpoint (GET/PUT) for memory access

- **Serve Channel Management**
  - `mothx serve` — start the unified API, Web UI, and channel runtime
  - `mothx serve init-config` — create `serve.json`
  - Web UI and serve APIs manage channel status, sessions, memory, webhooks, and cron jobs
  - `a2a start/stop/status/card` — A2A server management

### 📝 Changes

- WeChat iLink implementation with zero external dependencies (5 files: types/protocol/auth/crypto/wechat)
- Feishu bot with official SDK and WebSocket long-connection
- Shell hooks for pre/post tool call external scripts (JSON stdin/stdout)
- Webhook inbound routing with HMAC-SHA256 signature verification
- WebSocket uses `golang.org/x/net/websocket` (stdlib compatible)
- Serve runtime process lifecycle management

### 🐛 Bug Fixes

- **NPM Installer Packaging**
  - Fixed release packaging flow so `vibecoding-installer` always ships executable entry `bin/mothx`.
  - Added `scripts/npm-installer-wrapper.js` as the single source of wrapper logic, reused by both
    `scripts/build-npm.sh` and `scripts/build-npm-packages.sh` to avoid drift.
  - Adjusted `npm/.npmignore` and `npm/bin` handling to avoid shipping accidental build artifacts and to keep
    package manifests (`files`) explicit.

- **Channels Webhook Delivery and Filtering**
  - Webhook routes now treat unknown event types as non-matching unless the route explicitly allows `*`.
  - Added `delivery_target` to webhook routes so WeChat/Feishu delivery has a concrete recipient.
  - Updated webhook route listing and config templates to show the delivery target when present.

- **OpenAI Responses Thinking Mapping**
  - Mapped `--thinking xhigh` to `reasoning.effort: "high"` for the OpenAI Responses API.

### 🧪 Tests

- Reworked webhook router tests to wait on handler completion instead of sleeping, removing a race/flakiness source.
- Added coverage for webhook event rejection when the event type cannot be inferred.
- Added coverage for webhook delivery target handling.

## v0.1.26

### ✨ Features

- **Serve Mode** (`mothx serve`)
  - New HTTP server exposing a standard OpenAI Chat Completions API (`/v1/chat/completions`, `/v1/models`, `/health`)
  - Any OpenAI-compatible client (Cursor, Continue, Open WebUI, Python SDK, etc.) can connect directly
  - Streaming (SSE) and non-streaming responses fully supported
  - Backend powered by MothX agent loop with tool execution transparent to the caller

- **Multi-Session Support**
  - Built-in `SessionPool` for concurrent sessions, each with isolated agent, tools, and message history
  - Session association via `x_session_id` in request body; auto-created when absent
  - Configurable idle timeout (`session.idleTimeoutSeconds`) and max session limit (`session.maxSessions`)

- **Sub-Agent Support in Serve**
  - Optional `enableSubAgents` config to enable multi-agent orchestration in serve mode
  - Reuses existing `AgentFactory` / `AgentManager` / sub-agent tools with no core agent changes

- **Bearer Token Authentication**
  - Configurable via `serve.json` with `auth.enabled` and `auth.tokens` list
  - Disabled by default; `/health` endpoint always unauthenticated

- **Slash Commands via API**
  - `/clear`, `/mode`, `/model`, `/models`, `/sessions`, `/compact`, `/status`, `/skill`, `/skills`, `/help`
  - Triggered when the last user message starts with `/`; processed at the serve HTTP layer without invoking LLM
  - Responses use standard OpenAI format with `x_command` extension field

- **Tool Visibility Configuration** (`toolVisibility.mode`)
  - `"content"` (default): tool status sent as text in `content` field during streaming
  - `"sse_event"`: tool status sent as extended SSE events for custom clients
  - `"none"`: fully transparent, client sees only final text

- **System Prompt Handling** (`systemPromptMode`)
  - `"append"` (default): client system messages appended to built-in system prompt
  - `"ignore"`: client system messages discarded entirely

- **Security: allowedWorkDirs**
  - Directory whitelist for `x_working_dir` request-level overrides with path-separator-aware prefix matching
  - Three-layer security model: L1 auth + L2 directory control + L3 sandbox (bwrap)

- **Sandbox Support in Serve**
  - Configurable via `serve.json` `sandbox.enabled` / `sandbox.level` or `--sandbox` flag
  - Inherits detailed sandbox settings (allowedRead, deniedPaths, etc.) from `settings.json`

- **Serve Configuration** (`serve.json`)
  - Independent config file at `~/.vibecoding/serve.json`
  - Covers: listen address, auth, mode, sandbox, workingDir, allowedWorkDirs, session management, CORS, tool visibility, system prompt mode, request timeout, concurrency limit, logging
  - `mothx --init-serve` to generate template; `--force` to overwrite

- **Request Timeout & Concurrency**
  - `requestTimeoutSeconds` (default 1800s); streaming keeps alive as long as data flows
  - `maxConcurrentRequests` (default 0 = unlimited)

### 📝 Docs

- Added an API server proposal with full architecture, API design, security model, and implementation plan
- Updated `AGENTS.md` version note

## v0.1.25

### ✨ Features

- **Multi-Agent Mode**
  - Added opt-in `--multi-agent` support across CLI, TUI, and ACP mode
  - Added `AgentManager`, `EventRouter`, and per-agent registries so agents have isolated tools, job managers, sessions, messages, and context
  - Added `subagent_spawn`, `subagent_status`, `subagent_send`, and `subagent_destroy` tools for delegated background work
  - Added multi-agent prompt guidance and safeguards that prevent nested sub-agent spawning

- **Cron Task Support**
  - Added `internal/cron` with persistent cron store and scheduler coverage
  - Added `/cron` command entry points in multi-agent TUI workflows

- **Provider Vendor Adapter Layer**
  - Added vendor adapter registration in `internal/provider/vendor*.go`
  - Centralized provider/model creation in `internal/provider/factory`
  - Added vendor detection for DeepSeek, Xiaomi, Kimi, MiniMax, Seed, Qianfan, Bailian, Gitee, OpenRouter, Together, Groq, Fireworks, OpenAI, and Anthropic
  - Preserved existing provider config format while allowing vendor-specific defaults and generic OpenAI/Anthropic-compatible fallback
  - Added model `compat` handling for thinking formats, reasoning effort support, max token field selection, adaptive Anthropic thinking, and DeepSeek/Xiaomi assistant `reasoning_content`

### 🐛 Bug Fixes

- Auto-initialized sessions on first append so sub-agents can write session entries without requiring explicit prior initialization
- Fixed sub-agent tests to wait for background runs and clean up spawned agents before temporary directory removal
- Preserved ACP Anthropic cache-control behavior while moving provider creation to the shared factory

### 📝 Docs

- Updated `AGENTS.md` with provider factory and vendor adapter guidance
- Replaced the multi-agent implementation checklist with a completed architecture/status document
- Removed the obsolete root `todo.md`

### 🧪 Testing

- Added coverage for provider vendor resolution, provider factory creation, OpenAI/Anthropic compat behavior, multi-agent manager/router/sub-agent flows, cron storage/scheduler behavior, and session auto-initialization
- Verified with `make test` (`go test -v -race ./...`)

---

## v0.1.24

### ✨ Features

- **API Retry with Exponential Backoff**
  - Automatic retry for transient errors (5xx, network failures, rate limits) on initial HTTP connection
  - Exponential backoff: `baseDelay × 2^attempt`, capped at 30 seconds
  - Does NOT retry on user abort (`context.Canceled`), 4xx client errors, or mid-stream failures
  - Configurable via `retry` settings (`maxRetries`, `baseDelay`, `maxDelay`)
  - Agent forwards retry events as status updates visible in TUI and print mode
  - ACP mode also receives retry configuration

### 🐛 Bug Fixes

- **Anthropic `cache_control` Now Opt-In**
  - Changed default `cache_control` behavior to off (was auto-enabled for official API base URL)
  - Require explicit `cacheControl: true` in provider config to enable prompt caching
  - ACP provider creation explicitly enables `cache_control` for Anthropic

- **Anthropic Tool Result Grouping**
  - Fixed consecutive `toolResult` messages to be grouped into a single `user` message
  - Anthropic API requires all `tool_result` blocks for preceding `tool_use` to appear together before other content
  - Image blocks from tool results are now appended after all result blocks in the same message
  
- **Agent Tool-Only Loop Warning Ordering**
  - Moved the no-text tool-loop warning to be injected after tool results are appended
  - Keeps assistant -> toolResult -> warning message ordering valid for provider and session transcripts
  - Warning messages are now also persisted to session storage

### 📝 Docs

- **Comprehensive Configuration Documentation Rewrite**
  - Added missing settings: `cacheControl`, idle compression, full sandbox fields (`bwrapPath`, `allowedRead`, `allowedWrite`, `deniedPaths`, `passEnv`, `tmpSize`), `shellPath`, `shellCommandPrefix`, `sessionDir`, `skillsDir`, `theme`, `retry`
  - Documented shell command `apiKey` format (`!cmd`) for password manager integration
  - Fixed key resolution order: config `apiKey` first, then derived env var
  - Updated macOS config path documentation
  - Added top-level fields reference table with all defaults
  - Added per-platform defaults for sandbox paths and env vars
  - Improved examples with Claude provider `cacheControl`, idle compression, project-level overrides, and custom sandbox paths

### 🧪 Testing

- Added retry tests covering `IsRetryable`, `RetryDelay`, and `FormatRetryMessage`
- Added Anthropic provider tests for consecutive tool result grouping
- Added a regression test covering tool-only warning placement after tool results


---

## v0.1.23

### 🛠 Improvements

- **DeepSeek Thinking Format**
  - Added `thinkingFormat: "deepseek"` for DeepSeek reasoning requests
  - OpenAI-compatible requests now send `thinking: {type: "enabled"}` with `reasoning_effort`
  - Anthropic-compatible requests now send `thinking: {type: "enabled"}` with `output_config.effort`
  - Kept `thinkingFormat: "xiaomi"` as the legacy thinking-only format

### 🧪 Testing

- Added provider tests covering the new `deepseek` thinking format for both OpenAI- and Anthropic-compatible requests

### 📝 Docs

- Updated `anthropic-api` skill and configuration docs for the new `thinkingFormat` option

---

## v0.1.22

### ✨ Features

- **CLI/TUI MCP Auto-Loading**
  - CLI/TUI startup now loads global and project `mcp.json`, connects configured MCP servers, and registers MCP tools before the agent tool list is frozen

### 🐛 Bug Fixes

- **Markdown Rendering Style**
  - Switched CLI print mode and TUI markdown rendering from Glamour auto-style detection to the fixed `dark` style for more consistent terminal output

### 🧪 Testing

- Added MCP config loader coverage for placeholder template filtering

### 🛠 Improvements

- **Shared MCP Runtime**
  - Moved MCP connection/tool registration out of ACP-only code into a shared runtime used by ACP and normal CLI/TUI sessions
  - Starter-template placeholder MCP servers are ignored during automatic startup loading

---

## v0.1.21

### ✨ Features

- **Plan/Apply Workflow**
  - Added a built-in `plan` tool for structured task plans with `pending`, `running`, `done`, and `failed` step statuses
  - TUI now shows the current task plan and records plan updates in the transcript
  - Print mode and ACP now surface plan updates for non-interactive and editor-client flows

- **Apply Confirmation**
  - Added `approval.confirmBeforeWrite` to require approval before `write` and `edit` in agent mode
  - Enabled write/edit confirmation by default in generated settings
  - TUI approval prompts summarize write content by byte size instead of dumping full file content

- **MCP Config Commands**
  - Added `/init_mcp` to create project/global `mcp.json` with `basic`/`full` templates and optional `--force`
  - Added `/mcps` to list MCP servers from global and project `mcp.json` files
  - MCP config is now maintained in standalone `mcp.json` (separate from `settings.json`)

### 🧪 Testing

- Added coverage for the `plan` tool and write/edit approval gating
- Added HTTP-based MCP integration tests for tool/resource/prompt registration and callback paths
- Added SSE-based MCP integration tests for stream callbacks and message endpoint request/response flow

### 🛠 Improvements

- **ACP MCP Hardening**
  - Added MCP transport support for `http` and `sse` (alongside existing `stdio`)
  - Added MCP initialize/tool-discovery timeouts to avoid hanging ACP sessions
  - Added paginated `tools/list` fetching with upper page bounds
  - Added MCP `resources/*` and `prompts/*` discovery and tool registration
  - Added duplicate MCP server-name detection and MCP tool-name de-duplication
  - Added MCP inbound request/notification handling (`ping`, progress/logging/cancel notifications)
  - Added bridge for inbound `sampling/createMessage` to the active ACP provider/model
  - Added stricter close/error propagation

---

## v0.1.20

### ✨ Features

- **Structured File Change Reporting**
  - `write` and `edit` now attach structured file diff metadata to tool results
  - TUI tool details show full unified diffs while collapsed tool rows keep a compact `+N -N` summary
  - Print mode now emits clear file change summaries for non-interactive runs
  - ACP tool updates include diff metadata in raw output for compatible clients

### 🧪 Testing

- Added coverage for structured diff metadata from `write` and `edit`

---

## v0.1.19

### ✨ Features

- **TUI Tool Details Modal**
  - Replaced `Ctrl+O` toggle-expand with a scrollable full-screen modal overlay showing all tool calls and results
  - Supports PgUp/PgDn, Up/Down, Home/End navigation; Esc/Ctrl+O/q to close
  - Tool headers now display file paths; removed content truncation in tool args display
  - Write tool results show diff summary in the one-line summary line
  - Key input is blocked while the modal is open to prevent accidental actions

- **Write Tool Diff Summary**
  - `write` tool now computes LCS-based line-level diff when overwriting files
  - Returns structured diff info (`+N -N` with line ranges) in the tool result
  - Skips diff computation for very large files (>200K line pairs) to avoid memory pressure

### 🛠 Improvements

- **Unified Shell Args Across Sandbox Backends**
  - All sandbox backends (`none`, `mac`, `windows`) now use `platform.ShellArgs()` for cmd.exe/PowerShell argument construction
  - Fixes Windows cmd.exe and PowerShell commands in sandboxed execution modes
  - `ShellArgs` now normalizes shell name to lowercase before matching

### 🧪 Testing

- Added `TestNoneSandboxWrapCommandUsesPlatformShellArgs` covering cmd.exe and PowerShell argument generation

---

## v0.1.18

### 🐛 Bug Fixes

- **TUI Nil Pointer Panic**
  - Fixed a nil pointer panic in `printMessageOnce` when `printedMessageIdx` map was not initialized
  - Added nil check before accessing the map in the message printing logic

- **Stream Commit Before Tool Execution**
  - Added `commitActiveStream()` method to flush streaming content (thinking and assistant messages) to output before tool execution
  - Now properly commits active stream before `EventToolCall` and `EventToolApprovalRequest` handling
  - Ensures thinking and partial assistant responses are visible when tools run or approval is requested

### 🧪 Testing

- Added `TestHandleAgentEventCommitsStreamBeforeApproval` regression test for stream commit ordering

---

## v0.1.17

### 🛠 Improvements

- **TUI Native Scrollback**
  - Reworked TUI history rendering so completed messages are printed into the terminal's native scrollback instead of a fixed-height viewport
  - Removed the virtual scrollbar and mouse-capture approach; mouse wheel scrolling now uses normal terminal history behavior
  - Kept live streaming content, input, footer, context/cache status, and tool output controls in the Bubble Tea view

- **TUI Request Timers**
  - Added per-request elapsed time display while a response is running
  - Footer now keeps the last request duration after completion

- **Event Loop Decoupling**
  - Added shared agent event consumption helpers
  - Split the TUI agent-event bridge out of the main app file and reused the event loop from CLI print mode

- **Windows Console Compatibility**
  - Enabled Windows virtual terminal console modes where available for better PowerShell rendering on Windows 10

### 🐛 Bug Fixes

- Fixed a TUI startup deadlock caused by printing initial/session history before Bubble Tea had started consuming program messages
- Fixed an agent message-history data race found by `go test -race`
- Fixed mock provider cancellation handling for already-canceled contexts

### 🧪 Testing

- Full `make test` now passes with race detection
- Added TUI regression coverage for startup history printing without blocking
- Hardened tests that depend on local HTTP listeners or default home-directory session paths in restricted environments

---

## v0.1.16

### 🛠 Improvements

- **Session Open by ID or Path**
  - New `OpenByPathOrID` function allows opening sessions by either file path or session ID
  - `OpenByID` now supports prefix matching with ambiguity detection
  - `ContinueRecent` initializes new sessions immediately so they are ready for messages

- **Session Save Error Handling**
  - `AppendMessage` and `AppendCompaction` now return errors to the caller
  - Agent loop surfaces session-save failures as `EventError` instead of silently dropping them

- **Vendored Tool Test Guard**
  - Makefile `test` target now depends on `prepare-vendored` and a new `test-vendored` check
  - Tests fail early with a clear message if `rg`/`fd` binaries are missing for the current platform

### 🧪 Testing

- Added CLI flag parsing tests for root and ACP subcommands
- Added settings merge tests covering project overrides and environment variables
- Added session tests for `OpenByPathOrID`, prefix ambiguity, corrupt lines, and parent chain tracking

---

## v0.1.15

### 🐛 Bug Fixes

- **Vendored Search Tool Availability**
  - Fixed `grep` and `find` so they prepare embedded `rg` / `fd` binaries on demand instead of failing when vendored tools have not been extracted yet
  - Restored executable permissions for already-extracted vendored binaries to avoid `permission denied` failures on reuse

- **Bash Tool Result Handling**
  - Fixed bash tool responses to report stdout, stderr, working directory, and exit code in a stable structured format
  - Preserved non-zero command exits as normal tool results with explicit `exit_code` output instead of mixing shell failures into transport-level errors
  - Standardized empty stdout/stderr rendering as `(no output)` for more predictable downstream handling

---

## v0.1.14

### 🐛 Bug Fixes

- **Session Continue Context Injection (`-c`)**
  - Fixed a TUI state coupling issue where continued sessions could display history but fail to inject that history into the model context for follow-up prompts
  - Split session history state into separate UI-display and agent-injection flags to ensure resumed conversations keep prior context
  - Reset agent history-injection state consistently when the agent is recreated (abort/mode/model/skill/session switches)
  - Added missing TUI handlers for `EventStatus` and `EventMessageStart` so status/warning messages are rendered reliably

### 🧪 Testing

- Added regressions that cover:
  - history injection when UI history is already loaded
  - real startup ordering (`Init()` history load, then follow-up input) for continued sessions

---

## v0.1.13

### 🐛 Bug Fixes

- **Streaming Event and Tool Call Robustness**
  - Preserved terminal agent events in the TUI event listener so done/error/status handling is not dropped during streaming
  - Added Anthropic thinking signature streaming and replay support, and surfaced SSE `error` events as proper stream errors
  - Generated fallback tool call IDs for OpenAI-compatible streamed tool calls when providers omit IDs, with an extra defensive fallback in the agent loop

- **Sandbox Environment Inheritance**
  - Fixed `none` sandbox execution so commands inherit the parent environment, including variables such as `$HOME`
  - Clarified bubblewrap environment override handling to match runtime behavior

### 🛠 Improvements

- **Vendored Tool Build Flow**
  - Unified build and distribution targets around `prepare-vendored`
  - Removed the old `vendored-tools` release step and deprecated the stale extract helper script

- **Documentation Site Layout**
  - Expanded the docs landing page content width for better large-screen readability

- **Package Metadata**
  - Updated npm package versions for installer packages

### 📖 Documentation

- Updated README and docs landing pages to highlight safer approval handling, unified cache metrics, and consistent provider debugging
- Simplified `AGENTS.md` guidance for repository agents

### 🧪 Testing

- Added bash tool output coverage for stdout-only, stderr-only, no-output, and non-zero exit cases
- Added TUI regression tests for status/warning rendering and done/error event passthrough
- Added OpenAI streaming regression coverage for tool calls with missing IDs

---

## v0.1.12

### 🐛 Bug Fixes

- **Unified Cache Hit Rate Semantics**
  - Restored cache hit rate calculation to use the full prompt footprint (`CacheRead / TotalInputTokens()`)
  - Aligned CLI print mode token display with TUI cache-aware totals
  - Updated Anthropic cache tests and shared provider usage tests to match the unified definition

- **Approval Safety in Non-Interactive and YOLO Flows**
  - Made `bashBlacklist` effective in approval checks with higher priority than `bashWhitelist`
  - Blacklisted bash commands now still require approval in `yolo` mode
  - `--print` mode now fails fast instead of auto-approving commands that would require user confirmation

### 🛠 Improvements

- **Debug Output Consistency**
  - `--debug` now also enables provider-level request/response debug output
  - Applied the same behavior to ACP mode

- **Cross-Platform Path Handling**
  - Replaced string-based `.skills` path construction with `filepath.Join(...)`

### 📖 Documentation

- Updated CLI reference to document stricter `--print` behavior and debug output behavior
- Updated configuration guide for approval precedence and `VIBECODING_DEBUG`
- Updated root README and documentation landing pages to highlight safer approval handling, unified cache metrics, and provider debug behavior

### 🧪 Testing

- Added approval behavior tests for whitelist/blacklist and `yolo` mode
- Added print mode regression test for approval-required tool calls
- Expanded cache-related provider tests to cover the unified cache hit rate definition

---

## v0.1.11

### 🛠 Improvements

- **Command Structure Refactoring**
  - Extracted root command creation into separate function for better testability
  - Added unit tests for command initialization and configuration
  - Improved code modularity and maintainability

### 📖 Documentation

- **License & Documentation Updates**
  - Added MIT license file
  - Added Chinese README (README_zh.md) for broader accessibility
  - Updated npm package versions

---

## v0.1.10

### ✨ Features

- **ACP Support Documentation**
  - Added ACP (Agent Client Protocol) support documentation to READMEs
  - MothX can run as an ACP stdio agent for editor integrations
  - Compatible with VS Code, Zed, and JetBrains IDEs (IntelliJ IDEA/WebStorm) via ACP plugins

### 📖 Documentation

- Updated main README.md with ACP support feature
- Updated English README with features section
- Updated Chinese README with features section

---

## v0.1.9

### 🐛 Bug Fixes

- **TUI Deferred Render Goroutine Safety**
  - Fixed `scheduleRender` calling `updateViewportContent` from background goroutine without marshalling back to Bubble Tea's UI goroutine
  - Added `renderRequestMsg` type and `program.Send()` to properly marshal UI updates
  - Added `program *tea.Program` field and `SetProgram()` method for deferred UI scheduling

### 🛠 Improvements

- **TUI Abort Clears Queued Input**
  - Clear input queue and reset input state on manual abort and mode change
  - Prevents buffered keystrokes from executing after abort

- **Assistant Slot Reservation**
  - Added `EventTurnStart` handling to reserve display slot before text deltas arrive
  - Prevents tool output from shifting assistant message index mid-stream
  - Added empty raw markdown check in `updateViewportContent`

- **Tool Prompt Snippets**
  - Added "(preferred for ...)" hints to `read`, `ls`, `grep`, `find` tool descriptions
  - Reordered tool registration: read-only tools registered before write/edit/bash

### 🧪 Testing

- Added `TestHandleAgentEventReservesAssistantSlotBeforeTextDelta` test
- Added `TestAbortClearsQueuedInput` test

---

## v0.1.8

### 🐛 Bug Fixes

- **Token Counting with Cache-Aware TotalTokens**
  - Fixed Anthropic `TotalTokens` calculation to include `CacheRead` and `CacheWrite` tokens
  - Added `PromptTokens()` and `TotalInputTokens()` helper methods to `Usage` struct
  - Updated `CacheInfo()` to use `TotalInputTokens()` as denominator for accurate cache hit rates
  - Updated TUI to display correct token counts including cache tokens

### 🧪 Testing

- Added comprehensive tests for `PromptTokens()` and `TotalInputTokens()` helper methods
- Updated Anthropic provider tests with `TotalTokens` validation

---

## v0.1.7

### 🐛 Bug Fixes

- **Anthropic Provider Tool Use Serialization**
  - Fixed `tool_use` content blocks missing `input` field when tool has no arguments
  - Changed `Input` field from `map[string]interface{}` to `*map[string]interface{}` so `omitempty` only checks nil pointer, not empty map
  - Fixes API errors when using models like Xiaomi MiMo with Anthropic-compatible endpoints

---

## v0.1.6

### ✨ Features

- **Session Management Command**
  - Added `/sessions` command for browsing and managing project sessions
  - Supports listing, switching, clearing, and deleting sessions
  - Shows session details including file path and message count

### 🐛 Bug Fixes

- **Sandbox Initialization**
  - Fixed sandbox initialization validation and bwrap multiarch compatibility
  - Improved error handling for sandbox setup

### 📖 Documentation

- Updated AGENTS.md with current version information
- Formatted Go code for consistency

---

## v0.1.5

### ✨ Features

- **DeepSeek V4 Default Models**
  - Updated default model specs to DeepSeek V4 (Flash and Pro)
  - 1M context window, up to 384K max output tokens
- **Install Script Improvements**
  - Install scripts now show config directory path on completion

### 🐛 Bug Fixes

- **Windows IME Support**
  - Fixed Windows IME (CJK input) support in terminal
  - Fixed shell command resolution on Windows
  - Added config loading diagnostics for troubleshooting
- **Musl Deb Packages**
  - Fixed invalid dpkg architecture names for musl deb packages

### 🛠 Improvements

- **Configuration Simplification**
  - Removed `auth.json` support — all credentials now in `settings.json` only
  - Cleaner config path with single source of truth

### 📖 Documentation

- Clarified that OpenAI/Anthropic API-compatible services are also supported
- Removed all `auth.json` references from docs and install scripts
- Added expanded Windows `%APPDATA%` path examples
- Clearly distinguished Windows vs Linux/macOS config paths

---

## v0.1.4

### ✨ Features

- **Linux musl Build Support**
  - Added `make build-linux-musl` target for statically linked musl binaries (amd64 + aarch64)
  - musl tarballs produced via `dist-tarball` and `dist` targets
  - musl Debian packages produced via `dist-deb` target (amd64-musl / arm64-musl)
  - npm packages: `vibecoding-installer-linux-musl-x64` and `vibecoding-installer-linux-musl-arm64`
  - npm uses `libc` field for proper musl/glibc resolution (npm >=9.4)
  - postinstall.js auto-detects musl vs glibc on Linux

---

## v0.1.3

### ✨ Features

- **Versioning Rules**
  - Added version number management rules with base-10 carry-over (e.g., v0.1.9 -> v0.2.0)
  - Documented changelog rules: only write in docs/en/changelog.md and docs/zh/changelog.md
  - No separate release notes files allowed

---

## v0.1.2

### ✨ Features

- **Prompt Cache Optimization**
  - Implemented prompt cache optimization following LLM_Agent_Cache.md strategy
  - Cache system prompts and static context across multiple turns
  - Reduces API costs by reusing cached tokens for repeated prefixes

- **TUI Markdown Syntax Highlighting**
  - Assistant messages in TUI now have markdown syntax highlighting
  - Code blocks, headers, and formatting are visually distinguished
  - Improves readability of LLM responses

### 🐛 Bug Fixes

- **Security & Correctness**
  - Resolved critical security, race condition, and correctness issues
  - Addressed high and medium severity correctness issues across codebase
  - Removed dead code and improved overall code correctness

- **TUI Stability**
  - Fixed TUI startup hang caused by `clearStdin` blocking on unsupported stdin
  - Fixed TUI assistant message rendering broken by ANSI escape codes in prefix check

### 🛠 Improvements

- **Code Quality**
  - Addressed remaining medium severity issues across codebase
  - npm package versions updated

---

## v0.1.1

### ✨ Features

- **Cache Hit Rate Display**
  - Footer now shows cumulative cache hit percentage across all turns
  - Cache percentage is highlighted when hit rate ≥ 50% for quick visibility
  - Per-turn cache read/write counts displayed in token usage line

- **Proxy Compatibility**
  - Handle proxies that send usage fields in `message_delta` instead of `message_start`
  - Handle OpenAI proxies that split usage across multiple SSE chunks (first-wins per field)
  - Fixed missing space before `$` in print-mode token summary line

### 🛠 Improvements

- **Code Quality**
  - Extracted `Usage.CacheInfo()` to eliminate 3× duplicated cache display logic
  - npm package versions now use `v`-prefixed format (e.g. `v0.1.1`)
  - Normalized JSON formatting across all npm package.json files

### 🧪 Testing

- Added 37 unit tests for `CacheInfo()`, `formatCachePercent()`, and `renderFooter()` cache section
- Added 12 httptest integration tests for Anthropic and OpenAI SSE cache token parsing

---

## v0.1.0

### ✨ Features

- **Xiaomi MiMo Thinking Format Support**
  - Added `thinkingFormat` configuration option for Xiaomi MiMo API
  - OpenAI provider: MiMo endpoints use `thinking: {type: "enabled"}` format
  - Anthropic provider: MiMo endpoints omit `budget_tokens`
  - URL auto-detection: auto-detects `xiaomimimo` endpoints when `thinkingFormat` is not set
  - Debug logging: enabled via `VIBECODING_DEBUG` environment variable

### 🛠 Improvements

- **Configuration Flexibility**
  - `thinkingFormat` passed from config to provider, no longer relies solely on URL detection
  - Anthropic `budget_tokens` changed from required to optional (pointer type + `omitempty`)

---

## v0.0.9

### ✨ Features

- **Image Support in Tools**
  - `read` tool now supports reading image files (PNG, JPEG, GIF, WebP)
  - Images are returned as base64-encoded data with MIME type information
  - LLMs can now analyze and understand image content
  - Supported formats: `.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`

- **Rich Content Tool Results**
  - New `ToolResult` struct supports both plain text and rich content blocks
  - Tools can now return text + images in a single result
  - New factory functions: `NewTextToolResult()` and `NewImageToolResult()`

- **Model Switching**
  - `/model <id>` command allows switching models in interactive mode
  - `/model` without arguments shows current model and available options
  - Agent resets automatically when model is switched

- **Enhanced Help System**
  - `/help` command now shows detailed command descriptions
  - Added keyboard shortcuts reference (Tab, Esc, Ctrl+O, PgUp/PgDn)

### 🛠 Improvements

- **Context Token Estimation**
  - Fixed double-counting issue when both `Content` and `Contents` are present
  - Image tokens estimated as ~1200 tokens per image

- **Provider Message Conversion**
  - OpenAI: Images in tool results sent as supplementary user messages
  - Anthropic: Images sent as separate user messages alongside tool_result

### 🧪 Testing

- Added `TestReadToolImage` test case for image reading functionality
- All tool tests updated for new `ToolResult` return type

---

## v0.0.8

### ✨ Features

- **NPM Multi-Architecture Split Packages**
  - Split the npm package from a single all-platform bundle (~60MB) into 6 platform-specific packages (~10MB each)
  - Users now only download the binary for their current platform, reducing install size by 83%
  - Uses npm `optionalDependencies` + `os`/`cpu` fields for automatic platform matching
  - Main package `vibecoding-installer` is only ~2KB, links the correct platform package via `postinstall`

### 🛠 Improvements

- **Build System**
  - Added `scripts/build-npm-packages.sh` to generate platform-specific npm packages
  - Added `make npm-packages`, `make npm-pack`, `make npm-publish-all` targets
  - `sync-npm-version.sh` now syncs versions across all platform packages

---

## v0.0.7

### ✨ Features

- **Cross-Platform Sandbox Support**
  - Sandbox now supports macOS and Windows in addition to Linux
  - macOS uses `sandbox-exec` for process isolation
  - Windows uses restricted process creation without network access
  - Platform-specific sandbox implementations selected automatically

- **Repository Rename**
  - Module path renamed to `github.com/oschina/mothx`
  - All imports, documentation, and scripts updated accordingly

### 🛠 Improvements

- **Platform-Specific Process Handling**
  - Extracted `SysProcAttr` configuration into build-tagged files (`bash_unix.go`, `bash_windows.go`)
  - Background child process cleanup now works correctly on all platforms
  - `Setpgid` only set on Unix systems; Windows uses `CREATE_NEW_PROCESS_GROUP`

### 📖 Documentation

- Updated all GitHub URLs to new repository location
- Added v0.0.6 and v0.0.7 release notes

---

## v0.0.6

### 🛠 Improvements

- **Bash Tool Reliability**
  - Fixed background child process hanging issue
  - Added `WaitDelay` to prevent shell from waiting indefinitely on background children
  - Properly handle `exec.ErrWaitDelay` errors

- **NPM Installation**
  - Added npm package for installation via `npm install -g vibecoding-installer`
  - Automatic binary download during `postinstall`

### 📖 Documentation

- Added npm installation instructions
- Removed redundant markdown files from docs root
- Added v0.0.5 release notes

---

## v0.0.5

### ✨ Features

- **Non-root Installation**
  - `install.sh` now supports installation without root or sudo
  - Auto-detects writable install directory: uses `/usr/local/bin` if writable, otherwise falls back to `~/.vibecoding/bin`
  - Removes all `sudo` calls — user-level installation never requires elevated privileges

- **Automatic PATH Setup**
  - Auto-detects user's shell (bash, zsh, fish) and configures PATH in the appropriate config file
  - Supports `.bashrc`, `.bash_profile`, `.zshrc`, `.zshenv`, `config.fish`, and `.profile`
  - Skips configuration if PATH entry already exists (no duplicates)
  - Fish shell uses `set -gx PATH` syntax; bash/zsh use `export PATH=...`

### 🛠 Improvements

- **Environment Variables**
  - `INSTALL_DIR` — override the install directory (unchanged)
  - `AUTO_SETUP_PATH=0` — disable automatic PATH configuration
  - Better error messages for permission issues

- **Install Experience**
  - Shows install directory and PATH auto-setup status at the start
  - Cleaner output with colored status messages

### 📖 Documentation

- Added v0.0.5 release notes

---

## v0.0.4

### ✨ Features

- **Agent Mode Approval Mechanism**
  - Bash commands in Agent mode now require user approval
  - Configurable `bashWhitelist` for auto-approved command prefixes
  - Configurable `bashBlacklist` for commands always requiring approval
  - TUI displays approval prompt; user responds with `y`/`yes` or `n`/`no`
  - Approval requests can be cancelled via `abort`

- **Mode Permission Matrix**
  - Plan mode: Read-only tools (read, grep, find, ls)
  - Agent mode: Read/write auto-execute, bash requires approval
  - YOLO mode: All tools auto-execute
  - Updated system prompts with explicit permission matrix

### 🛠 Improvements

- **Default Approval Whitelist**
  - Default whitelist: `go`, `make`, `git`, `npm`, `yarn`, `node`, `python`, `pip`
  - Customizable in `settings.json`

- **Mode Switch Feedback**
  - Mode switching now shows detailed permission descriptions
  - `/mode` command displays full permission list for current mode

### 📖 Documentation

- Added approval configuration section
- Updated security docs with approval mechanism details
- Added v0.0.4 release notes

---

## v0.0.3

### ✨ Features

- **Session History Loading**
  - Display session info (file path and message count) when continuing or opening sessions
  - Load and display historical messages from previous sessions in TUI
  - Load history messages into agent context for continuity
  - Reset agent on abort to ensure clean state for next request

### 🛠 Improvements

- **Build & Distribution System**
  - Restructured Makefile with clear per-platform build and dist targets
  - Added `dist-linux`, `dist-darwin`, `dist-windows` targets
  - Added `build-zip.sh` for Windows zip packages
  - Added `checksums` target for release verification
  - Updated `build-deb.sh` and `build-tarball.sh` to support all platforms

### 📖 Documentation

- Added GitHub repository button in documentation site header
- Added v0.0.2 release notes

---

## v0.0.2

### ✨ Features

- **One-line Installation Scripts**
  - `install.sh` for Linux/macOS - downloads from GitHub Releases automatically
  - `install.ps1` for Windows PowerShell - supports custom install directory via `VIBECODING_INSTALL_DIR`
  - Both scripts detect platform/architecture, verify checksums, and configure PATH

- **Documentation Redesign**
  - Redesigned with Google Material Design style
  - Default language changed to English
  - Added hash routing for easy document sharing (e.g., `#/en/README`, `#/zh/configuration`)
  - Added logo to header and README

- **Brand Assets**
  - Added `docs/assets/icon.svg` (512×512) for packaging
  - Added `docs/assets/mothx.png` for README and small displays
  - Minimal, professional design with slate color palette

- **Build System**
  - Added `make build-windows` target (amd64 + arm64)
  - Added `make build-linux` and `make build-darwin` targets
  - Updated `make build-all` to use platform-specific targets

- **Documentation**
  - Added `docs/en/skills.md` for Skills system
  - Updated installation instructions in README and getting-started guides

### 🐛 Bug Fixes

- Moved assets to `docs/assets/` for proper GitHub Pages deployment

---

**Full Changelog**: https://github.com/oschina/mothx/compare/v0.1.26...v0.1.27

---

## CLI Reference

Source: https://mothx.net/en/cli-reference.md

# CLI Reference

## Overview

```
mothx [flags] [message...]
```

## Command Line Arguments

### Basic Parameters

| Parameter | Short | Default | Description |
|-----------|-------|---------|-------------|
| `--provider` | `-p` | Default from config file | LLM provider (deepseek-openai, deepseek-anthropic or custom name) |
| `--model` | `-m` | Default from config file | Model ID |
| `--mode` | `-M` | `yolo` | Run mode (plan, agent, yolo, os); falls back to `settings.json` `defaultMode` |
| `--thinking` | `-t` | `off` | Thinking level (off, minimal, low, medium, high, xhigh, max) |
| `--multi-agent` | - | `false` | Enable multi-agent tools and commands |
| `--delegate` | - | `false` | Enable delegation mode (blocking single sub-agent tool) |
| `--workflows` | - | `false` | Enable JavaScript workflow tools and `/workflows` commands |
| `--artifact` | - | `false` | Enable generated artifact publishing for this TUI/CLI process |
| `--expert` | - | - | Bind an expert bundle to this session; switching an existing expert forks the session |
| `--web-search` | - | `false` | Enable configured local web search tools for this run |
| `--browser` | - | `false` | Enable the browser automation tool |
| `--cron` | - | `false` | Enable the cron tool for scheduled tasks |

### Session Management

| Parameter | Short | Description |
|-----------|-------|-------------|
| `--continue` | `-c` | Continue most recent session |
| `--resume` | `-r` | Resume session by ID or path |
| `--session` | - | Use specific session ID or `.db` handle file |
| `--list-sessions` | - | List recent sessions across all working directories |
| `--list-sessions-limit` | - | How many sessions `--list-sessions` prints (default 20) |
| `--list-sessions-cwd` | - | Only list sessions for this working directory |

### Output Control

| Parameter | Short | Description |
|-----------|-------|-------------|
| `--print` | `-P` | Non-interactive mode, print response and exit. If a tool would require approval, the command exits with an error instead of auto-approving. |
| `--json` | - | Stream print-mode output as one JSON object per line (NDJSON) to stdout (all status/diagnostics still go to stderr, easy to pipe into `jq`). Requires `-P`. |
| `--verbose` | - | Verbose output |
| `--debug` | - | Enable debug logging, provider request/response debug output, and local pprof at `127.0.0.1:6060` |

### Security

| Parameter | Description |
|-----------|-------------|
| `--sandbox` | Enable sandbox (bubblewrap) |
| `--no-sandbox` | Disable sandbox (deprecated, disabled by default) |

### Other

| Parameter | Short | Description |
|-----------|-------|-------------|
| `--init-serve` | - | Create `serve.json` config template |
| `--init-a2a-master-config` | - | Create `a2a-list.json` config template |
| `--enable-a2a-master` | - | Enable A2A master mode (remote agent dispatch) |
| `--force` | - | Force overwrite existing files (used with `--init-*`) |
| `--version` | `-v` | Show version |
| `--help` | `-h` | Show help |

## Subcommands

### `acp` - Agent Client Protocol Server

Run MothX as an ACP-compliant stdio agent for IDE integration.

```
mothx acp [flags]
```

Supports VS Code, JetBrains IDEs, and any ACP-compatible editor.

| Flag | Short | Default | Description |
|------|-------|---------|-------------|
| `--provider` | `-p` | From config | LLM provider |
| `--model` | `-m` | From config | Model ID |
| `--mode` | `-M` | `yolo` | Run mode (plan, agent, yolo, os); falls back to `settings.json` `defaultMode` |
| `--thinking` | `-t` | From config | Thinking level |
| `--sandbox` | - | false | Enable sandbox |
| `--verbose` | - | false | Verbose output |
| `--debug` | - | false | Debug logging and local pprof |
| `--multi-agent` | - | false | Enable multi-agent tools for ACP sessions |
| `--delegate` | - | false | Enable delegation mode for ACP sessions |
| `--workflows` | - | false | Enable JavaScript workflow tools for ACP sessions |
| `--web-search` | - | false | Enable configured local web search tools for this ACP run |
| `--browser` | - | false | Enable browser automation for ACP sessions |
| `--artifact` | - | false | Enable generated artifact publishing for this ACP/Desktop process |
| `--permission-timeout` | - | `5m` | Approval decision timeout for `session/request_permission` (Go duration; env `MOTHX_ACP_PERMISSION_TIMEOUT`) |
| `--question-timeout` | - | `5m` | Question decision timeout for ACP question requests (Go duration; env `MOTHX_ACP_QUESTION_TIMEOUT`) |

See the [ACP Protocol](acp.md) documentation for IDE integration details.

### `a2a` - A2A Protocol Server

Run the standalone A2A (Agent-to-Agent) protocol server.

```
mothx a2a [command]
```

| Subcommand | Description |
|------------|-------------|
| `start` | Start A2A server |
| `stop` | Stop A2A server |
| `status` | Show server status |
| `card` | Show/generate Agent Card |
| `send <message>` | Send task to remote A2A server |
| `discover <url>` | Discover remote Agent Card |
| `--init-a2a-config` | Create `a2a.json` config template |
| `--force` | Force overwrite existing config file |

`mothx a2a send` also accepts `--target <url>` (default `http://localhost:8093`) and `--auth-token <token>`.

See [A2A Protocol](a2a.md) documentation for details.

### `serve` - Unified Server

Start MothX as a unified server exposing an OpenAI-compatible Chat Completions API, Web UI, and optional WeChat/Feishu/WebSocket messaging channels.

```
mothx serve [flags]
```

| Flag | Short | Default | Description |
|------|-------|---------|-------------|
| `--port` | - | `127.0.0.1:7872` | Listen port or address, e.g. `7872` or `0.0.0.0:7872` (overrides serve.json) |
| `--config` | - | - | Path to serve.json |
| `--web-ui-dir` | - | Built-in assets | Override embedded Serve Web UI assets with a frontend directory |
| `--unsafe` | - | false | Disable auth and bind Serve to all interfaces |
| `--work-dir` | - | Current directory | Default working directory |
| `--provider` | `-p` | From config | LLM provider |
| `--model` | `-m` | From config | Model ID |
| `--sandbox` | - | false | Enable sandbox (bwrap) |
| `--multi-agent` | - | false | Enable multi-agent tools |
| `--delegate` | - | false | Enable delegation mode |
| `--workflows` | - | false | Enable JavaScript workflow tools |
| `--web-search` | - | false | Enable configured local web search for Serve sessions |
| `--browser` | - | false | Enable browser automation for Serve sessions |
| `--artifact` | - | false | Enable generated artifact publishing for WebUI/API sessions |
| `--enable-a2a-master` | - | false | Enable A2A master mode for remote-agent dispatch |
| `--lobster` | - | false | Enable yolo mode, disable sandbox, and enable sub-agents |
| `--verbose` | - | false | Verbose output |
| `--debug` | - | false | Debug logging and local pprof |

| Subcommand | Description |
|------------|-------------|
| `init-config [global\|project]` | Create `serve.json` config template |
| `--force` | Force overwrite existing config file |

See [Serve Mode](serve.md) documentation for details.

### `stats` - Usage Statistics

Start the usage dashboard, or print token and request statistics directly in the terminal.

```
mothx stats [flags]
```

| Flag | Short | Default | Description |
|------|-------|---------|-------------|
| `--addr` | - | `127.0.0.1:7878` | Listen address for the web dashboard |
| `--db` | - | Default sessions database | Path to `sessions.db` |
| `--cli` | - | false | Print stats in the terminal instead of starting the web server |

Examples:
```bash
mothx stats
mothx stats --cli
mothx stats --cli --db ~/.mothx/sessions/sessions.db
```

### `pure` - Archive the Sessions Database

Move the shared `sessions.db` aside and create a fresh, empty database in its place. Nothing is deleted: every moved file is renamed next to the new database as `sessions.db.pure-<timestamp>.bak`, and the SQLite sidecars keep their suffix (`...bak-wal`, `...bak-shm`, `...bak-journal`), so the previous sessions stay recoverable. A sidecar whose database is already gone - from an interrupted reset or a hand-deleted file - is archived the same way, so the fresh database can never inherit it.

Only `sessions.db` and its sidecars are archived. Everything else in the session directory stays where it is, and each kind stays for its own reason: `channels/` holds **separate session roots**, each with its own `sessions.db` and session handles; every `knowledge-bases/<id>.db` **is** that knowledge base's own authoritative store (its configuration row and its rebuildable index live inside that file, and bases are enumerated from the directory, not from the shared database); and `artifacts/` holds attachment content that the archived database used to describe. Of the three, only unreferenced attachment storage is reclaimable - the rest is live data that a sessions-database reset does not invalidate. See the reclamation rules below.

```
mothx pure [flags]
```

| Flag | Short | Default | Description |
|------|-------|---------|-------------|
| `--session-dir` | - | Configured session directory | Session directory to reset |
| `--force` | - | false | Reset even while another `mothx` process holds an active session run |
| `--prune-unreferenced` | - | false | Also reclaim attachment storage no row references and that is already past the retention window |

Examples:
```bash
# Archive the default sessions database and start fresh
mothx pure

# Reset a specific session directory
mothx pure --session-dir ~/.mothx/sessions

# Reset despite an active run in another process
mothx pure --force

# Reset and immediately reclaim unreferenced attachment storage
mothx pure --prune-unreferenced
```

The command refuses to start while a session run is active in that directory, naming the session, the owning pid, and its run. That check reads execution leases, so an idle `mothx` process that only holds the database open is not detected - stop the other processes yourself, or pass `--force`. A database this process cannot open at all is reported as unknown rather than busy and still resets, since that is the case `pure` exists for.

Attachment storage becomes unreachable once the rows that described it are archived, and the same happens when a session is deleted or an intake fails after its content was written. Reclamation never relies on a reset: the Runtime sweeps the private store while accepting new attachments (at most once an hour per process) and once a day through its own cron maintenance job, and removes only directories that no row references **and** that were last written before the attachment retention window plus a 24-hour grace period - eight days by default with the 7-day retention. That floor is why reclamation can never destroy something a restored archive could still serve. `--prune-unreferenced` runs the same pass immediately and reports what it reclaimed and what it kept as too young; `channels/` and `knowledge-bases/` are never touched by it. The scheduled pass is configured by the optional `maintenance` section of `settings.json` (`reclaimAttachmentStorage`, `storageReconcileSchedule`); see [configuration](configuration.md#maintenance).

### `maintenance` - Inspect and Compact the Session Database

Session-storage maintenance never deletes transcript messages. `status` is read-only: it reports the database size, transcript and sub-agent entry counts, tool-execution record count, and reclaimable free pages. `vacuum` runs SQLite `VACUUM` to release free pages and reports the before/after state; `--dry-run` previews the reclaimable space without rewriting the database. No tool-execution record is pruned by either command.

```
mothx maintenance status [flags]
mothx maintenance vacuum [flags]
```

| Flag | Short | Default | Description |
|------|-------|---------|-------------|
| `--session-dir` | - | Configured session directory | Session directory to inspect or vacuum |
| `--dry-run` | - | false | `vacuum` only: report reclaimable free pages without rewriting the database |

Examples:
```bash
# Show database size, transcript counts, and reclaimable space
mothx maintenance status

# Preview what VACUUM would reclaim
mothx maintenance vacuum --dry-run

# Rewrite sessions.db and release free pages
mothx maintenance vacuum
```

`VACUUM` rewrites the whole database, needs free disk space equal to its size, and holds the SQLite writer for the duration of the rewrite; run it while other MothX processes are idle. The scheduled Runtime maintenance job performs the same optional VACUUM and applies the configured retention only to terminal tool-execution idempotency records; transcript messages are preserved by both paths. See [configuration](configuration.md#maintenance).

### `worktree` - Isolated Git Worktrees

Create, list, reset, and remove isolated git worktrees managed by the shared Runtime. Worktrees default to `<data-dir>/worktrees`, are registered in the sessions database, and are shared by TUI/CLI, ACP/Desktop, and sub-agents. Creation is controlled by `settings.json` `worktree.enabled`; disabling creation still allows listing, resetting, and removing existing worktrees.

```
mothx worktree <list|create|remove|reset> [flags]
```

| Subcommand | Description |
|------------|-------------|
| `list` | List managed worktrees |
| `create` | Create a worktree |
| `remove <id\|directory>` | Remove a managed worktree |
| `reset <id\|directory>` | Reset a worktree to its default branch |

| Flag | Subcommand | Description |
|------|------------|-------------|
| `--repo <dir>` | list, create | Repository directory (default: current directory) |
| `--project <id>` | list, create | Filter by, or associate with, a project ID |
| `--name <name>` | create | Worktree name (default: derived from the repository) |
| `--detach` | create | Create a detached worktree instead of a branch |
| `--start <command>` | create | Startup command stored for the worktree |
| `--root <dir>` | all | Override the worktree root directory |
| `--json` | list, create | Print machine-readable JSON |

Examples:
```bash
mothx worktree list
mothx worktree create --repo ~/projects/app --name feature-auth
mothx worktree reset feature-auth
mothx worktree remove /path/to/worktree
```

### `knowledge-mcp` - Knowledge Base MCP Server

Expose one or more managed knowledge bases as MCP tools over stdio. The server registers the ordinary `search_knowledge_base` tool; the allowlist is the authorization boundary.

```
mothx knowledge-mcp serve --knowledge-base <id> [--knowledge-base <id>...] [--session-dir <dir>]
```

| Flag | Description |
|------|-------------|
| `--knowledge-base <id>` | Knowledge base ID enabled for this server; repeat for multiple bases |
| `--session-dir <dir>` | Session storage directory (default: `settings.json`) |

Knowledge bases are created and indexed from Desktop or the WebUI. See [Knowledge Bases](knowledge-bases.md).

### `speedtest` - Provider Benchmark

Benchmark configured providers/models with a text-only streaming request. Successful runs are averaged and sorted by output tokens per second.

```
mothx speedtest [flags]
```

| Flag | Short | Default | Description |
|------|-------|---------|-------------|
| `--provider` | `-p` | all configured | Only test models from one provider |
| `--vendor` | - | - | Alias for `--provider` |
| `--model` | `-m` | all configured | Only test one model ID |
| `--prompt` | - | built-in text prompt | Prompt used for every test |
| `--max-tokens` | - | `256` | Maximum output tokens per request |
| `--timeout` | - | `2m` | Per-model timeout |
| `--concurrency` | - | `1` | Number of models tested in parallel |
| `--runs` | - | `3` | Runs per model; successful runs are averaged |
| `--thinking` | `-t` | `off` | Thinking level (`off`, `minimal`, `low`, `medium`, `high`, `xhigh`, `max`) |

```bash
mothx speedtest
mothx speedtest -p deepseek-openai -m deepseek-v4-flash
mothx speedtest --concurrency 4 --runs 2
```

### `doctor` - Environment Diagnostics

Diagnose your MothX environment: OS info, config files, providers, models, sandbox, MCP, and more.

```
mothx doctor [--json]
```

| Flag | Default | Description |
|------|---------|-------------|
| `--json` | `false` | Print one machine-readable JSON diagnosis (`{ ok, version, summary, checks }`) and nothing else on stdout |

The command checks your installation, configuration, provider connectivity, and sandbox availability.

### `systeminit` - Project AGENTS.md Generator

Generate or refresh a project `AGENTS.md` file that documents project conventions for AI agents.

```
mothx systeminit [guidance...]
```

This CLI subcommand runs non-interactively. In TUI and ACP, `/systeminit` runs interactively and uses the `question` tool to ask clarifying questions before generating the file.

| Argument | Description |
|----------|-------------|
| `guidance...` | Optional trailing guidance (e.g., `ask me in Chinese, write AGENTS.md in English`) |

Examples:
```bash
# Generate AGENTS.md with default behavior
mothx systeminit

# Generate with custom guidance
mothx systeminit ask me in Chinese, write in English
```

Checks performed:
- **Environment**: OS/arch, Go version, shell, home/working directory
- **Configuration Files**: Validates settings, serve, and MCP config files with parse checks
- **Providers & Models**: Lists configured providers with masked API keys, models with context window/max tokens/reasoning flags; verifies default provider initialization
- **Sandbox**: Checks bubblewrap availability and version
- **MCP Servers**: Lists configured MCP servers
- **Sessions**: Shows session directory and entry count
- **Session content store**: Reports split sessions (content only the legacy transcript still holds) and event-store sessions whose turn boundaries no longer address a matching marker; `--repair-session-content [all|SESSION_ID]` adopts a split-store delta and translates boundaries before anything is retired
- **Skills**: Shows global and project skills directories
- **Context Files**: Discovers AGENTS.md, CLAUDE.md, CURSOR.md, .cursorrules, CONVENTIONS.md

```bash
mothx doctor
```

Sample output:
```
  MothX Doctor
  ─────────────────

  Environment
    ✅ OS / Arch — linux/amd64
    ✅ Go version — go1.24.4
    ✅ Shell — /bin/bash
    ✅ Home directory — /home/user
    ✅ Working directory — /home/user/project

  Configuration Files
    ✅ Global settings — /home/user/.mothx/settings.json (1.2 KB)
    ⏭️  Project settings — .mothx/settings.json (not found)
    ...

  Providers & Models
    ✅ Default provider — deepseek-openai
    ✅ Default model — deepseek-v4-flash
    ✅ Provider: deepseek-openai — api=openai-chat, base=https://api.deepseek.com, key=sk-a****xyz
    ✅   └─ deepseek-v4-flash — ctx=1M, max=384K ★ default
    ✅ Provider init — deepseek-openai/deepseek-v4-flash created successfully

  Result: All 15 checks passed
```

## Usage Examples

### Basic Usage

```bash
# Interactive mode
mothx

# With initial prompt
mothx -P "Explain this codebase"

# Non-interactive print mode (`-p` selects a provider; `-P` enables printing)
mothx -P "Write a Hello World"
```

### JSON Output

```bash
# Stream NDJSON (one line per event) and reassemble the assistant text
mothx -P --json "Summarize this repo" | jq -r 'select(.type=="text_delta").text' | tr -d '\n'

# Capture the assistant text in a script
summary=$(mothx -P --json "Describe in one sentence" | jq -r 'select(.type=="text_delta").text' | tr -d '\n')

# Inspect the whole typed event stream
mothx -P --json "Summarize this repo" | jq -s '.'
```

`--json` only takes effect with `-P` (print mode). stdout emits an NDJSON (JSON Lines) stream — each agent event is its own JSON object on one line, so consumers can read line-by-line and react in real time. Event types include `start` (provider/model/mode), `text_delta`, `think_delta`, `tool_call`, `tool_execution_start`/`tool_execution_end`, `tool_result`, `plan_update`, `usage`, `context_usage`, `compaction_start`/`compaction_end`, and a terminating `done` or `error` event. All progress and debug output still goes to stderr, so stdout stays pure NDJSON.

### Specify Provider and Model

```bash
# Use DeepSeek (OpenAI API)
mothx --provider deepseek-openai --model deepseek-v4-flash

# Use DeepSeek (Anthropic API)
mothx -p deepseek-anthropic -m deepseek-v4-flash

# Use custom provider
mothx --provider my-custom-provider
```

### Choose Mode

```bash
# Plan mode - read-only analysis
mothx --mode plan

# Agent mode - standard read/write
mothx -M agent

# YOLO mode - full access (default)
mothx -M yolo
```

### Multi-Agent Mode

```bash
# Enable sub-agent tools and multi-agent commands
mothx --multi-agent

# ACP sessions can also opt in
mothx acp --multi-agent
```

When enabled, MothX registers the `subagent_*` tools and exposes multi-agent workflows such as delegated background investigation. Cron command entry points also depend on multi-agent mode.

### Expert Teams

```bash
# Bind an expert or team while starting a session
mothx --expert software-company
```

`--expert <bundle-id>` resolves a local expert bundle through the shared
Runtime. A team bundle enables its declared member dispatch capability for
that session; a single expert changes only the lead identity. In TUI, use
`/expert list|show <id>|bind <id>|unbind|switch <id>`. Replacing a bound
expert uses a session fork rather than rewriting the source session. See
[Expert Teams](expert-teams.md) for the complete behavior.

### Delegate Mode

```bash
# Enable blocking single sub-agent delegation
mothx --delegate

# ACP sessions can also opt in
mothx acp --delegate

# Serve can opt in
mothx serve --delegate
```

Delegate mode registers the `delegate_subagent` tool for synchronous, blocking sub-agent delegation. Unlike multi-agent (which runs async sub-agents in parallel), delegate mode runs one sub-agent at a time and waits for completion. Use it for bounded investigation tasks where the parent only needs a summarized result.

You can toggle delegation at runtime via `/delegate [on|off|status]` in TUI or serve slash commands.

### Thinking Levels

```bash
# Disable thinking
mothx --thinking off

# Medium level
mothx -t medium

# Highest level
mothx --thinking xhigh

# Provider maximum (where supported, for example DeepSeek V4.1)
mothx --thinking max
```

### Session Management

```bash
# Continue most recent session
mothx --continue
mothx -c

# Resume specific session
mothx --resume session-abc123
mothx -r ~/.mothx/sessions/--encoded-working-directory--/20260625-120000_abcd1234.db

# Use specific session handle file
mothx --session ./20260625-120000_abcd1234.db
```

In the TUI, startup without `--continue`, `--resume`, or `--session` does not create an empty session immediately. A new session is created when the first user message is sent. When an existing session is continued, resumed, or selected, its history is shown in the normal terminal scrollback.

### Sandbox

```bash
# Enable sandbox
mothx --sandbox

# Disable sandbox (default)
mothx
```

### Pipe Input

```bash
# Read from stdin
echo "Explain this code" | mothx -P

# Read from file contents directly
mothx -p "Explain this file: main.go"
```

### ACP Server

```bash
# Start ACP server (for IDE integration)
mothx acp

# ACP with specific model
mothx acp --provider deepseek-openai --model deepseek-v4-flash

# ACP with sandbox
mothx acp --sandbox --mode agent
```

## Interactive Commands

Commands available during interactive sessions:

### Mode & Configuration

| Command | Description |
|---------|-------------|
| `/mode [plan\|agent\|yolo\|os]` | Switch or show the current mode |
| `/model [model_id]` | Switch or show the current model |
| `/defaultModel [project\|global]` | Change the persisted default model |
| `/auth` | Configure provider credentials and endpoints |
| `/settings` | Configure settings.json groups, including providers, defaults, behavior, and approval |
| `/tuilang [global\|project] [auto\|zh\|en]` | Change the TUI language |
| `/env [list\|set KEY VALUE\|unset KEY\|clear]` | Inspect or edit environment variables for the process |
| `/esm [objective\|edit\|pause\|resume\|clear\|guide]` | Manage the ESM objective and progress panel |
| `/compact` | Trigger context compaction |
| `/delegate [on\|off\|status]` | Toggle or show delegate mode |
| `/browser [on\|off\|status]` | Toggle or show the browser tool |
| `/statusline [status\|on\|off\|command\|refresh] ...` | Configure the external status line |
| `/btw <question>` | Ask a side question without interrupting the main task |
| `/rule [force\|--force]` | Refresh project rules |
| `/systeminit [guidance]` | Generate or refresh project `AGENTS.md` |
| `/reload` | Restart with a fresh session (TUI) |
| `/alloweditpath [add <glob>\|remove <glob>\|clear]` | Manage the auto-edit path whitelist |
| `/allowautoedit [on\|off] [global]` | Toggle full auto-edit in agent mode |
| `/agent list\|switch <id>\|destroy <id>` | List, switch, or destroy sub-agents in multi-agent mode |

### Session & Orchestration

| Command | Description |
|---------|-------------|
| `/sessions` | Open the interactive session picker |
| `/sessions ls` | List sessions for the current project |
| `/sessions set <id>` | Switch to a session by ID prefix |
| `/sessions clear` | Start fresh; the new session is created on the next message |
| `/sessions del <id>` | Delete a session by ID prefix |
| `/clear` | Clear conversation |
| `/expert [list\|show <id>\|bind <id>\|unbind\|switch <id>]` | Manage the session Expert Team binding |
| `/cron add\|list\|enable\|disable\|remove\|run` | Manage scheduled tasks |
| `/workflows [list\|show <id>\|cancel <id>]` | Manage workflow runs |

The `/sessions` picker supports Up/Down to select, Enter to switch, `n` to start fresh, `d` to delete the selected session, and Esc to close.

### Skills & MCP

| Command | Description |
|---------|-------------|
| `/skills` | List available skills |
| `/skill <name>` | Activate a skill by name |
| `/skill:<name>` | Activate a skill (alternative syntax) |
| `/skillhub [search <q>]` | Open the online skill marketplace or search it |
| `/skillmgr` | Open the installed-skill manager |
| `/mcpmgr [project\|global]` | Open the MCP management panel (add, edit, delete, enable, or disable servers) |
| `/paste-image` | Attach an image from the clipboard (where supported) |

### General

| Command | Description |
|---------|-------------|
| `/stats server\|stop-server\|tui` | Open, stop, or print usage statistics |
| `/help` | Show help |
| `/quit` | Exit |

## Keyboard Shortcuts

| Shortcut | Function |
|----------|----------|
| `Enter` | Submit the current prompt |
| `Alt+Enter` / `Ctrl+J` | Insert a newline in the prompt editor |
| `Tab` | Cycle mode (`plan` → `agent` → `yolo`) |
| `Esc` | Abort current operation, approval, or question prompt |
| `Ctrl+O` | Open latest tool/details modal; press again, `Esc`, or `q` to close |
| `Ctrl+E` | Open the ESM progress panel; press again, `Esc`, or `q` to close |
| `Ctrl+G` | Toggle simple/full event display; simple is the default |
| `Up` / `Down` | Move within multiline input; browse prompt history at the first/last input line; scroll an open details/progress panel |
| `PgUp` / `PgDn` | Page through an open details/progress panel |
| `Home` / `End` | Move to the start/end of the current input line; jump to top/bottom in an open details/progress panel |

## Environment Variables

Default settings can be overridden via environment variables:

| Variable | Description |
|----------|-------------|
| `DEEPSEEK_API_KEY` | DeepSeek API key |
| `MOTHX_DIR` | Override config directory |
| `VIBECODING_PROVIDER` | Override default provider |
| `VIBECODING_MODEL` | Override default model |
| `VIBECODING_MODE` | Override default mode |
| `VIBECODING_THINKING` | Override default thinking level |
| `VIBECODING_USER_AGENT` | Custom User-Agent string |
| `VIBECODING_ALLOW_SHELL_CONFIG` | Allow `!command` credential/header resolution |
| `VIBECODING_DEBUG` | Enable provider request/response debug output |
| `VIBECODING_NO_UPDATE_CHECK` | Disable update checks |
| `MOTHX_ACP_PERMISSION_TIMEOUT` | Default ACP approval timeout (Go duration) |
| `MOTHX_ACP_QUESTION_TIMEOUT` | Default ACP question timeout (Go duration) |
| `MOTHX_WIN_OUTPUT_ENCODING` | Override captured Windows output decoding (`utf-8` or a code page number) |

## Exit Codes

| Code | Description |
|------|-------------|
| 0 | Success |
| 1 | General error |
| 2 | Usage error |
| 130 | User interrupt (Ctrl+C) |

---

## Configuration Guide

Source: https://mothx.net/en/configuration.md

# Configuration Guide

## Configuration File Locations

MothX uses two configuration files:

| File | Platform | Scope | Priority |
|------|----------|-------|----------|
| `~/.mothx/settings.json` | Linux/macOS | Global (all projects) | Low |
| `%APPDATA%\mothx\settings.json` | Windows | Global (all projects) | Low |
| `.mothx/settings.json` | All | Project-level | High |

> **Tip:** Override the global configuration directory with `MOTHX_DIR`.

> **Windows:** `%APPDATA%` resolves to `C:\Users\<Username>\AppData\Roaming`, so the full path is typically `C:\Users\<Username>\AppData\Roaming\mothx\settings.json`.

Project-level configuration overrides global configuration. Providers are merged by provider ID and then by fields explicitly present in the project file. An explicitly supplied `models` array replaces that provider's inherited model list.

### Legacy Directories

The current release uses `.mothx` for project files and `~/.mothx` (or `%APPDATA%\mothx` on Windows) for global files. Legacy `.vibe` and `.vibecoding` directories are neither read nor migrated. Copy any configuration you still need into the corresponding `.mothx` directory and review paths and fields.


### `tuilang` (TUI language)

The top-level `tuilang` setting accepts `"auto"` (the default), `"zh"`, or `"en"`. `zh` and `en` force the corresponding language. In `auto`, MothX checks the current UTC offset once at TUI startup: exactly UTC+08:00 selects Chinese; every other offset selects English. A project `.mothx/settings.json` value overrides the global value. The TUI `/settings` menu can switch the language, choose global or project scope, and apply a successful change immediately. Slash command syntax remains English in every language.
## Configuration Structure

### Complete Example

```json
{
  "providers": {
    "deepseek-anthropic": {
      "baseUrl": "https://api.deepseek.com/anthropic",
      "apiKey": "${DEEPSEEK_API_KEY}",
      "api": "anthropic-messages",
      "thinkingFormat": "deepseek",
      "cacheControl": false,
      "models": [
        {
          "id": "deepseek-v4-flash",
          "name": "DeepSeek-V4-Flash",
          "contextWindow": 1000000,
          "maxTokens": 384000,
          "cost": { "input": 0.5, "output": 2.0 }
        },
        {
          "id": "deepseek-v4-pro",
          "name": "DeepSeek-V4-Pro",
          "reasoning": true,
          "contextWindow": 1000000,
          "maxTokens": 384000,
          "cost": { "input": 1, "output": 4 }
        }
      ]
    },
    "deepseek-openai": {
      "baseUrl": "https://api.deepseek.com",
      "apiKey": "${DEEPSEEK_API_KEY}",
      "api": "openai-chat",
      "models": [
        {
          "id": "deepseek-v4-flash",
          "name": "DeepSeek-V4-Flash",
          "contextWindow": 1000000,
          "maxTokens": 384000,
          "cost": { "input": 0.5, "output": 2.0 }
        },
        {
          "id": "deepseek-v4-pro",
          "name": "DeepSeek-V4-Pro",
          "reasoning": true,
          "contextWindow": 1000000,
          "maxTokens": 384000,
          "cost": { "input": 1, "output": 4 }
        }
      ]
    }
  },
  "defaultProvider": "deepseek-openai",
  "defaultModel": "deepseek-v4-flash",
  "defaultMode": "yolo",
  "defaultThinkingLevel": "medium",
  "toolExecution": {
    "mode": "parallel",
    "maxConcurrency": 10
  },
  "statusLine": {
    "enabled": false,
    "type": "command",
    "command": "ccstatusline",
    "padding": 0,
    "refreshInterval": 10,
    "timeoutMs": 800,
    "fallback": "builtin"
  },
  "enablePlanTool": true,
  "enableArtifact": false,
  "enableACPArtifact": false,
  "maxContextTokens": 1000000,
  "contextFiles": {
    "enabled": true,
    "extraFiles": ["/path/to/extra-context.md"]
  },
  "skillsDir": "~/.mothx/skills",
  "compaction": {
    "enabled": true,
    "reserveTokens": 16384,
    "keepRecentTokens": 20000,
    "tokenizer": "auto",
    "template": "default"
  },
  "sandbox": {
    "enabled": false,
    "level": "none",
    "bwrapPath": "",
    "allowNetwork": false,
    "allowedRead": ["/usr", "/lib", "/lib64", "/bin", "/sbin"],
    "allowedWrite": [],
    "deniedPaths": ["/etc/shadow", "/root", "/home"],
    "passEnv": ["PATH", "HOME", "USER", "LANG", "TERM", "SHELL"],
    "tmpSize": "100m"
  },
  "sessionDir": "~/.mothx/sessions",
  "shellPath": "/bin/bash",
  "shellCommandPrefix": "",
  "theme": "dark",
  "tuilang": "auto",
  "retry": {
    "enabled": true,
    "maxRetries": 5,
    "baseDelayMs": 3000
  },
  "approval": {
    "bashWhitelist": ["go ", "make ", "git ", "npm ", "yarn ", "node ", "python ", "pip "],
    "bashBlacklist": ["rm -rf", "sudo"],
    "confirmBeforeWrite": true
  }
}
```

## All Configuration Fields

### Top-Level Fields Reference

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `providers` | object | *(see below)* | Provider configurations (keyed by name) |
| `defaultProvider` | string | `"deepseek-openai"` | Which provider to use by default |
| `defaultModel` | string | `"deepseek-v4-flash"` | Which model ID to use by default |
| `defaultMode` | string | `"yolo"` | Default run mode: `plan`, `agent`, `yolo`, or `os`. `router` is not a valid default: Router binds one or more external ACP worker profiles to one session, so it is entered through activation (`/router`) rather than a global default |
| `defaultThinkingLevel` | string | `"medium"` | Default thinking level |
| `toolExecution` | object | *(see below)* | Local function/custom tool execution mode and per-batch concurrency |
| `statusLine` | object | *(see below)* | External status line command settings for TUI only |
| `enablePlanTool` | bool | `true` | Register the built-in `plan` tool |
| `enableArtifact` | bool | `false` | Allow TUI/CLI sessions to publish generated artifacts |
| `enableACPArtifact` | bool | `false` | Allow Desktop/ACP sessions to publish generated artifacts |
| `imageGeneration` | object | *(disabled)* | Standalone image-generation tool settings |
| `maxContextTokens` | int | `0` (auto) | Override maximum context token count |
| `contextFiles` | object | *(see below)* | Context file loading settings |
| `skillsDir` | string | `"~/.mothx/skills"` | Global skills directory path |
| `skills` | object | *(empty)* | Skill loading overrides (currently a disable list) |
| `skillHub` | object | built-in defaults | Online skill marketplace settings |
| `compaction` | object | *(see below)* | Context compaction settings |
| `sandbox` | object | *(see below)* | Sandbox execution settings |
| `sessionDir` | string | `"~/.mothx/sessions"` | SQLite session storage directory |
| `shellPath` | string | `""` (auto) | Custom shell path for Bash tool |
| `shellCommandPrefix` | string | `""` | Prefix prepended to every shell command |
| `theme` | string | `"dark"` | UI theme: `"dark"` or `"light"` |
| `tuilang` | string | `"auto"` | TUI language: `"auto"`, `"zh"`, or `"en"` |
| `retry` | object | *(see below)* | API call retry settings |
| `approval` | object | *(see below)* | Bash command approval settings |
| `worktree` | object | *(see below)* | Isolated git worktree settings |
| `maintenance` | object | *(see below)* | Runtime-owned background housekeeping (attachment and session storage maintenance) |
| `webSearch` | object | *(see below)* | DeepSeek web search/fetch tool settings |
| `updateCheck` | bool | `true` | Enable npm-based update notifications |

---

## Configuration Details

### statusLine

TUI-only status line command configuration. When enabled, MothX sends the current status JSON to an external command via stdin and replaces the built-in footer below the input box with that command's stdout.

If it is disabled, not configured, still on its first run, times out, fails, or returns empty output, the TUI keeps the current built-in footer.

Other modes ignore this setting entirely, including Serve, Channels, ACP, and print mode.

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `enabled` | bool | `false` | Enable the external status line |
| `type` | string | `"command"` | Currently only `"command"` is supported |
| `command` | string | `""` | Status line command to execute, for example `ccstatusline` |
| `padding` | int | `0` | Blank lines appended after the status line output |
| `refreshInterval` | int | `0` | Optional periodic refresh in seconds; `0` means event-driven only |
| `timeoutMs` | int | `800` | Per-invocation timeout in milliseconds |
| `fallback` | string | `"builtin"` | Fallback strategy on failure; keep `"builtin"` |

Minimal example:

```json
{
  "statusLine": {
    "enabled": true,
    "type": "command",
    "command": "ccstatusline",
    "refreshInterval": 10,
    "timeoutMs": 800
  }
}
```

Notes:

- The current implementation supports `stdin snapshot` mode only.
- It does not emit `transcript_path`.
- It does not generate transcript JSONL files for `ccstatusline`.
- Widgets that depend on transcript history scanning may therefore be empty or less accurate.

### providers

Multi-provider configuration. Each provider is an object keyed by a user-chosen name:

| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `baseUrl` | string | ✓ | — | API base URL |
| `vendor` | string | — | auto-detect | Optional vendor adapter name (see below) |
| `apiKey` | string | — | `""` | API key (see [Authentication](#authentication-configuration) below) |
| `api` | string | — | auto-detect | API protocol: `"openai-chat"`, `"openai-responses"`, `"anthropic-messages"`, `"google-gemini"`, or `"google-vertex"` |
| `httpProxy` | string | — | `""` | Optional per-provider HTTP proxy URL, e.g. `"http://127.0.0.1:7890"` |
| `forceHTTP11` | bool | — | `false` | Force HTTP/1.1 for this provider by disabling HTTP/2 on the provider HTTP client |
| `headers` | object | — | `{}` | Optional custom HTTP headers applied to every provider request; values support the same `${ENV}` and `!cmd` resolution as `apiKey` |
| `thinkingFormat` | string | — | auto-detect | Thinking parameter format (see below) |
| `cacheControl` | bool | — | `false` | Enable Anthropic prompt caching; set `true` when using Claude models |
| `models` | array | — | `[]` | List of available models |

#### vendor field

The `vendor` field selects a vendor adapter without changing the provider config schema. It is optional; when omitted, MothX tries to detect the vendor from `baseUrl`, then falls back to the generic protocol provider selected by `api`.

Selection order:

1. Explicit `vendor`
2. Base URL detection
3. Generic fallback: `openai-chat`, `openai-responses`, `anthropic-messages`, `google-gemini`, or `google-vertex`

Built-in vendor adapters include `openai`, `anthropic`, `claude`, `deepseek`, `agnes`, `google-gemini`, `google-vertex`, `xiaomi`, `xiaomi-token-plan-ams`, `xiaomi-token-plan-cn`, `xiaomi-token-plan-sgp`, `volcengine`, `kimi`, `minimax`, `qianfan`, `bailian`, `gitee`, `openrouter`, `together`, `groq`, `fireworks`, `mistral`, `github-copilot`, `cloudflare-ai-gateway`, `cloudflare-workers-ai`, `sensenova`, and `amazon-bedrock`.

```json
{
  "providers": {
    "custom-deepseek": {
      "vendor": "deepseek",
      "baseUrl": "https://api.deepseek.com",
      "apiKey": "${DEEPSEEK_API_KEY}",
      "api": "openai-chat",
      "headers": {
        "X-Request-Source": "mothx",
        "X-Gateway-Token": "${MY_GATEWAY_TOKEN}"
      },
      "models": [
        { "id": "deepseek-v4-flash", "name": "DeepSeek-V4-Flash", "contextWindow": 1000000 }
      ]
    }
  }
}
```

#### Volcengine / Doubao example

The built-in `volcengine` provider uses the Ark OpenAI-compatible endpoint and supports Doubao Seed models. It can also be detected automatically from `ark.cn-beijing.volces.com`.

```json
{
  "providers": {
    "volcengine": {
      "vendor": "volcengine",
      "baseUrl": "https://ark.cn-beijing.volces.com/api/v3",
      "apiKey": "${VOLCENGINE_API_KEY}",
      "api": "openai-chat",
      "models": [
        { "id": "doubao-seed-evolving", "name": "Doubao Seed Evolving", "contextWindow": 262144, "maxTokens": 262144, "input": ["text", "image"] },
        { "id": "doubao-seed-2-1-pro-260628", "name": "Doubao Seed 2.1 Pro", "contextWindow": 262144, "maxTokens": 262144, "input": ["text", "image"] }
      ]
    }
  }
}
```

#### SenseNova (商汤日日新) example

The built-in `sensenova` provider uses the SenseNova token-plan endpoint and the OpenAI-compatible `openai-chat` API. It ships `sensenova-6.8-flash` and `sensenova-6.8-flash-lite`, both with a 1,000,000-token context window, a 131,072-token output ceiling, reasoning support, and `text`/`image` input. The vendor is also detected automatically from `token.sensenova.cn`.

```json
{
  "providers": {
    "sensenova": {
      "vendor": "sensenova",
      "baseUrl": "https://token.sensenova.cn/v1",
      "apiKey": "${SENSENOVA_API_KEY}",
      "api": "openai-chat",
      "models": [
        { "id": "sensenova-6.8-flash", "name": "SenseNova 6.8 Flash", "reasoning": true, "contextWindow": 1000000, "maxTokens": 131072, "input": ["text", "image"] },
        { "id": "sensenova-6.8-flash-lite", "name": "SenseNova 6.8 Flash Lite", "reasoning": true, "contextWindow": 1000000, "maxTokens": 131072, "input": ["text", "image"] }
      ]
    }
  }
}
```

#### Pointing MothX at a self-hosted or gateway endpoint

Any endpoint that speaks the OpenAI **Responses** API can be used as a provider by setting `api` to `"openai-responses"` and pointing `baseUrl` at it. This is the supported way to put a gateway, a corporate proxy, or your own translation shim in front of a model:

```json
{
  "providers": {
    "my-gateway": {
      "baseUrl": "http://127.0.0.1:8787/v1",
      "apiKey": "${MY_GATEWAY_TOKEN}",
      "api": "openai-responses",
      "httpProxy": "http://127.0.0.1:7890",
      "headers": {
        "X-Request-Source": "mothx"
      },
      "models": [
        { "id": "gpt-5.3-codex", "name": "GPT-5.3 Codex (gateway)", "reasoning": true, "contextWindow": 400000, "maxTokens": 128000, "input": ["text", "image"] }
      ]
    }
  },
  "defaultProvider": "my-gateway"
}
```

Notes for gateway setups:

- `apiKey` is the credential the **gateway** expects. MothX supports a plain string, `${ENV_VAR}`, and `!command` (with `VIBECODING_ALLOW_SHELL_CONFIG=1`), so a gateway that reads a token from disk or a secret manager works the same way a direct provider does.
- Declare the models explicitly. A gateway that does not implement `/v1/models` still works, because MothX uses the `models` list you configure.
- Use `"openai-chat"` instead of `"openai-responses"` when the gateway only implements Chat Completions. Reasoning models then need a `thinkingFormat` that the upstream understands.
- Verify the gateway with `mothx doctor` or the `mothx speedtest` command before starting a long run.

#### Using OpenAI Codex models

The built-in `openai` provider is already configured for the Codex model family: it uses the Responses API (`"openai-responses"`), points at `https://api.openai.com/v1`, and sends the Codex CLI user agent its endpoint expects. The Codex models (`gpt-5-codex`, `gpt-5.1-codex`, `gpt-5.2-codex`, `gpt-5.3-codex`, …) are part of the built-in model list, so no settings change is needed beyond an API key:

```bash
export OPENAI_API_KEY=sk-...
mothx --provider openai --model gpt-5.3-codex
```

**This uses the OpenAI API, billed per token.** It is not covered by a ChatGPT Plus/Pro subscription. See the FAQ entry "Can I use my ChatGPT/Codex subscription in MothX?" for why a ChatGPT subscription cannot be pointed at MothX directly.

### webSearch

Local web-search backend settings. This is disabled by default. When enabled, MothX registers the local `web_search` tool for chat providers without native hosted search. `web_fetch` is available for the DeepSeek backend. Provider-native hosted search (OpenAI Responses, and Anthropic Messages while `webSearch` is enabled) remains available and takes precedence over the local `web_search` function when present.

| Field | Type | Required | Default | Description |
|-------|------|----------|---------|-------------|
| `enabled` | bool | — | `false` | Enable the local `web_search` tool (and `web_fetch` for DeepSeek) |
| `backend` | string | — | `deepseek` | `deepseek` or `yuanbao` (Tencent Yuanbao SearchPro) |
| `provider` | string | — | `deepseek-openai` | DeepSeek credential fallback provider; ignored by the Yuanbao backend |
| `baseUrl` | string | — | backend default | DeepSeek: `https://api.deepseek.com` (`/v1/tools/search` and `/v1/tools/fetch`). Yuanbao: `https://api.wsa.cloud.tencent.com` (`/SearchPro`) |
| `token` | string | — | backend default | DeepSeek: provider `apiKey` or `${DEEPSEEK_API_KEY}`. Yuanbao: `${TENCENTCLOUD_WSA_APIKEY}`. An explicit value overrides the fallback |

DeepSeek example:

```json
{
  "webSearch": {
    "enabled": true,
    "backend": "deepseek",
    "provider": "deepseek-openai",
    "baseUrl": "https://api.deepseek.com",
    "token": "${DEEPSEEK_API_KEY}"
  }
}
```

Tencent Yuanbao example:

```json
{
  "webSearch": {
    "enabled": true,
    "backend": "yuanbao",
    "baseUrl": "https://api.wsa.cloud.tencent.com",
    "token": "${TENCENTCLOUD_WSA_APIKEY}"
  }
}
```

Both backends use Bearer authentication and read-only requests, so they may be used in plan mode. With `deepseek`, `web_search` accepts a query plus optional `count` (1–50), `ori_question`, `localization`, and `need_content`, and `web_fetch` accepts one HTTP/HTTPS URL and returns the page as Markdown. With `yuanbao`, `web_search` sends `{"Query": ...}` to `/SearchPro` and normalizes the returned `Pages` (title, URL, site, date, score, passage); the Yuanbao API currently provides search only, so `web_fetch` is not registered.

#### api field

The `api` field specifies the **protocol format**, not the service provider. You can point any provider to any compatible endpoint:

- `openai-chat`: OpenAI Chat Completions API format
- `openai-responses`: OpenAI Responses API format (`POST /v1/responses`)
- `anthropic-messages`: Anthropic Messages API format
- `google-gemini`: Native Gemini API `streamGenerateContent` format
- `google-vertex`: Native Vertex AI Gemini `streamGenerateContent` format

For example, DeepSeek offers both formats at different endpoints, and you can also use these formats to connect to the actual OpenAI or Anthropic services.

If not specified, auto-detected based on `baseUrl`:
- Contains `generativelanguage.googleapis.com` → `google-gemini`
- Contains `aiplatform.googleapis.com` → `google-vertex`
- Contains "anthropic" → `anthropic-messages`
- Others → `openai-chat`

#### responses field

`responses` configures the advanced behavior used when `api` is `"openai-responses"`. All fields are optional; model compatibility flags may reject unsupported fields before an upstream request is made.

```json
{
  "providers": {
    "openai": {
      "baseUrl": "https://api.openai.com/v1",
      "apiKey": "${OPENAI_API_KEY}",
      "api": "openai-responses",
      "responses": {
        "stateMode": "previous_response_id",
        "reasoningSummary": "auto",
        "reasoningContext": "all_turns",
        "promptCacheEnabled": true,
        "promptCacheMode": "implicit"
      }
    }
  }
}
```

| Field | Values / Type | Description |
|-------|---------------|-------------|
| `stateMode` | `replay`, `previous_response_id`, `conversation` | Session state strategy. `replay` is local-history replay; `previous_response_id` continues the provider response lineage; `conversation` requires `conversation`. |
| `store` | bool | Request upstream response storage when supported. |
| `conversation` | string | Provider conversation ID; required with `stateMode: "conversation"`. |
| `truncation` | `auto`, `disabled` | Upstream Responses truncation behavior. |
| `background` | bool | In Serve, run supported Responses requests remotely as durable background jobs. MothX polls them, resumes recoverable jobs after a restart, and handles local tools. |
| `reasoningSummary` | `auto`, `concise`, `detailed`, `none`, `off` | Request a reasoning summary where supported. |
| `reasoningContext` | `auto`, `current_turn`, `all_turns` | Controls the reasoning context sent between turns. |
| `reasoningMode` | `standard`, `pro` | Provider-specific reasoning mode. |
| `promptCacheEnabled` | bool | Enabled by default for Responses providers; set `false` to disable prompt-cache fields. |
| `promptCacheKey`, `promptCacheRetention`, `promptCacheMode`, `promptCacheTTL` | string | Prompt-cache key and provider-specific retention/mode/TTL controls. |
| `safetyIdentifier` | string | Provider safety identifier. |
| `metadata` | object | Non-sensitive provider metadata (maximum 16 entries). |
| `include` | string array | Extra supported Response item fields to include. |
| `serviceTier` | string | Provider service tier. |
| `structuredOutput` | object | JSON Schema structured output: `name`, `description`, `strict`, and `schema`. |
| `toolControl` | object | Tool selection and execution controls: `choice`, `parallel`, `maxCalls`. |
| `hostedTools` | object | Provider-hosted tool options: `webSearch`, `fileSearch`, `codeInterpreter`, `imageGeneration`, and `remoteMCP`. |

`background` is only available through `mothx serve`; normal CLI/TUI/ACP requests continue to use the streaming agent loop. A background-capable provider must support the selected model and Responses features.

`toolControl.choice` selects the `tool_choice` sent to OpenAI Responses providers: `auto`, `none`, `required`, or the name of a tool to force that tool. The WebUI exposes `responses.toolControl` under Settings > Providers (Tool Choice, Parallel Tool Calls, Max Tool Calls), and the TUI exposes it under `/settings` > provider > B. Protocol > Responses. The TUI editor writes the global settings file; project-level overrides remain supported through `.mothx/settings.json`.

Google native providers can be configured directly:

```json
{
  "providers": {
    "google-gemini": {
      "baseUrl": "https://generativelanguage.googleapis.com/v1beta/models",
      "apiKey": "${GOOGLE_API_KEY}",
      "api": "google-gemini",
      "models": [
        { "id": "gemini-2.5-flash", "name": "Gemini 2.5 Flash", "reasoning": true, "contextWindow": 1000000, "maxTokens": 65536 }
      ]
    },
    "google-vertex": {
      "baseUrl": "https://aiplatform.googleapis.com/v1/publishers/google/models",
      "apiKey": "${GOOGLE_CLOUD_API_KEY}",
      "api": "google-vertex",
      "models": [
        { "id": "gemini-2.5-flash", "name": "Gemini 2.5 Flash", "reasoning": true, "contextWindow": 1000000, "maxTokens": 65536 }
      ]
    }
  }
}
```

For `google-vertex`, `${GOOGLE_CLOUD_API_KEY}` uses the Vertex AI API key path and does not require `gcloud`, project, or location in the URL. OAuth access tokens are still supported by using a project-scoped URL such as `https://aiplatform.googleapis.com/v1/projects/YOUR_PROJECT/locations/global/publishers/google/models` and an access token value such as `!gcloud auth print-access-token`. Set `VIBECODING_ALLOW_SHELL_CONFIG=1` before using `!command` values.

#### thinkingFormat field

Specifies how thinking/reasoning parameters are sent to the API:

| Value | Behavior |
|-------|----------|
| `""` (empty) | Auto-detect based on URL |
| `"openai"` | Use OpenAI `reasoning_effort` format |
| `"anthropic"` | Use Anthropic `thinking` with `budget_tokens` |
| `"deepseek"` | Use DeepSeek `thinking: {type: "enabled"}` + `reasoning_effort` (OpenAI) or `output_config.effort` (Anthropic); an explicit off sends `thinking: {type: "disabled"}` |
| `"xiaomi"` | Legacy thinking-only format: `thinking: {type: "enabled"}` |
| `"thinking-only"` | Thinking switch without an effort field; use it to opt a DeepSeek V4.1 deployment out of `reasoning_effort`; an explicit off sends `thinking: {type: "disabled"}` |
| `"deepseek-v4.1"` | DeepSeek V4.1 `reasoning_effort`: `none` (no thinking), `minimal`, `low`, `medium`, `high`, `xhigh`, `max` |
| `"kimi"` | Kimi `reasoning_effort`: `low`, `high`, `max` |
| `"qwen"` | Qwen hybrid thinking: `enable_thinking` plus `thinking_budget` |
| `"zai"` | GLM/Z.ai thinking switch plus `reasoning_effort` mapped to `low`/`high`/`max` |
| `"doubao-seed"` | Doubao Seed 2.1 / Evolving `reasoning_effort`: `minimal` (no thinking), `low`, `medium`, `high` (default) |

When not set, automatically detects:
- URL contains `deepseek` → `"deepseek"`
- URL contains `xiaomimimo` → `"xiaomi"`
- Model ID matches `doubao-seed-2.1*` or `doubao-seed-evolving` → `"doubao-seed"`
- Model ID contains `deepseek-v4.1` or `deepseek-v4-1` → `"deepseek-v4.1"`
- Model ID contains `qwen3.5`, `qwen3.6`, `qwen3.7`, or `qwen3.8` → `"qwen"`
- Model ID contains `glm` → `"zai"`

An explicit provider `thinkingFormat` (or a model's `compat.thinkingFormat`) always wins over these heuristics. A deployment that only accepts the older thinking switch can opt out of `reasoning_effort` by setting `thinkingFormat` to `thinking-only`.

DeepSeek effort values follow its documented mapping: `minimal`/`low` → `low`, `medium`/`high`/`xhigh` → `high`, `max` → `max`. An explicit off sends `thinking: {type: "disabled"}` for Chat Completions and Anthropic Messages, and `reasoning_effort: "none"` for DeepSeek V4.1 and the Responses API.

Qwen hybrid thinking models send `enable_thinking: false` for an explicit off. GLM models map effort to `low`/`high`/`max` (`medium`/`high`/`xhigh` → `high`); GLM-5.3 cannot disable reasoning, so an explicit off leaves the vendor's always-on default instead of sending the rejected `thinking.type: "disabled"`.

When a Chat Completions request carries tools, replayed assistant messages carry their recorded reasoning content as `reasoning_content`. Endpoints that require the field always receive it, even when no reasoning was recorded: official DeepSeek, Kimi/Moonshot, and MiMo — including `mimo-*` model IDs served by aggregators such as B.AI, Gitee/Moark, or OpenRouter. No empty placeholder is synthesized for models that do not require it.

MothX also learns this at runtime: when an OpenAI-compatible gateway rejects `reasoning_effort`, it retries immediately without the field, shows the reason in the retry notice, and records `thinkingFormat: "thinking-only"` plus `supportsReasoningEffort: false` on that model so later runs omit it.

```json
{
  "providers": {
    "deepseek-openai": {
      "baseUrl": "https://api.deepseek.com",
      "apiKey": "sk-...",
      "api": "openai-chat",
      "thinkingFormat": "deepseek"
    }
  }
}
```

#### cacheControl field

Enable Anthropic-style prompt caching. When set to `true`, MothX adds cache control headers to requests. **You should enable this when using Claude models through the Anthropic API** to reduce cost and latency.

```json
{
  "providers": {
    "anthropic": {
      "baseUrl": "https://api.anthropic.com",
      "apiKey": "${ANTHROPIC_API_KEY}",
      "api": "anthropic-messages",
      "cacheControl": true,
      "models": [
        {
          "id": "claude-sonnet-4-20250514",
          "name": "Claude Sonnet 4",
          "contextWindow": 200000,
          "maxTokens": 8192,
          "cost": {
            "input": 3,
            "output": 15,
            "cacheRead": 0.3,
            "cacheWrite": 3.75
          }
        }
      ]
    }
  }
}
```

#### models array

Each model in the `models` array:

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `id` | string | — | Model ID sent to the API |
| `name` | string | — | Human-readable display name |
| `reasoning` | bool | `false` | Whether the model supports thinking/reasoning |
| `contextWindow` | int | `0` | Context window size (tokens) |
| `maxTokens` | int | `0` | Maximum output tokens per response. An explicit `0` disables the output-token limit on OpenAI/Google-style endpoints (the field is omitted from the request); Anthropic endpoints require `max_tokens`, so an explicit `0` falls back to the default of 16384 there |
| `input` | []string | `[]` | Supported input modalities: `"text"`, `"image"` |
| `cost` | object | `null` | Pricing per million tokens |
| `compat` | object | `null` | Model-specific compatibility flags for provider quirks |

The `cost` object:

| Field | Type | Description |
|-------|------|-------------|
| `input` | float | Cost per million input tokens |
| `output` | float | Cost per million output tokens |
| `cacheRead` | float | Cost per million cached read tokens (Anthropic) |
| `cacheWrite` | float | Cost per million cached write tokens (Anthropic) |

The `compat` object is optional and should only be set when a model needs protocol-specific adjustments:

| Field | Type | Description |
|-------|------|-------------|
| `thinkingFormat` | string | Override model thinking format (`openai`, `deepseek`, `xiaomi`, `anthropic`, etc.) |
| `requiresReasoningContentOnAssistant` | bool | Send empty `reasoning_content` on replayed assistant messages (also inferred for Kimi/MiMo model IDs and DeepSeek/MiMo/Moonshot endpoints) |
| `requiresReasoningContentOnAssistantMessages` | bool | Alias used by the reference implementation; treated the same as above |
| `forceAdaptiveThinking` | bool | Force Anthropic adaptive thinking format |
| `supportsReasoningEffort` | bool | Whether the model accepts `reasoning_effort` |
| `maxTokensField` | string | Use `max_tokens` or `max_completion_tokens` |
| `supportsDeveloperRole` | bool | Whether developer-role messages are supported |
| `supportsStore` | bool | Whether OpenAI `store` is supported |
| `supportsStrictMode` | bool | Whether strict tool schemas are supported |
| `supportsParallelToolCalls` | bool | Whether the provider/model accepts explicit parallel tool-call controls; set `false` for gateways that reject them. Anthropic Messages then omits the entire `tool_choice` object, not only `disable_parallel_tool_use` |
| `supportsToolChoice` | bool | Whether the provider/model accepts explicit tool-choice controls; Anthropic Messages omits `tool_choice` when this is `false` |
| `supportsCacheControlOnTools` | bool | Whether cache control can be applied to tool definitions |
| `supportsLongCacheRetention` | bool | Whether long prompt-cache retention is supported |
| `sendSessionAffinityHeaders` | bool | Whether session affinity headers should be sent |
| `supportsEagerToolInputStreaming` | bool | Whether Anthropic eager tool input streaming is supported |

`supportsToolChoice` and `supportsParallelToolCalls` are also editable in the WebUI model row and in the TUI under `/settings` > model > Compatibility; the remaining flags stay file-only.

```json
{
  "id": "deepseek-v4-flash",
  "name": "DeepSeek-V4-Flash",
  "contextWindow": 1000000,
  "maxTokens": 384000,
  "reasoning": false,
  "input": ["text"],
  "cost": {
    "input": 0.5,
    "output": 2.0
  }
}
```

---

### imageGeneration

Standalone image-generation configuration for the `image_generation` tool. The tool is registered only when `enabled` is `true`. Omitted endpoint fields fall back to the selected provider, so a normal OpenAI provider configuration usually needs only `enabled` and `provider`.

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `enabled` | bool | `false` | Register the `image_generation` tool |
| `provider` | string | `openai` | Provider used to fill omitted `apiType`, `baseUrl`, and `token` fields |
| `apiType` | string | `openai-images` | `openai-images` (Images API) or `openai-responses` (Responses native image generation) |
| `baseUrl` | string | provider `baseUrl`, then `https://api.openai.com/v1` | Image API endpoint |
| `token` | string | provider `apiKey` | Credential; supports `${ENV_VAR}` and opt-in `!command` resolution |
| `model` | string | `gpt-image-1` | Image model ID |

```json
{
  "imageGeneration": {
    "enabled": true,
    "provider": "openai",
    "model": "gpt-image-1"
  }
}
```

See [`image_generation`](tools.md#image_generation---image-generation) for the tool parameters.

---

### toolExecution

This is a local execution setting only. `sequential` limits MothX's local workers after a response arrives; it does not ask the model to emit one tool call at a time, so providers may still return multiple tool calls in a single response. A `parallel` batch reports each call's start in the model's declared order, and that ordering never blocks execution: calls still run concurrently, each waits for its own approvals and durable execution record, and only the completion order is unrestricted. The setting is shared by TUI, WebUI, Serve, channels, ACP, and sub-agents built through the common runtime. It does not control concurrency inside provider-hosted tools such as OpenAI Responses `web_search`; those calls remain under the provider's own orchestration and quota rules.

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `mode` | string | `"parallel"` | `"parallel"` uses bounded local workers; `"sequential"` executes returned calls one at a time locally (provider-side parallel output is unaffected) |
| `maxConcurrency` | int | `10` | Maximum local tool calls in flight for one Agent/tool-call batch; `1` is serial; omitted or non-positive values use `10` |

Example:

```json
{
  "toolExecution": {
    "mode": "parallel",
    "maxConcurrency": 10
  }
}
```

The WebUI exposes these fields in Settings > Tools, and the TUI exposes them under `/settings` > Behavior. The TUI editor writes the global settings file; project-level overrides remain supported through `.mothx/settings.json`. Existing sessions use the setting when a new Agent is built; an already running turn keeps its resolved limit.

### defaultProvider

Default provider name. Must match a key in `providers`.

```json
{ "defaultProvider": "deepseek-openai" }
```

### defaultModel

Default model ID. Must match an `id` in the chosen provider's `models` list.

```json
{ "defaultModel": "deepseek-v4-flash" }
```

### defaultMode

Default run mode:

| Value | Description |
|-------|-------------|
| `plan` | Read-only analysis mode — no file writes, sandboxed |
| `agent` | Standard read/write mode — Bash requires approval |
| `yolo` | Full access mode — all tools auto-execute |
| `os` | Shell-only mode — exposes Bash with YOLO-level approval behavior and no sandbox; high-risk protections still apply |

`router` is a valid session execution mode but not a valid `defaultMode`: it binds one or more external ACP workers per session, so enter it with `/router <id>[,<id>...]` (TUI) or `mothx --router --acp-agent <id>[,<id>...]`. If `defaultMode` is set to `router` anyway, it is treated as `plan` rather than failing: a default resolves before any worker is bound, and `plan` is the read-only projection of that intent, so the fallback never widens the tool surface to full access.

> **Status: beta (preview) mode.** Router is still an evaluation feature. Its tool surface, profile schema, and lifecycle may change in any release without a compatibility migration path, and it is deliberately excluded from `defaultMode`. Use it to try external ACP workers on a scratch session, and do not depend on it for unattended or production workflows.

```json
{ "defaultMode": "yolo" }
```

### defaultThinkingLevel

Default thinking level for reasoning models:

| Value | Description |
|-------|-------------|
| `off` | Disable thinking |
| `minimal` | Minimal thinking |
| `low` | Low level |
| `medium` | Medium level (default) |
| `high` | High level |
| `xhigh` | Highest level |
| `max` | Maximum level where the provider/model supports it (for example DeepSeek V4.1 `reasoning_effort`) |

```json
{ "defaultThinkingLevel": "medium" }
```

### enablePlanTool

Whether to register the built-in `plan` tool that allows the agent to create and track structured task plans.

```json
{ "enablePlanTool": true }
```

Set to `false` to disable it (e.g., if you prefer the agent not to use structured plans).

### enableArtifact / enableACPArtifact

Artifact publishing is opt-in and independently configured for terminal and ACP/Desktop sessions. Enabling one does not enable the other.

```json
{
  "enableArtifact": false,
  "enableACPArtifact": false
}
```

### maxContextTokens

Override the maximum context token count. When set to `0` (default), the value is derived from the model's `contextWindow`.

```json
{ "maxContextTokens": 200000 }
```

### contextFiles

Context file loading settings.

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `enabled` | bool | `true` | Whether to automatically load context files |
| `extraFiles` | []string | `[]` | Additional context file paths to load |

```json
{
  "contextFiles": {
    "enabled": true,
    "extraFiles": [
      "/path/to/extra-context.md",
      "~/.mothx/global-context.md"
    ]
  }
}
```

#### Auto-loaded Context Files

MothX automatically searches for and loads the following files:

1. **Global files** (in the global config directory):
   - `AGENTS.md`
   - `CLAUDE.md`

2. **Project files** (searched upward from current directory):
   - `AGENTS.md`
   - `CLAUDE.md`
   - `.mothx/AGENTS.md`
   - `.mothx/CLAUDE.md`
   - `.vibe/AGENTS.md` (legacy compatibility)
   - `.vibe/CLAUDE.md` (legacy compatibility)

---

### skillsDir

Path to the global skills directory. Supports `~` expansion.

| Platform | Default |
|----------|---------|
| Linux/macOS | `~/.mothx/skills` |
| Windows | `%APPDATA%\mothx\skills` |

```json
{ "skillsDir": "~/.mothx/skills" }
```

Skills are loaded from:
- **Global skills**: `<skillsDir>/<name>/SKILL.md`
- **Project skills**: `.skills/<name>/SKILL.md` (override global)

### skills

Disable specific skills by name without deleting their directories. Disabled skills are not loaded into the system prompt and cannot be activated for the session.

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `disabled` | string array | `[]` | Skill names to exclude |

```json
{
  "skills": {
    "disabled": ["legacy-release-checklist"]
  }
}
```

See [Skills System](skills.md) for directory precedence and activation commands.

### skillHub

Online skill marketplace settings used by `/skillhub` and the Desktop/WebUI skill browser. Built-in market definitions are used when `markets` is omitted.

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `defaultMarket` | string | `"yuandun"` | Market selected when opening the marketplace; falls back to the first enabled market |
| `defaultInstallScope` | string | `"project"` | Default install target: `project` or `global` |
| `officialHandles` | string array | built-in official handle | Marketplace handles treated as official publishers |
| `markets` | object array | built-in markets | Custom market definitions: `{ id, name, siteURL, apiURL, enabled, apiToken }`; 源盾 (`id: "yuandun"`) defaults to `https://yuandun.gitee.com` |

```json
{
  "skillHub": {
    "defaultMarket": "yuandun",
    "defaultInstallScope": "project",
    "markets": [
      { "id": "yuandun", "name": "源盾", "enabled": true, "apiURL": "https://yuandun.gitee.com" },
      { "id": "skillhub.cn", "name": "SkillHub.cn", "enabled": true },
      { "id": "clawhub.ai", "name": "ClawHub.ai", "enabled": true }
    ]
  }
}
```

See [Online Skill Marketplace](skillhub.md) for commands and market behavior.

---

### compaction

Context compaction (compression) configuration for managing long conversations. MothX automatically summarizes older messages when the estimated request reaches about 80% of the model context window.

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `enabled` | bool | `true` | Enable automatic context compaction |
| `reserveTokens` | int | `16384` | Compatibility setting also used to cap compaction summary output |
| `keepRecentTokens` | int | `20000` | Recent message tokens to keep uncompacted |
| `tokenizer` | string | `"auto"` | Token estimator selector. Currently `auto` and `generic` use the built-in chars/4 estimator |
| `tokenizerModel` | string | `""` | Optional model hint for future model-specific token estimators |
| `template` | string | `"default"` | Compression summary template: `default`, `code`, or `conversation` |

```json
{
  "compaction": {
    "enabled": true,
    "reserveTokens": 16384,
    "keepRecentTokens": 20000,
    "tokenizer": "auto",
    "template": "code"
  }
}
```

#### Compression Templates

- **`default`**: General structured checkpoint with goal, progress, decisions, next steps, and critical context.
- **`code`**: Coding-oriented checkpoint that emphasizes file paths, code changes, verification, and technical decisions.
- **`conversation`**: Concise discussion checkpoint for non-code conversations.

---

### sandbox

Sandbox configuration for secure command execution. Uses [bubblewrap (bwrap)](https://github.com/containers/bubblewrap) on Linux.

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `enabled` | bool | `false` | Enable sandboxed execution |
| `level` | string | `"none"` | Sandbox level: `"none"`, `"standard"`, `"strict"` |
| `bwrapPath` | string | `""` (auto) | Custom path to the `bwrap` binary |
| `allowNetwork` | bool | `false` | Allow network access inside sandbox |
| `allowedRead` | []string | *(platform-specific)* | Paths readable inside the sandbox |
| `allowedWrite` | []string | `[]` | Additional paths writable inside the sandbox |
| `deniedPaths` | []string | *(platform-specific)* | Paths explicitly denied inside the sandbox |
| `passEnv` | []string | *(platform-specific)* | Environment variables passed into the sandbox |
| `tmpSize` | string | `"100m"` | Size limit for the sandbox's `/tmp` tmpfs mount |

```json
{
  "sandbox": {
    "enabled": true,
    "level": "standard",
    "bwrapPath": "/usr/bin/bwrap",
    "allowNetwork": false,
    "allowedRead": ["/usr", "/lib", "/lib64", "/bin", "/sbin", "/etc/ssl"],
    "allowedWrite": ["/tmp/my-build"],
    "deniedPaths": ["/etc/shadow", "/root"],
    "passEnv": ["PATH", "HOME", "USER", "LANG", "TERM", "SHELL", "GOPATH"],
    "tmpSize": "200m"
  }
}
```

#### Sandbox Levels

| Level | File System | Network | Use Case |
|-------|------------|---------|----------|
| `none` | Full access | ✓ | No sandboxing (YOLO mode default) |
| `standard` | Project read-write | ✗ | Everyday development (Agent mode) |
| `strict` | Project read-only | ✗ | Code review / analysis (Plan mode) |

#### Platform Defaults for allowedRead

**Linux:**
```json
["/usr", "/lib", "/lib64", "/bin", "/sbin", "/etc/ld.so.cache", "/etc/ssl", "/etc/ca-certificates", "/dev/null", "/dev/urandom", "/dev/zero", "/proc/self", "/proc/meminfo", "/proc/cpuinfo"]
```

**macOS:**
```json
["/usr", "/lib", "/bin", "/sbin", "/System", "/Library"]
```

**Windows:**
```json
["C:\\Windows", "C:\\Program Files", "C:\\Program Files (x86)"]
```

#### Platform Defaults for deniedPaths

**Linux / macOS:**
```json
["/etc/shadow", "/etc/gshadow", "/etc/passwd", "/root", "/home"]
```

**Windows:**
```json
["C:\\Users\\<Username>\\Documents", "C:\\Users\\<Username>\\Desktop"]
```

#### Platform Defaults for passEnv

**All platforms:** `PATH`, `HOME`, `USER`, `LANG`, `LC_ALL`, `TERM`

**Linux additionally:** `SHELL`, `GOPATH`, `GOROOT`, `GOPROXY`, `GOMODCACHE`, `NODE_PATH`

**macOS additionally:** `SHELL`, `TMPDIR`

**Windows additionally:** `APPDATA`, `LOCALAPPDATA`, `COMPUTERNAME`, `USERPROFILE`, `SYSTEMROOT`

---

### sessionDir

Directory for SQLite session storage. Supports `~` expansion.

MothX stores all session metadata and entries in a single, unified `sessions.db` database file under `sessionDir` (using virtual handles for CLI/TUI, and creating physical handles as needed for Channels). See [Session Management](sessions.md) for the layout.

| Platform | Default |
|----------|---------|
| Linux/macOS | `~/.mothx/sessions` |
| Windows | `%APPDATA%\mothx\sessions` |

```json
{ "sessionDir": "~/.mothx/sessions" }
```

---

### shellPath

Custom shell path for the Bash tool. When empty (default), MothX uses the platform default:

| Platform | Default |
|----------|---------|
| Linux | `$SHELL` or `/bin/bash` |
| macOS | `$SHELL` or `/bin/zsh` |
| Windows | `powershell.exe` or `cmd.exe` |

```json
{ "shellPath": "/usr/bin/fish" }
```

### shellCommandPrefix

A string prepended to every shell command before execution. Useful for setting up environment or activating virtualenvs.

```json
{ "shellCommandPrefix": "source ~/.venv/bin/activate && " }
```

When empty (default), commands are executed directly.

---

### theme

UI color theme for the terminal interface.

| Value | Description |
|-------|-------------|
| `"dark"` | Dark background theme (default) |
| `"light"` | Light background theme |

```json
{ "theme": "dark" }
```

---

### retry

API call retry configuration with exponential backoff. Retries apply to transient initial HTTP failures and early SSE read failures before any visible output has been emitted. Once text, thinking, tool calls, or usage have streamed to the client, stream read failures are not retried to avoid duplicate output.

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `enabled` | bool | `true` | Enable automatic retries on transient API errors |
| `maxRetries` | int | `5` | Maximum number of retry attempts |
| `baseDelayMs` | int | `3000` | Base delay in milliseconds (doubles on each retry) |

```json
{
  "retry": {
    "enabled": true,
    "maxRetries": 5,
    "baseDelayMs": 3000
  }
}
```

#### Retryable Errors

The following errors trigger automatic retries:

| Category | Examples |
|----------|----------|
| Rate limiting | HTTP 429 |
| Server errors | HTTP 502, 503, 504 |
| Network errors | connection refused, connection reset, DNS errors, HTTP/2 `INTERNAL_ERROR` stream resets |
| Timeouts | HTTP client timeout, TCP timeout |

The following are **not** retried:
- Context cancellation (user pressed Ctrl+C)
- HTTP 4xx client errors (except 429): 400, 401, 403, 404
- Stream read failures after visible output has already been emitted

#### Backoff Strategy

Each retry waits `baseDelayMs × 2^attempt` milliseconds, capped at 30 seconds:

| Attempt | Delay (base=2000ms) |
|---------|--------------------|
| 1st | 2s |
| 2nd | 4s |
| 3rd | 8s |

When a retry occurs, MothX displays a status message in the TUI:
```
Retrying (1/3): request timed out — waiting 2.0s...
Retrying (2/3): rate limited (HTTP 429) — waiting 4.0s...
```

#### Disabling Retries

```json
{
  "retry": {
    "enabled": false
  }
}
```

---

### approval

Agent mode approval configuration. Controls which Bash commands auto-execute and which require user confirmation.

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `bashWhitelist` | []string | *(see below)* | Command prefixes that auto-approve in agent mode |
| `bashBlacklist` | []string | `[]` | Command prefixes that **always** require approval |
| `confirmBeforeWrite` | bool | `true` | Require user approval before `Write`/`Edit` tools run in agent mode |

#### Default Whitelist

```json
["go ", "make ", "git ", "npm ", "yarn ", "node ", "python ", "pip "]
```

#### Approval Flow

```
Agent requests tool execution
│
▼
Check mode
├─ Plan mode → Deny (read-only)
├─ Agent mode → Continue checking
└─ YOLO mode → Auto-approve unless blacklisted
│
▼
Blacklist check (highest priority):
├─ Command matches blacklist → Require user approval
└─ Otherwise continue
│
▼
In Agent mode:
├─ Project allow.json matches → Auto-approve (see below)
├─ Command matches settings whitelist → Auto-approve
├─ Write/Edit tool + confirmBeforeWrite=true → Require user approval
├─ Non-Bash tool → Auto-approve
└─ Otherwise → Require user approval
│
▼
In --print mode:
  Commands that would need approval → Fail immediately
```

#### Example Configurations

**Only allow git and npm:**
```json
{
  "approval": {
    "bashWhitelist": ["git ", "npm "]
  }
}
```

**Custom blacklist:**
```json
{
  "approval": {
    "bashWhitelist": ["go ", "make ", "git "],
    "bashBlacklist": ["rm -rf", "sudo", "dd "]
  }
}
```

**Disable write confirmation (trust the agent):**
```json
{
  "approval": {
    "confirmBeforeWrite": false
  }
}
```

### worktree

Isolated git worktrees managed by the shared Runtime (`agentruntime.WorktreeManager`). Worktrees live under `<data-dir>/worktrees` by default and are registered in the sessions database, so TUI/CLI, ACP/Desktop, and sub-agents share the same registry.

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `enabled` | bool | `true` | Allow creating new worktrees; `false` keeps `list`, `remove`, and `reset` available |
| `branchPrefix` | string | `"mothx"` | Branch name prefix for created worktrees |
| `startCommand` | string | `""` | Default command stored for a worktree and run after create/reset |
| `perChildSubagents` | bool | `false` | Run every sub-agent in its own isolated worktree |
| `esm` | bool | `false` | ESM worker/critic/audit roles share one worktree per objective |

An external ACP worker honors the worktree resolved by `AgentManager` (an
explicit child worktree or `perChildSubagents`) instead of falling back to the
session directory. Its `fs/*` and `terminal/*` bridges are rooted in that
worktree, and terminal completion records a bounded change-set snapshot
(base/head revision, changed paths, patch, untracked content, digest) with the
durable child history. The Router lead applies a selected snapshot through
`subagent_integrate`, which uses one Runtime-owned exclusive base-workspace
lane; it never copies the mutable child worktree. A git apply conflict is
returned as evidence, and an already-applied snapshot digest is idempotent.

```json
{
  "worktree": {
    "enabled": true,
    "branchPrefix": "mothx",
    "perChildSubagents": false
  }
}
```

Create, list, reset, and remove worktrees with [`mothx worktree`](cli-reference.md#worktree---isolated-git-worktrees), or the equivalent ACP/Desktop controls.

### acpAgents

`acpAgents` is the global allowlist of external ACP coding agents MothX may use as Router workers. MothX never auto-discovers agents and never accepts a command or endpoint from a model tool call. A local profile's `command[0]` may be an absolute path or a bare command resolved through `PATH` at launch, and launch never runs a shell string. A remote profile selects one administrator-configured `url`.

> **Status: beta (preview) mode.** Router is still an evaluation feature, and so are the `acpAgents` profiles that feed it: the fields below may change in any release without a compatibility migration path. Configure a profile to evaluate an external worker, not as a production integration contract.

```json
{
  "acpAgents": [
    {
      "id": "codex",
      "title": "Codex ACP",
      "model": "gpt-5-codex",
      "transport": "stdio",
      "command": ["codex-acp"],
      "enabled": true,
      "environment": ["OPENAI_API_KEY"],
      "terminal": false,
      "maxConcurrentChildren": 1,
      "permissionPolicy": "auto_allow_once",
      "driver": "generic-acp",
      "mcpBridge": "auto",
      "capabilityOverrides": {"promptAudio": false}
    }
  ]
}
```

- `id` is the only value exposed to the model. `command` is an argv array; `command[0]` may be an absolute path or a bare command resolved through `PATH` at launch (launch never goes through a shell).
- `model` is the external Agent's own model ID, not a MothX provider/model selection. Runtime applies it when it creates the worker session, using the standard ACP `configOptions` model option (`category: "model"`). If the worker advertises only the deprecated `models`/`session/set_model` wire, Runtime falls back to it. Leave `model` empty (or omit it) to keep the third-party Agent's default behavior. A configured model must be one the worker offers; otherwise delegation fails with the available choices instead of silently running a different model. On `session/resume`, an Agent that returns no option catalog keeps the model already stored in its remote session.
- `transport` is `stdio` (default) for a local ACP process, or `websocket` / `http` for the ACP remote transport. Remote profiles require `url` and must not set `command` or `environment`; the URL must use `ws://`/`wss://` or `http://`/`https://` accordingly and must not embed credentials. MothX supports cookie-based session affinity, HTTP/2 (required for `https://` endpoints), and the connection/session-scoped SSE streams from the ACP RFD. No endpoint authentication flow is implemented. An `http://` endpoint is intended only for trusted local development.
- `environment` lists variable **names**; values are read from `env.json` or the process environment at launch and are never shown to the model or written to events.
- `role` and `write_scope` belong to each delegation, not the profile. The model may supply `role` as an optional semantic hint (default: `investigate`) and `write_scope` as optional task metadata used by the prompt, audit, and overlap checks. Neither is a filesystem sandbox: an external ACP Agent runs its own tools, so MothX cannot confine its writes to a declared directory. Use a Runtime-managed per-child worktree plus `delegate_worker_mgr(action=integrate)` when isolated write work matters.
- `roles` and `writeRoots` are deprecated settings-compatibility fields. Older `settings.json` files containing them still load, but the values are ignored and are no longer exposed by the TUI, Runtime catalog, WebUI, or Desktop. They no longer authorize or restrict a role.
- `terminal` (default `false`) opts the profile into the client-owned ACP terminal bridge. When enabled, the remote Agent may ask MothX to run an argv command; MothX runs it through the shared workspace sandbox and process-group containment with a bounded output buffer. Terminal authentication and URL authentication are not implemented. Enable this only for an Agent executable you already trust to choose commands.
- `maxConcurrentChildren` is `1` by default and bounded at `8`. Read-only Router workers may use this ceiling concurrently; the Runtime reuses one initialized ACP connection for multiple isolated remote sessions in the same profile/workdir. A Registry-backed connection advertises `fs.writeTextFile` as part of its capability union even when the first task is read-only, while each session's handler still requires a write-role task with a non-empty `write_scope`. An `implement` worker that runs in a Runtime-managed per-child worktree may coexist with readers because it cannot write the base workspace. A base-workspace writer (including `delegate_worker_mgr(action=integrate)`) is exclusive in both directions, so the Runtime rejects it while any other external worker is live and rejects new readers while it is active. Use `delegate_worker_mgr(action=wait, handle: ...)` for each read-only fan-out result.
- `allowParallelBaseWorkspaceWrites` is `false` by default and relaxes that last exclusivity for write-role workers that target the session workspace instead of a managed per-child worktree. It is explicit executable trust, not a performance default: an external ACP Agent runs its own tools, so MothX cannot confine its writes to the declared `write_scope`, and two workers can still touch the same file. Enable it only when the tasks partition the workspace by module, and set `maxConcurrentChildren` above one, because the ceiling still applies. The Runtime still refuses a parallel writer whose declared `write_scope` overlaps a live base writer, since that overlap is statically visible. `mothx doctor` reports the opt-in, and the `/router` panel exposes it as "Parallel workspace writes". Per-child worktrees plus `subagent_integrate` remain the safer default.
- `permissionPolicy` is `auto_allow_once` or `auto_reject` for Router; `interactive` profiles cannot be activated as Router workers. MothX only selects a one-time option the remote Agent actually offered and never auto-selects `allow_always`/`reject_always`.
- `driver` selects the ACP flavor (default `generic-acp`). A flavor may describe verified protocol quirks (permission option shape, update normalization, config-option naming) but must never grant authorization, sandbox policy, concurrency, or a capability the Agent did not advertise. Unknown values fall back to `generic-acp`, so adding a new flavor does not require a settings migration. Real interop on 2026-11-10 (OpenCode 2.0.16 and codex-acp 0.16.0) showed `generic-acp` already describes both agents and their loopback MCP bridge handshake; no flavor is required.
- `mcpBridge` is `auto` (default) or `off`. `auto` injects the Runtime's loopback HTTP worker bridge (`worker_mgr(context|report|ask)`) into a local stdio worker's `session/new|load|resume`; `off` disables injection. Any other value is rejected by profile validation, and empty/whitespace still means `auto`. Remote profiles and containers that cannot reach host loopback project `mcpBridge=unreachable` and run without the bridge. Bridge failure never blocks a task.
- `capabilityOverrides` can only tighten the resolved capability set: every value must be `false` and keys must be canonical capability names (`sessionResume`, `sessionLoad`, `sessionClose`, `sessionFork`, `additionalDirectories`, `promptImage`, `promptAudio`, `promptEmbeddedContext`, `mcpHttp`, `mcpSse`, `mcpStdio`, `fsReadText`, `fsWriteText`, `terminal`, `modelConfigOption`, `thoughtStream`, `nativeSubagents`). A `true` value is rejected because it would widen authority. Resolved capabilities and every degradation are stored on `session_child_runs` and shown in child metadata.

Edit `acpAgents` either in `settings.json` or from the TUI `/router` panel, which lists profiles with their Runtime-resolved eligibility and can add, edit, delete, and activate one. The WebUI Settings → Router Worker page (`PATCH /api/acp/profiles`) and Desktop Settings → Router Workers (`mothx/manage/acp/profiles/patch`) expose the narrower behavior-metadata edit (`model`, `driver`, `mcpBridge`, `capabilityOverrides`); they never accept argv, URLs, environment names, or trust flags. An empty `model` patch resets the profile to the worker's default. The panel writes only through the shared configuration owner, so an invalid candidate set (empty `command[0]` for stdio, missing/mismatched remote `url`, duplicate ID, inline secret value) is rejected before anything is stored. Activate Router with `t` in the panel, `/router <id>[,<id>...]` in the TUI, the Router button in the WebUI or Desktop composer, or `mothx --router --acp-agent <id>[,<id>...]`. The first profile is the default target and the ordered list is the session-bound allowlist; Runtime validates every profile and records the matching non-blocking strategy per profile. Activation requires an idle session whose source is not forced to yolo, and persists the selection plus Router mode through the normal session replay entries. The TUI/CLI never read profile argv or start the worker themselves.

**Trust boundary:** choosing a local profile means trusting that executable with the session working directory, the environment variables you allowlisted, and any network access it chooses. Choosing a remote profile means trusting that endpoint with the task, declared workspace roots, and any content MothX sends through the negotiated filesystem or terminal bridges. Router's read-only tool list constrains MothX's own lead, not the external Agent. Run `mothx doctor` to validate profile shape, driver/bridge/override fields, loopback `tcp4` bindability, and local executable availability without launching or connecting to anything.

### maintenance

Runtime-owned background housekeeping. These are not user automation tasks: MothX schedules them through the shared cron lifecycle, and they stay out of the cron views in the Web UI and Desktop, the `/api/cron` management surface, and the `cron` tool.

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `reclaimAttachmentStorage` | bool | `true` | Reclaim attachment storage that no durable row references any more |
| `storageReconcileSchedule` | string | `@daily` | Cadence of that reconciliation (`@daily`, `@every 12h`, or a 5-field cron expression) |
| `reclaimSessionStorage` | bool | `true` | Run session-storage maintenance. It never deletes transcript messages |
| `sessionStorageSchedule` | string | `@daily` | Cadence of session-storage maintenance (`@daily`, `@every 12h`, or a 5-field cron expression) |
| `toolExecutionRetentionDays` | int | `0` | Keep completed/abandoned tool-execution idempotency records for this many days; `0` keeps them forever |
| `vacuumSessionStorage` | bool | `false` | Run `VACUUM` after pruning to release free pages |

```json
{
  "maintenance": {
    "reclaimAttachmentStorage": false,
    "toolExecutionRetentionDays": 90,
    "vacuumSessionStorage": true
  }
}
```

Reclamation removes only directories under the session directory's `artifacts/` store that (a) no `session_attachments` row references **and** (b) were last written before the attachment retention window plus a 24-hour grace period (8 days by default with the 7-day retention). It fails closed when the sessions database cannot be read, never follows symbolic links, and ignores anything not shaped like its own generated attachment identifiers, so unrelated data is never interpreted as reclaimable storage. That floor is also what keeps reclamation from destroying anything a restored `mothx pure` archive could still serve. See [`mothx pure`](cli-reference.md#pure---archive-the-sessions-database).

An invalid `storageReconcileSchedule` falls back to the default with a `[cron]` log line, and changing the cadence updates only the scheduled job's schedule - run counters and status are preserved. Turning reclamation off removes the scheduled job at the next scheduler start, and a stale job row that still fires is refused instead of deleting anything.

Session-storage maintenance preserves every transcript message forever: it never deletes `entries`, `sub_entries`, compaction entries, content overrides, or EventStore content. It may prune only `completed`/`abandoned` `tool_execution_records` older than `toolExecutionRetentionDays` (default `0` keeps every record); `running`, `interrupted`, and `retry_requested` records are always kept so an uncertain tool side effect stays fenced. Every pass runs `PRAGMA optimize` and backfills the derived session-content search index for up to 512 not-yet-indexed sessions (newest first); unreadable stores are skipped and retried on the next run. `vacuumSessionStorage` additionally rewrites the database file to release free pages; it is off by default because `VACUUM` holds the SQLite writer for the duration of the rewrite.

### Project-Level Allow Rules (`allow.json`)

In addition to the global `settings.json` approval configuration, MothX supports project-level allow rules in `allow.json` (`.mothx/allow.json`). These rules enable auto-approval of specific bash commands **per project** without modifying global settings.

| File | Scope | Priority |
|------|-------|----------|
| `.mothx/allow.json` | Current project | High |
| `~/.mothx/allow.json` | Global fallback | Low |

#### Fields

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `autoEdit` | bool | `true` | Auto-approve `write`/`edit` tools in agent mode. When no `allow.json` exists, defaults to `true`. A file with `"autoEdit": false` explicitly disables it. |
| `editPaths` | []string | `[]` | Glob patterns for paths whose `write`/`edit` auto-approve in agent mode. Supports `**` (cross-directory) and `*` (single segment). Project-level only. |
| `bashCommands` | []string | `[]` | Exact bash command strings that auto-approve in agent mode. Project-level only. |
| `bashPrefixes` | []string | `[]` | Bash command prefixes that auto-approve in agent mode. Trailing spaces are significant (e.g. `"go test "` matches `go test ./...`). Project-level only. |

#### Interaction with Settings

- **Blacklist overrides allow rules**: A command matching `bashBlacklist` in `settings.json` will always require approval, even if it matches a project-level `bashCommands` or `bashPrefixes` entry.
- **`autoEdit` inheritance**: Global `autoEdit` is inherited unless the project file explicitly sets it. Writing a project `allow.json` without `autoEdit` will **not** persist the inherited global value.

#### Example `.mothx/allow.json`

```json
{
  "autoEdit": true,
  "editPaths": ["docs/**", "*.md"],
  "bashCommands": ["make test", "make build"],
  "bashPrefixes": ["go test ", "go vet "]
}
```

#### Managing from the TUI

- The approval dialog offers **"Always Allow Exact Command"** and **"Always Allow Command Prefix"** options when a bash command is pending. Selecting one persists the rule to `.mothx/allow.json`.
- Use `/alloweditpath add <glob>` to manage `editPaths`.
- Use `/allowautoedit [on|off]` to toggle `autoEdit`.

---

## MCP Configuration

MCP servers are configured in standalone `mcp.json` files, not in `settings.json`.

MothX loads MCP configuration at startup from:

1. Global config: `~/.mothx/mcp.json` on Linux/macOS, or `%APPDATA%\mothx\mcp.json` on Windows
2. Project config: `.mothx/mcp.json`

Serve's Web UI provides an MCP editor in **Settings → MCP** for the global file, plus a project-level editor from the active session's chat toolbar. Saved MCP servers are applied to newly created sessions; existing sessions keep their registered tools until recreated.

Manage global or project MCP servers from the TUI:

```text
/mcpmgr project
/mcpmgr global
```

The panel supports adding, editing, deleting, enabling, disabling, and reloading
the scoped `mcp.json`. Press `a` to choose the transport first, then configure
name, endpoint/command, arguments, environment, headers, and enabled state one
field at a time. Enter or `e` edits the selected server, Space enables or
disables it, and `d` then `y` deletes it.
Saving reconnects the affected servers in place, so the current session picks
up the new MCP tool set without restarting the client. A run that is already in
flight keeps the tool set it froze at build time; the change applies to the
next run.

Example:

```json
{
  "mcpServers": [
    {
      "name": "local-tools",
      "type": "stdio",
      "command": "mcp-server",
      "args": ["--port", "8080"],
      "env": [
        {"name": "API_KEY", "value": "sk-..."}
      ]
    },
    {
      "name": "remote-tools",
      "type": "http",
      "url": "https://mcp.example.com",
      "headers": [
        {"name": "Authorization", "value": "Bearer token"}
      ]
    }
  ]
}
```

Supported transports:

- `stdio`: `command` may be an executable name resolved through `PATH`, or a direct path; put arguments in `args`
- `http`: MCP Streamable HTTP endpoint via `url` (the preferred remote transport)
- `sse`: legacy SSE stream via `url` plus `messageUrl`

MCP tools are registered after built-in tools and `skill_ref`, but before the agent is created. The agent freezes its system prompt and tool definitions for the session, so changes to `mcp.json` require restarting the client or creating a new Serve session.

Tool names use `mcp_<server_name>_<tool_name>`. If a name already exists, MothX appends a numeric suffix instead of replacing an existing tool. Starter-template placeholders such as `/absolute/path/to/mcp-server`, `example.com`, and `replace-me` are ignored during automatic startup loading.

---

## Authentication Configuration

MothX supports multiple ways to provide API keys, with flexible resolution logic.

### Key Resolution Order

When MothX needs the API key for a provider, it checks in this order:

1. **Provider `apiKey` field** in `settings.json` — if set, resolved using the rules below
2. **Derived environment variable** — provider name is converted to an env var: e.g., `deepseek-openai` → `DEEPSEEK_OPENAI_API_KEY`

### apiKey Field Formats

The `apiKey` field in a provider config supports three formats:

| Format | Example | Behavior |
|--------|---------|----------|
| `${VAR}` | `"${DEEPSEEK_API_KEY}"` | Reads the value of environment variable `VAR` |
| `!command` | `"!pass show deepseek-key"` | Executes a shell command and uses its stdout only when `VIBECODING_ALLOW_SHELL_CONFIG=1` |
| Plain string | `"sk-abc123..."` | Used as-is (⚠️ not recommended for shared configs) |

#### Environment Variable Reference

```json
{
  "providers": {
    "deepseek-openai": {
      "apiKey": "${DEEPSEEK_API_KEY}"
    }
  }
}
```

Then set the environment variable:

```bash
export DEEPSEEK_API_KEY=sk-...
```

#### Shell Command (Password Manager Integration)

Prefix with `!` to run a shell command. MothX uses `sh -c` on Linux/macOS and `powershell.exe` on Windows.

Shell command resolution is disabled by default. To enable it for trusted local configuration, set:

```bash
export VIBECODING_ALLOW_SHELL_CONFIG=1
```

```json
{
  "providers": {
    "anthropic": {
      "apiKey": "!pass show api/anthropic"
    },
    "openai": {
      "apiKey": "!security find-generic-password -s openai-api -w"
    }
  }
}
```

This is useful for integrating with password managers like `pass`, `1password-cli`, macOS Keychain, or any other secret store.

#### Derived Environment Variable Fallback

If no `apiKey` is configured for a provider, MothX derives an environment variable name from the provider name:

| Provider Name | Derived Env Var |
|---------------|-----------------|
| `deepseek-openai` | `DEEPSEEK_OPENAI_API_KEY` |
| `deepseek-anthropic` | `DEEPSEEK_ANTHROPIC_API_KEY` |
| `my-custom-provider` | `MY_CUSTOM_PROVIDER_API_KEY` |
| `anthropic` | `ANTHROPIC_API_KEY` |
| `openai` | `OPENAI_API_KEY` |

The rule: replace `-` with `_`, uppercase everything, append `_API_KEY`.

### Authentication Examples

**Option 1: Environment Variables (simplest)**

```bash
export DEEPSEEK_API_KEY=sk-...
```

With default config, MothX will look for `DEEPSEEK_OPENAI_API_KEY` for the `deepseek-openai` provider. But if the provider's `apiKey` is set to `${DEEPSEEK_API_KEY}`, it reads that env var instead.

**Option 2: Inline in Configuration File**

```json
{
  "providers": {
    "deepseek-openai": {
      "apiKey": "sk-..."
    }
  }
}
```

**Option 3: Password Manager**

```json
{
  "providers": {
    "deepseek-openai": {
      "apiKey": "!pass show deepseek"
    }
  }
}
```

---

## Invalid Settings Recovery

When a global or project-level `settings.json` cannot be parsed during startup, MothX attempts to rename it to a timestamped backup in the same directory, for example:

```text
settings.json.bak_20260715-143000
```

If that name already exists, MothX appends a numeric suffix such as `_1`. The warning printed to stderr includes the platform-native absolute backup path.

After a successful backup, an invalid global file is replaced by built-in defaults for the current run, while an invalid project file is ignored and the valid global settings remain active. The default global `settings.json` is recreated on the next startup. If the backup cannot be created—for example because the directory is read-only—configuration loading returns an error.

---

## Environment Variable Overrides

These environment variables override settings at runtime:

| Environment Variable | Overrides | Example |
|---------------------|-----------|---------|
| `MOTHX_DIR` | Global configuration directory | `export MOTHX_DIR=/custom/config` |
| `VIBECODING_PROVIDER` | `defaultProvider` | `export VIBECODING_PROVIDER=anthropic` |
| `VIBECODING_MODEL` | `defaultModel` | `export VIBECODING_MODEL=claude-sonnet-4-20250514` |
| `VIBECODING_MODE` | `defaultMode` | `export VIBECODING_MODE=yolo` |
| `VIBECODING_THINKING` | `defaultThinkingLevel` | `export VIBECODING_THINKING=high` |
| `VIBECODING_DEBUG` | Enable provider-level request/response debug output | `export VIBECODING_DEBUG=1` |
| `VIBECODING_PPROF_ADDR` | pprof listen address when `--debug` is set | `export VIBECODING_PPROF_ADDR=127.0.0.1:6061` |
| `MOTHX_SQLITE_SYNCHRONOUS` | Session-database SQLite durability: defaults to `NORMAL` (the WAL-recommended pairing, no per-commit fsync); set to `FULL` to restore per-commit fsync | `export MOTHX_SQLITE_SYNCHRONOUS=FULL` |
| `MOTHX_SQLITE_QUICK_CHECK` | Startup SQLite integrity check: enabled by default; set to `off` to skip it for very large databases. `mothx doctor` still performs an on-demand read-only check | `export MOTHX_SQLITE_QUICK_CHECK=off` |
| `VIBECODING_NO_UPDATE_CHECK` | Disable update check | `export VIBECODING_NO_UPDATE_CHECK=1` |
| `VIBECODING_NPM_REGISTRY` | Override npm registry for update checks | `export VIBECODING_NPM_REGISTRY=https://registry.npmjs.org` |

---

## Configuration Examples

### Minimal Configuration

Only need to set the default provider and model. Everything else uses sensible defaults.

```json
{
  "defaultProvider": "deepseek-openai",
  "defaultModel": "deepseek-v4-flash"
}
```

### Multi-Provider Configuration

Switch between providers at runtime using `/provider` or `--provider`:

```json
{
  "providers": {
    "deepseek-anthropic": {
      "vendor": "deepseek",
      "baseUrl": "https://api.deepseek.com/anthropic",
      "apiKey": "${DEEPSEEK_API_KEY}",
      "api": "anthropic-messages"
    },
    "deepseek-openai": {
      "vendor": "deepseek",
      "baseUrl": "https://api.deepseek.com",
      "apiKey": "${DEEPSEEK_API_KEY}",
      "api": "openai-chat"
    },
    "anthropic": {
      "vendor": "anthropic",
      "baseUrl": "https://api.anthropic.com",
      "apiKey": "${ANTHROPIC_API_KEY}",
      "api": "anthropic-messages",
      "cacheControl": true,
      "models": [
        {
          "id": "claude-sonnet-4-20250514",
          "name": "Claude Sonnet 4",
          "contextWindow": 200000,
          "maxTokens": 8192,
          "cost": { "input": 3, "output": 15, "cacheRead": 0.3, "cacheWrite": 3.75 }
        }
      ]
    }
  },
  "defaultProvider": "deepseek-openai",
  "defaultModel": "deepseek-v4-flash"
}
```

### Custom API Endpoint / HTTP Proxy / Headers

`baseUrl` points to an API endpoint or API gateway. `httpProxy` configures the network proxy used only by that provider's HTTP client. When `httpProxy` is empty, the provider keeps Go's default `HTTP_PROXY` / `HTTPS_PROXY` environment behavior. Set `forceHTTP11` to `true` when a proxy or gateway has unstable HTTP/2 streaming behavior.

Use `headers` to attach custom HTTP headers to every request for a provider. Header values support the same resolution rules as `apiKey`, including `${ENV_VAR}` and opt-in `!cmd` shell commands. Custom headers are applied after MothX's default provider headers, so they can also override defaults such as `Authorization`, `x-api-key`, or gateway-specific headers when needed.

```json
{
  "providers": {
    "my-proxy": {
      "baseUrl": "https://my-proxy.example.com/v1",
      "api": "openai-chat",
      "apiKey": "${MY_PROXY_API_KEY}",
      "httpProxy": "http://127.0.0.1:7890",
      "forceHTTP11": true,
      "headers": {
        "X-Gateway-Token": "${MY_GATEWAY_TOKEN}",
        "X-Request-Source": "mothx"
      },
      "models": [
        {
          "id": "gpt-4o",
          "name": "GPT-4o (via proxy)",
          "contextWindow": 128000,
          "maxTokens": 16384
        }
      ]
    }
  },
  "defaultProvider": "my-proxy",
  "defaultModel": "gpt-4o"
}
```

### Enable Sandbox with Custom Paths

```json
{
  "sandbox": {
    "enabled": true,
    "level": "standard",
    "allowNetwork": false,
    "allowedRead": ["/usr", "/lib", "/lib64", "/bin", "/sbin", "/etc/ssl", "/opt/go"],
    "passEnv": ["PATH", "HOME", "USER", "LANG", "TERM", "SHELL", "GOPATH", "GOROOT"],
    "tmpSize": "200m"
  }
}
```

### Use the Code Compaction Template

```json
{
  "compaction": {
    "enabled": true,
    "reserveTokens": 16384,
    "keepRecentTokens": 20000,
    "tokenizer": "auto",
    "template": "code"
  }
}
```

### Project-Level Override

Place in `.mothx/settings.json` to override specific settings for a project:

```json
{
  "defaultMode": "yolo",
  "defaultThinkingLevel": "high",
  "shellCommandPrefix": "source .venv/bin/activate && ",
  "approval": {
    "bashWhitelist": ["python ", "pytest ", "pip ", "make "],
    "confirmBeforeWrite": false
  }
}
```

This merges with your global settings — only the fields you specify are overridden.

---

## MothX Desktop

Source: https://mothx.net/en/desktop.md

# MothX Desktop

> **Deprecated.** MothX Native is now the primary desktop client
> ([Native guide](native.md)). Desktop (Electron) no longer publishes release
> artifacts automatically; only manual compatibility builds remain during the
> migration window, and this codebase is frozen except for security fixes.
> Sessions and configuration are shared Runtime state, so moving to Native
> requires no data migration — see [Migrating from Desktop](native.md#migrating-from-desktop).
> Removal condition: `desktop/` and its build/release entry points are deleted
> once a full release cycle ships no Desktop assets and no manual compatibility
> build was needed.

MothX Desktop is the graphical MothX client. It is a **pure ACP (Agent Client
Protocol) client**: the Electron main process launches the bundled `mothx acp`
runtime over stdio and speaks newline-delimited JSON-RPC. It does not start
`mothx serve`, does not embed the Svelte Web UI, and does not expose an HTTP or
token tunnel.

## What it is

- **One ACP client.** `desktop/main/acp-client.ts` owns request correlation,
  notifications, reverse approval/question requests, restart/backoff, and
  lifecycle. The renderer only talks to `window.mothx` through the preload IPC
  bridge.
- **A separate frontend.** The renderer is React 19 + shadcn/ui + Tailwind CSS
  under `desktop/renderer/`; it is not the Svelte Web UI in `ui/`.
- **A thin projection.** Sessions, runs, messages, tools, approvals, questions,
  attachments, artifacts, Expert Teams, knowledge bases, worktrees, providers,
  MCP configuration, and schedules are canonical ACP/Runtime state. Desktop only
  renders and manages that state through ACP methods.
- **Local presentation state only.** Theme, language, and new-session directory
  history live in `desktop-store.json`. The runtime binary choice (bundled vs. a
  user-picked path) is client-shell launch state in the Electron main process,
  not a workspace or security boundary.

## Features

- Chat with streaming text, reasoning, tool cards, diffs, plan cards, and
  usage/cache projections.
- Approval and question dialogs backed by the shared Runtime decision model.
- Session list, history paging, fork, resume, rename/metadata, project grouping,
  pinning, and delete.
- Attachments and generated artifacts, including artifact cards and preview.
- Expert Teams: bind an expert or team for a session; switching an existing
  expert forks the session.
- Knowledge bases: create, scan, inspect runs/sources, query, schedule, and
  clear the index.
- Isolated git worktrees shared with the CLI and Runtime.
- Provider/model, mode, thinking, sandbox, browser, and web-search settings.
- Skills and the online Skill Hub, MCP servers, memory, cron automation, and
  usage statistics.
- Sub-agent status and read-only child transcript panels.

Optional controls are gated by the feature keys advertised in
`initialize._meta["mothx.dev"].features`. If a key is absent, the matching panel
or action is unavailable rather than silently emulated.

## Build and run

From the repository root:

```bash
make desktop-vendor    # npm ci + build/vendor the platform runtime
make desktop-build     # bundle main/preload and renderer into desktop/dist
make desktop-dev       # renderer watch + Electron + DevTools/CDP
```

From `desktop/`:

```bash
npm run build          # build main/preload/renderer
npm run typecheck      # TypeScript boundary check
npm test               # main/preload/renderer and protocol tests
npm run e2e            # optional Electron ACP smoke test
npm start              # version:set + ensure:electron + build + launch
```

`make desktop-dev` prepares the runtime first and uses `desktop/.dev-user-data/`
so a development instance does not fight an installed app for the single-instance
lock. Linux requires a working display server; use a real desktop session,
`ssh -X`, or Xvfb. Without `DISPLAY`, Electron exits during Chromium startup.

Development packages:

```bash
make desktop-dist-dev-linux
make desktop-dist-dev-mac
make desktop-dist-dev-win
```

The packaged app vendors a source-built `mothx` runtime. The Electron main
process resolves it in this order: `MOTHX_BINARY` (development override) → the
custom binary selected in Desktop settings → the bundled vendor directory → the
repository `bin/` directory. A missing custom binary falls back to the bundled
one.

## Runtime and protocol

Desktop uses the same ACP v1 surface documented in [ACP Protocol](acp.md), plus
`mothx.dev` extensions. The main process starts one shared ACP child process and
routes multiple sessions through it. It never reads `settings.json`, the
sessions database, or Serve configuration directly; management operations use
`mothx/manage/*` and are capability-gated.

Typical method groups:

- Lifecycle: `initialize`, `mothx/doctor`
- Sessions: `session/new`, `session/load`, `session/resume`, `session/fork`,
  `session/list`, `session/close`, `session/delete`
- Runs: `session/prompt`, `session/cancel`, `$/cancel_request`
- Configuration: `session/set_config_option`, `session/set_mode`
- Notifications: `session/update`, `_mothx/session_event`
- Reverse requests: `session/request_permission`, `mothx/requestQuestion`
- Attachments/artifacts: `mothx/attachment/list|fetch`
- Management: `mothx/manage/*`

## Troubleshooting

- **Blank window or crash on Linux:** confirm `DISPLAY` points at a live X
  server, or run under Xvfb.
- **Custom runtime does not start:** verify the path is executable and reports a
  compatible `mothx --version`; Desktop falls back to the bundled runtime.
- **Optional panel missing:** the runtime did not advertise its feature key.
  Update the bundled runtime or the Desktop release together.
- **Approval or question never resolves:** check the ACP decision timeout
  (`--permission-timeout`, `--question-timeout`, or the
  `MOTHX_ACP_PERMISSION_TIMEOUT` / `MOTHX_ACP_QUESTION_TIMEOUT` environment
  variables). The Runtime terminalizes unrecoverable pending decisions.

---

## Development Guide

Source: https://mothx.net/en/development.md

# Development Guide

This document describes how to contribute code to MothX.

## Development Environment Setup

### System Requirements

- Go 1.27+
- Git
- Make (optional)
- bubblewrap (optional, for sandbox testing)

### Get Source Code

```bash
git clone https://github.com/oschina/mothx.git
cd mothx
```

### Install Dependencies

```bash
go mod download
```

### Build Project

```bash
# Build
make build

# Install to $GOPATH/bin
make install
```

### Run Tests

```bash
# Run all tests
make test

# Run tests for specific package
go test ./internal/tools/

# Run specific test
go test -run TestReadTool ./internal/tools/

# Run the local-only TUI Router end-to-end suite (not part of CI)
go test -tags tui_router_e2e ./internal/tui/ -run 'RouterE2E' -v
```

The `tui_router_e2e` suite starts a fake ACP worker as a child process and
drives the production TUI → Runtime → Router → ACP path. It is intentionally
behind a build tag, so `make test` and CI neither compile nor run it. Run it
locally after changing Router lifecycle, TUI projection, or ACP worker code;
add `-race` when investigating concurrent worker behavior.

### Browser and Desktop end-to-end checks

The Router surfaces have browser-level coverage as well:

```bash
# WebUI: a real browser drives the composer, picks a worker, and activates it.
cd ui && npm run e2e          # includes e2e/router.smoke.mjs

# Desktop: the real runtime binary is driven over ACP stdio.
cd desktop && npm run build:runtime && npm run e2e:router
```

The WebUI smoke test runs a headless Chromium against the built UI and a fake
host, so it needs `npm run build` first. The Desktop round trip needs a runtime
built from the current source, because it asserts the Router management
projection that the host binary carries.

### Native desktop checks

MothX Native (the primary desktop client) is a nested Go module with headless
UI coverage instead of a browser driver:

```bash
make native-test    # transcript reducer + headless page/i18n/pixel tests
make native-vet     # go vet + MyGo lifetime/goroutine checks
make native-build   # stripped binary into native/build/
```

The headless tester renders every settings page and main view offline; English
scans fail on untranslated Chinese UI, and pixel probes pin the background
image/veil/shell paint order. Run `go test -race ./...` inside `native/` when
touching background-run routing or panel invalidation.

## Project Structure

```
mothx/
├── agent/                     # Public SDK types (Agent, Provider, Builder)
├── bootstrap/                 # Public SDK wiring into internal implementations
├── cmd/mothx/                 # CLI entry point and subcommands
├── desktop/                   # Electron desktop client (pure ACP; deprecated)
├── native/                    # Primary desktop client: pure-Go MyGo app (pure ACP)
├── ui/                        # Svelte Web UI embedded into Serve
├── internal/
│   ├── agent/                 # Core Agent loop, events, prompts, sub-agent tools
│   ├── agentruntime/          # Shared front-end-neutral Runtime and run lifecycle
│   ├── acp/                   # ACP server and mothx.dev extensions
│   ├── a2a/                   # A2A server and remote-agent master dispatch
│   ├── architecture/          # Architecture guard tests
│   ├── browser/               # vibe-browser tool
│   ├── config/                # settings.json / serve.json
│   ├── context/, contextfiles/# Token budget and project context
│   ├── cron/                  # Scheduled task store and scheduler
│   ├── dao/                   # Sole SQL/query/row-mapping owner
│   ├── db/                    # Connection/transaction/migration lifecycle
│   ├── esm/                   # Enable Supervisor Mode
│   ├── expert/                # Expert Team bundle discovery/validation
│   ├── imageproc/             # Image normalization
│   ├── mcp/                   # MCP integration
│   ├── memory/, messaging/    # Channel memory and platform abstraction
│   ├── platform/              # Cross-platform helpers and assets
│   ├── provider/              # Protocol providers, vendor adapters, factory
│   ├── sandbox/               # Sandbox abstraction
│   ├── serve/                 # OpenAI API, Web UI, channels, hooks, cron
│   ├── session/               # Session domain, migrations, event store
│   ├── skills/, skillhub/     # Skills and marketplace
│   ├── stats/                 # Usage statistics
│   ├── systeminit/            # AGENTS.md generation
│   ├── tools/                 # Built-in tools
│   ├── tui/                   # Bubble Tea TUI
│   └── workflow/              # JavaScript workflow runtime
├── example/                   # Public SDK examples
└── docs/                      # Bilingual docs, generated indexes, site
```

## Core Interfaces

### Provider Interface

```go
type Provider interface {
    Name() string
    Models() []*Model
    GetModel(id string) *Model
    Chat(ctx context.Context, params ChatParams) <-chan StreamEvent
}
```

### Tool Interface

```go
type Tool interface {
    Name() string
    Description() string
    PromptSnippet() string
    PromptGuidelines() []string
    Parameters() json.RawMessage
    Execute(ctx context.Context, params map[string]any) (ToolResult, error)
}
```

## Agent Runtime Rules

Production Agent construction and execution follow the shared Runtime boundary:

- Build Agents only through `SessionRuntime.BuildAgent`, `BuildTransientAgent`, or
  `agentruntime.NewAgentManager`. Do not add adapter-local `agent.Config`
  assembly or call `agent.New`/`agent.NewWithLoopConfig`.
- Resolve source, mode, capabilities, tools, sandbox, approval, MCP, and run
  policy once with `ResolveSource`/`ResolvePolicy`; adapters project the result.
- Use `ExecutionRuntime`/`RunStore` for durable runs and exactly one canonical
  terminal event. Do not create a second run state machine.
- Use `DecisionService`/`DecisionRecord` for approvals and questions.
- Put all SQL in `internal/dao`; use `internal/db` only for connection,
  transaction, and migration lifecycle.
- Keep entry points thin: TUI, CLI, WebUI/API, Desktop/ACP, channels, Cron, ESM,
  and A2A may decode protocols and render events, but not own sessions, run
  lifecycle, attachments, artifacts, or policy.
- Run `go test ./internal/architecture` after moving production construction or
  persistence call sites.

## Adding New Tools

### Step 1: Create Tool File

```go
// internal/tools/mytool.go
package tools

import (
    "context"
    "encoding/json"
)

type MyTool struct {
    workdir string
}

func NewMyTool(workdir string) *MyTool {
    return &MyTool{workdir: workdir}
}

func (t *MyTool) Name() string {
    return "mytool"
}

func (t *MyTool) Description() string {
    return "Description of my tool"
}

func (t *MyTool) PromptSnippet() string {
    return "Short one-line description for the system prompt"
}

func (t *MyTool) PromptGuidelines() []string {
    return []string{"Use this tool when ..."}
}

func (t *MyTool) Parameters() json.RawMessage {
    return json.RawMessage(`{
        "type": "object",
        "properties": {
            "param1": {
                "type": "string",
                "description": "First parameter"
            }
        },
        "required": ["param1"]
    }`)
}

func (t *MyTool) Execute(ctx context.Context, params map[string]any) (ToolResult, error) {
    param1, _ := params["param1"].(string)
    if param1 == "" {
        return ToolResult{}, fmt.Errorf("param1 is required")
    }
    return NewTextToolResult("result"), nil
}
```

### Step 2: Register Tool

Add the canonical name to `builtinToolOrder` and its constructor to
`builtinToolFactories()` in `internal/tools/tool.go`. `RegisterDefaults`,
`RegisterDefaultsWithPlanTool`, and `RegisterFiltered` all derive from those two
lists, so the tool is registered consistently.

### Step 3: Describe it for the system prompt

Return a concise `PromptSnippet` and targeted `PromptGuidelines` from the tool.
The shared Runtime builds the Available tools and Guidelines sections from those
methods; do not add per-adapter prompt text.

### Step 4: Write Tests

```go
// internal/tools/mytool_test.go
package tools

import (
    "context"
    "testing"
)

func TestMyTool_Execute(t *testing.T) {
    tool := NewMyTool("/tmp")
    result, err := tool.Execute(context.Background(), map[string]any{"param1": "value"})
    if err != nil {
        t.Fatalf("unexpected error: %v", err)
    }
    if result.Text != "expected" {
        t.Errorf("expected 'expected', got %q", result.Text)
    }
}
```

## Adding Provider Support

Most new services should be added as vendor adapters, not new protocol
providers. If the service speaks OpenAI Chat Completions or Anthropic Messages,
reuse the generic provider and register vendor defaults in `internal/provider`.

### Add an OpenAI/Anthropic-Compatible Vendor

1. Create `internal/provider/vendor_myvendor.go`.
2. Register URL detection and defaults with `RegisterVendorAdapter`.
3. Add model `compat` flags only for behavior that differs from the generic protocol.
4. Add focused tests in `internal/provider` and, if request formatting changes, in `internal/provider/openai` or `internal/provider/anthropic`.

```go
package provider

func init() {
    RegisterVendorAdapter(simpleVendorAdapter{
        name:           "myvendor",
        domains:        []string{"api.myvendor.example"},
        thinkingFormat: "deepseek", // optional
        defaultAPI:     "openai-chat",
    })
}
```

Provider creation for CLI, ACP, WebUI/Serve, and Desktop goes through
`internal/provider/factory`; Agent construction goes through `agentruntime`.
Do not add vendor-specific creation code to adapters or assemble a complete
`agent.Config` outside the shared Runtime.

### Add a New Protocol Provider

Only add a new provider package when the service has a native protocol that is
not covered by OpenAI Chat Completions or Anthropic Messages.

1. Create `internal/provider/myprotocol`.
2. Implement `provider.Provider`.
3. Add construction support in `internal/provider/factory`.
4. Keep settings JSON compatibility stable.
5. Add provider and factory tests.

## Testing

### Run All Tests

```bash
make test
make test-desktop     # Electron main/preload/renderer tests
```

### Run Tests for Specific Package

```bash
go test ./internal/agent/
go test ./internal/tools/
```

### Generate Coverage Report

```bash
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out
```

## Code Standards

### Formatting

```bash
make fmt
```

Or manually:

```bash
gofmt -w .
goimports -w .
```

### Linting

```bash
make lint
```

### Naming Conventions

- Package names: lowercase words, e.g., `tools`, `agent`
- Interface names: verbs or nouns, e.g., `Provider`, `Tool`
- Struct names: PascalCase, e.g., `ReadTool`, `AgentConfig`
- Function names: PascalCase, e.g., `NewAgent`, `Execute`
- Variable names: camelCase, e.g., `workdir`, `maxTokens`

### Error Handling

```go
// Good practice
result, err := doSomething()
if err != nil {
    return fmt.Errorf("do something: %w", err)
}

// Bad practice
result, _ := doSomething()
```

## Git Workflow

### Commit Convention

Use Conventional Commits:

```
<type>(<scope>): <subject>

[optional body]

[optional footer]
```

Types:
- `feat`: New feature
- `fix`: Bug fix
- `docs`: Documentation
- `refactor`: Refactoring
- `test`: Tests
- `chore`: Miscellaneous

Examples:

```
feat(tools): add new search tool
fix(agent): fix streaming issue
docs(readme): update installation guide
```

### Pull Request

1. Fork project
2. Create feature branch
3. Commit changes
4. Run tests
5. Create Pull Request

## Debugging

### Enable Debug Logging

```bash
mothx --debug
```

### Using dlv

```bash
# Install dlv
go install github.com/go-delve/delve/cmd/dlv@latest

# Debug
dlv debug ./cmd/mothx -- --debug
```

## Release Process

### Version Numbers

Use Semantic Versioning:

```
MAJOR.MINOR.PATCH

Example: 1.0.0, 1.1.0, 1.0.1
```

### Create Release

```bash
# Update version number
git tag -a v1.0.0 -m "Release v1.0.0"

# Push tags
git push --tags

# Build release packages
make build-all
```

### Publish to npm

```bash
# Publish release version
make npm-publish-all

# Publish pre-release version
make npm-publish-pre
```

Users can install via npm:

```bash
npm install -g mothx-installer
```

### Publish to PyPI

```bash
# Install publishing tools
python3 -m pip install --user "setuptools>=77.0.0" build twine

# Publish release wheels
make pypi-publish

# Publish pre-release wheels
make pypi-publish-pre
```

Users can install via PyPI:

```bash
pipx install mothx-installer
```

## Frequently Asked Questions

### Q: How to add a new tool?

A: See [Adding New Tools](#adding-new-tools) section.

### Q: How to add a new Provider?

A: See [Adding New Providers](#adding-new-providers) section.

### Q: What to do if tests fail?

A:
1. Check Go version
2. Run `go mod tidy`
3. Check error logs

### Q: How to debug sandbox issues?

A:
1. Use `--debug` flag
2. Check if bwrap is installed: `bwrap --version`
3. Check system logs

---

## Expert Teams

Source: https://mothx.net/en/expert-teams.md

# Expert Teams

Expert Teams let a session use a reusable expert identity or a coordinated
team. An expert bundle defines the lead persona, optional member personas,
and their declared capabilities. The Runtime resolves the bundle once for the
session; TUI, WebUI, Desktop/ACP, and channels only display that shared state.

## Start with an expert

Use `--expert` when starting MothX, or manage the binding from the TUI:

```bash
# Start a new session with the built-in software team
mothx --expert software-company

# Inspect the available expert bundles in an existing TUI session
/expert list
/expert show software-company

# Bind or remove an expert identity
/expert bind software-company
/expert unbind
```

`/expert bind` can bind an unbound session and `/expert unbind` removes the
identity from the current session. Neither operation rewrites previous
conversation history.

## Built-in catalog

MothX ships the original generalist bundles plus twelve role-based teams (58 new roles). New
team member display names use duty labels such as `Backend Lead` or
`Database & Migration Lead` instead of personal names. Each role-based bundle
also ships one focused skill (for example `backend-change-review` or
`llm-eval-gate`) that is loaded only while that expert is bound.

| Bundle | Team | Roles |
| --- | --- | --- |
| software-company | Software Company | Delivery Director, Product Manager, Software Architect, Software Engineer, QA Engineer |
| frontend-developer | Frontend Developer | Frontend Developer |
| backend-platform | Backend Platform Team | Backend Lead, API & Contract Lead, Database & Migration Lead, Service Runtime Lead, Backend Verification Lead |
| web-frontend | Web Frontend Team | Web Frontend Lead, React/Next.js Lead, Vue/Angular Lead, Design System & Accessibility Lead, Frontend Performance Lead |
| mobile-crossplatform | Mobile & Cross-platform Team | Mobile Lead, Android & KMP Lead, Flutter Lead, React Native Lead, iOS & Swift Lead |
| systems-lowlevel | Systems & Low-level Team | Systems Lead, Rust Lead, C++ Lead, Go Systems Lead |
| enterprise-jvm-dotnet | Enterprise JVM & .NET Team | Enterprise Lead, Java & Spring Lead, Kotlin Lead, C# & .NET Lead, PHP & Ruby Lead |
| qa-testing | QA & Testing Team | QA Lead, TDD Lead, E2E Test Lead, Regression Analysis Lead, Silent Failure Audit Lead |
| security-compliance | Security & Compliance Team | Security Lead, Application Security Lead, Agent Security Lead, Supply Chain Audit Lead, Compliance Review Lead |
| devops-sre | Platform Ops & SRE Team | Platform Ops Lead, Kubernetes Lead, CI/CD & Release Lead, Observability Lead, Config & Environment Lead |
| data-ml-ai | Data, ML & AI Engineering Team | Data & Model Lead, MLOps Lead, PyTorch Lead, Retrieval & Recommender Lead, LLM Evaluation Lead |
| product-architecture | Product & Architecture Team | Product & Architecture Lead, Product Planning Lead, Architecture Design Lead, Code Explorer Lead, Spec Miner Lead |
| docs-research | Docs & Research Team | Docs & Research Lead, Docs Governance Lead, Codebase Onboarding Lead, Deep Research Lead |
| agent-platform | Agent Platform & Meta-Engineering Team | Agent Platform Lead, Agent Architecture Lead, Harness & Evaluation Lead, Loop Operations Lead, Evaluation Lead |


## Switch experts by forking

Changing from one non-empty expert to another creates a new session branch:

```text
/expert switch frontend-developer
```

The source session keeps its original expert, history, and identity prompt.
The fork receives the requested expert at the current conversation boundary.
This prevents two expert identities from being mixed into one history.

The WebUI expert panel and Desktop's **Expert** session option follow the
same rule. Initial binding and unbinding update the current idle session;
switching an existing expert creates and opens a fork.

## Team behavior

Team bundles automatically enable the session's multi-agent capability. You
do not need to add `--multi-agent` just to use a team. The lead receives the
team roster and may dispatch declared members by ID:

```text
subagent_spawn(member: "software-engineer", task: "Implement the focused fix and run its tests.")
subagent_wait(timeout_ms: 30000)
```

Members are still normal sub-agents: their tool/mode limits come from the
bundle and the session policy, nested member spawning is unavailable, and
high-risk command protection remains in force. A single-persona expert only
changes the lead identity; it does not force team tools.

A bound team always exposes the full canonical sub-agent tool set
(`subagent_spawn`, `subagent_status`, `subagent_send`, `subagent_wait`,
`subagent_answer`, `subagent_destroy`). The team capability is authoritative:
per-tool toggles that disable individual sub-agent tools apply only to non-team
multi-agent sessions and do not remove tools from a team session.

Member lifecycle cards are projections of canonical child events. A member
completion updates its own status and is delivered to an active lead at an
agent-loop boundary. It never starts a new lead run by itself.

A member that needs a decision asks the lead instead of the human. The question
is queued for the lead (delivered as a `[MEMBER_QUESTION]` steering message, or
as a `subagent_wait` pending entry with status `question`) and is answered with
`subagent_answer(handle: "<member>", question_id: "…", answer: "…")`; the user
only sees the question projected on the lead's stream. A blocking
`delegate_subagent` child cannot ask questions, because its caller is parked
inside the tool call that would have to answer it.

The mailbox path is available in every session that can spawn members, not only
in team sessions. A bound team, and any interactive source (TUI, Web UI, ACP),
also holds its run open for still-running members at the wrap-up turn, so a
member's completion or question can be handled within the same run; headless and
asynchronous sources (CLI, cron, messaging channels) deliver member
notifications at the next iteration or the next run instead.

## ESM interaction

Expert Teams work with Enable Supervisor Mode (ESM) without creating a second
task scheduler. Only a user creates, edits, resumes, or clears an ESM
objective. When a session is truly idle and the objective is still runnable,
the normal ESM continuation path may start the next lead run; member terminal
events are not continuation triggers.

For a team-bound ESM worker, the lead identity and roster are retained,
including member scheduling: the worker continuation drains member
notifications and waits for members before its run may end. ESM critic, audit,
and recovery roles remain isolated: they do not receive member scheduling tools
and never drain or wait on the session's members.

## Add local bundles

Expert bundles are discovered lazily from the built-in catalog, the user
configuration directory's `experts/` folder, and the project folder:

```text
<config-dir>/experts/<bundle-name>/
<project>/.mothx/experts/<bundle-name>/
```

Project bundles override global bundles with the same name, which override
built-in bundles. A bundle contains `expert.json` and one or more persona
files under `agents/`; invalid bundles are shown as unavailable and cannot be
bound. See [the expert-team implementation proposal](https://github.com/oschina/mothx/blob/main/docs/proposal/expert-team-mothx-proposal.md)
for the bundle schema and architecture rationale.

## Create and install a team with the built-in Skill

MothX includes the `expert-creater` Skill. Once enabled, the current Agent
creates and installs a validated project-level team at
`.mothx/experts/<team-id>/`, including `expert.json` and its member personas.
It never overwrites an existing team directory unless you explicitly ask to
update that team.

| Surface | Activation command |
| --- | --- |
| TUI and WebUI chat | `/skill expert-creater` |
| Desktop and ACP | `/expert-creater`; ACP also accepts `/skill expert-creater` and `/skill:expert-creater` |

After activation, describe the team's goal and the lead/member roles in your
next message. Bind the resulting team with the existing picker or
`/expert bind <team-id>`; switching an already-bound team still follows the
normal fork rule.

---

## Frequently Asked Questions (FAQ)

Source: https://mothx.net/en/faq.md

# Frequently Asked Questions (FAQ)

> Real questions from real users, with practical solutions

---

## 🚀 Installation & Startup

### Q: After installation, running `mothx` shows "command not found"

**A:** This usually means the installation path isn't in your PATH environment variable.

```bash
# Check installation location
which mothx || where mothx

# If installed via npm, check npm global path
npm root -g

# Solution: Add installation path to PATH
# Linux/macOS (add to ~/.bashrc or ~/.zshrc)
export PATH="$HOME/.local/bin:$PATH"

# Or reinstall to system path
sudo npm install -g mothx-installer
```

### Q: npm installation fails with permission error

**A:** Don't use sudo for npm global packages. Try these alternatives:

```bash
# Option 1: Change npm global directory
mkdir -p ~/.npm-global
npm config set prefix '~/.npm-global'
export PATH=~/.npm-global/bin:$PATH

# Option 2: Use npx to run directly
npx mothx

# Option 3: Use the one-line installer (Linux/macOS)
curl -fsSL https://mothx.net/install.sh | bash
```

```bat
:: Windows Command Prompt
curl.exe -fsSL https://mothx.net/install.bat -o install.bat && install.bat
```

### Q: After starting, nothing happens, cursor just blinks

**A:** This could be a terminal compatibility or TUI rendering issue:

```bash
# Option 1: Use print mode (non-interactive)
mothx -P "hello"

# Option 2: Check terminal support
echo $TERM  # Should be xterm-256color or similar

# Option 3: Try a different terminal
# Recommended: iTerm2 (macOS), Windows Terminal (Windows), Alacritty (Linux)
```

---

## 🔑 API Keys & Connection

### Q: Shows "API key not found" or "Unauthorized"

**A:** Check your API key configuration:

```bash
# Option 1: Use environment variables
export DEEPSEEK_API_KEY=sk-...
# or
export OPENAI_API_KEY=sk-...

# Option 2: Check config file
cat ~/.mothx/settings.json

# Option 3: Run diagnostics
mothx doctor
```

### Q: Shows "connection timeout" or "network error"

**A:** Network connection issues, common for users behind firewalls:

```bash
# Option 1: Use proxy
export HTTPS_PROXY=http://127.0.0.1:7890

# Option 2: Use a provider that's accessible from your region
# Configure in settings.json
{
  "providers": {
    "deepseek": {
      "vendor": "deepseek",
      "api": "openai-chat",
      "baseUrl": "https://api.deepseek.com",
      "apiKey": "sk-..."
    }
  },
  "defaultProvider": "deepseek"
}

# Option 3: Check DNS
nslookup api.deepseek.com
```

### Q: Shows "rate limit exceeded"

**A:** API call frequency limit exceeded:

```bash
# Option 1: Wait a few minutes and retry

# Option 2: Configure retry mechanism
{
  "retry": {
    "enabled": true,
    "maxRetries": 5,
    "baseDelayMs": 3000
  }
}

# Option 3: Switch to another provider
mothx --provider openai --model gpt-4o
```

### Q: Can I use my ChatGPT/Codex subscription in MothX?

**Short answer:** a ChatGPT Plus/Pro subscription cannot be pointed at MothX. Use an OpenAI API key (per-token billing), or point MothX at any OpenAI-Responses-compatible gateway you already operate.

**Why not the subscription?** Three independent reasons:

| Reason | Detail |
|--------|--------|
| Different endpoint | A ChatGPT subscription is served by Codex's internal backend (`chatgpt.com/backend-api/codex/responses`), not by the public OpenAI API. It is an undocumented, Codex-specific variant of the Responses API, so it can change without notice. |
| Different authentication | It authenticates with a ChatGPT OAuth access token plus a ChatGPT account ID, and the token expires and refreshes on OpenAI's schedule. MothX provider credentials are a static value, `${ENV}`, or `!command` — there is no OAuth refresh flow to plug into. |
| Terms of service | Routing subscription access into a third-party client is not what the subscription is sold for. |

This is a different situation from **Codex CLI** itself: the Codex CLI can send a ChatGPT-login request to a custom `base_url` (leave `env_key` unset and it attaches its own OAuth token). That is Codex talking to its own backend, which is why it works there and not here.

**What to do instead**

1. *Use the OpenAI API.* The built-in `openai` provider is already configured for the Codex model family (Responses API + Codex user agent), so it works with just a key:

   ```bash
   export OPENAI_API_KEY=sk-...
   mothx --provider openai --model gpt-5.3-codex
   ```

2. *Use a gateway you control.* Any endpoint that speaks the OpenAI Responses API can back a provider:

   ```json
   {
     "providers": {
       "my-gateway": {
         "baseUrl": "http://127.0.0.1:8787/v1",
         "apiKey": "${MY_GATEWAY_TOKEN}",
         "api": "openai-responses",
         "models": [
           { "id": "gpt-5.3-codex", "name": "GPT-5.3 Codex (gateway)", "reasoning": true, "contextWindow": 400000, "maxTokens": 128000 }
         ]
       }
     }
   }
   ```

   If you want subscription-style access through your own gateway, that gateway is responsible for the OAuth refresh and any protocol translation; MothX only sees an ordinary Responses-compatible endpoint. See [configuration.md → providers](configuration.md#providers) for the full field list.

---

## 💰 Cost & Billing

### Q: How much does it cost to use MothX?

**A:** MothX itself is free and open source. Costs come from LLM API calls:

| Provider | Approximate Price (per million tokens) |
|----------|---------------------------------------|
| DeepSeek V4 Flash | $0.15-0.30 |
| DeepSeek V4 Pro | $0.60-1.20 |
| GPT-4o | $2.50-10 |
| Claude Sonnet | $3-15 |

**Cost-saving tips:**
- Use `deepseek-v4-flash` (default) for best value
- Enable cache hit optimization (automatic)
- Use `/compact` to compress context
- Avoid sending very long code files

### Q: How to check token usage?

**A:** The TUI status bar shows:
- Cache hit rate
- Current turn token usage
- Cumulative token usage

```bash
# Use debug mode for detailed info
mothx --debug
```

### Q: How to reduce API costs?

**A:**

1. **Use cheaper models**: `deepseek-v4-flash` has the best value
2. **Enable caching**: Repeated prompt prefixes are cached
3. **Compress context**: Use `/compact` command
4. **Limit output length**: Set `maxTokens` for the relevant provider model
5. **Use Plan mode**: Analyze first, then execute

---

## 🎮 Usage Modes

### Q: What's the difference between Plan, Agent, and YOLO modes?

**A:**

| Mode | File Ops | Network | Bash Approval | Use Case |
|------|----------|---------|---------------|----------|
| Plan | Read-only | ❌ | N/A | Code analysis, planning |
| Agent | Read/Write | ❌ | Required | Daily development (recommended) |
| YOLO | Full | ✅ | Not required | System admin, automation |

**Recommendation:** Use Agent mode for daily work, switch to YOLO when you need network or system operations.

### Q: Why are bash commands rejected in Agent mode?

**A:** Agent mode requires approval for bash commands by default:

```bash
# Option 1: Type 'y' to approve when prompted

# Option 2: Configure whitelist (auto-approve)
{
  "approval": {
    "bashWhitelist": ["go ", "make ", "git ", "npm ", "ls ", "cat "],
    "bashBlacklist": ["rm -rf", "sudo"]
  }
}

# Option 3: Switch to YOLO mode
/mode yolo
```

### Q: How to make AI only read code, not modify it?

**A:** Use Plan mode:

```bash
# Command line
mothx --mode plan

# Interactive
/mode plan

# Or press Tab to cycle through modes
```

---

## 🧠 Models & Thinking

### Q: When should I use thinking mode?

**A:**

| Scenario | Recommended Thinking Level |
|----------|---------------------------|
| Simple Q&A | off |
| Code generation | low - medium |
| Complex refactoring | high |
| Architecture design | xhigh |
| Debugging | medium |

```bash
# Change the thinking level
/settings       # Settings > defaults > thinking level
mothx -t high   # Specify per run on the command line
```

### Q: Why doesn't thinking mode work?

**A:** Not all models support thinking mode:

```bash
# Models that support thinking mode
mothx --provider deepseek --model deepseek-v4-pro -t high
mothx --provider openai --model o1 -t high
mothx --provider anthropic --model claude-3-5-sonnet -t high

# Unsupported models ignore thinking parameters
mothx --model deepseek-v4-flash -t high  # No effect
```

### Q: How to switch to a different model?

**A:**

```bash
# Temporary switch
mothx --provider openai --model gpt-4o

# Interactive switch
/model gpt-4o
/model  # View available models

# Permanent change to default model
# Edit ~/.mothx/settings.json
{
  "defaultProvider": "openai",
  "defaultModel": "gpt-4o"
}
```

---

## 📝 Session Management

### Q: Conversation is too long, AI starts forgetting context

**A:**

```bash
# Option 1: Compress context (keeps key info)
/compact

# Option 2: Enable auto-compaction
{
  "compaction": {
    "enabled": true,
    "reserveTokens": 16384,
    "keepRecentTokens": 20000
  }
}

# Option 3: Start a new session
/clear
```

### Q: How to resume a previous conversation?

**A:**

```bash
# Continue most recent session
mothx -c

# List all sessions
/sessions

# Switch to specific session
/sessions set abc123

# Or via command line
mothx --resume abc123
```

### Q: Session storage is taking up too much space

**A:**

```bash
# Check session sizes
du -sh ~/.mothx/sessions/

# Delete old sessions (removes both handle file and SQLite records)
/sessions del abc123

# Back up the whole session root before manual cleanup; it contains sessions.db
cp -a ~/.mothx/sessions ~/backups/sessions
```

### Q: Shows "Database migration error" on startup

**A:**

When `sessions.db` can no longer be migrated by the current version, MothX does not get stuck: it first backs the
old database up next to it as `sessions.db.migration-failed-<timestamp>.bak`, creates a new empty `sessions.db`, and
reports the migration failure in the startup notice and the logs.

- The previous sessions are all in the backup file; nothing was deleted, and the new database is usable immediately.
- Other mothx processes sharing that session directory receive a local UDP notice (`database_rebuilt`) and drop their old database handles, so they stop writing to the replaced file; the broadcast stays on the loopback network and never leaves the host.
- To get the old data back, fix the cause of the migration failure (for example open the database with the older MothX build), then rename the `.bak` file back to `sessions.db`.
- Once the old data is no longer needed, delete the `.bak` file.

---

## 🛠️ Tool Usage

### Q: AI command execution rejected, shows "permission denied"

**A:** Check file permissions and sandbox settings:

```bash
# Option 1: Check file permissions
ls -la <file>

# Option 2: Check sandbox configuration
mothx doctor

# Option 3: Temporarily disable sandbox
mothx --no-sandbox

# Option 4: Switch to YOLO mode
/mode yolo
```

### Q: grep/find tools return no results

**A:** Could be path or pattern issues:

```bash
# Make sure you're in the project directory
cd /path/to/your/project
mothx

# Use absolute paths
mothx -P "Search for TODO in /path/to/project"

# Check if .gitignore is excluding target files
```

### Q: How to prevent AI from automatically executing commands?

**A:**

```bash
# Option 1: Use Plan mode (read-only)
/mode plan

# Option 2: Be explicit in your prompt
mothx -P "Analyze this code, don't execute any commands"

# Option 3: Configure approval
{
  "approval": {
    "bashWhitelist": [],
    "confirmBeforeWrite": true
  }
}
```

---

## 🔒 Security & Privacy

### Q: Does MothX upload my code?

**A:** MothX itself doesn't upload code, but it sends your prompts to the configured LLM API:

- **Local processing**: File reads, tool execution happen locally
- **API calls**: Prompt content is sent to LLM providers
- **Recommendation**: Don't include sensitive info (passwords, keys) in prompts

### Q: How to prevent AI from deleting important files?

**A:**

```bash
# Option 1: Use Plan mode (read-only)
/mode plan

# Option 2: Configure blacklist
{
  "approval": {
    "bashBlacklist": ["rm -rf", "rm -r", "sudo"]
  }
}

# Option 3: Use Git version control
git add -A && git commit -m "backup before AI changes"

# Option 4: Enable sandbox
mothx --sandbox
```

### Q: Sandbox mode not working?

**A:** Sandbox is Linux-only:

```bash
# Check if bubblewrap is installed
bwrap --version

# Install
sudo apt install bubblewrap      # Debian/Ubuntu
sudo dnf install bubblewrap      # Fedora
sudo pacman -S bubblewrap        # Arch

# macOS/Windows users can use WSL2
```

---

## 💻 IDE Integration

### Q: Can't see MothX in VS Code

**A:** Check ACP configuration:

```json
// .vscode/settings.json or global settings.json
{
  "acp.agents": {
    "mothx": {
      "command": "mothx",
      "args": ["acp", "--mode", "agent"]
    }
  }
}
```

Make sure:
1. MothX is installed and in PATH
2. VS Code version supports ACP
3. Restart VS Code

### Q: JetBrains IDE integration not working

**A:**

1. Open `Settings → Tools → ACP Agents`
2. Add Agent:
   - Name: `MothX`
   - Command: `mothx`
   - Arguments: `acp --mode agent`
3. Click Test to verify connection
4. Restart IDE

---

## 🌐 Serve Mode

### Q: How to use MothX as an API server?

**A:**

```bash
# Start Serve
mothx serve

# Config file ~/.mothx/serve.json
{
  "port": 8080,
  "auth": {
    "token": "your-secret-token"
  }
}

# Call API
curl http://localhost:8080/v1/chat/completions \
  -H "Authorization: Bearer your-secret-token" \
  -H "Content-Type: application/json" \
  -d '{"model":"deepseek-v4-flash","messages":[{"role":"user","content":"hello"}]}'
```

### Q: What APIs does Serve support?

**A:** Compatible with OpenAI Chat Completions API:

- `/v1/chat/completions` - Chat completion
- `/v1/models` - Model list
- Supports SSE streaming
- Supports all configured providers and models

---

## 📱 Messaging Platforms

### Q: How to deploy as a WeChat/Feishu bot?

**A:**

```bash
# Start Channels mode
mothx serve

# Config file ~/.mothx/serve.json
{
  "platform": "wechat",  // or "feishu"
  "appId": "your-app-id",
  "appSecret": "your-app-secret",
  "defaultProvider": "deepseek"
}
```

See [Serve Mode](serve.md) documentation for details.

---

## 🔧 Troubleshooting

### Q: `mothx doctor` shows errors

**A:** The doctor command checks:

```bash
mothx doctor
```

Common issues:
- **Config**: Config file format error → Check the JSON syntax. During normal startup, MothX backs up an invalid `settings.json` to `.bak_<timestamp>` and prints its absolute path to stderr. You can recover valid values from that backup. If the error includes `backup failed`, check file and directory permissions or whether the filesystem is read-only.
- **Provider**: API key missing or invalid → Reconfigure
- **Sandbox**: bubblewrap not installed → Install or ignore
- **MCP**: MCP server config error → Check mcp.json

### Q: How to view detailed logs?

**A:**

```bash
# Enable debug mode
mothx --debug

# Logs will show
- API request/response details
- Tool execution process
- Error stack traces
```

### Q: Shows "context window exceeded"

**A:** Context exceeds model limit:

```bash
# Option 1: Compress context
/compact

# Option 2: Enable auto-compaction
{
  "compaction": {
    "enabled": true
  }
}

# Option 3: Use a model with larger context
mothx --model deepseek-v4-pro  # 1M context

# Option 4: Clear conversation and start fresh
/clear
```

### Q: Tool execution hangs

**A:**

```bash
# Option 1: Press Esc to abort current operation

# Option 2: Check for interactive commands blocking
# Example: git push may require password input

# Option 3: Configure non-interactive mode
{
  "env": {
    "GIT_TERMINAL_PROMPT": "0",
    "DEBIAN_FRONTEND": "noninteractive"
  }
}
```

---

## 🆚 Comparison with Other Tools

### Q: What's the difference between MothX and Claude Code?

**A:**

| Feature | MothX | Claude Code |
|---------|-----------|-------------|
| Price | Free & Open Source | Paid |
| Models | Multi-provider | Anthropic only |
| Sandbox | ✅ bwrap | ❌ |
| Session Management | ✅ Full | Limited |
| IDE Integration | ✅ ACP | ✅ |
| Messaging | ✅ WeChat/Feishu | ❌ |
| Serve | ✅ OpenAI compatible | ❌ |

### Q: What's the difference between MothX and Cursor?

**A:**

- **MothX**: Terminal tool, lightweight, great for CLI users
- **Cursor**: IDE with GUI, great for users who prefer graphical interfaces

Choose based on:
- Prefer terminal → MothX
- Prefer GUI → Cursor
- Need API service → MothX Serve

---

## 📚 More Resources

- [5-Minute Quick Start](quick-start-tutorial.md)
- [Features Overview](features-overview.md)
- [Use Cases](use-cases.md)
- [Configuration Guide](configuration.md)
- [Tool Reference](tools.md)

---

<p align="center">
  <strong>Still have questions? Ask on GitHub!</strong><br>
  <a href="https://github.com/oschina/mothx/issues">GitHub Issues</a> · <a href="https://github.com/oschina/mothx/discussions">GitHub Discussions</a>
</p>

---

## ✨ MothX Core Features Explained

Source: https://mothx.net/en/features-overview.md

# ✨ MothX Core Features Explained

> One tool to meet all your AI coding needs.

---

## 🤖 Multi-Provider Support

### Supported Providers

| Provider | Models | API Format |
|----------|--------|------------|
| **DeepSeek** (default) | deepseek-v4-flash, deepseek-v4-pro | OpenAI Chat / Anthropic Messages |
| **OpenAI** | GPT-4o, o1, etc. | OpenAI Chat |
| **Anthropic** | Claude Sonnet, Opus, etc. | Anthropic Messages |
| **LongCat** | LongCat-2.0 (1M context, 128K output) | OpenAI Chat / Anthropic Messages |
| **Vendor Adapters** | Google Gemini, Google Vertex, Xiaomi, Volcengine/Doubao, Kimi, MiniMax, Seed, Qianfan, Bailian, Gitee, StepFun, OpenRouter, Together, Groq, Fireworks, Mistral, GitHub Copilot, Cloudflare AI Gateway, Cloudflare Workers AI, Amazon Bedrock, Z.AI, LongCat, AMD Radeon, and more | OpenAI Chat or Anthropic Messages |
| **Custom** | Any compatible model | Generic OpenAI Chat or Anthropic Messages fallback |

### Quick Switch

```bash
# Use DeepSeek
mothx --provider deepseek-openai --model deepseek-v4-flash

# Use OpenAI
mothx --provider openai --model gpt-4o

# Use Anthropic
mothx --provider anthropic --model claude-3-5-sonnet-20241022
```

### Vendor Adapters

MothX ships 60+ built-in provider presets, including:

- **China**: Xiaomi, Volcengine/Doubao, Kimi, MiniMax, Seed, Qianfan, Bailian, Gitee, StepFun, Z.AI, LongCat, AMD Radeon
- **International**: Google Gemini, Google Vertex, OpenRouter, Together, Groq, Fireworks, Mistral, GitHub Copilot, Cloudflare AI Gateway, Cloudflare Workers AI, Amazon Bedrock

No additional configuration needed — just set the API key and start using. See the [Provider & Model Catalog](../provider-model-list.md) for the generated list of every built-in provider and model.

---

## ⚡ Lightning Fast

### SSE Streaming

MothX uses SSE (Server-Sent Events) streaming to return tokens in real-time, no need to wait for complete responses.

### Cache Hit Optimization

- **Real-time cache hit rate display**: Shows cache hit percentage in the TUI footer
- **Per-turn cache statistics**: Detailed cache hit info for each conversation turn
- **Unified cache metrics**: Consistent statistics across TUI and print modes

### Performance Comparison

| Feature | MothX | Other Tools |
|---------|-----------|-------------|
| Streaming | ✅ SSE | Partial support |
| Cache hit rate | ✅ Real-time display | ❌ Not displayed |
| Token statistics | ✅ Unified metrics | ❌ Inconsistent |

---

## 🧠 Think Mode

### Supported Models

- **DeepSeek**: deepseek-v4-pro (supports thinking mode)
- **OpenAI**: o1 series (supports thinking mode)
- **Anthropic**: Claude series (supports thinking mode)

### Thinking Levels

```bash
# Set thinking level
mothx --thinking off      # No thinking
mothx --thinking minimal  # Minimal thinking
mothx --thinking low      # Low thinking
mothx --thinking medium   # Medium thinking
mothx --thinking high     # High thinking
mothx --thinking xhigh    # Ultra high thinking
```

### Use Cases

- **Complex problems**: Use `high` or `xhigh` for deeper reasoning
- **Simple problems**: Use `off` or `minimal` for faster responses
- **Debugging code**: Use `medium` for balanced speed and quality

---

## 🛡️ Sandboxed

### bwrap Process Isolation

MothX uses [bubblewrap](https://github.com/containers/bubblewrap) for process-level isolation, ensuring secure execution.

### Three Modes

![Three Safety Modes](assets/image/modes-en.webp)

| Mode | File System | Network | Use Case |
|------|------------|---------|----------|
| **Plan** | Read-only | ❌ | Analysis, planning |
| **Agent** | Read/Write | ❌ | Daily development |
| **YOLO** | Full | ✅ | System-level operations |

### Security Features

- **bashBlacklist priority**: Blacklisted commands (like `rm -rf`, `sudo`) are always blocked
- **Approval gates**: In Agent mode, bash commands require approval
- **`--print` fast fail**: Exits immediately when approval is needed, won't hang

### Installing bwrap

```bash
# Debian/Ubuntu
sudo apt install bubblewrap

# Fedora
sudo dnf install bubblewrap

# Arch
sudo pacman -S bubblewrap
```

---

## 📝 Session Management

### SQLite Persistence

MothX uses SQLite-backed storage for persistent session history. Features include:

- **Interactive picker**: `/sessions` opens a dialog with Up/Down navigation, Enter to switch, `n` for new, `d` for delete
- **Lazy creation**: TUI startup defers session creation until the first user message
- **Branching**: Create new branches from any node
- **Compaction**: Automatically compact old sessions to save space
- **Tree structure**: Visualize session trees

### Session Commands

```bash
# Continue most recent session
mothx --continue

# Resume specific session
mothx --resume <session-id>

# Use specific session handle file
mothx --session <session-file.db>
```

### TUI Session Picker

In the TUI, use `/sessions` to open the interactive session picker:

- **Up/Down**: Navigate sessions
- **Enter**: Switch to selected session
- **n**: Start a new session
- **d**: Delete selected session
- **Esc**: Close picker

Text commands are also available:
```bash
/sessions ls        # List sessions
/sessions set <id>  # Switch to session
/sessions clear     # Start fresh
/sessions del <id>  # Delete session
```

### Session Storage Location

| Platform | Location |
|----------|----------|
| Linux/macOS | `~/.mothx/sessions/` |
| Windows | `%APPDATA%\mothx\sessions\` |

---

## 🧩 Skills System

### What Are Skills?

Skills are reusable prompt snippets for:

- **Project conventions**: Coding standards, naming rules, architecture patterns
- **Team sharing**: Unify team development style
- **Quick onboarding**: New members quickly understand project conventions

### Creating Skills

```bash
# Global skills (available for all projects)
~/.mothx/skills/<name>/SKILL.md

# Project skills (override global)
.skills/<name>/SKILL.md
```

### Using Skills

```bash
# List available skills
> /skills

# Activate a skill
> /skill my-conventions

# Load skill reference
> /skill_ref my-references
```

### Online Skill Marketplace

MothX is compatible with 源盾 / SkillHub / ClawHub, supporting:

- **Skill installation**: One-click install online skills
- **Cron infrastructure**: Scheduled skill execution
- **Community sharing**: Share your skills

---

## 📊 Stats Dashboard

### Usage Statistics

MothX includes a built-in stats dashboard for tracking token usage, requests, and costs.

```bash
# Start web dashboard (default 127.0.0.1:7878)
mothx stats

# Print stats in terminal
mothx stats --cli

# Use alternate database
mothx stats --db ~/.mothx/sessions/sessions.db
```

### Features

- **Pure HTML/CSS/JS**: No external dependencies, charts drawn on `<canvas>`
- **Overall summary**: Requests, tokens, cost, duration
- **Time-series charts**: Visualize usage over time
- **Per-provider/model breakdowns**: See which providers and models you use most
- **Protocol + Vendor split**: Separate vendor (company) from protocol (API format)
- **Filtering**: By time range (today/week/month/all), vendor, and protocol
- **Recent requests table**: Paginated list of recent API calls

### CLI Mode

```bash
# Print stats directly in terminal
mothx stats --cli
```

Shows:
- Total tokens, requests, cost, duration
- Per-provider breakdown
- Per-model breakdown
- 10 most recent requests

---

## 💻 IDE Integration

### ACP Protocol

MothX supports Agent Client Protocol (ACP), integrating with:

- **VS Code**
- **Zed**
- **JetBrains IDEs** (IntelliJ IDEA, WebStorm, etc.)

### VS Code Integration

Add to `settings.json`:

```json
{
  "acp.agents": {
    "mothx": {
      "command": "mothx",
      "args": ["acp", "--mode", "agent", "--multi-agent"]
    }
  }
}
```

### JetBrains Integration

Navigate to `Settings → Tools → ACP Agents` and add:

- **Name**: MothX
- **Command**: `mothx`
- **Arguments**: `acp --mode agent`

---

## 🌐 Serve Mode

### OpenAI-Compatible HTTP API

MothX can be used as an OpenAI-compatible HTTP server:

```bash
# Start serve
mothx serve

# Configuration files
~/.mothx/serve.json
.mothx/serve.json
```

### Use Cases

- **Team sharing**: Team members share AI coding assistant
- **CI/CD integration**: Use AI in CI/CD pipelines
- **API service**: Provide AI coding API service

---

## 📱 Messaging Platforms

### WeChat/Feishu/WebSocket

MothX can be deployed as a chatbot:

```bash
# Start messaging channels
mothx serve

# Configuration files
~/.mothx/serve.json
.mothx/serve.json
```

### Features

- **Multi-user support**: Independent sessions per user
- **Persistent sessions**: Session history automatically saved
- **Progress callbacks**: Real-time tool execution progress
- **Thinking display**: Show AI's thinking process
- **WeChat QR Login**: Scan-to-authenticate with login status polling
- **Configuration Hot-Reload**: Auto-reload provider/model config after saving via Web UI

---

## 🤝 Multi-Agent

### Sub-Agent Delegation

```bash
# Enable multi-agent mode
mothx --multi-agent

# Sub-agent tools
subagent_spawn    # Create sub-agent
subagent_status   # Check sub-agent status
subagent_send     # Send message to sub-agent
subagent_destroy  # Destroy sub-agent
```

### Delegate Mode

```bash
# Enable one blocking delegated sub-agent
mothx --delegate

# Toggle in TUI or Serve sessions
/delegate on
/delegate status
/delegate off
```

`--delegate` registers `delegate_subagent`, a synchronous tool for one bounded investigation at a time. Use it when the main agent only needs a summarized result from a focused multi-step task.

### A2A Protocol

```bash
# Enable A2A Master mode
mothx --enable-a2a-master

# Generate sample config
mothx --init-a2a-master-config
```

### Dynamic Workflows

```bash
# Enable Workflow mode
mothx --workflows

# Workflow tools
workflow_run      # Run an JavaScript workflow
workflow_status   # Check workflow status
workflow_cancel   # Cancel a workflow run
```

Orchestrate multiple worker agents using an JavaScript DSL, with phase grouping, parallel execution, concurrency control, result fan-in, and run logs. Ideal for code audits, architecture research, multi-role reviews, generate-critic loops, and other complex multi-agent scenarios.

See the [Workflow Mode](workflow.md) documentation for full syntax and best practices.

### Use Cases

- **Large tasks**: Split large tasks into multiple subtasks
- **Parallel execution**: Multiple sub-agents working in parallel
- **Remote collaboration**: Manage remote agents via A2A protocol

---

## 🎨 Rich TUI

### Features

- **Markdown rendering**: Real-time Markdown content rendering
- **Syntax highlighting**: Code block syntax highlighting
- **Thinking display**: Show AI's thinking process in full event mode or the details modal
- **Tool modals**: View tool execution details (Ctrl+O)
- **Event display modes**: The default simple view keeps one-line tool summaries and hides routine lifecycle noise; Ctrl+G switches to the full event view (Ctrl+O always opens raw tool details)
- **Multiline input**: Alt+Enter/Ctrl+J for newlines, Up/Down for history at boundaries
- **Status bar**: Show cache hit rate, token statistics, context usage, elapsed time
- **Sticky todo list**: Active plan steps remain visible while streaming
- **Native scrollback**: Completed transcript blocks print to terminal scrollback

### Keyboard Shortcuts

| Shortcut | Function |
|----------|----------|
| `Enter` | Submit prompt |
| `Alt+Enter` / `Ctrl+J` | Insert newline |
| `Tab` | Cycle mode (plan → agent → yolo) |
| `Esc` | Abort current operation, approval, or question |
| `Ctrl+O` | Open/close tool details modal |
| `Ctrl+G` | Toggle simple/full event display |
| `Up` / `Down` | Move in input; browse history at boundaries; scroll tool modal |
| `PgUp` / `PgDn` | Page through tool modal |
| `Home` / `End` | Start/end of input line; top/bottom of tool modal |

### Slash Commands

| Command | Description |
|---------|-------------|
| `/systeminit [guidance]` | Generate or refresh project `AGENTS.md` |
| `/reload` | Restart with fresh session (TUI only) |
| `/btw <question>` | Ask a side question without interrupting main task |
| `/alloweditpath [add\|remove\|clear] <glob>` | Manage auto-edit path whitelist |
| `/allowautoedit [on\|off] [global]` | Toggle full auto-edit in agent mode |

---

## 🔒 Security Control

### Approval Mechanism

```json
{
  "approval": {
    "bashWhitelist": ["go ", "make ", "git ", "npm "],
    "bashBlacklist": ["rm -rf", "sudo"],
    "confirmBeforeWrite": true
  }
}
```

### Project-Level Bash Auto-Approval

`allow.json` supports project-level bash auto-approval rules:

```json
{
  "bashCommands": ["make test"],
  "bashPrefixes": ["go test ", "go build "]
}
```

- `bashCommands`: Exact command match
- `bashPrefixes`: Prefix match (trailing spaces are significant)
- Settings-level `bashBlacklist` takes precedence over project allow rules

### Interactive Approval Dialog

When approval is required, the TUI shows a dialog with:

- **Approve Once**: Run this time only
- **Deny**: Reject the command
- **Always Allow Exact Command**: Persist to `.mothx/allow.json`
- **Always Allow Command Prefix**: Persist prefix to `.mothx/allow.json`

### Security Features

- **bashBlacklist priority**: Blacklisted commands are always blocked
- **YOLO mode safety**: Even in YOLO mode, blacklist still applies
- **`--print` fast fail**: Exits immediately when approval is needed
- **Project allow rules**: Per-project bash auto-approval via `.mothx/allow.json`

---

## 📊 Unified Cache Metrics

### Real-time Display

- **Cache hit rate**: Real-time display in TUI footer
- **Token statistics**: Detailed token usage per conversation turn
- **Unified metrics**: Consistent statistics across TUI and print modes

### Use Cases

- **Cost optimization**: Monitor cache hit rate to optimize API call costs
- **Performance monitoring**: Monitor token usage to optimize response speed

---

## 🐞 Consistent Debug Output

### `--debug` Mode

```bash
# Enable debug mode
mothx --debug

# Debug output includes
- Provider request/response
- ACP mode debugging
- Tool execution details
- Local pprof at http://127.0.0.1:6060/debug/pprof/
```

### Use Cases

- **Troubleshooting**: Quickly locate API call issues
- **Development debugging**: Debug custom tools or skills
- **Performance analysis**: Analyze API call performance

---

## 🩺 Environment Diagnostics

### `doctor` Subcommand

```bash
# Run environment diagnostics
mothx doctor
```

### Check Items

- **Configuration files**: Check settings.json, serve.json, serve.json
- **Provider**: Check API keys and connections
- **Sandbox**: Check bwrap installation and configuration
- **MCP**: Check MCP server configuration
- **Sessions**: Check session storage
- **Skills**: Check skill loading
- **Context files**: Check AGENTS.md, CLAUDE.md, etc.

### Update Notifications

MothX checks for newer releases via npm registry and shows a non-blocking reminder when an update is available. Checks run in the background, keep only a local 24h cooldown timestamp, and never block the foreground.

Disable via `settings.json` with `"updateCheck": false`, or via `VIBECODING_NO_UPDATE_CHECK=1`.

---

## 🆕 Current Release Capabilities

The following capabilities are integrated into the current runtime; actual availability depends on configuration and model compatibility:

- **OpenAI Responses**: Supports native response item replay, reasoning, structured output, hosted tools, prompt cache, and optional durable background runs through `responses.background`. Background runs can be queried, canceled, reconnected, or abandoned and recover after Serve restarts.
- **Desktop client**: A separate Electron ACP app with chat, tool/diff cards, approvals, questions, artifacts, Expert Teams, knowledge bases, worktrees, and management panels; it starts the bundled `mothx acp` runtime and never starts `mothx serve`.
- **Knowledge bases**: A Desktop/WebUI-managed, rebuildable index of a read-only directory. Canonical index runs use the shared Runtime, snapshots publish atomically, and sessions query evidence through a standard Knowledge MCP server.
- **Attachments and artifacts**: Runtime-owned intake, storage, replay, provider conversion, and delivery; `publish_artifact` is the only path that turns a completed file into a deliverable artifact.
- **Web UI management**: Provides session search and pagination, run status and cancellation, an approval center, tool results, skill activation, MCP configuration, Provider/Serve settings, and a `/stats` dashboard.
- **MCP**: Supports stdio, streamable HTTP, and legacy SSE.
- **Parallel tool execution**: Local function and custom tool calls within one agent turn run through a bounded parallel worker pool. Call starts are reported in the model's declared order without blocking execution, so calls still overlap and only the completion order is unrestricted. The `toolExecution` setting controls `mode` (`parallel`/`sequential`) and `maxConcurrency` (default `10`). Shared by TUI, WebUI, Serve, channels, ACP, and sub-agents.
 Global and project `mcp.json` files can be edited and are loaded into new Serve sessions.
- **Messaging channels**: Supports WeChat and Feishu. Background runs persist events and can deliver results after reconnect or restart. WebSocket `/ws/runs` and `/ws/logs` are Web UI event streams, not standalone messaging channels.
- **Project state files**: Current project state is under `.mothx/`, including `settings.json`, `serve.json`, `allow.json`, `memory.md`, and skill directories. Legacy `.vibe` paths are no longer migrated automatically.
- **Model capability validation**: Images, attachments, Responses hosted tools, and reasoning parameters are validated against the selected model before requests are sent; unsupported combinations fail early.

---

## 🎯 Summary

MothX is an **all-in-one terminal AI coding assistant** with these core advantages:

1. **One binary does it all**: No need to install multiple tools
2. **Multi-provider support**: 60+ built-in provider presets, one-click switching
3. **Security control**: Sandbox isolation, approval gates, blacklist protection
4. **Rich features**: Session management, skills system, IDE integration
5. **High performance**: SSE streaming, cache hit optimization

**Ready to get started?** [5-Minute Quick Start](quick-start-tutorial.md)

---

## Quick Start

Source: https://mothx.net/en/getting-started.md

# Quick Start

This guide helps you get started with MothX in 5 minutes.

## System Requirements

- **Operating System**: Linux, macOS, Windows 10/11
- **Go**: 1.24+ (when building from source)
- **Optional**: bubblewrap (for sandbox functionality)

## Installation

### Method 1: One-line Install (Recommended)

The script uses an existing Node.js installation when available. If Node.js is
missing, it installs the latest Node.js LTS release first and then installs the
latest MothX package through npm.

**Linux/macOS:**

```bash
curl -fsSL https://mothx.net/install.sh | bash
```

**Windows (Command Prompt):**

```bat
curl.exe -fsSL https://mothx.net/install.bat -o install.bat && install.bat
```

Run the command in Command Prompt (`cmd.exe`). The installer checks for Node.js, installs the latest Node.js LTS when needed, and then installs MothX globally through npm.

**Uninstall:**

```bash
# npm
npm uninstall -g mothx-installer

# PyPI
pipx uninstall mothx-installer

# Linux/macOS
curl -fsSL https://mothx.net/install.sh | bash -s -- --uninstall

# Windows
npm uninstall -g mothx-installer
```

The online installers ultimately run `npm install -g mothx-installer`.

### Method 2: Docker (GHCR)

```bash
# Default Ubuntu image, runs as root
docker run --rm -it --entrypoint bash ghcr.io/oschina/mothx:latest

# Run MothX in the current workspace
docker run --rm -it -v "$PWD:/workspace" -w /workspace ghcr.io/oschina/mothx:latest
```

Available tags:

- `latest` / `ubuntu` - default Ubuntu image
- `debian`, `fedora`, `alpine` - distro variants
- `vX.Y.Z`, `vX.Y.Z-ubuntu`, `vX.Y.Z-debian`, `vX.Y.Z-fedora`, `vX.Y.Z-alpine` - release tags

Published architectures: `linux/amd64`, `linux/arm64`

The container runs as `root` by default and includes `bash`, `git`, `curl`, `ca-certificates`, and `openssh-client`.

### Method 3: Go Install

```bash
go install github.com/oschina/mothx/cmd/mothx@latest
```

### Method 4: Build from Source

```bash
# Clone repository
git clone https://github.com/oschina/mothx.git
cd mothx

# Build
make build

# Binary is located at bin/mothx
```

### Method 5: Install to System

```bash
# After building from source
make install
```

## Configure API Keys

### Option 1: Environment Variables

```bash
# DeepSeek
export DEEPSEEK_API_KEY=sk-...
```

### Option 2: Settings File

Or add keys directly to your settings.json:

```json
{
  "providers": {
    "deepseek-openai": {
      "vendor": "deepseek",
      "api": "openai-chat",
      "baseUrl": "https://api.deepseek.com",
      "apiKey": "sk-..."
    }
  }
}
```

The optional `vendor` field selects a vendor adapter. If it is omitted, MothX detects the vendor from `baseUrl` when possible and otherwise falls back to the generic provider selected by `api`. See the [Configuration Guide](configuration.md) for details.

## First Run

### Interactive Mode

```bash
# Start interactive session
mothx
```

### Non-Interactive Mode

```bash
# Single question
mothx -p "Explain what this code does"

# Read from stdin
echo "Write a Hello World" | mothx -P
```

### Specify Model

```bash
# Use DeepSeek-V4-Flash
mothx --provider deepseek-openai --model deepseek-v4-flash

# Use DeepSeek-V4-Pro
mothx --provider deepseek-openai --model deepseek-v4-pro
```

### Multi-Agent Mode

```bash
# Enable sub-agent tools and multi-agent commands
mothx --multi-agent

# ACP sessions can opt in too
mothx acp --multi-agent
```

Multi-agent mode registers `subagent_*` tools for delegated work. Cron command entry points are available in TUI multi-agent workflows.

### Expert Teams

Bind a reusable single expert or a coordinated team to a session:

```bash
# Start with the built-in software team
mothx --expert software-company
```

In TUI, use `/expert list`, `/expert show <id>`, `/expert bind <id>`,
`/expert unbind`, and `/expert switch <id>`. Switching between two experts
creates a session fork so the original identity and history remain intact.
Team experts automatically enable the session's member-dispatch capability.
See [Expert Teams](expert-teams.md) for lifecycle, ESM, and local-bundle details.

### Delegate Mode

```bash
# Enable blocking single sub-agent delegation
mothx --delegate

# Toggle it at runtime in TUI
/delegate on
/delegate status
/delegate off
```

Delegate mode registers `delegate_subagent`, a synchronous tool for one bounded subtask at a time. It is useful for multi-step investigations or focused verification where the main agent only needs a summarized result.

### A2A Master Mode

```bash
# Generate sample config
mothx --init-a2a-master-config

# Enable master mode
mothx --enable-a2a-master
```

A2A Master mode lets you manage multiple remote A2A agents, with the LLM automatically dispatching tasks via the `a2a_dispatch` tool. See [A2A Protocol](a2a.md) for details.

## Choose Mode

MothX provides three modes:

```bash
# Plan mode - read-only analysis
mothx --mode plan

# Agent mode - standard read/write
mothx --mode agent

# YOLO mode - full access (default)
mothx --mode yolo
```

| Mode | File System | Network | Use Case |
|------|------------|---------|----------|
| **Plan** | Read-only | ✗ | Analysis, planning |
| **Agent** | Read/Write | ✗ | Daily development |
| **YOLO** | Full | ✓ | System-level operations |

## Basic Interaction

### Common Commands

```bash
/mode plan      # Switch to Plan mode
/mode agent     # Switch to Agent mode
/model          # View current model
/settings       # Configure defaults, including thinking level
/clear          # Clear conversation
/help           # Show help
/quit           # Exit
```

### Keyboard Shortcuts

| Shortcut | Function |
|----------|----------|
| `Enter` | Submit the current prompt |
| `Alt+Enter` / `Ctrl+J` | Insert a newline in the prompt editor |
| `Tab` | Cycle mode (`plan` → `agent` → `yolo`) |
| `Esc` | Abort the current operation, approval, or question prompt |
| `Ctrl+O` | Open the latest tool/details modal; press again, `Esc`, or `q` to close |
| `Ctrl+E` | Open the ESM progress panel; press again, `Esc`, or `q` to close |
| `Ctrl+G` | Toggle simple/full event display; simple is the default |
| `Up` / `Down` | Move within multiline input; browse prompt history at the first/last input line; scroll an open details/progress panel |
| `PgUp` / `PgDn` | Page through an open details/progress panel |
| `Home` / `End` | Move to the start/end of the current input line; jump to top/bottom in an open details/progress panel |

Completed conversation blocks are printed to the terminal's native scrollback, so use your terminal's normal mouse wheel, trackpad, or scrollbar to review older transcript output.

## Usage Examples

### Code Explanation

```bash
mothx -P "Explain the purpose of main.go"
```

### Code Generation

```bash
mothx -P "Write a Go HTTP server"
```

### File Operations

```bash
mothx -P "Create a README.md in the current directory"
```

### Continue Session

```bash
# Continue most recent session
mothx --continue

# Resume specific session
mothx --resume <session-id>
```

## Skills System

Skills are reusable prompt snippets that help enforce project conventions:

```bash
# List available skills
> /skills

# Activate a skill
> /skill my-conventions
```

Create skills by adding `SKILL.md` files:
- **Global**: `~/.mothx/skills/<name>/SKILL.md` (available for all projects)
- **Project**: `.skills/<name>/SKILL.md` (project-specific, overrides global)

See the [Skills System](skills.md) documentation for details.

## IDE Integration

MothX can be integrated into your IDE via the Agent Client Protocol (ACP):

### VS Code

Add to `settings.json`:
```json
{
  "acp.agents": {
    "mothx": {
      "command": "mothx",
      "args": ["acp", "--mode", "agent", "--multi-agent"]
    }
  }
}
```

### JetBrains IDEs

Navigate to `Settings → Tools → ACP Agents` and add:
- **Name**: MothX
- **Command**: `mothx`
- **Arguments**: `acp --mode agent`

See the [ACP Protocol](acp.md) documentation for details.

## Troubleshooting

If something doesn't work, run the built-in diagnostics:

```bash
mothx doctor
```

This checks your environment, config files, providers, sandbox, MCP, sessions, skills, and context files, and reports any issues.

## Next Steps

- Read the [Configuration Guide](configuration.md) to customize settings
- Check the [Tool Reference](tools.md) to learn about available tools
- Try [multi-agent mode](cli-reference.md#multi-agent-mode) for delegated investigation and cron command entry points
- Try [delegate mode](cli-reference.md#delegate-mode) for blocking single sub-agent investigation tasks
- Understand the [Security Model](security.md) to protect your system
- Explore the [Skills System](skills.md) to create reusable prompt snippets
- Set up [IDE Integration](acp.md) with VS Code or JetBrains
- Check out [Scenarios & Walkthroughs](scenarios.md) for practical usage examples

---

## Knowledge Bases

Source: https://mothx.net/en/knowledge-bases.md

# Knowledge Bases

A knowledge base is a Desktop/WebUI-managed, rebuildable index of a directory you
choose. It is not a chat attachment store, a general RAG path, or a special Agent
mode. The source directory is **read-only**: MothX never writes to it, and
deleting a knowledge base never deletes the source.

Knowledge bases are useful for "ask questions about this repository, docs tree,
or notes folder" while keeping the normal Agent Runtime and tools unchanged.

## Create a knowledge base

In Desktop or WebUI, choose **New Knowledge Base** and set:

| Field | Description |
|-------|-------------|
| `name` | Display name |
| `rootDir` | Absolute path to the source directory (read-only) |
| `preprocessProfile` | `documents`, `code`, `notes`, or `mixed` |
| `provider` / `model` | Model used by the bounded indexer Agent during scans |
| `mode` | Indexer run mode; unattended scans resolve to a safe unattended mode |
| `thinkingLevel` | Optional thinking level for the indexer |
| `schedule` | Desktop only: `manual`, `hourly`, `daily`, `weekly`, `monthly`, or a 5-field cron expression |
| `enabled` | Pause scheduling without deleting the base |
| `ignoreGlobs` | Optional glob patterns relative to the source root |

Profile file coverage:

- `documents`: Markdown, MDX, text, reStructuredText, AsciiDoc, HTML
- `code`: source and config files (Go, TS/JS, Python, Java, Rust, C/C++, C#, Ruby,
  PHP, Swift, Kotlin, SQL, JSON, YAML, TOML, XML, GraphQL, shell) plus Markdown
- `notes`: Markdown and text
- `mixed`: both document and code sets

PDF/Office files are not extracted deterministically in the first version. They
are reported as skipped/unsupported in discovery diagnostics, and an Agent may
still read them from the source directory with ordinary read-only tools. Binary,
oversized, or unreadable files are skipped rather than sent to the model.

Ignore rules combine the fixed directory list (`.git`, `.hg`, `.svn`, `.mothx`,
`node_modules`, `vendor`, `dist`, `build`, `coverage`, `.next`, `.vite`),
`ignoreGlobs`, and suggestions read from the source root's `.gitignore` and
`.mothxignore`. Discovery reports `discovered`, `ignored`, and `skipped` results
so a file is never silently excluded.

## Indexing

A scan is an ordinary Runtime Agent execution with a canonical durable Run. It:

1. Discovers and validates files inside the source root.
2. Applies ignore rules and records diagnostics.
3. Extracts deterministic text chunks and builds the graph/FTS snapshot.
4. Optionally runs the bounded indexer Agent to enrich the graph.
5. Publishes the finished snapshot atomically and makes it active.

If a rebuild fails or is cancelled, the previous active snapshot stays usable.
Manual and scheduled scans share the same background-job machinery and coalesce
so a trigger arriving during a scan becomes exactly one follow-up scan. Scheduled
scans use the shared Cron store; the Cron job is namespaced and is not exposed as
a user automation task.

Inspect **Index runs** for status, counts, diff summaries, and failure codes.
`clear` removes the active index while keeping the knowledge base configuration
and source directory.

## Querying from a session

A main session accesses a knowledge base only through a configured standard
Knowledge MCP server:

```bash
mothx knowledge-mcp serve --knowledge-base <id>
```

Register that command as an ordinary MCP server for the session. The server
exposes `search_knowledge_base`; the MCP allowlist is the authorization boundary.
Results are bounded reference data with file/chunk citations and uncertainty
metadata; they are untrusted tool output, not instructions.

There is no knowledge-specific Agent mode, prompt injection, renderer-side
pre-query, or separate query model. The Agent calls the MCP tool like any other
tool and reasons over the returned evidence.

```bash
mothx knowledge-mcp serve \
  --knowledge-base kb_123 \
  --knowledge-base kb_456
```

`--session-dir` overrides the session storage directory (defaults to
`settings.json`). See [`knowledge-mcp`](cli-reference.md#knowledge-mcp---knowledge-base-mcp-server).

## Management

Desktop management uses the capability-gated ACP projections below. WebUI uses
the equivalent Serve REST endpoints under `/api/knowledge-bases` instead:

- `mothx/manage/knowledge-bases/list|get|create|update|delete`
- `.../scan`, `.../status`, `.../query`, `.../mcp/apply`
- `.../runs/list`, `.../runs/get`, `.../sources/list`
- `.../schedule`, `.../clear`

`knowledgeRuns` and `knowledgeSources` feature keys gate run history and
file-level source browsing. Deleting a knowledge base removes its own database
and registration; it never removes or modifies the source directory.

## Storage

Each knowledge base has one private SQLite database:

```text
<sessionDir>/knowledge-bases/<id>.db
```

The configuration row, snapshots, files, chunks, graph nodes/edges, FTS index,
and evidence live inside that file. Canonical Runs and audit records stay in the
shared `sessions.db`.

The file is a rebuildable index, not a source of truth. Keep the source directory
backed up; the index can always be rebuilt.

## Security notes

- The source directory is read-only for indexing and querying.
- The Knowledge MCP allowlist determines which bases a session can query.
- Query results are size-bounded and must be treated as untrusted reference data.
- Indexer/Librarian agents may use ordinary read-only tools inside the source
  root only; `yolo` does not turn indexing into write, delete, network, or
  delegation access.
- `mothx pure` archives the shared sessions database but leaves
  `knowledge-bases/<id>.db` files in place.

---

## MothX Native Desktop Client

Source: https://mothx.net/en/native.md

# MothX Native Desktop Client

MothX Native is the **primary desktop client** for MothX. It is a pure-Go
application built with [MyGo](https://github.com/egoist/mygo)'s `ui` package:
every widget is drawn by the app itself — no HTML, no JavaScript, no webview,
no Electron. Like the deprecated Desktop client, it is a **pure ACP (Agent
Client Protocol) client**: it launches a `mothx acp` child over stdio and
speaks ACP v1 (newline-delimited JSON-RPC 2.0) plus the additive `mothx.dev`
extensions. Sessions, runs, settings, providers, skills, knowledge bases, and
every management surface stay Runtime-owned; Native only projects them.

> **Status:** Native replaces the Electron [Desktop client](desktop.md), which
> is deprecated. Release pages publish Native desktop artifacts automatically
> on version tags; Electron builds remain available only as manual
> compatibility builds during the migration window.

## Install

Download the asset for your platform from the release page
(`mothx-native-<version>-<platform>-<arch>`):

- **Linux amd64:** raw binary, `.deb`, `.tar.gz`, or `PKGBUILD`.
- **macOS universal:** `.dmg`.
- **Windows amd64:** portable `.exe` or `-setup.exe` installer.

Native needs a `mothx` runtime binary. It resolves, in order: the launch
argument `--mothx-bin`, the binary persisted in Settings → Runtime,
`MOTHX_BIN`, `PATH`, then the repository's `../bin/mothx` development
fallback. The persisted choice is client-shell launch state only; it is never
written to `settings.json`/`serve.json`. If a selected binary fails to start
or initialize, Native rolls back to the previous choice automatically.

Build from source instead:

```sh
make native-build        # bin-style stripped binary in native/build/
make native-dist         # package for the current platform
make native-dist-linux   # linux/amd64 (deb, tar.gz, PKGBUILD)
make native-dist-darwin  # darwin/universal
make native-dist-windows # windows/amd64
```

## What you get

- **Tasks:** project/recent/ungrouped sidebar with per-session menus, cursor
  pagination, pinning, project grouping, rename, fork, delete, and workdir
  changes; a paginated History view with search and scope filters.
- **Chat:** streaming markdown, reasoning with a live preview while collapsed,
  tool cards with input/diff/output, plan cards and a plan progress side panel
  (including the Runtime-provided plan title/note), inline approval/question
  cards with deadlines (multi-property elicitation forms render one field per
  schema property and answer as content keyed by property name), inline
  sub-agent lifecycle cards with a live running/total header count, structured
  error cards, inline images, artifact preview/save, full-transcript copy and
  export.
- **Composer:** mode, provider/model/thinking picker with capability badges,
  expert binding (replacement forks), sandbox/browser/web-search capabilities,
  attachments (workspace files as links, outside files and clipboard images
  embedded), slash commands, and a workspace menu backed by recent-directory
  history.
- **Pages:** Skills (command cards + SkillHub marketplace), Automation (cron),
  Library (knowledge-base status), each with page-level management dialogs.
- **Settings:** the full Desktop management surface — application defaults,
  providers, MCP, skills, SkillHub, experts, ACP workers, environment,
  channels + deliveries, memory, cron, serve, knowledge bases, stats — plus
  local Appearance (theme, language, home preset/logo/background with an
  app-wide or home-only scope), Runtime (connection, doctor, logs, binary
  choice), and About.
- **Collaboration:** isolated git worktrees, Router worker selection with
  read-only worker evidence, and the read-only sub-agent roster/transcript.
- **Shell:** light/dark/system theme, Chinese/English UI, toasts, background
  run caches per session, and background-approval attention badges.

Like Desktop, a fresh process gives the first draft a private
`~/MothX/mothx_projects_*` quick-start directory; explicitly picked directories
are remembered only as picker history. A **New Task** draft inherits no
directory: the shell asks for one when the task is created and asks again at
send time if it is still unset (cancelling keeps the draft). Until a directory
exists, the provider/model menu is projected from the provider catalog, exactly
as Desktop does before `draft-config-options` can resolve a cwd. Both are
presentation state in
`native-preferences.json` (theme, language, home appearance, runtime binary,
directory history) — never session or configuration authority.

## Migrating from Desktop

Nothing canonical moves: sessions, transcripts, providers, MCP servers,
skills, experts, knowledge bases, schedules, and channel configuration live in
the shared Runtime and appear in Native exactly as they did in Desktop (and in
the TUI/WebUI). Only Electron-local presentation state is left behind:

| Desktop (Electron) | Native |
|---|---|
| `desktop-store.json` theme/language | Settings → Appearance (re-pick once) |
| Home logo/background, opacity/blur/fit/position | Settings → Appearance, plus a new app-wide/home-only scope |
| Bundled vs. custom runtime binary | Settings → Runtime binary choice (with automatic rollback) |
| Last/recent workspace picker history | Remembered automatically in Native preferences |
| DevTools / local CDP debugging | Settings → Runtime diagnostics and ACP stderr log |

Feature-gated panels behave the same way: if a panel is missing, the runtime
did not advertise its feature key — update the runtime binary, not the shell.

## Troubleshooting

- **Linux:** Native draws its own window but still needs a display server
  (X11/Wayland). Headless hosts should use the TUI or `mothx serve` + Web UI.
- **Runtime does not start:** check Settings → Runtime for the resolved
  binary and origin; a failed custom-binary switch rolls back automatically.
- **Approval/question never resolves:** the Runtime decision timeouts
  (`MOTHX_ACP_PERMISSION_TIMEOUT` / `MOTHX_ACP_QUESTION_TIMEOUT`) apply
  unchanged; unrecoverable pending decisions are terminalized by the Runtime.

## Development

```sh
make native-dev    # run from source
make native-test   # transcript reducer + headless UI tests
make native-vet    # go vet + MyGo lifetime/goroutine checks
```

The headless tester renders every page offline; English scans fail on any
untranslated Chinese UI, and pixel probes pin the background layering.
## Code layout

`native/main.go` is only the entry point. The implementation lives in private
`internal/` packages: `internal/acp` (stdio JSON-RPC transport and wire payloads),
`internal/i18n`, `internal/icons`, `internal/kit` (shared palette/widgets), and
one package per Runtime-managed domain under `internal/feature/*` (providers,
skills, SkillHub, MCP, knowledge, experts, cron, channels, env, memory, stats,
serve, and ACP workers). `internal/desktop` is the composition shell for the app
lifecycle, session/run state, transcript/composer, task tree, History, worktree,
collaboration, and page layout. Its implementation is split by concern across
`app_*.go` (state/lifecycle, connection, session catalog and flow, composer,
decisions, settings) and `view_*.go` (root view, chrome, sidebar, pages, chat,
transcript, message cards, composer); the alias files keep the shell's feature
vocabulary thin, and `internal/feature/hosttest` provides the shared fake Host
for feature-package guard tests. Business packages never import the shell; the
shell implements the narrow `Host` interface each feature declares.

---

## Adding a New Provider

Source: https://mothx.net/en/provider-guide.md

# Adding a New Provider

This guide explains how to add support for a new LLM provider or vendor to MothX.

## Architecture Overview

MothX separates two concerns when adding provider support:

1. **Protocol Providers** — handle the wire protocol (OpenAI Chat Completions, Anthropic Messages, Google Gemini). These live in `internal/provider/openai/`, `internal/provider/anthropic/`, and `internal/provider/google/`.
2. **Vendor Adapters** — apply vendor-specific defaults (thinking format, cache control, default API) on top of a protocol provider. These live in `internal/provider/vendor_*.go`.

Most new providers only need a vendor adapter file. You only need a new protocol provider if the API wire format is fundamentally different from existing ones.

## Quick Start: Adding a Vendor Adapter

### Step 1: Create the vendor file

Create `internal/provider/vendor_<name>.go`:

```go
package provider

func init() {
    RegisterVendorAdapter(simpleVendorAdapter{
        name:           "my-vendor",
        domains:        []string{"api.myvendor.com"},
        thinkingFormat: "myvendor",  // optional
        defaultAPI:     "openai-chat", // optional
        cacheControl:   nil,          // optional: boolPtr(true) to enable
    })
}
```

### Step 2: Add tests (if needed)

Vendor adapters are tested through `vendor_test.go`. If your adapter has special behavior beyond the simple adapter, add a test case there.

That's it. The `init()` function registers the adapter automatically.

## Vendor Adapter Fields

| Field | Type | Description |
|-------|------|-------------|
| `name` | `string` | Unique vendor name (lowercase, e.g. `"deepseek"`, `"google-gemini"`) |
| `domains` | `[]string` | URL substrings for auto-detection from base URL |
| `thinkingFormat` | `string` | Thinking/reasoning format: `"deepseek"`, `"anthropic"`, `"openai"`, `"qwen"`, `"zai"`, `"xiaomi"`, etc. |
| `defaultAPI` | `string` | Default protocol: `"openai-chat"`, `"anthropic-messages"`, `"google-gemini"`, `"google-vertex"` |
| `cacheControl` | `*bool` | Enable/disable cache control. Use `boolPtr(true)` to enable. |

## How Vendor Detection Works

When a user configures a provider in `settings.json`:

```json
{
  "providers": {
    "my-provider": {
      "vendor": "my-vendor",
      "baseUrl": "https://api.myvendor.com/v1",
      "apiKey": "sk-...",
      "api": "openai-chat",
      "models": [
        { "id": "my-model", "name": "My Model", "contextWindow": 128000 }
      ]
    }
  },
  "defaultProvider": "my-provider",
  "defaultModel": "my-model"
}
```

`providers` is an object keyed by provider ID; use `baseUrl`/`apiKey`, not
`base_url`/`api_key`. A provider ID is the name you pass to `--provider`.

The resolution flow is:

1. **Explicit vendor field** — if `vendor` is set in config, use that adapter directly
2. **Base URL matching** — scan registered adapters' `domains` for a substring match
3. **Protocol fallback** — if the URL contains "anthropic", use `anthropic-messages`; otherwise `openai-chat`

### Example: Multiple Domain Aliases

Some vendors have multiple API domains:

```go
func init() {
    RegisterVendorAdapter(simpleVendorAdapter{
        name:    "my-vendor",
        domains: []string{"api.myvendor.com", "api.v2.myvendor.com"},
    })
}
```

### Example: Multiple Adapters per Vendor

When a vendor has distinct regional endpoints with different behavior:

```go
func init() {
    RegisterVendorAdapter(simpleVendorAdapter{
        name:           "myvendor-us",
        domains:        []string{"us.api.myvendor.com"},
        thinkingFormat: "myvendor",
    })
    RegisterVendorAdapter(simpleVendorAdapter{
        name:           "myvendor-eu",
        domains:        []string{"eu.api.myvendor.com"},
        thinkingFormat: "myvendor",
    })
}
```

## Protocol Provider Details

### OpenAI-Compatible (`openai-chat`)

Most vendors use this. The provider sends requests to `/chat/completions` with streaming SSE responses. Supports function calling, tool use, and structured outputs.

### OpenAI Responses (`openai-responses`)

For OpenAI's Responses API. Uses `POST /v1/responses` and supports streaming responses, native response-item replay, reasoning, structured output, hosted tools, and prompt-cache controls.

`responses.stateMode` controls how follow-up requests retain context: use `replay` for local history replay, `previous_response_id` to continue an upstream response lineage, or `conversation` with a provider conversation ID. With `responses.background: true`, `mothx serve` can submit supported work as a durable remote task, poll it, recover it after a server restart, and execute local function/custom tools as required.

### Anthropic-Compatible (`anthropic-messages`)

For Anthropic's Messages API. Uses `/v1/messages` with SSE streaming. Supports extended thinking and cache control.

### Google Gemini (`google-gemini`)

For Google's Generative Language API. Uses `streamGenerateContent` with SSE streaming.

### Google Vertex (`google-vertex`)

For Google Cloud Vertex AI. Similar to Gemini but with GCP authentication.

## When to Add a Protocol Provider

You need a new protocol provider only when:

- The API wire format is fundamentally different from OpenAI/Anthropic/Google
- The streaming protocol is not SSE-based
- Authentication requires a custom flow (e.g., OAuth2 with token refresh)

To add a protocol provider:

1. Create a new directory under `internal/provider/<name>/`
2. Implement the `Provider` interface:
   ```go
   type Provider interface {
       Chat(ctx context.Context, params ChatParams) <-chan StreamEvent
       Name() string
       Models() []*Model
       GetModel(id string) *Model
   }
   ```
3. Register a factory in `internal/provider/registry.go`:
   ```go
   func init() {
       Register("my-protocol", func(cfg *config.ProviderConfig) (Provider, error) {
           return myprovider.New(cfg)
       })
   }
   ```

## Testing

Run vendor adapter tests:

```bash
go test ./internal/provider/ -run TestVendor
```

Run the full provider test suite:

```bash
go test ./internal/provider/...
```

## Checklist

- [ ] Created `internal/provider/vendor_<name>.go`
- [ ] Vendor name is lowercase and unique
- [ ] `domains` list covers all known API endpoints
- [ ] `thinkingFormat` set if the vendor supports extended thinking
- [ ] `defaultAPI` set if the vendor uses a non-OpenAI protocol
- [ ] Tests pass: `go test ./internal/provider/...`
- [ ] No changes to `settings.json` schema needed (vendor adapters are transparent)

---

## 🚀 MothX 5-Minute Quick Start

Source: https://mothx.net/en/quick-start-tutorial.md

# 🚀 MothX 5-Minute Quick Start

> Skip the long docs — let's get you coding!

## Step 1: Install (30 seconds)

```bash
# Option 1: npm (recommended, auto-downloads correct binary)
npm install -g mothx-installer

# Option 2: PyPI
pipx install mothx-installer

# Option 3: One-line install (Linux/macOS)
curl -fsSL https://mothx.net/install.sh | bash
```

```bat
:: Option 4: One-line install (Windows Command Prompt)
curl.exe -fsSL https://mothx.net/install.bat -o install.bat && install.bat
```

```bash
# Option 5: Go install
go install github.com/oschina/mothx/cmd/mothx@latest
```

**Uninstall:**

```bash
# npm
npm uninstall -g mothx-installer

# PyPI
pipx uninstall mothx-installer

# Linux/macOS (one-line install)
curl -fsSL https://mothx.net/install.sh | bash -s -- --uninstall
```

## Step 2: Configure API Key (30 seconds)

```bash
# Set DeepSeek API key (default provider)
export DEEPSEEK_API_KEY=sk-...

# Or use OpenAI
export OPENAI_API_KEY=sk-...

# Or use Anthropic
export ANTHROPIC_API_KEY=sk-ant-...
```

## Step 3: Run! (10 seconds)

```bash
# Start interactive session
mothx

# Or ask directly
mothx -P "Hello, MothX!"
```

That's it — you're coding with AI!

---

## 🎮 Three Modes, Switch Anytime

| Mode | Command | Use Case |
|------|---------|----------|
| 🗒️ **Plan** | `mothx --mode plan` | Read-only analysis, safe exploration |
| 🔧 **Agent** | `mothx --mode agent` | Standard development |
| 🚀 **YOLO** | `mothx --mode yolo` | Full freedom, no restrictions (default) |

In interactive mode, press `Tab` or type `/mode plan|agent|yolo` to switch.

---

## 💡 Common Use Cases

### 📝 Code Generation
```bash
mothx -P "Write a Go HTTP server with RESTful API"
mothx -P "Create a Python scraper for news headlines"
mothx -P "Generate a React component with search box and list"
```

### 🔍 Code Understanding
```bash
mothx -P "Explain what main.go does"
mothx -P "What does this regex mean?"
mothx -P "Analyze the architecture of this project"
```

### 🛠️ Code Refactoring
```bash
mothx -P "Refactor this function to use generics"
mothx -P "Optimize this code for performance"
mothx -P "Split this class into smaller modules"
```

### 🧪 Test Generation
```bash
mothx -P "Write unit tests for UserService"
mothx -P "Generate integration test cases"
mothx -P "Write an end-to-end test"
```

### 📚 Documentation
```bash
mothx -P "Generate JSDoc comments for this function"
mothx -P "Write a README.md"
mothx -P "Generate API documentation"
```

---

## ⌨️ Keyboard Shortcuts

| Shortcut | Function |
|----------|----------|
| `Enter` | Submit prompt |
| `Alt+Enter` | New line |
| `Tab` | Switch mode |
| `Esc` | Abort current operation |
| `Ctrl+O` | Open tool details |
| `Ctrl+G` | Toggle simple/full event display (simple by default) |
| `Up/Down` | Browse history |
| `Ctrl+C` | Cancel/clear input |

---

## 🔧 Common Commands

```bash
/mode plan      # Switch to Plan mode
/mode agent     # Switch to Agent mode
/mode yolo      # Switch to YOLO mode
/model          # Show current model
/settings       # Configure defaults, including thinking level
/clear          # Clear conversation
/help           # Show help
/quit           # Exit
```

---

## 🎯 Real-World Examples

### Example 1: Create a New Project
```bash
mothx -P "Create an Express.js project with user auth and database connection"
```

### Example 2: Debug Code
```bash
mothx -P "This code throws TypeError: Cannot read property 'map' of undefined, help me fix it"
```

### Example 3: Code Review
```bash
mothx --mode plan "Review the code in current directory, find potential issues"
```

### Example 4: Generate Config Files
```bash
mothx -P "Generate a Docker Compose file with Node.js, PostgreSQL, and Redis"
```

### Example 5: Write Regex
```bash
mothx -P "Write a regex to match Chinese phone numbers"
```

---

## 🛡️ Safety Tips

- **Plan mode**: Read-only, won't modify files — great for exploration
- **Agent mode**: Read/write, but bash commands require approval (configurable whitelist)
- **YOLO mode**: Full freedom — use with caution!

By default, dangerous commands (like `rm -rf`, `sudo`) are blocked by the blacklist.

---

## 📱 Advanced Usage

### IDE Integration
```bash
# VS Code: Add to settings.json
{
  "acp.agents": {
    "mothx": {
      "command": "mothx",
      "args": ["acp", "--mode", "agent"]
    }
  }
}
```

### API Server
```bash
# Start OpenAI-compatible HTTP server
mothx serve
```

### Chatbot
```bash
# Deploy as WeChat/Feishu bot
mothx serve
```

---

## 🆘 Need Help?

```bash
# Run diagnostics
mothx doctor

# Show help
mothx --help

# Enable debug mode
mothx --debug
```

---

## 📖 More Resources

- [Full Documentation](../../README.md) — All features explained
- [Configuration Guide](configuration.md) — Customize settings
- [Tool Reference](tools.md) — All built-in tools
- [Scenarios & Walkthroughs](scenarios.md) — More real-world examples
- [FAQ](faq.md) — Common questions answered

---

<p align="center">
  <strong>🎉 Congratulations! You've mastered the basics of MothX.</strong><br>
  <strong>Now, start your AI coding journey!</strong>
</p>

---

## Scenarios & Walkthroughs

Source: https://mothx.net/en/scenarios.md

# Scenarios & Walkthroughs

This document demonstrates MothX's various usage modes through practical scenarios.

---

## Scenario 1: Daily Coding (Single Agent Mode)

The most basic usage — conversing with AI in the terminal for everyday development tasks.

### Setup

```bash
# Set API key
export DEEPSEEK_API_KEY=sk-...

# Enter project directory
cd ~/projects/myapp
```

### A: Code Explanation

```bash
$ mothx -P "explain the core logic of internal/agent/agent.go"
```

MothX will:
1. Load context files (`AGENTS.md`, `CLAUDE.md`)
2. Read the file with `read`
3. Explore related code with `ls`, `grep`
4. Output a structured explanation

### B: Bug Fix

```bash
$ mothx
```

```
> fix the null pointer error in handler.go

[Agent]
  📄 read("internal/handler.go", offset=45, limit=20)
  → Found: line 52 doesn't check if err is nil

  📝 edit("internal/handler.go", edits=[
    {oldText: "resp, _ := client.Do(req)",
     newText: "resp, err := client.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}"}
  ])
  → Edit successful

  🔧 bash("go build ./...")
  → Build passed

✅ Fixed: added error check at line 52
```

### C: Adding a New Feature

```
> add a /health endpoint to the HTTP handler

[Agent]
  📄 plan(title="Add /health endpoint", steps=[
    {title: "Read existing handler structure", status: "running"},
    {title: "Add health handler", status: "pending"},
    {title: "Register route", status: "pending"},
    {title: "Add tests", status: "pending"},
    {title: "Verify build", status: "pending"}
  ])

  📄 read("internal/server/routes.go")
  📝 edit(...)  # Add handler
  📝 edit(...)  # Register route
  🔧 bash("go test ./internal/server/ -run TestHealth")
  🔧 bash("go build ./...")

  📄 plan(..., steps=[..., {title: "Verify build", status: "done"}])

✅ Done: /health endpoint added and tested
```

### Mode Selection Guide

| Task | Recommended Mode | Command |
|------|-----------------|---------|
| Read code, learn project | `plan` | `mothx --mode plan` |
| Write code, fix bugs | `agent` | `mothx --mode agent` |
| Install deps, system ops | `yolo` (default) | `mothx` |

---

## Scenario 2: Non-Interactive Mode (CI/Script Integration)

Use MothX in CI pipelines or scripts.

### A: Code Review

```bash
# Review PR in CI
git diff main..feature | mothx -P "review this diff, point out potential issues"
```

### B: Automated Refactoring

```bash
# Batch refactoring
mothx -P "change all fmt.Errorf calls to use %w for error wrapping" --mode yolo
```

### C: Generate Documentation

```bash
# Generate README for a package
mothx -P "generate README.md for internal/cache package with usage examples" --mode yolo
```

---

## Scenario 3: Multi-Agent Mode (Complex Task Delegation)

Enable sub-agent tools with `--multi-agent` to split and execute complex tasks in parallel.

### Launch

```bash
$ mothx --multi-agent
```

### Scenario: Parallel Refactoring and Testing

```
> I need: 1) rename internal/cache to internal/store
>        2) ensure all tests pass at the same time

[Agent]
  🤖 subagent_spawn(task="Rename internal/cache to internal/store, update all import paths",
                     mode="agent",
                     tools=["read", "write", "edit", "bash", "grep", "find"])

  → Handle: "agent-1"

  🤖 subagent_spawn(task="Run full test suite, report failures",
                     mode="agent",
                     tools=["read", "bash", "grep", "find"])

  → Handle: "agent-2"

  ... wait for sub-agents ...

  🤖 subagent_status(handle="agent-1")
  → Status: completed
  → Result: "Renamed cache to store, updated 15 files' import paths"

  🤖 subagent_status(handle="agent-2")
  → Status: completed
  → Result: "3 tests failed: TestCacheGet, TestCacheSet, TestCacheDelete"

  🤖 subagent_send(handle="agent-1", message="Fix the 3 failing tests reported by agent-2")

  ... sub-agent continues ...

✅ Done: package renamed, all tests pass
```

### Sub-Agent Tools Summary

| Tool | Purpose |
|------|---------|
| `subagent_spawn` | Start sub-agent, returns handle |
| `subagent_status` | Query sub-agent status and results |
| `subagent_send` | Send follow-up instructions |
| `subagent_destroy` | Stop and clean up sub-agent |

### Multi-Agent + Cron Scheduling

```bash
# Daily code review
mothx serve cron add "daily-review" \
  "review the last 24 hours of git changes, output an issue report" \
  --schedule "@daily"
```

---

## Scenario 4: VS Code ACP Integration

Use MothX directly in VS Code as an AI coding assistant.

### Step 1: Install

```bash
npm install -g mothx-installer
```

### Step 2: Configure VS Code

Edit VS Code's `settings.json`:

```json
{
  "acp.agents": {
    "mothx": {
      "command": "mothx",
      "args": ["acp", "--mode", "agent", "--multi-agent"],
      "description": "MothX AI Assistant"
    }
  }
}
```

### Step 3: Use

1. Open your project in VS Code
2. Open the ACP panel (via extension)
3. Ask questions or request code changes directly

**Experience in VS Code:**

```
You: change ParseConfig in utils.go to support YAML format

MothX:
  [tool_call: read utils.go]
  [tool_call: edit utils.go]
  [tool_call: bash "go test ./..."]
  ✅ YAML support added, all tests pass
```

### ACP Mode Special Capabilities

| Capability | Description |
|------------|-------------|
| Session Management | IDE auto-manages session create/load/continue |
| Permission Requests | IDE popup for high-risk operations |
| MCP Integration | IDE can pass MCP server configs |
| Multi-Agent | Enable sub-agent tools via `--multi-agent` |

---

## Scenario 5: A2A Standalone Server Mode

Run MothX as an A2A server for other agents to call.

### A: Start Standalone A2A Server

```bash
# Initialize config
mothx a2a --init-a2a-config

# Edit a2a.json (optional)
vim ~/.mothx/a2a.json

# Start server
mothx a2a start --port 8093 --work-dir ~/projects/myapp
```

### B: Other Agents Call It

```bash
# Using mothx client
mothx a2a send "list all Go files in the project" --target http://localhost:8093

# Using curl
curl -X POST http://localhost:8093/a2a \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "message/send",
    "params": {
      "message": {
        "role": "user",
        "parts": [{"type": "text", "text": "run all tests"}]
      }
    },
    "id": 1
  }'

# Discover remote agent capabilities
mothx a2a discover http://localhost:8093
```

### C: A2A Server with Authentication

```bash
# Start with auth token
mothx a2a start --auth-token "my-secret-token-xxx"

# Client call with token
mothx a2a send "review main.go" \
  --target http://remote-server:8093 \
  --auth-token "my-secret-token-xxx"
```

---

## Scenario 6: A2A Master Mode (Cross-Machine Agent Dispatch)

Manage multiple remote A2A agents, letting the LLM automatically dispatch tasks.

### Architecture

```
┌─────────────────────────────────────────────────────────┐
│  Local (MothX + A2A Master)                         │
│                                                         │
│  mothx --enable-a2a-master                         │
│  ┌─────────────────────────────────────────────────┐   │
│  │  LLM auto-decides → a2a_dispatch tool            │   │
│  └─────────────────────────────────────────────────┘   │
│           │                   │                         │
│           ▼                   ▼                         │
│  ┌──────────────┐   ┌──────────────┐                   │
│  │ code-reviewer│   │  ci-agent    │                   │
│  │ 192.168.1.10 │   │ 192.168.1.20 │                   │
│  │ :8093        │   │ :8093        │                   │
│  └──────────────┘   └──────────────┘                   │
└─────────────────────────────────────────────────────────┘
```

### Step 1: Start A2A Servers on Remote Machines

**Machine A (Code Review Agent):**
```bash
# 192.168.1.10
mothx a2a start --port 8093 --work-dir ~/projects/shared
```

**Machine B (CI Agent):**
```bash
# 192.168.1.20
mothx a2a start --port 8093 --work-dir ~/ci-runner --auth-token "ci-secret"
```

### Step 2: Initialize Master Config Locally

```bash
# Generate sample config
mothx --init-a2a-master-config

# Edit a2a-list.json
vim ~/.mothx/a2a-list.json
```

```json
{
  "agents": [
    {
      "name": "code-reviewer",
      "url": "http://192.168.1.10:8093"
    },
    {
      "name": "ci-agent",
      "url": "http://192.168.1.20:8093",
      "auth_token": "ci-secret"
    }
  ]
}
```

### Step 3: Enable Master Mode

```bash
$ mothx --enable-a2a-master --verbose
```

```
A2A master mode enabled: 2 agents loaded from /home/user/.mothx/a2a-list.json

> review internal/handler.go for code quality, then run tests to make sure nothing breaks

[Agent]
  I'll dispatch tasks to both remote agents:

  🔧 a2a_dispatch(agent_name="code-reviewer",
                   message="Review internal/handler.go for code quality, focus on
                           error handling, performance, and security")

  → code-reviewer returns: "Found 3 issues: 1) Line 45 doesn't handle timeout..."

  🔧 a2a_dispatch(agent_name="ci-agent",
                   message="Run the full test suite, report results")

  → ci-agent returns: "47/47 tests passed, coverage 82%"

✅ Summary:
- Code review found 3 issues (details listed)
- All tests pass, coverage 82%
- Recommend fixing timeout handling on line 45 first
```

---

## Scenario 7: Serve Mode (HTTP API)

Run MothX as an OpenAI-compatible HTTP service for other applications to call.

### Initialize and Start

```bash
# Generate config template
mothx --init-serve

# Edit serve.json (set token, port, etc.)
vim ~/.mothx/serve.json

# Start serve
mothx serve --port 8080 --work-dir ~/projects/myapp
```

### Call It

```bash
# curl (OpenAI-compatible format)
curl http://localhost:8080/v1/chat/completions \
  -H "Authorization: Bearer your-token" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-v4-flash",
    "messages": [
      {"role": "user", "content": "explain this project architecture"}
    ]
  }'

# Python OpenAI SDK
from openai import OpenAI
client = OpenAI(base_url="http://localhost:8080/v1", api_key="your-token")
response = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=[{"role": "user", "content": "write an HTTP middleware"}]
)
```

---

## Scenario 8: Channels Messaging Serve

Connect MothX to WeChat/Feishu for unattended AI coding assistant.

### Start

```bash
# Configure serve.json
vim ~/.mothx/serve.json

# Start
mothx serve
```

### Typical Config

```json
{
  "server": { "port": 8090, "auth_token": "my-token" },
  "platforms": {
    "wechat": { "enabled": true },
    "feishu": { "enabled": true, "app_id": "...", "app_secret": "..." }
  },
  "default_mode": "yolo",
  "security": {
    "smart_approvals": true,
    "allowed_work_dirs": ["/srv/projects"]
  },
  "cron": { "enabled": true },
  "memory": { "enabled": true }
}
```

### Usage in Messaging Platform

```
User: /new
Bot:  New session created

User: add rate limiting middleware to the api package
Bot:  [executing...]
      ✅ Added rate limiting middleware with configurable requests/sec
      Modified: internal/api/middleware.go, internal/api/routes.go

User: run tests
Bot:  [running go test ./...]
      ✅ All passed (12/12)
```

---

## Scenario 9: Combined Modes (Multi-Tool Workflow)

Combine multiple modes for a complete development workflow.

### Example: Develop + Review + Deploy

```bash
# 1. Local development (TUI mode)
cd ~/projects/myapp
mothx --mode yolo

# 2. Pre-commit review (Plan mode)
mothx --mode plan "review all changes in git diff"

# 3. Post-push CI review (Serve mode)
# In CI script:
curl http://serve:8080/v1/chat/completions \
  -d '{"messages": [{"role": "user", "content": "review PR #42"}]}'

# 4. Scheduled security scan (Channels + Cron)
mothx serve cron add "security-scan" \
  "scan for security vulnerabilities and sensitive data leaks" \
  --schedule "@weekly"
```

---

## Quick Reference

| Scenario | Command |
|----------|---------|
| Daily coding | `mothx` |
| Read-only analysis | `mothx --mode plan` |
| Full access | `mothx --mode yolo` |
| Non-interactive | `mothx -P "..."` |
| Multi-agent | `mothx --multi-agent` |
| A2A server | `mothx a2a start` |
| A2A master | `mothx --enable-a2a-master` |
| HTTP API | `mothx serve` |
| Messaging channels | `mothx serve` |
| IDE integration | `mothx acp` |
| Continue session | `mothx -c` |
| Resume session | `mothx -r <id>` |
| Init serve config | `mothx --init-serve` |
| Init A2A config | `mothx a2a --init-a2a-config` |
| Init master config | `mothx --init-a2a-master-config` |

---

## SDK Integration Guide

Source: https://mothx.net/en/sdk.md

# SDK Integration Guide

MothX exposes a public Go package (`github.com/oschina/mothx/agent`) that lets you embed an AI coding agent into your own applications. This guide covers:

1. [Public Agent Package](#public-agent-package) — types, interfaces, and Builder API
2. [Implementing a Custom Provider](#implementing-a-custom-provider) — bring your own LLM backend
3. [Building and Running an Agent](#building-and-running-an-agent) — creating an agent and processing events
4. [Event Types](#event-types) — understanding the event stream
5. [Sub-Agent Mode](#sub-agent-mode) — delegating tasks to child agents

---

## Public Agent Package

Import path:

```go
import "github.com/oschina/mothx/agent"
```

This package contains **only public types and interfaces** — no internal dependencies. It defines:

| Type | Description |
|------|-------------|
| `Agent` | Interface for all agent implementations |
| `Provider` | Interface for LLM backends |
| `Builder` | Fluent API for creating Agent instances |
| `Event` / `EventType` | Agent event stream types |
| `Message` / `ContentBlock` | Conversation message types |
| `ChatParams` / `StreamEvent` | LLM request/response types |
| `ModelInfo` / `ModelCompat` | Model metadata and compatibility flags |
| `BaseProvider` | Embeddable helper for common Provider methods |

### Agent Interface

```go
type Agent interface {
    // ID returns the unique identifier for this agent.
    ID() AgentID

    // ParentID returns the parent agent's ID, or empty if top-level.
    ParentID() AgentID

    // Run processes a user message and streams events back.
    Run(ctx context.Context, userMsg string) <-chan Event

    // RunWithMessages processes with explicit message history.
    RunWithMessages(ctx context.Context, messages []Message) <-chan Event

    // Abort signals the agent to stop processing.
    Abort()

    // GetMessages returns a copy of the current message history.
    GetMessages() []Message

    // SetMessages replaces the message history.
    SetMessages(msgs []Message)

    // GetContext returns a copy of the current agent context.
    GetContext() *AgentContext

    // SetContext replaces the agent context.
    SetContext(ctx *AgentContext)

    // GetContextUsage returns the current context window usage.
    GetContextUsage() *ContextUsage

    // LoadHistoryMessages loads historical messages into agent context.
    LoadHistoryMessages(messages []Message)

    // HandleApprovalResponse processes the user's approval response.
    HandleApprovalResponse(approvalID string, approved bool)
}
```

### Provider Interface

```go
type Provider interface {
    // Chat sends a chat request and returns a channel of streaming events.
    Chat(ctx context.Context, params ChatParams) <-chan StreamEvent

    // Name returns the provider's name (e.g. "openai", "anthropic").
    Name() string

    // Models returns the list of available models.
    Models() []ModelInfo

    // GetModel returns a model by ID, or nil if not found.
    GetModel(id string) *ModelInfo
}
```

---

## Implementing a Custom Provider

To integrate your own LLM backend, implement the `agent.Provider` interface. Embed `agent.BaseProvider` for free `Name()` / `Models()` / `GetModel()` implementations:

```go
package mybackend

import (
    "context"

    "github.com/oschina/mothx/agent"
)

type MyProvider struct {
    agent.BaseProvider
    apiKey string
}

func NewMyProvider(apiKey string) *MyProvider {
    models := []agent.ModelInfo{
        {
            ID:            "my-model-v1",
            Name:          "My Model V1",
            Provider:      "mybackend",
            ContextWindow: 128000,
            MaxTokens:     8192,
        },
    }
    return &MyProvider{
        BaseProvider: agent.NewBaseProvider("mybackend", models),
        apiKey:       apiKey,
    }
}

func (p *MyProvider) Chat(ctx context.Context, params agent.ChatParams) <-chan agent.StreamEvent {
    ch := make(chan agent.StreamEvent, 100)

    go func() {
        defer close(ch)

        // 1. Send StreamStart
        ch <- agent.StreamEvent{Type: agent.StreamStart}

        // 2. Call your LLM API, stream responses...
        // For each text chunk:
        ch <- agent.StreamEvent{
            Type:      agent.StreamTextDelta,
            TextDelta: "Hello from my model!",
        }

        // 3. If model requests tool calls:
        // ch <- agent.StreamEvent{
        //     Type: agent.StreamToolCall,
        //     ToolCall: &agent.ToolCallBlock{
        //         ID:        "call_1",
        //         Name:      "bash",
        //         Arguments: []byte(`{"command":"ls"}`),
        //     },
        // }

        // 4. Report usage
        ch <- agent.StreamEvent{
            Type: agent.StreamUsage,
            Usage: &agent.Usage{
                InputTokens:  100,
                OutputTokens: 50,
                TotalTokens:  150,
            },
        }

        // 5. Signal completion
        ch <- agent.StreamEvent{
            Type:       agent.StreamDone,
            StopReason: "end_turn",
        }
    }()

    return ch
}
```

You can also use `WithProviderByName()` on the Builder to resolve a built-in provider by vendor name, base URL, API type, and API key without implementing `Provider` yourself:

```go
a, err := agent.NewBuilder().
    WithProviderByName("openai", "", "openai-chat", os.Getenv("OPENAI_API_KEY")).
    WithModel("gpt-4o").
    Build()
```

---

## Building and Running an Agent

Use the `Builder` fluent API to create an agent:

```go
package main

import (
    "context"
    "fmt"
    "os"

    "github.com/oschina/mothx/agent"
    _ "github.com/oschina/mothx/internal/agent" // register internal builder
)

func main() {
    a, err := agent.NewBuilder().
        WithProvider(mybackend.NewMyProvider(os.Getenv("MY_API_KEY"))).
        WithModel("my-model-v1").
        WithMode("agent").                          // "plan", "agent", or "yolo"
        WithWorkDir("/home/user/project").
        WithThinkingLevel(agent.ThinkingMedium).
        WithMaxTokens(16384).
        WithMaxIterations(400).
        WithToolExecutionMode("parallel").           // "parallel" or "sequential"
        WithMaxToolConcurrency(10).
        WithSystemPromptExtra("Focus on Go code.").
        WithCompaction(true, 16384).
        WithApprovalHandler(func(toolCallID, toolName string, args map[string]any) bool {
            fmt.Printf("Approve %s? [y/n] ", toolName)
            var input string
            fmt.Scanln(&input)
            return input == "y"
        }).
        Build()
    if err != nil {
        panic(err)
    }

    ctx := context.Background()
    events := a.Run(ctx, "List all Go files in this project")

    for event := range events {
        switch event.Type {
        case agent.EventTextDelta:
            fmt.Print(event.TextDelta)
        case agent.EventThinkDelta:
            // thinking content (optional)
        case agent.EventToolCall:
            fmt.Printf("\n[tool: %s]\n", event.ToolCall.Name)
        case agent.EventToolExecutionEnd:
            fmt.Printf("[result: %s]\n", truncate(event.ToolResult, 200))
        case agent.EventToolApprovalRequest:
            // Handle approval (see Builder.WithApprovalHandler)
        case agent.EventRunFinished:
            switch event.Status {
            case agent.TaskSuccess:
                fmt.Printf("\n--- Done (reason: %s) ---\n", event.StopReason)
            case agent.TaskCanceled:
                fmt.Fprintln(os.Stderr, "Canceled")
            default:
                fmt.Fprintf(os.Stderr, "Run ended with status %s: %v\n", event.Status, event.Error)
            }
        // EventDone and EventError are legacy compatibility events.
        }
    }
}

func truncate(s string, n int) string {
    if len(s) > n {
        return s[:n] + "..."
    }
    return s
}
```

### Builder Options

| Method | Default | Description |
|--------|---------|-------------|
| `WithProvider(p)` | *required* | LLM provider |
| `WithProviderByName(vendor, baseURL, api, apiKey)` | — | Resolve built-in provider |
| `WithModel(id)` | first model | Model ID |
| `WithMode(mode)` | `"yolo"` | `"plan"` / `"agent"` / `"yolo"` / `"os"` |
| `WithWorkDir(dir)` | `os.Getwd()` | Working directory |
| `WithThinkingLevel(level)` | `ThinkingMedium` | `Off` / `Minimal` / `Low` / `Medium` / `High` / `XHigh` |
| `WithMaxTokens(n)` | `16384` | Max output tokens |
| `WithMaxIterations(n)` | `400` | Safety limit for loop iterations |
| `WithToolExecutionMode(m)` | `"parallel"` | `"parallel"` / `"sequential"` |
| `WithMaxToolConcurrency(n)` | `10` | Maximum local tool calls in flight per tool-call batch; `1` is serial |
| `WithTools(names)` | all | Filter available tools |
| `WithSystemPromptExtra(s)` | `""` | Extra system prompt context |
| `WithSandbox(bool)` | `false` | Enable sandbox isolation |
| `WithSessionDir(dir)` | `~/.mothx/sessions` | Session persistence |
| `WithCompaction(enabled, reserve)` | `true, 16384` | Context compaction settings |
| `WithMultiAgent(bool)` | `false` | Enable sub-agent tools |
| `WithDelegateMode(bool)` | `false` | Enable blocking single sub-agent delegation |
| `WithExternalTools(tools...)` | none | Register host-provided custom tools |
| `WithoutBuiltinTools()` | false | Disable all built-in coding tools (pair with `WithExternalTools`) |
| `WithApprovalHandler(fn)` | nil | Custom tool approval callback |

---

## Event Types

The `Event` stream follows the agent lifecycle:

```
EventAgentStart
  └─ EventTurnStart
       ├─ EventTextDelta (streaming text)
       ├─ EventThinkDelta (streaming thinking)
       ├─ EventToolCall (tool requested)
       ├─ EventToolExecutionStart → EventToolExecutionEnd
       ├─ EventToolResult
       ├─ EventToolApprovalRequest → EventToolApprovalResponse
       ├─ EventPlanUpdate
       └─ EventUsage
  └─ EventTurnEnd
  └─ ... (more turns if tool calls trigger continuation)
  └─ EventRunFinished   ← single canonical terminal event (Status)
  └─ EventDone / EventError  ← legacy compatibility, emitted after EventRunFinished
EventAgentEnd
```

Exactly one `EventRunFinished` is emitted per run, before any legacy terminal
event and before `EventAgentEnd`. Its `Status` is the single source of truth
for the task outcome:

| TaskStatus | Meaning |
|------------|---------|
| `success` | Run completed normally and achieved its objective |
| `incomplete` | Run stopped before achieving its objective (output/context limits, max iterations, stuck detection) without a hard error |
| `failed` | Run terminated due to an error (`Error` carries the detail) |
| `canceled` | Run was canceled by the user, a timeout, or context cancellation |

Consumers should classify results from `EventRunFinished.Status` and must not
treat a closed event channel without a terminal event as success.

| EventType | Key Fields | Description |
|-----------|------------|-------------|
| `EventAgentStart` | — | Agent begins processing |
| `EventAgentEnd` | `Messages` | Agent finished, final message history |
| `EventTurnStart` | — | New LLM turn begins |
| `EventTurnEnd` | `TurnMessage`, `ContextUsage` | Turn completed |
| `EventTextDelta` | `TextDelta` | Incremental text from LLM |
| `EventThinkDelta` | `ThinkDelta` | Incremental thinking from LLM |
| `EventToolCall` | `ToolCall`, `ToolArgs` | LLM requests a tool call |
| `EventToolExecutionStart` | `ToolCallID`, `ToolName`, `ToolArgs` | Tool execution begins |
| `EventToolExecutionEnd` | `ToolCallID`, `ToolResult`, `ToolDiff`, `ToolError` | Tool execution completed |
| `EventToolResult` | `ToolCallID`, `ToolResult` | Tool result recorded |
| `EventToolApprovalRequest` | `ApprovalID`, `ApprovalTool`, `ApprovalArgs` | Tool needs user approval |
| `EventPlanUpdate` | `Plan` | Structured task plan update |
| `EventUsage` | `Usage`, `ContextUsage` | Token usage report |
| `EventDone` | `StopReason`, `Usage` | Agent loop completed (legacy; prefer `EventRunFinished.Status`) |
| `EventError` | `Error`, `StopReason` | Error occurred (legacy; prefer `EventRunFinished.Status`) |
| `EventRunFinished` | `Status`, `StopReason`, `Usage`, `Error`, `Attachments`, `ContextUsage` | Single canonical terminal event; `Status` is `success` / `incomplete` / `failed` / `canceled` |
| `EventCompactionStart/End` | `StatusMessage` | Context compaction lifecycle |

---

## Sub-Agent Mode

Sub-agent mode allows the main agent to delegate bounded, independent subtasks to child agents running in parallel. Enable it via CLI (`--multi-agent`) or SDK (`WithMultiAgent(true)`).

### Architecture Overview

```
┌─────────────────────────────────────────────────┐
│                 Main Agent                       │
│  - Full system prompt, tools, context           │
│  - Orchestrator role                             │
│  - Has subagent_* tools                         │
├─────────────────────────────────────────────────┤
│         AgentManager                             │
│   ┌──────────┐  ┌──────────┐  ┌──────────┐     │
│   │ SubAgent │  │ SubAgent │  │ SubAgent │     │
│   │    #1    │  │    #2    │  │    #3    │     │
│   │ (search) │  │ (review) │  │ (test)   │     │
│   └──────────┘  └──────────┘  └──────────┘     │
│         ↑            ↑             ↑             │
│     Isolated     Isolated      Isolated          │
│     context,     context,      context,          │
│     registry,    registry,     registry,         │
│     session      session       session           │
└─────────────────────────────────────────────────┘
```

### Key Components

| Component | Package | Description |
|-----------|---------|-------------|
| `AgentManager` | `internal/agent` | Manages lifecycle of all agent instances, tracks parent/child relationships, enforces policies |
| `AgentFactory` | `internal/agent` | Creates agents with consistent configuration and isolated tool registries |
| `EventRouter` | `internal/agent` | Routes events by `AgentID` to agent-specific or global handlers |
| `SubAgentPolicy` | `internal/agent` | Security constraints: max children (5), allowed modes, timeout per agent (10min) |
| `subagent_*` tools | `internal/agent` | Tools the main agent uses to spawn/manage sub-agents |

### Sub-Agent Tools

When multi-agent mode is enabled, the main agent gets four tools:

#### `subagent_spawn`

Create and start a sub-agent for a bounded task.

```json
{
  "task": "Search for all usages of the deprecated function X in src/",
  "mode": "agent",
  "work_dir": "/home/user/project",
  "tools": ["read", "grep", "find", "ls"],
  "max_iterations": 100,
  "system_prompt_extra": "Focus only on the src/ directory"
}
```

Returns a handle for polling:

```json
{
  "handle": "agent-1",
  "status": "running",
  "timeout": "10m0s"
}
```

#### `subagent_status`

Check a sub-agent's status and get results:

```json
{
  "handle": "agent-1"
}
```

Returns:

```json
{
  "handle": "agent-1",
  "status": "done",
  "message_count": 12,
  "last_response": "Found 3 usages of function X: ...",
  "updated_at": "2025-05-28T10:30:00Z"
}
```

Possible status values: `"ready"`, `"running"`, `"done"`, `"error"`.

#### `subagent_send`

Send a follow-up message to a running sub-agent:

```json
{
  "handle": "agent-1",
  "message": "Also check the test/ directory"
}
```

#### `subagent_destroy`

Destroy a finished sub-agent and release resources:

```json
{
  "handle": "agent-1"
}
```

### Sub-Agent Policy and Constraints

| Constraint | Default | Description |
|------------|---------|-------------|
| Max children | 5 | Maximum concurrent sub-agents per parent |
| Allowed modes | `["plan", "agent", "yolo"]` | Sub-agents default to the parent mode, then `yolo` |
| Timeout per agent | 10 minutes | Each sub-agent has an independent timeout |
| Total timeout | 30 minutes | Global timeout for all sub-agents |
| Nesting | Disabled | Sub-agents **cannot** spawn their own sub-agents |
| Sandbox | Inherited | Sub-agents inherit the parent's sandbox configuration |

### Sub-Agent Isolation

Each sub-agent runs with **fully isolated state**:

- **Own tool registry** — independent `tools.Registry` with its own `workDir`, `Sandbox`, and `JobManager`
- **Own message history** — separate conversation context
- **Own session** — independent session storage
- **Filtered tools** — `subagent_*` tools are removed from sub-agent registries to prevent nesting
- **Extra context** — includes `SubAgentOperatingContract` instructing the sub-agent to stay within scope

### SDK Usage: Enabling Multi-Agent

```go
a, err := agent.NewBuilder().
    WithProvider(myProvider).
    WithModel("claude-sonnet-4-20250514").
    WithMode("agent").
    WithMultiAgent(true). // Enable sub-agent tools
    Build()
```

When `WithMultiAgent(true)` is set, the agent's system prompt includes the sub-agent orchestration instructions and the `subagent_spawn/status/send/destroy` tools become available.

### Event Routing with Sub-Agents

Events from sub-agents carry the sub-agent's `AgentID`. Use the `EventRouter` to dispatch events to the right handler:

```go
// Internal usage example (for reference)
router := agent.NewEventRouter()

// Register handler for a specific agent
router.RegisterAgent("agent-1", agent.RouterEventHandlerFunc(func(e agent.Event) error {
    fmt.Printf("[%s] %v\n", e.AgentID, e.Type)
    return nil
}))

// Register global handler for all agents
router.RegisterGlobal(agent.RouterEventHandlerFunc(func(e agent.Event) error {
    // Log all events across all agents
    return nil
}))
```

### Best Practices for Sub-Agents

1. **Spawn for independent work** — Sub-agents are ideal for parallel code search, review, testing, or investigation tasks that don't depend on each other.
2. **Give clear scope** — Each sub-agent task should include: what to do, where to look, what to produce, and when to stop.
3. **Limit tools** — Restrict tools to what the task needs (e.g., read-only tools for search tasks).
4. **Poll and verify** — Don't trust sub-agent results blindly. Use `subagent_status` to check, then verify important claims.
5. **Clean up** — Always `subagent_destroy` finished agents to release resources.
6. **Avoid over-delegation** — Small, sequential, or highly stateful work is better done inline.

---

## External Tools (Embedding)

When embedding MothX in your own application, you can expose host-provided capabilities to the agent alongside (or instead of) the built-in coding tools.

### ExternalTool Interface

```go
// ExternalTool is implemented by embedding applications to expose custom tools.
type ExternalTool interface {
    Name() string
    Description() string
    Parameters() json.RawMessage
    Execute(ctx context.Context, params map[string]any) (*ExternalToolResult, error)
}
```

### ExternalToolResult

```go
type ExternalToolResult struct {
    Text     string          // Plain text result
    Error    string          // Error message (if any)
    Contents []ContentBlock  // Optional rich content blocks
}
```

### Registering External Tools

```go
import (
    "github.com/oschina/mothx/agent"
    _ "github.com/oschina/mothx/bootstrap" // required for embedding
)

a, err := agent.NewBuilder().
    WithProvider(myProvider).
    WithModel("my-model").
    WithExternalTools(myDatabaseTool, myAPITool).  // Register custom tools
    Build()
```

You can also disable all built-in tools and use only host-provided tools:

```go
a, err := agent.NewBuilder().
    WithProvider(myProvider).
    WithModel("my-model").
    WithoutBuiltinTools().           // Disable read, write, bash, etc.
    WithExternalTools(myCustomTool). // Only custom tools
    Build()
```

### System Prompt Contributions

Optionally implement `ExternalToolPromptInfo` to contribute system-prompt hints:

```go
type ExternalToolPromptInfo interface {
    PromptSnippet() string     // Short context about the tool
    PromptGuidelines() string  // Usage guidelines for the LLM
}
```

### Bootstrap Package

External modules must blank-import the `bootstrap` package once to register the internal builder and provider resolution hooks (since internal packages cannot be imported directly):

```go
import _ "github.com/oschina/mothx/bootstrap"
```

### Approval Forwarding

Sub-agent tool calls that require approval (e.g., `bash` in agent mode) are forwarded to the parent agent's event channel. The parent TUI or approval handler sees `EventToolApprovalRequest` events with the sub-agent's `AgentID`, allowing the user to approve/deny tool calls across all agents from a single interface.

---

## Internal Architecture Reference

For developers who need to understand the internal wiring:

```
agent/                          # Public package (import this)
  ├── types.go                  # Agent, Message, Event types
  ├── provider.go               # Provider, ChatParams, StreamEvent types
  └── builder.go                # Builder API → calls buildInternal

internal/agent/                 # Internal implementation
  ├── agent.go                  # Core agent loop
  ├── factory.go                # AgentFactory (creates agents with isolated registries)
  │   └── init() { SetBuilderFunc(buildFromPublicBuilder) }
  ├── bridge.go                 # Type converters (public ↔ internal)
  │   ├── ProviderAdapter       # Wraps public Provider → internal
  │   └── AgentAdapter          # Wraps internal Agent → public
  ├── manager.go                # AgentManager (lifecycle, parent/child tracking)
  ├── subagent.go               # subagent_spawn/status/send/destroy tools
  ├── router.go                 # EventRouter (per-agent + global dispatch)
  └── system_prompt.go          # System prompt builder
```

The bridge layer in `internal/agent/bridge.go` converts between public and internal types automatically:

- `agent.Builder.Build()` → calls `buildFromPublicBuilder()` → creates internal `Agent` → wraps in `AgentAdapter` → returns `agent.Agent`
- Public `Provider` → `ProviderAdapter` → internal `provider.Provider`
- Internal `Event` → `EventToPublic()` → public `agent.Event`
- Internal `Message` → `MessageToPublic()` → public `agent.Message` (and vice versa)

---

## Security & Sandbox

Source: https://mothx.net/en/security.md

# Security & Sandbox

MothX implements Linux process-level sandbox isolation through bubblewrap (bwrap) to protect system security.

## Sandbox Overview

### What is a Sandbox

A sandbox is a security mechanism that restricts a program's file system and network access permissions.

```
┌─────────────────────────────────────────────────────────────┐
│                     Sandbox Overview                         │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  ┌─────────────────────────────────────────────────────────┐│
│  │                  Sandboxed Process                      ││
│  │                                                          ││
│  │   Project Directory                                      ││
│  │   ┌─────────────────────────────────────────────────┐   ││
│  │   │  RW/RO access                                   │   ││
│  │   └─────────────────────────────────────────────────┘   ││
│  │                                                          ││
│  │   System Directories                                     ││
│  │   ┌─────────────────────────────────────────────────┐   ││
│  │   │  RO access only                                 │   ││
│  │   └─────────────────────────────────────────────────┘   ││
│  │                                                          ││
│  │   Network                                                ││
│  │   ┌─────────────────────────────────────────────────┐   ││
│  │   │  Blocked (standard/strict)                      │   ││
│  │   └─────────────────────────────────────────────────┘   ││
│  │                                                          ││
│  └─────────────────────────────────────────────────────────┘│
│                                                              │
└─────────────────────────────────────────────────────────────┘
```

## Sandbox Levels

| Level | Mode | File System | Network | Use Case |
|-------|------|------------|---------|----------|
| **none** | YOLO | Full access | Allowed | System administration, network operations |
| **standard** | Agent | Project R/W, System R/O | Disabled | Daily development |
| **strict** | Plan | Project R/O, System R/O | Disabled | Code review, analysis |

### Detailed Comparison

| Feature | none | standard | strict |
|---------|------|----------|--------|
| Read project files | ✓ | ✓ | ✓ |
| Write project files | ✓ | ✓ | ✗ |
| Read system files | ✓ | ✓ | ✓ |
| Write system files | ✓ | ✗ | ✗ |
| Network access | ✓ | ✗ | ✗ |
| Install packages | ✓ | ✗ | ✗ |
| Modify configuration | ✓ | ✗ | ✗ |

## Modes and Sandboxes

### Plan Mode (Strict Sandbox)

**Purpose:** Read-only analysis and planning

```bash
mothx --mode plan
mothx -M plan
```

**Features:**
- Project directory: Read-only
- System directory: Read-only
- Network: Disabled

**Use Cases:**
- Code review
- Project analysis
- Learning codebase
- Creating development plans

### Agent Mode (Standard Sandbox)

**Purpose:** Standard development tasks

```bash
mothx --mode agent --sandbox
mothx -M agent --sandbox
```

**Features:**
- Project directory: Read/write
- System directory: Read-only
- Network: Disabled

**Use Cases:**
- Writing code
- Modifying files
- Running tests
- Building projects

### YOLO Mode (No Sandbox)

**Purpose:** Full access

```bash
mothx --mode yolo
mothx -M yolo
```

**Features:**
- Project directory: Full access
- System directory: Full access
- Network: Allowed

**Use Cases:**
- System administration
- Installing packages
- Network requests
- Cross-project operations

**Risks:**
- May modify system files
- May execute dangerous commands
- May expose sensitive information

## Network Service Hardening

Serve, Channels, and A2A can expose HTTP/WebSocket entry points. Treat these services as remote code-execution surfaces whenever tools can run in `agent` or `yolo` mode.

- **Serve**: enable `auth.enabled` before exposing beyond loopback; startup warns when Serve listens beyond loopback in `yolo` mode without authentication.
- **A2A**: standalone A2A binds to `127.0.0.1` by default. Use `--host 0.0.0.0` only for intentional exposure, and configure an auth token.
- **Channels WebSocket**: send tokens with `Authorization: Bearer <token>` during the WebSocket handshake. Query-string tokens are accepted only for compatibility.
- **Working directories**: use `allowedWorkDirs` / `allowed_work_dirs` to restrict per-request or per-platform working directories.

## Trusted Config Shell Commands

Provider API keys can be loaded from shell commands with `apiKey: "!command"`, but this is disabled by default. Enable it only for trusted local config:

```bash
export VIBECODING_ALLOW_SHELL_CONFIG=1
```

Prefer environment-variable references such as `${DEEPSEEK_API_KEY}` for shared configs.

## Enabling Sandbox

### Command Line

```bash
# Enable sandbox
mothx --sandbox

# Disable sandbox
mothx --no-sandbox

# Combine with mode
mothx --sandbox --mode plan
```

### Configuration File

```json
{
  "sandbox": {
    "enabled": true,
    "level": "standard",
    "allowNetwork": false
  }
}
```

### Environment Variable

```bash
export VIBECODING_SANDBOX=true
```

## bubblewrap (bwrap)

### What is bwrap

bubblewrap is a lightweight Linux sandbox tool that uses Linux namespaces for process isolation.

### Installing bwrap

```bash
# Debian/Ubuntu
sudo apt install bubblewrap

# Fedora/RHEL
sudo dnf install bubblewrap

# Arch Linux
sudo pacman -S bubblewrap

# Verify installation
bwrap --version
```

### How bwrap Works

```
┌─────────────────────────────────────────────────────────────┐
│                    bwrap Namespaces                          │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  ┌─────────────────────────────────────────────────────────┐│
│  │                    Mount Namespace                       ││
│  │  /project    → RW/RO (depending on level)              ││
│  │  /usr        → RO                                       ││
│  │  /lib        → RO                                       ││
│  │  /etc        → RO                                       ││
│  └─────────────────────────────────────────────────────────┘│
│                                                              │
│  ┌─────────────────────────────────────────────────────────┐│
│  │                    Network Namespace                     ││
│  │  No network access (standard/strict)                    ││
│  └─────────────────────────────────────────────────────────┘│
│                                                              │
│  ┌─────────────────────────────────────────────────────────┐│
│  │                    PID Namespace                         ││
│  │  Process isolation                                      ││
│  └─────────────────────────────────────────────────────────┘│
│                                                              │
└─────────────────────────────────────────────────────────────┘
```

### bwrap Command Examples

```bash
# Standard sandbox
bwrap \
  --ro-bind /usr /usr \
  --ro-bind /lib /lib \
  --ro-bind /lib64 /lib64 \
  --ro-bind /bin /bin \
  --ro-bind /etc /etc \
  --bind /home/user/project /home/user/project \
  --tmpdir /tmp \
  --proc /proc \
  --dev /dev \
  --chdir /home/user/project \
  --unshare-net \
  --unshare-pid \
  --die-with-parent \
  -- sh -c "go build ./..."

# Strict sandbox
bwrap \
  --ro-bind /usr /usr \
  --ro-bind /lib /lib \
  --ro-bind /home/user/project /home/user/project \
  --tmpdir /tmp \
  --proc /proc \
  --dev /dev \
  --chdir /home/user/project \
  --unshare-net \
  --unshare-pid \
  --die-with-parent \
  -- sh -c "go vet ./..."
```

## Sandbox Configuration Details

### SandboxManager

```go
type Manager struct {
    level       Level
    workdir     string
    allowNetwork bool
}

type Level int

const (
    LevelNone     Level = iota  // Unrestricted
    LevelStandard               // Standard sandbox
    LevelStrict                 // Strict sandbox
)
```

### Configuration Options

```json
{
  "sandbox": {
    "enabled": true,
    "level": "standard",
    "allowNetwork": false,
    "allowDevices": false,
    "extraBinds": [
      "/path/to/extra:/mnt/extra"
    ]
  }
}
```

| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `enabled` | bool | false | Enable sandbox |
| `level` | string | "standard" | Sandbox level |
| `allowNetwork` | bool | false | Allow network |
| `allowDevices` | bool | false | Allow device access |
| `extraBinds` | []string | [] | Extra bind mounts |

## Security Best Practices

### 1. Enable Sandbox by Default

```bash
# Set alias in shell configuration
alias mothx='mothx --sandbox'
```

### 2. Choose Mode Based on Task

| Task | Recommended Mode | Reason |
|------|------------------|--------|
| Reading code | Plan | Read-only, safest |
| Modifying code | Agent | Project R/W, no network |
| Running tests | Agent | Needs execution permission |
| Installing dependencies | YOLO | Needs network |
| System administration | YOLO | Needs full permissions |

### 3. Review High-Risk Operations

The following operations should be reviewed by humans:

- Deleting files
- Modifying system configuration
- Executing unknown scripts
- Accessing sensitive data

### 4. Use Version Control

```bash
# Commit regularly
git add .
git commit -m "save progress"

# Use branches
git checkout -b feature/new-feature
```

### 5. Limit Project Directory

```bash
# Run from project root directory
cd /home/user/project
mothx --sandbox
```

## Sandbox Limitations

### Unsupported Operations

| Operation | none | standard | strict |
|-----------|------|----------|--------|
| Install system software | ✓ | ✗ | ✗ |
| Access network | ✓ | ✗ | ✗ |
| Modify system files | ✓ | ✗ | ✗ |
| Access other projects | ✓ | ✗ | ✗ |
| Docker operations | ✓ | ✗ | ✗ |

### Performance Impact

- Startup time: ~10-50ms increase
- Memory overhead: Negligible
- I/O performance: Minimal impact

### Platform Support

| Platform | Support |
|----------|---------|
| Linux | ✓ Full support |
| macOS | ✗ Not supported |
| Windows | ✗ Not supported (WSL usable) |

## Security Risks

### Risks That Still Exist Even With Sandbox

1. **Project file corruption**: Agent mode can modify project files
2. **Symbolic link attacks**: Symbolic links in project may point outside
3. **Resource exhaustion**: May consume excessive CPU/memory
4. **Information leakage**: Project files may contain sensitive information

### Mitigation Measures

```bash
# 1. Use version control
git init
git add .
git commit -m "initial"

# 2. Regular backups
cp -r project project.backup

# 3. Limit resources
timeout 300 mothx --sandbox

# 4. Check symbolic links
find . -type l -ls
```

## Approval Mechanism

MothX uses a multi-layer approval system for Agent mode.

### How It Works

In Agent mode, executing bash commands goes through the following checks:

1. **Blacklist check (highest priority)**: Command prefix matches `bashBlacklist` → Always require approval, even if project allow rules match.
2. **Project allow rules**: Command matches `bashCommands` (exact) or `bashPrefixes` (prefix) in `.mothx/allow.json` → Auto-approve.
3. **Settings whitelist**: Command prefix matches `bashWhitelist` in `settings.json` → Auto-approve.
4. **Default behavior**: Non-whitelisted commands → Require user approval via the interactive dialog.

### Interactive Approval Dialog

When a command requires approval, the TUI displays a dialog with:

- **Approve Once** — Run the command this time only.
- **Deny** — Reject the command.
- **Always Allow Exact Command** — Persist the exact command to `.mothx/allow.json` and approve.
- **Always Allow Command Prefix** — Persist the command prefix (e.g. `go test `) to `.mothx/allow.json` and approve.

Navigation: ↑/↓ to move, Enter to select, y to approve, n to deny, Esc to abort.

### Project-Level Allow Rules (`allow.json`)

Project allow rules are stored in `.mothx/allow.json` and support:

- `bashCommands`: Exact command strings that auto-approve.
- `bashPrefixes`: Command prefixes that auto-approve. Trailing spaces are significant.
- `autoEdit`: Auto-approve write/edit tools (defaults to `true` when no file exists).
- `editPaths`: Glob patterns for auto-approve paths.

```json
{
  "bashCommands": ["make test"],
  "bashPrefixes": ["go test ", "go build "]
}
```

### Configuration Example

```json
{
  "approval": {
    "bashWhitelist": ["go ", "make ", "git ", "npm ", "yarn "],
    "bashBlacklist": ["rm -rf", "sudo"]
  }
}
```

### Default Whitelist

```json
[
  "go ",
  "make ",
  "git ",
  "npm ",
  "yarn ",
  "node ",
  "python ",
  "pip "
]
```

### Approval Flow Diagram

```
┌─────────────────────────────────────────────────────────────┐
│                    Approval Flow                             │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  Agent requests bash command execution                       │
│  │                                                           │
│  ▼                                                           │
│  Check mode                                                  │
│  ├─ Plan mode → Deny (read-only)                             │
│  ├─ Agent mode → Continue checking                           │
│  └─ YOLO mode → Auto-approve unless blacklisted              │
│                                                              │
│  Blacklist check (highest priority):                         │
│  ├─ Matches blacklist → Require approval                     │
│  └─ Otherwise continue                                       │
│                                                              │
│  In Agent mode:                                              │
│  ├─ Project allow.json matches → Auto-approve                │
│  ├─ Matches settings whitelist → Auto-approve                │
│  └─ Otherwise → Interactive approval dialog                  │
│                                                              │
└─────────────────────────────────────────────────────────────┘
```

### Security Recommendations

1. **Keep default whitelist**: Only allow common safe commands
2. **Add blacklist**: Add dangerous commands like `rm -rf`, `sudo` to blacklist
3. **Use project allow rules**: Prefer `.mothx/allow.json` over global whitelist for project-specific commands
4. **Regular review**: Check approval logs to understand Agent-executed commands
5. **Combine with sandbox**: Use `--sandbox` to limit file system access

## Audit and Logging

### Enable Debug Logging

```bash
mothx --debug
```

### View Executed Commands

In debug mode, all executed commands are output to stderr:

```
[DEBUG] Executing: go build ./...
[DEBUG] Sandbox: bwrap --ro-bind /usr /usr ...
[DEBUG] Exit code: 0
```

### Log Recording

```bash
# Save logs
mothx --debug 2>mothx.log

# Analyze logs
grep "Executing:" mothx.log
```

## Troubleshooting

### bwrap Not Installed

```
Error: bwrap: command not found
```

**Solution:**

```bash
# Install bwrap
sudo apt install bubblewrap

# Or disable sandbox
mothx --no-sandbox
```

### Permission Issues

```
Error: bwrap: Permission denied
```

**Solution:**

1. Check if bwrap is correctly installed
2. Confirm user has permission to execute bwrap
3. Check file system permissions

### Network Access Failure

```
Error: network is unreachable
```

**Solution:**

1. Use YOLO mode
2. Or configure `allowNetwork: true`

### File Access Failure

```
Error: Read-only file system
```

**Solution:**

1. Use Agent mode (standard)
2. Or use YOLO mode (none)
3. Check file permissions

## References

- [bubblewrap GitHub](https://github.com/containers/bubblewrap)
- [Linux Namespaces](https://man7.org/linux/man-pages/man7/namespaces.7.html)
- [seccomp](https://man7.org/linux/man-pages/man2/seccomp.2.html)
- [Security Best Practices](https://owasp.org/www-project-developer-guide/)

---

## Serve Mode

Source: https://mothx.net/en/serve.md

# Serve Mode

`mothx serve` is the only server entry point. It starts the unified runtime for:

- OpenAI-compatible `/v1/chat/completions` API
- Durable OpenAI Responses background-run management for providers configured with `api: "openai-responses"` and `responses.background: true`
- Web UI management panel (chat interface, session management, settings editor)
- WeChat, Feishu, WebSocket messaging channels
- Cron scheduled tasks, Memory persistent memory, Hooks
- Stats usage statistics dashboard
- Multi-Agent sub-agent support

```bash
# Start Serve (default 127.0.0.1:7872)
mothx serve

# Specify port and work directory
mothx serve --port 8080 --work-dir /path/to/project

# Bind to external interface (allow access from other machines)
mothx serve --port 0.0.0.0:8080 --work-dir /path/to/project

# Disable auth and bind to all interfaces for a trusted network
mothx serve --unsafe --work-dir /path/to/project

# Initialize configuration files
mothx serve init-config global   # generates ~/.mothx/serve.json
mothx serve init-config project  # generates .mothx/serve.json
`--unsafe` is an explicit high-risk mode: it disables authentication and changes the current process to listen on all interfaces. Do not use it on an untrusted network; prefer loopback plus Bearer-token authentication.

`/v1/chat/completions` accepts standard OpenAI Chat Completions fields and returns standard JSON/SSE data frames. VibeCoding-specific `x_*` request and response fields are not supported. WebUI session selection, runtime capabilities, skills, approvals, and run events use the structured `/api/...` endpoints and WebSocket streams instead.

## Configuration

Configuration lives in `serve.json`:

- Global: `~/.mothx/serve.json`
- Project: `.mothx/serve.json`
- Custom path: `mothx serve --config /path/to/serve.json`

The project config overlays the global config.

### Core Configuration Fields

```json
{
  "api": {
    "listen": "127.0.0.1:7872",
    "auth": {
      "enabled": true,
      "tokens": ["your-secret-token"]
    },
    "defaultWorkDir": "/path/to/project",
  },
  "features": {
    "multiAgent": true,
    "workflows": true
  },
  "artifact": false,
  "sandbox": {
    "enabled": false
  },
  "channels": {
    "artifact": false,
    "wechat": { "enabled": false },
    "feishu": { "enabled": false }
  },
  "webUI": {
    "enabled": true
  },
  "cron": {
    "enabled": true
  },
  "memory": {
    "path": ".mothx/memory.md"
  },
  "allowedWorkDirs": ["/path/to/project"],
  "agent": {
    "mode": "yolo"
  }
}
```

Artifact publishing is disabled by default. Top-level `artifact` controls WebUI/API sessions; `channels.artifact` independently controls WeChat and Feishu sessions.

### Configuration Hot-Reload

After saving settings via the Web UI, Serve automatically hot-reloads provider/model configuration without requiring a restart.

## Network Access

To allow access from other machines, bind Serve to an external interface with `--port 0.0.0.0:8080` or set `"listen": "0.0.0.0:8080"` in `serve.json`. Enable Bearer token auth before exposing Serve beyond loopback. For trusted local networks only, `--unsafe` disables auth and binds loopback/default listens to `0.0.0.0` for the current process.

When `api.auth.enabled` is true, the Web UI displays a login page. Enter any value from `api.auth.tokens` as its password. A successful login stores an HttpOnly, SameSite-Strict browser cookie; API clients can continue using `Authorization: Bearer <token>` unchanged.

## Security

Security is controlled by three independent layers:

1. **Bearer Token Auth**: `api.token` or `security.token`
2. **Work Directory Whitelist**: `api.allowedWorkDirs`
3. **Sandbox Isolation**: `sandbox.enabled` (bwrap)

## Web UI

Access `http://127.0.0.1:7872` to open the Web UI. When authentication is enabled, first sign in with an `api.auth.tokens` token. The Web UI provides:

- **Chat Interface**: SSE streaming output, tool call/result rendering, plan cards, and a compact composer config panel that merges the current model with `plan`/`agent`/`yolo`/`os` and Work/Code display modes. Submissions preserve persisted conversation history; optional images, session tool toggles, skills, and explicit mode can be sent with a run. Runtime mode and capability changes apply immediately from the server's authoritative response, while session-list refreshes remain best-effort. The composer reflects server-side queued/running states after reconnect.
- **Dynamic Workbench**: `/chat` supports session tabs, up to four split panes, menu/drag splitting, persisted layout, and a single-pane mobile projection. Every pane owns its composer, model selection, draft, approvals, and trajectory view. Panes render the canonical `sessionRunStates` projection directly, and an all-tabs overflow menu keeps every open session reachable. The workbench toolbar also opens a read-only Plan dock that projects the focused session's latest `plan` message without adding storage, a tool, or a backend endpoint. The legacy single-session fallback and its setting/query switch have been removed; events are always consumed by the same `session-stream` dispatcher.
- **Interactive Terminal**: when `/api/status` reports `features.terminal`, the workbench toolbar can open an interactive PTY for the focused session's cwd (xterm.js over WebSocket). The terminal is a local shell with the serve process user's privileges, is not protected by the sandbox, and inherits the full serve process environment; it creates no Run, writes no transcript, and takes no Runtime lease. It is available on a loopback listener, or on a non-loopback listener when auth is enabled with a token; an unauthenticated non-loopback listener returns `terminal_unsafe`. Because `--unsafe` binds all interfaces while disabling auth, it also disables the terminal: use a loopback listener (the `make ui-dev` backend now binds `127.0.0.1:7872` without `--unsafe`) or configure auth with a token when you need the terminal during development.
- **Git Changes Panel**: the workbench toolbar can open a resizable right-side Changes dock for the focused tab — a session tab resolves its persisted cwd, a draft tab uses its chosen directory. It projects branch, Staged / Unstaged / Untracked sections with per-file `+/-` stats, and a per-file unified diff through the read-only `GET /api/git/changes` and `GET /api/git/diff` endpoints (`sessionId` or `path`). The panel shells out to `git status`/`git diff` only: it creates no Run, never stages, commits, or mutates the repository, and re-reads automatically when a run reaches its terminal state.
- **Files Panel + Preview**: the workbench toolbar can open a resizable Files rail over the same focused-tab target. The tree lazy-loads one directory at a time via `GET /api/files/list` (relative paths only, traversal/symlink-escape rejected, 2000-entry cap), shows git change badges and ancestor-dir marks from `/api/git/changes`, remembers expansion per root in localStorage, and opens an in-panel text preview via `GET /api/files/content` (2 MiB cap, binary/invalid-UTF-8 detection, line numbers). Each row's "open with" menu is gated by `GET /api/files/openers` and posts allowlisted argv to `POST /api/files/open`: reveal in the system file manager (Finder `open -R` / Explorer `/select,` / `xdg-open`), open a new system terminal in the directory (`Terminal.app`, Windows Terminal, or a detected Linux emulator), or open VS Code/VSCodium/Cursor when their binaries or apps exist. "Open in web terminal" instead routes the browsed subdirectory into the existing terminal dock through the optional `cwd` field of `POST /api/terminals`, which must resolve inside the session cwd. **External launches share the terminal's transport gate** (`EffectiveTerminalEnabled`): available on a loopback listener, on non-loopback only with auth plus a real token, and disabled together with the terminal under `--unsafe`; the menu states why launches are unavailable when gated. All file listing, preview, and external-launch actions are read-only projections outside the Runtime: they create no Run, take no lease, and launchers never go through a shell string. Layering: `internal/workspacefiles` owns the only read-only listing/reading and path containment, `internal/workspaceopen` owns the only launcher table plus the `RootResolver`/`OpenerPolicy` contracts, and serve is a thin projection; ACP reuses the same two packages rather than duplicating logic (see migration debt #5 in the unification proposal).
- **Approval Center**: Review pending tool approvals, approve once or deny, persist command/path allow rules, and inspect the session approval audit history.
- **Session Management**: Pagination, keyboard shortcuts, historical sessions, runtime snapshots, capability toggles, and reconnect-safe approval state. Historical sessions are sorted by last-used time with the most recently replied-to session at the top; the session-management page shows each session's last reply time. Active runs remain protected after a page refresh until they reach a terminal state. `GET /api/sessions` is bounded: without `limit` it returns the first 100 sessions plus `total`, `limit`, `offset`, and `hasMore`, and `scope=active`/`/api/sessions/active` project only the in-memory session pool instead of loading all history.
- **Responses Background Runs**: When an `openai-responses` provider enables `responses.background`, Serve submits supported requests as remote background tasks, persists their response lineage and archived output, polls them through completion, resumes recoverable runs after restart, and executes local function/custom-tool calls. The authenticated run API supports `GET /api/responses/runs/{localRunID}?session_id={sessionID}` plus `cancel`, `reconnect`, and `abandon` actions; see [Configuration](configuration.md#responses-field).
- **Settings Editor**: Provider/Model configuration, Defaults, Web Search, MCP, Context Files, Compaction, Sandbox, Retry, Approval, Provider Config. Provider, app, and Serve configuration changes refresh related status and tool availability without restarting the server. MCP settings edit the global `mcp.json`; the chat toolbar exposes project-level MCP configuration for the active session.
- **DeepSeek Web Search fallback**: when enabled, the shared Runtime registers a local `web_search` tool backed by DeepSeek's official Search API or Tencent Yuanbao SearchPro (selectable with `webSearch.backend`) for providers without native hosted search. The DeepSeek backend also registers `web_fetch`. OpenAI Responses keeps its provider-native hosted web search, and Anthropic Messages uses its provider-native hosted search while `webSearch` is enabled; both take precedence over the local `web_search` function.
- **Channel Management**: WeChat QR login and Feishu configuration
- **WebSocket streams**: `/ws/runs` and `/ws/logs` are Serve event streams used by the Web UI; they are not a separate messaging channel
- **Settings**: Memory, WorkDir, Logs, SkillHub, environment, and MCP management are available in addition to provider and agent settings
- **Serve Config**: Features, API, Cron, Memory, Security, Agent, Hooks, Channels, Lobster Mode

### Terminal configuration

The optional `terminal` section of `serve.json` controls the interactive terminal; omitting it keeps the automatic policy (loopback enabled; non-loopback enabled only with configured auth tokens):

```json
{
  "terminal": {
    "enabled": null,
    "shell": "",
    "maxSessions": 8,
    "maxPerSession": 2,
    "scrollbackBytes": 1048576,
    "maxOutputBytesPerSec": 1048576,
    "allowedOrigins": []
  }
}
```

An empty `allowedOrigins` means strict same-origin; reverse proxies or custom front ends must list their origin explicitly. The terminal status bar continuously shows that the shell is outside the sandbox and inherits the serve process user/environment, warns that it shares the focused session's cwd with a possibly running Agent (with a stronger notice when the canonical execution snapshot is local or in another process), surfaces the placeholder-auth-token warning reported by `/api/status`, and reports server-side output backpressure instead of treating it as a disconnect. A page reload reattaches the detached shell recorded for that tab instead of leaking it and creating a second terminal; once the shell exits or the id is lost, Reconnect creates a fresh terminal. Browser cookie sessions receive no `terminalToken` in the create response; only auth-disabled or Bearer-authenticated clients get one for non-browser WebSocket attach. Serve logs terminal lifecycle metadata only (`terminal_created`/`terminal_exited`/`terminal_killed` with id, session, cwd, and exit code), never input or output. Disabling the terminal closes existing shells and rejects new WebSocket attaches. On Linux the shell carries `Pdeathsig`, so it is terminated if the serve process dies; on Windows the backend uses ConPTY (Windows 10 1809+ or Windows 11) and older systems report `terminal_unsupported`. The terminal shares the serve auth token: holding the token is equivalent to owning that user's shell. That is the access boundary, not a UI toggle; use a separate OS user or container when stronger isolation is required instead of trimming terminal environment variables or relying on the sandbox.

### Screenshots

**Chat Interface** — SSE streaming, tool call/result rendering, plan cards, and merged model/mode config:

![Web UI Chat](assets/image/webui-chat.webp)

**Session Management** — paginated history, runtime snapshots, capability toggles:

![Web UI Sessions](assets/image/webui-sessions.webp)

**Settings Editor** — Provider/Model, Defaults, Web Search, Compaction, Sandbox, Approval:

![Web UI Settings](assets/image/webui-settings.webp)

**Skills** — browse and load project/global skills:

![Web UI Skills](assets/image/webui-skills.webp)

**Cron** — scheduled task management:

![Web UI Cron](assets/image/webui-cron.webp)

The list shows user-authored tasks only. One Runtime-owned maintenance job (`mothx-maintenance:artifact-storage`, daily) runs in the same scheduler to reclaim unreferenced attachment storage; it is hidden from this view and from name lookup, and is re-created whenever the scheduler starts. See [`mothx pure`](cli-reference.md#pure---archive-the-sessions-database).


## Messaging Channels

### WeChat

- QR code login support (scan-to-authenticate)
- Login status polling with error handling
- API endpoint: `/api/channels/wechat/login`

### Feishu

- Supports appId/appSecret/workspace/allowedUsers configuration
- Automatic message routing and session persistence

### WebSocket event streams

The Web UI uses authenticated `/ws/runs` and `/ws/logs` streams for run events and logs. These endpoints are not configured as a standalone messaging channel.

## Stats Dashboard

The Serve Web UI exposes usage statistics at `/stats` (for example, `http://127.0.0.1:7872/stats`). The standalone `mothx stats` command is separate and defaults to `127.0.0.1:7878`.

![Web UI Stats](assets/image/webui-stats.webp)

## CLI Flags

| Flag | Description | Default |
|------|-------------|--------|
| `--port` | Listen address (host:port) | `127.0.0.1:7872` |
| `--work-dir` | Working directory | Current directory |
| `--config` | Configuration file path | `~/.mothx/serve.json` or `.mothx/serve.json` |
| `--web-ui-dir` | Web UI static assets directory | Built-in path |
| `--unsafe` | Disable auth and bind Serve to all interfaces | Disabled |
| `--debug` | Enable pprof profiling server | Disabled |

---

## Session Management

Source: https://mothx.net/en/sessions.md

# Session Management

MothX stores sessions in SQLite, supporting tree structure, branching, compaction, labels, and fast session lookup.

## Session Storage

### Storage Architecture

MothX's session architecture differs based on the execution mode:

1. **CLI / TUI / Serve Mode (Single Database + Virtual Handles)**
   All session metadata (session list, session IDs, CWD, timestamps) and all history messages/entries are stored entirely inside a single, unified SQLite database file `sessions.db` under `sessionDir`.
   In this mode, **no physical working directory subdirectories or per-session handle files are created on disk**. The `.db` paths displayed in the CLI/TUI (e.g., `~/.mothx/sessions/20260625-120000_abcd1234.db`) are **virtual paths** (handles) computed dynamically from the database metadata. They do not exist on the filesystem but are fully recognized, navigated, and deleted by the program.

2. **Serve Channels (Single Database + Physical Handles)**
   Unattended messaging channels store records in the single `sessions.db` database and additionally write physical subdirectory handle files containing the session ID (e.g., `20260625-120000_abcd1234.db`) under platform-specific or per-user paths on disk. This layout facilitates platform-specific mapping and lifecycle tracking.

### Storage Location Layout

```text
~/.mothx/sessions/
├── sessions.db                       # The unified SQLite database for all session entries and metadata
└── channels/                           # (Only present for messaging channels)
    └── wechat/user_123/active.db       # Channels platform-specific physical session handle
```

### Path Encoding

In scenarios requiring directory isolation (such as Channels), working directory paths are encoded with URL-safe base64 to avoid collisions and filesystem issues.

Examples:
- `/home/user/project` → `--L2hvbWUvdXNlci9wcm9qZWN0--`
- `/home/user/my.app` → a distinct encoded directory name

## SQLite Schema

Session state is stored in `sessions.db` using two core tables:

| Table | Purpose |
|-------|---------|
| `sessions` | Session metadata: ID, working directory, timestamp, parent session, schema version |
| `entries` | Ordered event log: messages, model changes, compactions, labels, and metadata entries |

Entries keep stable IDs and parent IDs so the conversation can be replayed as a tree and compacted safely.

### Entry Types

| Type | Description |
|------|-------------|
| `session` | Session metadata |
| `message` | User/assistant/tool messages |
| `model_change` | Model switch record |
| `thinking_level_change` | Thinking-level switch record |
| `compaction` | Context compression checkpoint |
| `custom` | Runtime-specific custom metadata entry |
| `custom_message` | Message payload created by an external or custom runtime |
| `session_info` | Display metadata such as session name |
| `branch_summary` | Branch switch summary |
| `label` | User-defined label |

### Durability and Write Performance

`sessions.db` runs in WAL mode with the durability level defaulting to the SQLite-recommended `synchronous(NORMAL)`: commits no longer fsync individually (syncing is concentrated at WAL checkpoints), which markedly lowers writer-lock contention and write latency when several processes (Serve, TUI, ACP, CLI) share one session directory. The semantics are:

- A process crash (kill -9, panic) loses nothing.
- An OS crash or power loss does not corrupt the database, but commits made since the last checkpoint (typically seconds of writes) may roll back; a missing run terminal state converges through the lease-expiry → orphan-recovery path, so a session never stays stuck as "running" forever.

Deployments sensitive to power loss (unstable power, some network drives) can restore the legacy per-commit fsync behavior with the `MOTHX_SQLITE_SYNCHRONOUS=FULL` environment variable; it takes effect per process, and mixed old/new processes sharing one database file is safe. Startup runs a SQLite `quick_check` before the session database is used. Very large databases can skip this fixed opening cost with `MOTHX_SQLITE_QUICK_CHECK=off`; `mothx doctor` still performs an on-demand, read-only integrity check and reports `sessions.integrity`. Session-storage maintenance (`maintenance.reclaimSessionStorage`) never deletes transcript messages: it only prunes completed/abandoned tool-execution idempotency records when `toolExecutionRetentionDays` is configured above `0`, optionally runs `VACUUM`, and backfills the derived search index and list display projections for up to 512 sessions per pass. With `--debug`, the `mothx_sqlite` metrics on the `/debug/vars` endpoint (busy-retry hits and backoff total, transaction begin count/total wait/slowest single wait plus bucket-approximated p50/p99, checkpoint attempt/failure and frame counts, per-database WAL size, and per-database connection-pool wait counters) and the `mothx_runtime_lease` metrics (lease fence-loss count and per-database heartbeat health) make cross-process writer contention and lease health observable. Full design and load-test matrix: `docs/proposal/sqlite-write-pressure-reduction-proposal.md`.

## Session Operations

### Create New Session

```go
sess := session.New(cwd, sessionDir)
if err := sess.Init(); err != nil {
    return err
}
```

### Continue Recent Session

```bash
mothx --continue
mothx -c
```

```go
sess, err := session.ContinueRecent(cwd, sessionDir)
```

### Resume Specific Session

```bash
# By session ID or unique prefix
mothx --resume abcd1234

# By session handle path
mothx --resume ~/.mothx/sessions/--encoded-working-directory--/20260625-120000_abcd1234.db
```

```go
sess, err := session.OpenByPathOrID(cwd, sessionDir, "abcd1234")
```

### TUI Session Picker

In interactive TUI mode, starting without `--continue`, `--resume`, or `--session` does not create an empty session immediately. The session is created when the first user message is sent.

Use `/sessions` to open the interactive session picker. It supports Up/Down navigation, Enter to switch, `n` to start fresh, `d` to delete the selected session, and Esc to close. Text commands are still available:

```bash
/sessions ls
/sessions set abcd1234
/sessions clear
/sessions del abcd1234
```

When an existing session is continued, resumed, or selected, its history is printed into the normal terminal scrollback.

### Web UI Session History

The Serve Web UI history list is sorted by last-used time in descending order, with the most recently replied-to session at the top. The Web UI session-management page also shows each session's last reply time for quickly locating recent conversations.

### Add Message

```go
_, err := sess.AppendMessage(provider.NewUserMessage("Hello"))
```

## Tree Structure

Session entries form a parent-linked tree:

```text
session-abcd1234
├── msg-001 (user: "Hello")
│   └── msg-002 (assistant: "Hi!")
│       └── msg-003 (user: "Tell me more")
└── msg-004 (user: "Different question")  # Branch point
    └── msg-005 (assistant: "...")
```

This supports exploring different directions, returning to previous points, and preserving alternate solutions.

## Session Compression

MothX records compaction checkpoints in SQLite. After compaction, replay state preserves per-message entry IDs and the compaction boundary (`firstKeptEntryID`). When a session is reloaded:

- Messages are trimmed to the correct compaction boundary
- The summary message is prepended automatically
- Subsequent messages keep their original entry IDs

Configure compaction in settings:

```json
{
  "compaction": {
    "enabled": true,
    "reserveTokens": 16384,
    "keepRecentTokens": 20000
  }
}
```

## Best Practices

### Regular Cleanup

Prefer the built-in `/sessions del <id>` command or the authenticated session API when deleting normal CLI, TUI, or Serve sessions. These interfaces remove the session records from the shared `sessions.db`; virtual handles do not require manual file deletion.

```bash
/sessions ls
/sessions del abcd1234
```

Manual physical-handle cleanup is normally relevant only to channel-specific session bindings. Inspect first and remove only dated binding files under encoded working-directory subdirectories. Do not delete the root `sessions.db` unless you intend to remove all persisted session data.

```bash
# Example: inspect old channel binding files first, then delete carefully
find ~/.mothx/sessions -path '*/channels/*/*.db' -mtime +30 -print
```

### Backup Important Sessions

Back up the session root directory, especially `sessions.db` and the encoded working-directory handle directories:

```bash
cp -a ~/.mothx/sessions ~/backups/
```

## Troubleshooting

### Session Database Error

```text
Error: session "..." not registered in DB
```

Possible causes:
- The session handle file exists but the SQLite record was removed
- `sessions.db` was deleted or restored from an older backup
- The session root was partially copied

Solutions:
1. Restore the full session root from backup
2. Resume by a valid session ID shown in `/sessions list`
3. Delete stale handle files if the SQLite record no longer exists

### Session Lost

Possible causes:
- Working directory changed
- Session handle file or database was deleted
- The encoded working-directory directory is different

Solutions:
1. Check `~/.mothx/sessions/` or `%APPDATA%\mothx\sessions\`
2. Use `--resume <session-id>` from the original working directory
3. Confirm the configured `sessionDir` is correct

---

## Online Skill Marketplace Integration

Source: https://mothx.net/en/skillhub.md

# Online Skill Marketplace Integration

MothX is compatible with existing skill marketplaces (源盾 / SkillHub / ClawHub). Skill packages published on these platforms can be used directly in MothX.

| Platform | URL | Region |
|----------|-----|--------|
| **源盾 (Yuandun)** | [https://yuandun.gitee.com](https://yuandun.gitee.com/) | China |
| **SkillHub** | [https://skillhub.cn](https://skillhub.cn/) | China |
| **ClawHub** | [https://clawhub.ai](https://clawhub.ai/) | International |

MothX includes a built-in TUI marketplace for browsing, searching, inspecting, and
installing public 源盾 / SkillHub / ClawHub packages. Open it with `/skillhub`. 源盾 is
listed first and is the default market. MothX identifies itself to 源盾 with
`X-Client-Source: MothX` and `User-Agent: MothX`; 源盾 uses the header for download attribution.

This guide covers:

1. [Installing Skills from Marketplaces](#installing-skills-from-marketplaces) — TUI and command usage
2. [Skill Format Compatibility](#skill-format-compatibility) — standard format details
3. [Local Skill System](#local-skill-system) — built-in features
4. [Cron Foundation](#cron-foundation) — scheduled task infrastructure

---

## Installing Skills from Marketplaces

Open the built-in marketplace with `/skillhub`.

In the `mothx serve` Web UI, open **Skills** from the sidebar. The Web UI and TUI share
the same 源盾 / SkillHub / ClawHub adapters and safe installer, including Official, Browse,
Search, detail, install, update, and current-session activation. Project installs are
derived from the current session workDir and constrained by `allowedWorkDirs`.

| Key | Action |
|-----|--------|
| `Tab` / `Shift+Tab` | Switch 源盾 / SkillHub.cn / ClawHub.ai |
| `[` / `]` | Switch Browse / Search / Official |
| `/` | Edit the search query; `Enter` searches |
| `Up` / `Down` | Select a skill |
| `Left` / `Right` | Page through cursor-based markets (源盾 / ClawHub) or SkillHub pages |
| `Enter` | Load details and file list |
| `d` | Open the scrollable files, security, and evaluation detail view |
| `c` / `s` | Cycle category / sort in 源盾 or SkillHub.cn Browse |
| `i` | Install to the selected scope |
| `u` | Update an installed skill when a newer version is available |
| `a` | Install and activate for the current session |
| `g` / `p` | Select global / project scope |
| `r` | Refresh |
| `Esc` | Close the marketplace |

Lists show download counts as `DL`. SkillHub.cn Browse is ordered by downloads.
源盾 Browse uses the market's cursor and supports the same category and sort controls.
`[official]` means the skill is published by a configured Official account;
`[certified]` identifies a verified publisher; `[verified]` is the marketplace's
skill verification flag; and `[risk]` marks a suspicious result. These labels are
kept separate because account origin is not the same as platform verification.
Details also show source, category, tags, security scan summaries, evaluation availability, and download endpoints when provided by the market. The `d` view distinguishes primary and fallback download sources.
SkillHub.cn Browse supports category filters and descending downloads, stars, installs, score, or updated-time sorting. 源盾 Browse supports its fixed categories and COMPREHENSIVE / DOWNLOADS / STARS / LATEST sorting through the same controls.
Installed skills with a newer version show `[update]`; press `u` to update. Active skills are reloaded into the current session after an update.

The command form is also available:

```text
/skillhub search <query>
/skillhub detail <market>/<id>
/skillhub install <market>/<id> [--global|--project] [--activate]
/skillhub installed
```

Installation and activation are separate. Installation writes the package and refreshes
the local skill list. Activation also rebuilds the current session agent so the next
request includes the skill.

Downloaded archives are size-limited and checked for path traversal, absolute paths,
Windows drive paths, and symbolic links. Existing hand-written skills are not overwritten;
updates can only replace a managed directory installed from the same marketplace entry.

Manual installation remains supported by placing a compatible skill directory in one of
the local skill directories.

---

## Skill Format Compatibility

MothX's skill format is fully compatible with the 源盾 / SkillHub / ClawHub standard:

```
skill-name/
├── SKILL.md              # Required: skill definition
└── references/           # Optional: on-demand reference files
    ├── api-guide.md
    └── examples.md
```

### SKILL.md Standard Format

```markdown
# Skill Name

Short description.

## Rules

- Rule 1
- Rule 2

## Examples

...
```

### Reference Files

Skills can include reference files under a `references/` directory, loaded on demand via the `skill_ref` tool:

```
> skill_ref(skill="go-expert", ref="references/api-guide.md")
→ Returns the content of api-guide.md
```

This allows skills to include extensive reference material without consuming system prompt space.

---

## Local Skill System

In addition to marketplace downloads, you can create local skills directly.

### Skill Directories

| Type | Location | Scope |
|------|----------|-------|
| Global | `~/.mothx/skills/` (Linux/macOS) or `%APPDATA%\mothx\skills\` (Windows) | All projects |
| Project | `.mothx/skills/`, `.skills/`, or `skills/` | Current project, overrides global in that order |

### Creating a Skill

```bash
mkdir -p ~/.mothx/skills/go-expert
cat > ~/.mothx/skills/go-expert/SKILL.md << 'EOF'
# Go Expert

Expert-level Go coding standards.

## Rules

- Use `gofmt` for formatting
- Follow Effective Go guidelines
- Return errors; do not panic
- Use `fmt.Errorf` with `%w` for wrapping

## Testing

- Write table-driven tests
- Use `t.Run` for subtests
- Aim for >80% coverage
EOF
```

### Using Skills

```
> /skills
Loaded 2 skills:
  - go-expert (global)
  - project-conventions (project)

> /skill:go-expert
Loaded skill: go-expert
```

### Configuration

Configure the global skills directory in `settings.json`:

```json
{
  "skillsDir": "~/.mothx/skills",
  "skillHub": {
    "defaultMarket": "yuandun",
    "defaultInstallScope": "project",
    "officialHandles": ["user_0064faa7"],
    "markets": [
      { "id": "yuandun", "name": "源盾", "enabled": true, "apiURL": "https://yuandun.gitee.com" },
      { "id": "skillhub.cn", "name": "SkillHub.cn", "enabled": true },
      { "id": "clawhub.ai", "name": "ClawHub.ai", "enabled": true }
    ]
  }
}
```

`officialHandles` controls the accounts aggregated in the SkillHub.cn Official tab.
The 源盾 market ships with `https://yuandun.gitee.com` as its default `apiURL`;
override it only when using a mirror. 源盾 is ordered before SkillHub.cn and is the
default market.
Project skills load automatically without extra configuration.

---

## Cron Foundation

MothX has an internal cron infrastructure (`internal/cron` package) and TUI command entry points. The cron store persists session-bound jobs to the `cron_jobs` table in `sessions.db`, and the scheduler checks for due jobs on a 30-second interval.

### `/cron` TUI Commands

Requires multi-agent mode (`--multi-agent` or Ctrl+P to toggle):

```
> /cron add <description>      — Add a scheduled task
> /cron list                   — List scheduled tasks
> /cron enable <id>            — Enable a task
> /cron disable <id>           — Disable a task
> /cron remove <id>            — Remove a task
> /cron run <id>               — Run a task now
```

### Cron Job Data Model

| Field | Description |
|-------|-------------|
| `id` | Unique job ID (e.g. `cron-1716883200`) |
| `name` | Short task description |
| `prompt` | Task prompt for sub-agent |
| `schedule` | 5-field cron expression |
| `mode` | `agent` or `yolo` |
| `enabled` | Whether the job is active |
| `last_run` | Timestamp of last execution |
| `next_run` | Computed next execution time |
| `run_count` | Total executions |
| `last_status` | `success`, `failed`, or `running` |

### Scheduler Architecture

```
Scheduler loop (every 30s)
    │
    ├── List all enabled jobs from store
    │
    ├── Check each job: is it due?
    │   ├── Never run before → due
    │   ├── NextRun has passed → due
    │   └── Last run > 1 hour ago → due (fallback)
    │
    └── Due jobs → spawn sub-agent
              │
              ├── Mark job as "running"
              ├── Create agent via AgentManager
              ├── Run agent with job prompt
              ├── Collect result
              └── Update job status (success/failed)
```

---

## Related Documents

- [Skills System](skills.md) — Local skills format and management
- [Configuration](configuration.md) — Full settings reference
- [Security](security.md) — Sandbox and approval controls

---

## Skills System

Source: https://mothx.net/en/skills.md

# Skills System

MothX's Skills system allows you to create reusable prompt snippets called Skills.

## Overview

Skills are prompt snippets stored as `SKILL.md` files that can be loaded and injected into the system prompt.

```
┌─────────────────────────────────────────────────────────────┐
│                     Skills System                            │
├─────────────────────────────────────────────────────────────┤
│                                                              │
│  Global Skills                 Project Skills                │
│  Linux/macOS: ~/.mothx/        .skills/                      │
│  skills/                                                       │
│  Windows: %APPDATA%\mothx\skills\                            │
│  ┌─────────────────────┐      ┌─────────────────────┐       │
│  │ coding-standards/   │      │ project-specific/   │       │
│  │   SKILL.md          │      │   SKILL.md          │       │
│  │                     │      │                     │       │
│  │ git-workflow/       │      │ testing-rules/      │       │
│  │   SKILL.md          │      │   SKILL.md          │       │
│  └─────────────────────┘      └─────────────────────┘       │
│            │                            │                    │
│            └──────────┬─────────────────┘                    │
│                       │                                      │
│                       ▼                                      │
│              ┌─────────────────┐                             │
│              │  System Prompt  │                             │
│              └─────────────────┘                             │
│                                                              │
└─────────────────────────────────────────────────────────────┘
```

## Skill Directories

### Global Skills

Location:
- Linux/macOS: `~/.mothx/skills/`
- Windows: `%APPDATA%\mothx\skills\`

Global skills are available for all projects.

```bash
# Linux/macOS
~/.mothx/skills/
├── coding-standards/
│   └── SKILL.md
├── git-workflow/
│   └── SKILL.md
└── review-checklist/
    └── SKILL.md

# Windows
%APPDATA%\mothx\skills\
├── coding-standards\
│   └── SKILL.md
├── git-workflow\
│   └── SKILL.md
└── review-checklist\
    └── SKILL.md
```

### Project Skills

MothX discovers project-local skills from these directories, in increasing priority order:

1. `.mothx/skills/` (the project config skills directory)
2. `.skills/`
3. `.agents/skills/`
4. `skills/`

Later directories override an earlier skill with the same name. Global skills are loaded first, so any project-local copy takes precedence. Each skill is a subdirectory containing `SKILL.md` or `skill.md`.

## SKILL.md Format

Each skill is a Markdown file containing the skill's description and content.

### Example

```markdown
# Coding Standards

This skill defines coding standards for the project.

## Go Code Style

- Use `gofmt` for formatting
- Follow Effective Go guidelines
- Use meaningful variable names
- Add comments for exported functions

## Error Handling

- Always handle errors
- Use `fmt.Errorf` with `%w` for wrapping
- Don't panic in library code

## Testing

- Write table-driven tests
- Use `t.Run` for subtests
- Aim for >80% coverage
```

### Structure

1. **Title** (H1): Skill name
2. **Description** (first paragraph): Brief description of the skill
3. **Content**: Detailed content and rules

## Configuration

### Skills Directory

Configure the skills directory in `settings.json`:

```json
{
  "skillsDir": "~/.mothx/skills"
}
```

On Windows, use `%APPDATA%\mothx\skills` or an absolute path.
```

### Project Local Skills

Project skills are discovered automatically from the project skill directories listed above, with no additional configuration required. Discovery/installation is separate from activation: the Web UI can browse/search SkillHub or ClawHub, install skills, and select which skills are active for a session.

## Usage

### Loading Skills

Skills are loaded automatically at startup:

```go
skillsMgr := skills.NewManager(globalSkillsDir, projectSkillsDir)
if err := skillsMgr.Load(); err != nil {
    // handle error
}
```

### Viewing Loaded Skills

Use the `/skills` command in interactive mode:

```
> /skills
Loaded 3 skills:
  - coding-standards (global)
  - git-workflow (global)
  - project-conventions (project)
```

### Skill Injection

Skill content is injected into the system prompt for the skills active in the current session. A discovered or installed skill is not necessarily enabled for every session.

## Best Practices

### 1. Keep Skills Concise

Focus each skill on a single topic:

```markdown
# Git Commit Rules

## Commit Message Format

<type>(<scope>): <subject>

## Types

- feat: New feature
- fix: Bug fix
- docs: Documentation
- style: Formatting
- refactor: Code restructuring
- test: Adding tests
- chore: Maintenance
```

### 2. Use Global Skills for Common Rules

Place rules that apply to all projects in the global skills directory:

```bash
# Linux/macOS
~/.mothx/skills/
└── general-rules/
    └── SKILL.md

# Windows
%APPDATA%\mothx\skills\
└── general-rules\
    └── SKILL.md
```

### 3. Use Project Skills to Override Specific Rules

Project skills can override global skills:

```bash
.skills/
└── general-rules/  # Overrides global general-rules
    └── SKILL.md
```

### 4. Organize Skill Directories

Organize skills by topic:

```bash
# Linux/macOS
~/.mothx/skills/
├── coding/
│   ├── go-style/
│   │   └── SKILL.md
│   └── python-style/
│       └── SKILL.md
├── git/
│   ├── commit-rules/
│   │   └── SKILL.md
│   └── branch-strategy/
│       └── SKILL.md
└── review/
    └── checklist/
        └── SKILL.md

# Windows
%APPDATA%\mothx\skills\
├── coding\
│   ├── go-style\
│   │   └── SKILL.md
│   └── python-style\
│       └── SKILL.md
├── git\
│   ├── commit-rules\
│   │   └── SKILL.md
│   └── branch-strategy\
│       └── SKILL.md
└── review\
    └── checklist\
        └── SKILL.md
```

## Example Skills

### Code Review Skill

```markdown
# Code Review Checklist

## Before Review

- [ ] Code compiles without errors
- [ ] Tests pass
- [ ] No lint warnings

## Review Points

- [ ] Clear variable/function names
- [ ] Proper error handling
- [ ] No hardcoded values
- [ ] Comments for complex logic
- [ ] Test coverage adequate

## Security

- [ ] No SQL injection
- [ ] No XSS vulnerabilities
- [ ] Proper input validation
- [ ] Secrets not exposed
```

### Testing Skill

```markdown
# Testing Guidelines

## Test Structure

```go
func TestFunction(t *testing.T) {
    tests := []struct {
        name     string
        input    interface{}
        expected interface{}
    }{
        // test cases
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            // test logic
        })
    }
}
```

## Coverage

- Aim for >80% code coverage
- Focus on edge cases
- Test error paths
```

## Troubleshooting

### Skills Not Loading

1. Check directory permissions
2. Confirm `SKILL.md` filename is correct
3. Use `/skills` command to view loading status

### Skills Not Working

1. Confirm skill content format is correct
2. Check if system prompt contains skill content
3. Restart MothX to reload

## Related Documents

- [Configuration](configuration.md) - Skills directory configuration
- [Architecture](architecture.md) - Skills system architecture
- [Workflow Mode](workflow.md) - JavaScript DSL workflow orchestration

## Built-in Skills

### workflow-javascript Skill

When you enable `--workflows` mode, MothX automatically creates a `.skills/workflow-javascript/` directory under your project root with complete syntax rules, pattern skeletons, and best practices. The skill includes 8 reference files:

- Core rules (loaded by default)
- Research and Investigation patterns
- Serial and Parallel Composition
- Decision Routing
- Bounded While Loops
- Horizontal Multi-Agent Collaboration
- Master-Slave Small Teams
- Evaluator-Optimizer Review Passes
- Governance and Human Checkpoints

See the [Workflow Mode](workflow.md) documentation for details.

---

## Tool System Reference Guide

Source: https://mothx.net/en/tools.md

# Tool System Reference Guide

MothX provides a powerful and extensible set of built-in tools for file operations, codebase exploration, shell execution, multi-agent coordination, and workspace interaction.

---

## 1. Tool Execution Safety and Sandboxing

Before exploring individual tools, it is crucial to understand the three run modes under which MothX can execute tools:

| Run Mode | Tool Modification Privileges | Network Access | Typical Use |
|----------|------------------------------|----------------|-------------|
| **plan** | Read-only; writes and modifications are denied | Usually disabled | Analysis and planning |
| **agent** | Workspace reads/writes; risky operations require approval | Controlled by sandbox and tool configuration | Daily development |
| **yolo** | Relaxed approvals and full tool operations; blacklist still applies | Controlled by sandbox configuration | Explicitly authorized automation (default) |
| **os** | Bash only with YOLO-level approval behavior; high-risk protections still apply | Disabled | Shell-only automation |

### Sandbox Mechanics (`bwrap`)
When `sandbox.enabled` is `true` in `settings.json`, MothX isolates commands run via `bash` (or other external processes):
* **Allowed Paths**: The sandbox mounts system folders (`/usr`, `/lib`, `/bin`, etc.) as read-only, and mounts the active workspace directory as read-write (`standard`) or read-only (`strict`).
* **Denied Paths**: Sensitive directories (like `~/.ssh`, `/etc/shadow`, etc.) are completely hidden or blocked.
* **Network Isolation**: Direct networking is blocked by creating a separate network namespace (`--unshare-net`).


## 1a. Parallel Tool Execution

When an agent turn returns multiple local function or custom tool calls, MothX can execute them concurrently using a bounded worker pool. This is controlled by the `toolExecution` setting in `settings.json`:

| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `mode` | string | `"parallel"` | `"parallel"` uses bounded local workers; `"sequential"` executes returned calls one at a time locally (provider-side parallel output is unaffected) |
| `maxConcurrency` | int | `10` | Maximum concurrent tool calls per agent turn (set to `1` for serial execution) |

Calls report their start in the order the model emitted them, so a later call's start is never visible before an earlier call's. This ordering never blocks execution: calls still run concurrently, each waits for its own approvals and durable execution record independently, and they may finish in any order — tool completion events may therefore stream out of order, while provider continuation messages are restored in the original call order. The setting is shared by TUI, WebUI, Serve, channels, ACP, and sub-agents built through the common runtime. `sequential` only changes local execution after a response arrives; a provider may still return multiple tool calls in one response. It does not control concurrency inside provider-hosted tools configured directly in provider settings (for example Responses Code Interpreter); those calls remain under the provider's own orchestration.


---

## 2. Comprehensive Tool Directory

| Tool | Category | Action | Execution Security | Availability |
|------|----------|--------|-------------------|--------------|
| [`read`](#read---file-reading) | File System | Read file content (supports images and pagination) | Read-only access allowed | All modes |
| [`write`](#write---file-writing) | File System | Create or overwrite files | Requires Standard/Yolo | CLI, ACP, Serve, Channels |
| [`edit`](#edit---precise-file-modification) | File System | Atomic text replacements | Requires Standard/Yolo | CLI, ACP, Serve, Channels |
| [`insert`](#insert---structural-file-insertion) | File System | Insert content at a structural file position | Requires Standard/Yolo | CLI, ACP, Serve, Channels |
| [`publish_artifact`](#publish_artifact---generated-artifact-publishing) | Artifact | Copy a completed file into Runtime-owned attachment storage | Read workdir + private attachment write | Artifact-enabled sessions |
| [`ls`](#ls---directory-listing) | Exploration | List directory contents | Read-only access allowed | All modes |
| [`find`](#find---file-search) | Exploration | Search for files by pattern | Read-only access allowed | All modes |
| [`grep`](#grep---text-content-search) | Exploration | Regex search within files | Read-only access allowed | All modes |
| [`web_search`](#web-search---deepseek-or-yuanbao-web-search) | Web | Search the live web via DeepSeek Search or Tencent Yuanbao SearchPro | Read-only network access | Providers without native hosted search (OpenAI Responses and Anthropic Messages use provider-native search) |
| [`web_fetch`](#web-fetch---deepseek-web-fetch) | Web | Fetch one page as Markdown via the DeepSeek Fetch API | Read-only network access | Enabled by `webSearch` |
| [`browser`](#browser---browser-automation) | Web | Control a Chromium-family browser through vibe-browser | Network + local process control | Enabled by `--browser` / browser capability |
| [`image_generation`](#image_generation---image-generation) | Media | Generate images from a text prompt | Provider request | Enabled by `imageGeneration.enabled` |
| [`bash`](#bash---command-execution) | Execution | Run shell commands (supports sync & async) | Subject to Sandbox Level | CLI, ACP, Serve, Channels |
| [`jobs`](#jobs---background-job-management) | Execution | List or check status of background jobs | Read-only access allowed | All modes |
| [`kill`](#kill---stop-background-job) | Execution | Stop a running background job | Requires Standard/Yolo | CLI, ACP, Serve, Channels |
| [`plan`](#plan---task-planning) | Session | Update a visible progress/task plan | Read-only access allowed | All modes |
| [`question`](#question---user-clarification) | Session | Prompt user for multiple-choice input | Plan & Agent mode | TUI & ACP |
| [`memory`](#memory---persistent-memory) | Workflow | Read/write to persistent `memory.md` | Session-scoped read/write | Serve Mode |
| [`cron`](#cron---scheduled-background-tasks) | Workflow | Schedule background tasks via sub-agents | Session-scoped scheduling | Channels & Multi-Agent |
| [`subagent_spawn`](#subagent_---delegated-work) | Multi-Agent | Spawn isolated sub-agents | Sub-agent scoped limits | Multi-Agent Mode |
| [`subagent_status`](#subagent_---delegated-work) | Multi-Agent | Query sub-agent status | Read-only | Multi-Agent Mode |
| [`subagent_send`](#subagent_---delegated-work) | Multi-Agent | Send commands to sub-agents | Send message | Multi-Agent Mode |
| [`subagent_wait`](#subagent_---delegated-work) | Multi-Agent | Wait for member activity when the critical path is blocked | Bounded wait (2.5s-120s) | Multi-Agent Mode |
| [`delegate_worker_mgr`](#delegate_worker_mgr---router-worker-lifecycle) | Router | Manage the external ACP worker lifecycle | Provider profile + Runtime policy | Router Mode |
| [`subagent_answer`](#subagent_---delegated-work) | Multi-Agent | Answer a member's blocking question so it can continue | Question scoped | Multi-Agent Mode |
| [`subagent_destroy`](#subagent_---delegated-work) | Multi-Agent | Remove sub-agents & clean up | Destroy | Multi-Agent Mode |
| [`delegate_subagent`](#delegate_subagent---blocking-single-sub-agent-delegation) | Delegate | Run one synchronous sub-agent task | Sub-agent scoped limits | Delegate Mode |
| [`workflow_run`](#workflow_run---dynamic-javascript-workflows) | Workflow | Run a JavaScript workflow with worker agents | Worker-agent scoped limits | Workflow Mode |
| [`workflow_lint`](#workflow_lint---workflow-validation) | Workflow | Validate workflow JavaScript without running workers | Read-only | Workflow Mode |
| [`workflow_status`](#workflow_status---workflow-run-status) | Workflow | Inspect workflow runs and results | Read-only | Workflow Mode |
| [`workflow_cancel`](#workflow_cancel---workflow-cancellation) | Workflow | Cancel an active workflow run | In-process active run only | Workflow Mode |
| [`a2a_dispatch`](#a2a_dispatch---remote-agent-dispatch) | Multi-Agent | Dispatch tasks to a remote A2A agent | Network request | A2A Master Mode |
| [`skill_ref`](#skill_ref---skill-reference-loading) | Skills | Load external skill documentation | Read-only | All modes |

---

## 3. Tool Details & Parameters

### read - File Reading

Read file contents with support for pagination (vital for handling large source files without blowing up the context window) and image rendering.

#### Parameters:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `path` | string | ✓ | Path to the file. |
| `offset` | integer | - | Starting line number (1-indexed). |
| `limit` | integer | - | Maximum number of lines to read. |

#### Image File Support:
If the file path ends with a supported image extension (`.png`, `.jpg`, `.jpeg`, `.gif`, `.webp`), the tool automatically encodes the image content in Base64 and returns a rich content block with its MIME type, which enables multimodal models to "see" the image.

#### Example Payload:
```json
{
  "path": "src/main.go",
  "offset": 120,
  "limit": 50
}
```

---

### write - File Writing

Create a new file or completely overwrite an existing file. This operation is atomic (uses a temporary file first, then renames it) to prevent corruption.

#### Parameters:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `path` | string | ✓ | Path to write. |
| `content` | string | ✓ | Full text content of the file. |

#### Example Payload:
```json
{
  "path": "config.json",
  "content": "{\n  \"port\": 8080,\n  \"debug\": true\n}"
}
```

---

### edit - Precise File Modification

The `edit` tool performs highly precise, **atomic multi-replacement operations** on a single file. Understanding how this tool operates under the hood is critical:

#### Edit Lifecycle & Safety Rules:
1. **Pre-Flight Validation**: Before any modification is made, MothX reads the file and searches for each `oldText` block in `edits[]`.
2. **Uniqueness Check**: Every `oldText` pattern **must match exactly once** in the target file. If a pattern matches 0 times or matches multiple times, the **entire** batch of edits fails immediately with an error, and the file is untouched.
3. **Overlap Resolution**: MothX sorts the matches by their start index and checks if any edit overlaps with another. If an overlap is detected, the operation aborts to prevent corrupt edits.
4. **Atomic Application**: Edits are applied in sorted order based on their indices in the original file. No partial edits are written. The file is modified atomically via a temporary file write.

#### Parameters:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `path` | string | ✓ | File to edit. |
| `edits` | array of objects | ✓ | List of replacement blocks. |

**Edit Object Structure:**

| Property | Type | Required | Description |
|----------|------|----------|-------------|
| `oldText` | string | ✓ | Exact block of text to replace. |
| `newText` | string | ✓ | The replacement text. |

#### Example Payload:
```json
{
  "path": "server.go",
  "edits": [
    {
      "oldText": "func Start() {\n\tlog.Println(\"Starting server...\")",
      "newText": "func Start() {\n\tlog.Println(\"Booting microservice...\")"
    }
  ]
}
```

---

### insert - Structural File Insertion

Inserts UTF-8 text into an existing file at exactly one structural position: the file head, the file tail, before a 1-based line, or after a 1-based line. It is the right tool when the location is structural and no unique text anchor exists. Use `edit` for exact text replacement, deletion, or text-matched insertion, and `write` to create or completely rewrite a file.

#### Parameters:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `path` | string | ✓ | File to modify. |
| `content` | string | ✓ | UTF-8 text to insert. Must not be empty. |
| `position` | object | ✓ | `{ "type": "head"\|"tail"\|"before_line"\|"after_line", "line": <1-based integer> }`. `line` is required for `before_line` and `after_line`. |
| `create_if_missing` | bool | - | Create a missing file. Only valid with `head` or `tail`; default `false`. |
| `ensure_newline` | bool | - | Ensure the inserted content ends with a newline; default `true`. |
| `dedupe` | object | - | Optional `{ "enabled": true, "mode": "exact"\|"trimmed"\|"line" }` check that skips a byte-identical insertion. |
| `dry_run` | bool | - | Report the diff without writing; default `false`. |

Text-match parameters (`match`, `match_mode`, `occurrence`) are rejected on purpose; use `edit` for those semantics.

#### Example Payload:
```json
{
  "path": "internal/tools/registry.go",
  "content": "\tregistry.Register(NewMyTool(registry))\n",
  "position": { "type": "after_line", "line": 42 },
  "dedupe": { "enabled": true, "mode": "exact" }
}
```

---

### bash - Command Execution

Executes a command using the shell (e.g., `/bin/bash` on Linux/macOS, BusyBox on Windows, or PowerShell as fallback). It supports both synchronous (blocking) and asynchronous (background) execution modes.

#### Parameters:

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `command` | string | ✓ | - | Shell command string to execute. |
| `timeout` | integer | - | 45 | Maximum execution time in seconds (max 600). Use `async=true` for long-running processes; `timeout=0` means no tool-level deadline. |
| `async` | boolean | - | false | If `true` (or if command ends with `&`), the process starts in the background and returns a `jobId` immediately. |

#### Example Payload (Synchronous):
```json
{
  "command": "go test -v ./internal/provider/...",
  "timeout": 60
}
```

#### Example Payload (Asynchronous):
```json
{
  "command": "npm run dev",
  "async": true
}
```

---

### jobs - Background Job Management

List, query, or clean up asynchronous shell processes spawned with `bash` (`async=true`).

#### Parameters:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `jobId` | integer | - | Query detailed logs, start time, CPU elapsed time, and status for a specific job. |
| `cleanup` | boolean | - | Remove finished jobs from the manager list. |

#### Example Payload (List All):
```json
{}
```

#### Example Payload (Query Specific Job):
```json
{
  "jobId": 1
}
```

---

### kill - Stop Background Job

Forcefully stop (send SIGTERM / SIGKILL) an asynchronous background job started via the `bash` tool.

#### Parameters:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `jobId` | integer | ✓ | ID of the job to terminate. |

#### Example Payload:
```json
{
  "jobId": 1
}
```

---

### ls - Directory Listing

List files and directories inside a target path, giving exact file sizes, modification statuses, and types.

#### Parameters:

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `path` | string | - | `.` | Directory to list. |

#### Example Payload:
```json
{
  "path": "./internal"
}
```

---

### find - File Search

Find file paths matching glob patterns. This tool runs the pure-Go `go-fd` engine in-process and respects ignore files.

#### Parameters:

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `pattern` | string | ✓ | - | Glob pattern to search (e.g. `*.go`, `*test*`). |
| `path` | string | - | `.` | Root directory for search. |
| `maxDepth` | integer | - | - | Maximum search depth. |
| `maxResults`| integer | - | 100 | Limit on number of results. |

#### Example Payload:
```json
{
  "pattern": "*_test.go",
  "path": "internal/provider",
  "maxDepth": 3
}
```

---

### grep - Text Content Search

Perform fast regex-based searches across codebase files. This tool runs the pure-Go `go-ripgrep` engine in-process and respects ignore files. If the pattern is an invalid regex, the search automatically falls back to a literal match and reports that fallback in the result.

#### Parameters:

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `pattern` | string | ✓ | - | Regular expression pattern. Invalid regex patterns automatically fall back to literal search. |
| `path` | string | - | `.` | Directory or file path to search. |
| `include` | string | - | - | Glob pattern for files to include (e.g., `*.go`). |
| `maxResults`| integer | - | 100 | Limit on returned matches. |

#### Example Payload:
```json
{
  "pattern": "type ProviderConfig struct",
  "include": "*.go"
}
```

---

### web_search - DeepSeek or Yuanbao Web Search

Searches the live web through the selected local backend. With `webSearch.backend = "deepseek"` it calls DeepSeek's official Search API (`POST /v1/tools/search`) using `webSearch.baseUrl`/`token` or the selected provider credential. With `backend = "yuanbao"` it calls Tencent Yuanbao SearchPro (`POST /SearchPro`) with `{"Query": ...}` and an API key from `webSearch.token` or `${TENCENTCLOUD_WSA_APIKEY}`. Results are returned as ranked titles, URLs, snippets, long summaries, optional page content, site metadata, dates, and authority scores. When the chat provider has native hosted search (OpenAI Responses, or Anthropic Messages while `webSearch` is enabled), MothX uses that hosted search instead and omits this local tool.

#### Parameters:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `query` | string | Yes | Search query (1–128 characters). Supports `site:`, `-site:`, `lang:`, `after:`, `before:`, `-term`, and quoted phrases. |
| `count` | integer | No | Result count from 1 to 50 (default 10). |
| `ori_question` | string | No | Original user question to improve intent understanding. |
| `localization` | string | No | IP address used to prefer localized results. |
| `need_content` | boolean | No | Include extracted page content in `content`. |

#### Example Payload:
```json
{
  "query": "DeepSeek V4 site:github.com OR site:huggingface.co lang:zh after:2025",
  "count": 5,
  "need_content": true
}
```

---

### web_fetch - DeepSeek Web Fetch

Fetches one page through DeepSeek's official Fetch API (`POST /v1/tools/fetch`) and returns its Markdown content. The target must be an HTTP/HTTPS URL with a host and no embedded credentials.

#### Parameters:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `url` | string | Yes | Page URL (maximum 8192 characters). |

#### Example Payload:
```json
{
  "url": "https://example.com/article"
}
```

---

### browser - Browser Automation

Opt-in browser control backed by the `vibe-browser` SDK. Enable it with `--browser` for TUI/CLI or the corresponding session capability in Serve, ACP, and Desktop. The tool drives a Chromium-family browser through actions rather than shell commands.

Typical flow: `open` or `navigate` to a URL, call `snapshot` to obtain grounded selectors/refs, then `click`, `fill`, `type`, `press`, `select`, or `check`; finish with `get_text`, `get_html`, or `screenshot` for verification. After navigation or an interaction, wait for a selector/text/URL or take another snapshot before reporting success.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `action` | string | ✓ | Action to perform. Common values: `open`, `navigate`, `back`, `forward`, `reload`, `snapshot`, `click`, `fill`, `type`, `press`, `select`, `get_text`, `get_html`, `get_value`, `screenshot`, `wait_for_selector`, `wait_for_text`, `wait_for_url`, `tab_new`, `tab_close`, `close`. |
| `url` | string | - | Target URL for `open`/`navigate`. |
| `selector` | string | - | CSS selector, or a ref returned by `snapshot`. |
| `value` / `text` / `key` | string | - | Input value, text target, or keyboard key for the matching actions. |
| `outputPath` | string | - | Project-relative path for `screenshot` output. |
| `format` / `quality` | string / integer | - | Screenshot encoding (`png`, `jpeg`, `webp`) and quality. |
| `fullPage` | bool | - | Capture the full scrollable page. |
| `imageMode` / `maxLongEdge` | string / integer | - | Returned screenshot processing mode and maximum long edge. |

Returned screenshots are model-visible images; large results can be bounded with `imageMode` and `maxLongEdge`.

---

### image_generation - Image Generation

Generates one or more images from a text prompt using the standalone `imageGeneration` configuration. The tool is registered only when `imageGeneration.enabled` is `true`.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `prompt` | string | ✓ | Image generation prompt. |
| `size` | string | - | Requested size, for example `1024x1024`. |
| `quality` | string | - | `low`, `medium`, `high`, or `auto`. |
| `n` | integer | - | Number of images, 1-4. |

Endpoint and credential fields fall back to the configured provider; `apiType` selects `openai-images` (default) or `openai-responses`. See [configuration](configuration.md#imagegeneration).

---

### publish_artifact - Generated Artifact Publishing

The only Agent-facing way to declare a completed file as a deliverable artifact. It resolves symlinks, rejects directories and any path that escapes the session work directory, then copies the file into Runtime-owned attachment storage before reporting success, so later writes cannot mutate what is delivered. Artifact publishing is opt-in and configured independently for terminal (`enableArtifact`), ACP/Desktop (`enableACPArtifact`), and Serve/channel sessions.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `path` | string | ✓ | Completed regular file, relative to the current working directory. |
| `filename` | string | - | User-facing attachment filename. |
| `kind` | string | - | `auto`, `image`, `file`, `audio`, or `video`; `auto` detects images from bytes. |

Do not claim a file is deliverable merely because its path was mentioned. Publish it with this tool (or an authorized provider attachment resolver) so the Runtime owns the attachment record and delivery state.

---

### plan - Task Planning

Renders a multi-step checklist panel in the TUI and persists the current plan state. The TUI also shows active non-done steps in a sticky todo list so users can keep track of progress while the transcript continues streaming.

#### Parameters:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `steps` | array of objects | ✓ | Ordered steps of the task. |
| `title` | string | - | Short descriptive title of the plan. |
| `note` | string | - | Current risk warning, blocker, or status note. |

**Step Object Structure:**

| Property | Type | Required | Allowed Values | Description |
|----------|------|----------|----------------|-------------|
| `title` | string | ✓ | - | Concise description of the step. |
| `status` | string | ✓ | `pending`, `running`, `done`, `failed` | Execution state. |

#### Example Payload:
```json
{
  "title": "Database Migration",
  "steps": [
    { "title": "Check current schema", "status": "done" },
    { "title": "Run migration script", "status": "running" },
    { "title": "Verify data consistency", "status": "pending" }
  ]
}
```

---

### question - User Clarification

The assistant can halt execution and ask the user a multiple-choice question to clarify requirements. Available in `plan` and `agent` modes inside the TUI and ACP sessions. The interactive TUI lets the user navigate options and select the correct path.

#### Parameters:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `question` | string | ✓ | The question being asked. |
| `options` | array of strings | ✓ | List of choices for the user. |

#### Example Payload:
```json
{
  "question": "Which styling library would you prefer for the frontend components?",
  "options": [
    "Tailwind CSS",
    "Styled Components",
    "Vanilla CSS / CSS Modules"
  ]
}
```

---

### memory - Persistent Memory

In Channels messaging mode, the assistant can record user preferences, decisions, and system rules in `.mothx/memory.md`. This memory is loaded at the beginning of each session.

#### Parameters:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `action` | string | ✓ | Action to take: `read`, `add`, `update`, `delete`. |
| `section` | string | - | Heading section (e.g. `Lessons Learned`, `Project Rules`). |
| `content` | string | - | Text block to write or match. |
| `old` | string | - | Target text to replace (used in `update`). |
| `new` | string | - | New replacement text (used in `update`). |

#### Example Payload (Add Memory):
```json
{
  "action": "add",
  "section": "Project Rules",
  "content": "All API endpoints must be documented in OpenAPI 3.0 format."
}
```

---

### cron - Scheduled Background Tasks

Enables creating and managing cron-like scheduled tasks that execute in the background via sub-agents. 

MothX also schedules one Runtime-owned maintenance job (`mothx-maintenance:artifact-storage`, daily) that reclaims unreferenced attachment storage through this same scheduler. It is host housekeeping rather than a user task, so it is excluded from `list`, from name resolution, and from the Web UI and Desktop automation views; it is created automatically whenever a cron scheduler starts. See [`mothx pure`](cli-reference.md#pure---archive-the-sessions-database) for the reclamation rules and the on-demand pass.

#### Parameters:

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `action` | string | ✓ | - | Action: `list`, `create`, `enable`, `disable`, `remove`, `run`. |
| `id` | string | - | - | Job ID (required for edit/remove actions). |
| `name` | string | - | - | Short mnemonic name. |
| `prompt` | string | - | - | The prompt instruction sent to the sub-agent. |
| `schedule` | string | - | - | Cron notation or interval (e.g. `@daily`, `@every 15m`). |
| `oneshot` | boolean | - | false | Run only once and then disable itself. |
| `mode` | string | - | `yolo` | Sub-agent execution mode (`agent` or `yolo`). |

#### Example Payload:
```json
{
  "action": "create",
  "name": "daily-git-pull",
  "prompt": "Pull the latest upstream branch and verify compilation.",
  "schedule": "@daily",
  "mode": "yolo"
}
```

---

### subagent_* - Delegated Work

When MothX is launched in multi-agent mode (`--multi-agent`), the main agent can spin up completely separate sub-agents to parallelize work. Sub-agents run in their own session contexts, have separate memories, separate temporary files, and isolated logs.

Member questions and completions are delivered to an active lead through the session mailbox (as steering messages) in every session that can spawn members; only a session bound to an expert **team** also holds its run open for still-running members at the wrap-up turn. Other sessions end the turn normally and see the notification at their next iteration or next run.

#### `subagent_spawn`
Launches a sub-agent to handle a focused prompt task asynchronously.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `task` | string | ✓ | Prompt describing the precise task to fulfill. |
| `mode` | string | - | Run mode (`plan`, `agent`, or `yolo`; defaults to the parent mode, then `yolo`). |
| `work_dir` | string | - | Specific subdirectory to run the sub-agent in. |
| `tools` | array of strings | - | Whitelist of allowed tool names (empty for all). |
| `max_iterations` | integer | - | Maximum agent loop cycles. |

#### `subagent_status`
Queries progress and returns the result once complete.
```json
{ "handle": "subagent-job-1" }
```

#### `subagent_send`
Appends additional guidance or questions to an active sub-agent.
```json
{ "handle": "subagent-job-1", "message": "Also fix imports in helper_test.go." }
```

#### `subagent_wait`
Blocks until a spawned member or sub-agent completion lands in the session mailbox, or the bounded timeout elapses. It returns only a pending summary (member id, status, and a `question_id` for members waiting on an answer); completion content is delivered automatically at the next iteration boundary.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `timeout_ms` | integer | - | Maximum wait in milliseconds, clamped to 2500-120000 (default 30000). |

#### `subagent_answer`
Answers a blocking question a running member asked the lead instead of the human. The question arrives as a `[MEMBER_QUESTION]` steering message or as a `subagent_wait` pending entry with status `question`; the member stays blocked until this tool resolves it.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `handle` | string | ✓ | Member handle that asked the question. |
| `question_id` | string | ✓ | Question ID from the `[MEMBER_QUESTION]` message or the wait summary. |
| `answer` | string | ✓ | Answer the member continues with. |

A question that is no longer pending (already answered, expired, or belonging to another member) is reported as an error instead of a silent success.

#### `subagent_destroy`
Cleans up logs and releases the sub-agent container/process context.
```json
{ "handle": "subagent-job-1" }
```

---

### delegate_subagent - Blocking Single Sub-Agent Delegation

When MothX is launched with delegate mode (`--delegate`) or enabled at runtime with `/delegate on`, the main agent gets a single blocking `delegate_subagent` tool. It is useful when a bounded subtask requires several exploration steps, but the parent only needs the final summarized result.

Unlike `subagent_*` multi-agent tools, `delegate_subagent` runs synchronously: the parent waits until the child agent completes, then receives a JSON result. Only one delegated sub-agent can run at a time.

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `task` | string | ✓ | - | Specific bounded task with goal, relevant paths/context, expected output, and stop conditions. |
| `mode` | string | - | Parent mode, then `yolo` | Sub-agent execution mode: `plan`, `agent`, or `yolo`. |
| `work_dir` | string | - | Current working directory | Working directory for the sub-agent. |
| `tools` | array of strings | - | All tools except nested sub-agent/delegate | Optional tool allowlist, e.g. `["read", "grep", "find"]`. |
| `max_iterations` | integer | - | `100` | Maximum tool-call iterations. |
| `system_prompt_extra` | string | - | - | Extra instructions or constraints for the worker. |

Example payload:
```json
{
  "task": "Find all Go files in internal/serve/openaiapi/ that import net/http but do not call http.Error. Return file paths with line numbers.",
  "mode": "plan",
  "tools": ["grep", "read", "find"],
  "max_iterations": 20
}
```

Result shape:
```json
{
  "status": "done",
  "result": "...summarized worker response...",
  "duration": "1.234s",
  "tool_calls": 7,
  "tool_breakdown": {"grep": 4, "read": 3}
}
```

Use delegate mode for broad searches, multi-step investigations, focused implementation, or verification tasks. Avoid it for one-tool operations, tasks needing user clarification, or highly stateful work that depends on the full conversation.

#### Router external worker

> **Status: beta (preview) mode.** Router is still an evaluation feature: the tool, its actions, and the profile schema may change in any release without a compatibility migration path. Use it to try external ACP workers on a scratch session, not as a production integration contract.

Router mode (`/router` panel, `/router <id>[,<id>...]`, or `--router --acp-agent <id>[,<id>...]`) exposes exactly one management tool, `delegate_worker_mgr`. The local `delegate_subagent` and `subagent_*` tools are never registered in Router: every worker lifecycle operation is an `action` of the one signature, sharing the same handle, permission, and state.

```json
{"action": "delegate", "task": "…", "agent": "opencode", "role": "implement", "write_scope": ["internal/retry/"], "verification": "go test ./internal/retry"}
```

| action | Required | Behavior |
|---|---|---|
| `delegate` | `task`, `agent` | Blocking bounded worker turn; returns `{status, handle, result, worker}`. |
| `spawn` | `task`, `agent` | Asynchronous worker; returns a handle immediately. |
| `status` | `handle` | Read one worker's canonical manager status and metadata. |
| `list` | none | List this session's workers, including retained completed history. |
| `send` | `handle`, `message` | Append one follow-up turn to an idle worker on the same remote session. |
| `wait` | `handle` or `handles` | Wait for a terminal state or the bounded window; returns a summary, not full text. |
| `destroy` | `handle` | Close the remote session and release its permit. |
| `integrate` | `changes` | Apply immutable change-set snapshots through the exclusive Runtime lane. |
| `answer` | `question_id`, `answer` | Resolve a worker question through the Runtime-owned `DecisionService`. |

`delegate`/`spawn` accept the bounded contract fields `task`, `agent`, `role`, `read_scope`, `write_scope`, `expected_deliverables`, `verification`, `stop_conditions`, `system_prompt_extra`, and `attachments`. `agent` is projected as a JSON `const` for one bound worker or an ordered `enum` for several; an unbound profile is rejected with the bound allowlist. `mode`, `work_dir`, `worktree`, `tools`, and `max_iterations` are not accepted: the worker's mode, tools, lifetime, and working directory come from its ACP profile and the Runtime-resolved session directory. The Runtime validates each action's required combination and names a missing field in the error.

`wait` accepts `timeout_seconds` (clamped to 120s; string-form `wait` also accepts a handle). It only limits waiting and never cancels the worker. `integrate` is all-or-nothing across a multi-selection and reuses the existing rollback evidence. `answer` is lead-only; a question ID from another session is rejected.

A spawned external worker outlives the lead turn that created it: its lifecycle is owned by the shared Agent Core/Runtime, so TUI, CLI, WebUI/API, ACP, and Channel entry points behave identically. It remains explicitly cancellable through `destroy` and Runtime shutdown. Read-only workers can run concurrently up to the profile's `maxConcurrentChildren`; a base-workspace writer (including `integrate`) remains exclusive in both directions. The Runtime reuses one initialized ACP process for multiple remote sessions in the same profile/workdir, while each child keeps an isolated remote session ID and canonical event stream. If a transport dies, the next turn prefers capability-gated `session/resume` and falls back to `session/load`; an in-flight prompt is never replayed.

#### Worker MCP bridge (`worker_mgr`)

When the Runtime has a live loopback bridge, a local stdio worker receives one MCP server named `mothx-worker` in `session/new|load|resume`, authenticated by a per-child bearer token. The worker sees exactly one tool:

| action | Required | Behavior |
|---|---|---|
| `context` | none | Return the task contract, work directory, and bridge capabilities. |
| `report` | `kind`, `text` | Append to the session's own `worker-messages/<sessionId>/worker_messages.jsonl`. `notice`/`progress` stay out of lead context; `finding` is injected as a `[WORKER_FINDING]` steering message and may wake an idle lead. |
| `ask` | `text` | Create a durable `DecisionQuestion`, queue it as a `[MEMBER_QUESTION]`, and block until the lead calls `delegate_worker_mgr(action=answer)`, the deadline elapses, or the worker turn is cancelled. |

There is no spawn/send/destroy/steer control surface and no `childId` parameter: the token is the scope. `report` is limited to 8 KiB, `ask` to 4 KiB, options to 8, and each child to 20 calls/minute. `dedupe_key` is unique per `(session, child, key)` and a repeat returns the same message ID. The per-child token lives for the worker's remote session, not one turn: after a turn reaches its terminal state the scope rejects bridge calls with an MCP tool error naming `child_terminal` (HTTP 200, `isError=true`), and the next `send`/follow-up re-enables the same credential. Tokens are revoked on destroy/close, session shutdown, or process exit, and a resumed remote session receives a fresh token. Only loopback HTTP is implemented; SSE and stdio are rejected/diagnostic. A remote or containerized worker cannot reach host loopback, so it projects `mcpBridge=unreachable` and runs without the bridge. Remote ACP worker completion text remains `worker-reported` evidence; never upgrade it to verified without reading the workspace.

Worker activity is projected read-only in every entry point. The TUI `/router` panel lists recent worker messages and pending questions; the ACP adapter exposes `mothx/worker/messages` (feature key `workerMessages`) and the WebUI reads the same projection from `GET /api/sessions/{id}/router`. Desktop renders it in the Router composer section. None of these surfaces can answer a worker question: only the lead's `delegate_worker_mgr(action=answer)` resolves the durable `DecisionQuestion`. Profile behavior metadata (`model`, `driver`, `mcpBridge`, `capabilityOverrides`) is editable from the TUI `/router` panel, the WebUI Settings → Router Worker page (`PATCH /api/acp/profiles`), and Desktop Settings → Router Workers (`mothx/manage/acp/profiles/patch`); each surface sends only those fields, so argv, URLs, environment names, and trust flags stay operator-owned.

#### Worker integration and capability bridges

`delegate_worker_mgr(action=integrate)` applies selected immutable change sets from finished external Router workers to the session workspace. It never copies a mutable child worktree, never reruns the worker, and never starts a second Runner: the Runtime loads the durable snapshot, verifies the digest, status, truncation state, and managed-worktree identity, then uses one exclusive integration lane. A multi-selection is all-or-nothing within that call: if a later snapshot conflicts, snapshots this call already applied are reversed and their evidence is updated.

```json
{"action": "integrate", "changes": [{"handle": "worker-1", "digest": "sha256:..."}]}
```

The result reports `integrationId`, `status`, applied files, and per-child evidence. A missing, truncated, failed, or digest-mismatched snapshot is rejected before anything is written. A git apply conflict is returned as structured `conflict` evidence with a nil tool error so the lead can inspect the base workspace and decide how to recover; earlier selections from the same call are rolled back first. An already-applied `{handle, digest}` is idempotent. Integration evidence is persisted on `session_child_runs` (migration 57).

Resolved worker capabilities (`sessionResume`, `sessionLoad`, `sessionClose`, `additionalDirectories`, prompt media, `mcpHttp`, filesystem/terminal bridges, config-option/thought/subagent support) are persisted on `session_child_runs` (migration 58) as `resolved_capabilities_json`, `capability_degradations_json`, and `mcp_bridge`, and projected in child metadata. The Runtime never enables a capability the Agent did not advertise, and a profile `capabilityOverrides` entry can only tighten it. The `delegate_worker_mgr` description publishes a bounded per-worker summary derived from the same resolver (report/ask, attachments, write, terminal, resume) and names why the bridge is unavailable for a remote, `mcpBridge=off`, closed-listener, or override-tightened profile.

When the Runtime has a workspace Registry, an external worker may also request `fs/read_text_file`. The Runtime resolves the absolute path through the session's workspace roots and symlink fence, limits text reads to 1 MiB of valid UTF-8, and honors ACP's optional 1-based `line`/`limit`. `session/new` sends the same Runtime-authorized roots as `cwd` plus `additionalDirectories` only when the Agent advertises `sessionCapabilities.additionalDirectories`; the same rule applies to `session/load` and `session/resume`. A Registry-backed connection advertises `fs/write_text_file` as part of its capability union; a write-role task with a non-empty `write_scope` may use it. Each write must resolve inside that task scope and uses the shared file lock and atomic-write path. This bridge is optional convenience, not containment: the external Agent's own tools remain outside MothX's write scope. A profile with `"terminal": true` also gets `terminal/create`, `terminal/output`, `terminal/wait_for_exit`, `terminal/kill`, and `terminal/release`; commands run through the shared sandbox and process-group containment with a bounded non-interactive output buffer. Terminal and URL authentication are not implemented.

`attachments` accepts Runtime input resource IDs from the request manifest. The Runtime verifies ownership, size, and hash, then negotiates delivery through the Agent's advertised ACP `promptCapabilities`: `image` content, `audio` content, or an embedded `resource` for `embeddedContext`. An unsupported attachment is not silently dropped; the worker prompt names the omission, the Runtime resource ID, and the session-relative path. Because an isolated worker runs in a fresh worktree, that path is provenance rather than a promise that the file exists in the worker's workspace.

Router cannot be combined with an Expert Team: unbind the team before activating Router or binding a team to an existing Router session. A single-persona expert remains compatible because it contributes identity/skills without enabling the team's local multi-agent surface.


---

### workflow_lint - Workflow Validation

Validates a workflow script without invoking worker agents. It checks JavaScript syntax, `workflow`/`phase`/`agent` structure, agent option spelling, required prompts, and `result`/`resultKey`/`resultLatest`/`results` references. Run it before `workflow_run` for non-trivial generated or edited workflows.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `source` | string | ✓ | Complete raw JavaScript workflow DSL source. Do not pass Markdown fences. |

---

### workflow_run - Dynamic JavaScript Workflows

When MothX is launched with workflow mode (`--workflows`), the main agent can run a plain JavaScript workflow script that coordinates multiple worker agents across phases. Workflow mode is independent from `--multi-agent`: enabling workflows exposes `workflow_*` tools, not `subagent_*` tools.

Workflow scripts must use the supported JavaScript DSL. Do not describe workflow structure with a JSON DSL.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `source` | string | ✓ | JavaScript workflow source. The top-level form should be `workflow("name", body)`. |
| `timeoutSeconds` | integer | - | Tool-level timeout for the whole workflow run. Omit to use the default tool timeout, set a positive number for bounded long workflows, or set `0` only for intentional continuous workflows with no agent-level deadline. |

Example payload:
```json
{
  "source": "workflow(\"auth audit\", {concurrency: 2, phases: [phase(\"scan\", parallel(agent(\"api\", {mode: \"plan\", tools: [\"read\", \"grep\"], maxIterations: 100, prompt: \"Audit internal/serve/openaiapi auth risks\"}), agent(\"channels\", {mode: \"plan\", tools: [\"read\", \"grep\"], maxIterations: 100, prompt: \"Audit internal/serve/channels auth risks\"}))), phase(\"verify\", agent(\"cross-check\", {mode: \"plan\", tools: [\"read\", \"grep\"], maxIterations: 80, prompt: results(\"scan\") + \"\\nReconcile the findings and list concrete risks.\"}))]});",
  "timeoutSeconds": 900
}
```

Supported workflow builtins include `workflow`, `phase`, `parallel`, `series`, `agent`, `concurrency`, `result`, `resultKey`, `resultLatest`, `results`, and `log`. Worker agents receive dynamic workflow context through their task prompt, so the parent system prompt and tool definitions remain frozen after agent construction.

Important defaults: `concurrency` defaults to 5, `mode` inherits the parent agent mode, omitted `tools` uses the default tool set for the worker mode, and omitted/zero/negative `maxIterations` defaults to 100 worker-agent loop iterations. Use `key` for repeated logical agents inside loops; keyed results are stored as `phase.agent[key]` and can be read with `resultKey` or `resultLatest`. Worker agents cannot spawn subagents, delegate, or start nested workflows, and the DSL has no per-worker `:timeout`, `model`, `:thinking-level`, or `:max-tokens` options.

For detailed usage and best practices of workflow mode, see the [Workflow Mode](workflow.md) documentation.

### workflow_status - Workflow Run Status

Lists recent workflow runs, or returns the full persisted state for one run.

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string | - | Workflow run ID. Omit to list recent runs. |

### workflow_cancel - Workflow Cancellation

Cancels an active workflow run in the current MothX process. Completed runs, runs from another process, and runs from before a restart are not active and cannot be canceled by ID.

---

### a2a_dispatch - Remote Agent Dispatch

Only available in A2A Master Mode. Dispatches a task request over network to a remote agent endpoint registered in the local configuration files.

#### Parameters:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `agent_name` | string | ✓ | Remote agent alias registered in `a2a-list.json`. |
| `message` | string | ✓ | Full instruction to send to the remote agent. |

#### Example Payload:
```json
{
  "agent_name": "kubernetes-deployer",
  "message": "Deploy image tag v1.2.3 to development namespace."
}
```

---

### skill_ref - Skill Reference Loading

Load reference context from a localized skill. This keeps large reference schemas, api endpoints, and documentation out of the main agent prompt until specifically requested.

#### Parameters:

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `skill` | string | ✓ | Skill directory name. |
| `ref` | string | ✓ | Path of the reference file inside the skill folder. |

#### Example Payload:
```json
{
  "skill": "kubernetes-skill",
  "ref": "references/helm-deployment.md"
}
```

---

## 4. Best Practices for Developers & Users

To get the absolute best out of MothX's tool loop, keep the following principles in mind:

1. **The Read-Before-Modify Standard**: Always ensure you (or the model) call `read` on files before attempting to modify them with `edit`. Having the exact, complete block in context ensures the `oldText` parameter matches perfectly and prevents atomic editing failures.
2. **Minimize `bash` usage for exploration**: Avoid running shell commands like `grep`, `find`, or `cat` inside a bash tool. MothX's dedicated `grep`, `find`, and `read` tools are heavily optimized, parsed directly into structured data, and do not suffer from sub-shell spawn latencies or sandbox restrictions.
3. **Handle Long-Running Jobs with Care**: When spinning up servers or continuous builders using `bash` in async mode (`async=true`), regularly call `jobs` to clean up exited jobs (`cleanup=true`) to keep the system overhead down, and use `kill` to shut down background servers once they are no longer required.

---

## 🎯 MothX Use Cases & Real-World Examples

Source: https://mothx.net/en/use-cases.md

# 🎯 MothX Use Cases & Real-World Examples

> From daily development to enterprise deployment, MothX meets all your needs.

---

## 💻 Daily Development

### Scenario 1: Quick Code Generation

```bash
# Generate a Go HTTP server
mothx -P "Write a Go HTTP server with RESTful API and user authentication"

# Generate a React component
mothx -P "Create a React search component with debounce and loading state"

# Generate a Python scraper
mothx -P "Write a Python scraper to fetch Hacker News headlines"
```

### Scenario 2: Code Understanding

```bash
# Explain code
mothx -P "Explain what main.go does"

# Explain regex
mothx -P "What does this regex mean? ^(?:https?:\/\/)?(?:www\.)?([^\/]+)"

# Analyze architecture
mothx -P "Analyze this project's architecture and draw component relationships"
```

### Scenario 3: Code Refactoring

```bash
# Refactor to generics
mothx -P "Refactor this function to use generics"

# Optimize performance
mothx -P "Optimize this code for performance, reduce memory allocations"

# Split modules
mothx -P "Split this class into smaller modules, following single responsibility principle"
```

### Scenario 4: Test Generation

```bash
# Unit tests
mothx -P "Write unit tests for UserService, covering all edge cases"

# Integration tests
mothx -P "Generate integration test cases for API endpoints"

# End-to-end tests
mothx -P "Write an end-to-end test simulating user login flow"
```

### Scenario 5: Documentation

```bash
# Function comments
mothx -P "Generate JSDoc comments for this function"

# README
mothx -P "Write a README.md for this project with installation and usage instructions"

# API documentation
mothx -P "Generate API documentation with request/response examples"
```

---

## 🔍 Code Review

### Scenario 1: PR Review

```bash
# Review PR
mothx --mode plan "Review this PR, find potential issues and suggestions"

# Security review
mothx --mode plan "Review this code for security vulnerabilities"

# Performance review
mothx --mode plan "Review this code for performance bottlenecks"
```

### Scenario 2: Code Quality

```bash
# Code standards
mothx --mode plan "Check if this code follows Go coding standards"

# Error handling
mothx --mode plan "Check if this code has proper error handling"

# Concurrency safety
mothx --mode plan "Check if this code is concurrency-safe"
```

---

## 🚀 CI/CD Integration

### Scenario 1: Auto-generate Documentation

```bash
# Generate changelog
mothx -p "Generate changelog from git log, grouped by version" > CHANGELOG.md

# Generate API docs
mothx -p "Generate API documentation from code comments" > docs/api.md

# Generate migration guide
mothx -p "Generate migration guide from v1 to v2" > docs/migration.md
```

### Scenario 2: Code Analysis

```bash
# Static analysis
mothx -p "Analyze this code for potential issues" > analysis.txt

# Security scan
mothx -p "Scan this code for security vulnerabilities" > security.txt

# Performance analysis
mothx -p "Analyze this code for performance bottlenecks" > performance.txt
```

### Scenario 3: Automated Testing

```bash
# Generate test cases
mothx -p "Generate test cases for this function" > tests/function_test.go

# Generate test data
mothx -p "Generate test data with edge cases" > testdata.json

# Generate test report
mothx -p "Generate test report from test results" > report.md
```

---

## 🌐 API Server

### Scenario 1: Team Sharing

```bash
# Start serve
mothx serve

# Config file ~/.mothx/serve.json
{
  "port": 8080,
  "auth": {
    "token": "your-secret-token"
  },
  "defaultProvider": "deepseek-openai",
  "defaultModel": "deepseek-v4-flash"
}
```

### Scenario 2: API Integration

```python
import requests

# Call MothX API
response = requests.post(
    "http://localhost:8080/v1/chat/completions",
    headers={"Authorization": "Bearer your-secret-token"},
    json={
        "model": "deepseek-v4-flash",
        "messages": [{"role": "user", "content": "Hello, MothX!"}]
    }
)

print(response.json())
```

### Scenario 3: Load Balancing

```yaml
# docker-compose.yml
version: '3'
services:
  mothx-1:
    image: mothx
    command: serve
    ports:
      - "8081:8080"
  
  mothx-2:
    image: mothx
    command: serve
    ports:
      - "8082:8080"
  
  nginx:
    image: nginx
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf
```

---

## 📱 Chatbot

### Scenario 1: WeChat Bot

```bash
# Start messaging channels
mothx serve

# Config file ~/.mothx/serve.json
{
  "platform": "wechat",
  "appId": "your-app-id",
  "appSecret": "your-app-secret",
  "defaultProvider": "deepseek-openai",
  "defaultModel": "deepseek-v4-flash"
}
```

### Scenario 2: Feishu Bot

```bash
# Config file ~/.mothx/serve.json
{
  "platform": "feishu",
  "appId": "your-app-id",
  "appSecret": "your-app-secret",
  "defaultProvider": "deepseek-openai",
  "defaultModel": "deepseek-v4-flash"
}
```

### Scenario 3: WebSocket

```bash
# Config file ~/.mothx/serve.json
{
  "platform": "websocket",
  "port": 8080,
  "defaultProvider": "deepseek-openai",
  "defaultModel": "deepseek-v4-flash"
}
```

---

## 🤝 Multi-Agent Collaboration

### Scenario 1: Large Task Decomposition

```text
# Enable multi-agent mode
mothx --multi-agent

# Main agent decomposes task
> "Decompose this large task into 5 subtasks, assign each to a sub-agent"

# The agent can call subagent_spawn internally for each focused subtask.
```

### Scenario 2: Parallel Execution

Example tool-call payloads used by the agent:

```json
{ "tool": "subagent_spawn", "arguments": { "task": "Task 1: Process dataset A" } }
{ "tool": "subagent_spawn", "arguments": { "task": "Task 2: Process dataset B" } }
{ "tool": "subagent_status", "arguments": { "handle": "subagent-job-1" } }
{ "tool": "subagent_send", "arguments": { "handle": "subagent-job-1", "message": "Return results" } }
```

### Scenario 3: A2A Remote Collaboration

```bash
# Enable A2A Master mode
mothx --enable-a2a-master

# Configure remote agents
# a2a-list.json
[
  {
    "name": "data-agent",
    "url": "http://agent1.example.com:8080",
    "description": "Data processing agent"
  },
  {
    "name": "report-agent",
    "url": "http://agent2.example.com:8080",
    "description": "Report generation agent"
  }
]

# Main agent automatically dispatches tasks
> "Analyze data and generate report"
```

### Scenario 4: Dynamic Workflow Orchestration

Use Workflow mode for structured multi-phase, verified complex task orchestration:

```bash
# Enable Workflow mode
mothx --workflows

# Ask AI to run a security audit workflow
> "Run a security audit on internal/serve/openaiapi and internal/serve/channels, parallel scan then cross-verify"

# AI automatically generates and executes an JavaScript workflow like:
# - phase 1: parallel scan of multiple modules
# - phase 2: cross-verify results, drop weak findings
# - phase 3: generate final audit report
```

Workflow mode is ideal for code audits, architecture research, multi-role reviews, generate-critic loops, and other scenarios requiring structured multi-agent collaboration. See the [Workflow Mode](workflow.md) documentation for details.

---

## 🛠️ System Administration

### Scenario 1: Server Management

```bash
# Check server status
mothx --mode yolo "Check server CPU, memory, and disk usage"

# Clean logs
mothx --mode yolo "Clean log files older than 30 days in /var/log"

# Backup data
mothx --mode yolo "Backup database to /backup directory"
```

### Scenario 2: Docker Management

```bash
# Generate Dockerfile
mothx -P "Generate a Dockerfile for this Node.js project"

# Generate docker-compose.yml
mothx -P "Generate docker-compose.yml with Node.js, PostgreSQL, and Redis"

# Optimize image
mothx -P "Optimize this Dockerfile to reduce image size"
```

### Scenario 3: Kubernetes Management

```bash
# Generate Kubernetes config
mothx -P "Generate Kubernetes Deployment and Service configuration"

# Generate Helm Chart
mothx -P "Generate a Helm Chart for this application"

# Troubleshoot
mothx --mode plan "Analyze this Kubernetes Pod logs, find crash reason"
```

---

## 📊 Data Analysis

### Scenario 1: Data Processing

```bash
# Data cleaning
mothx -P "Clean this CSV file with Python, handle missing values and outliers"

# Data transformation
mothx -P "Convert JSON data to CSV format"

# Data aggregation
mothx -P "Aggregate sales data by month, calculate total and average"
```

### Scenario 2: Data Visualization

```bash
# Generate charts
mothx -P "Generate a sales trend chart with Matplotlib"

# Generate dashboard
mothx -P "Generate an interactive dashboard with Plotly"

# Generate report
mothx -P "Generate an analysis report from data with charts and conclusions"
```

---

## 🎓 Learning & Education

### Scenario 1: Code Learning

```bash
# Explain code
mothx -P "Explain this code line by line"

# Explain algorithms
mothx -P "Explain the quicksort algorithm principle and implementation"

# Explain design patterns
mothx -P "Explain the singleton pattern use cases and implementation"
```

### Scenario 2: Programming Practice

```bash
# Generate exercises
mothx -P "Generate 10 Python programming exercises with increasing difficulty"

# Check answers
mothx -P "Check if this answer is correct"

# Generate explanations
mothx -P "Generate detailed explanations for this problem"
```

### Scenario 3: Project Guidance

```bash
# Project planning
mothx -P "Help me plan the architecture of a blog system"

# Tech stack selection
mothx -P "Recommend a tech stack suitable for this project"

# Code review
mothx -P "Review my code and give improvement suggestions"
```

---

## 🏢 Enterprise Applications

### Scenario 1: Code Standards

```bash
# Generate standards document
mothx -P "Generate team coding standards document"

# Check standards
mothx --mode plan "Check if this code follows team standards"

# Auto-fix
mothx -P "Auto-fix code standards issues in this code"
```

### Scenario 2: Knowledge Base

```bash
# Generate knowledge base
mothx -P "Generate knowledge base documentation from code comments"

# Search knowledge base
mothx -P "Search knowledge base for user authentication documentation"

# Update knowledge base
mothx -P "Update knowledge base with new API documentation"
```

### Scenario 3: Automation Workflows

```bash
# Generate workflow
mothx -P "Generate GitHub Actions workflow for automated testing and deployment"

# Generate scripts
mothx -P "Generate automation script for daily database backup"

# Generate monitoring
mothx -P "Generate monitoring script to detect server anomalies"
```

---

## 🎯 Best Practices

### 1. Choose the Right Mode

- **Plan mode**: For analysis, planning, code review
- **Agent mode**: For daily development, code generation, testing
- **YOLO mode**: For system administration, automation scripts

### 2. Use Skills System

```bash
# Create project skill
.skills/conventions/SKILL.md

# Skill content example
# Project Coding Standards

## Naming Conventions
- Variables: camelCase
- Functions: camelCase
- Classes: PascalCase
- Constants: UPPER_SNAKE_CASE

## Code Style
- Use 4-space indentation
- Max 120 characters per line
- Use single quotes for strings

## Comment Standards
- Functions must have JSDoc comments
- Complex logic must have inline comments
- TODOs must include owner
```

### 3. Configure Approval Whitelist

```json
{
  "approval": {
    "bashWhitelist": ["go ", "make ", "git ", "npm "],
    "bashBlacklist": ["rm -rf", "sudo"],
    "confirmBeforeWrite": true
  }
}
```

### 4. Use Session Management

```bash
# Continue most recent session
mothx --continue

# Resume specific session
mothx --resume <session-id>

# Use specific session handle file
mothx --session <session-file.db>
```

### 5. Monitor Cache Hit Rate

- Check cache hit rate in TUI footer
- Optimize prompts to improve cache hit rate
- Monitor token usage to control costs

---

## 📖 More Resources

- [5-Minute Quick Start](quick-start-tutorial.md) — Skip the long docs, just start coding!
- [Features Overview](features-overview.md) — Learn about all features
- [Configuration Guide](configuration.md) — Customize settings
- [Tool Reference](tools.md) — All built-in tools
- [FAQ](faq.md) — Common questions answered

---

<p align="center">
  <strong>🎉 Now you've mastered all MothX use cases.</strong><br>
  <strong>Start your AI coding journey!</strong>
</p>

---

## Workflow JavaScript

Source: https://mothx.net/en/workflow.md

# Workflow JavaScript

Workflow mode orchestrates worker agents with a raw JavaScript DSL. Enable it with `--workflows`; the project skill `workflow-javascript` contains the full reference patterns.

```javascript
workflow("quick audit", {
  concurrency: 2,
  phases: [
    phase("scan", parallel(
      agent("api", { mode: "plan", tools: ["read", "grep"], prompt: "Audit API risks." }),
      agent("channels", { mode: "plan", tools: ["read", "grep"], prompt: "Audit channel risks." })
    )),
    phase("verify", agent("cross-check", {
      mode: "plan", prompt: "Reconcile findings:\n" + results("scan")
    }))
  ]
});
```

`workflow(name, options)` accepts `concurrency` and `phases`. Use `phase`, `parallel`, `series`, and `agent` nodes. Agent names and phase names must be string literals. Agent options are `prompt`, `mode`, `workDir`, `tools`, `maxIterations`, `key`, and `systemPromptExtra`; tools are normal JavaScript arrays.

Runtime expressions: `result("phase.agent")`, `resultKey("phase.agent", "r0")`, `resultLatest("phase.agent")`, `results("phase")`, and `log("message", value)`. Repeated logical agents keep a literal name and use a unique key such as `key: "r" + i`.

Concurrency defaults to 5. Worker `maxIterations` defaults to 100 when omitted, zero, or negative. `workflow_run` `timeoutSeconds` is a separate tool-level timeout. Worker agents cannot start nested orchestration. Use `workflow_lint` before running non-trivial generated or edited source.

The CLI and Serve mode expose `/workflows` for listing, inspection, and cancellation. `workflow_cancel` only cancels active runs in the current process.

---
