mocode-ai 1.6.4 → 1.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +382 -365
  2. package/README.zh-CN.md +19 -2
  3. package/dist/agent/model-turn.js +14 -1
  4. package/dist/agent/run-coordinator.js +7 -1
  5. package/dist/agent/spawn.js +38 -5
  6. package/dist/agent/stages/model-runner.js +1 -1
  7. package/dist/agent/stages/tool-dispatcher.js +1 -0
  8. package/dist/agent/tool-turn.js +2 -0
  9. package/dist/agent/work-discipline.js +3 -1
  10. package/dist/bots/bus.js +117 -0
  11. package/dist/bots/cli.js +102 -0
  12. package/dist/bots/store.js +100 -0
  13. package/dist/config/index.js +53 -2
  14. package/dist/config/presets.js +40 -1
  15. package/dist/config/profiles.js +9 -1
  16. package/dist/context/clearing.js +53 -0
  17. package/dist/context/relevance.js +6 -0
  18. package/dist/context/text-search.js +113 -0
  19. package/dist/headless.js +302 -0
  20. package/dist/index.js +171 -3
  21. package/dist/jobs/approval.js +153 -0
  22. package/dist/jobs/approve-cli.js +30 -0
  23. package/dist/jobs/attach.js +61 -0
  24. package/dist/jobs/checkpoint.js +33 -0
  25. package/dist/jobs/launch.js +107 -0
  26. package/dist/jobs/runner.js +59 -0
  27. package/dist/jobs/store.js +101 -0
  28. package/dist/jobs/worktree.js +63 -0
  29. package/dist/llm/index.js +35 -8
  30. package/dist/llm/providers/anthropic.js +14 -4
  31. package/dist/llm/reasoning.js +141 -0
  32. package/dist/memory/reflect.js +1 -1
  33. package/dist/memory/store.js +31 -28
  34. package/dist/models/budgets.js +11 -0
  35. package/dist/models/catalog.js +130 -0
  36. package/dist/models/map-preset.js +50 -0
  37. package/dist/models/model-panel.js +227 -0
  38. package/dist/models/protocol.js +44 -0
  39. package/dist/models/reasoning-cap.js +88 -0
  40. package/dist/models/search.js +58 -0
  41. package/dist/models/types.js +8 -0
  42. package/dist/notify/index.js +144 -0
  43. package/dist/repl/commands/bots.js +32 -0
  44. package/dist/repl/commands/effort.js +81 -0
  45. package/dist/repl/commands/jobs.js +109 -0
  46. package/dist/repl/commands/model-actions.js +138 -0
  47. package/dist/repl/commands/model-catalog.js +67 -0
  48. package/dist/repl/commands/model-panel-ui.js +107 -0
  49. package/dist/repl/commands/model.js +22 -20
  50. package/dist/repl/commands/registry.js +12 -0
  51. package/dist/repl/commands/schedule.js +37 -0
  52. package/dist/repl/commands/session.js +54 -0
  53. package/dist/repl/commands/stats.js +28 -0
  54. package/dist/repl/commands.js +6 -58
  55. package/dist/repl/runtime.js +5 -1
  56. package/dist/repl/status-bar.js +4 -2
  57. package/dist/rollback/store.js +17 -0
  58. package/dist/runtime/runtime.js +31 -1
  59. package/dist/schedule/cli.js +114 -0
  60. package/dist/schedule/cron.js +79 -0
  61. package/dist/schedule/daemon.js +166 -0
  62. package/dist/schedule/store.js +98 -0
  63. package/dist/session/compact.js +84 -3
  64. package/dist/session/index.js +2 -0
  65. package/dist/session/retention.js +297 -0
  66. package/dist/session/scheduler.js +30 -3
  67. package/dist/session/store.js +108 -6
  68. package/dist/session/usage-stats.js +90 -0
  69. package/dist/skills/activation.js +2 -0
  70. package/dist/skills/builtin-skills.js +153 -0
  71. package/dist/skills/discover.js +3 -1
  72. package/dist/skills/runner.js +4 -1
  73. package/dist/tools/builtins/arena.js +156 -0
  74. package/dist/tools/builtins/index.js +8 -0
  75. package/dist/tools/builtins/message-bus.js +98 -0
  76. package/dist/tools/builtins/read-file.js +19 -1
  77. package/dist/tools/builtins/run-command.js +2 -1
  78. package/dist/tools/builtins/session-search.js +33 -0
  79. package/dist/tools/builtins/task.js +2 -0
  80. package/dist/tools/constants.js +8 -0
  81. package/dist/tools/read-dedup.js +62 -0
  82. package/dist/tools/tool-runtime.js +1 -0
  83. package/dist/ui/batch.js +140 -104
  84. package/dist/ui/composer.js +4 -18
  85. package/dist/ui/fuzzy-picker.js +227 -0
  86. package/dist/ui/hierarchical-picker.js +302 -0
  87. package/dist/ui/intervention.js +17 -1
  88. package/dist/ui/layout-internal/statusbar.js +18 -7
  89. package/dist/ui/prompt-internal/editor.js +10 -27
  90. package/dist/ui/render.js +2 -0
  91. package/package.json +1 -1
package/README.md CHANGED
@@ -1,365 +1,382 @@
1
- <img src="./assets/banner-en.svg?v=2" alt="MoCode">
2
-
3
- <p align="right">English | <a href="./README.zh-CN.md">简体中文</a></p>
4
-
5
- # MoCode
6
-
7
- [![npm version](https://img.shields.io/npm/v/mocode-ai.svg)](https://www.npmjs.com/package/mocode-ai)
8
- [![npm downloads](https://img.shields.io/npm/dm/mocode-ai.svg)](https://www.npmjs.com/package/mocode-ai)
9
- [![CI](https://img.shields.io/github/actions/workflow/status/wanxunyang/mocode/ci.yml?label=CI)](https://github.com/wanxunyang/mocode/actions/workflows/ci.yml)
10
- [![license](https://img.shields.io/github/license/wanxunyang/mocode)](https://github.com/wanxunyang/mocode/blob/main/LICENSE)
11
-
12
- A terminal coding agent: give it a goal, and it **completes it autonomously** — no step-by-step hand-holding required.
13
-
14
- MoCode explores your code, reads/writes/edits files, runs shell commands, and searches the web on its own, driving the task forward through a loop of "think → call a tool → observe the result → think again." It works with any OpenAI-compatible endpoint (GLM, DeepSeek, Qwen, local Ollama / vLLM, etc.), runs as a full-screen TUI with streaming output and visible reasoning.
15
-
16
- ## Demo
17
-
18
- See mocode complete real tasks autonomously:
19
-
20
- **Fixing documentation drift in its own codebase** — mocode counts the actual built-in tools, finds the mismatch with `package.json` and `AGENTS.md`, and rewrites them so all three sources agree.
21
-
22
- <p align="center"><img src="./assets/demo-doc-fix.gif" alt="mocode autonomously fixes documentation drift" width="100%"></p>
23
-
24
- **Building a web app from scratch, with visual self-verification** — mocode creates a complete Pomodoro timer (HTML/CSS/JS, no third-party libs, Web Audio API), then uses `dev_server` + `browser` + `screenshot` to inspect its own render and iterate until the layout looks right.
25
-
26
- <p align="center"><img src="./assets/demo-build-pomodoro.gif" alt="mocode builds a Pomodoro web app and self-verifies via browser screenshots" width="100%"></p>
27
-
28
- ## Engineering discipline
29
-
30
- MoCode keeps code-level control light and leaves task strategy to the agent:
31
-
32
- - **Advisory working discipline** — The system prompt asks the agent to make focused changes, avoid redundant retrieval, and decide for itself whether validation is useful. Validation is optional and is never a completion gate.
33
- - **Transparent tool failures** — Each tool call runs once and returns its raw structured failure to the agent, which decides whether and how to recover.
34
- - **`ask_human` for user-owned decisions** — The agent asks only when repository evidence cannot resolve a high-impact choice; implementation details remain autonomous.
35
- - **Five-zone context controls + token self-calibration** — Five independent dials (`autoCompact` / `contextOptimize` / `contextRelprune` / `contextLifecycle` / `contextBudget`) manage context pressure. Token estimation self-calibrates against provider usage.
36
-
37
- ## Architecture
38
-
39
- MoCode is organized as a layered runtime: the terminal experience drives an autonomous core, the core reaches capabilities through a guarded execution plane, and a persistent intelligence layer keeps long-running work coherent.
40
-
41
- <p align="center"><img src="./assets/architecture/system-overview.svg" alt="MoCode layered system architecture" width="100%"></p>
42
-
43
- ### Autonomous execution loop
44
-
45
- Each model response is one step in a closed loop. Tool calls are classified by declared capabilities, safe reads can run in parallel, and writes acquire canonical resource locks. Tool evidence returns to history unchanged apart from a hard per-result safety cap. When the agent has no more tools to call, its response completes immediately; the framework does not run hidden validation or force another model turn.
46
-
47
- <p align="center"><img src="./assets/architecture/agent-loop.svg" alt="MoCode autonomous agent execution loop" width="100%"></p>
48
-
49
- ### Context compression only under real pressure
50
-
51
- Normal sessions retain full tool evidence and structured freshness/provenance metadata. At 80% of the model window, one scheduler event runs enabled exact-supersession, stale-artifact, and old-log/search cleanup, then always compacts history. Lifecycle tracking never ages content by tool-call count.
52
-
53
- <p align="center"><img src="./assets/architecture/context-engine.svg" alt="MoCode context engineering and durable memory architecture" width="100%"></p>
54
-
55
- ### Multi-agent work without unsafe shared writes
56
-
57
- Read-only sub-agents fan out concurrently. Writer agents work inside private filesystem overlays and return structured ChangeSets; the coordinator checks expected hashes, acquires canonical locks, and performs conflict-safe merges. Validation remains an explicit agent choice in the shared workspace.
58
-
59
- <p align="center"><img src="./assets/architecture/multi-agent.svg" alt="MoCode multi-agent overlay and ChangeSet coordination" width="100%"></p>
60
-
61
- ### Controlled execution: permission gates and capability scheduling
62
-
63
- Every mutating tool calls into a permission layer before it runs. Tools are classified `safe` / `confirm` / `dangerous`, scopes can be `once` / `session` / `project` / global-tool, fingerprints are stable hashes (command, path, or args), and the persistent record lives in `~/.mocode/permissions.json` (v3 schema, with v2 resource grants still loaded). Piped or CI environments default to deny until you opt in.
64
-
65
- <p align="center"><img src="./assets/architecture/permission-model.svg" alt="MoCode permission model: tool classes, four-tier grants, fingerprinting, durable storage" width="100%"></p>
66
-
67
- ### Agent-directed validation
68
-
69
- MoCode does not run a hidden validation cascade when a task ends. The agent can explicitly call `run_command` for a focused test, typecheck, or build when it judges that evidence useful; otherwise it may finish without an extra framework-controlled round trip.
70
-
71
- ### Rollback timeline: per-mutation snapshots, restore by turn
72
-
73
- A clean undo point is saved before every mutating tool. `/rollback <turnId>` restores file buffers in reverse-chronological order under canonical resource locks — it does not re-run the model or launch automatic tests. Read tools, network effects, and binary changes are explicitly out of scope, kept honest in the contract.
74
-
75
- <p align="center"><img src="./assets/architecture/rollback-flow.svg" alt="MoCode rollback timeline and per-turn snapshot flow" width="100%"></p>
76
-
77
- ### Context controls: one pressure gate, independently optional stages
78
-
79
- The controls remain independently configurable, but automatic rewriting has exactly one trigger: corrected or raw request occupancy reaching 80%. That event runs every enabled pressure cleanup and then always compacts history. `contextLifecycle` only tracks provenance metadata, while EWMA calibration keeps the estimate aligned with provider usage.
80
-
81
- <p align="center"><img src="./assets/architecture/context-controls.svg" alt="MoCode context controls: five independent toggles, observation lifecycle, token self-calibration" width="100%"></p>
82
-
83
- ### Desktop pet: a passive mirror over WebSocket
84
-
85
- The optional Electron sub-package (`packages/pet-app`) shows a stateful floating character that mirrors agent activity via a one-way WebSocket stream. Quit with `/pet quit`. The renderer owns no business logic; the agent loop is unchanged regardless of whether the pet is running.
86
-
87
- <p align="center"><img src="./assets/architecture/pet-bridge.svg" alt="MoCode desktop pet bridge: hooks, frames, Electron client" width="100%"></p>
88
-
89
- ## Why MoCode
90
-
91
- MoCode isn't a chat box with a coat of paint — it's an agent that actually gets things done:
92
-
93
- - **Autonomous multi-step execution** — In a single conversation, the agent chains multiple steps on its own: read code, edit code, run tests, fix based on errors, and so on. It decides the next step without you nagging it. When it hits a decision point, it calls `ask_human` to pop up a panel and ask you (blocking until you respond).
94
- - **Parallel read-only tools** — Consecutive read-only operations in a turn (reading files, grep, glob, codegraph, web search/fetch) run concurrently, so total time is roughly the slowest single call instead of the sum of all of them. Operations with side effects (writing/editing files) stay sequential to preserve snapshot ordering and data safety.
95
- - **Sub-agents divide and conquer** — Complex tasks can spawn independent sub-agents with isolated histories and scoped toolsets. Read-only workers can fan out concurrently; writer workers run in private filesystem overlays and return ChangeSets that are merged under expected-hash checks and canonical resource locks. Only structured findings return to the main thread.
96
- - **Plan / Auto dual mode** — In `plan` mode the agent is read-only (reads code, queries indexes, searches — never writes to disk, runs commands, or spawns sub-agents) and produces a plan; `auto` mode permits execution. Tool capabilities are not a static “full” mode: a lightweight LLM router selects the minimum sufficient groups for each real user turn, and the main model may add groups on a later step when needed.
97
- - **Pressure-driven context compression** — Normal history keeps full tool evidence. At 80% occupancy, one scheduler event runs all enabled cleanup and always follows with a history summary. `/context` shows live usage and `/compact` remains an explicit manual override.
98
- - **Cross-session long-term memory** — The agent can save project architecture, conventions, and lessons learned as long-term memory, auto-loaded in future sessions. A background process periodically reflects on conversations to mine things worth remembering. Memories can be created, searched, updated, and forgotten, with recall-based decay.
99
- - **Project context (`AGENTS.md`)** — A single project-level memory file at `AGENTS.md` captures both static facts (project description, commands, module list, directory tree) and human/AI-written insights (conventions, architectural decisions, pitfalls). Generate it once with `/init`, then keep it up to date by hand or by asking the agent to refresh it. Auto-injected into the system prompt every turn, but lean by design: the `directory tree` and `extension points` sections stay out of the prompt as one-line pointers (read_file `AGENTS.md` on demand), keeping the always-on payload small. During work, the agent may append stable, non-obvious facts it discovers to `.mocode/agents-draft.md`; `/init` merges and clears that draft.
100
- - **Session notepad (notes.md)** — For complex multi-step tasks (≥3 file changes / ≥5 tool calls), the agent maintains a working notepad at `.mocode/sessions/<sessionId>/notes.md` (file-based, survives context compression). It records the execution plan with the dedicated `plan_update` tool — a three-state step machine (`pending`/`in_progress`/`completed`, at most one `in_progress`) that auto-settles to `## Done:` when finished. The active plan is re-injected into the system prompt after compaction and re-synced into context whenever notes.md changes, and a gentle reminder nudges the agent if it goes several tool-steps without updating the plan. A live progress chip in the TUI status bar shows `plan: [title] (3/7) ▸ [current step]`.
101
- - **Interruptible and reversible** — Ctrl+C interrupts the current turn at any time (kills child processes recursively, rolls history back to before the turn started, leaves no half-finished tool calls). `/rollback` restores file changes from per-turn snapshots, with a per-file keep/undo choice — no git dependency required.
102
- - **Input safety net** — Long prompts no longer fear a stray Enter: `Ctrl+G` opens an in-TUI composer popup (notepad-style editing — Enter inserts a newline, with soft wrap, selection, copy/cut/paste and undo; Ctrl+S fills the text back into the input box without sending). `Ctrl+R`/`Ctrl+P` fuzzy-search your input history (Enter only fills it back), and the post-send recall window widens to 2 seconds with any-key recall for long inputs.
103
- - **Sandbox protection** — File reads/writes go through a sandbox that blocks out-of-bounds paths (`../../`, absolute paths outside the root, symlink escapes, etc.), so the agent never touches files outside your working directory.
104
- - **Computer Use (high-risk, routed only for explicit GUI intent)** — When the request genuinely requires real mouse/keyboard interaction, the router can expose the `computer-control` group and feed each resulting screenshot back to the model. `/cu off` (or `MOCODE_COMPUTER_USE_ENABLED=false`) is a hard veto; `/cu on` merely allows routing and does not keep the tool permanently visible. The blast radius exceeds file tools because OS input bypasses the file sandbox. **Use a VM / sandbox / dedicated test machine**, not a daily driver. Every action still passes the permission gate, and plan mode always blocks it. Windows first; macOS/Linux pending.
105
-
106
- ## Features
107
-
108
- - **Streaming output + visible reasoning** — Responses render as they're generated; when the model supports reasoning, the thinking process is visible in real time and auto-collapses to save screen space.
109
- - **Full-screen TUI** — Alt-screen mode with a fixed status bar, scrollback (PgUp/PgDn), typeahead while the agent is running, and auto-prefill for the next turn.
110
- - **Session persistence** — Every turn is saved automatically; `--resume` / `/resume` picks up a past session.
111
- - **Skills system** — Scans directories like `~/.mocode/skills/` automatically; each skill's description is injected into the system prompt, and the model calls `use_skill` to load the full instructions only when relevant (progressive disclosure: skim the summary first, load the body only if needed).
112
- - **Optional desktop pet** — A small floating window (`/pet`) shows a stateful character that mirrors agent activity (idle / thinking / tool running / waiting for human). Works as a separate process over WebSocket; quit it with `/pet quit`. Sits beside the terminal, never blocks it.
113
- - **Slash commands** — `/exit` `/clear` `/cd` `/context` `/skills` `/compact` `/resume` `/rollback` `/memory` `/reflect` `/init` `/theme` `/model` `/plan` `/auto` `/pet`, with dropdown filtering as you type.
114
-
115
- ## Documentation
116
-
117
- - [中文使用指南](./docs/usage.md) — 菜单式快速上手、命令速查、模式、会话、项目上下文与排障。
118
- - [Project context](./docs/usage.md#项目上下文) — `AGENTS.md` and Skills.
119
-
120
- ## Installation
121
-
122
- Requires Node.js ≥ 18.
123
-
124
- ```bash
125
- npm install -g mocode-ai
126
- ```
127
-
128
- This gives you the `mocode` command. Prefer not to install globally? Run it directly with `npx mocode-ai`.
129
-
130
- > MoCode does not contact the registry on startup. Use `/upgrade check`, `/upgrade status`, or `/upgrade now` explicitly when you want to check or install an update. Real installation is disabled in source/tsx development mode.
131
-
132
- ### Run from source (development / contributing)
133
-
134
- ```bash
135
- git clone https://github.com/wanxunyang/mocode.git
136
- cd mocode
137
- npm install
138
- npm start
139
- ```
140
-
141
- Source runs directly via tsx, no build step. After changing code, restart `npm start` for changes to take effect (tsx loads modules at startup, no hot reload). Runtime dependencies: `openai`, `dotenv`, `fast-glob`; dev dependencies: `tsx`, `typescript`, `@types/node`.
142
-
143
- ### Repository stacks and contributing
144
-
145
- The production path is the TypeScript CLI. `packages/work-app` is incubating, `packages/pet-app` is optional, and `rust/` is an experimental, non-critical-path TUI with a mandatory promotion/archive deadline. See:
146
-
147
- - [stack status and owners](docs/architecture/stack-status.md)
148
- - [architecture decisions](docs/adr/README.md)
149
- - [contribution guide](CONTRIBUTING.md)
150
- - [maintainer and troubleshooting runbooks](docs/runbooks/README.md)
151
- - [Rust experiment status](rust/README.md)
152
-
153
- Do not import another package's `src/` or internal `dist/` layout. Applications consume package exports and the public `mocode-agent-host` bin contract.
154
-
155
- ## Configuration
156
-
157
- On first use, run the setup wizard to fill in three fields interactively (API base URL / key / model name), written to `~/.mocode/config` (global, works from any directory or terminal):
158
-
159
- ```bash
160
- mocode config
161
- ```
162
-
163
- You can also configure it from inside the REPL with the `/model` command (pick a backend preset interactively and fill in each field, applied immediately and persisted). Without configuration, the REPL still opens and prompts you to run `/model`.
164
-
165
- You can also hand-edit the config files. MoCode loads them in the following priority order (later entries override earlier ones, only backfilling unset environment variables; anything `export`ed in your shell always takes precedence):
166
-
167
- 1. `<cwd>/.env` — legacy compatibility, lowest priority (see `.env.example` in the source repo for reference)
168
- 2. `~/.mocode/config` — global (written by `/model` and `mocode config`)
169
- 3. `<cwd>/.mocode/config` — project-level override, highest priority
170
-
171
- Three required fields:
172
-
173
- ```env
174
- LLM_BASE_URL=https://open.bigmodel.cn/api/v3 # swap in your backend
175
- LLM_API_KEY=your-key-here
176
- LLM_MODEL=glm-4.6 # swap in your model name
177
- ```
178
-
179
- Common backend `base_url` values:
180
-
181
- | Backend | base_url |
182
- | -------------- | --------------------------------------------------- |
183
- | GLM (Zhipu) | `https://open.bigmodel.cn/api/v3` |
184
- | DeepSeek | `https://api.deepseek.com` |
185
- | Qwen (Alibaba) | `https://dashscope.aliyuncs.com/compatible-mode/v1` |
186
- | Local Ollama | `http://localhost:11434/v1` |
187
- | Local vLLM | `http://localhost:8000/v1` |
188
-
189
- > The model must support OpenAI-style function calling, otherwise tools won't be triggered.
190
-
191
- ### Optional configuration
192
-
193
- | Environment variable | Description | Default |
194
- | ------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------- |
195
- | `MAX_TOKENS` | Max tokens per response | unlimited |
196
- | `CONTEXT_WINDOW_TOKENS` | Model context window; must match the real model | `256000` |
197
- | `LLM_STREAM_USAGE` | Include `stream_options.include_usage` on streaming requests for real usage | `true` |
198
- | `AUTO_COMPACT` | Final history-compaction safety fallback | `true` |
199
- | `AUTO_REFLECT` | Background reflection pass (opt-in; periodically mines memories from conversations) | `false` |
200
- | `REFLECT_EVERY_N` | Trigger a background reflection every N turns (runs alongside the agent, non-blocking) | `5` |
201
- | `ANYSEARCH_API_KEY` | Web search API key (falls back to anonymous free quota if unset) | none |
202
- | `ANYSEARCH_BASE_URL` | Search API endpoint | `https://api.anysearch.com` |
203
- | `SKILLS_DIRS` | Override the default skill scan directories (platform path separator) | three default directories |
204
- | `MOCODE_CONTEXT_OPTIMIZE` | Typed encoding of Cold logs/searches, only under real pressure (set `false` to disable) | `true` |
205
- | `MOCODE_CONTEXT_RELPRUNE` | Exact superseded-evidence pruning, only under real pressure (set `false` to disable) | `true` |
206
- | `MOCODE_LIFECYCLE` | Provenance metadata tracking; never ages or rewrites content | `true` |
207
- | `MAX_STEPS` | Max agent loop steps per turn (infinite-loop safety only) | `1000` |
208
- | `SUB_AGENT_MAX_STEPS` | Sub-agent loop safety ceiling; defaults to the main-agent value | `1000` |
209
- | `SANDBOX_ROOT` | Sandbox root directory (file operation boundary; falls back to cwd if unset) | none |
210
- | `MOCODE_SUBAGENT_ENABLED` | Set `false` to veto the `orchestration` route group; unset/`true` allows on-demand routing | unset |
211
- | `MOCODE_FRONTEND_TOOLS_ENABLED` | Set `false` to veto `browser-debug` and `desktop-observe` (does not affect `background-exec`); unset/`true` allows routing | unset |
212
- | `MOCODE_COMPUTER_USE_ENABLED` | Set `false` to veto high-risk `computer-control`; unset/`true` allows explicit-intent routing | unset |
213
- | `MEMORY_ENABLED` | Set `false` to veto memory groups; `true` also enables the Memory Index | unset |
214
- | `MOCODE_SHELL` | Default shell for `run_command` / `dev_server`: `cmd` \| `powershell` \| `bash` | `cmd` (Windows) / `bash` |
215
- | `MOCODE_WEB_FETCH_PROXY` | Prefix-style plaintext proxy used by `web_fetch` only when a direct fetch is blocked (e.g. `https://r.jina.ai/`); opt-in because it hands your URLs to a third party | unset (disabled) |
216
- | `MOCODE_THEME` | Color theme (default/dark/light…; shell env takes precedence over file) | `default` |
217
-
218
- ## Usage
219
-
220
- ```bash
221
- mocode # new session (run inside your target project directory)
222
- mocode --resume # list saved sessions
223
- mocode --resume <id> # resume a specific session
224
- mocode config # edit configuration
225
- ```
226
-
227
- Running from source uses `npm start` (equivalent to `mocode`, but skips the self-update check).
228
-
229
- Once in the REPL, just start chatting. It launches straight into the full-screen TUI, showing a banner (model / backend / working directory / tool list). Responses stream in, with the reasoning section visible in real time before collapsing.
230
-
231
- The agent operates in **the working directory it was launched from** — to have it work on a specific project, `cd` into that project before running `mocode`.
232
-
233
- ## Tools
234
-
235
- Every real user turn first goes through a constrained LLM router. Nine common tools are always available (`read_file`, `glob`, `grep`, `web_search`, `web_fetch`, `plan_update`, `note_append`, `ask_human`, `use_skill`); additional capabilities are selected as composable groups for writing, shell debugging, browser debugging, desktop observation/control, memory, orchestration, and MCP. If the initial set is insufficient, the main model must call `add_tool_groups` alone; the expanded schemas appear on the next model step. A routing failure reuses the previous turn’s groups (or common-only), never the full toolset.
236
-
237
- | Tool | Purpose |
238
- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
239
- | `read_file` | Read a file: text with line numbers (`offset` / `limit`), images (PNG/JPEG/GIF/WebP detected by magic bytes) as visual model input; other binaries are rejected instead of dumped as garbled text |
240
- | `write_file` | Create/overwrite a file, auto-creating parent directories; `append=true` adds to the end without re-sending the whole file |
241
- | `edit_file` | Precise string replacement (`old_string` must match uniquely) |
242
- | `run_command` | Run a foreground shell command, merging stdout+stderr, 120s default timeout; `shell=cmd\|powershell\|bash` picks the interpreter |
243
- | `glob` | Find files by glob pattern (excludes node_modules/.git) |
244
- | `grep` | Regex content search, pure JS implementation, no `rg` dependency; `context=N` returns neighbouring lines inline so a hit rarely needs a follow-up read |
245
- | `codegraph` | With a `.codegraph/` index built, query symbol source and call chains (more accurate and cheaper than read_file/grep) |
246
- | `web_search` | Web search (AnySearch), returns title/URL/snippet/body |
247
- | `web_fetch` | Fetch a URL, cleaning HTML into plain text; browser-like headers, auto-retry on transient failures, optional plaintext-proxy fallback |
248
- | `use_skill` | Load the full SKILL.md instructions for a given skill |
249
- | `ask_human` | Pop up a Q&A panel at decision points; user picks a preset or types freely (blocks until answered) |
250
- | `plan_update` | Record/update the session execution plan (the `## Plan:` block in notes.md); three-state steps, at most one in_progress, auto-settles to `## Done:` when all complete |
251
- | `sub-agent` | Spawn a capable isolated worker; read tasks can run concurrently and writes use overlay + ChangeSet safe merge |
252
-
253
- | `memory_save` | Save a piece of cross-session long-term memory (title indexed, body fetched on demand) |
254
- | `memory_search` | Search memory bodies by keyword; hits boost the recall count (affects forgetting decay) |
255
- | `memory_list` | List the memory index (id/title/summary, no body) |
256
- | `memory_update` | Edit a memory in place (id unchanged; correct stale facts / update summary / toggle pin) |
257
- | `memory_forget` | Forget a memory: archived by default (recoverable), `mode=delete` for a hard delete (pinned memories can't be deleted) |
258
-
259
- The six `memory_*` tools are split into `memory-read` and `memory-write` route groups. They appear only when the router selects them; `MEMORY_ENABLED=false` vetoes both groups, while `MEMORY_ENABLED=true` also enables the compact Memory Index in the prompt. `/memory_switch` manages that compatibility gate.
260
-
261
- Frontend capabilities are also split by purpose: `browser` forms `browser-debug`, whole-desktop `screenshot` is `desktop-observe`, and `dev_server` has its own ungated `background-exec` group — any process that must outlive a single tool call (dev server, inference service, watcher, log tail) belongs there rather than in `run_command`. Selecting `browser-debug` implies `background-exec`, so a weak model that only asks for the browser still gets the ability to start the server it needs to look at. Image reading lives in `read_file` (magic-byte sniffing) and remains a common read tool. The router may combine these groups with `computer-control` when a task genuinely needs both structured web diagnostics and real desktop interaction. `/fe off` is a hard veto, not a manual profile selector — it does not affect `dev_server`.
262
-
263
- ### Shell selection
264
-
265
- `run_command` and `dev_server` accept `shell=cmd|powershell|bash`. The default is unchanged from earlier releases (`cmd.exe` on Windows, `bash` elsewhere) so existing prompts and skills keep working; `MOCODE_SHELL` flips the default globally for those who prefer POSIX on Windows. When `bash` is requested on Windows, Git for Windows' `bash.exe` is auto-detected — the WSL `System32\bash.exe` is deliberately excluded, since it lands in a Linux distro with different paths, toolchain, and security policy. Non-interactive `cmd.exe` cannot run `timeout /t`; use `shell=powershell` with `Start-Sleep`, or `shell=bash` with `sleep`.
266
-
267
- ### Automatic retry (the `retryable` contract)
268
-
269
- `ToolOutcome.retryable` used to have zero consumers project-wide — a tool honestly marked "this was a transient failure" and nothing acted on it, leaving the model to burn a full LLM round-trip to retry (and often forgetting to). The runtime now re-issues calls that fail transiently, with backoff (400ms / 1200ms, two retries max):
270
-
271
- - Only tools that explicitly declare `idempotent` participate — the side-effect-free network reads (`web_fetch`, `web_search`). No write or process tool declares it, and none is ever auto-retried: retrying those would duplicate side effects, so their retry semantics stay inside the tool (e.g. `edit_file`'s `expected_hash` conflict).
272
- - Only `status=error` with `retryable=true` is retried; `denied` / `aborted` / `success` are terminal.
273
- - **`TIMEOUT` is never auto-retried**: one timeout has already consumed the whole window (`web_fetch` uses 30s), so two retries could stretch a single tool call to 90s — exactly the frozen-spinner experience users hate. The `retryable` flag is still reported, so the model can decide for itself.
274
- - Aborting mid-backoff gives up immediately instead of burning the window, and when retries are exhausted the attempt count is appended to the output so the model knows the runtime already tried.
275
-
276
- ### Frontend / UI loop
277
-
278
- `dev_server` + `browser` form a loop of "start it → open the page → see the rendered result":
279
-
280
- ```
281
- dev_server start command="npm run dev" readyUrl="http://localhost:5173"
282
- browser open → navigate → click / fill → screenshot
283
- dev_server stop id=srv-xxxx
284
- ```
285
-
286
- - `dev_server` processes survive across tool calls (`run_command` can't — it tree-kills children on timeout or when the turn is interrupted). Readiness waiting supports `readyUrl` (loopback only) or `readyPattern` (matches startup logs); logs go to `.mocode/dev-servers/<id>.log` and support incremental reads via `offset`.
287
- - `browser` page sessions also persist across calls; screenshots feed back to the model through the multimodal channel, along with recent console output, page errors, and failed requests.
288
- - Safe defaults: `browser` only allows `http/https` on `localhost / 127.0.0.1 / ::1`, rejecting `file:` and credentialed URLs; set `MOCODE_BROWSER_ALLOW_REMOTE=true` to reach remote hosts. `dev_server` runs arbitrary commands and shares `run_command`'s `dangerous` risk class — requires user confirmation before execution.
289
- - Both are disabled in plan mode; on exit mocode tree-kills background processes and closes the browser.
290
- - The browser binary is not bundled with the npm package; run `npx playwright install chromium` before first use.
291
-
292
- ## Slash commands
293
-
294
- | Command | Purpose |
295
- | ---------------- | ---------------------------------------------------------------------------------------------- |
296
- | `/exit` `/quit` | Exit MoCode |
297
- | `/clear` | Clear history (keeps the system prompt) + clear screen |
298
- | `/cd` | Switch workspace (`/cd <path>`; bare `/cd` shows current, `/cd -` returns). Old session is saved to the old workspace, the new one starts like `/clear` |
299
- | `/image` | Attach a local image to the next message; supports `attach <path>` / `list` / `clear` |
300
- | `/context` | Show a context usage bar (tokens / message count, estimated or measured) |
301
- | `/skills` | List discovered skills |
302
- | `/compact` | Compress history (optionally with a focus hint: `/compact …`) |
303
- | `/resume` | Resume a saved session |
304
- | `/rollback` | Menu to pick a turn to roll back to (↑↓ · Enter) |
305
- | `/memory` | Show memory library: entry count + recent index |
306
- | `/memory_switch` | Allow/block memory routing and toggle the Memory Index; effective next real user turn |
307
- | `/reflect` | Manually trigger a background memory reflection pass |
308
- | `/model` | Configure the LLM (baseURL / apiKey / model / context window), applied immediately + persisted |
309
- | `/init` | Scan the project and generate `AGENTS.md` project memory (dispatched to the agent) |
310
- | `/theme` | Switch color theme (↑↓ · Enter, or `/theme <name>` directly) |
311
- | `/plan` | Switch to plan mode (read-only exploration + plan output, approve to switch to auto) |
312
- | `/auto` | Switch back to executable mode; tools are routed per task |
313
- | `/pet` | Toggle the optional desktop pet (floating window mirroring agent state) |
314
- | `/fe` | Allow/block automatic routing of `browser-debug` and `desktop-observe` |
315
- | `/cu` | Allow/block automatic routing of high-risk `computer-control` |
316
- | `/subagent` | Allow/block automatic routing of `orchestration` |
317
- | `/pet skin` | Pick a pet skin (↑↓ · Enter) |
318
- | `/pet quit` | Fully shut down the pet process (not just disconnect) |
319
-
320
- Type `/` to trigger the dropdown menu, keep typing to filter; Esc to cancel.
321
-
322
- ## Quick verification (after configuring your key)
323
-
324
- ```
325
- > hello, who are you # verify LLM connectivity
326
- > read sample.txt # triggers read_file
327
- > change foo to bar in sample.txt # triggers read_file + edit_file
328
- > list all .txt files in this directory # triggers glob
329
- > search the code for runAgent # triggers grep
330
- > run node -e "console.log(1+1)" # triggers run_command
331
- > search what's new in TypeScript 5.5 # triggers web_search
332
- ```
333
-
334
- Each step prints `● tool name + argument summary` and `↳ result preview` in the terminal; the agent decides the next step on its own within the loop, with responses streaming in as they're generated.
335
-
336
- ## Skills
337
-
338
- MoCode automatically scans the following directories for skills (each skill is a `<name>/SKILL.md` with frontmatter):
339
-
340
- - `~/.claude/skills/`
341
- - `~/.mocode/skills/`
342
- - `<cwd>/.mocode/skills/`
343
-
344
- A skill's `description` is injected into the system prompt (progressive disclosure, tier 1); the model calls `use_skill` to load the full body (tier 2) only when the task is relevant. Use `/skills` to see discovered skills.
345
-
346
- ## Working discipline
347
-
348
- The system prompt provides lightweight guidance rather than a framework gate: inspect only what matters, make focused changes, avoid repeated stale reads, and report uncertainty honestly. The agent decides whether validation is useful for the task and chooses the scope itself. Broad test/build suites are not run by default, and lack of validation never blocks completion or triggers an extra model turn.
349
-
350
- ## Project memory (AGENTS.md)
351
-
352
- MoCode has a **two-tier memory** model distinct from skills:
353
-
354
- - **Tier-1 — `AGENTS.md` (auto-loaded every session):** Markdown project memory that gets concatenated into the system prompt on every turn. Discovery walks `~/.mocode/AGENTS.md` → every `AGENTS.md` from the cwd up to the filesystem root (far→near, near wins). On overflow the body is truncated with a marker pointing back at the files. Generate or refresh one with `/init`, or write it by hand — it's plain Markdown, no schema. `AGENTS.md` is also where the agent itself persists "next-session facts" it deduces (architecture, conventions, pitfalls).
355
- - **Tier-2 — `memory_*` tool library (agent-driven, routed on demand):** Discrete tagged records (`decision` / `fact` / `pitfall` / `reference` / `feedback`) with recall-count-based decay (30-day → archived; 90-day → GC). The LLM router selects `memory-read` for retrieval and `memory-write` only for explicit persistence intent. Set `MEMORY_ENABLED=false` to veto both groups; `true` additionally injects the compact Memory Index. The agent searches before saving and updates existing entries rather than duplicating them.
356
-
357
- ## Type checking
358
-
359
- ```bash
360
- npm run typecheck # tsc --noEmit
361
- ```
362
-
363
- ## Future extensions
364
-
365
- MCP tool integration, finer-grained capability locks, and a real worktree-isolated sub-agent mode. The current version is a streaming, reasoning-visible, rollback-capable terminal coding agent with 20 tools, working-notepad planning, cross-session memory, capability-aware tool scheduling, serial workspace-sharing sub-agents, and an optional desktop pet.
1
+ <img src="./assets/banner-en.svg?v=2" alt="MoCode">
2
+
3
+ <p align="right">English | <a href="./README.zh-CN.md">简体中文</a></p>
4
+
5
+ # MoCode
6
+
7
+ [![npm version](https://img.shields.io/npm/v/mocode-ai.svg)](https://www.npmjs.com/package/mocode-ai)
8
+ [![npm downloads](https://img.shields.io/npm/dm/mocode-ai.svg)](https://www.npmjs.com/package/mocode-ai)
9
+ [![CI](https://img.shields.io/github/actions/workflow/status/wanxunyang/mocode/ci.yml?label=CI)](https://github.com/wanxunyang/mocode/actions/workflows/ci.yml)
10
+ [![license](https://img.shields.io/github/license/wanxunyang/mocode)](https://github.com/wanxunyang/mocode/blob/main/LICENSE)
11
+
12
+ A terminal coding agent: give it a goal, and it **completes it autonomously** — no step-by-step hand-holding required.
13
+
14
+ MoCode explores your code, reads/writes/edits files, runs shell commands, and searches the web on its own, driving the task forward through a loop of "think → call a tool → observe the result → think again." It works with any OpenAI-compatible endpoint (GLM, DeepSeek, Qwen, local Ollama / vLLM, etc.), runs as a full-screen TUI with streaming output and visible reasoning.
15
+
16
+ ## Demo
17
+
18
+ See mocode complete real tasks autonomously:
19
+
20
+ **Fixing documentation drift in its own codebase** — mocode counts the actual built-in tools, finds the mismatch with `package.json` and `AGENTS.md`, and rewrites them so all three sources agree.
21
+
22
+ <p align="center"><img src="./assets/demo-doc-fix.gif" alt="mocode autonomously fixes documentation drift" width="100%"></p>
23
+
24
+ **Building a web app from scratch, with visual self-verification** — mocode creates a complete Pomodoro timer (HTML/CSS/JS, no third-party libs, Web Audio API), then uses `dev_server` + `browser` + `screenshot` to inspect its own render and iterate until the layout looks right.
25
+
26
+ <p align="center"><img src="./assets/demo-build-pomodoro.gif" alt="mocode builds a Pomodoro web app and self-verifies via browser screenshots" width="100%"></p>
27
+
28
+ ## Faster and more token-efficient
29
+
30
+ - **Two-level model picker** — A bare `/model` lists providers first; Enter drills into one to pick a model. Search is scoped to the current level — provider names at the top, model names inside a provider — never mixed into one flat list.
31
+ - **Reasoning effort `/effort`** — One normalized `off / low / medium / high / auto`, translated per target model (Anthropic / OpenAI o·gpt-5 / Qwen3 / GLM / DeepSeek-R1 / Doubao). Unknown models and third-party gateways get **no** unknown fields, avoiding hard 400s.
32
+ - **Usage stats `/stats`** — This session's cache hit rate, tiered token usage, and compaction count, built from real provider reports rather than estimates.
33
+ - **Cache-safe compaction fork** — When prior dialogue can be reused verbatim, it forks to preserve the prompt-cache prefix and avoid rebilling; otherwise it falls back to summarization (disable with `MOCODE_COMPACT_FORK=false`).
34
+ - **Repeated-read de-duplication** — Re-reading the same file within one turn hits a cache, so you never pay twice for identical content (disable with `MOCODE_READ_DEDUP=false`).
35
+ - **Sub-agent depth gate** — Recursive spawning is capped at 3 levels by default (tune with `SUB_AGENT_MAX_DEPTH`), preventing unbounded sub-agent fan-out.
36
+
37
+ ## Engineering discipline
38
+
39
+ MoCode keeps code-level control light and leaves task strategy to the agent:
40
+
41
+ - **Advisory working discipline** — The system prompt asks the agent to make focused changes, avoid redundant retrieval, and decide for itself whether validation is useful. Validation is optional and is never a completion gate.
42
+ - **Transparent tool failures** — Each tool call runs once and returns its raw structured failure to the agent, which decides whether and how to recover.
43
+ - **`ask_human` for user-owned decisions** — The agent asks only when repository evidence cannot resolve a high-impact choice; implementation details remain autonomous.
44
+ - **Five-zone context controls + token self-calibration** — Five independent dials (`autoCompact` / `contextOptimize` / `contextRelprune` / `contextLifecycle` / `contextBudget`) manage context pressure. Token estimation self-calibrates against provider usage.
45
+
46
+ ## Architecture
47
+
48
+ MoCode is organized as a layered runtime: the terminal experience drives an autonomous core, the core reaches capabilities through a guarded execution plane, and a persistent intelligence layer keeps long-running work coherent.
49
+
50
+ <p align="center"><img src="./assets/architecture/system-overview.svg" alt="MoCode layered system architecture" width="100%"></p>
51
+
52
+ ### Autonomous execution loop
53
+
54
+ Each model response is one step in a closed loop. Tool calls are classified by declared capabilities, safe reads can run in parallel, and writes acquire canonical resource locks. Tool evidence returns to history unchanged apart from a hard per-result safety cap. When the agent has no more tools to call, its response completes immediately; the framework does not run hidden validation or force another model turn.
55
+
56
+ <p align="center"><img src="./assets/architecture/agent-loop.svg" alt="MoCode autonomous agent execution loop" width="100%"></p>
57
+
58
+ ### Context compression only under real pressure
59
+
60
+ Normal sessions retain full tool evidence and structured freshness/provenance metadata. At 80% of the model window, one scheduler event runs enabled exact-supersession, stale-artifact, and old-log/search cleanup, then always compacts history. Lifecycle tracking never ages content by tool-call count.
61
+
62
+ <p align="center"><img src="./assets/architecture/context-engine.svg" alt="MoCode context engineering and durable memory architecture" width="100%"></p>
63
+
64
+ ### Multi-agent work without unsafe shared writes
65
+
66
+ Read-only sub-agents fan out concurrently. Writer agents work inside private filesystem overlays and return structured ChangeSets; the coordinator checks expected hashes, acquires canonical locks, and performs conflict-safe merges. Validation remains an explicit agent choice in the shared workspace.
67
+
68
+ <p align="center"><img src="./assets/architecture/multi-agent.svg" alt="MoCode multi-agent overlay and ChangeSet coordination" width="100%"></p>
69
+
70
+ ### Controlled execution: permission gates and capability scheduling
71
+
72
+ Every mutating tool calls into a permission layer before it runs. Tools are classified `safe` / `confirm` / `dangerous`, scopes can be `once` / `session` / `project` / global-tool, fingerprints are stable hashes (command, path, or args), and the persistent record lives in `~/.mocode/permissions.json` (v3 schema, with v2 resource grants still loaded). Piped or CI environments default to deny until you opt in.
73
+
74
+ <p align="center"><img src="./assets/architecture/permission-model.svg" alt="MoCode permission model: tool classes, four-tier grants, fingerprinting, durable storage" width="100%"></p>
75
+
76
+ ### Agent-directed validation
77
+
78
+ MoCode does not run a hidden validation cascade when a task ends. The agent can explicitly call `run_command` for a focused test, typecheck, or build when it judges that evidence useful; otherwise it may finish without an extra framework-controlled round trip.
79
+
80
+ ### Rollback timeline: per-mutation snapshots, restore by turn
81
+
82
+ A clean undo point is saved before every mutating tool. `/rollback <turnId>` restores file buffers in reverse-chronological order under canonical resource locks — it does not re-run the model or launch automatic tests. Read tools, network effects, and binary changes are explicitly out of scope, kept honest in the contract.
83
+
84
+ <p align="center"><img src="./assets/architecture/rollback-flow.svg" alt="MoCode rollback timeline and per-turn snapshot flow" width="100%"></p>
85
+
86
+ ### Context controls: one pressure gate, independently optional stages
87
+
88
+ The controls remain independently configurable, but automatic rewriting has exactly one trigger: corrected or raw request occupancy reaching 80%. That event runs every enabled pressure cleanup and then always compacts history. `contextLifecycle` only tracks provenance metadata, while EWMA calibration keeps the estimate aligned with provider usage.
89
+
90
+ <p align="center"><img src="./assets/architecture/context-controls.svg" alt="MoCode context controls: five independent toggles, observation lifecycle, token self-calibration" width="100%"></p>
91
+
92
+ ### Desktop pet: a passive mirror over WebSocket
93
+
94
+ The optional Electron sub-package (`packages/pet-app`) shows a stateful floating character that mirrors agent activity via a one-way WebSocket stream. Quit with `/pet quit`. The renderer owns no business logic; the agent loop is unchanged regardless of whether the pet is running.
95
+
96
+ <p align="center"><img src="./assets/architecture/pet-bridge.svg" alt="MoCode desktop pet bridge: hooks, frames, Electron client" width="100%"></p>
97
+
98
+ ## Why MoCode
99
+
100
+ MoCode isn't a chat box with a coat of paint — it's an agent that actually gets things done:
101
+
102
+ - **Autonomous multi-step execution** — In a single conversation, the agent chains multiple steps on its own: read code, edit code, run tests, fix based on errors, and so on. It decides the next step without you nagging it. When it hits a decision point, it calls `ask_human` to pop up a panel and ask you (blocking until you respond).
103
+ - **Parallel read-only tools** — Consecutive read-only operations in a turn (reading files, grep, glob, codegraph, web search/fetch) run concurrently, so total time is roughly the slowest single call instead of the sum of all of them. Operations with side effects (writing/editing files) stay sequential to preserve snapshot ordering and data safety.
104
+ - **Sub-agents divide and conquer** — Complex tasks can spawn independent sub-agents with isolated histories and scoped toolsets. Read-only workers can fan out concurrently; writer workers run in private filesystem overlays and return ChangeSets that are merged under expected-hash checks and canonical resource locks. Only structured findings return to the main thread.
105
+ - **Plan / Auto dual mode** — In `plan` mode the agent is read-only (reads code, queries indexes, searches — never writes to disk, runs commands, or spawns sub-agents) and produces a plan; `auto` mode permits execution. Tool capabilities are not a static “full” mode: a lightweight LLM router selects the minimum sufficient groups for each real user turn, and the main model may add groups on a later step when needed.
106
+ - **Pressure-driven context compression** — Normal history keeps full tool evidence. At 80% occupancy, one scheduler event runs all enabled cleanup and always follows with a history summary. `/context` shows live usage and `/compact` remains an explicit manual override.
107
+ - **Cross-session long-term memory** — The agent can save project architecture, conventions, and lessons learned as long-term memory, auto-loaded in future sessions. A background process periodically reflects on conversations to mine things worth remembering. Memories can be created, searched, updated, and forgotten, with recall-based decay.
108
+ - **Project context (`AGENTS.md`)** — A single project-level memory file at `AGENTS.md` captures both static facts (project description, commands, module list, directory tree) and human/AI-written insights (conventions, architectural decisions, pitfalls). Generate it once with `/init`, then keep it up to date by hand or by asking the agent to refresh it. Auto-injected into the system prompt every turn, but lean by design: the `directory tree` and `extension points` sections stay out of the prompt as one-line pointers (read_file `AGENTS.md` on demand), keeping the always-on payload small. During work, the agent may append stable, non-obvious facts it discovers to `.mocode/agents-draft.md`; `/init` merges and clears that draft.
109
+ - **Session notepad (notes.md)** — For complex multi-step tasks (≥3 file changes / ≥5 tool calls), the agent maintains a working notepad at `.mocode/sessions/<sessionId>/notes.md` (file-based, survives context compression). It records the execution plan with the dedicated `plan_update` tool — a three-state step machine (`pending`/`in_progress`/`completed`, at most one `in_progress`) that auto-settles to `## Done:` when finished. The active plan is re-injected into the system prompt after compaction and re-synced into context whenever notes.md changes, and a gentle reminder nudges the agent if it goes several tool-steps without updating the plan. A live progress chip in the TUI status bar shows `plan: [title] (3/7) ▸ [current step]`.
110
+ - **Interruptible and reversible** — Ctrl+C interrupts the current turn at any time (kills child processes recursively, rolls history back to before the turn started, leaves no half-finished tool calls). `/rollback` restores file changes from per-turn snapshots, with a per-file keep/undo choice — no git dependency required.
111
+ - **Input safety net** — Long prompts no longer fear a stray Enter: `Ctrl+G` opens an in-TUI composer popup (notepad-style editing — Enter inserts a newline, with soft wrap, selection, copy/cut/paste and undo; Ctrl+S fills the text back into the input box without sending). `Ctrl+R`/`Ctrl+P` fuzzy-search your input history (Enter only fills it back), and the post-send recall window widens to 2 seconds with any-key recall for long inputs.
112
+ - **Sandbox protection** — File reads/writes go through a sandbox that blocks out-of-bounds paths (`../../`, absolute paths outside the root, symlink escapes, etc.), so the agent never touches files outside your working directory.
113
+ - **Computer Use (high-risk, routed only for explicit GUI intent)** — When the request genuinely requires real mouse/keyboard interaction, the router can expose the `computer-control` group and feed each resulting screenshot back to the model. `/cu off` (or `MOCODE_COMPUTER_USE_ENABLED=false`) is a hard veto; `/cu on` merely allows routing and does not keep the tool permanently visible. The blast radius exceeds file tools because OS input bypasses the file sandbox. **Use a VM / sandbox / dedicated test machine**, not a daily driver. Every action still passes the permission gate, and plan mode always blocks it. Windows first; macOS/Linux pending.
114
+
115
+ ## Features
116
+
117
+ - **Streaming output + visible reasoning** — Responses render as they're generated; when the model supports reasoning, the thinking process is visible in real time and auto-collapses to save screen space.
118
+ - **Full-screen TUI** — Alt-screen mode with a fixed status bar, scrollback (PgUp/PgDn), typeahead while the agent is running, and auto-prefill for the next turn.
119
+ - **Session persistence** — Every turn is saved automatically; `--resume` / `/resume` picks up a past session.
120
+ - **Background jobs** — `mocode run --bg "task"` spawns a detached process that survives terminal close; state and logs land in `.mocode/jobs/`, and `/jobs` lists, tails logs, or kills them. Set `MOCODE_NOTIFY_WEBHOOK` to push a finish notification (ntfy/Bark/Telegram/generic). When an unattended job hits an unauthorised confirm/dangerous action it parks (status `paused`) and pings you; approve in another terminal with `mocode approve <id>` (`mocode deny` to reject, or `/jobs approve` inside the TUI), and it resumes in the same process. Follow a running (or finished) job live with `mocode attach <id>`. Long jobs checkpoint their history after every tool batch; if the process dies or the machine reboots, `mocode resume-job <id>` replays from the last checkpoint (in-flight work is re-run). `MOCODE_JOB_MAX_MS` / `MOCODE_JOB_MAX_TOKENS` add hard wall-clock/token caps.
121
+ - **Named bots** — `mocode bots add` defines role-based bots (job-specific system prompt + optional exact-tool whitelist + sandbox scope) at project/global level; run with `--bot <name>`, combine with `run --bg` or schedules.
122
+ - **Arena** — The `arena` tool runs the same task N times (2-6) as parallel independent workers, then a judge model ranks every candidate against your criteria and returns the winner with the full ranking. Useful for design/exploration/problem-solving where several attempts beat one.
123
+ - **Persistent bot messaging** — The `message_bus` tool gives named bots a durable, asynchronous message store (`send` / `inbox` / `ack` / `history`): a supervisor bot can hand off work to another bot that is not currently running; the worker reads its inbox later (e.g. when a schedule wakes it), does the job, and replies. Identity follows the `--bot` identity, and each bot only sees/acks its own messages.
124
+ - **Scheduled tasks** — `mocode schedule add` registers cron and/or webhook triggers; a local detached daemon (`schedule start`, loopback-only) fires background jobs on time or on `POST /trigger/<token>`, with per-minute dedup. A stateless `schedule tick` is also available for OS task schedulers.
125
+ - **Headless one-shot mode** — `mocode -p "task"` or piped `echo "task" | mocode`, with optional `--json` structured output; confirm/dangerous actions are denied by default when non-interactive (opt in with `--dangerously-skip-permissions`; `--verbose` adds tool-result summaries, `--session-dir <dir>`, `--worktree` ephemeral git worktree), and sessions are still saved for `--resume`.
126
+ - **Skills system** — Scans directories like `~/.mocode/skills/` automatically; each skill's description is injected into the system prompt, and the model calls `use_skill` to load the full instructions only when relevant (progressive disclosure: skim the summary first, load the body only if needed).
127
+ - **Optional desktop pet** — A small floating window (`/pet`) shows a stateful character that mirrors agent activity (idle / thinking / tool running / waiting for human). Works as a separate process over WebSocket; quit it with `/pet quit`. Sits beside the terminal, never blocks it.
128
+ - **Slash commands** — `/exit` `/clear` `/cd` `/context` `/skills` `/compact` `/resume` `/rollback` `/jobs` `/schedules` `/bots` `/memory` `/reflect` `/init` `/theme` `/model` `/effort` `/stats` `/plan` `/auto` `/pet`, with dropdown filtering as you type.
129
+
130
+ ## Documentation
131
+
132
+ - [中文使用指南](./docs/usage.md) — 菜单式快速上手、命令速查、模式、会话、项目上下文与排障。
133
+ - [Project context](./docs/usage.md#项目上下文) — `AGENTS.md` and Skills.
134
+
135
+ ## Installation
136
+
137
+ Requires Node.js ≥ 18.
138
+
139
+ ```bash
140
+ npm install -g mocode-ai
141
+ ```
142
+
143
+ This gives you the `mocode` command. Prefer not to install globally? Run it directly with `npx mocode-ai`.
144
+
145
+ > MoCode does not contact the registry on startup. Use `/upgrade check`, `/upgrade status`, or `/upgrade now` explicitly when you want to check or install an update. Real installation is disabled in source/tsx development mode.
146
+
147
+ ### Run from source (development / contributing)
148
+
149
+ ```bash
150
+ git clone https://github.com/wanxunyang/mocode.git
151
+ cd mocode
152
+ npm install
153
+ npm start
154
+ ```
155
+
156
+ Source runs directly via tsx, no build step. After changing code, restart `npm start` for changes to take effect (tsx loads modules at startup, no hot reload). Runtime dependencies: `openai`, `dotenv`, `fast-glob`; dev dependencies: `tsx`, `typescript`, `@types/node`.
157
+
158
+ ### Repository stacks and contributing
159
+
160
+ The production path is the TypeScript CLI. `packages/work-app` is incubating, `packages/pet-app` is optional, and `rust/` is an experimental, non-critical-path TUI with a mandatory promotion/archive deadline. See:
161
+
162
+ - [stack status and owners](docs/architecture/stack-status.md)
163
+ - [architecture decisions](docs/adr/README.md)
164
+ - [contribution guide](CONTRIBUTING.md)
165
+ - [maintainer and troubleshooting runbooks](docs/runbooks/README.md)
166
+ - [Rust experiment status](rust/README.md)
167
+
168
+ Do not import another package's `src/` or internal `dist/` layout. Applications consume package exports and the public `mocode-agent-host` bin contract.
169
+
170
+ ## Configuration
171
+
172
+ On first use, run the setup wizard to fill in three fields interactively (API base URL / key / model name), written to `~/.mocode/config` (global, works from any directory or terminal):
173
+
174
+ ```bash
175
+ mocode config
176
+ ```
177
+
178
+ You can also configure it from inside the REPL with the `/model` command (pick a backend preset interactively and fill in each field, applied immediately and persisted). Without configuration, the REPL still opens and prompts you to run `/model`.
179
+
180
+ You can also hand-edit the config files. MoCode loads them in the following priority order (later entries override earlier ones, only backfilling unset environment variables; anything `export`ed in your shell always takes precedence):
181
+
182
+ 1. `<cwd>/.env` — legacy compatibility, lowest priority (see `.env.example` in the source repo for reference)
183
+ 2. `~/.mocode/config` — global (written by `/model` and `mocode config`)
184
+ 3. `<cwd>/.mocode/config` — project-level override, highest priority
185
+
186
+ Three required fields:
187
+
188
+ ```env
189
+ LLM_BASE_URL=https://open.bigmodel.cn/api/v3 # swap in your backend
190
+ LLM_API_KEY=your-key-here
191
+ LLM_MODEL=glm-4.6 # swap in your model name
192
+ ```
193
+
194
+ Common backend `base_url` values:
195
+
196
+ | Backend | base_url |
197
+ | -------------- | --------------------------------------------------- |
198
+ | GLM (Zhipu) | `https://open.bigmodel.cn/api/v3` |
199
+ | DeepSeek | `https://api.deepseek.com` |
200
+ | Qwen (Alibaba) | `https://dashscope.aliyuncs.com/compatible-mode/v1` |
201
+ | Local Ollama | `http://localhost:11434/v1` |
202
+ | Local vLLM | `http://localhost:8000/v1` |
203
+
204
+ > The model must support OpenAI-style function calling, otherwise tools won't be triggered.
205
+
206
+ ### Optional configuration
207
+
208
+ | Environment variable | Description | Default |
209
+ | ------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------- |
210
+ | `MAX_TOKENS` | Max tokens per response | unlimited |
211
+ | `CONTEXT_WINDOW_TOKENS` | Model context window; must match the real model | `256000` |
212
+ | `LLM_STREAM_USAGE` | Include `stream_options.include_usage` on streaming requests for real usage | `true` |
213
+ | `AUTO_COMPACT` | Final history-compaction safety fallback | `true` |
214
+ | `AUTO_REFLECT` | Background reflection pass (opt-in; periodically mines memories from conversations) | `false` |
215
+ | `REFLECT_EVERY_N` | Trigger a background reflection every N turns (runs alongside the agent, non-blocking) | `5` |
216
+ | `ANYSEARCH_API_KEY` | Web search API key (falls back to anonymous free quota if unset) | none |
217
+ | `ANYSEARCH_BASE_URL` | Search API endpoint | `https://api.anysearch.com` |
218
+ | `SKILLS_DIRS` | Override the default skill scan directories (platform path separator) | three default directories |
219
+ | `MOCODE_CONTEXT_OPTIMIZE` | Typed encoding of Cold logs/searches, only under real pressure (set `false` to disable) | `true` |
220
+ | `MOCODE_CONTEXT_RELPRUNE` | Exact superseded-evidence pruning, only under real pressure (set `false` to disable) | `true` |
221
+ | `MOCODE_LIFECYCLE` | Provenance metadata tracking; never ages or rewrites content | `true` |
222
+ | `MAX_STEPS` | Max agent loop steps per turn (infinite-loop safety only) | `1000` |
223
+ | `SUB_AGENT_MAX_STEPS` | Sub-agent loop safety ceiling; defaults to the main-agent value | `1000` |
224
+ | `SANDBOX_ROOT` | Sandbox root directory (file operation boundary; falls back to cwd if unset) | none |
225
+ | `MOCODE_SUBAGENT_ENABLED` | Set `false` to veto the `orchestration` route group; unset/`true` allows on-demand routing | unset |
226
+ | `MOCODE_FRONTEND_TOOLS_ENABLED` | Set `false` to veto `browser-debug` and `desktop-observe` (does not affect `background-exec`); unset/`true` allows routing | unset |
227
+ | `MOCODE_COMPUTER_USE_ENABLED` | Set `false` to veto high-risk `computer-control`; unset/`true` allows explicit-intent routing | unset |
228
+ | `MEMORY_ENABLED` | Set `false` to veto memory groups; `true` also enables the Memory Index | unset |
229
+ | `MOCODE_SHELL` | Default shell for `run_command` / `dev_server`: `cmd` \| `powershell` \| `bash` | `cmd` (Windows) / `bash` |
230
+ | `MOCODE_WEB_FETCH_PROXY` | Prefix-style plaintext proxy used by `web_fetch` only when a direct fetch is blocked (e.g. `https://r.jina.ai/`); opt-in because it hands your URLs to a third party | unset (disabled) |
231
+ | `MOCODE_THEME` | Color theme (default/dark/light…; shell env takes precedence over file) | `default` |
232
+
233
+ ## Usage
234
+
235
+ ```bash
236
+ mocode # new session (run inside your target project directory)
237
+ mocode --resume # list saved sessions
238
+ mocode --resume <id> # resume a specific session
239
+ mocode config # edit configuration
240
+ ```
241
+
242
+ Running from source uses `npm start` (equivalent to `mocode`, but skips the self-update check).
243
+
244
+ Once in the REPL, just start chatting. It launches straight into the full-screen TUI, showing a banner (model / backend / working directory / tool list). Responses stream in, with the reasoning section visible in real time before collapsing.
245
+
246
+ The agent operates in **the working directory it was launched from** — to have it work on a specific project, `cd` into that project before running `mocode`.
247
+
248
+ ## Tools
249
+
250
+ Every real user turn first goes through a constrained LLM router. Nine common tools are always available (`read_file`, `glob`, `grep`, `web_search`, `web_fetch`, `plan_update`, `note_append`, `ask_human`, `use_skill`); additional capabilities are selected as composable groups for writing, shell debugging, browser debugging, desktop observation/control, memory, orchestration, and MCP. If the initial set is insufficient, the main model must call `add_tool_groups` alone; the expanded schemas appear on the next model step. A routing failure reuses the previous turn’s groups (or common-only), never the full toolset.
251
+
252
+ | Tool | Purpose |
253
+ | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
254
+ | `read_file` | Read a file: text with line numbers (`offset` / `limit`), images (PNG/JPEG/GIF/WebP detected by magic bytes) as visual model input; other binaries are rejected instead of dumped as garbled text |
255
+ | `write_file` | Create/overwrite a file, auto-creating parent directories; `append=true` adds to the end without re-sending the whole file |
256
+ | `edit_file` | Precise string replacement (`old_string` must match uniquely) |
257
+ | `run_command` | Run a foreground shell command, merging stdout+stderr, 120s default timeout; `shell=cmd\|powershell\|bash` picks the interpreter |
258
+ | `glob` | Find files by glob pattern (excludes node_modules/.git) |
259
+ | `grep` | Regex content search, pure JS implementation, no `rg` dependency; `context=N` returns neighbouring lines inline so a hit rarely needs a follow-up read |
260
+ | `codegraph` | With a `.codegraph/` index built, query symbol source and call chains (more accurate and cheaper than read_file/grep) |
261
+ | `web_search` | Web search (AnySearch), returns title/URL/snippet/body |
262
+ | `web_fetch` | Fetch a URL, cleaning HTML into plain text; browser-like headers, auto-retry on transient failures, optional plaintext-proxy fallback |
263
+ | `use_skill` | Load the full SKILL.md instructions for a given skill |
264
+ | `ask_human` | Pop up a Q&A panel at decision points; user picks a preset or types freely (blocks until answered) |
265
+ | `plan_update` | Record/update the session execution plan (the `## Plan:` block in notes.md); three-state steps, at most one in_progress, auto-settles to `## Done:` when all complete |
266
+ | `sub-agent` | Spawn a capable isolated worker; read tasks can run concurrently and writes use overlay + ChangeSet safe merge |
267
+
268
+ | `memory_save` | Save a piece of cross-session long-term memory (title indexed, body fetched on demand) |
269
+ | `memory_search` | Search memory bodies by keyword; hits boost the recall count (affects forgetting decay) |
270
+ | `memory_list` | List the memory index (id/title/summary, no body) |
271
+ | `memory_update` | Edit a memory in place (id unchanged; correct stale facts / update summary / toggle pin) |
272
+ | `memory_forget` | Forget a memory: archived by default (recoverable), `mode=delete` for a hard delete (pinned memories can't be deleted) |
273
+
274
+ The six `memory_*` tools are split into `memory-read` and `memory-write` route groups. They appear only when the router selects them; `MEMORY_ENABLED=false` vetoes both groups, while `MEMORY_ENABLED=true` also enables the compact Memory Index in the prompt. `/memory_switch` manages that compatibility gate.
275
+
276
+ Frontend capabilities are also split by purpose: `browser` forms `browser-debug`, whole-desktop `screenshot` is `desktop-observe`, and `dev_server` has its own ungated `background-exec` group — any process that must outlive a single tool call (dev server, inference service, watcher, log tail) belongs there rather than in `run_command`. Selecting `browser-debug` implies `background-exec`, so a weak model that only asks for the browser still gets the ability to start the server it needs to look at. Image reading lives in `read_file` (magic-byte sniffing) and remains a common read tool. The router may combine these groups with `computer-control` when a task genuinely needs both structured web diagnostics and real desktop interaction. `/fe off` is a hard veto, not a manual profile selector — it does not affect `dev_server`.
277
+
278
+ ### Shell selection
279
+
280
+ `run_command` and `dev_server` accept `shell=cmd|powershell|bash`. The default is unchanged from earlier releases (`cmd.exe` on Windows, `bash` elsewhere) so existing prompts and skills keep working; `MOCODE_SHELL` flips the default globally for those who prefer POSIX on Windows. When `bash` is requested on Windows, Git for Windows' `bash.exe` is auto-detected — the WSL `System32\bash.exe` is deliberately excluded, since it lands in a Linux distro with different paths, toolchain, and security policy. Non-interactive `cmd.exe` cannot run `timeout /t`; use `shell=powershell` with `Start-Sleep`, or `shell=bash` with `sleep`.
281
+
282
+ ### Automatic retry (the `retryable` contract)
283
+
284
+ `ToolOutcome.retryable` used to have zero consumers project-wide — a tool honestly marked "this was a transient failure" and nothing acted on it, leaving the model to burn a full LLM round-trip to retry (and often forgetting to). The runtime now re-issues calls that fail transiently, with backoff (400ms / 1200ms, two retries max):
285
+
286
+ - Only tools that explicitly declare `idempotent` participate — the side-effect-free network reads (`web_fetch`, `web_search`). No write or process tool declares it, and none is ever auto-retried: retrying those would duplicate side effects, so their retry semantics stay inside the tool (e.g. `edit_file`'s `expected_hash` conflict).
287
+ - Only `status=error` with `retryable=true` is retried; `denied` / `aborted` / `success` are terminal.
288
+ - **`TIMEOUT` is never auto-retried**: one timeout has already consumed the whole window (`web_fetch` uses 30s), so two retries could stretch a single tool call to 90s — exactly the frozen-spinner experience users hate. The `retryable` flag is still reported, so the model can decide for itself.
289
+ - Aborting mid-backoff gives up immediately instead of burning the window, and when retries are exhausted the attempt count is appended to the output so the model knows the runtime already tried.
290
+
291
+ ### Frontend / UI loop
292
+
293
+ `dev_server` + `browser` form a loop of "start it → open the page → see the rendered result":
294
+
295
+ ```
296
+ dev_server start command="npm run dev" readyUrl="http://localhost:5173"
297
+ browser open → navigate → click / fill → screenshot
298
+ dev_server stop id=srv-xxxx
299
+ ```
300
+
301
+ - `dev_server` processes survive across tool calls (`run_command` can't — it tree-kills children on timeout or when the turn is interrupted). Readiness waiting supports `readyUrl` (loopback only) or `readyPattern` (matches startup logs); logs go to `.mocode/dev-servers/<id>.log` and support incremental reads via `offset`.
302
+ - `browser` page sessions also persist across calls; screenshots feed back to the model through the multimodal channel, along with recent console output, page errors, and failed requests.
303
+ - Safe defaults: `browser` only allows `http/https` on `localhost / 127.0.0.1 / ::1`, rejecting `file:` and credentialed URLs; set `MOCODE_BROWSER_ALLOW_REMOTE=true` to reach remote hosts. `dev_server` runs arbitrary commands and shares `run_command`'s `dangerous` risk class — requires user confirmation before execution.
304
+ - Both are disabled in plan mode; on exit mocode tree-kills background processes and closes the browser.
305
+ - The browser binary is not bundled with the npm package; run `npx playwright install chromium` before first use.
306
+
307
+ ## Slash commands
308
+
309
+ | Command | Purpose |
310
+ | ---------------- | ---------------------------------------------------------------------------------------------- |
311
+ | `/exit` `/quit` | Exit MoCode |
312
+ | `/clear` | Clear history (keeps the system prompt) + clear screen |
313
+ | `/cd` | Switch workspace (`/cd <path>`; bare `/cd` shows current, `/cd -` returns). Old session is saved to the old workspace, the new one starts like `/clear` |
314
+ | `/image` | Attach a local image to the next message; supports `attach <path>` / `list` / `clear` |
315
+ | `/context` | Show a context usage bar (tokens / message count, estimated or measured) |
316
+ | `/skills` | List discovered skills |
317
+ | `/compact` | Compress history (optionally with a focus hint: `/compact …`) |
318
+ | `/resume` | Resume a saved session |
319
+ | `/rollback` | Menu to pick a turn to roll back to (↑↓ · Enter) |
320
+ | `/memory` | Show memory library: entry count + recent index |
321
+ | `/memory_switch` | Allow/block memory routing and toggle the Memory Index; effective next real user turn |
322
+ | `/reflect` | Manually trigger a background memory reflection pass |
323
+ | `/model` | Two-level picker (provider → model; scoped search), plus baseURL / apiKey / context-window config; applied immediately + persisted |
324
+ | `/effort` | Set reasoning effort off/low/medium/high/auto (e.g. `/effort high`); not sent for unrecognized models |
325
+ | `/stats` | Session usage: cache hit rate / tiered tokens / compaction count |
326
+ | `/init` | Scan the project and generate `AGENTS.md` project memory (dispatched to the agent) |
327
+ | `/theme` | Switch color theme (↑↓ · Enter, or `/theme <name>` directly) |
328
+ | `/plan` | Switch to plan mode (read-only exploration + plan output, approve to switch to auto) |
329
+ | `/auto` | Switch back to executable mode; tools are routed per task |
330
+ | `/pet` | Toggle the optional desktop pet (floating window mirroring agent state) |
331
+ | `/fe` | Allow/block automatic routing of `browser-debug` and `desktop-observe` |
332
+ | `/cu` | Allow/block automatic routing of high-risk `computer-control` |
333
+ | `/subagent` | Allow/block automatic routing of `orchestration` |
334
+ | `/pet skin` | Pick a pet skin (↑↓ · Enter) |
335
+ | `/pet quit` | Fully shut down the pet process (not just disconnect) |
336
+
337
+ Type `/` to trigger the dropdown menu, keep typing to filter; Esc to cancel.
338
+
339
+ ## Quick verification (after configuring your key)
340
+
341
+ ```
342
+ > hello, who are you # verify LLM connectivity
343
+ > read sample.txt # triggers read_file
344
+ > change foo to bar in sample.txt # triggers read_file + edit_file
345
+ > list all .txt files in this directory # triggers glob
346
+ > search the code for runAgent # triggers grep
347
+ > run node -e "console.log(1+1)" # triggers run_command
348
+ > search what's new in TypeScript 5.5 # triggers web_search
349
+ ```
350
+
351
+ Each step prints `● tool name + argument summary` and `↳ result preview` in the terminal; the agent decides the next step on its own within the loop, with responses streaming in as they're generated.
352
+
353
+ ## Skills
354
+
355
+ MoCode automatically scans the following directories for skills (each skill is a `<name>/SKILL.md` with frontmatter):
356
+
357
+ - `~/.claude/skills/`
358
+ - `~/.mocode/skills/`
359
+ - `<cwd>/.mocode/skills/`
360
+
361
+ A skill's `description` is injected into the system prompt (progressive disclosure, tier 1); the model calls `use_skill` to load the full body (tier 2) only when the task is relevant. Use `/skills` to see discovered skills.
362
+
363
+ ## Working discipline
364
+
365
+ The system prompt provides lightweight guidance rather than a framework gate: inspect only what matters, make focused changes, avoid repeated stale reads, and report uncertainty honestly. The agent decides whether validation is useful for the task and chooses the scope itself. Broad test/build suites are not run by default, and lack of validation never blocks completion or triggers an extra model turn.
366
+
367
+ ## Project memory (AGENTS.md)
368
+
369
+ MoCode has a **two-tier memory** model distinct from skills:
370
+
371
+ - **Tier-1 — `AGENTS.md` (auto-loaded every session):** Markdown project memory that gets concatenated into the system prompt on every turn. Discovery walks `~/.mocode/AGENTS.md` → every `AGENTS.md` from the cwd up to the filesystem root (far→near, near wins). On overflow the body is truncated with a marker pointing back at the files. Generate or refresh one with `/init`, or write it by hand — it's plain Markdown, no schema. `AGENTS.md` is also where the agent itself persists "next-session facts" it deduces (architecture, conventions, pitfalls).
372
+ - **Tier-2 — `memory_*` tool library (agent-driven, routed on demand):** Discrete tagged records (`decision` / `fact` / `pitfall` / `reference` / `feedback`) with recall-count-based decay (30-day → archived; 90-day → GC). The LLM router selects `memory-read` for retrieval and `memory-write` only for explicit persistence intent. Set `MEMORY_ENABLED=false` to veto both groups; `true` additionally injects the compact Memory Index. The agent searches before saving and updates existing entries rather than duplicating them.
373
+
374
+ ## Type checking
375
+
376
+ ```bash
377
+ npm run typecheck # tsc --noEmit
378
+ ```
379
+
380
+ ## Future extensions
381
+
382
+ MCP tool integration, finer-grained capability locks, and a real worktree-isolated sub-agent mode. The current version is a streaming, reasoning-visible, rollback-capable terminal coding agent with 25 tools, working-notepad planning, cross-session memory, capability-aware tool scheduling, serial workspace-sharing sub-agents, and an optional desktop pet.