mocode-ai 1.8.2 → 1.8.4

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
@@ -40,7 +40,7 @@ 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
- - **`ask_human` for user-owned decisions** — The agent asks only when repository evidence cannot resolve a high-impact choice; implementation details remain autonomous.
43
+ - **`ask_human` for user-owned decisions** — The agent must ask before any decision the user has not made (multiple reasonable approaches) and before key modifications (public APIs, schemas, dependencies, file moves/deletes, architecture, security, large or irreversible changes). Only trivial, repository-precedent details are decided alone.
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
 
46
46
  ## Architecture
package/README.zh-CN.md CHANGED
@@ -92,14 +92,14 @@ mocode 把代码层控制保持得尽量轻,把任务策略交给 agent:
92
92
 
93
93
  - **建议式工作纪律** — system prompt 只要求聚焦改动、避免重复检索、诚实报告不确定性;是否验证及验证范围由 agent 自主决定,不是完成硬门。
94
94
  - **有界重试,明确报告失败** — runtime 仅对显式声明 `idempotent` 的工具瞬时错误自动重试,最多两次;`TIMEOUT`、权限拒绝、中断和非幂等调用不自动重试。最终结构化结果交给 agent,由其决定后续恢复方式,详见[自动重试](#自动重试retryable-契约)。
95
- - **ask_human 卡点降级** — 仅高影响且属于用户所有权的选择才询问,其余实现细节由 agent 自主推进。
95
+ - **ask_human 决策与关键修改先问** — 用户尚未做出的决策(存在多个合理方案)和关键修改(公共 API、schema、依赖、文件移动/删除、架构、安全、大范围或不可逆改动)必须先询问用户;只有符合仓库惯例的琐碎细节才由 agent 自行决定。
96
96
  - **五区上下文控制 + token 自校准** — 独立旋钮管理上下文压力,token 估算根据真实 provider 用量校准。
97
97
 
98
98
  ## 为什么用 mocode
99
99
 
100
100
  mocode 不是一个套壳聊天框,而是一个能真正动手干活的 agent:
101
101
 
102
- - **自主多步推进** — 一次对话里连续多步:读代码、改代码、跑测试、根据报错再改……agent 自己决定下一步,中途不用你反复催。遇到卡点会调 `ask_human` 弹面板问你(阻塞到回应)。
102
+ - **自主多步推进** — 一次对话里连续多步:读代码、改代码、跑测试、根据报错再改……agent 自己决定下一步,中途不用你反复催。遇到决策点或关键修改会先调 `ask_human` 弹面板问你(阻塞到回应)。
103
103
  - **能力感知并发** — 连续且声明支持并行的工具(如读文件、grep、glob、联网读取)可并发执行。按资源加锁的文件改动也可同时派发,由规范化资源锁协调冲突资源,而不是把所有写入全局串行化。进程类及未声明并行能力的工具保持各自的串行执行约束。
104
104
  - **子 agent 分而治之** — 子任务拥有独立历史分支,工具权限不超过父 step 的能力上限;按并发上限分批运行,直接写入共享工作区并共用父级回滚轮次。主线接收最终摘要及执行元数据;没有每个 worker 独立的文件系统隔离或合并阶段。
105
105
  - **计划 / 执行双模式** — `plan` 模式下探查并产出计划,不修改项目文件、不跑 shell 命令、不派生子 agent;内部会话和计划记录仍可持久化。`auto` 模式允许执行,但不是静态“全工具”模式:每个真实用户轮先由轻量 LLM router 选择最小充分工具簇,主模型需要时可在后续 step 追加能力。
@@ -32,20 +32,29 @@ const CORE_SECTION = `Use your judgment to choose the shortest reliable path fro
32
32
  - Report honestly what you changed, what you checked, and anything left uncertain.
33
33
 
34
34
  Never invent file paths, APIs, config keys, flags, or behavior. Distinguish repository evidence from assumptions.`;
35
- /** ASK-01: only user-owned, high-impact choices should interrupt autonomous execution. */
35
+ /**
36
+ * ASK-02: user decisions and key modifications are the user's call, not the agent's.
37
+ * The agent must call `ask_human` BEFORE acting; only trivial, reversible details may be decided alone.
38
+ */
36
39
  const ASK_WHITELIST_SECTION = `## When to ask instead of guess
37
40
 
38
- Call \`ask_human\` before coding only when repository evidence cannot resolve a user-owned, high-impact choice:
39
- 1. irreversible deletion, migration, security, permission, or external side effect;
40
- 2. public API compatibility (keep, deprecate, rename, or remove);
41
- 3. multiple reasonable options that materially change product behavior;
42
- 4. the request itself admits two or more materially different readings that lead to different deliverables (do not silently pick one and guess).
41
+ 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
+
43
+ Ask BEFORE acting when any of these applies:
44
+ 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
+ 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.
46
+ 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).
47
+ 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.
48
+ 5. Evidence conflicts or gaps: repository evidence is missing, contradictory, or stale on something that changes the outcome.
49
+ 6. A failed approach: the same approach failed twice and the next step is a different approach, tool, or tradeoff than the user agreed to.
50
+
51
+ For ambiguous or vague requests, load the \`brainstorming\` skill and clarify through a short dialogue (one question at a time) before starting work. For a key modification, state what will change, why, and the impact in \`question\`/\`context\`, offer a confirm / adjust / cancel style choice, and make no related edits until the user answers.
43
52
 
44
- When the request is ambiguous, vague, or missing key information, first load the \`brainstorming\` skill and clarify the need through a short dialogue (one question at a time) before starting work.
53
+ 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.
45
54
 
46
- For naming and implementation details, follow repository precedent and choose the safest reversible default. Disclose any consequential assumption.
55
+ 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.
47
56
 
48
- Budget: during requirement clarification (the \`brainstorming\` workflow) ask as many questions as genuinely advance understanding; during execution after requirements are clear, use at most 2 \`ask_human\` calls per turn, then fall back to the safest reversible default and disclose it in the final reply.`;
57
+ 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.`;
49
58
  /** Advisory guidance shared by main and sub-agents. */
50
59
  export function buildWorkDisciplineSection(_modelFamily) {
51
60
  return `${CORE_SECTION}\n\n${ASK_WHITELIST_SECTION}`;
@@ -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; ask only when the choice is user-owned (see When to ask instead of guess).`;
147
+ - Disclose assumptions; decisions and key modifications belong to the user, so ask first (see When to ask instead of guess).`;
148
148
  /** 解析用户自定义声音:persona.md 文件优先(项目级 > 全局),其次 env MOCODE_PERSONA。无则返回 ''。 */
149
149
  function readPersonaFile() {
150
150
  const candidates = [
@@ -3,6 +3,7 @@ import { stdin } from 'node:process';
3
3
  import * as layout from '../ui/layout.js';
4
4
  import * as mouse from '../ui/mouse.js';
5
5
  import { promptComposer } from '../ui/composer.js';
6
+ import { ensurePasteDetector, pasteState } from '../ui/prompt-internal/paste.js';
6
7
  import { appendCurrentSessionRuntimeEvent } from '../session/index.js';
7
8
  import { getAgentMode } from '../agent/mode.js';
8
9
  const emitter = stdin;
@@ -16,6 +17,8 @@ let listening = false; // onRunningKey 是否处于挂载期(start → stop 之
16
17
  let queuedTurns = [];
17
18
  /** 运行态打开的输入面板(Ctrl+G);非 null = 面板仍开着。主循环进 INPUT 态前须等它关闭,否则两个 keypress 监听抢键。 */
18
19
  let composerPending = null;
20
+ /** 粘贴多行时 \r\n 合一:刚吃了 \r,尾随的 \n 需吞掉(与 INPUT 态编辑器一致)。 */
21
+ let pasteJustSawCR = false;
19
22
  /** 获取运行中输入缓冲(agent 结束后预填下一轮 INPUT 态)。 */
20
23
  export function getRunningInput() {
21
24
  return runningInput;
@@ -64,6 +67,12 @@ export function waitForRunningComposer() {
64
67
  function paint() {
65
68
  layout.paintRunningInput(runningInput.replace(/[\r\n]/g, ' '), runningCursor, runningPlaceholder);
66
69
  }
70
+ /** 在光标处插入文本(打字/粘贴),推进光标并重绘;换行保留在缓冲里(回显折空格),作为同一条内容。 */
71
+ function insertRunningText(text) {
72
+ runningInput = runningInput.slice(0, runningCursor) + text + runningInput.slice(runningCursor);
73
+ runningCursor += text.length;
74
+ paint();
75
+ }
67
76
  /**
68
77
  * Ctrl+G(运行态):打开输入面板编辑 typeahead 缓冲。
69
78
  * 期间摘掉 onRunningKey(面板自己挂 keypress),并标记 overlay——流式输出 / 状态行心跳 / spinner 帧只喂缓冲
@@ -145,6 +154,27 @@ function onRunningKey(_str, key) {
145
154
  }
146
155
  return;
147
156
  }
157
+ // 粘贴中(块级/时间窗检测,与 INPUT 态编辑器共用 pasteState):整段累积进 typeahead 缓冲,
158
+ // 换行作为多行文本插入而非触发 Enter 入队——否则粘贴一段含上百行的日志会被拆成上百条排队消息。
159
+ // \r\n 合一成单个 \n(尾随 \n 吞掉);可打印字符在光标处插入。粘贴结束(50ms 静默)后用户按 Enter 才整条入队。
160
+ if (pasteState.pasting) {
161
+ const s = key.sequence ?? '';
162
+ const isReturn = key.name === 'return' || key.name === 'enter';
163
+ if (s === '\n' && pasteJustSawCR) {
164
+ pasteJustSawCR = false;
165
+ return;
166
+ }
167
+ if (isReturn || s === '\r' || s === '\n') {
168
+ pasteJustSawCR = s === '\r';
169
+ insertRunningText('\n');
170
+ return;
171
+ }
172
+ pasteJustSawCR = false;
173
+ if (s && s >= ' ' && s !== '\uFEFF' && !key.ctrl && !key.meta)
174
+ insertRunningText(s);
175
+ return;
176
+ }
177
+ pasteJustSawCR = false;
148
178
  // Ctrl+G:打开输入面板(与 INPUT 态一致;确认只填回 typeahead 缓冲,agent 结束后预填,不发送)
149
179
  if (key.ctrl && key.name === 'g') {
150
180
  if (!composerPending) {
@@ -222,9 +252,7 @@ function onRunningKey(_str, key) {
222
252
  }
223
253
  // 可打印字符(>= 空格,非 ctrl/meta)→ 光标处插入 + 非 dim 回显(与空闲态一致)
224
254
  if (s && s >= ' ' && !key.ctrl && !key.meta) {
225
- runningInput = runningInput.slice(0, runningCursor) + s + runningInput.slice(runningCursor);
226
- runningCursor += s.length;
227
- paint();
255
+ insertRunningText(s);
228
256
  }
229
257
  }
230
258
  /** 鼠标右键单击输入框(未拖动)时 layout 读剪贴板后回调:在光标处插入 typeahead 缓冲(单行,换行折为空格)。 */
@@ -239,6 +267,15 @@ export function startRunningListener(placeholder) {
239
267
  runningPlaceholder = placeholder;
240
268
  runningInput = '';
241
269
  runningCursor = 0;
270
+ pasteJustSawCR = false;
271
+ // 粘贴检测(块级/时间窗)是 INPUT 态编辑器同款、全局幂等:运行态也装上,使多行/大段粘贴
272
+ // 在 onRunningKey 的 pasting 分支整段进 typeahead,而不是被换行拆成多条排队消息。
273
+ ensurePasteDetector();
274
+ if (pasteState.pasteTimer)
275
+ clearTimeout(pasteState.pasteTimer);
276
+ pasteState.pasting = false;
277
+ pasteState.pasteParts = [];
278
+ pasteState.onPasteEnd = null; // 运行态直接实时累积进 runningInput,不用编辑器的落 chip 回调
242
279
  emitKeypressEvents(stdin); // 幂等:首轮 prompt 已永久挂解析器,这里防御性再调
243
280
  try {
244
281
  stdin.setRawMode(true);
@@ -72,7 +72,7 @@ const BRAINSTORM_BODY = `# Brainstorming(需求澄清)
72
72
 
73
73
  ## 边界
74
74
 
75
- - 澄清期 ask_human 不计入「执行阶段每轮最多 2 次」的预算,但每个问题必须实质推进理解;用户不耐烦或说「你决定」时,取最安全的可逆默认并说明。
75
+ - ask_human 没有次数上限,但每个问题必须实质推进理解、相关问题合并提问;用户明确说「你决定」时,取最安全的可逆默认并说明。
76
76
  - 用户取消:停止,不要按自己的猜测继续。
77
77
  - 问题与方案用用户的语言。
78
78
  - 澄清期间保持只读:不改文件、不跑有副作用的命令。
@@ -113,7 +113,8 @@ export const askHumanTool = {
113
113
  'Ask the user a question and wait for their response.',
114
114
  ' CHOICES: pass 2-4 concrete options via `options`, each as { label, description? }; every non-empty option requires a non-empty `label`.',
115
115
  ' FREE-TEXT: pass `options: []` when the answer cannot be reduced to choices (e.g. "paste the error message").',
116
- ' DO NOT call when the task is clear and a sensible default exists.',
116
+ ' MUST call BEFORE any decision the user has not made (multiple reasonable approaches) or any key modification (public API, schema, dependencies, file moves/deletes, architecture, security, large or irreversible changes); never decide these yourself.',
117
+ ' Skip only for trivial details that follow repository precedent and are easily reversible.',
117
118
  ].join(' '),
118
119
  parameters: {
119
120
  type: 'object',
@@ -1,23 +1,3 @@
1
- /**
2
- * 内容物理行缓冲(Phase 2 滚动回滚用)。
3
- *
4
- * 存折行后的物理行,每行自洽带色,供 layout.repaintViewport 单行直出、无需继承 SGR 状态。
5
- * contentWrite 逐字符喂入(feedChar / feedSgr / breakRow);setLines 替换当前段(md 流式渲染用)。
6
- * markdown 段额外保留未折行 source,终端列宽变化时可重新渲染对应物理行;普通行仍沿用原模型。
7
- *
8
- * **SGR 自洽模型**:每行存 `rowStartSgr + curRaw + \x1B[0m`:
9
- * - rowStartSgr:本行起始时继承的活跃 SGR 前缀(来自上一行末状态);
10
- * - curRaw:本行原始字节——可见字符 + 行内出现的 SGR 码(保留行内开合,如 `${dim}ab${reset}cd`);
11
- * - 末尾 reset:使单行渲染不依赖后续。
12
- * 这样行内 SGR 变化与跨行继承都正确——简单"前缀+可见文本"模型会丢行内开合的色。
13
- *
14
- * **当前行**:任何 feedChar/feedSgr/breakRow 后 hasCurrent=true;breakRow(\n/折行)提交本行并开新空行
15
- * (hasCurrent 仍 true,代表光标所在的新空行)。这让 offset=0 的 viewport 重画与实时屏严格一致
16
- * (含 \n 后的光标空行),避免回尾时内容错位。
17
- *
18
- * 主题(theme.ts)只用单参数 SGR 码,故 curSgr 状态机简单:遇 \x1B[0m / \x1B[m 清空,其余累加。
19
- * 上限 20000 行防无限增长(超限丢头部,批量 trim)。
20
- */
21
1
  const MAX_ROWS = 20000;
22
2
  let rows = [];
23
3
  let curSgr = ''; // 当前活跃 SGR 状态(行内演进;行末值 = 下行继承值)
@@ -165,7 +145,7 @@ export function beginSegment() {
165
145
  * 行须各自自洽(行内 SGR 自带、行末 reset)——不经 feedChar/feedSgr,直接入 rows,
166
146
  * 故 setLines 后 hasCurrent=false(snapshot 只返 rows;续写位由 layout 跟踪)。
167
147
  */
168
- export function setLines(lines, source) {
148
+ export function setLines(lines, source, codeBlocks) {
169
149
  if (segMark) {
170
150
  rows.length = segMark.rowIdx;
171
151
  }
@@ -179,6 +159,7 @@ export function setLines(lines, source) {
179
159
  segment.rowCount = lines.length;
180
160
  if (source !== undefined)
181
161
  segment.source = source;
162
+ segment.codeBlocks = codeBlocks;
182
163
  }
183
164
  }
184
165
  trimRows();
@@ -202,7 +183,9 @@ export function reflowMarkdown(cols, render) {
202
183
  const start = Math.max(0, Math.min(rows.length, segment.start));
203
184
  const oldCount = Math.max(0, Math.min(segment.rowCount, rows.length - start));
204
185
  const oldLines = rows.slice(start, start + oldCount);
205
- const next = render(segment.source, width);
186
+ const rendered = render(segment.source, width);
187
+ const next = Array.isArray(rendered) ? rendered : rendered.lines;
188
+ segment.codeBlocks = Array.isArray(rendered) ? [] : rendered.codeBlocks;
206
189
  rows.splice(start, oldCount, ...next);
207
190
  const delta = next.length - oldCount;
208
191
  segment.start = start;
@@ -308,6 +291,26 @@ export function lineAt(abs) {
308
291
  const all = snapshot();
309
292
  return abs >= 0 && abs < all.length ? all[abs] : null;
310
293
  }
294
+ /** 命中某个代码块的复制按钮时返回其原文、header 绝对行与按钮显示列区间,否则 null。col 为 0-based 显示列。 */
295
+ export function codeBlockCopyAt(absLine, col) {
296
+ for (const segment of reflowSegments) {
297
+ const rel = absLine - segment.start;
298
+ for (const block of segment.codeBlocks ?? []) {
299
+ if (rel === block.headerLine &&
300
+ block.buttonColStart >= 0 &&
301
+ col >= block.buttonColStart &&
302
+ col < block.buttonColEnd) {
303
+ return {
304
+ code: block.code,
305
+ headerAbs: segment.start + block.headerLine,
306
+ colStart: block.buttonColStart,
307
+ colEnd: block.buttonColEnd,
308
+ };
309
+ }
310
+ }
311
+ }
312
+ return null;
313
+ }
311
314
  /** 等长替换一条已提交物理行,供运行中的工具 batch 原地刷新摘要。 */
312
315
  export function replaceLine(abs, line) {
313
316
  if (abs < 0 || abs >= rows.length)
@@ -5,7 +5,7 @@ import { charWidth, truncateAnsi, ansiDisplayWidth, remapWrappedPoint } from '..
5
5
  import { ui } from '../theme.js';
6
6
  import * as content from '../content.js';
7
7
  import { reset as resetBatches, shiftBatchesAfter, shiftBatchesForReflow } from '../batch.js';
8
- import { renderMarkdown } from '../markdown.js';
8
+ import { renderMarkdownWithMeta } from '../markdown.js';
9
9
  import { state } from './state.js';
10
10
  import { esc, cup, getGeo, setRegion, runningCaretPos } from './screen.js';
11
11
  import { viewportAbsStart, repaintViewport } from './scroll.js';
@@ -304,8 +304,8 @@ function renderMdSegment() {
304
304
  // offset += delta(可负:setLines 重渲染可能缩行)冻住视图。md 段在尾,窗口在上方,冻结后不重叠。
305
305
  const scrolled = state.scrollOffset > 0;
306
306
  const totalBefore = scrolled ? content.totalRows() : 0;
307
- const lines = renderMarkdown(state.mdBuf, g.cols);
308
- content.setLines(lines, state.mdBuf);
307
+ const { lines, codeBlocks } = renderMarkdownWithMeta(state.mdBuf, g.cols);
308
+ content.setLines(lines, state.mdBuf, codeBlocks);
309
309
  state.mdRenderedLen = state.mdBuf.length;
310
310
  const segRows = lines.length;
311
311
  const available = g.contentBottom - state.segmentStartRow + 1;
@@ -410,8 +410,8 @@ export function contentWriteMdOnce(s) {
410
410
  commitMd();
411
411
  const g = getGeo();
412
412
  content.beginSegment();
413
- const lines = renderMarkdown(s, g.cols);
414
- content.setLines(lines, s);
413
+ const { lines, codeBlocks } = renderMarkdownWithMeta(s, g.cols);
414
+ content.setLines(lines, s, codeBlocks);
415
415
  content.commitSegment();
416
416
  // setLines 直接提交了全部 markdown 物理行;补回一个未提交的空当前行,保证满屏时
417
417
  // 下一次 contentWrite 从正文下一行开始,而不是在 contentBottom 第 1 列覆盖正文末行。
@@ -821,7 +821,7 @@ export function reflowContentForResize(cols, colsChanged) {
821
821
  const welcomeChange = reflowWelcomeBlockForResize(cols);
822
822
  if (welcomeChange)
823
823
  changes.push(welcomeChange);
824
- changes.push(...content.reflowMarkdown(cols, renderMarkdown));
824
+ changes.push(...content.reflowMarkdown(cols, renderMarkdownWithMeta));
825
825
  }
826
826
  for (const change of changes) {
827
827
  shiftBatchesForReflow(change.start, change.oldCount, change.newCount);
@@ -356,8 +356,33 @@ function handleMouseEvent(e) {
356
356
  // 内容区纯点击(未拖动):若落在工具 batch 摘要行上 → 切换展开/折叠;
357
357
  // 否则原行为:清选区。batch 反查通过 content lineAt + dynamic import(避免 layout↔batch 循环依赖)。
358
358
  const absClick = state.selection.anchorLine; // 起止同行同列,取任一;未拖动时 line = anchor = end
359
+ const colClick = state.selection.anchorCol;
359
360
  void (async () => {
360
361
  try {
362
+ // 代码块复制按钮:命中 header 右侧「复制」即把代码原文写剪贴板(优先于选区/batch 展开)。
363
+ const copyHit = content.codeBlockCopyAt(absClick, colClick);
364
+ if (copyHit) {
365
+ state.selection = null;
366
+ copyToClipboard(copyHit.code);
367
+ // 按钮瞬时反白反馈 900ms(纯视觉覆盖,不改缓冲,不依赖剪贴板成败回执)。
368
+ const flash = {
369
+ absLine: copyHit.headerAbs,
370
+ colStart: copyHit.colStart,
371
+ colEnd: copyHit.colEnd,
372
+ until: Date.now() + 900,
373
+ };
374
+ state.copyFlash = flash;
375
+ repaintViewport();
376
+ setTimeout(() => {
377
+ // 连点时只清自己那次闪烁,不误清后一次。
378
+ if (state.copyFlash !== flash)
379
+ return;
380
+ state.copyFlash = null;
381
+ repaintViewport();
382
+ }, 900).unref?.();
383
+ repaint();
384
+ return;
385
+ }
361
386
  const m = await import('../batch.js');
362
387
  const entry = m.findEntryByAbsLine(absClick);
363
388
  if (entry) {
@@ -118,6 +118,14 @@ export function repaintViewport() {
118
118
  line = highlightRange(line, colStart, colEnd);
119
119
  }
120
120
  }
121
+ // 代码块「复制」按钮点击反馈:超时则清除(纯视觉,不改缓冲)。复用选区反白样式。
122
+ if (state.copyFlash) {
123
+ if (Date.now() >= state.copyFlash.until)
124
+ state.copyFlash = null;
125
+ else if (state.copyFlash.absLine === absStart + r - 1) {
126
+ line = highlightRange(line, state.copyFlash.colStart, state.copyFlash.colEnd);
127
+ }
128
+ }
121
129
  p += cup(r, 1) + esc.clearLine + line;
122
130
  }
123
131
  // 光标:合并进同一 write(若拆成两次 stdout.write,行写完光标会暂留 contentRow/contentBottom,
@@ -70,7 +70,8 @@ export function extractSelectionText(sel) {
70
70
  const lineW = displayWidth(plain);
71
71
  const colStart = abs === sel.startLine ? sel.startCol : 0;
72
72
  const colEnd = abs === sel.endLine ? sel.endCol : lineW;
73
- out.push(sliceByDisplayCol(plain, colStart, colEnd));
73
+ // 去行尾空白:代码块整块铺底色时每行补满到列宽,不剥会把补位空格一起复制出去。
74
+ out.push(sliceByDisplayCol(plain, colStart, colEnd).trimEnd());
74
75
  }
75
76
  return out.join('\n');
76
77
  }
@@ -106,4 +106,6 @@ export const state = {
106
106
  /** 覆盖层自报的真光标位(1-based 屏坐标;null = 未报/光标不在可视区)。overlay 期间 drawStatusBar
107
107
  * 照常刷底栏,但末尾 cup 回这里而非 runningCaretPos,防 80ms 心跳把弹窗光标拽到底栏输入框。 */
108
108
  overlayCaret: null,
109
+ // ── 代码块「复制」按钮点击反馈(瞬时反白,不改缓冲;超时后随下次 repaintViewport 自然消失) ──
110
+ copyFlash: null,
109
111
  };
@@ -406,10 +406,14 @@ const MEMO = new Map();
406
406
  const MEMO_CAP = 16;
407
407
  function renderMarkdownImpl(text, cols) {
408
408
  const out = [];
409
- const src = text.split('\n');
409
+ const codeBlocks = [];
410
+ const src = text.split(/\r?\n/); // 兼容 CRLF:否则行尾 \r 让 fence 正则失配、整块不识别
410
411
  let i = 0;
411
412
  let inFence = false;
412
413
  let fenceChar = '';
414
+ let fenceLen = 0; // 开栏围栏长度:闭合栏须 ≥ 此长度(CommonMark),4 反引号外层可安全包住 3 反引号示例
415
+ let fenceDepth = 0; // 同长度带语言标注的嵌套开栏深度(3 反引号外层包 ```ts 示例的常见写法)
416
+ let fenceIndent = 0; // 开栏缩进(列表项内的围栏):复制原文时按 CommonMark 剥掉这层缩进
413
417
  let lang = '';
414
418
  let codeBuf = [];
415
419
  let para = [];
@@ -425,17 +429,61 @@ function renderMarkdownImpl(text, cols) {
425
429
  para = [];
426
430
  prevBlank = true;
427
431
  };
432
+ // 代码块整块铺 codeBg 底色(header + 代码行补满到 cols),与正文区分出「可复制区」。
433
+ // 非 TTY(codeBg 为空串)退化为无底色、不补尾随空格。文本内的 reset 之后重开底色,防高亮 SGR 打断。
434
+ const paintCodeRow = (text) => {
435
+ const bg = ui.codeBg;
436
+ const body = clipAnsiLine(text, cols);
437
+ if (!bg)
438
+ return body;
439
+ const pad = Math.max(0, cols - ansiDisplayWidth(body));
440
+ return `${bg}${body.split(RESET).join(RESET + bg)}${' '.repeat(pad)}${RESET}`;
441
+ };
442
+ // header 行:左侧 dim 语言标签(始终保留这行以承载按钮),右端 accent 复制图标 ` ❐ `(两侧各留 1 格扩大点击面)。
443
+ // 窄窗放不下按钮时只画标签,buttonCol=-1 表示不可点。
444
+ const COPY_BTN = ' \u2750 ';
445
+ const buildHeader = (language) => {
446
+ const btnW = displayWidth(COPY_BTN);
447
+ const left = language ? ` ${ui.dim}${language}${ui.reset}` : ' ';
448
+ const leftW = 2 + displayWidth(language); // ' ' gutter + 语言名
449
+ const spaces = cols - leftW - btnW;
450
+ if (spaces < 0)
451
+ return { line: paintCodeRow(left), colStart: -1, colEnd: -1 };
452
+ const colStart = leftW + spaces;
453
+ return {
454
+ line: paintCodeRow(`${left}${' '.repeat(spaces)}${ui.accent}${COPY_BTN}${ui.reset}`),
455
+ colStart,
456
+ colEnd: colStart + btnW,
457
+ };
458
+ };
428
459
  const flushCode = () => {
429
- if (lang)
430
- out.push(` ${ui.dim}${lang}${ui.reset}`);
431
- const highlighted = highlightCodeBlock(codeBuf.join('\n'), lang);
460
+ const strip = fenceIndent > 0 ? new RegExp(`^[ \\t]{0,${fenceIndent}}`) : null;
461
+ const code = (strip ? codeBuf.map((l) => l.replace(strip, '')) : codeBuf).join('\n');
462
+ const headerLine = out.length;
463
+ const header = buildHeader(lang);
464
+ out.push(header.line);
465
+ const codeStartLine = out.length;
466
+ const highlighted = highlightCodeBlock(code, lang);
432
467
  const codeW = Math.max(1, cols - 2);
433
468
  for (const l of wrapAnsiString(highlighted, codeW)) {
434
- out.push(clipAnsiLine(` ${l}`, cols));
469
+ out.push(paintCodeRow(` ${l}`));
435
470
  }
471
+ const codeEndLine = out.length - 1;
472
+ codeBlocks.push({
473
+ headerLine,
474
+ codeStartLine,
475
+ codeEndLine,
476
+ buttonColStart: header.colStart,
477
+ buttonColEnd: header.colEnd,
478
+ lang,
479
+ code,
480
+ });
436
481
  out.push('');
437
482
  inFence = false;
438
483
  fenceChar = '';
484
+ fenceLen = 0;
485
+ fenceDepth = 0;
486
+ fenceIndent = 0;
439
487
  lang = '';
440
488
  codeBuf = [];
441
489
  prevBlank = true;
@@ -446,7 +494,7 @@ function renderMarkdownImpl(text, cols) {
446
494
  // 若不恢复,后续所有标题、列表和下一段代码都会被吞进首个代码块,最终显示成截图里的原始
447
495
  // `##` / ```。只接受“独占一行、恰好两个同类字符”,避免误伤代码中的行内双反引号。
448
496
  const shortClose = inFence ? line.match(/^\s*(`{2}|~{2})\s*$/) : null;
449
- if (shortClose && shortClose[1][0] === fenceChar) {
497
+ if (shortClose && shortClose[1][0] === fenceChar && fenceDepth === 0) {
450
498
  flushCode();
451
499
  i++;
452
500
  continue;
@@ -458,11 +506,25 @@ function renderMarkdownImpl(text, cols) {
458
506
  flushPara();
459
507
  inFence = true;
460
508
  fenceChar = fm[2][0];
509
+ fenceLen = fm[2].length;
510
+ fenceDepth = 0;
511
+ fenceIndent = fm[1].length;
461
512
  lang = fm[3].trim();
462
513
  codeBuf = [];
463
514
  }
464
- else if (fm[2][0] === fenceChar) {
465
- flushCode();
515
+ else if (fm[2][0] === fenceChar && fm[2].length >= fenceLen) {
516
+ if (fm[3].trim()) {
517
+ // 带语言标注的同类围栏不是闭合栏(CommonMark),按嵌套开栏计深度,其配对的裸栏不会提前截断外层块。
518
+ fenceDepth++;
519
+ codeBuf.push(line);
520
+ }
521
+ else if (fenceDepth > 0) {
522
+ fenceDepth--;
523
+ codeBuf.push(line);
524
+ }
525
+ else {
526
+ flushCode();
527
+ }
466
528
  }
467
529
  else {
468
530
  codeBuf.push(line);
@@ -587,15 +649,29 @@ function renderMarkdownImpl(text, cols) {
587
649
  // "\n\n" 与首段正文拆成不同 chunk;仅清洗首个正文 chunk 不够,因为 mdBuf
588
650
  // 累积重渲染时这些换行仍会变成段首空行。这里最终兜底,正文段永不自带前导空行。
589
651
  const isVisualBlank = (line) => stripAnsi(line).trim().length === 0;
590
- while (out.length > 0 && isVisualBlank(out[0]))
652
+ let headShift = 0;
653
+ while (out.length > 0 && isVisualBlank(out[0])) {
591
654
  out.shift();
655
+ headShift++;
656
+ }
592
657
  // 末尾不留空行:agent onText 后接 onToolCall 的 contentWrite('\n') 会补 1 空行分隔正文与 ● 行;
593
658
  // 若 md 末尾自带空行(段落/代码块后)则叠成 2 空行。裁掉末尾连续空行,让 onToolCall / 轮末
594
659
  // contentWrite('\n') 恰好补 1 行(与改造前 raw 文本行为一致)。块间空行(flushPara/flushCode 中段
595
660
  // push 的)不受影响——只裁末尾。
596
661
  while (out.length > 0 && isVisualBlank(out[out.length - 1]))
597
662
  out.pop();
598
- return out;
663
+ // 前导空行被 shift:同步平移仍在输出区内的代码块相对行(被整体裁掉的块丢弃)。
664
+ const blocks = headShift
665
+ ? codeBlocks
666
+ .map((b) => ({
667
+ ...b,
668
+ headerLine: b.headerLine - headShift,
669
+ codeStartLine: b.codeStartLine - headShift,
670
+ codeEndLine: b.codeEndLine - headShift,
671
+ }))
672
+ .filter((b) => b.codeEndLine >= 0)
673
+ : codeBlocks;
674
+ return { lines: out, codeBlocks: blocks };
599
675
  }
600
676
  /**
601
677
  * 把 markdown 文本渲染成 ANSI 物理行数组(每行 ansiDisplayWidth ≤ cols,自洽带色)。
@@ -603,20 +679,24 @@ function renderMarkdownImpl(text, cols) {
603
679
  * 命中(MRU 提升),cols 变(resize)或切主题(themeVersion 变)则重算覆写。供 layout.contentWriteMd
604
680
  * 每 chunk 调用(memo 使重复渲染命中缓存)。themeVersion 使 setTheme 后全量重绘不命中旧主题缓存行。
605
681
  */
606
- export function renderMarkdown(text, cols) {
682
+ export function renderMarkdownWithMeta(text, cols) {
607
683
  const hit = MEMO.get(text);
608
684
  if (hit && hit.cols === cols && hit.themeVersion === getThemeVersion()) {
609
685
  MEMO.delete(text);
610
686
  MEMO.set(text, hit); // MRU 提升
611
- return hit.lines;
687
+ return { lines: hit.lines, codeBlocks: hit.codeBlocks };
612
688
  }
613
- const lines = renderMarkdownImpl(text, cols);
689
+ const { lines, codeBlocks } = renderMarkdownImpl(text, cols);
614
690
  if (MEMO.has(text))
615
691
  MEMO.delete(text);
616
692
  else if (MEMO.size >= MEMO_CAP)
617
693
  MEMO.delete(MEMO.keys().next().value);
618
- MEMO.set(text, { cols, lines, themeVersion: getThemeVersion() });
619
- return lines;
694
+ MEMO.set(text, { cols, lines, codeBlocks, themeVersion: getThemeVersion() });
695
+ return { lines, codeBlocks };
696
+ }
697
+ /** 只取物理行(向后兼容 reflow / 测试);代码块定位信息见 renderMarkdownWithMeta。 */
698
+ export function renderMarkdown(text, cols) {
699
+ return renderMarkdownWithMeta(text, cols).lines;
620
700
  }
621
701
  // 供 check 脚本 / 单元验证用(不进 layout 运行时路径)。
622
702
  export const __test = { clipAnsiLine, renderInline, wrapAnsiString, segsToAnsi };
package/dist/ui/theme.js CHANGED
@@ -34,6 +34,7 @@ const DEFAULT = {
34
34
  // diff 行底色:One Dark bg #282c34 上加 ~14% 亮度的对应色,够辨识但不刺眼
35
35
  addBg: '\x1B[48;2;44;62;42m', // 偏暗绿(One Dark green(152,195,121)暗化)
36
36
  delBg: '\x1B[48;2;62;38;42m', // 偏暗红(One Dark red(224,108,117)暗化)
37
+ codeBg: '\x1B[48;2;50;56;68m', // One Dark bg(40,44,52)上提亮一档的冷灰蓝;纯黑终端上同样可辨
37
38
  };
38
39
  /**
39
40
  * 内建主题表。default=One Dark、light=Solarized Light、solarized=Solarized Dark、
@@ -60,6 +61,7 @@ const THEMES = {
60
61
  // 比直接用 base1 更柔,跟深 fg(red/green)对比充足
61
62
  addBg: '\x1B[48;2;220;235;205m',
62
63
  delBg: '\x1B[48;2;245;218;215m',
64
+ codeBg: '\x1B[48;2;238;232;213m', // Solarized base2:浅米底上的代码块
63
65
  },
64
66
  solarized: {
65
67
  red: '\x1B[38;2;220;50;47m',
@@ -77,6 +79,7 @@ const THEMES = {
77
79
  // diff 行底色:Solarized Dark base03(0,43,54)上加对应色族暗 tint
78
80
  addBg: '\x1B[48;2;20;50;38m',
79
81
  delBg: '\x1B[48;2;55;30;30m',
82
+ codeBg: '\x1B[48;2;7;54;66m', // Solarized base02
80
83
  },
81
84
  gruvbox: {
82
85
  red: '\x1B[38;2;251;73;52m',
@@ -94,6 +97,7 @@ const THEMES = {
94
97
  // diff 行底色:Gruvbox dark bg(40,40,40)上贴暗 bg0_a 风格
95
98
  addBg: '\x1B[48;2;40;55;30m',
96
99
  delBg: '\x1B[48;2;70;35;30m',
100
+ codeBg: '\x1B[48;2;60;56;54m', // Gruvbox bg1
97
101
  },
98
102
  nord: {
99
103
  red: '\x1B[38;2;191;97;106m',
@@ -111,6 +115,7 @@ const THEMES = {
111
115
  // diff 行底色:Nord polar night(46,52,64)上贴对应色族暗 tint
112
116
  addBg: '\x1B[48;2;46;66;52m',
113
117
  delBg: '\x1B[48;2;72;46;52m',
118
+ codeBg: '\x1B[48;2;59;66;82m', // Nord polar night nord1
114
119
  },
115
120
  orange: {
116
121
  // 秋季/南瓜橙:深暖底(#231c16 系)+ accent 主强调走橙色;yellow 槽也偏橙
@@ -131,6 +136,7 @@ const THEMES = {
131
136
  // diff 行底色:暖深棕底上贴对应色族暗 tint,跟 fg 配对柔和可辨
132
137
  addBg: '\x1B[48;2;55;70;35m',
133
138
  delBg: '\x1B[48;2;78;42;32m',
139
+ codeBg: '\x1B[48;2;58;46;36m',
134
140
  },
135
141
  rose: {
136
142
  // 玫红:深紫底 + accent 玫粉作主强调;magenta 槽与 accent 同源(主题色),
@@ -150,6 +156,7 @@ const THEMES = {
150
156
  // diff 行底色:深紫底贴对应色族暗 tint,绿暗化偏橄榄、红暗化偏紫红
151
157
  addBg: '\x1B[48;2;50;60;42m',
152
158
  delBg: '\x1B[48;2;75;40;52m',
159
+ codeBg: '\x1B[48;2;56;42;54m',
153
160
  },
154
161
  emerald: {
155
162
  // 翡翠绿:深绿底 + accent 翡翠绿作主强调;green 槽与 accent 同源(主题色),
@@ -169,6 +176,7 @@ const THEMES = {
169
176
  // diff 行底色:深绿底贴对应色族暗 tint,绿暗化偏深绿、红暗化偏暗红
170
177
  addBg: '\x1B[48;2;30;55;40m',
171
178
  delBg: '\x1B[48;2;60;40;40m',
179
+ codeBg: '\x1B[48;2;34;56;50m',
172
180
  },
173
181
  amber: {
174
182
  // 琥珀金黄:深棕底 + accent 琥珀金黄作主强调;yellow 槽与 accent 同源(主题色),
@@ -188,6 +196,7 @@ const THEMES = {
188
196
  // diff 行底色:深棕底贴对应色族暗 tint,绿暗化偏橄榄、红暗化偏暗棕红
189
197
  addBg: '\x1B[48;2;50;55;25m',
190
198
  delBg: '\x1B[48;2;70;40;28m',
199
+ codeBg: '\x1B[48;2;60;48;32m',
191
200
  },
192
201
  lavender: {
193
202
  // 薰衣草淡紫:深紫底 + accent 淡紫作主强调;magenta 槽与 accent 同源(主题色),
@@ -207,6 +216,7 @@ const THEMES = {
207
216
  // diff 行底色:深紫底贴对应色族暗 tint,绿暗化偏冷绿、红暗化偏冷紫红
208
217
  addBg: '\x1B[48;2;38;46;42m',
209
218
  delBg: '\x1B[48;2;60;40;55m',
219
+ codeBg: '\x1B[48;2;50;44;70m',
210
220
  },
211
221
  sunset: {
212
222
  // 日落珊瑚:深棕红底 + accent 珊瑚红作主强调;red 槽与 accent 同源(主题色);
@@ -226,6 +236,7 @@ const THEMES = {
226
236
  // diff 行底色:深棕红底贴对应色族暗 tint,绿暗化偏橄榄、红暗化偏暗棕红
227
237
  addBg: '\x1B[48;2;50;55;30m',
228
238
  delBg: '\x1B[48;2;75;32;30m',
239
+ codeBg: '\x1B[48;2;62;42;40m',
229
240
  },
230
241
  };
231
242
  let currentName = 'default';
@@ -320,4 +331,7 @@ export const ui = {
320
331
  get delBg() {
321
332
  return color('delBg');
322
333
  },
334
+ get codeBg() {
335
+ return color('codeBg');
336
+ },
323
337
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mocode-ai",
3
- "version": "1.8.2",
3
+ "version": "1.8.4",
4
4
  "description": "终端编码 agent:LLM + tool-call 循环 + 流式输出(含思考)+ 27 个工具,接任意 OpenAI 兼容后端。",
5
5
  "type": "module",
6
6
  "bin": {