mocode-ai 0.4.5 → 0.4.7

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.
package/README.md CHANGED
@@ -1,219 +1,219 @@
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
- A terminal coding agent: give it a goal, and it **completes it autonomously** — no step-by-step hand-holding required.
8
-
9
- 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.
10
-
11
- ## Why MoCode
12
-
13
- MoCode isn't a chat box with a coat of paint — it's an agent that actually gets things done:
14
-
15
- - **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).
16
- - **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.
17
- - **Sub-agents divide and conquer** — Complex tasks can spawn independent sub-agents, each with its own conversation history (isolated from the main thread), an optional restricted toolset, and a step cap. They can explore multiple code areas or directions in parallel and report back only a summary, which the main thread uses to decide what's next.
18
- - **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 unlocks the full toolset. The agent can switch between the two on its own — scope out an unfamiliar codebase first, then start making changes.
19
- - **Automatic context compression** — As the context window fills up, a three-tier compression kicks in (trim individual results → compact older tool results in place → summarize older turns), so long sessions never overflow. `/context` shows live token usage; `/compact` triggers manual compression (optionally with a focus hint to preserve what matters).
20
- - **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.
21
- - **Working notepad (todolist)** — For complex multi-step tasks (≥3 file changes / ≥5 tool calls), the agent first writes a plan to `.mocode/plans/<id>.md` (file-based, survives context compression), then ticks each step as it goes. A live progress chip in the TUI status bar shows `plan: [title] (3/7) ▸ [current step]`. `finish` auto-archives completed plans to `plans/archive/`, with explicit `list / delete / unarchive` actions.
22
- - **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.
23
- - **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.
24
-
25
- ## Features
26
-
27
- - **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.
28
- - **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.
29
- - **Session persistence** — Every turn is saved automatically; `--resume` / `/resume` picks up a past session.
30
- - **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).
31
- - **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.
32
- - **Slash commands** — `/exit` `/clear` `/context` `/skills` `/compact` `/resume` `/rollback` `/memory` `/reflect` `/init` `/theme` `/model` `/plan` `/auto` `/pet`, with dropdown filtering as you type.
33
-
34
- ## Installation
35
-
36
- Requires Node.js ≥ 18.
37
-
38
- ```bash
39
- npm install -g mocode-ai
40
- ```
41
-
42
- This gives you the `mocode` command. Prefer not to install globally? Run it directly with `npx mocode-ai`.
43
-
44
- > MoCode checks for new versions on startup and self-updates in the background via `npm i -g mocode-ai@latest` — the update takes effect on the next launch, with zero startup delay and silent failure if offline. This is skipped in dev mode (`npm start`, running via tsx).
45
-
46
- ### Run from source (development / contributing)
47
-
48
- ```bash
49
- git clone https://github.com/wanxunyang/mocode.git
50
- cd mocode
51
- npm install
52
- npm start
53
- ```
54
-
55
- 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`.
56
-
57
- ## Configuration
58
-
59
- 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):
60
-
61
- ```bash
62
- mocode config
63
- ```
64
-
65
- 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`.
66
-
67
- 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):
68
-
69
- 1. `<cwd>/.env` — legacy compatibility, lowest priority (see `.env.example` in the source repo for reference)
70
- 2. `~/.mocode/config` — global (written by `/model` and `mocode config`)
71
- 3. `<cwd>/.mocode/config` — project-level override, highest priority
72
-
73
- Three required fields:
74
-
75
- ```env
76
- LLM_BASE_URL=https://open.bigmodel.cn/api/v3 # swap in your backend
77
- LLM_API_KEY=your-key-here
78
- LLM_MODEL=glm-4.6 # swap in your model name
79
- ```
80
-
81
- Common backend `base_url` values:
82
-
83
- | Backend | base\_url |
84
- | -------------- | ---------------------------------------------------- |
85
- | GLM (Zhipu) | `https://open.bigmodel.cn/api/v3` |
86
- | DeepSeek | `https://api.deepseek.com` |
87
- | Qwen (Alibaba) | `https://dashscope.aliyuncs.com/compatible-mode/v1` |
88
- | Local Ollama | `http://localhost:11434/v1` |
89
- | Local vLLM | `http://localhost:8000/v1` |
90
-
91
- > The model must support OpenAI-style function calling, otherwise tools won't be triggered.
92
-
93
- ### Optional configuration
94
-
95
- | Environment variable | Description | Default |
96
- | --------------------------- | ---------------------------------------------------------------------- | --------------------------- |
97
- | `MAX_TOKENS` | Max tokens per response | unlimited |
98
- | `CONTEXT_WINDOW_TOKENS` | Model context window; must match the real model | `128000` |
99
- | `COMPACT_THRESHOLD` | Auto-compaction trigger threshold (fraction of window) | `0.85` |
100
- | `LLM_STREAM_USAGE` | Include `stream_options.include_usage` on streaming requests for real usage | `true` |
101
- | `AUTO_COMPACT` | Auto-compaction master switch | `true` |
102
- | `AUTO_REFLECT` | Background reflection pass master switch (periodically mines memories from conversations) | `true` |
103
- | `REFLECT_EVERY_N` | Trigger a background reflection every N turns (runs alongside the agent, non-blocking) | `5` |
104
- | `ANYSEARCH_API_KEY` | Web search API key (falls back to anonymous free quota if unset) | none |
105
- | `ANYSEARCH_BASE_URL` | Search API endpoint | `https://api.anysearch.com` |
106
- | `SKILLS_DIRS` | Override the default skill scan directories (platform path separator) | three default directories |
107
- | `MOCODE_CONTEXT_OPTIMIZE` | Typed encoding of tool results before they reach the LLM (tree/search/log…); disable for raw passthrough (length trimming only) | `true` |
108
- | `MAX_STEPS` | Max agent loop steps per turn (prevents infinite loops) | `200` |
109
- | `SUB_AGENT_MAX_STEPS` | Default step cap for sub-agents (spawned via the `task` tool) | `50` |
110
- | `SANDBOX_ROOT` | Sandbox root directory (file operation boundary; falls back to cwd if unset) | none |
111
- | `MOCODE_THEME` | Color theme (default/dark/light…; shell env takes precedence over file) | `default` |
112
-
113
- ## Usage
114
-
115
- ```bash
116
- mocode # new session (run inside your target project directory)
117
- mocode --resume # list saved sessions
118
- mocode --resume <id> # resume a specific session
119
- mocode config # edit configuration
120
- ```
121
-
122
- Running from source uses `npm start` (equivalent to `mocode`, but skips the self-update check).
123
-
124
- 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.
125
-
126
- 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`.
127
-
128
- ## Tools
129
-
130
- | Tool | Purpose |
131
- | ---------------- | ------------------------------------------------------------------------- |
132
- | `read_file` | Read a file with line numbers; supports `offset` / `limit` |
133
- | `write_file` | Create/overwrite a file, auto-creating parent directories |
134
- | `edit_file` | Precise string replacement (`old_string` must match uniquely) |
135
- | `run_command` | Run a shell command, merging stdout+stderr, 120s default timeout |
136
- | `glob` | Find files by glob pattern (excludes node\_modules/.git) |
137
- | `grep` | Regex content search, pure JS implementation, no `rg` dependency |
138
- | `codegraph` | With a `.codegraph/` index built, query symbol source and call chains (more accurate and cheaper than read\_file/grep) |
139
- | `web_search` | Web search (AnySearch), returns title/URL/snippet/body |
140
- | `web_fetch` | Fetch a URL, cleaning HTML into plain text |
141
- | `use_skill` | Load the full SKILL.md instructions for a given skill |
142
- | `ask_human` | Pop up a Q&A panel at decision points; user picks a preset or types freely (blocks until answered) |
143
- | `switch_mode` | Switch between `plan` (read-only planning) and `auto` (full execution); the agent can call this itself to explore before acting |
144
- | `drop_context` | Replace irrelevant old tool results in history with stubs to free up context (preserves tool_call_id pairing, leaves system prompt and current turn untouched, idempotent) |
145
- | `task` | Spawn a sub-agent for an independent subtask (isolated history, optional restricted toolset, optional step cap); consecutive calls run in parallel automatically, returning only a summary |
146
- | `todolist` | Working notepad: write a multi-step plan to `.mocode/plans/<id>.md` (survives compression) and tick steps as you go; `finish` auto-archives, with `list / delete / unarchive` for history |
147
- | `memory_save` | Save a piece of cross-session long-term memory (title indexed, body fetched on demand) |
148
- | `memory_search` | Search memory bodies by keyword; hits boost the recall count (affects forgetting decay) |
149
- | `memory_list` | List the memory index (id/title/summary, no body) |
150
- | `memory_update` | Edit a memory in place (id unchanged; correct stale facts / update summary / toggle pin) |
151
- | `memory_forget` | Forget a memory: archived by default (recoverable), `mode=delete` for a hard delete (pinned memories can't be deleted) |
152
-
153
- The five `memory_*` tools are gated on `MEMORY_ENABLED=true` at startup; toggle at runtime with `/memory_switch` (REPL restart required, by design — see Skills section for the difference between Tier-1 `MOCODE.md` and Tier-2 memory).
154
-
155
- ## Slash commands
156
-
157
- | Command | Purpose |
158
- | ------------------ | ----------------------------------------------------------------------- |
159
- | `/exit` `/quit` | Exit MoCode |
160
- | `/clear` | Clear history (keeps the system prompt) + clear screen |
161
- | `/context` | Show a context usage bar (tokens / message count, estimated or measured) |
162
- | `/skills` | List discovered skills |
163
- | `/compact` | Compress history (optionally with a focus hint: `/compact …`) |
164
- | `/resume` | Resume a saved session |
165
- | `/rollback` | Menu to pick a turn to roll back to (↑↓ · Enter) |
166
- | `/memory` | Show memory library: entry count + recent index |
167
- | `/memory_switch` | Toggle Tier-2 memory on/off (REPL restart required — by design) |
168
- | `/reflect` | Manually trigger a background memory reflection pass |
169
- | `/model` | Configure the LLM (baseURL / apiKey / model / context window), applied immediately + persisted |
170
- | `/init` | Scan the project and generate `MOCODE.md` project memory (dispatched to the agent) |
171
- | `/theme` | Switch color theme (↑↓ · Enter, or `/theme <name>` directly) |
172
- | `/plan` | Switch to plan mode (read-only exploration + plan output, approve to switch to auto) |
173
- | `/auto` | Switch back to auto mode (full toolset execution) |
174
- | `/pet` | Toggle the optional desktop pet (floating window mirroring agent state) |
175
- | `/pet skin` | Pick a pet skin (↑↓ · Enter) |
176
- | `/pet quit` | Fully shut down the pet process (not just disconnect) |
177
-
178
- Type `/` to trigger the dropdown menu, keep typing to filter; Esc to cancel.
179
-
180
- ## Quick verification (after configuring your key)
181
-
182
- ```
183
- > hello, who are you # verify LLM connectivity
184
- > read sample.txt # triggers read_file
185
- > change foo to bar in sample.txt # triggers read_file + edit_file
186
- > list all .txt files in this directory # triggers glob
187
- > search the code for runAgent # triggers grep
188
- > run node -e "console.log(1+1)" # triggers run_command
189
- > search what's new in TypeScript 5.5 # triggers web_search
190
- ```
191
-
192
- 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.
193
-
194
- ## Skills
195
-
196
- MoCode automatically scans the following directories for skills (each skill is a `<name>/SKILL.md` with frontmatter):
197
-
198
- - `~/.claude/skills/`
199
- - `~/.mocode/skills/`
200
- - `<cwd>/.mocode/skills/`
201
-
202
- 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.
203
-
204
- ## Project memory (MOCODE.md)
205
-
206
- MoCode has a **two-tier memory** model distinct from skills:
207
-
208
- - **Tier-1 — `MOCODE.md` (auto-loaded every session):** Markdown project memory that gets concatenated into the system prompt on every turn. Discovery walks `~/.mocode/MOCODE.md` → every `MOCODE.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. `MOCODE.md` is also where the agent itself persists "next-session facts" it deduces (architecture, conventions, pitfalls).
209
- - **Tier-2 — `memory_*` tool library (agent-driven, opt-in):** Discrete tagged records (`decision` / `fact` / `pitfall` / `reference` / `feedback`) with recall-count-based decay (30-day → archived; 90-day → GC). The agent saves / searches / updates / forgets via tools; titles go in the system-prompt index (≤50), bodies fetched on demand via `memory_search`. Off by default; toggle with `MEMORY_ENABLED=true` at startup or `/memory_switch` (REPL restart required).
210
-
211
- ## Type checking
212
-
213
- ```bash
214
- npm run typecheck # tsc --noEmit
215
- ```
216
-
217
- ## Future extensions
218
-
219
- MCP tool integration, a permission confirmation UI, 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, parallel 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
+ A terminal coding agent: give it a goal, and it **completes it autonomously** — no step-by-step hand-holding required.
8
+
9
+ 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.
10
+
11
+ ## Why MoCode
12
+
13
+ MoCode isn't a chat box with a coat of paint — it's an agent that actually gets things done:
14
+
15
+ - **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).
16
+ - **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.
17
+ - **Sub-agents divide and conquer** — Complex tasks can spawn independent sub-agents, each with its own conversation history (isolated from the main thread), an optional restricted toolset, and a step cap. They can explore multiple code areas or directions in parallel and report back only a summary, which the main thread uses to decide what's next.
18
+ - **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 unlocks the full toolset. The agent can switch between the two on its own — scope out an unfamiliar codebase first, then start making changes.
19
+ - **Automatic context compression** — As the context window fills up, a three-tier compression kicks in (trim individual results → compact older tool results in place → summarize older turns), so long sessions never overflow. `/context` shows live token usage; `/compact` triggers manual compression (optionally with a focus hint to preserve what matters).
20
+ - **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.
21
+ - **Working notepad (todolist)** — For complex multi-step tasks (≥3 file changes / ≥5 tool calls), the agent first writes a plan to `.mocode/plans/<id>.md` (file-based, survives context compression), then ticks each step as it goes. A live progress chip in the TUI status bar shows `plan: [title] (3/7) ▸ [current step]`. `finish` auto-archives completed plans to `plans/archive/`, with explicit `list / delete / unarchive` actions.
22
+ - **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.
23
+ - **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.
24
+
25
+ ## Features
26
+
27
+ - **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.
28
+ - **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.
29
+ - **Session persistence** — Every turn is saved automatically; `--resume` / `/resume` picks up a past session.
30
+ - **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).
31
+ - **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.
32
+ - **Slash commands** — `/exit` `/clear` `/context` `/skills` `/compact` `/resume` `/rollback` `/memory` `/reflect` `/init` `/theme` `/model` `/plan` `/auto` `/pet`, with dropdown filtering as you type.
33
+
34
+ ## Installation
35
+
36
+ Requires Node.js ≥ 18.
37
+
38
+ ```bash
39
+ npm install -g mocode-ai
40
+ ```
41
+
42
+ This gives you the `mocode` command. Prefer not to install globally? Run it directly with `npx mocode-ai`.
43
+
44
+ > MoCode checks for new versions on startup and self-updates in the background via `npm i -g mocode-ai@latest` — the update takes effect on the next launch, with zero startup delay and silent failure if offline. This is skipped in dev mode (`npm start`, running via tsx).
45
+
46
+ ### Run from source (development / contributing)
47
+
48
+ ```bash
49
+ git clone https://github.com/wanxunyang/mocode.git
50
+ cd mocode
51
+ npm install
52
+ npm start
53
+ ```
54
+
55
+ 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`.
56
+
57
+ ## Configuration
58
+
59
+ 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):
60
+
61
+ ```bash
62
+ mocode config
63
+ ```
64
+
65
+ 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`.
66
+
67
+ 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):
68
+
69
+ 1. `<cwd>/.env` — legacy compatibility, lowest priority (see `.env.example` in the source repo for reference)
70
+ 2. `~/.mocode/config` — global (written by `/model` and `mocode config`)
71
+ 3. `<cwd>/.mocode/config` — project-level override, highest priority
72
+
73
+ Three required fields:
74
+
75
+ ```env
76
+ LLM_BASE_URL=https://open.bigmodel.cn/api/v3 # swap in your backend
77
+ LLM_API_KEY=your-key-here
78
+ LLM_MODEL=glm-4.6 # swap in your model name
79
+ ```
80
+
81
+ Common backend `base_url` values:
82
+
83
+ | Backend | base\_url |
84
+ | -------------- | ---------------------------------------------------- |
85
+ | GLM (Zhipu) | `https://open.bigmodel.cn/api/v3` |
86
+ | DeepSeek | `https://api.deepseek.com` |
87
+ | Qwen (Alibaba) | `https://dashscope.aliyuncs.com/compatible-mode/v1` |
88
+ | Local Ollama | `http://localhost:11434/v1` |
89
+ | Local vLLM | `http://localhost:8000/v1` |
90
+
91
+ > The model must support OpenAI-style function calling, otherwise tools won't be triggered.
92
+
93
+ ### Optional configuration
94
+
95
+ | Environment variable | Description | Default |
96
+ | --------------------------- | ---------------------------------------------------------------------- | --------------------------- |
97
+ | `MAX_TOKENS` | Max tokens per response | unlimited |
98
+ | `CONTEXT_WINDOW_TOKENS` | Model context window; must match the real model | `128000` |
99
+ | `COMPACT_THRESHOLD` | Auto-compaction trigger threshold (fraction of window) | `0.85` |
100
+ | `LLM_STREAM_USAGE` | Include `stream_options.include_usage` on streaming requests for real usage | `true` |
101
+ | `AUTO_COMPACT` | Auto-compaction master switch | `true` |
102
+ | `AUTO_REFLECT` | Background reflection pass master switch (periodically mines memories from conversations) | `true` |
103
+ | `REFLECT_EVERY_N` | Trigger a background reflection every N turns (runs alongside the agent, non-blocking) | `5` |
104
+ | `ANYSEARCH_API_KEY` | Web search API key (falls back to anonymous free quota if unset) | none |
105
+ | `ANYSEARCH_BASE_URL` | Search API endpoint | `https://api.anysearch.com` |
106
+ | `SKILLS_DIRS` | Override the default skill scan directories (platform path separator) | three default directories |
107
+ | `MOCODE_CONTEXT_OPTIMIZE` | Typed encoding of tool results before they reach the LLM (tree/search/log…); disable for raw passthrough (length trimming only) | `true` |
108
+ | `MAX_STEPS` | Max agent loop steps per turn (prevents infinite loops) | `200` |
109
+ | `SUB_AGENT_MAX_STEPS` | Default step cap for sub-agents (spawned via the `task` tool) | `50` |
110
+ | `SANDBOX_ROOT` | Sandbox root directory (file operation boundary; falls back to cwd if unset) | none |
111
+ | `MOCODE_THEME` | Color theme (default/dark/light…; shell env takes precedence over file) | `default` |
112
+
113
+ ## Usage
114
+
115
+ ```bash
116
+ mocode # new session (run inside your target project directory)
117
+ mocode --resume # list saved sessions
118
+ mocode --resume <id> # resume a specific session
119
+ mocode config # edit configuration
120
+ ```
121
+
122
+ Running from source uses `npm start` (equivalent to `mocode`, but skips the self-update check).
123
+
124
+ 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.
125
+
126
+ 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`.
127
+
128
+ ## Tools
129
+
130
+ | Tool | Purpose |
131
+ | ---------------- | ------------------------------------------------------------------------- |
132
+ | `read_file` | Read a file with line numbers; supports `offset` / `limit` |
133
+ | `write_file` | Create/overwrite a file, auto-creating parent directories |
134
+ | `edit_file` | Precise string replacement (`old_string` must match uniquely) |
135
+ | `run_command` | Run a shell command, merging stdout+stderr, 120s default timeout |
136
+ | `glob` | Find files by glob pattern (excludes node\_modules/.git) |
137
+ | `grep` | Regex content search, pure JS implementation, no `rg` dependency |
138
+ | `codegraph` | With a `.codegraph/` index built, query symbol source and call chains (more accurate and cheaper than read\_file/grep) |
139
+ | `web_search` | Web search (AnySearch), returns title/URL/snippet/body |
140
+ | `web_fetch` | Fetch a URL, cleaning HTML into plain text |
141
+ | `use_skill` | Load the full SKILL.md instructions for a given skill |
142
+ | `ask_human` | Pop up a Q&A panel at decision points; user picks a preset or types freely (blocks until answered) |
143
+ | `switch_mode` | Switch between `plan` (read-only planning) and `auto` (full execution); the agent can call this itself to explore before acting |
144
+ | `drop_context` | Replace irrelevant old tool results in history with stubs to free up context (preserves tool_call_id pairing, leaves system prompt and current turn untouched, idempotent) |
145
+ | `task` | Spawn a sub-agent for an independent subtask (isolated history, optional restricted toolset, optional step cap); consecutive calls run in parallel automatically, returning only a summary |
146
+ | `todolist` | Working notepad: write a multi-step plan to `.mocode/plans/<id>.md` (survives compression) and tick steps as you go; `finish` auto-archives, with `list / delete / unarchive` for history |
147
+ | `memory_save` | Save a piece of cross-session long-term memory (title indexed, body fetched on demand) |
148
+ | `memory_search` | Search memory bodies by keyword; hits boost the recall count (affects forgetting decay) |
149
+ | `memory_list` | List the memory index (id/title/summary, no body) |
150
+ | `memory_update` | Edit a memory in place (id unchanged; correct stale facts / update summary / toggle pin) |
151
+ | `memory_forget` | Forget a memory: archived by default (recoverable), `mode=delete` for a hard delete (pinned memories can't be deleted) |
152
+
153
+ The five `memory_*` tools are gated on `MEMORY_ENABLED=true` at startup; toggle at runtime with `/memory_switch` (REPL restart required, by design — see Skills section for the difference between Tier-1 `MOCODE.md` and Tier-2 memory).
154
+
155
+ ## Slash commands
156
+
157
+ | Command | Purpose |
158
+ | ------------------ | ----------------------------------------------------------------------- |
159
+ | `/exit` `/quit` | Exit MoCode |
160
+ | `/clear` | Clear history (keeps the system prompt) + clear screen |
161
+ | `/context` | Show a context usage bar (tokens / message count, estimated or measured) |
162
+ | `/skills` | List discovered skills |
163
+ | `/compact` | Compress history (optionally with a focus hint: `/compact …`) |
164
+ | `/resume` | Resume a saved session |
165
+ | `/rollback` | Menu to pick a turn to roll back to (↑↓ · Enter) |
166
+ | `/memory` | Show memory library: entry count + recent index |
167
+ | `/memory_switch` | Toggle Tier-2 memory on/off (REPL restart required — by design) |
168
+ | `/reflect` | Manually trigger a background memory reflection pass |
169
+ | `/model` | Configure the LLM (baseURL / apiKey / model / context window), applied immediately + persisted |
170
+ | `/init` | Scan the project and generate `MOCODE.md` project memory (dispatched to the agent) |
171
+ | `/theme` | Switch color theme (↑↓ · Enter, or `/theme <name>` directly) |
172
+ | `/plan` | Switch to plan mode (read-only exploration + plan output, approve to switch to auto) |
173
+ | `/auto` | Switch back to auto mode (full toolset execution) |
174
+ | `/pet` | Toggle the optional desktop pet (floating window mirroring agent state) |
175
+ | `/pet skin` | Pick a pet skin (↑↓ · Enter) |
176
+ | `/pet quit` | Fully shut down the pet process (not just disconnect) |
177
+
178
+ Type `/` to trigger the dropdown menu, keep typing to filter; Esc to cancel.
179
+
180
+ ## Quick verification (after configuring your key)
181
+
182
+ ```
183
+ > hello, who are you # verify LLM connectivity
184
+ > read sample.txt # triggers read_file
185
+ > change foo to bar in sample.txt # triggers read_file + edit_file
186
+ > list all .txt files in this directory # triggers glob
187
+ > search the code for runAgent # triggers grep
188
+ > run node -e "console.log(1+1)" # triggers run_command
189
+ > search what's new in TypeScript 5.5 # triggers web_search
190
+ ```
191
+
192
+ 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.
193
+
194
+ ## Skills
195
+
196
+ MoCode automatically scans the following directories for skills (each skill is a `<name>/SKILL.md` with frontmatter):
197
+
198
+ - `~/.claude/skills/`
199
+ - `~/.mocode/skills/`
200
+ - `<cwd>/.mocode/skills/`
201
+
202
+ 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.
203
+
204
+ ## Project memory (MOCODE.md)
205
+
206
+ MoCode has a **two-tier memory** model distinct from skills:
207
+
208
+ - **Tier-1 — `MOCODE.md` (auto-loaded every session):** Markdown project memory that gets concatenated into the system prompt on every turn. Discovery walks `~/.mocode/MOCODE.md` → every `MOCODE.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. `MOCODE.md` is also where the agent itself persists "next-session facts" it deduces (architecture, conventions, pitfalls).
209
+ - **Tier-2 — `memory_*` tool library (agent-driven, opt-in):** Discrete tagged records (`decision` / `fact` / `pitfall` / `reference` / `feedback`) with recall-count-based decay (30-day → archived; 90-day → GC). The agent saves / searches / updates / forgets via tools; titles go in the system-prompt index (≤50), bodies fetched on demand via `memory_search`. Off by default; toggle with `MEMORY_ENABLED=true` at startup or `/memory_switch` (REPL restart required).
210
+
211
+ ## Type checking
212
+
213
+ ```bash
214
+ npm run typecheck # tsc --noEmit
215
+ ```
216
+
217
+ ## Future extensions
218
+
219
+ MCP tool integration, a permission confirmation UI, 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, parallel sub-agents, and an optional desktop pet.
@@ -145,8 +145,9 @@ ${PLATFORM_NOTE}
145
145
 
146
146
  ## Step / Turn Economy (read this first — saves LLM calls)
147
147
  - **Minimize turns**: each user message costs at least one LLM call, and history grows every step until threshold-triggered compact fires (extra call). If a request contains ≥2 independent sub-goals (e.g. "改 X 然后再优化 Y"), ask the user to split them into separate turns rather than chaining both in one go. State this politely: "这条包含 N 个独立目标,建议拆成 N 次对话,以避免上下文膨胀。"
148
- - **Context check before any call — do this before the batching rule below**: before planning tool calls for this turn, first check whether the current conversation, an earlier tool result, or a file/symbol already read in this session already answers it. If it does, skip the call and answer directly. Only call a tool when the info is genuinely missing, may be stale (the underlying file/state changed since you last read it), or was never retrieved. This applies to every tool — codegraph, grep, web_search, run_command — not just read_file.
148
+ - **Answer directly when you already know the answer — do this before the batching rule below**: before planning any tool calls for this turn, first check whether you can answer from the current conversation, an earlier tool result already in context, a file/symbol already read in this session, or general reasoning/knowledge alone. If so, skip tools entirely and answer directly. Only call a tool when the info is genuinely missing, may be stale (the underlying file/state changed since you last read it), or requires verification you cannot do from context. This applies to every tool — codegraph, grep, web_search, run_command — not just read_file.
149
149
  - ✅ already have it: user asks "刚才那个函数在哪个文件" after codegraph_explore returned it two turns ago → answer from that result, no new call.
150
+ - ✅ pure reasoning: user asks "这个改动会不会影响性能" and the relevant code/logic is already visible in context → reason and answer directly, no need to re-run a profiler or re-read the file "just to be safe".
150
151
  - ❌ wasteful: re-running grep/codegraph for a symbol whose location this same conversation already returned, "just to be sure".
151
152
  - **Plan the full turn, then emit it as one batch — this is the single biggest step-saver**: before emitting anything, enumerate every read / edit / command you'll need for this sub-goal, then return them together as one set of tool_calls (reads run in parallel, writes/commands run in the order given). Don't emit one call, observe, then emit the next in a follow-up turn when you could have planned both upfront.
152
153
  - ✅ one turn: \`[read_file A, read_file B, edit_file A, run_command 'npm test']\`