mocode-ai 1.10.0 → 1.10.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.
Files changed (50) hide show
  1. package/dist/agent/index.js +13 -3
  2. package/dist/agent/mentioned-files.js +71 -0
  3. package/dist/agent/model-turn.js +55 -11
  4. package/dist/agent/progress-guard.js +67 -0
  5. package/dist/agent/run-coordinator.js +140 -12
  6. package/dist/agent/short-path-completion.js +109 -0
  7. package/dist/agent/spawn.js +39 -0
  8. package/dist/agent/stages/history-manager.js +1 -0
  9. package/dist/agent/tool-helpers.js +2 -2
  10. package/dist/agent/tool-turn.js +49 -4
  11. package/dist/agent/work-discipline.js +9 -9
  12. package/dist/config/index.js +13 -10
  13. package/dist/context/relevance.js +2 -1
  14. package/dist/host/stdio.js +88 -27
  15. package/dist/i18n/index.js +26 -10
  16. package/dist/llm/index.js +27 -3
  17. package/dist/llm/message-shape.js +18 -0
  18. package/dist/llm/reasoning.js +17 -0
  19. package/dist/models/reasoning-cap.js +19 -2
  20. package/dist/orchestrator/lane-executor.js +7 -1
  21. package/dist/orchestrator/repl.js +30 -49
  22. package/dist/repl/commands/appearance.js +1 -2
  23. package/dist/repl/commands/compact.js +4 -0
  24. package/dist/repl/commands/model-actions.js +4 -3
  25. package/dist/repl/commands/model.js +2 -3
  26. package/dist/repl/message-format.js +7 -6
  27. package/dist/repl/running-input.js +27 -65
  28. package/dist/repl/runtime.js +118 -76
  29. package/dist/rollback/store.js +36 -23
  30. package/dist/runtime/runtime.js +1 -1
  31. package/dist/session/compact.js +41 -4
  32. package/dist/session/retention.js +4 -0
  33. package/dist/session/short-path-metrics.js +185 -0
  34. package/dist/session/store.js +78 -3
  35. package/dist/session/terminal-transcript.js +101 -0
  36. package/dist/tools/builtins/ask-human.js +2 -2
  37. package/dist/tools/builtins/edit-file.js +28 -5
  38. package/dist/tools/builtins/grep.js +85 -35
  39. package/dist/tools/builtins/plan-update.js +4 -2
  40. package/dist/tools/builtins/read-file.js +95 -44
  41. package/dist/tools/builtins/run-command.js +57 -9
  42. package/dist/tools/ripgrep-client.js +31 -11
  43. package/dist/tools/tool-runtime.js +29 -8
  44. package/dist/ui/layout-internal/content-write.js +7 -3
  45. package/dist/ui/layout-internal/core.js +1 -1
  46. package/dist/ui/layout-internal/state.js +0 -6
  47. package/dist/ui/layout-internal/statusbar.js +0 -30
  48. package/dist/ui/output-sink.js +24 -0
  49. package/dist/ui/spinner.js +3 -1
  50. package/package.json +4 -2
@@ -0,0 +1,109 @@
1
+ import { lstatSync, readFileSync } from 'node:fs';
2
+ import { contentHash } from '../changeset/hash.js';
3
+ import { parseArgs } from './tool-helpers.js';
4
+ // 只接受明确、完整的字面量替换请求。命令仍由模型经正常权限和工具流程调用。
5
+ const ZH = /^将 ?`(?<file>[^`\r\n]+)` ?中的 ?`(?<oldText>[^`\r\n]+)` ?替换为 ?`(?<newText>[^`\r\n]*)`。(?:然后运行 ?`(?<command>[^`\r\n]+)`|无需运行检查)。?$/u;
6
+ const EN = /^Replace `(?<oldText>[^`\r\n]+)` with `(?<newText>[^`\r\n]*)` in `(?<file>[^`\r\n]+)`\. (?:Then run `(?<command>[^`\r\n]+)`|No checks needed)\.?$/iu;
7
+ const MAX_EDIT_BYTES = 256 * 1024;
8
+ export function createShortPathCompletion(input, ctx) {
9
+ const text = input.trim();
10
+ const zh = ZH.exec(text);
11
+ const match = zh ?? EN.exec(text);
12
+ if (!match?.groups)
13
+ return;
14
+ const { file, oldText, newText, command } = match.groups;
15
+ if (oldText === newText)
16
+ return;
17
+ let edit;
18
+ let verified = false;
19
+ let fallback;
20
+ const resolve = (value) => {
21
+ if (typeof value !== 'string')
22
+ return;
23
+ try {
24
+ return ctx.jailResolve(value);
25
+ }
26
+ catch {
27
+ return;
28
+ }
29
+ };
30
+ return {
31
+ get fallback() {
32
+ return fallback;
33
+ },
34
+ reject(reason) {
35
+ fallback ??= reason;
36
+ },
37
+ observe(call, outcome) {
38
+ if (fallback)
39
+ return;
40
+ if (outcome.status !== 'success') {
41
+ fallback = 'tool_failed';
42
+ return;
43
+ }
44
+ const args = parseArgs(call.arguments);
45
+ if (!edit && call.name === 'read_file' && !outcome.modelAttachments?.length) {
46
+ const target = resolve(file);
47
+ if (target && target === resolve(args?.path))
48
+ return;
49
+ }
50
+ if (!edit && call.name === 'edit_file') {
51
+ const target = resolve(file);
52
+ const change = outcome.changeSet?.changes[0];
53
+ if (target &&
54
+ target === resolve(args?.path) &&
55
+ args?.old_string === oldText &&
56
+ args?.new_string === newText &&
57
+ outcome.exactTextReplacement &&
58
+ outcome.changeSet?.changes.length === 1 &&
59
+ change?.operation === 'update' &&
60
+ change.beforeHash &&
61
+ change.afterHash &&
62
+ target === resolve(change.path)) {
63
+ edit = { path: target, hash: change.afterHash };
64
+ }
65
+ else {
66
+ fallback = 'edit_unproven';
67
+ }
68
+ return;
69
+ }
70
+ if (edit && command && call.name === 'run_command') {
71
+ if (args?.command === command &&
72
+ args.shell === undefined &&
73
+ outcome.code === 'OK' &&
74
+ !outcome.changedFiles?.length) {
75
+ verified = true;
76
+ }
77
+ else {
78
+ fallback = 'verification_mismatch';
79
+ }
80
+ return;
81
+ }
82
+ fallback = 'unexpected_tool';
83
+ },
84
+ finalText() {
85
+ if (fallback || !edit || (command && !verified))
86
+ return;
87
+ const changes = ctx.getCurrentTurnMutationState().changedFiles;
88
+ if (changes.length !== 1 || resolve(changes[0].path) !== edit.path || resolve(file) !== edit.path) {
89
+ fallback = 'workspace_changed';
90
+ return;
91
+ }
92
+ try {
93
+ const info = lstatSync(edit.path);
94
+ if (!info.isFile() || info.size > MAX_EDIT_BYTES || contentHash(readFileSync(edit.path)) !== edit.hash) {
95
+ fallback = 'workspace_changed';
96
+ return;
97
+ }
98
+ }
99
+ catch {
100
+ fallback = 'workspace_changed';
101
+ return;
102
+ }
103
+ const target = '`' + file + '`';
104
+ if (zh)
105
+ return command ? `已在${target}完成替换,指定检查已通过。` : `已在${target}完成替换。`;
106
+ return command ? `Updated ${target}. The requested check passed.` : `Updated ${target}.`;
107
+ },
108
+ };
109
+ }
@@ -145,6 +145,26 @@ export async function spawnAgent(opts) {
145
145
  ? `Task context (authoritative; do not rediscover):\n${opts.context.slice(0, 4000)}\n\nSub-task:\n${opts.prompt}`
146
146
  : opts.prompt;
147
147
  }
148
+ // ── 结构化进度行(progress 通道的机器可读一半)──
149
+ // 人类可读的 `▸ 工具名 对象` 只有一行、且不含工具输出,GUI 侧没有任何可展开的内容。
150
+ // 这里对每次内部工具调用额外吐 start/end 两条**单行** JSON,宿主可据此把子 agent 的步骤
151
+ // 渲染成可展开条目(GUI 现在就是这么做的)。单行是硬约束:宿主按 \n 累积,JSON.stringify
152
+ // 会把内容里的换行转义掉;超长入参/输出裁到上限,避免一次 read_file 撑大 IPC 与恢复日志。
153
+ //
154
+ // 前缀常量在 packages/work-app/src/sub-agent-progress.ts 有一份同值拷贝:
155
+ // 渲染层是浏览器环境、不能 import src 的模块,故由那个纯函数模块承载解析(两边注释互指)。
156
+ const SUB_TOOL_PREFIX = '[sub-tool]';
157
+ const SUB_TOOL_MAX_CHARS = 6000;
158
+ const clipSubTool = (text) => text.length <= SUB_TOOL_MAX_CHARS
159
+ ? text
160
+ : `${text.slice(0, SUB_TOOL_MAX_CHARS)}\n… (${text.length - SUB_TOOL_MAX_CHARS} more chars)`;
161
+ const emitSubTool = (payload) => {
162
+ if (live || !opts.progress)
163
+ return;
164
+ opts.progress(`${SUB_TOOL_PREFIX}${JSON.stringify(payload)}\n`);
165
+ };
166
+ /** 本子 agent 内部工具调用的单调序号:宿主按它对齐 start/end 两条(同一步并行调用时 tc.id 可能缺失)。 */
167
+ let stepToolSeq = 0;
148
168
  // 静默 hooks:缓冲中间过程到 transcript,不写主屏。
149
169
  let transcript = '';
150
170
  const buf = [];
@@ -254,6 +274,15 @@ export async function spawnAgent(opts) {
254
274
  if (!live && opts.progress) {
255
275
  opts.progress(`▸ ${tc.name} ${summary}\n`);
256
276
  }
277
+ // 结构化一条 start:带完整入参,宿主展开时能看到真实命令/替换片段。
278
+ emitSubTool({
279
+ phase: 'start',
280
+ seq: stepToolSeq++,
281
+ id: tc.id ?? '',
282
+ name: tc.name,
283
+ summary,
284
+ args: clipSubTool(tc.arguments ?? ''),
285
+ });
257
286
  // 实时写入主内容区:子 agent 的每次工具调用累计到摘要行计数。
258
287
  ensureQuietLine(opts.quietLabel ?? t('skill.executing', { name: opts.prompt.slice(0, 40) }));
259
288
  ensureLiveBatch();
@@ -270,6 +299,16 @@ export async function spawnAgent(opts) {
270
299
  const preview = summarizeToolResult(tc.name, output);
271
300
  if (preview)
272
301
  writeBuf(` ↳ ${preview}\n`);
302
+ // 结构化一条 end:带该次调用的输出(截断)。这是 GUI 展开子 agent 步骤时唯一的数据来源——
303
+ // 在此之前子 agent 的工具输出从未离开子进程。
304
+ emitSubTool({
305
+ phase: 'end',
306
+ id: tc.id ?? '',
307
+ name: tc.name,
308
+ summary: preview || t('toolSummary.noOutput'),
309
+ failed: isToolErrorOutput(output),
310
+ output: clipSubTool(output),
311
+ });
273
312
  if (liveBatchId) {
274
313
  // 子 agent 批不展示 diff(其写入已直接落工作区,由主 agent 的当前回滚事务统一追踪);
275
314
  // 空 preview 用占位标记 entry 已完成,避免折叠后摘要仍显示"运行中"。
@@ -16,6 +16,7 @@ function assistantMessage(turn) {
16
16
  // 「agent 完成了这一轮」写盘。构造点在此收敛,transport 边界另有兜底
17
17
  // (src/llm/message-shape.ts)负责让存量中毒会话自愈。
18
18
  content: !hasToolCalls && turn.content === null ? '' : turn.content,
19
+ ...(turn.reasoningContent ? { reasoning_content: turn.reasoningContent } : {}),
19
20
  };
20
21
  if (hasToolCalls) {
21
22
  // thoughtSignature 不是 OpenAI 字段,是 mocode 给 Gemini/Vertex 透传用的;
@@ -201,10 +201,10 @@ export function pushToolResult(history, tc, output, pruner, lifecycle, _schedule
201
201
  const succeeded = succeededOverride ?? isToolResultSuccess(output);
202
202
  const capped = capToolResultForHistory(tc.name, output);
203
203
  // push-time 截断兜底:完整结果另存 compacted/result-<id>.txt,并在进 history 的
204
- // 截断内容尾部留一行全文指针。仅主 agent(共享 contextState)落盘——子 agent 的
204
+ // 截断内容尾部留一行全文指针。仅持久化会话落盘——子 agent 的
205
205
  // 结果随其临时 history 消亡,不污染主会话。best-effort:存不上就只保留截断内容。
206
206
  let content = capped;
207
- if (capped.length < output.length && runtimeContextState === contextState) {
207
+ if (capped.length < output.length && runtimeContextState.archiveHistory) {
208
208
  try {
209
209
  const rel = getActiveSessionStore().archiveToolResult(getCurrentSessionId() ?? '', tc.id, output);
210
210
  if (rel)
@@ -1,4 +1,5 @@
1
- import { isToolResultsNoise } from './tool-helpers.js';
1
+ import { isToolResultsNoise, parseArgs } from './tool-helpers.js';
2
+ import { t } from '../i18n/index.js';
2
3
  const PLAN_NAG_THRESHOLD = 3;
3
4
  const PLAN_NAG_TEXT = '[mocode] Reminder: you have an active plan in notes.md but have not updated it recently. ' +
4
5
  'If you finished a step, call plan_update to check it off (keep at most one in_progress); ' +
@@ -9,9 +10,36 @@ const PLAN_NAG_TEXT = '[mocode] Reminder: you have an active plan in notes.md bu
9
10
  * 新增附件产出点**必须**复用这一个前言。
10
11
  */
11
12
  export const ATTACHMENT_PREAMBLE = 'The read_file tool loaded the following visual input: ';
13
+ function describeFirstAction(call) {
14
+ switch (call.name) {
15
+ case 'read_file':
16
+ case 'edit_file':
17
+ case 'write_file': {
18
+ const path = parseArgs(call.arguments)?.path;
19
+ const file = typeof path === 'string' && path.trim() && !/[\p{Cc}\p{Cf}]/u.test(path)
20
+ ? JSON.stringify(path.length > 100 ? path.slice(0, 97) + '…' : path)
21
+ : t('agent.openingTargetFile');
22
+ return t(call.name === 'read_file' ? 'agent.openingRead' : 'agent.openingEdit', { file });
23
+ }
24
+ case 'grep':
25
+ case 'glob':
26
+ return t('agent.openingSearch');
27
+ case 'run_command':
28
+ return t('agent.openingCommand');
29
+ case 'web_search':
30
+ case 'web_fetch':
31
+ return t('agent.openingWeb');
32
+ case 'ask_human':
33
+ return t('agent.openingClarify');
34
+ case 'add_tool_groups':
35
+ return t('agent.openingTools');
36
+ default:
37
+ return t('agent.openingGeneric');
38
+ }
39
+ }
12
40
  /** Owns tool-turn history publication, transaction settlement, plan nag, attachments and checkpoint ordering. */
13
41
  export async function runToolTurn(input) {
14
- const { opts, ctx, historyManager, result, stream, step, maxSteps, planState, turnLifecycle, cancellationLifecycle, terminationPolicy, rebuildHistoryIndexes, dispatch, } = input;
42
+ const { opts, ctx, historyManager, result, stream, step, opening, maxSteps, planState, turnLifecycle, cancellationLifecycle, terminationPolicy, rebuildHistoryIndexes, dispatch, } = input;
15
43
  const { hooks, signal } = opts;
16
44
  turnLifecycle.addToolCalls(result.toolCalls.length);
17
45
  if (result.content && isToolResultsNoise(result.content)) {
@@ -20,9 +48,26 @@ export async function runToolTurn(input) {
20
48
  stream.gotText = false;
21
49
  stream.lastChar = '';
22
50
  }
23
- if (stream.mode !== 'idle' && stream.lastChar !== '\n')
51
+ const needsOpening = opening && (!stream.gotText || !result.content?.trim());
52
+ if (needsOpening) {
53
+ // UI 兜底只陈述已知动作,不伪造模型正文或把工具参数写进模型历史。
54
+ const call = result.toolCalls[0];
55
+ const action = describeFirstAction(call);
56
+ hooks.onText?.(opening === 'steering' ? t('agent.openingSteered', { action }) : action);
57
+ turnLifecycle.emitTrace('opening_fallback', { tool: call.name, ...(opening === 'steering' ? { opening } : {}) });
58
+ }
59
+ if (needsOpening || (stream.mode !== 'idle' && stream.lastChar !== '\n'))
24
60
  hooks.onTextEnd?.();
25
- historyManager.appendAssistantTurn({ content: result.content, toolCalls: result.toolCalls });
61
+ if (opening) {
62
+ for (const call of result.toolCalls)
63
+ hooks.onToolCall?.(call.name);
64
+ hooks.onChatDone?.();
65
+ }
66
+ historyManager.appendAssistantTurn({
67
+ content: result.content,
68
+ toolCalls: result.toolCalls,
69
+ reasoningContent: result.reasoningContent,
70
+ });
26
71
  const toolBatch = historyManager.beginToolBatch(result.toolCalls);
27
72
  const workingHistory = toolBatch.workingMessages;
28
73
  try {
@@ -1,5 +1,6 @@
1
1
  // Lightweight, advisory working guidance. The agent decides how much discovery and
2
2
  // validation each task needs; the framework does not enforce a completion gate.
3
+ export const PLAN_USAGE_GUIDANCE = 'Use a plan for distinct deliverables, work that needs a durable handoff, or when the user requests one. Locating, editing and checking one focused change are one task.';
3
4
  /**
4
5
  * 从 config.model 字符串里嗅探 model family。匹配规则尽量宽松,够用即可。
5
6
  * 未来 AHE 闭环后可以换成 config.modelFamily 字段。
@@ -23,26 +24,25 @@ export function inferModelFamily(model) {
23
24
  const CORE_SECTION = `Use your judgment to choose the shortest reliable path from the request to a useful result.
24
25
 
25
26
  - Answer directly when you already can: questions, explanations, advice, reviews, and read-only analysis that the conversation and known evidence already support get a direct answer with no tools, no extra investigation, and no validation. Reach for a tool only when the answer genuinely depends on information you do not have.
26
- - Inspect only the code and context needed for the next decision; do not gather evidence "just in case".
27
+ - For one focused change in AUTO, read the owning code, apply the edit as soon as its target and effect are clear, and review the returned change. Open another file only to resolve a concrete dependency. Check changed behavior at its entry point when it could regress, then report the result.
27
28
  - Make the smallest coherent change and avoid unrelated refactors.
28
29
  - Preserve existing behavior and public API compatibility unless the task explicitly requires a change.
29
- - Validation (typecheck/lint/build/test, or running the change) applies only to work that changes code or behavior. Decide whether it is useful based on risk, scope, available commands, and the user's request; it is never required for pure questions, explanations, or read-only analysis. It is optional, not a completion gate, and the user asking for an answer is not asking for verification.
30
- - When validation is useful, choose the smallest relevant check yourself; do not run broad test/build suites by default. Trivial, self-evidently correct edits (comments, docs, typo fixes) need no check either.
31
- - Re-read or rerun only when evidence is stale or the next edit depends on exact current content.
30
+ - Review the diff returned by edit_file when available. For small local edits such as a label or style tweak, that can be sufficient. For a logic change, pick the smallest check that exercises the requested behavior. Respect explicit acceptance checks.
31
+ - When validation is useful, run ONE smallest relevant check, once: the owning package's typecheck, a single targeted test, or the affected entry point. Do not chain typecheck → lint → build → test, do not re-run a check that already passed on code you have not touched since, and do not run broad suites "to be safe". Comments, docs, formatting, and typo fixes need no check at all. It is optional, not a completion gate.
32
+ - Use the evidence already gathered. Make another call when it can resolve a remaining decision or verify a requested outcome. Once the outcomes are established, finish. Re-read or rerun when state may have changed or an edit needs exact current content.
32
33
  - On failure, diagnose before retrying; after repeated identical failures, change approach.
33
34
  - Report honestly what you changed, what you checked, and anything left uncertain.
34
35
 
35
36
  Never invent file paths, APIs, config keys, flags, or behavior. Distinguish repository evidence from assumptions.`;
36
37
  /**
37
- * ASK-02: user decisions and key modifications are the user's call, not the agent's.
38
- * The agent must call `ask_human` BEFORE acting; only trivial, reversible details may be decided alone.
38
+ * 用户决定影响结果的取舍与关键变更;常规、可回退的实现细节由 agent 处理。
39
39
  */
40
40
  const ASK_WHITELIST_SECTION = `## When to ask instead of guess
41
41
 
42
- The user owns every decision and every key change. NEVER decide these on your own: call \`ask_human\` FIRST, wait for the answer, then act. Asking is the default; acting alone is the exception.
42
+ Carry out a clear request using established local conventions. Choose routine, reversible implementation details yourself. Use \`ask_human\` before a key modification or when a missing user decision would change the outcome.
43
43
 
44
44
  Ask BEFORE acting when any of these applies:
45
- 1. A decision point: two or more reasonable approaches, designs, libraries, or behaviors exist and the user has not chosen one. Present the options with trade-offs and your recommendation; do not pick silently.
45
+ 1. A decision point: the available choices materially change user-visible behavior, compatibility, cost, or scope and the user has not chosen. Present the options with trade-offs and your recommendation.
46
46
  2. A key modification: changing public APIs, data formats, schemas, config semantics, or default behavior; adding, removing, or upgrading dependencies; renaming/moving/deleting files or modules; changing architecture or cross-module contracts; touching auth, permissions, security, or build/CI/release setup.
47
47
  3. A broad or risky change: edits spanning many files, large refactors, anything hard to reverse, or any external side effect (push, deploy, network writes, data deletion/migration).
48
48
  4. Scope growth: the work needs more than what the user asked for (extra features, unrelated fixes, behavior changes), or the request admits two or more materially different readings.
@@ -53,7 +53,7 @@ For ambiguous or vague requests, load the \`brainstorming\` skill and clarify th
53
53
 
54
54
  If the user cancels or answers "you decide", stop guessing: take the safest reversible option and state it. Do not repeat a question the user already answered.
55
55
 
56
- Only these may be decided alone: naming and style that follow repository precedent, local implementation details inside an already-approved change, and read-only investigation. Disclose any assumption you made.
56
+ An explicit request to implement a focused change authorizes its ordinary local implementation choices. Disclose assumptions that affect the result.
57
57
 
58
58
  There is no per-turn cap on \`ask_human\`: ask as often as a decision genuinely requires, but batch related questions into one call instead of asking one trivial thing at a time. If \`ask_human\` is unavailable or no user can answer (non-interactive run), choose the safest reversible option, avoid the key modification if possible, and disclose it in the final reply.`;
59
59
  /** Advisory guidance shared by main and sub-agents. */
@@ -7,7 +7,7 @@ import { getActiveSkill } from '../skills/activation.js';
7
7
  import { getCurrentSessionId } from '../session/state.js';
8
8
  import { getNotesFilePath, extractActiveNotesSections } from '../session/notes.js';
9
9
  import { buildGuiActionsSection } from '../session/gui-actions.js';
10
- import { buildWorkDisciplineSection, inferModelFamily } from '../agent/work-discipline.js';
10
+ import { buildWorkDisciplineSection, inferModelFamily, PLAN_USAGE_GUIDANCE } from '../agent/work-discipline.js';
11
11
  import { buildValidationCommandsSection } from '../verification/prompt.js';
12
12
  import { getActivePresetName, readPreset } from './presets.js';
13
13
  import { detectLanguage, setLanguage, t } from '../i18n/index.js';
@@ -144,7 +144,7 @@ const DEFAULT_VOICE = `## Voice
144
144
  - Give technical recommendations with brief trade-off reasoning when choices exist.
145
145
  - Focus on useful information. Avoid unnecessary greetings, apologies, repetition, or filler.
146
146
  - Match the user's style and language while staying task-focused.
147
- - Disclose assumptions; decisions and key modifications belong to the user, so ask first (see When to ask instead of guess).`;
147
+ - Disclose material assumptions and ask about decisions that affect the outcome (see When to ask instead of guess).`;
148
148
  /** 解析用户自定义声音:persona.md 文件优先(项目级 > 全局),其次 env MOCODE_PERSONA。无则返回 ''。 */
149
149
  function readPersonaFile() {
150
150
  const candidates = [
@@ -471,7 +471,7 @@ Complete programming tasks through an "analyze → call tool → observe result
471
471
  ## Workflow
472
472
  - Answer first: if the request is a question, explanation, or read-only analysis you can already answer from context and known evidence, reply directly — no tools, no exploration, no verification ceremony. Tool calls and checks exist only to get information the answer actually needs.
473
473
  - Understand: use existing conversation and tool evidence before gathering more.
474
- - Plan: for tasks with 3+ steps or context-loss risk, record the plan with the \`plan_update\` tool (see Session state).
474
+ - Plan: ${PLAN_USAGE_GUIDANCE}
475
475
  - Delegate: when the \`sub-agent\` tool is exposed, prefer it for exploration-heavy work (unfamiliar subsystems, multi-file audits, open-ended "how does X work here" investigation) and for independent sub-tasks — emit several \`sub-agent\` calls in ONE message and they run concurrently. A worker returns only its summary, so its tool noise never floods the main context. Keep single known-path reads and trivial lookups inline.
476
476
  - Implement: edit against a fresh read (see Tool policy); change scope follows Engineering principles.
477
477
  - Verify: only for work that changes code or behavior, and only when the risk is worth it — pure answers and read-only analysis need no verification. Whether and what to run follows Engineering principles; use Validation commands for exact commands.
@@ -484,13 +484,15 @@ ${buildValidationCommandsSection()}
484
484
  ${buildWorkDisciplineSection(inferModelFamily(config.model))}
485
485
 
486
486
  ## Tool policy
487
- - 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).
488
- - Go directly to a known path or symbol; use discovery tools only when the location is unknown.
489
- - 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.
487
+ - Opening and silent execution: the main agent starts every tool-using user turn with exactly one short visible sentence explaining what it will check or change first and why, in the SAME assistant response as the first tool calls. A new batch of live user updates gets one similar opening before the next tools. Sub-agents stay silent. After the opening, strictly no step-by-step narration (no "let me…", "让我先…", "now checking…" between calls).
488
+ - Known vs unknown target: when the request already names the file (a filename or path appears in the user's message), that file is KNOWN — make read_file on it your FIRST tool call. Do NOT grep/glob beforehand to "locate" or "confirm" a file the request already identified; that burns a full model round-trip for zero new information. Search only when the target file or symbol is genuinely unknown: grep with a narrow pattern and context to inspect nearby code immediately. For a known file and symbol, read_file(path, anchor, limit) locates and reads the implementation in one call.
489
+ - Edit against fresh exact text. For an unknown file and a specific symbol or literal, use grep(edit_context=true). If it returns an [edit_context ...] excerpt that covers the change, copy the exact text and pass its hash as expected_hash to edit_file without rereading. Otherwise use read_file on the exact path and narrow range. Ordinary search hits, summaries and diffs are not edit evidence.
490
490
  - 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.
491
- - 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.
491
+ - Treat evidence from before compaction, session resume, an edit conflict, or an external change as stale. Reread the affected range before reusing its text or hash. In old_string mode with a fresh read_file, expected_hash is optional.
492
492
  - 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.
493
493
  - Never batch a read with an edit that depends on it; do not repeat overlapping reads or unchanged failed calls.
494
+ - Batch related verification checks that share setup into one bounded script or existing test command. Return a compact per-check result and failure samples, without credentials or full response bodies. Use dedicated file tools for source lookup.
495
+ - When a group of checks fails in the same way, inspect the shared dependency once (for example, gateway registration when several related API paths return 404). Record confirmed blockers, finish independent checks, and batch the affected rechecks after any authorized fix. Report once the requested checks have evidence or a concrete blocker.
494
496
  - On failure, inspect the full error, change the approach, and retry only with a reason. Drop stale tool output when it no longer supports the task.
495
497
  - For generated content over roughly 200 lines or 5K tokens, write it in stages: first write_file the initial chunk, then extend it with write_file(append=true, content=<next chunk>) — each call stays small and the file grows transactionally. Appends are VERBATIM: if the file does not already end with a newline, begin your chunk with "\\n" so lines do not merge.
496
498
 
@@ -505,7 +507,7 @@ ${buildVoiceSection()}
505
507
 
506
508
  ## Reporting
507
509
  - Stop immediately when no more tools are needed; give conclusions directly.
508
- - **Do not stop prematurely during exploration**: if you started investigating but haven't gathered enough information to answer the user's question, keep calling tools. Only stop when you have sufficient evidence or hit a dead end.
510
+ - **Do not stop prematurely during exploration**: once you are already gathering evidence for a task, keep calling tools until you have enough to answer — do not bail out mid-investigation. This applies to the task you decided to work on, not to deciding whether a tool was needed at all: if the request was a question you could already answer, answering it directly was complete. Only stop when you have sufficient evidence or hit a dead end.
509
511
  - **No flattery / no preamble in conclusions**: skip "Sure", "好的", "我已经完成了" and similar no-information prefixes — jump straight to substance.
510
512
  - **Lead with the outcome**: the first line says what you did or what you found in one sentence — no restatement of the request, no "task completed" wrapper.
511
513
  - **Shape the rest for scanning**, including only the sections that carry content: what changed (grouped by logical change: \`path:line\` plus the behavior it delivers, one line each; note renames/deletions; skip purely mechanical edits) → what you verified and its result, or "not run" with the reason → what is still open (≤3 bullets). Never paste diffs or whole files the terminal already showed.
@@ -513,7 +515,7 @@ ${buildVoiceSection()}
513
515
  - **Prevent the follow-up**: before you stop, check the reply already answers what the user would ask next — what changed and where, why, what you verified, and what is left or uncertain. A missing fact costs the user a whole extra round-trip; add that fact, not more prose.
514
516
  - **No dead endings**: drop "hope this helps", "if you need anything else…", "let me know if you'd like me to…", and any closing paragraph that restates what you just wrote.
515
517
  - **Terminal-first formatting**: at most one level of \`##\` headings or a few bold lead-ins, lists no deeper than two levels, tables only when a column comparison is what makes them readable, no emoji. Reply in the user's language; keep code, paths, and commands verbatim.
516
- - Definition of done (code/behavior changes only): never declare a multi-feature implementation finished just because the code exists. Each distinct implementation request listed in the plan must be actually verified where a check is warranted (the relevant check run / observed result), not merely implemented; mark plan steps \`[x]\` only after that verification. If the user supplied an acceptance list, every item on it must pass. Leave unverified items explicitly listed as pending instead of collapsing them into "done". This rule does not apply to questions, explanations, or read-only analysis — answer those directly with no verification.`;
518
+ - Definition of done (multi-feature code/behavior changes only): never declare a multi-feature implementation finished just because the code exists. Where the change is actually observable to a check, verify it — one relevant check run, or the affected entry point exercised — not a chain of them. For a focused edit, follow the risk-based check in Engineering principles. Mark plan steps \`[x]\` once the step's work is complete, not only after a command ran. If the user supplied an acceptance list, every item on it must pass. Unverified items belong in the reply as pending, not folded into "done". This rule does not apply to questions, explanations, or read-only analysis.`;
517
519
  // 动态段(置于末尾):AGENTS.md 项目记忆 + notepad 索引/说明。工具簇特定指导由
518
520
  // ToolPolicyController.reminder() 按当前 turn 的 route 注入,避免旧全局 profile 与真实 schema 分裂。
519
521
  // 按需注入(#13):有内容的索引才拼对应标题,避免空标题噪声。
@@ -523,7 +525,7 @@ ${buildVoiceSection()}
523
525
  // 避免把规则在系统提示里每请求预付第三遍。**标题 '## Session state' 必须保留**:
524
526
  // buildMocodeCorePrompt 靠 MARKER_DROPPABLE_SECTION 给子 agent 切片。
525
527
  dynamicParts.push(`## Session state (\`.mocode/sessions/${sessionId ?? '<id>'}/notes.md\`)\n` +
526
- 'For tasks with 3+ steps or context-loss risk, keep an execution plan with `plan_update`; record non-obvious findings/decisions/open questions/risks with `note_append`. ' +
528
+ 'Use `plan_update` for durable plans and `note_append` for non-obvious findings, decisions or risks. ' +
527
529
  'Both write notes.md, which survives compaction — run read_file on it to recover context after compaction. ' +
528
530
  'Their formats and rules live in each tool\u2019s description; do not hand-edit the files. ' +
529
531
  'When compaction drops older conversation, its verbatim text (user messages, your earlier decisions, full tool args/results) is archived under ' +
@@ -612,6 +614,7 @@ export const config = {
612
614
  : (__activePreset?.reasoningEffort ?? parseReasoningEffort(process.env.REASONING_EFFORT) ?? 'auto'),
613
615
  compactFork: process.env.MOCODE_COMPACT_FORK !== 'false',
614
616
  readDedup: process.env.MOCODE_READ_DEDUP !== 'false',
617
+ shortPathCompletion: process.env.MOCODE_SHORT_PATH_COMPLETION === 'true',
615
618
  contextOptimize: process.env.MOCODE_CONTEXT_OPTIMIZE !== 'false',
616
619
  contextRelprune: process.env.MOCODE_CONTEXT_RELPRUNE !== 'false',
617
620
  contextLifecycle: process.env.MOCODE_LIFECYCLE !== 'false',
@@ -28,7 +28,8 @@ function normalizedInteger(value, fallback) {
28
28
  * 无法解析参数时返 null(调用方保守跳过,不做区间淘汰)。 */
29
29
  function readRange(argsRaw) {
30
30
  const args = parseArgs(argsRaw);
31
- if (!args)
31
+ // 带 anchor 时 offset 是查找起点,实际返回区间取决于文件内容。
32
+ if (!args || args.anchor !== undefined)
32
33
  return null;
33
34
  const offset = Math.max(1, normalizedInteger(args.offset, 1));
34
35
  const limit = Math.max(1, Math.min(normalizedInteger(args.limit, READ_DEFAULT_LIMIT), READ_LIMIT_CAP));
@@ -15,6 +15,7 @@ import { ToolPolicyController } from '../tools/policy.js';
15
15
  import { routeToolGroups } from '../tools/router.js';
16
16
  // 装配官方默认工具包:registry 不再顶层 import builtins(破模块循环),host 入口须显式装配。
17
17
  import '../tools/builtins/index.js';
18
+ import { muteStdoutOutput } from '../ui/output-sink.js';
18
19
  import { setAskHumanHandler } from '../tools/builtins/ask-human.js';
19
20
  import { HOST_PROTOCOL_VERSION, parseCommand } from './protocol.js';
20
21
  // ── 面板数据源(会话 / 回滚 / 改动 / 用量 / 记忆 / 设置)──
@@ -39,7 +40,7 @@ let sessionId = '';
39
40
  let history = [];
40
41
  let queryHistory = [];
41
42
  let lastToolGroups = [];
42
- let contextState = createContextState();
43
+ let contextState = createContextState({ archiveHistory: true });
43
44
  const approvals = new Map();
44
45
  /** 独立 AI 请求按面板 requestId 取消;不得复用任务 run 的 activeRun。 */
45
46
  const commitMessageRequests = new Map();
@@ -195,7 +196,7 @@ function createSession() {
195
196
  history = [{ role: 'system', content: currentSystemMessage() }];
196
197
  queryHistory = [];
197
198
  lastToolGroups = [];
198
- contextState = createContextState();
199
+ contextState = createContextState({ archiveHistory: true });
199
200
  // R17 基线必须跟着「会话真正开始」这一刻拍:/clear、resume 之后旧基线作废,
200
201
  // 否则新会话第一条消息会把上一会话的改动当成「本轮新增」播报一遍。
201
202
  captureMemoryBaseline();
@@ -214,7 +215,7 @@ function restoreSession(id) {
214
215
  history.unshift({ role: 'system', content: currentSystemMessage() });
215
216
  queryHistory = [...(loaded.queryHistory ?? [])];
216
217
  lastToolGroups = [...(loaded.lastToolGroups ?? [])];
217
- contextState = createContextState();
218
+ contextState = createContextState({ archiveHistory: true });
218
219
  captureMemoryBaseline();
219
220
  return true;
220
221
  }
@@ -319,6 +320,31 @@ function hooksFor(runId) {
319
320
  // usage.totalTokens 是本轮累计消耗,绝不是上下文占用;详情统一读当前 prompt 快照。
320
321
  emit('live_usage', { ...usage, contextUsage: contextUsageSnapshot() }, runId);
321
322
  },
323
+ // 自动压缩:终端有「压缩中」spinner + 压缩行,GUI 什么都看不到 —— 用户只会发现
324
+ // 上下文百分比莫名掉了一截。所以 start 立刻给状态行,done 在会话流里留一条系统行。
325
+ onCompactProgress: (event) => {
326
+ if (event.phase === 'start') {
327
+ emit('context_compacting', { manual: event.manual, ...(event.focus ? { focus: event.focus } : {}) }, runId);
328
+ return;
329
+ }
330
+ // 失败/中断只收状态行:没压成功就不该在会话流里留一条「已压缩」。
331
+ if (event.failed || event.aborted || !event.compacted) {
332
+ emit('context_compacting_done', { failed: event.failed === true, aborted: event.aborted === true }, runId);
333
+ return;
334
+ }
335
+ const usage = contextUsageSnapshot();
336
+ emit('context_compacted', {
337
+ manual: event.manual,
338
+ summarized: event.summarized,
339
+ reason: event.reason,
340
+ historyRebuilt: event.historyRebuilt === true,
341
+ beforeTokens: event.estimateBefore,
342
+ afterTokens: event.estimateAfter,
343
+ usagePercent: usage.percent,
344
+ contextUsage: usage,
345
+ contextWindow: runtime().context.config.contextWindowTokens,
346
+ }, runId);
347
+ },
322
348
  onImageRelief: (info) => emit('image_relief', { ...info }, runId),
323
349
  onNoReply: () => emit('no_reply', {}, runId),
324
350
  onMaxSteps: () => emit('max_steps', {}, runId),
@@ -326,11 +352,40 @@ function hooksFor(runId) {
326
352
  onDone: (elapsedMs, usage) => emit('run_finished', { elapsedMs, usage }, runId),
327
353
  };
328
354
  }
355
+ function inputForRun(command) {
356
+ return command.attachments?.length
357
+ ? [
358
+ ...(command.prompt ? [{ type: 'text', text: command.prompt }] : []),
359
+ ...command.attachments.flatMap((attachment) => {
360
+ if (attachment.dataUrl)
361
+ return [{ type: 'image_url', name: attachment.name, image_url: { url: attachment.dataUrl } }];
362
+ if (typeof attachment.text !== 'string')
363
+ return [];
364
+ // name/attachment/truncated 是会话回放元数据,transport 发送前统一移除。
365
+ return [
366
+ {
367
+ type: 'text',
368
+ name: attachment.name,
369
+ attachment: true,
370
+ truncated: attachment.truncated === true,
371
+ text: `用户附件 ${JSON.stringify(attachment.name)} 的提取文本如下。${attachment.truncated ? '(内容已截断,仅提供前 100000 字符)' : ''}\n\n${attachment.text}`,
372
+ },
373
+ ];
374
+ }),
375
+ ]
376
+ : command.prompt;
377
+ }
329
378
  async function run(command) {
330
379
  if (closing)
331
380
  return;
332
- if (activeRun)
333
- return error('An agent run is already active for this project.', command.id);
381
+ if (activeRun) {
382
+ if (activeRun.id !== command.id || activeRun.controller.signal.aborted)
383
+ return error('The active run cannot accept this message.', command.id);
384
+ activeRun.pending.push(inputForRun(command));
385
+ queryHistory.push(command.prompt);
386
+ emit('message_received', { pending: activeRun.pending.length }, command.id);
387
+ return;
388
+ }
334
389
  if (!command.prompt.trim() && !command.attachments?.length)
335
390
  return;
336
391
  let toolPolicy;
@@ -344,31 +399,11 @@ async function run(command) {
344
399
  // 每个被接受的 stdio run 都是真实用户 turn;在路由与 Agent 执行前清除上一轮 skill deny。
345
400
  clearSkillActivation();
346
401
  const controller = new AbortController();
347
- activeRun = { id: command.id, controller };
402
+ activeRun = { id: command.id, controller, pending: [] };
348
403
  queryHistory.push(command.prompt);
349
404
  // 首个模型请求前也要有可恢复的用户轮。run-coordinator 的 cancellation checkpoint
350
405
  // 是内存快照、不会调用 onCheckpoint;这里追加 user 后再落盘,避免首轮崩溃只剩侧栏标题。
351
- const userInput = command.attachments?.length
352
- ? [
353
- ...(command.prompt ? [{ type: 'text', text: command.prompt }] : []),
354
- ...command.attachments.flatMap((attachment) => {
355
- if (attachment.dataUrl)
356
- return [{ type: 'image_url', name: attachment.name, image_url: { url: attachment.dataUrl } }];
357
- if (typeof attachment.text !== 'string')
358
- return [];
359
- // name/attachment/truncated 是会话回放元数据,transport 发送前统一移除。
360
- return [
361
- {
362
- type: 'text',
363
- name: attachment.name,
364
- attachment: true,
365
- truncated: attachment.truncated === true,
366
- text: `用户附件 ${JSON.stringify(attachment.name)} 的提取文本如下。${attachment.truncated ? '(内容已截断,仅提供前 100000 字符)' : ''}\n\n${attachment.text}`,
367
- },
368
- ];
369
- }),
370
- ]
371
- : command.prompt;
406
+ const userInput = inputForRun(command);
372
407
  history.push({ role: 'user', content: userInput });
373
408
  persistSession();
374
409
  emit('run_started', {
@@ -420,6 +455,7 @@ async function run(command) {
420
455
  userInput,
421
456
  // 上面已把用户轮写入首个持久化检查点,core 不能再 append 一次。
422
457
  continueFromHistory: true,
458
+ drainUserMessages: () => activeRun?.pending.splice(0) ?? [],
423
459
  signal: controller.signal,
424
460
  hooks: hooksFor(command.id),
425
461
  contextState,
@@ -475,6 +511,13 @@ async function run(command) {
475
511
  approvals.delete(approvalId);
476
512
  }
477
513
  }
514
+ // Accepted messages must survive cancellation or a step-limit exit before consumption.
515
+ const remaining = activeRun?.pending.splice(0) ?? [];
516
+ if (remaining.length > 0) {
517
+ for (const content of remaining)
518
+ history.push({ role: 'user', content });
519
+ persistSession();
520
+ }
478
521
  activeRun = null;
479
522
  }
480
523
  }
@@ -507,6 +550,7 @@ async function compact(command) {
507
550
  if (!sessionId)
508
551
  createSession();
509
552
  emit('status', { value: 'compacting' }, command.id);
553
+ emit('context_compacting', { manual: true, ...(command.focus ? { focus: command.focus } : {}) }, command.id);
510
554
  const activeRuntime = runtime();
511
555
  const log = await activeRuntime.compact(history, {
512
556
  focus: command.focus,
@@ -518,6 +562,19 @@ async function compact(command) {
518
562
  // 旧实测锚点属于压缩前请求,不能跨摘要边界继续外推。
519
563
  contextState.promptAnchor = undefined;
520
564
  const usage = contextUsageSnapshot();
565
+ // 与自动路径同一个事件形状:GUI 的会话流据此留一条「已压缩」系统行(切走再回来还在)。
566
+ // compact_done 保留给旧客户端的 toast,两条事件在这里是有意的分工,不是重复。
567
+ emit('context_compacted', {
568
+ manual: true,
569
+ summarized: log.compactDetail?.reason === 'summarize',
570
+ reason: log.compactDetail?.reason,
571
+ historyRebuilt: log.historyMutation === 'rebuild',
572
+ beforeTokens: log.compactDetail?.estimateBefore,
573
+ afterTokens: log.compactDetail?.estimateAfter,
574
+ usagePercent: usage.percent,
575
+ contextUsage: usage,
576
+ contextWindow: runtime().context.config.contextWindowTokens,
577
+ }, command.id);
521
578
  emit('compact_done', {
522
579
  compacted: log.compactHistoryCalled,
523
580
  beforeTokens: log.compactDetail?.estimateBefore,
@@ -1346,6 +1403,10 @@ function requestShutdownCancellation() {
1346
1403
  }
1347
1404
  }
1348
1405
  const input = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
1406
+ // host 的 stdout 是 NDJSON 协议通道:layout.contentWrite / Spinner 的「非 TTY 直接写」兜底
1407
+ // 会把压缩行、图片卡片行这类裸文本灌进来,客户端 JSON.parse 失败后当 diagnostic 丢掉。
1408
+ // 用户可见反馈必须走下面的事件(context_compacted / image_relief …),兜底写一律静音。
1409
+ muteStdoutOutput();
1349
1410
  const pendingCommands = new Set();
1350
1411
  const heartbeatTimer = startHeartbeat();
1351
1412
  const startupPromise = initializeRuntime();