mocode-ai 1.7.11 → 1.8.1

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
@@ -104,7 +104,7 @@ MoCode isn't a chat box with a coat of paint — it's an agent that actually get
104
104
  - **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.
105
105
  - **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
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. 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.
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. Background reflection is on by default (max 3 auto-reflections per session; `AUTO_REFLECT=false` to disable) and mines conversations for useful memories; profile facts are graded by provenance (reflection inferences stay candidates until the user confirms them); reflection also tallies behavioral evidence — a candidate is auto-internalized after several independent confirmations with zero contradiction, while a held belief demotes back to candidate after repeated behavioral contradiction (every such move is surfaced, and a user `/memory confirm` overrides it). Memories can be created, searched, updated, and forgotten, with recall-based decay.
108
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
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
110
  - **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.
@@ -215,7 +215,7 @@ Common backend `base_url` values:
215
215
  | `CONTEXT_WINDOW_TOKENS` | Model context window; must match the real model | `256000` |
216
216
  | `LLM_STREAM_USAGE` | Include `stream_options.include_usage` on streaming requests for real usage | `true` |
217
217
  | `AUTO_COMPACT` | Final history-compaction safety fallback | `true` |
218
- | `AUTO_REFLECT` | Background reflection pass (opt-in; periodically mines memories from conversations) | `false` |
218
+ | `AUTO_REFLECT` | Background reflection pass (on by default, max 3 auto runs/session; set `false` to disable) | `true` |
219
219
  | `REFLECT_EVERY_N` | Trigger a background reflection every N turns (runs alongside the agent, non-blocking) | `5` |
220
220
  | `ANYSEARCH_API_KEY` | Web search API key (falls back to anonymous free quota if unset) | none |
221
221
  | `ANYSEARCH_BASE_URL` | Search API endpoint | `https://api.anysearch.com` |
package/README.zh-CN.md CHANGED
@@ -104,7 +104,7 @@ mocode 不是一个套壳聊天框,而是一个能真正动手干活的 agent:
104
104
  - **子 agent 分而治之** — 子任务拥有独立历史分支,工具权限不超过父 step 的能力上限;按并发上限分批运行,直接写入共享工作区并共用父级回滚轮次。主线接收最终摘要及执行元数据;没有每个 worker 独立的文件系统隔离或合并阶段。
105
105
  - **计划 / 执行双模式** — `plan` 模式下探查并产出计划,不修改项目文件、不跑 shell 命令、不派生子 agent;内部会话和计划记录仍可持久化。`auto` 模式允许执行,但不是静态“全工具”模式:每个真实用户轮先由轻量 LLM router 选择最小充分工具簇,主模型需要时可在后续 step 追加能力。
106
106
  - **统一压力驱动压缩** — 正常 history 保留完整工具证据;达到 80% 后由一次调度事件运行所有已启用的清理,并始终继续 history 摘要。`/context` 显示实时用量,`/compact` 仍是用户显式覆盖。
107
- - **跨会话长期记忆** — agent 能把项目架构、约定、踩过的坑存成长期记忆,下次会话自动加载;可通过 `AUTO_REFLECT=true` 开启后台反思,从对话中挖掘值得记住的事实(默认关闭)。记忆可增删改、带召回衰减。
107
+ - **跨会话长期记忆** — agent 能把项目架构、约定、踩过的坑存成长期记忆,下次会话自动加载;后台反思默认开启(每会话至多 3 次、`AUTO_REFLECT=false` 可关),从对话中挖掘值得记住的事实,画像事实按来源分级(反思推断先作候选,用户确认才内化);反思还会累计行为证据——候选经多次独立印证且零反驳会自动内化,已内化信念若被后续行为反复相悖则退回候选(每次自动升降级都会提示,用户可用 `/memory confirm` 翻案)。记忆可增删改、带召回衰减。
108
108
  - **会话记事本(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
109
  - **可中断、可回滚** — Ctrl+C 将中断信号传给模型请求及支持取消的运行中工具;历史恢复到最近已提交工具批次的检查点,而不是无条件丢弃整轮。已经完成的文件写入仍保留,需显式撤销;`/rollback` 可从轮次快照恢复已追踪文件,逐个选择「保留/撤销」,不依赖 git。
110
110
  - **输入安全网** — 长 prompt 不再怕误按 Enter:`Ctrl+G` 弹出 TUI 内「输入面板」(记事本式编辑,Enter=换行、软换行、选区、复制/剪切/粘贴、撤销,Ctrl+S 填回输入框不自动发送);`Ctrl+R`/`Ctrl+P` 模糊搜索历史输入(Enter 只回填不发送);长文本误发后撤回窗口自动放宽到 2 秒且任意键可撤回。
@@ -214,7 +214,7 @@ LLM_MODEL=glm-4.6 # 换成你的模型名
214
214
  | `CONTEXT_WINDOW_TOKENS` | 模型上下文窗口,须对齐真实模型 | `256000` |
215
215
  | `LLM_STREAM_USAGE` | 流式请求带 `stream_options.include_usage` 拿真实用量 | `true` |
216
216
  | `AUTO_COMPACT` | 最终 history compact 安全保护 | `true` |
217
- | `AUTO_REFLECT` | 后台反思 pass(默认关闭,需要时显式开启) | `false` |
217
+ | `AUTO_REFLECT` | 后台反思 pass(默认开启,每会话至多 3 次自动反思;显式 `false` 关闭) | `true` |
218
218
  | `REFLECT_EVERY_N` | 每 N 轮触发一次后台反思(与 agent 并发,不阻塞) | `5` |
219
219
  | `ANYSEARCH_API_KEY` | 联网搜索 API key(不配走匿名免费额度) | 无 |
220
220
  | `ANYSEARCH_BASE_URL` | 搜索 API 端点 | `https://api.anysearch.com` |
@@ -5,7 +5,7 @@
5
5
  import { ui } from '../ui/theme.js';
6
6
  import { Spinner } from '../ui/spinner.js';
7
7
  import { summarizeToolCall, summarizeToolResult, truncateDisplay, fmtElapsed } from '../ui/render.js';
8
- import { renderFileChange } from '../ui/diff.js';
8
+ import { renderFileChange, renderMultiFileChange } from '../ui/diff.js';
9
9
  import * as layout from '../ui/layout.js';
10
10
  import * as batch from '../ui/batch.js';
11
11
  import { config } from '../config/index.js';
@@ -150,7 +150,7 @@ function writeToolHeader(tc, toolRuntime) {
150
150
  }
151
151
  /** 渲染工具结果:mutation 成功走 diff 块(行号 + 语法高亮);其余走一行 preview。
152
152
  * 同 writeToolHeader,改为累积到 BatchRenderer(只缓存字符串,不写屏)。 */
153
- function writeToolResult(tc, output, parsed, preWriteOld, editStartLine, toolRuntime) {
153
+ function writeToolResult(tc, output, parsed, preWriteOld, editStartLine, toolRuntime, multiHunks) {
154
154
  // 优先按 tool_call id 反查所属批(并行 / sub-agent 组时 currentBatchId 已不是它)。
155
155
  const batchId = batch.batchIdForCall(tc.id) ?? currentBatchId;
156
156
  if (!batchId)
@@ -173,19 +173,55 @@ function writeToolResult(tc, output, parsed, preWriteOld, editStartLine, toolRun
173
173
  }
174
174
  let diff = null;
175
175
  if ((tc.name === 'edit_file' || tc.name === 'write_file') && parsed && !isToolErrorOutput(output)) {
176
- const oldText = tc.name === 'edit_file' ? String(parsed.old_string ?? '') : preWriteOld;
177
- const newText = String((tc.name === 'edit_file' ? parsed.new_string : parsed.content) ?? '');
178
- diff = renderFileChange({
179
- path: String(parsed.path ?? ''),
180
- kind: tc.name === 'edit_file' ? 'edit' : 'write',
181
- oldStr: tc.name === 'edit_file' ? String(parsed.old_string ?? '') : preWriteOld,
182
- newStr: String((tc.name === 'edit_file' ? parsed.new_string : parsed.content) ?? ''),
183
- startLine: tc.name === 'edit_file' ? editStartLine : 1,
184
- });
176
+ const filePath = String(parsed.path ?? '');
177
+ const isEdit = tc.name === 'edit_file';
178
+ // 多替换模式:每个 old/new 段一个 hunk,渲染成一个 Update 块内的多个 hunk。
179
+ const multi = isEdit && multiHunks && multiHunks.length > 0 ? multiHunks : null;
180
+ const oldText = isEdit
181
+ ? multi
182
+ ? multi.map((h) => h.oldStr).join('\n')
183
+ : String(parsed.old_string ?? '')
184
+ : preWriteOld;
185
+ const newText = isEdit
186
+ ? multi
187
+ ? multi.map((h) => h.newStr).join('\n')
188
+ : String(parsed.new_string ?? '')
189
+ : String(parsed.content ?? '');
190
+ if (multi) {
191
+ diff = renderMultiFileChange({
192
+ path: filePath,
193
+ hunks: multi.map((h) => ({ oldStr: h.oldStr, newStr: h.newStr, startLine: h.startLine })),
194
+ });
195
+ // 渲染器对超大 diff 返回 null(无法做 LCS)时退回工具结果摘要。
196
+ if (!diff)
197
+ diff = renderFileChange({
198
+ path: filePath,
199
+ kind: 'edit',
200
+ oldStr: oldText,
201
+ newStr: newText,
202
+ startLine: editStartLine,
203
+ });
204
+ }
205
+ else {
206
+ diff = renderFileChange({
207
+ path: filePath,
208
+ kind: isEdit ? 'edit' : 'write',
209
+ oldStr: isEdit ? String(parsed.old_string ?? '') : preWriteOld,
210
+ newStr: String((isEdit ? parsed.new_string : parsed.content) ?? ''),
211
+ startLine: isEdit ? editStartLine : 1,
212
+ });
213
+ }
214
+ // 回合改动统计:多替换按各 hunk 独立计算后累加(拼接不相邻段再 diff 会把跨段行误算成增删)。
215
+ const delta = multi
216
+ ? multi.reduce((acc, h) => {
217
+ const d = lineDelta(h.oldStr, h.newStr);
218
+ return { added: acc.added + d.added, removed: acc.removed + d.removed };
219
+ }, { added: 0, removed: 0 })
220
+ : lineDelta(oldText, newText);
185
221
  turnFileChanges.push({
186
- path: String(parsed.path ?? ''),
222
+ path: filePath,
187
223
  kind: tc.name === 'write_file' && preWriteOld == null ? 'A' : 'M',
188
- ...lineDelta(oldText, newText),
224
+ ...delta,
189
225
  });
190
226
  }
191
227
  const preview = diff ? '' : summarizeToolResult(tc.name, output);
@@ -406,7 +442,7 @@ runtimeOrContext = defaultRuntime) {
406
442
  onToolStart: (name) => spinner.start(t('agent.executing', { tool: name })),
407
443
  onToolOutput: (tc, chunk) => batch.recordOutput(tc.id, chunk, layout),
408
444
  onToolDone: () => spinner.stop(),
409
- onToolResult: (tc, output, parsed, preWriteOld, editStartLine) => writeToolResult(tc, output, parsed, preWriteOld, editStartLine, runtime.context.toolRuntime),
445
+ onToolResult: (tc, output, parsed, preWriteOld, editStartLine, multiHunks) => writeToolResult(tc, output, parsed, preWriteOld, editStartLine, runtime.context.toolRuntime, multiHunks),
410
446
  onToolBatchEnd: () => {
411
447
  // 一次工具轮次结束不再切 UI batch;下一轮若仍无正文,继续复用 currentBatchId。
412
448
  },
@@ -290,7 +290,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
290
290
  break;
291
291
  }
292
292
  case 'result':
293
- hooks.onToolResult?.(event.call, event.outcome.output, event.parsed, event.diff.preWriteOld, event.diff.editStartLine);
293
+ hooks.onToolResult?.(event.call, event.outcome.output, event.parsed, event.diff.preWriteOld, event.diff.editStartLine, event.diff.multiHunks);
294
294
  if (event.call.name === 'ask_human' && event.outcome.status === 'success') {
295
295
  askHumanCountThisTurn += 1;
296
296
  emitTrace('ask_human_call', {
@@ -326,6 +326,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
326
326
  delegation: delegationForOrchestrator,
327
327
  readDedup,
328
328
  argumentErrorHint: (name) => argumentErrorHint(name, runtimeContextState),
329
+ ...(result.finishReason ? { finishReason: result.finishReason } : {}),
329
330
  onToolOutput: (call, chunk) => hooks.onToolOutput?.(call, chunk),
330
331
  ...(opts.toolPolicy
331
332
  ? {
@@ -401,6 +402,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
401
402
  allowedToolNames: currentAllowedToolNames(),
402
403
  delegation: delegationForOrchestrator(),
403
404
  readDedup,
405
+ ...(result.finishReason ? { finishReason: result.finishReason } : {}),
404
406
  });
405
407
  }
406
408
  }
@@ -572,6 +574,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
572
574
  allowedToolNames: currentAllowedToolNames(),
573
575
  delegation: delegationForOrchestrator(),
574
576
  readDedup,
577
+ ...(result.finishReason ? { finishReason: result.finishReason } : {}),
575
578
  }));
576
579
  // 完成即发:usage/onToolOutcome/trace 在各 outcome 落地瞬间发出(1s 的
577
580
  // grep 不再被 60s 的 web_fetch 卡住可见性);history 回灌严格按原序。
@@ -671,6 +674,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
671
674
  delegation: delegationForOrchestrator(),
672
675
  readDedup,
673
676
  ...(hint ? { argumentErrorHint: hint } : {}),
677
+ ...(result.finishReason ? { finishReason: result.finishReason } : {}),
674
678
  onLockAcquired: (lockedArgs) => {
675
679
  entry.diff = readDiffContext(entry.tc, lockedArgs, ctx.jailResolve);
676
680
  },
@@ -685,7 +689,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
685
689
  for (let offset = 0; offset < entries.length; offset++) {
686
690
  const entry = entries[offset];
687
691
  const outcome = await outcomes[offset];
688
- hooks.onToolResult?.(entry.tc, outcome.output, entry.denied ? null : entry.parsed, entry.diff.preWriteOld, entry.diff.editStartLine);
692
+ hooks.onToolResult?.(entry.tc, outcome.output, entry.denied ? null : entry.parsed, entry.diff.preWriteOld, entry.diff.editStartLine, entry.diff.multiHunks);
689
693
  pushToolResult(history, entry.tc, outcome.output, relprune, lifecycle, scheduler, runtimeContextState, outcome.status === 'success');
690
694
  const invalidatedFiles = [
691
695
  ...new Set([...(outcome.changedFiles ?? []), ...(outcome.staleFiles ?? [])]),
@@ -760,6 +764,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
760
764
  delegation: delegationForOrchestrator(),
761
765
  readDedup,
762
766
  ...(hint ? { argumentErrorHint: hint } : {}),
767
+ ...(result.finishReason ? { finishReason: result.finishReason } : {}),
763
768
  onLockAcquired: (lockedArgs) => {
764
769
  entry.diff = readDiffContext(entry.tc, lockedArgs, ctx.jailResolve);
765
770
  },
@@ -776,7 +781,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
776
781
  for (let k = 0; k < entries.length; k++) {
777
782
  const entry = entries[k];
778
783
  const outcome = await started[k];
779
- hooks.onToolResult?.(entry.tc, outcome.output, entry.denied ? null : entry.parsed, entry.diff.preWriteOld, entry.diff.editStartLine);
784
+ hooks.onToolResult?.(entry.tc, outcome.output, entry.denied ? null : entry.parsed, entry.diff.preWriteOld, entry.diff.editStartLine, entry.diff.multiHunks);
780
785
  pushToolResult(history, entry.tc, outcome.output, relprune, lifecycle, scheduler, runtimeContextState, outcome.status === 'success');
781
786
  const invalidatedFiles = [
782
787
  ...new Set([...(outcome.changedFiles ?? []), ...(outcome.staleFiles ?? [])]),
@@ -856,6 +861,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
856
861
  delegation: delegationForOrchestrator(),
857
862
  readDedup,
858
863
  ...(serialHint ? { argumentErrorHint: serialHint } : {}),
864
+ ...(result.finishReason ? { finishReason: result.finishReason } : {}),
859
865
  onLockAcquired: (lockedArgs) => {
860
866
  if (mutationParsed)
861
867
  diff = readDiffContext(tc, lockedArgs, ctx.jailResolve);
@@ -866,7 +872,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
866
872
  traceToolEnd(tc, i, outcome);
867
873
  const output = outcome.output;
868
874
  hooks.onToolDone?.();
869
- hooks.onToolResult?.(tc, output, mutationParsed, diff.preWriteOld, diff.editStartLine);
875
+ hooks.onToolResult?.(tc, output, mutationParsed, diff.preWriteOld, diff.editStartLine, diff.multiHunks);
870
876
  if (tc.name === 'ask_human' && outcome.status === 'success') {
871
877
  askHumanCountThisTurn += 1;
872
878
  emitTrace('ask_human_call', {
@@ -49,6 +49,7 @@ class LegacyCompatibleToolDispatcher {
49
49
  delegation: request.delegation(),
50
50
  readDedup: request.readDedup,
51
51
  ...(hint ? { argumentErrorHint: hint } : {}),
52
+ ...(request.finishReason ? { finishReason: request.finishReason } : {}),
52
53
  ...(onLockAcquired ? { onLockAcquired } : {}),
53
54
  });
54
55
  const executionEvents = (index, parsed, outcome) => {
@@ -128,31 +128,59 @@ export function unregisteredToolOutcome(name, toolRuntime) {
128
128
  /** mutation 执行前读旧内容供 diff:write_file 取整文件旧内容(不存在→null=新建),
129
129
  * edit_file 取 old_string 起始行号(供 diff 显示真实文件行号)。读不到则 diff 退化为相对行号。
130
130
  * 非 mutation 或参数非法返 { preWriteOld: null, editStartLine: 1 }。失败不阻断。 */
131
+ const toLf = (s) => s.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
131
132
  export function readDiffContext(tc, parsed, resolvePath = jailResolve) {
133
+ const empty = { preWriteOld: null, editStartLine: 1 };
132
134
  if (!parsed)
133
- return { preWriteOld: null, editStartLine: 1 };
135
+ return empty;
134
136
  const p = String(parsed.path ?? '');
135
137
  if (!p)
136
- return { preWriteOld: null, editStartLine: 1 };
138
+ return empty;
137
139
  if (tc.name === 'write_file') {
138
140
  try {
139
141
  // jailResolve:沙箱越界(../../、绝对外圈、软链出圈)抛错 → catch 兜底返 null,不泄露牢外内容(TOCTOU)
140
142
  return { preWriteOld: readFileSync(resolvePath(p), 'utf8'), editStartLine: 1 };
141
143
  }
142
144
  catch {
143
- return { preWriteOld: null, editStartLine: 1 }; // 文件不存在(新建)、不可读 或 沙箱越界(不泄露)
145
+ return empty; // 文件不存在(新建)、不可读 或 沙箱越界(不泄露)
144
146
  }
145
147
  }
146
148
  if (tc.name === 'edit_file') {
147
149
  // 行尾归一化:LLM 生成的 old_string 用 LF(\n),但 Windows 文件可能是 CRLF(\r\n),
148
150
  // 不统一则 indexOf 必败、editStartLine 恒为 1。与 edit-file.ts 保持一致归一化为 LF。
149
- const oldStr = String(parsed.old_string ?? '')
150
- .replace(/\r\n/g, '\n')
151
- .replace(/\r/g, '\n');
151
+ const replacements = Array.isArray(parsed.replacements) ? parsed.replacements : null;
152
152
  try {
153
153
  // jailResolve:同上,沙箱越界抛错 → catch 兜底,不泄露牢外内容
154
154
  const raw = readFileSync(resolvePath(p), 'utf8');
155
- const data = raw.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
155
+ const data = toLf(raw);
156
+ // 多替换模式:在「编辑前」的原文上为每个 old_string 定位唯一命中的起始行,
157
+ // 供多 hunk diff 显示真实文件行号。任一项非唯一/找不到就不带 hunk(退回工具结果摘要),
158
+ // 真正的原子校验仍以 edit-file.ts execute 为准,这里只做展示、失败不阻断。
159
+ if (replacements) {
160
+ const hunks = [];
161
+ for (const item of replacements) {
162
+ if (!item || typeof item !== 'object')
163
+ return empty;
164
+ const rec = item;
165
+ if (typeof rec.old_string !== 'string' || typeof rec.new_string !== 'string')
166
+ return empty;
167
+ const oldStr = toLf(rec.old_string);
168
+ if (!oldStr)
169
+ return empty;
170
+ const first = data.indexOf(oldStr);
171
+ if (first < 0 || data.indexOf(oldStr, first + oldStr.length) !== -1)
172
+ return empty;
173
+ hunks.push({
174
+ oldStr: rec.old_string,
175
+ newStr: rec.new_string,
176
+ startLine: data.slice(0, first).split('\n').length,
177
+ });
178
+ }
179
+ if (hunks.length === 0)
180
+ return empty;
181
+ return { preWriteOld: null, editStartLine: hunks[0].startLine, multiHunks: hunks };
182
+ }
183
+ const oldStr = toLf(String(parsed.old_string ?? ''));
156
184
  const idx = oldStr ? data.indexOf(oldStr) : -1;
157
185
  return {
158
186
  preWriteOld: null,
@@ -160,10 +188,10 @@ export function readDiffContext(tc, parsed, resolvePath = jailResolve) {
160
188
  };
161
189
  }
162
190
  catch {
163
- return { preWriteOld: null, editStartLine: 1 }; // 读不到:diff 退化为相对行号(含沙箱越界)
191
+ return empty; // 读不到:diff 退化为相对行号(含沙箱越界)
164
192
  }
165
193
  }
166
- return { preWriteOld: null, editStartLine: 1 };
194
+ return empty;
167
195
  }
168
196
  /** 回灌 tool 结果到 history。
169
197
  * 正常路径只做单条 hard cap;原始 output 同时供 TUI 展示,因此用户与模型
@@ -22,11 +22,19 @@ export function readConfigFile() {
22
22
  }
23
23
  /**
24
24
  * 读-合并-写:把 entries 覆盖进 ~/.mocode/config,保留文件里其它键。
25
- * mkdirSync 兜底(首跑无 ~/.mocode)。不吞 I/O 异常——向导路径让其抛(与历史行为一致);
26
- * UI 偏好路径用 `updateConfigKey`(自带 try/catch 静默)。
25
+ * 值为 null 表示从配置文件删除该键(用于切到「不带某可选值」的预设时清除残留,
26
+ * 否则旧值会一直盖过新预设)。mkdirSync 兜底(首跑无 ~/.mocode)。不吞 I/O 异常——
27
+ * 向导路径让其抛(与历史行为一致);UI 偏好路径用 `updateConfigKey`(自带 try/catch 静默)。
27
28
  */
28
29
  export function writeConfigKeys(entries) {
29
- const merged = { ...readConfigFile(), ...entries };
30
+ const existing = readConfigFile();
31
+ const merged = { ...existing };
32
+ for (const [k, v] of Object.entries(entries)) {
33
+ if (v === null)
34
+ delete merged[k];
35
+ else
36
+ merged[k] = v;
37
+ }
30
38
  const body = Object.entries(merged)
31
39
  .map(([k, v]) => `${k}=${v}`)
32
40
  .join('\n');
@@ -57,6 +57,7 @@ const LLM_ENV_KEYS = [
57
57
  'LLM_API_KEY',
58
58
  'LLM_MODEL',
59
59
  'CONTEXT_WINDOW_TOKENS',
60
+ 'MAX_TOKENS',
60
61
  'ANTHROPIC_PROMPT_CACHE',
61
62
  'REASONING_EFFORT',
62
63
  ];
@@ -485,7 +486,7 @@ ${buildWorkDisciplineSection(inferModelFamily(config.model))}
485
486
  - Silent Execution: invoke tools directly without preamble. Output visible text ONLY for the final answer and critical mid-task findings. Strictly no step-by-step narration (no "let me…", "让我先…", "now checking…" between calls).
486
487
  - Go directly to a known path or symbol; use discovery tools only when the location is unknown.
487
488
  - Edit against a FRESH read: before editing, call read_file on the exact path and copy the exact target text. Never reconstruct old_string from a grep/summary/diff — those lose whitespace and indentation and cause edit failures.
488
- - Pick the right file tool: use edit_file for partial changes to an existing file (expected_hash is OPTIONAL in old_string mode, REQUIRED in line-range mode); use write_file only to create a file, to rewrite most of a file (replacing needs the latest read_file hash), or to append (append=true needs no read_file and no hash). Never write a throwaway script (tmp_patch*.cjs, fix_*.py, ...) to modify source files: scripts run outside ChangeSet tracking, so rollback and diff cannot see them.
489
+ - Pick the right file tool: for an EXISTING file, DEFAULT to edit_file — one old_string for a single change, replacements[] for many separate changes in one atomic call, or a line range for a big block. Do NOT overwrite an existing file with write_file just to tweak parts of it (re-sending the whole file wastes tokens and its long JSON is truncation-prone). Use write_file only to create a new file, to append (append=true needs no read_file and no hash), or to rewrite essentially the WHOLE file (a full rewrite needs the latest read_file hash). expected_hash is OPTIONAL in edit_file old_string/replacements mode, REQUIRED in line-range mode. Never write a throwaway script (tmp_patch*.cjs, fix_*.py, ...) to modify source files: scripts run outside ChangeSet tracking, so rollback and diff cannot see them.
489
490
  - A read_file hash from before a compaction, session resume, edit conflict, or external change is STALE and will be rejected if you pass it. In edit_file old_string mode just omit expected_hash; otherwise re-read rather than reuse an old hash.
490
491
  - Emit multiple independent tool calls in ONE assistant message so they run concurrently — e.g. several read_file regions, a grep plus a glob, or several web_fetch calls. One lookup per message wastes a full model round-trip each time. Place parallel-safe calls consecutively; keep any call that depends on their results (e.g. an edit) for the next message.
491
492
  - Never batch a read with an edit that depends on it; do not repeat overlapping reads or unchanged failed calls.
@@ -581,7 +582,8 @@ export const config = {
581
582
  model: llmKeysFromShell.includes('LLM_MODEL')
582
583
  ? process.env.LLM_MODEL || 'gpt-4o-mini'
583
584
  : (__activePreset?.model ?? process.env.LLM_MODEL ?? 'gpt-4o-mini'),
584
- maxTokens: process.env.MAX_TOKENS ? Number(process.env.MAX_TOKENS) : undefined,
585
+ // 优先级:shell env > 激活预设(目录添加时按 limit.output 预填)> undefined=不下发吃后端默认。
586
+ maxTokens: process.env.MAX_TOKENS ? Number(process.env.MAX_TOKENS) : (__activePreset?.maxTokens ?? undefined),
585
587
  // 用 getter 而非 buildBasePrompt() 立即求值:对象字面量初始化期间 buildBasePrompt 会读取
586
588
  // config.model 等字段,直接调用会触发 TDZ。Getter 也让语言、persona 等运行时变化在下一轮生效。
587
589
  get systemPrompt() {
@@ -610,7 +612,7 @@ export const config = {
610
612
  contextBudget: process.env.MOCODE_BUDGET_SCHEDULER !== 'false',
611
613
  lowPressureRatio: Math.min(0.95, Math.max(0.1, Number(process.env.MOCODE_LOW_PRESSURE_RATIO) || 0.6)),
612
614
  toolClearing: process.env.MOCODE_TOOL_CLEARING !== 'false',
613
- autoReflect: process.env.AUTO_REFLECT === 'true',
615
+ autoReflect: process.env.AUTO_REFLECT !== 'false',
614
616
  memoryEnabled: process.env.MEMORY_ENABLED === 'true',
615
617
  reflectEveryN: Number(process.env.REFLECT_EVERY_N) || 5,
616
618
  maxSteps: Number(process.env.MAX_STEPS) || 1000,
@@ -727,6 +729,14 @@ export function updateModelConfig(opts) {
727
729
  config.contextWindowTokens = opts.contextWindowTokens;
728
730
  process.env.CONTEXT_WINDOW_TOKENS = String(opts.contextWindowTokens);
729
731
  }
732
+ if (opts.maxTokens !== undefined) {
733
+ // null = 显式清除(切到无该值的预设);数字 = 设置。同步 env 保证本窗口立即按新值/不发该字段。
734
+ config.maxTokens = opts.maxTokens === null ? undefined : opts.maxTokens;
735
+ if (opts.maxTokens === null)
736
+ delete process.env.MAX_TOKENS;
737
+ else
738
+ process.env.MAX_TOKENS = String(opts.maxTokens);
739
+ }
730
740
  if (opts.anthropicPromptCache !== undefined) {
731
741
  config.anthropicPromptCache = opts.anthropicPromptCache;
732
742
  process.env.ANTHROPIC_PROMPT_CACHE = opts.anthropicPromptCache ? 'true' : 'false';
@@ -88,6 +88,14 @@ export function parsePreset(raw) {
88
88
  if (typeof contextWindow !== 'number' || !Number.isFinite(contextWindow) || contextWindow <= 0) {
89
89
  throw new Error(`预设 ${name}: contextWindow 必须为正数`);
90
90
  }
91
+ // maxTokens 可选:缺省=不下发(吃后端默认);给了就必须是正整数。
92
+ let maxTokens;
93
+ if (obj.maxTokens !== undefined && obj.maxTokens !== null) {
94
+ if (typeof obj.maxTokens !== 'number' || !Number.isFinite(obj.maxTokens) || obj.maxTokens <= 0) {
95
+ throw new Error(`预设 ${name}: maxTokens 必须为正数`);
96
+ }
97
+ maxTokens = Math.floor(obj.maxTokens);
98
+ }
91
99
  const provider = normalizePresetProvider(obj.provider);
92
100
  const anthropicPromptCache = provider === 'anthropic' && obj.anthropicPromptCache !== false;
93
101
  // reasoningEffort 缺省 = auto;显式写了非法值按现有校验风格报错(坏文件由 listPresets 跳过)。
@@ -132,6 +140,7 @@ export function parsePreset(raw) {
132
140
  apiKey,
133
141
  model,
134
142
  contextWindow: Math.floor(contextWindow),
143
+ ...(maxTokens ? { maxTokens } : {}),
135
144
  anthropicPromptCache,
136
145
  ...(reasoningEffort ? { reasoningEffort } : {}),
137
146
  ...extra,
package/dist/headless.js CHANGED
@@ -22,7 +22,7 @@ import './tools/builtins/index.js';
22
22
  import { initializeAllMcp, getMcpTools, closeAllMcp } from './mcp/index.js';
23
23
  import { config, buildBasePrompt, isMemoryEnabled } from './config/index.js';
24
24
  import { effectiveSystemPrompt } from './skills/index.js';
25
- import { buildMemoryIndexSection } from './memory/store.js';
25
+ import { buildMemoryIndexSection, gcMemories } from './memory/store.js';
26
26
  import { buildAboutYouSection, initPersona } from './memory/persona.js';
27
27
  import { buildProjectGraphHint } from './memory/recall.js';
28
28
  import { defaultRuntime, Runtime } from './runtime/index.js';
@@ -158,6 +158,15 @@ export async function runHeadless(opts) {
158
158
  // 系统提示:Bot 岗位角色在前,基础约定在后;白名单存在时补一句工具边界。
159
159
  const memoryOn = isMemoryEnabled();
160
160
  initPersona(memoryOn);
161
+ // 遗忘 GC 与反思解耦:headless 启动也跑一次(best-effort,不拖垮一次性执行)。
162
+ if (memoryOn) {
163
+ try {
164
+ gcMemories();
165
+ }
166
+ catch {
167
+ // best-effort
168
+ }
169
+ }
161
170
  const baseConventions = buildBasePrompt(sessionId) +
162
171
  buildAboutYouSection(memoryOn) +
163
172
  buildMemoryIndexSection(memoryOn) +
@@ -21,6 +21,9 @@ const zhCN = {
21
21
  'commands.memoryOff': '关闭记忆子系统',
22
22
  'commands.memoryStatus': '查看当前开关与原理',
23
23
  'commands.memoryReflect': '手动触发后台记忆反思',
24
+ 'commands.memoryProfile': '查看长期画像与待确认候选',
25
+ 'commands.memoryProfileConfirm': '确认一条画像候选并内化(/memory confirm <edge-id>)',
26
+ 'commands.memoryProfileDrop': '撤销一条画像(/memory drop <edge-id>)',
24
27
  'commands.memoryInit': '扫描项目生成 AGENTS.md 项目记忆',
25
28
  'commands.subagent': '子 Agent 自动路由 gate',
26
29
  'commands.subagentOn': '允许按需路由 orchestration',
@@ -418,6 +421,9 @@ const en = {
418
421
  'commands.memoryOff': 'Disable the memory subsystem',
419
422
  'commands.memoryStatus': 'Show current state and behavior',
420
423
  'commands.memoryReflect': 'Run background memory reflection',
424
+ 'commands.memoryProfile': 'Show long-term profile and pending candidates',
425
+ 'commands.memoryProfileConfirm': 'Confirm a profile candidate and internalize it (/memory confirm <edge-id>)',
426
+ 'commands.memoryProfileDrop': 'Withdraw a profile fact (/memory drop <edge-id>)',
421
427
  'commands.memoryInit': 'Scan project and generate AGENTS.md',
422
428
  'commands.subagent': 'Sub-agent automatic-routing gate',
423
429
  'commands.subagentOn': 'Allow orchestration to be routed when needed',
package/dist/llm/index.js CHANGED
@@ -579,7 +579,11 @@ async function chatWithRuntime(runtime, messages, handlers, signal, toolsOverrid
579
579
  };
580
580
  // 流中途故障用独立计数,避免与 HTTP 层共享 10 次预算(理由见 STREAM_RETRY_MAX_ATTEMPTS)。
581
581
  let streamRetries = 0;
582
- for (let attempt = 1; attempt <= RETRY_MAX_ATTEMPTS; attempt++) {
582
+ // 后台任务可收紧总尝试数(见 LlmRequestOverrides.maxAttempts);非法值回落到默认。
583
+ const maxAttempts = overrides?.maxAttempts && Number.isFinite(overrides.maxAttempts)
584
+ ? Math.min(RETRY_MAX_ATTEMPTS, Math.max(1, Math.floor(overrides.maxAttempts)))
585
+ : RETRY_MAX_ATTEMPTS;
586
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
583
587
  if (signal?.aborted) {
584
588
  throw new DOMException('This operation was aborted', 'AbortError');
585
589
  }
@@ -602,7 +606,7 @@ async function chatWithRuntime(runtime, messages, handlers, signal, toolsOverrid
602
606
  isStreamInterruptedError(err) &&
603
607
  !producedOutput &&
604
608
  streamRetries < STREAM_RETRY_MAX_ATTEMPTS;
605
- if (attempt >= RETRY_MAX_ATTEMPTS || (!isRetryableError(err, signal) && !streamRetryable)) {
609
+ if (attempt >= maxAttempts || (!isRetryableError(err, signal) && !streamRetryable)) {
606
610
  throw err;
607
611
  }
608
612
  if (streamRetryable)
@@ -740,6 +744,10 @@ async function chatOnce(messages, handlers, signal, toolsOverride, runtime = def
740
744
  let consumedAny = false;
741
745
  const thinkFilter = new ThinkTagFilter();
742
746
  let usage;
747
+ // finish_reason 只在最后一个带 choice 的 chunk 出现;取最后一次非空值。
748
+ // 'length' 意味着输出在 max_tokens 处被硬切断——长 tool_call 参数此时必为残缺 JSON,
749
+ // 工具层据此把笼统的 INVALID_JSON 升级成截断恢复指引。
750
+ let finishReason;
743
751
  const toolAcc = new Map();
744
752
  const emitVisible = (text) => {
745
753
  if (!text)
@@ -784,7 +792,11 @@ async function chatOnce(messages, handlers, signal, toolsOverride, runtime = def
784
792
  cachedTokens: usage.cachedTokens,
785
793
  });
786
794
  }
787
- const delta = chunk.choices?.[0]?.delta;
795
+ const choice0 = chunk.choices?.[0];
796
+ const delta = choice0?.delta;
797
+ if (typeof choice0?.finish_reason === 'string' && choice0.finish_reason) {
798
+ finishReason = choice0.finish_reason;
799
+ }
788
800
  if (!delta)
789
801
  continue; // 末尾 usage-only chunk 等无 delta
790
802
  if (delta.content) {
@@ -835,6 +847,7 @@ async function chatOnce(messages, handlers, signal, toolsOverride, runtime = def
835
847
  content: consumedAny ? visibleContent : null,
836
848
  toolCalls,
837
849
  usage,
850
+ finishReason,
838
851
  };
839
852
  }
840
853
  // ── token 估算(自包含,不依赖 ui / 外部 tokenizer)──────────────────────
@@ -315,6 +315,8 @@ export async function anthropicChatOnce(messages, handlers, signal, tools, runti
315
315
  await throwResponseError(response);
316
316
  let content = '';
317
317
  let usage;
318
+ // message_delta 的 delta.stop_reason 给出停止原因;max_tokens 归一到 OpenAI 的 'length'。
319
+ let finishReason;
318
320
  const toolAcc = new Map();
319
321
  const live = { cjk: 0, other: 0 };
320
322
  const reportLive = () => {
@@ -391,6 +393,12 @@ export async function anthropicChatOnce(messages, handlers, signal, tools, runti
391
393
  continue;
392
394
  }
393
395
  if (type === 'message_delta') {
396
+ // stop_reason 位于 message_delta 的 delta 子对象(与 usage 同级事件)。
397
+ const d = event.delta;
398
+ if (typeof d?.stop_reason === 'string' && d.stop_reason) {
399
+ // Anthropic: end_turn / max_tokens / stop_sequence / tool_use / tool_use 等。
400
+ finishReason = d.stop_reason === 'max_tokens' ? 'length' : d.stop_reason;
401
+ }
394
402
  const raw = event.usage;
395
403
  if (raw) {
396
404
  const previous = usage ?? usageFromAnthropic({});
@@ -414,5 +422,5 @@ export async function anthropicChatOnce(messages, handlers, signal, tools, runti
414
422
  const toolCalls = [...toolAcc.entries()]
415
423
  .sort((a, b) => a[0] - b[0])
416
424
  .map(([, call]) => ({ ...call, arguments: call.arguments || '{}' }));
417
- return { content: content || null, toolCalls, usage };
425
+ return { content: content || null, toolCalls, usage, finishReason };
418
426
  }
@@ -407,5 +407,11 @@ export async function vertexChatOnce(messages, handlers, signal, tools, runtime,
407
407
  content += marker;
408
408
  handlers.onText?.(marker);
409
409
  }
410
- return { content: content || null, toolCalls, usage };
410
+ return {
411
+ content: content || null,
412
+ toolCalls,
413
+ usage,
414
+ // Gemini MAX_TOKENS 归一到 OpenAI 的 'length',供工具层给出截断恢复指引。
415
+ ...(finishReason ? { finishReason: finishReason === 'MAX_TOKENS' ? 'length' : finishReason } : {}),
416
+ };
411
417
  }