mocode-ai 1.6.5 → 1.6.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 +46 -31
- package/README.zh-CN.md +57 -30
- package/dist/agent/run-coordinator.js +2 -1
- package/dist/agent/tool-turn.js +2 -0
- package/dist/bots/bus.js +117 -0
- package/dist/bots/cli.js +102 -0
- package/dist/bots/store.js +100 -0
- package/dist/config/index.js +2 -1
- package/dist/headless.js +302 -0
- package/dist/index.js +171 -3
- package/dist/jobs/approval.js +153 -0
- package/dist/jobs/approve-cli.js +30 -0
- package/dist/jobs/attach.js +61 -0
- package/dist/jobs/checkpoint.js +33 -0
- package/dist/jobs/launch.js +107 -0
- package/dist/jobs/runner.js +59 -0
- package/dist/jobs/store.js +101 -0
- package/dist/jobs/worktree.js +63 -0
- package/dist/notify/index.js +144 -0
- package/dist/repl/commands/bots.js +32 -0
- package/dist/repl/commands/jobs.js +109 -0
- package/dist/repl/commands/model.js +5 -20
- package/dist/repl/commands/registry.js +6 -0
- package/dist/repl/commands/schedule.js +37 -0
- package/dist/repl/commands.js +3 -58
- package/dist/schedule/cli.js +114 -0
- package/dist/schedule/cron.js +79 -0
- package/dist/schedule/daemon.js +166 -0
- package/dist/schedule/store.js +98 -0
- package/dist/session/scheduler.js +0 -3
- package/dist/session/store.js +1 -1
- package/dist/tools/builtins/arena.js +156 -0
- package/dist/tools/builtins/glob.js +64 -16
- package/dist/tools/builtins/grep.js +176 -122
- package/dist/tools/builtins/index.js +13 -2
- package/dist/tools/builtins/message-bus.js +98 -0
- package/dist/tools/builtins/run-command.js +2 -1
- package/dist/tools/constants.js +11 -0
- package/dist/tools/ripgrep-client.js +180 -0
- package/dist/ui/batch.js +31 -1
- package/dist/ui/composer.js +4 -18
- package/dist/ui/fuzzy-picker.js +1 -3
- package/dist/ui/intervention.js +6 -0
- package/dist/ui/prompt-internal/editor.js +10 -27
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -39,7 +39,7 @@ See mocode complete real tasks autonomously:
|
|
|
39
39
|
MoCode keeps code-level control light and leaves task strategy to the agent:
|
|
40
40
|
|
|
41
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
|
-
- **
|
|
42
|
+
- **Bounded tool retries, explicit failures** — The runtime automatically retries only transient errors from tools explicitly marked `idempotent`, at most twice. `TIMEOUT`, permission denial, cancellation, and non-idempotent calls are not automatically retried. The resulting structured outcome is returned to the agent for any further recovery decision; see [Automatic retry](#automatic-retry-the-retryable-contract).
|
|
43
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
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
45
|
|
|
@@ -47,29 +47,29 @@ MoCode keeps code-level control light and leaves task strategy to the agent:
|
|
|
47
47
|
|
|
48
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
49
|
|
|
50
|
-
|
|
50
|
+
Implementation entry points: [Agent core](src/agent/core.ts), [tool dispatch](src/agent/stages/tool-dispatcher.ts), and [tool execution](src/tools/tool-runtime.ts).
|
|
51
51
|
|
|
52
52
|
### Autonomous execution loop
|
|
53
53
|
|
|
54
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
55
|
|
|
56
|
-
<p align="center"><img src="./assets/architecture/agent-loop.svg" alt="MoCode autonomous agent execution loop" width="100%"></p>
|
|
57
|
-
|
|
58
56
|
### Context compression only under real pressure
|
|
59
57
|
|
|
60
58
|
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
59
|
|
|
62
|
-
|
|
60
|
+
The implementation is defined by [budget accounting](src/context/budget.ts) and [pressure scheduling](src/session/scheduler.ts).
|
|
61
|
+
|
|
62
|
+
### Multi-agent work in a shared workspace
|
|
63
63
|
|
|
64
|
-
|
|
64
|
+
Sub-agents keep independent history branches, can reuse the parent's conversation prefix, and cannot expand beyond the tool set delegated by the parent step. Consecutive sub-agent calls run in bounded parallel batches (`SUB_AGENT_CONCURRENCY`, default `5`; set `1` for sequential dispatch).
|
|
65
65
|
|
|
66
|
-
|
|
66
|
+
**History isolation is not filesystem isolation.** Sub-agents write directly to the shared workspace and inherit the parent's current rollback turn. There is no private filesystem overlay, per-worker worktree, or post-task ChangeSet merge. Nested tools acquire their own resource locks; supported file edits enforce their own expected-hash checks. These guards do not make an entire multi-step sub-task an isolated transaction. The parent receives the final summary, status, usage, and tracked changed files rather than the full worker transcript. Validation remains an explicit agent choice.
|
|
67
67
|
|
|
68
|
-
|
|
68
|
+
See [sub-agent execution](src/agent/spawn.ts), [the sub-agent tool](src/tools/builtins/task.ts), and [capability-based dispatch](src/agent/stages/tool-dispatcher.ts).
|
|
69
69
|
|
|
70
70
|
### Controlled execution: permission gates and capability scheduling
|
|
71
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).
|
|
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). In piped or CI environments, unapproved `confirm` / `dangerous` actions are denied by default; safe operations do not require an interactive prompt.
|
|
73
73
|
|
|
74
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
75
|
|
|
@@ -77,18 +77,16 @@ Every mutating tool calls into a permission layer before it runs. Tools are clas
|
|
|
77
77
|
|
|
78
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
79
|
|
|
80
|
-
### Rollback timeline:
|
|
80
|
+
### Rollback timeline: tracked file changes, restore by turn
|
|
81
81
|
|
|
82
|
-
|
|
82
|
+
Rollback records supported text-file mutations, including tracked changes made by sub-agents in the parent's turn. `/rollback` restores recorded file contents under canonical resource locks; it does not re-run the model or launch automatic tests. It is not a universal undo mechanism: network effects, desktop actions, binary changes, and other untracked effects are outside its scope. Cancelling a turn does not automatically undo completed file writes.
|
|
83
83
|
|
|
84
|
-
|
|
84
|
+
See the [rollback store](src/rollback/store.ts) for capture and restore boundaries.
|
|
85
85
|
|
|
86
86
|
### Context controls: one pressure gate, independently optional stages
|
|
87
87
|
|
|
88
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
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
90
|
### Desktop pet: a passive mirror over WebSocket
|
|
93
91
|
|
|
94
92
|
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.
|
|
@@ -100,16 +98,16 @@ The optional Electron sub-package (`packages/pet-app`) shows a stateful floating
|
|
|
100
98
|
MoCode isn't a chat box with a coat of paint — it's an agent that actually gets things done:
|
|
101
99
|
|
|
102
100
|
- **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
|
-
- **
|
|
104
|
-
- **Sub-agents divide and conquer** —
|
|
105
|
-
- **Plan / Auto dual mode** — In `plan` mode the agent
|
|
101
|
+
- **Capability-aware concurrency** — Consecutive tools declared safe to parallelize (such as file reads, grep, glob, and web reads) can run concurrently. Resource-locked file mutations can also be dispatched together: canonical locks coordinate conflicting resources rather than serializing every write globally. Process tools and tools without parallel capabilities retain their declared serial behavior.
|
|
102
|
+
- **Sub-agents divide and conquer** — Workers have independent history branches and inherit the parent step's tool ceiling. They run in bounded parallel batches, write directly to the shared workspace, and share the parent's rollback turn. A final summary and execution metadata return to the parent; there is no per-worker filesystem isolation or merge stage.
|
|
103
|
+
- **Plan / Auto dual mode** — In `plan` mode the agent explores and produces a plan without editing project files, running shell commands, or spawning sub-agents; internal session/plan records may still be persisted. `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
104
|
- **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.
|
|
105
|
+
- **Cross-session long-term memory** — The agent can save project architecture, conventions, and lessons learned as long-term memory, auto-loaded in future sessions. Optional background reflection mines conversations for useful memories when `AUTO_REFLECT=true` (off by default). Memories can be created, searched, updated, and forgotten, with recall-based decay.
|
|
108
106
|
- **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
107
|
- **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
|
|
108
|
+
- **Interruptible and reversible** — Ctrl+C propagates cancellation to model requests and supported running tools. History returns to the latest committed tool-batch checkpoint rather than unconditionally discarding the entire turn. Completed file writes remain until explicitly reverted; `/rollback` restores tracked file changes from turn snapshots with a per-file keep/undo choice, without requiring git.
|
|
111
109
|
- **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
|
-
- **
|
|
110
|
+
- **File-path boundaries** — Built-in file reads/writes reject paths outside `SANDBOX_ROOT` (the working directory by default), including traversal and symlink escapes. This is a file-tool path guard, not an OS-level sandbox for shell commands, MCP servers, or desktop input. Memory and skills may intentionally use configured locations outside the project. Review permissions before allowing high-risk tools; see [sandbox policy](src/sandbox/policy.ts).
|
|
113
111
|
- **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
112
|
|
|
115
113
|
## Features
|
|
@@ -117,9 +115,15 @@ MoCode isn't a chat box with a coat of paint — it's an agent that actually get
|
|
|
117
115
|
- **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
116
|
- **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
117
|
- **Session persistence** — Every turn is saved automatically; `--resume` / `/resume` picks up a past session.
|
|
118
|
+
- **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.
|
|
119
|
+
- **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.
|
|
120
|
+
- **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.
|
|
121
|
+
- **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.
|
|
122
|
+
- **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.
|
|
123
|
+
- **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`.
|
|
120
124
|
- **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).
|
|
121
125
|
- **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.
|
|
122
|
-
- **Slash commands** — `/exit` `/clear` `/cd` `/context` `/skills` `/compact` `/resume` `/rollback` `/memory` `/reflect` `/init` `/theme` `/model` `/effort` `/stats` `/plan` `/auto` `/pet`, with dropdown filtering as you type.
|
|
126
|
+
- **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.
|
|
123
127
|
|
|
124
128
|
## Documentation
|
|
125
129
|
|
|
@@ -136,7 +140,7 @@ npm install -g mocode-ai
|
|
|
136
140
|
|
|
137
141
|
This gives you the `mocode` command. Prefer not to install globally? Run it directly with `npx mocode-ai`.
|
|
138
142
|
|
|
139
|
-
> 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.
|
|
143
|
+
> 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; see the [upgrade implementation](src/commands/upgrade.ts).
|
|
140
144
|
|
|
141
145
|
### Run from source (development / contributing)
|
|
142
146
|
|
|
@@ -147,7 +151,7 @@ npm install
|
|
|
147
151
|
npm start
|
|
148
152
|
```
|
|
149
153
|
|
|
150
|
-
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).
|
|
154
|
+
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). Install from the repository root so npm resolves the workspaces. Dependency lists and development commands are maintained in [package.json](package.json), rather than duplicated here.
|
|
151
155
|
|
|
152
156
|
### Repository stacks and contributing
|
|
153
157
|
|
|
@@ -161,6 +165,10 @@ The production path is the TypeScript CLI. `packages/work-app` is incubating, `p
|
|
|
161
165
|
|
|
162
166
|
Do not import another package's `src/` or internal `dist/` layout. Applications consume package exports and the public `mocode-agent-host` bin contract.
|
|
163
167
|
|
|
168
|
+
### Keeping documentation aligned
|
|
169
|
+
|
|
170
|
+
When changing execution, permissions, concurrency, rollback, or upgrade behavior, update both `README.md` and `README.zh-CN.md` against the implementation links in these sections. Diagrams must describe the same current behavior before being embedded. Use the package manifests and built-in registry for dependency/tool inventories, and the stack-status page for release boundaries; do not treat a design proposal or an old diagram as a shipped guarantee.
|
|
171
|
+
|
|
164
172
|
## Configuration
|
|
165
173
|
|
|
166
174
|
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):
|
|
@@ -215,6 +223,8 @@ Common backend `base_url` values:
|
|
|
215
223
|
| `MOCODE_LIFECYCLE` | Provenance metadata tracking; never ages or rewrites content | `true` |
|
|
216
224
|
| `MAX_STEPS` | Max agent loop steps per turn (infinite-loop safety only) | `1000` |
|
|
217
225
|
| `SUB_AGENT_MAX_STEPS` | Sub-agent loop safety ceiling; defaults to the main-agent value | `1000` |
|
|
226
|
+
| `SUB_AGENT_CONCURRENCY` | Concurrent sub-agent calls per dispatch batch; `1` dispatches them sequentially | `5` |
|
|
227
|
+
| `SUB_AGENT_MAX_DEPTH` | Maximum recursive delegation depth | `3` |
|
|
218
228
|
| `SANDBOX_ROOT` | Sandbox root directory (file operation boundary; falls back to cwd if unset) | none |
|
|
219
229
|
| `MOCODE_SUBAGENT_ENABLED` | Set `false` to veto the `orchestration` route group; unset/`true` allows on-demand routing | unset |
|
|
220
230
|
| `MOCODE_FRONTEND_TOOLS_ENABLED` | Set `false` to veto `browser-debug` and `desktop-observe` (does not affect `background-exec`); unset/`true` allows routing | unset |
|
|
@@ -233,7 +243,7 @@ mocode --resume <id> # resume a specific session
|
|
|
233
243
|
mocode config # edit configuration
|
|
234
244
|
```
|
|
235
245
|
|
|
236
|
-
Running from source uses `npm start
|
|
246
|
+
Running from source uses `npm start`. Neither source nor installed runs automatically check for updates at startup; `/upgrade` is an explicit user action, and real installation is disabled in source/tsx mode.
|
|
237
247
|
|
|
238
248
|
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.
|
|
239
249
|
|
|
@@ -241,7 +251,9 @@ The agent operates in **the working directory it was launched from** — to have
|
|
|
241
251
|
|
|
242
252
|
## Tools
|
|
243
253
|
|
|
244
|
-
Every real user turn first goes through a constrained LLM router.
|
|
254
|
+
Every real user turn first goes through a constrained LLM router. Common tools include `read_file`, `glob`, `grep`, `web_search`, `web_fetch`, `plan_update`, `note_append`, `ask_human`, and `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 requests more groups with `add_tool_groups`; 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.
|
|
255
|
+
|
|
256
|
+
The tables below are selected capabilities, not an exhaustive tool inventory. Current registrations and capability declarations are maintained in the [built-in registry](src/tools/builtins/index.ts); exposure is controlled by [ToolPolicy](src/tools/policy.ts). Codegraph queries use an installed skill/CLI when available, not a standalone built-in `codegraph` tool.
|
|
245
257
|
|
|
246
258
|
| Tool | Purpose |
|
|
247
259
|
| ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
@@ -250,24 +262,26 @@ Every real user turn first goes through a constrained LLM router. Nine common to
|
|
|
250
262
|
| `edit_file` | Precise string replacement (`old_string` must match uniquely) |
|
|
251
263
|
| `run_command` | Run a foreground shell command, merging stdout+stderr, 120s default timeout; `shell=cmd\|powershell\|bash` picks the interpreter |
|
|
252
264
|
| `glob` | Find files by glob pattern (excludes node_modules/.git) |
|
|
253
|
-
| `grep` | Regex content search, pure
|
|
254
|
-
| `codegraph` | With a `.codegraph/` index built, query symbol source and call chains (more accurate and cheaper than read_file/grep) |
|
|
265
|
+
| `grep` | Regex content search powered by ripgrep (bundled via `@vscode/ripgrep`; respects `.gitignore`, skips binaries), falling back to a pure-JS scan only when no `rg` binary is available; `context=N` returns neighbouring lines inline so a hit rarely needs a follow-up read |
|
|
255
266
|
| `web_search` | Web search (AnySearch), returns title/URL/snippet/body |
|
|
256
267
|
| `web_fetch` | Fetch a URL, cleaning HTML into plain text; browser-like headers, auto-retry on transient failures, optional plaintext-proxy fallback |
|
|
257
268
|
| `use_skill` | Load the full SKILL.md instructions for a given skill |
|
|
258
269
|
| `ask_human` | Pop up a Q&A panel at decision points; user picks a preset or types freely (blocks until answered) |
|
|
259
270
|
| `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 |
|
|
260
|
-
| `sub-agent` | Spawn a
|
|
271
|
+
| `sub-agent` | Spawn a worker with an independent history and the parent step's tool ceiling; bounded concurrency, shared workspace and rollback turn |
|
|
261
272
|
|
|
273
|
+
| Memory tool | Purpose |
|
|
274
|
+
| ----------- | ------- |
|
|
262
275
|
| `memory_save` | Save a piece of cross-session long-term memory (title indexed, body fetched on demand) |
|
|
263
276
|
| `memory_search` | Search memory bodies by keyword; hits boost the recall count (affects forgetting decay) |
|
|
264
277
|
| `memory_list` | List the memory index (id/title/summary, no body) |
|
|
265
278
|
| `memory_update` | Edit a memory in place (id unchanged; correct stale facts / update summary / toggle pin) |
|
|
266
279
|
| `memory_forget` | Forget a memory: archived by default (recoverable), `mode=delete` for a hard delete (pinned memories can't be deleted) |
|
|
280
|
+
| `memory_graph` | Traverse neighbors, find paths, add triples, or inspect graph statistics; keyword search is provided by `memory_search` |
|
|
267
281
|
|
|
268
282
|
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.
|
|
269
283
|
|
|
270
|
-
Frontend capabilities are also split by purpose: `browser` forms `browser-debug`, whole-desktop `screenshot` is `desktop-observe`, and `dev_server` has its own
|
|
284
|
+
Frontend capabilities are also split by purpose: `browser` forms `browser-debug`, whole-desktop `screenshot` is `desktop-observe`, and `dev_server` has its own `background-exec` group (not controlled by `/fe`; execution still goes through permissions) — 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`.
|
|
271
285
|
|
|
272
286
|
### Shell selection
|
|
273
287
|
|
|
@@ -317,6 +331,7 @@ dev_server stop id=srv-xxxx
|
|
|
317
331
|
| `/model` | Two-level picker (provider → model; scoped search), plus baseURL / apiKey / context-window config; applied immediately + persisted |
|
|
318
332
|
| `/effort` | Set reasoning effort off/low/medium/high/auto (e.g. `/effort high`); not sent for unrecognized models |
|
|
319
333
|
| `/stats` | Session usage: cache hit rate / tiered tokens / compaction count |
|
|
334
|
+
| `/upgrade` | Explicit update check/status/install (`check` / `status` / `now`); no automatic startup update |
|
|
320
335
|
| `/init` | Scan the project and generate `AGENTS.md` project memory (dispatched to the agent) |
|
|
321
336
|
| `/theme` | Switch color theme (↑↓ · Enter, or `/theme <name>` directly) |
|
|
322
337
|
| `/plan` | Switch to plan mode (read-only exploration + plan output, approve to switch to auto) |
|
|
@@ -368,9 +383,9 @@ MoCode has a **two-tier memory** model distinct from skills:
|
|
|
368
383
|
## Type checking
|
|
369
384
|
|
|
370
385
|
```bash
|
|
371
|
-
npm run typecheck #
|
|
386
|
+
npm run typecheck # protocol/runtime + root + tests + evals
|
|
372
387
|
```
|
|
373
388
|
|
|
374
389
|
## Future extensions
|
|
375
390
|
|
|
376
|
-
MCP tool integration
|
|
391
|
+
MCP tool integration is already supported; see the [MCP configuration guide](src/mcp/README.md). Finer-grained capability coordination and optional per-worker worktree isolation are extension directions, not guarantees of the current shared-workspace sub-agent implementation. Current tool registrations are maintained in the [built-in registry](src/tools/builtins/index.ts), and production, optional, incubating, and experimental stacks are distinguished in [stack status](docs/architecture/stack-status.md).
|
package/README.zh-CN.md
CHANGED
|
@@ -38,25 +38,25 @@ mocode 自己探索代码、读写改文件、执行命令、联网查资料,以
|
|
|
38
38
|
|
|
39
39
|
MoCode 是一个分层的自治运行时:终端交互层驱动 Agent 内核,内核通过受控能力平面执行真实操作,持久化认知层则让长任务和跨会话工作保持连贯。
|
|
40
40
|
|
|
41
|
-
|
|
41
|
+
实现入口:[Agent 内核](src/agent/core.ts)、[工具派发](src/agent/stages/tool-dispatcher.ts)、[工具执行](src/tools/tool-runtime.ts)。
|
|
42
42
|
|
|
43
43
|
### 自治执行循环
|
|
44
44
|
|
|
45
45
|
每次模型响应都是闭环中的一步。工具调用按能力声明分类,安全读取可以并行,写操作获取规范化资源锁。工具证据除单条 hard cap 外原样进入 history,用户与模型看到同一事实。agent 没有更多工具调用时立即完成;框架不会暗中运行验证,也不会强迫追加一轮模型调用。
|
|
46
46
|
|
|
47
|
-
<p align="center"><img src="./assets/architecture/agent-loop-zh-CN.svg" alt="MoCode 自治 Agent 执行循环" width="100%"></p>
|
|
48
|
-
|
|
49
47
|
### 只在真实 Context Pressure 下压缩
|
|
50
48
|
|
|
51
49
|
正常会话保留完整工具证据,只维护 freshness / provenance 元数据。总上下文达到 80% 时,统一调度事件会执行已启用的 superseded、stale artifact、旧日志/搜索清理,然后始终继续 history compact;Lifecycle 不再按工具调用次数老化正文。
|
|
52
50
|
|
|
53
|
-
|
|
51
|
+
具体行为以[预算计算](src/context/budget.ts)和[压力调度](src/session/scheduler.ts)实现为准。
|
|
52
|
+
|
|
53
|
+
### 多 Agent 协作:共享工作区,有界并发
|
|
54
54
|
|
|
55
|
-
|
|
55
|
+
子 agent 维护独立历史分支,可以复用父级对话前缀,工具能力不能超出父 step 委派的范围。连续的子 agent 调用按并发上限分批执行(`SUB_AGENT_CONCURRENCY` 默认 `5`,设为 `1` 时逐个派发)。
|
|
56
56
|
|
|
57
|
-
|
|
57
|
+
**历史隔离不等于文件系统隔离。** 子 agent 直接写入共享工作区,并继承父级当前轮次的回滚记录;没有私有文件系统 overlay、每个 worker 独立的 worktree,也没有任务结束后的 ChangeSet 合并阶段。嵌套工具各自获取资源锁,支持的文件编辑各自执行 expected hash 校验;这些保护不意味着整个多步子任务具备事务隔离。主线接收最终摘要、状态、用量和已追踪的改动文件,而不是完整的子任务过程记录。是否验证及验证范围仍由 agent 自主决定。
|
|
58
58
|
|
|
59
|
-
|
|
59
|
+
对应实现:[子 agent 执行](src/agent/spawn.ts)、[sub-agent 工具](src/tools/builtins/task.ts)、[能力感知派发](src/agent/stages/tool-dispatcher.ts)。
|
|
60
60
|
|
|
61
61
|
### 受控执行:权限门 + 能力调度
|
|
62
62
|
|
|
@@ -68,18 +68,16 @@ MoCode 是一个分层的自治运行时:终端交互层驱动 Agent 内核,
|
|
|
68
68
|
|
|
69
69
|
mocode 不会在任务结束时暗中启动验证瀑布。agent 可以根据任务风险自行调用 `run_command` 跑聚焦测试、typecheck 或 build;也可以在无需额外证据时直接结束,不产生框架强制的额外轮次。
|
|
70
70
|
|
|
71
|
-
###
|
|
71
|
+
### 回滚时间线:追踪文件改动,按轮次恢复
|
|
72
72
|
|
|
73
|
-
|
|
73
|
+
回滚记录支持范围内的文本文件改动,包括子 agent 在父级轮次中产生的已追踪改动。`/rollback` 在规范化资源锁下恢复已记录的文件内容,不重跑模型,也不自动启动测试。它不是通用撤销机制:网络副作用、桌面操作、二进制改动及其他未追踪的副作用不在恢复范围内。中断当前轮次不会自动撤销已经完成的文件写入。
|
|
74
74
|
|
|
75
|
-
|
|
75
|
+
快照捕获与恢复边界见[回滚存储实现](src/rollback/store.ts)。
|
|
76
76
|
|
|
77
77
|
### 上下文控制:一个真实压力线,阶段独立可选
|
|
78
78
|
|
|
79
79
|
这些控制项仍可独立配置,但自动改写只有一个触发条件:校正后或原始请求占用达到 80%。该事件会运行所有已启用的 pressure 清理,然后始终继续压缩历史。`contextLifecycle` 只维护 provenance 元数据,EWMA 则让估算持续对齐 provider 实测用量。
|
|
80
80
|
|
|
81
|
-
<p align="center"><img src="./assets/architecture/context-controls-zh-CN.svg" alt="MoCode 上下文控制:五个独立开关、观察生命周期、token 自校准" width="100%"></p>
|
|
82
|
-
|
|
83
81
|
### 桌宠:WebSocket 上的被动镜像
|
|
84
82
|
|
|
85
83
|
可选 Electron 子包(`packages/pet-app`)用一个悬浮小角色镜像 agent 状态:单向 WebSocket 推送事件帧,`/pet quit` 完全关闭。渲染层零业务逻辑,无论桌宠是否在跑,主 agent 循环一字不改。
|
|
@@ -91,7 +89,7 @@ mocode 不会在任务结束时暗中启动验证瀑布。agent 可以根据任
|
|
|
91
89
|
mocode 把代码层控制保持得尽量轻,把任务策略交给 agent:
|
|
92
90
|
|
|
93
91
|
- **建议式工作纪律** — system prompt 只要求聚焦改动、避免重复检索、诚实报告不确定性;是否验证及验证范围由 agent 自主决定,不是完成硬门。
|
|
94
|
-
-
|
|
92
|
+
- **有界重试,明确报告失败** — runtime 仅对显式声明 `idempotent` 的工具瞬时错误自动重试,最多两次;`TIMEOUT`、权限拒绝、中断和非幂等调用不自动重试。最终结构化结果交给 agent,由其决定后续恢复方式,详见[自动重试](#自动重试retryable-契约)。
|
|
95
93
|
- **ask_human 卡点降级** — 仅高影响且属于用户所有权的选择才询问,其余实现细节由 agent 自主推进。
|
|
96
94
|
- **五区上下文控制 + token 自校准** — 独立旋钮管理上下文压力,token 估算根据真实 provider 用量校准。
|
|
97
95
|
|
|
@@ -100,15 +98,15 @@ mocode 把代码层控制保持得尽量轻,把任务策略交给 agent:
|
|
|
100
98
|
mocode 不是一个套壳聊天框,而是一个能真正动手干活的 agent:
|
|
101
99
|
|
|
102
100
|
- **自主多步推进** — 一次对话里连续多步:读代码、改代码、跑测试、根据报错再改……agent 自己决定下一步,中途不用你反复催。遇到卡点会调 `ask_human` 弹面板问你(阻塞到回应)。
|
|
103
|
-
-
|
|
104
|
-
- **子 agent 分而治之** —
|
|
105
|
-
- **计划 / 执行双模式** — `plan`
|
|
101
|
+
- **能力感知并发** — 连续且声明支持并行的工具(如读文件、grep、glob、联网读取)可并发执行。按资源加锁的文件改动也可同时派发,由规范化资源锁协调冲突资源,而不是把所有写入全局串行化。进程类及未声明并行能力的工具保持各自的串行执行约束。
|
|
102
|
+
- **子 agent 分而治之** — 子任务拥有独立历史分支,工具权限不超过父 step 的能力上限;按并发上限分批运行,直接写入共享工作区并共用父级回滚轮次。主线接收最终摘要及执行元数据;没有每个 worker 独立的文件系统隔离或合并阶段。
|
|
103
|
+
- **计划 / 执行双模式** — `plan` 模式下探查并产出计划,不修改项目文件、不跑 shell 命令、不派生子 agent;内部会话和计划记录仍可持久化。`auto` 模式允许执行,但不是静态“全工具”模式:每个真实用户轮先由轻量 LLM router 选择最小充分工具簇,主模型需要时可在后续 step 追加能力。
|
|
106
104
|
- **统一压力驱动压缩** — 正常 history 保留完整工具证据;达到 80% 后由一次调度事件运行所有已启用的清理,并始终继续 history 摘要。`/context` 显示实时用量,`/compact` 仍是用户显式覆盖。
|
|
107
|
-
- **跨会话长期记忆** — agent
|
|
105
|
+
- **跨会话长期记忆** — agent 能把项目架构、约定、踩过的坑存成长期记忆,下次会话自动加载;可通过 `AUTO_REFLECT=true` 开启后台反思,从对话中挖掘值得记住的事实(默认关闭)。记忆可增删改、带召回衰减。
|
|
108
106
|
- **会话记事本(notes.md)** — 复杂多步任务(≥3 处文件改动 / ≥5 步工具调用)时,agent 在 `.mocode/sessions/<sessionId>/notes.md` 维护一个工作记事本(落盘抗压缩),可记录中间发现、设计决策、待验证问题和结构化计划。执行计划由专用 `plan_update` 工具维护——三态步骤机(`pending`/`in_progress`/`completed`,同一时刻至多一个 `in_progress`),全部完成自动结算为 `## Done:`。活跃 plan 在压缩后重注入系统提示、notes.md 一变就重同步进上下文,若连续多步未更新还会有温和提醒。TUI 状态栏实时显示进度 chip:`plan: [标题] (3/7) ▸ [当前步]`。
|
|
109
|
-
- **可中断、可回滚** — Ctrl+C
|
|
107
|
+
- **可中断、可回滚** — Ctrl+C 将中断信号传给模型请求及支持取消的运行中工具;历史恢复到最近已提交工具批次的检查点,而不是无条件丢弃整轮。已经完成的文件写入仍保留,需显式撤销;`/rollback` 可从轮次快照恢复已追踪文件,逐个选择「保留/撤销」,不依赖 git。
|
|
110
108
|
- **输入安全网** — 长 prompt 不再怕误按 Enter:`Ctrl+G` 弹出 TUI 内「输入面板」(记事本式编辑,Enter=换行、软换行、选区、复制/剪切/粘贴、撤销,Ctrl+S 填回输入框不自动发送);`Ctrl+R`/`Ctrl+P` 模糊搜索历史输入(Enter 只回填不发送);长文本误发后撤回窗口自动放宽到 2 秒且任意键可撤回。
|
|
111
|
-
-
|
|
109
|
+
- **文件路径边界** — 内置文件读写拒绝越出 `SANDBOX_ROOT`(默认工作目录)的路径,包括路径穿越和软链出圈。这是文件工具的路径保护,不是针对 shell 命令、MCP server 或桌面输入的操作系统级沙箱;记忆与 skills 可以按设计访问项目外的配置位置。允许高风险工具前应审查权限,详见[沙箱策略](src/sandbox/policy.ts)。
|
|
112
110
|
- **Computer Use(高危,仅明确 GUI 意图时路由)** — 请求确实需要真实鼠标/键盘交互时,router 才可暴露 `computer-control`,并把每次动作后的截图回灌模型。`/cu off`(或 `MOCODE_COMPUTER_USE_ENABLED=false`)是硬否决;`/cu on` 仅允许按需路由,不会让工具常驻。它会绕过文件沙箱,**强烈建议只在 VM / 沙箱 / 专用测试机里使用**。每个动作仍走权限门,plan 模式永远屏蔽。Windows 首发,macOS/Linux 待接入。
|
|
113
111
|
|
|
114
112
|
## 特性
|
|
@@ -116,9 +114,15 @@ mocode 不是一个套壳聊天框,而是一个能真正动手干活的 agent:
|
|
|
116
114
|
- **流式输出 + 思考可见** — 回复边生成边显示;模型支持 reasoning 时思考过程实时可见,思考段自动折叠(不占屏)
|
|
117
115
|
- **全屏 TUI** — 备用屏(alt screen)+ 固定底栏状态行 + 滚动回看(PgUp/PgDn),运行中可打字(typeahead),下一轮自动预填
|
|
118
116
|
- **会话持久化** — 每轮自动落盘,`--resume` / `/resume` 续接历史会话
|
|
117
|
+
- **后台任务** — `mocode run --bg "任务"` 派 detached 子进程,关终端不死;状态与日志落 `.mocode/jobs/`,`/jobs` 可列表/看日志/kill。设 `MOCODE_NOTIFY_WEBHOOK` 后,任务结束自动推送通知(ntfy/Bark/Telegram/generic)。无人值守任务遇到未授权的 confirm/dangerous 动作时会挂起(状态 `paused`)并通知你;在另一终端敲 `mocode approve <id>` 批准(`mocode deny` 拒绝,或 TUI 内 `/jobs approve`),任务在同一进程内续跑。用 `mocode attach <id>` 可实时跟随运行中(或已结束)的任务。长任务在每个工具批次后落 checkpoint;进程挂掉或机器重启后,`mocode resume-job <id>` 从最后 checkpoint 重放(在途动作会重跑)。`MOCODE_JOB_MAX_MS` / `MOCODE_JOB_MAX_TOKENS` 提供硬性时长/token 上限。
|
|
118
|
+
- **具名 Bot** — `mocode bots add` 定义岗位 Bot(专属系统提示 + 可选工具白名单 + 沙箱范围),项目/全局两级;`--bot <name>` 按名运行,可与后台/schedules 组合。
|
|
119
|
+
- **Arena 竞技场** — `arena` 工具把同一任务并行跑 N 遍(2-6,各自独立),再由 judge 模型按你给的标准对所有候选打分排序,返回排名和最优方案。适合设计/探索/解题这类“多跑几遍选最好”的场景。
|
|
120
|
+
- **持久 Bot 消息协作** — `message_bus` 工具给具名 bot 提供持久的异步消息存储(`send`/`inbox`/`ack`/`history`):主管 bot 可把活交给当前没在运行的 bot;worker 之后(如被计划任务唤起)拉 inbox、干活、回复。身份随 `--bot` 走,每个 bot 只能看到/确认发给自己的消息。
|
|
121
|
+
- **计划任务** — `mocode schedule add` 注册 cron / webhook 触发;本地 detached 守护(`schedule start`,仅回环)到点或被 `POST /trigger/<token>` 触发即派后台 job,分钟去重;另有 `schedule tick` 供系统任务计划调用。
|
|
122
|
+
- **Headless 一次性执行** — `mocode -p "任务"` 或管道 `echo "任务" | mocode`,可选 `--json` 结构化输出;非交互下 confirm/dangerous 操作默认拒绝(`--dangerously-skip-permissions` 显式放开;`--verbose` 追加工具结果摘要、`--session-dir <目录>`、`--worktree` git 隔离工作树),会话仍自动落盘可 `--resume`
|
|
119
123
|
- **Skills 系统** — 自动扫描 `~/.mocode/skills/` 等目录,description 注入系统提示,模型按需调 `use_skill` 加载完整指令(渐进式披露:先看简介,任务相关才加载正文)
|
|
120
124
|
- **可选桌宠** — 独立悬浮窗(`/pet`)显示一个小角色,镜像 agent 活动(空闲 / 思考 / 跑工具 / 等人工),独立进程走 WebSocket,`/pet quit` 完全关闭。挂在终端外,绝不挡终端。
|
|
121
|
-
- **斜杠命令** — `/exit` `/clear` `/cd` `/context` `/skills` `/compact` `/resume` `/rollback` `/memory` `/reflect` `/init` `/theme` `/model` `/effort` `/stats` `/plan` `/auto` `/pet`,输入时下拉过滤
|
|
125
|
+
- **斜杠命令** — `/exit` `/clear` `/cd` `/context` `/skills` `/compact` `/resume` `/rollback` `/jobs` `/schedules` `/bots` `/memory` `/reflect` `/init` `/theme` `/model` `/effort` `/stats` `/plan` `/auto` `/pet`,输入时下拉过滤
|
|
122
126
|
|
|
123
127
|
## 使用文档
|
|
124
128
|
|
|
@@ -135,7 +139,7 @@ npm install -g mocode-ai
|
|
|
135
139
|
|
|
136
140
|
装完即得 `mocode` 命令。不想全局装也可免装直跑:`npx mocode-ai`。
|
|
137
141
|
|
|
138
|
-
> mocode
|
|
142
|
+
> mocode 启动时不查询 registry,也不自动安装更新。需要时显式使用 `/upgrade check`、`/upgrade status` 或 `/upgrade now` 检查、查看状态或升级;源码/tsx 开发模式禁止真正执行安装。实现见[升级命令](src/commands/upgrade.ts)。
|
|
139
143
|
|
|
140
144
|
### 从源码运行(开发 / 贡献)
|
|
141
145
|
|
|
@@ -146,7 +150,23 @@ npm install
|
|
|
146
150
|
npm start
|
|
147
151
|
```
|
|
148
152
|
|
|
149
|
-
源码经 tsx
|
|
153
|
+
源码经 tsx 直接运行,无需先构建。修改代码后需重启 `npm start` 生效(tsx 启动时加载模块,不热更新)。请在仓库根目录安装依赖,让 npm 处理 workspaces;完整依赖和开发命令以 [package.json](package.json) 为准,不在此重复维护清单。
|
|
154
|
+
|
|
155
|
+
### 技术栈状态与贡献边界
|
|
156
|
+
|
|
157
|
+
生产主路径是 TypeScript CLI;`packages/work-app` 处于孵化阶段,`packages/pet-app` 是可选组件,`rust/` 是非关键路径的实验性 TUI,设有晋升或归档期限。参见:
|
|
158
|
+
|
|
159
|
+
- [技术栈状态与责任人](docs/architecture/stack-status.md)
|
|
160
|
+
- [架构决策](docs/adr/README.md)
|
|
161
|
+
- [贡献指南](CONTRIBUTING.md)
|
|
162
|
+
- [维护与排障手册](docs/runbooks/README.md)
|
|
163
|
+
- [Rust 实验状态](rust/README.md)
|
|
164
|
+
|
|
165
|
+
不要导入其他 package 的 `src/` 或内部 `dist/` 布局;应用通过 package exports 和公开的 `mocode-agent-host` bin 契约消费能力。
|
|
166
|
+
|
|
167
|
+
### 文档与实现同步
|
|
168
|
+
|
|
169
|
+
修改执行、权限、并发、回滚或升级行为时,应按本页对应的源码入口同步更新 `README.md` 和 `README.zh-CN.md`;架构图与当前行为一致后才嵌入。依赖与工具清单分别以 package manifests 和内置工具注册表为准,发布边界以技术栈状态页为准,不把设计提案或旧架构图当作已交付保证。
|
|
150
170
|
|
|
151
171
|
## 配置
|
|
152
172
|
|
|
@@ -202,6 +222,8 @@ LLM_MODEL=glm-4.6 # 换成你的模型名
|
|
|
202
222
|
| `MOCODE_LIFECYCLE` | 只维护 provenance 元数据,不按次数改写正文 | `true` |
|
|
203
223
|
| `MAX_STEPS` | 每轮 Agent 循环最大步数(仅防无限循环) | `1000` |
|
|
204
224
|
| `SUB_AGENT_MAX_STEPS` | 子 Agent 循环安全上限,默认与主 Agent 一致 | `1000` |
|
|
225
|
+
| `SUB_AGENT_CONCURRENCY` | 每批子 agent 调用的并发上限;设为 `1` 时逐个派发 | `5` |
|
|
226
|
+
| `SUB_AGENT_MAX_DEPTH` | 递归委派深度上限 | `3` |
|
|
205
227
|
| `SANDBOX_ROOT` | 沙箱根目录(文件操作边界;未配则用 cwd 兜底) | 无 |
|
|
206
228
|
| `MOCODE_SUBAGENT_ENABLED` | 设 `false` 硬禁用 `orchestration`;unset/`true` 允许按需路由 | 未设置 |
|
|
207
229
|
| `MOCODE_FRONTEND_TOOLS_ENABLED` | 设 `false` 硬禁用 `browser-debug` / `desktop-observe`(不影响 `background-exec`);unset/`true` 允许路由 | 未设置 |
|
|
@@ -220,7 +242,7 @@ mocode --resume <id> # 续接指定会话
|
|
|
220
242
|
mocode config # 改配置
|
|
221
243
|
```
|
|
222
244
|
|
|
223
|
-
|
|
245
|
+
从源码运行使用 `npm start`。源码和安装版启动时都不会自动检查更新;`/upgrade` 由用户显式触发,源码/tsx 模式禁止真正执行安装。
|
|
224
246
|
|
|
225
247
|
进入 REPL 后直接对话。启动即进全屏 TUI,显示横幅(模型 / 后端 / 工作目录 / 工具列表)。回复流式打印,思考段实时可见后折叠。
|
|
226
248
|
|
|
@@ -228,7 +250,9 @@ agent 工作在**启动时所在的工作目录**——想让它操作某个项
|
|
|
228
250
|
|
|
229
251
|
## 工具
|
|
230
252
|
|
|
231
|
-
每个真实用户轮都会先经过受约束的 LLM router
|
|
253
|
+
每个真实用户轮都会先经过受约束的 LLM router。公共工具包括 `read_file`、`glob`、`grep`、`web_search`、`web_fetch`、`plan_update`、`note_append`、`ask_human`、`use_skill`;写文件、shell 调试、浏览器调试、桌面观察/控制、记忆、编排和 MCP 作为可组合工具簇按需选择。初始能力不足时,主模型通过 `add_tool_groups` 请求追加能力,新增 schema 从下一 step 生效。路由失败只继承上一轮工具簇(或仅公共工具),绝不回退到全工具。
|
|
254
|
+
|
|
255
|
+
以下表格列举部分能力,不是完整工具清单。当前注册及能力声明见[内置工具注册表](src/tools/builtins/index.ts),实际暴露由 [ToolPolicy](src/tools/policy.ts) 控制。Codegraph 查询在安装了对应 skill/CLI 时使用,不是独立的内置 `codegraph` 工具。
|
|
232
256
|
|
|
233
257
|
| 工具 | 作用 |
|
|
234
258
|
| ------------- | ---------------------------------------------------------------------------------------------------------------------- |
|
|
@@ -240,20 +264,22 @@ agent 工作在**启动时所在的工作目录**——想让它操作某个项
|
|
|
240
264
|
| `dev_server` | 启动/查看/读日志/停止**任意需跨调用存活的后台进程**(dev server、推理服务、watcher、日志尾随) |
|
|
241
265
|
| `browser` | Playwright 驱动真实 Chromium:导航 / 点击 / 填表 / 取文本 / 截图 / 控制台诊断 |
|
|
242
266
|
| `glob` | 按 glob 模式找文件(排除 node_modules/.git) |
|
|
243
|
-
| `grep` |
|
|
244
|
-
| `codegraph` | 已建 `.codegraph/` 索引时,查代码符号源码与调用链(比 read_file/grep 更准更省) |
|
|
267
|
+
| `grep` | 内容正则搜索,以 ripgrep 为快速路径(随 `@vscode/ripgrep` 分发,尊重 `.gitignore`、跳过二进制),找不到 `rg` 时才回退纯 JS 扫描;`context=N` 内联返回邻居行并保留原始缩进,命中后基本不用再 read_file 一次 |
|
|
245
268
|
| `web_search` | 联网搜索(AnySearch),返回标题/URL/摘要/正文 |
|
|
246
269
|
| `web_fetch` | 抓取指定 URL,HTML 清洗成纯文本;带全套浏览器拟真头,瞬时失败(429/5xx/网络抖动)自动退避重试,可选纯文本代理回退 |
|
|
247
270
|
| `use_skill` | 加载某 skill 的完整 SKILL.md 指令 |
|
|
248
271
|
| `ask_human` | 决策点弹终端问答面板,用户选预设项或自由输入(阻塞至回应) |
|
|
249
272
|
| `plan_update` | 记录/更新会话执行计划(notes.md 的 `## Plan:` 段);三态步骤机,同一时刻至多一个 in_progress,全部完成自动结算为 `## Done:` |
|
|
250
|
-
| `sub-agent` |
|
|
273
|
+
| `sub-agent` | 派生独立历史、工具权限不超过父 step 的子 agent;有界并发,共享工作区和回滚轮次 |
|
|
251
274
|
|
|
275
|
+
| 记忆工具 | 作用 |
|
|
276
|
+
| -------- | ---- |
|
|
252
277
|
| `memory_save` | 存一条跨会话长期记忆(标题进索引,正文按需取) |
|
|
253
278
|
| `memory_search` | 按关键词搜记忆正文,命中即提升召回计数(影响遗忘衰减) |
|
|
254
279
|
| `memory_list` | 列记忆索引(id/标题/摘要,无正文) |
|
|
255
280
|
| `memory_update` | 原地改一条记忆(id 不变;纠正过时事实 / 改摘要 / 改 pin) |
|
|
256
281
|
| `memory_forget` | 遗忘记忆:默认归档(可复活),`mode=delete` 硬删(pinned 拒删) |
|
|
282
|
+
| `memory_graph` | 遍历邻居、查找路径、添加三元组或查看图谱统计;关键词搜索由 `memory_search` 提供 |
|
|
257
283
|
|
|
258
284
|
### 前端 / UI 闭环
|
|
259
285
|
|
|
@@ -271,7 +297,7 @@ dev_server stop id=srv-xxxx
|
|
|
271
297
|
- 两者在 plan 模式下均被禁用;mocode 退出时会树杀后台进程并关闭浏览器。
|
|
272
298
|
- 浏览器二进制不随 npm 包分发,首次使用前需 `npx playwright install chromium`。
|
|
273
299
|
|
|
274
|
-
前端能力按用途拆分:`browser` 属于 `browser-debug`,整桌面截图 `screenshot` 属于 `desktop-observe`,而 `dev_server`
|
|
300
|
+
前端能力按用途拆分:`browser` 属于 `browser-debug`,整桌面截图 `screenshot` 属于 `desktop-observe`,而 `dev_server` 独立成 **`background-exec` 簇**(不受 `/fe` 开关控制,但执行仍需经过权限检查) —— 任何需要跨工具调用存活的进程(dev server、推理/模型服务、watcher、日志尾随)都归它,而不是塞进 `run_command`。选中 `browser-debug` 会**蕴含**激活 `background-exec`:弱模型只想到要浏览器时,也能拿到「先把服务起起来」的能力(半套能力比多一套能力更糟)。图片读取(`read_file` 魔数分流)则始终是公共只读能力。任务同时需要结构化网页诊断与真实桌面交互时,router 可再组合 `computer-control`。`/fe off` 是硬否决,不是手动 profile 选择器——它不影响 `dev_server`。
|
|
275
301
|
|
|
276
302
|
### Shell 选择器
|
|
277
303
|
|
|
@@ -307,6 +333,7 @@ dev_server stop id=srv-xxxx
|
|
|
307
333
|
| `/model` | 两级面板切换模型(先选厂商再选模型;顶层按厂商名、厂商内按模型名过滤);也可配置 baseURL / apiKey / 上下文窗口,即时生效 + 持久化 |
|
|
308
334
|
| `/effort` | 设置思考强度 off/low/medium/high/auto(如 `/effort high`);未识别模型不下发参数 |
|
|
309
335
|
| `/stats` | 本会话用量:缓存命中率 / 分层 token / 压缩次数 |
|
|
336
|
+
| `/upgrade` | 显式检查更新、查看状态或安装(`check` / `status` / `now`);启动时不自动更新 |
|
|
310
337
|
| `/init` | 扫描项目生成 `AGENTS.md` 项目记忆(发给 agent 执行) |
|
|
311
338
|
| `/theme` | 切换颜色主题(↑↓ · Enter,或 `/theme <name>` 直切) |
|
|
312
339
|
| `/plan` | 切到 plan 模式(只读探查 + 产出计划,审批后切 auto 执行) |
|
|
@@ -358,9 +385,9 @@ mocode 的**双层记忆**模型,跟 Skills 是两件事:
|
|
|
358
385
|
## 类型检查
|
|
359
386
|
|
|
360
387
|
```bash
|
|
361
|
-
npm run typecheck #
|
|
388
|
+
npm run typecheck # protocol/runtime + 根项目 + tests + evals
|
|
362
389
|
```
|
|
363
390
|
|
|
364
391
|
## 可后续扩展
|
|
365
392
|
|
|
366
|
-
MCP
|
|
393
|
+
MCP 工具集成已经支持,配置见 [MCP 指南](src/mcp/README.md)。更细粒度的能力协调、可选的每 worker 独立 worktree 是后续扩展方向,不是当前共享工作区子 agent 已具备的保证。现有工具以[内置工具注册表](src/tools/builtins/index.ts)为准,生产、可选、孵化和实验技术栈的区别见[技术栈状态](docs/architecture/stack-status.md)。
|
|
@@ -64,7 +64,8 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
64
64
|
const turnLifecycle = createTurnLifecycle(opts, ctx, stages, savedMode);
|
|
65
65
|
const { usageMeter, emitTrace, traceTurnId } = turnLifecycle;
|
|
66
66
|
const toolTurnPlanState = { stepsSincePlanTouch: 0 };
|
|
67
|
-
|
|
67
|
+
if (!opts.continueFromHistory)
|
|
68
|
+
historyManager.appendUserTurn(userInput);
|
|
68
69
|
// P2:每用户 turn 一个重复读 scope,经 dispatcher → ToolContext 透传给 read_file。
|
|
69
70
|
const readDedup = createReadDedup();
|
|
70
71
|
// The initial cancellation checkpoint is captured after the user turn and before any model/tool work.
|
package/dist/agent/tool-turn.js
CHANGED
|
@@ -78,6 +78,8 @@ export async function runToolTurn(input) {
|
|
|
78
78
|
rebuildHistoryIndexes();
|
|
79
79
|
throw error;
|
|
80
80
|
}
|
|
81
|
+
// D3: batch committed (staged shadow pushed into backing) -> persist full history.
|
|
82
|
+
hooks.onCheckpoint?.(opts.history);
|
|
81
83
|
hooks.onToolBatchEnd?.();
|
|
82
84
|
cancellationLifecycle.checkpoint();
|
|
83
85
|
const batchDecision = terminationPolicy.decide({
|