mocode-ai 1.8.8 → 1.8.10

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 (61) hide show
  1. package/dist/agent/index.js +17 -17
  2. package/dist/agent/model-turn.js +8 -4
  3. package/dist/agent/run-coordinator.js +6 -0
  4. package/dist/agent/spawn.js +8 -4
  5. package/dist/agent/stages/tool-dispatcher.js +31 -11
  6. package/dist/changeset/hash.js +17 -0
  7. package/dist/changeset/index.js +6 -10
  8. package/dist/config/index.js +6 -1
  9. package/dist/context/text-search.js +28 -10
  10. package/dist/flows/cli.js +1 -1
  11. package/dist/flows/flow.js +1 -1
  12. package/dist/flows/trace.js +1 -1
  13. package/dist/headless.js +23 -0
  14. package/dist/index.js +1 -1
  15. package/dist/memory/anchor.js +319 -0
  16. package/dist/memory/audit.js +65 -0
  17. package/dist/memory/episodic.js +546 -0
  18. package/dist/memory/graph.js +233 -9
  19. package/dist/memory/health.js +208 -0
  20. package/dist/memory/index.js +12 -3
  21. package/dist/memory/pending.js +269 -0
  22. package/dist/memory/portable.js +150 -0
  23. package/dist/memory/proactive.js +588 -0
  24. package/dist/memory/recall-stats.js +1 -1
  25. package/dist/memory/reflect.js +260 -6
  26. package/dist/memory/relation-vocab.js +26 -4
  27. package/dist/memory/store.js +587 -41
  28. package/dist/memory/tail.js +88 -0
  29. package/dist/memory/write-gate.js +44 -0
  30. package/dist/permissions/computer-review.js +1 -1
  31. package/dist/permissions/flow-review.js +1 -1
  32. package/dist/repl/commands/flow.js +1 -1
  33. package/dist/repl/commands/memory.js +257 -6
  34. package/dist/repl/commands/session.js +13 -0
  35. package/dist/repl/commands/tool-group.js +6 -0
  36. package/dist/repl/episode-finalize.js +55 -0
  37. package/dist/repl/running-input.js +1 -1
  38. package/dist/repl/runtime.js +41 -3
  39. package/dist/runtime/uia-selector.js +1 -1
  40. package/dist/runtime/uia-service.js +3 -3
  41. package/dist/runtime/wait-until.js +1 -1
  42. package/dist/runtime/window-list.js +1 -1
  43. package/dist/sandbox/policy.js +49 -0
  44. package/dist/session/compact.js +47 -12
  45. package/dist/session/gui-actions.js +1 -1
  46. package/dist/tools/builtins/computer.js +5 -5
  47. package/dist/tools/builtins/memory-graph.js +12 -1
  48. package/dist/tools/builtins/memory-list.js +13 -3
  49. package/dist/tools/builtins/memory-save.js +82 -2
  50. package/dist/tools/builtins/memory-search.js +57 -2
  51. package/dist/tools/builtins/memory-update.js +52 -1
  52. package/dist/tools/builtins/read-file.js +51 -2
  53. package/dist/tools/builtins/run-flow.js +1 -1
  54. package/dist/tools/constants.js +60 -0
  55. package/dist/ui/intervention.js +38 -2
  56. package/dist/ui/layout-internal/core.js +8 -2
  57. package/dist/ui/layout-internal/input-paint.js +15 -7
  58. package/dist/ui/layout-internal/screen.js +9 -0
  59. package/dist/ui/layout-internal/scroll.js +49 -11
  60. package/dist/ui/layout-internal/state.js +8 -0
  61. package/package.json +6 -1
@@ -1,4 +1,5 @@
1
- import { searchEntries } from '../../memory/store.js';
1
+ import { searchEntries, loadStalenessMap, } from '../../memory/store.js';
2
+ import { describeAnchorState, evaluateAnchors } from '../../memory/anchor.js';
2
3
  import { searchGraphFacts } from '../../memory/graph.js';
3
4
  import { recordRecallSearch } from '../../memory/recall-stats.js';
4
5
  // ---------- memory_search ----------
@@ -6,6 +7,37 @@ import { recordRecallSearch } from '../../memory/recall-stats.js';
6
7
  // (CJK 分词加权、边级相关度 + 一跳邻接,跨 global/project 两 scope)。命中条目即 bump
7
8
  // recallCount(遗忘衰减依据)。结果走 capToolResultForHistory 的放宽上限(同 use_skill)。
8
9
  const GRAPH_FACTS_LIMIT = 10;
10
+ /**
11
+ * R14:状态标记。**默认 active 且非失效时不输出任何东西**——绝大多数查询走默认
12
+ * `status:'active'`,那条路径必须零噪音,否则每条记忆都多一行前缀,白占上下文。
13
+ *
14
+ * R2:代码锚点失效走同一个位置但**分开措辞**。两种失效要模型做的事不一样:
15
+ * `STALE-DERIVED` 是「这条结论的根据没了」,`STALE-CODE` 是「结论可能仍对,但它描述的
16
+ * 那段代码/行号/细节要重新核对」——合并成一句会丢掉这个区别。
17
+ */
18
+ function statusMark(e, st, anchor) {
19
+ const parts = [];
20
+ if (e.status === 'superseded')
21
+ parts.push(`SUPERSEDED${e.supersededBy ? ` → ${e.supersededBy}` : ''}`);
22
+ else if (e.status === 'archived')
23
+ parts.push('ARCHIVED');
24
+ if (st?.stale) {
25
+ // 失效原因是给模型判断"还能不能用"的关键:源被取代(结论可能仍成立)
26
+ // 与源被删(根据没了)是两回事。
27
+ const why = [
28
+ st.inactive.length > 0 ? `源已失效: ${st.inactive.join(', ')}` : '',
29
+ st.missing.length > 0 ? `源已被删除: ${st.missing.join(', ')}` : '',
30
+ ]
31
+ .filter(Boolean)
32
+ .join('; ');
33
+ parts.push(`STALE-DERIVED${why ? ` (${why})` : ''}`);
34
+ }
35
+ if (anchor?.stale) {
36
+ const why = describeAnchorState(anchor);
37
+ parts.push(`STALE-CODE${why ? ` (${why})` : ''}`);
38
+ }
39
+ return parts.length > 0 ? ` [${parts.join(' | ')}]` : '';
40
+ }
9
41
  export const memorySearchTool = {
10
42
  name: 'memory_search',
11
43
  description: 'Search memory entries by keyword (substring match), returning full body. Also surfaces knowledge-graph facts (active edges across project + global), ranked by CJK-aware term overlap on entity names/aliases/relation/fact, plus one-hop neighbor edges for context.',
@@ -35,8 +67,31 @@ export const memorySearchTool = {
35
67
  status: typeof args.status === 'string' ? args.status : undefined,
36
68
  limit: typeof args.limit === 'number' ? args.limit : undefined,
37
69
  });
70
+ // R14:派生条目的失效判定要拿全库做源查找(源可能在另一 scope,也可能已被硬删),
71
+ // 不能在命中结果集内自洽判断。searchEntries 已 bump 过 recall,这里再 loadAll
72
+ // 拿到的是同一份(含脏集增量),不会引入不一致。
73
+ const staleInfo = r.length > 0 ? loadStalenessMap() : new Map();
74
+ // R2:锚点判定只针对**命中条目**,不走 loadAnchorStaleMap(那会扫全库并 stat 每个锚点)。
75
+ // 命中集通常 5 条,而且 readCached 有 mtime 缓存,成本可以忽略。
76
+ const anchorInfo = new Map();
77
+ for (const e of r) {
78
+ if (!e.anchors || e.anchors.length === 0)
79
+ continue;
80
+ anchorInfo.set(e.id, evaluateAnchors(e.anchors));
81
+ }
38
82
  const entryText = r
39
- .map((e) => `# [${e.id}] ${e.name} (${e.type}, recalled ${e.recallCount})\nsummary: ${e.summary}\n\n${e.body}`)
83
+ .map((e) => {
84
+ // R1.5:条件-动作字段放在最前面,它们是"要不要用上这条记忆"的判断依据;
85
+ // 只有存在时才输出,老条目无此字段不受影响。
86
+ const lead = [e.trigger ? `when: ${e.trigger}` : '', e.action ? `do: ${e.action}` : '']
87
+ .filter(Boolean)
88
+ .join('\n');
89
+ // R14:状态标记必须紧贴标题。模型是把整块结果当"现状"读的——一条已被取代的
90
+ // 条目混在 active 里,它不会自己去比对 updatedAt。实测 status='any' 时 archived
91
+ // 条目能占到前 4 名,不给标记就等于把过期事实当现状喂进去。
92
+ const mark = statusMark(e, staleInfo.get(e.id), anchorInfo.get(e.id));
93
+ return `# [${e.id}] ${e.name} (${e.type}, recalled ${e.recallCount})${mark}\nsummary: ${e.summary}\n${lead ? lead + '\n' : ''}\n${e.body}`;
94
+ })
40
95
  .join('\n\n---\n\n');
41
96
  // 知识图谱事实段:边级相关度检索(容错:图坏了不连累条目搜索)。
42
97
  let graphText = '';
@@ -1,4 +1,24 @@
1
1
  import { updateEntry } from '../../memory/store.js';
2
+ /**
3
+ * anchors 参数归一(同 memory_save):只取 path/symbol,hash 由 store 现算。
4
+ * 传空数组表示**清空**锚点,传 undefined 表示不动。
5
+ */
6
+ function parseAnchorInputs(raw) {
7
+ if (!Array.isArray(raw))
8
+ return [];
9
+ const out = [];
10
+ for (const item of raw) {
11
+ if (!item || typeof item !== 'object')
12
+ continue;
13
+ const a = item;
14
+ const p = typeof a.path === 'string' ? a.path.trim() : '';
15
+ if (!p)
16
+ continue;
17
+ const s = typeof a.symbol === 'string' ? a.symbol.trim() : '';
18
+ out.push({ path: p, ...(s ? { symbol: s } : {}) });
19
+ }
20
+ return out;
21
+ }
2
22
  // ---------- memory_update ----------
3
23
  // 原地改一条记忆(id 不变)。反思的弱意义:干活时发现事实变了/过时即纠正。
4
24
  export const memoryUpdateTool = {
@@ -14,6 +34,29 @@ export const memoryUpdateTool = {
14
34
  name: { type: 'string', description: 'New title (id does not change with name)' },
15
35
  pinned: { type: 'boolean', description: 'Toggle pin status (true pins and exempts decay / false unpins)' },
16
36
  reason: { type: 'string', description: 'Update reason (recorded in lastUpdateReason for traceability)' },
37
+ trigger: {
38
+ type: 'string',
39
+ description: 'R1.5 WHEN this memory applies. Use this to fill in a missing trigger after the situation actually recurred — that is the expected flow, do not invent a vague one up front. Pass "" to clear.',
40
+ },
41
+ action: {
42
+ type: 'string',
43
+ description: 'R1.5 WHAT to do when the trigger holds. Pass "" to clear.',
44
+ },
45
+ anchors: {
46
+ type: 'array',
47
+ description: 'R2 code anchors — REPLACES the whole set (pass [] to clear). Only paths/symbols; the content hash is recomputed at write time. Use this when the memory is about a specific file/function and you want a later edit to surface it as stale instead of silently serving an outdated fact.',
48
+ items: {
49
+ type: 'object',
50
+ properties: {
51
+ path: { type: 'string', description: 'Workspace-relative file path, e.g. "src/memory/store.ts"' },
52
+ symbol: {
53
+ type: 'string',
54
+ description: 'Optional function/class/const name; prefers a fragment over the whole file',
55
+ },
56
+ },
57
+ required: ['path'],
58
+ },
59
+ },
17
60
  },
18
61
  required: ['id'],
19
62
  },
@@ -32,8 +75,16 @@ export const memoryUpdateTool = {
32
75
  patch.reason = args.reason;
33
76
  if (typeof args.pinned === 'boolean')
34
77
  patch.pinned = args.pinned;
78
+ // trigger/action 无真值判断:空串是「清空」这个明确意图(见 updateEntry)。
79
+ if (typeof args.trigger === 'string')
80
+ patch.trigger = args.trigger;
81
+ if (typeof args.action === 'string')
82
+ patch.action = args.action;
83
+ // anchors 同理:空数组是「清空锚点」,不传才是「不动」。
84
+ if (args.anchors !== undefined)
85
+ patch.anchors = parseAnchorInputs(args.anchors);
35
86
  if (Object.keys(patch).length === 0)
36
- return '错误:至少传一个要改的字段(summary/body/name/pinned/reason)。';
87
+ return '错误:至少传一个要改的字段(summary/body/name/pinned/reason/trigger/action/anchors)。';
37
88
  const r = updateEntry(id, patch);
38
89
  if (r.ok)
39
90
  return `已更新记忆 [${id}]。`;
@@ -1,9 +1,11 @@
1
1
  import { readFile, stat } from 'node:fs/promises';
2
2
  import { resolve } from 'node:path';
3
3
  import { contentHash } from '../../changeset/index.js';
4
+ import { entriesAnchoredTo } from '../../memory/store.js';
5
+ import { evaluateAnchorsAgainst, toAnchorPath } from '../../memory/anchor.js';
4
6
  import { IMAGE_READ_MARKER, MAX_FILE_LINES, MAX_HISTORY_RESULT } from '../constants.js';
5
7
  import { MAX_INLINE_BYTES_DEFAULT, isProbablyBinary, loadImageAttachmentWithDownscale, sniffImageMime, } from '../../attachments/image.js';
6
- import { config } from '../../config/index.js';
8
+ import { config, isMemoryEnabled } from '../../config/index.js';
7
9
  /** 默认单次 read_file 拉取的行数。刻意压低,逼 LLM 分块读大文件,
8
10
  * 配合 description 中的 PAGINATION IS MANDATORY 引导。
9
11
  * 300 行 ≈ 一个屏幕的源码量,够定位一段逻辑而不至于吃光上下文。 */
@@ -139,14 +141,21 @@ export const readFileTool = {
139
141
  };
140
142
  }
141
143
  }
142
- const output = end < lines.length
144
+ const baseOutput = end < lines.length
143
145
  ? `${artifactHeader}\n${body}\n\n... (${lines.length - end} 行未显示,共 ${lines.length} 行)`
144
146
  : `${artifactHeader}\n${body}`;
147
+ // R2.4:回注锚定本文件的记忆(最多 3 条,只回 fresh)。
148
+ // 为什么放在 read_file 而不是 system prompt:prompt 每轮注入会撞 cache,而且
149
+ // 「正在看这个文件」这一刻才是这条记忆最有用的时机;读到不相关的文件时零成本。
150
+ // 判定用**刚读到的这份 data**,不会再碰磁盘。
151
+ const output = baseOutput + memoryHintFor(path, data);
145
152
  // dedup 只登记「确实会进 context 的区间」。pushToolResult 会把超长输出经
146
153
  // capToolResultForHistory 中截到 MAX_HISTORY_RESULT(丢中段)——若此处仍登记
147
154
  // 完整 [reqStart, reqEnd],后续对「被截掉的中段」的重读会被 findUnchanged 命中,
148
155
  // 模型拿到 unchanged 短指针却找不到内容,只能反复缩小区间撞墙、最终用 shell 绕过
149
156
  // (实测事故:会话 20261012-033757)。故输出超 cap 时只登记头/尾两段实际保留的行。
157
+ // 用 output(含回注段)判长度:最终进 history 的就是它,回注把长度顶过 cap 时
158
+ // 必须按截断口径登记,否则会记成"完整保留"而制造幽灵命中。
150
159
  if (dedup && config.readDedup && output.length > MAX_HISTORY_RESULT) {
151
160
  const fileHash = contentHash(data);
152
161
  const truncated = truncatedOutputRanges(lines, start, end, output.length, MAX_HISTORY_RESULT);
@@ -159,6 +168,46 @@ export const readFileTool = {
159
168
  return { status: 'success', code: 'OK', retryable: false, output };
160
169
  },
161
170
  };
171
+ /** 回注条数上限。再多就变成噪音,模型会学会跳过这一段。 */
172
+ const MEMORY_HINT_LIMIT = 3;
173
+ /**
174
+ * 参与 fresh 判定的候选条数上限。
175
+ *
176
+ * 必须**先过滤 fresh、再截 3 条**:锚定同一个文件的记忆里,靠前的可能已经过期。
177
+ * 若先按 3 条截断再过滤,前 3 条恰好都 stale 时整段回注会静默消失,而第 4 条
178
+ * 明明仍然有效。这个上限只为防止上百条锚点时白跑一遍 hash 判定。
179
+ */
180
+ const MEMORY_HINT_SCAN = 20;
181
+ /**
182
+ * R2.4:本文件被哪些**仍然对得上**的记忆锚定。
183
+ *
184
+ * 只回 fresh 的:内容已经变了说明这条记忆过期,此刻提示它等于把旧事实塞进上下文;
185
+ * 它会在 `memory_search` 结果里带 `STALE-CODE` 标记出现,那里的语境更合适。
186
+ *
187
+ * 失败静默:记忆是增强通道,读文件本身的成功不能被它拖坏。
188
+ */
189
+ function memoryHintFor(path, data) {
190
+ try {
191
+ if (!isMemoryEnabled())
192
+ return '';
193
+ const anchorPath = toAnchorPath(path);
194
+ const hits = entriesAnchoredTo(anchorPath, { limit: MEMORY_HINT_SCAN });
195
+ if (hits.length === 0)
196
+ return '';
197
+ // 只判**本文件**的锚点:一条记忆可能同时锚定多个文件,拿本文件的文本去判别的文件
198
+ // 必然判 missing,整条记忆会被误当过期(见 evaluateAnchorsAgainst 的 anchorPath 说明)。
199
+ const fresh = hits
200
+ .filter((e) => !evaluateAnchorsAgainst(e.anchors, data, anchorPath).stale)
201
+ .slice(0, MEMORY_HINT_LIMIT);
202
+ if (fresh.length === 0)
203
+ return '';
204
+ const lines = fresh.map((e) => `- [${e.id}] ${e.name} — ${e.summary}`);
205
+ return `\n\n## Memory anchored to this file\n${lines.join('\n')}`;
206
+ }
207
+ catch {
208
+ return '';
209
+ }
210
+ }
162
211
  /**
163
212
  * 输出将被中截(头 60% / 尾 40%)时,反推真正保留进 context 的行区间。
164
213
  * 输出长度按行聚合估算:行号前缀(≤7 字符 + tab)与换行在各行间均摊,误差 ≤1 行,
@@ -1,5 +1,5 @@
1
1
  /**
2
- * run_flow 工具:回放 `.mocode/flows/<name>.json` 里录制好的桌面流程(design-notes/computer-use-rpa.md §5.3)。
2
+ * run_flow 工具:回放 `.mocode/flows/<name>.json` 里录制好的桌面流程(design-notes/computer-use/computer-use-rpa.md §5.3)。
3
3
  *
4
4
  * 与逐步调用 computer 的区别:整条流程不经过模型,按录制的 selector 现场定位元素,失败按步骤的
5
5
  * onError 策略重试 / 跳过 / 中止 / 交还模型。权限在整条 flow 层面一次做完(permissions/flow-review.ts):
@@ -70,6 +70,17 @@ export const USER_DIRECTIVE_MAX_CONSTRAINTS = 3;
70
70
  // ── 记忆(Tier-2 JSONL 工具库)──────────────────────────────────────────────
71
71
  /** 单条记忆 body 上限(字符)。进 history 前 memory_search 结果另有 MAX_MEMORY_RESULT 兜底。 */
72
72
  export const MAX_MEMORY_ENTRY = 4000;
73
+ /**
74
+ * 记忆检索的相关性下限:命中至少这么多个「证据词元」才算相关(R15 实测值)。
75
+ *
76
+ * 证据词元 = 长度 ≥ 2 的 token(ASCII 词或 CJK bigram),单个汉字不算 ——
77
+ * 「红烧肉怎么炖」里的「肉」「好」几乎必然出现在某条记忆正文里,这正是误报来源。
78
+ *
79
+ * 取值 2 的依据:`npm run eval:memory-retrieval` 的 6 条负例在 1 时仍会有 1 条漏过
80
+ * (只重合一个词就返回),取 2 后负例误报 100% → 0%,正例 recall@1 保持 98%。
81
+ * 代价是 1 条词面重合极弱的探针从 recall@3 掉出(pro-2),已记录在 R15 实施结果里。
82
+ */
83
+ export const MEMORY_SEARCH_MIN_EVIDENCE = 2;
73
84
  /** 启动注入 systemPrompt 的索引条目上限(遗忘封顶后 active 条目 ≤ MAX_ACTIVE,索引再封一层)。 */
74
85
  export const MAX_INDEX_ENTRIES = 50;
75
86
  /** active 记忆封顶:超则按 recallCount 低 × lastRecalledAt 老 淘汰到 archived。 */
@@ -78,6 +89,55 @@ export const MAX_ACTIVE = 100;
78
89
  export const DECAY_DAYS = 30;
79
90
  /** GC:archived 超 GC_DAYS → 硬删。 */
80
91
  export const GC_DAYS = 90;
92
+ /**
93
+ * R6 情节记忆的衰减周期,**刻意远短于事实记忆**。
94
+ *
95
+ * 情节是"最近发生了什么"的索引,价值随时间陡降:三天前的会话摘要还能帮你接上工作,
96
+ * 一个月前的只会挤占 token 并干扰判断。事实记忆(怎么配置、哪里有坑)则相反,
97
+ * 越久越该留。若共用 30/90 天,每会话一条 episode 会在两个月内堆到几百条,
98
+ * 把长期知识挤出 `MAX_ACTIVE` 的封顶——这是"情节淹没语义"的标准失败模式。
99
+ *
100
+ * 注意与 `buildEpisodeSection` 的注入上限配合:衰减周期决定**存多久**,
101
+ * 注入上限决定**每次显示几条**,两者必须同时生效才不会互相抵消。
102
+ */
103
+ export const EPISODE_DECAY_DAYS = 7;
104
+ /** 情节归档后多久硬删。比事实的 90 天短得多,理由同上。 */
105
+ export const EPISODE_GC_DAYS = 30;
106
+ /**
107
+ * R11 已巩固情节的衰减周期:被归纳进语义条目后,原始情节的价值只剩"哪次会话"的
108
+ * 追溯入口,主体知识已经在语义条目里。3 天足够覆盖"刚做完那次"的复盘窗口,
109
+ * 再久就是与已巩固的结论重复占 token。这是 R11.1 里「降权」的具体落法。
110
+ */
111
+ export const EPISODE_CONSOLIDATED_DECAY_DAYS = 3;
112
+ // ── R11 情节巩固(episode → 语义)──────────────────────────────────────────
113
+ /**
114
+ * 触发巩固的最少同主题情节数。
115
+ *
116
+ * 2 条不巩固:两条情节的"共性"很可能只是一次性的上下文(同一个 bug 修了两轮),
117
+ * 过早抽象会把噪声固化成长期事实。3 条且跨 2 个会话才够看出重复模式。
118
+ */
119
+ export const CONSOLIDATE_MIN_EPISODES = 3;
120
+ /** 触发巩固的最少不同会话数(单会话内的多次情节是同一件事的续集,不是模式)。 */
121
+ export const CONSOLIDATE_MIN_SESSIONS = 2;
122
+ /** 单次巩固最多处理的组数:后台任务要可控,且一组一次 LLM 调用。 */
123
+ export const CONSOLIDATE_MAX_GROUPS = 2;
124
+ /**
125
+ * 单组的成员上限。受 `store.ts` 的 `MAX_DERIVED_FROM`(8)约束——超过 8 条时
126
+ * `derivedFrom` 会被截断,剩下的源条目查不到来源反而失去可追溯性。
127
+ */
128
+ export const CONSOLIDATE_MAX_GROUP_SIZE = 8;
129
+ /** 分组时最多扫描的情节条数(按 createdAt 降序取最近的一批)。 */
130
+ export const CONSOLIDATE_SCAN_LIMIT = 40;
131
+ /** 两条情节的请求文本至少共享多少个非泛化 token 才算同主题。 */
132
+ export const CONSOLIDATE_MIN_TOKEN_OVERLAP = 2;
133
+ /** 喂给巩固模型的总输入字符预算(超了就整组丢弃,不做中截——残缺的组会被归纳错)。 */
134
+ export const CONSOLIDATE_INPUT_MAX_CHARS = 6000;
135
+ /** 启动时注入的最近 episode 条数(硬上限,见 R6.3)。 */
136
+ export const EPISODE_INJECT_LIMIT = 3;
137
+ /** 单条 episode 里保留的请求条数上限:一次会话几十轮很常见,全列等于存全文(R6.4 禁止)。 */
138
+ export const EPISODE_MAX_REQUESTS = 8;
139
+ /** 单条请求在 episode 里的字符上限(压平成一行后的截断长度)。 */
140
+ export const EPISODE_REQUEST_MAX_CHARS = 120;
81
141
  /** memory_search 结果(召回的记忆正文)的放宽上限:指令性内容,中截破坏语义,对齐 use_skill。 */
82
142
  export const MAX_MEMORY_RESULT = 64000;
83
143
  // ── 知识图谱层(memory-graph.json,单 scope 容量)──────────────────────────
@@ -190,6 +190,11 @@ async function promptInterventionInner(req) {
190
190
  redraw();
191
191
  }
192
192
  function redraw() {
193
+ // 介入面板在 RUNNING 态弹出,最关键的命令/diff/ask_human 行恰好在内容区底部。
194
+ // 先按菜单行数预留内容区底部等宽行:正文整体重排到菜单上沿之上,菜单不再盖住决策依据;
195
+ // 菜单高度不变时 setMenuReserve 内部去重,↑↓ 导航不会整屏闪。
196
+ const menuLines = mode === 'choice' ? menuLinesChoice() : menuLinesInput();
197
+ layout.setMenuReserve(menuLines.length);
193
198
  if (mode === 'choice') {
194
199
  const hint = t('prompt.chooseConfirm');
195
200
  layout.paintInput({
@@ -197,7 +202,7 @@ async function promptInterventionInner(req) {
197
202
  lines: [hint],
198
203
  cursorLine: 0,
199
204
  cursorCol: displayWidth(hint),
200
- menu: { lines: menuLinesChoice() },
205
+ menu: { lines: menuLines },
201
206
  });
202
207
  }
203
208
  else {
@@ -206,7 +211,7 @@ async function promptInterventionInner(req) {
206
211
  lines: [text],
207
212
  cursorLine: 0,
208
213
  cursorCol: displayWidth(text.slice(0, cursor)),
209
- menu: { lines: menuLinesInput() },
214
+ menu: { lines: menuLines },
210
215
  });
211
216
  }
212
217
  }
@@ -217,6 +222,15 @@ async function promptInterventionInner(req) {
217
222
  cleanup();
218
223
  resolve(result);
219
224
  }
225
+ /** 终端尺寸变化:layout 先重设区域/钳预留(它也挂了 SIGWINCH),稍等再按新几何重算
226
+ * 菜单行数并重设预留 + 重画,否则窗口缩高后旧菜单会超出新预留带、选项被裁。 */
227
+ function onResize() {
228
+ setTimeout(() => {
229
+ if (resolved)
230
+ return;
231
+ redraw();
232
+ }, 60);
233
+ }
220
234
  /** 退出:摘自己的监听 + 恢复快照监听 + 擦菜单恢复内容区。不 setRawMode(false)/pause stdin(运行态由 repl 接管)。 */
221
235
  function cleanup() {
222
236
  if (activeFinish === finish)
@@ -227,6 +241,12 @@ async function promptInterventionInner(req) {
227
241
  for (const l of savedListeners)
228
242
  emitter.on('keypress', l);
229
243
  savedListeners = [];
244
+ try {
245
+ process.removeListener('SIGWINCH', onResize);
246
+ }
247
+ catch {
248
+ // 忽略
249
+ }
230
250
  // 先 paintInput(dim,menu:null):擦菜单(用 lastMenuRows)+ 画 dim 占位底栏 + 复位 lastMenuRows=0;
231
251
  // 再处理滚动:面板内可能滚过滚轮(scrollOffset>0)→ resetScroll 回尾让 agent 后续输出可见;
232
252
  // 未滚则 repaintViewport 从 content 缓冲重画内容区(恢复被菜单覆盖的 ● ask_human 行)。
@@ -238,6 +258,10 @@ async function promptInterventionInner(req) {
238
258
  cursorCol: 0,
239
259
  menu: null,
240
260
  });
261
+ // 释放菜单预留行:正文恢复满内容区(setMenuReserve 内部重画被菜单占过的底部行)。
262
+ // 必须在 menu:null 擦菜单之后——先释放会让 repaintViewport 用正文覆盖尚未擦的菜单,
263
+ // 紧接着的 stale lastMenuRows 擦除又会把刚恢复的正文抹掉。
264
+ layout.setMenuReserve(0);
241
265
  if (layout.isScrolled())
242
266
  layout.resetScroll();
243
267
  else
@@ -397,6 +421,12 @@ async function promptInterventionInner(req) {
397
421
  }
398
422
  stdin.resume();
399
423
  emitter.on('keypress', onKey);
424
+ try {
425
+ process.on('SIGWINCH', onResize);
426
+ }
427
+ catch {
428
+ // 不支持则放弃 resize 自适应,不阻断面板
429
+ }
400
430
  layout.setCursorChangeHandler(applyExternalCursor); // 鼠标左键单击输入框 → 移光标到点击位
401
431
  redraw();
402
432
  }
@@ -409,6 +439,12 @@ async function promptInterventionInner(req) {
409
439
  catch {
410
440
  // 忽略
411
441
  }
442
+ try {
443
+ process.removeListener('SIGWINCH', onResize);
444
+ }
445
+ catch {
446
+ // 忽略
447
+ }
412
448
  for (const l of savedListeners) {
413
449
  try {
414
450
  emitter.on('keypress', l);
@@ -29,10 +29,10 @@ import { composePlanLines, drawStatusBar, startTurnTimer, stopTurnTimer } from '
29
29
  import { paintInput, repaint } from './input-paint.js';
30
30
  import { WHEEL_LINES, screenRowToAbsLine, repaintViewport, scrollBy, scrollWheel, resetScroll, lockScrollToBottom, } from './scroll.js';
31
31
  import { contentWrite, contentInsertAfter, contentDeleteFrom, contentReplaceLine, reflowContentForResize, flushMdSegment, } from './content-write.js';
32
- export { isTuiActive, getGeo, setRegion, contentMode, isStreamingPaused } from './screen.js';
32
+ export { isTuiActive, getGeo, getEffectiveContentBottom, setRegion, contentMode, isStreamingPaused } from './screen.js';
33
33
  export { drawStatusBar, setStatus, stopTurnTimer, startTurnTimerIfRunning, paintLiveAtCursor, clearLiveAtCursor, setLiveUsage, setQueuedTurn, setStatusBase, } from './statusbar.js';
34
34
  export { paintInput, paintRunningInput, repaint } from './input-paint.js';
35
- export { isScrolled, repaintViewport, repaintContentLine, scrollBy, scrollWheel, resetScroll, lockScrollToBottom, unlockScroll, isScrollLocked, } from './scroll.js';
35
+ export { isScrolled, repaintViewport, repaintContentLine, scrollBy, scrollWheel, resetScroll, setMenuReserve, lockScrollToBottom, unlockScroll, isScrollLocked, } from './scroll.js';
36
36
  export { contentWrite, writeBanner, rewriteBanner, bannerHeight, contentWriteMd, contentWriteMdOnce, clearContent, rewindContent, writeWelcomeBlock, dismissWelcomeBlock, contentInsertAfter, contentDeleteFrom, totalRows, isLastContentRowBlank, normalizeMutationBoundary, normalizeInputBoundary, contentReplaceLine, notifyContentReset, } from './content-write.js';
37
37
  // ── 裸 console 防御 ──
38
38
  // 第三方库(如 openai SDK)可能用 console.log 直写 stdout,在 RUNNING 态会落到光标所在的底栏
@@ -565,6 +565,12 @@ export function enterAltScreen() {
565
565
  const colsChanged = latest.cols !== state.lastTerminalCols;
566
566
  reflowContentForResize(latest.cols, colsChanged);
567
567
  state.lastTerminalCols = latest.cols;
568
+ // 介入面板开着时菜单预留行可能因新窗口高度而越界:重新钳到 contentBottom-1。
569
+ // 菜单本身的重排由 intervention 的 resize 监听负责(它会按新几何重算 menuLines 并再设一次预留);
570
+ // 这里只保证视口几何不留错值,避免正文重排到菜单带里。
571
+ if (state.menuReserveRows > 0) {
572
+ state.menuReserveRows = Math.min(state.menuReserveRows, latest.contentBottom - 1);
573
+ }
568
574
  repaintViewport(); // 内容区按最新高度和列宽重画;markdown 历史已按新列宽 reflow
569
575
  repaint(); // 底栏重画
570
576
  }, 100);
@@ -5,7 +5,7 @@ import { charWidth, displayWidth, truncateDisplay, truncateDisplayHead, wrapByDi
5
5
  import { ui } from '../theme.js';
6
6
  import * as content from '../content.js';
7
7
  import { state } from './state.js';
8
- import { esc, cup, getGeo, setRegion, runningCaretPos } from './screen.js';
8
+ import { esc, cup, getGeo, getEffectiveContentBottom, setRegion, runningCaretPos } from './screen.js';
9
9
  import { SEL_OPEN, SEL_OFF, normalizeInputSelection, inputViewSig } from './selection.js';
10
10
  import { composeSpinnerLine, composeModelLine, composePlanLines, drawStatusBar } from './statusbar.js';
11
11
  // ── 输入区(底栏输入框 + 向上菜单)──
@@ -147,11 +147,14 @@ export function paintInput(view) {
147
147
  }
148
148
  g = setRegion(needFooterH);
149
149
  }
150
- // 2b. 重画内容末行(底栏上一行)从缓冲:防 WT 边距漏影(状态行重复到该行),并保证该行显正确内容
150
+ // 2b. 重画内容末行(有效视口底行)从缓冲:防 WT 边距漏影(状态行重复到该行),并保证该行显正确内容。
151
+ // 介入面板预留菜单行时,末行是菜单上沿那一行(getEffectiveContentBottom),不是物理 contentBottom——
152
+ // 后者属于菜单预留带,由第 5 步画菜单,这里不能碰,否则会在选项之间漏出正文。
151
153
  {
152
- const slice = content.sliceFromEnd(state.scrollOffset, g.contentBottom);
153
- const line = slice[g.contentBottom - 1] ?? '';
154
- buf += cup(g.contentBottom, 1) + esc.clearLine + line;
154
+ const effBottom = getEffectiveContentBottom();
155
+ const slice = content.sliceFromEnd(state.scrollOffset, effBottom);
156
+ const line = slice[effBottom - 1] ?? '';
157
+ buf += cup(effBottom, 1) + esc.clearLine + line;
155
158
  }
156
159
  // 2c. 虚拟空行(内容区与状态栏之间的视觉间隔,属底栏非内容):
157
160
  // - 无活跃 plan:清空保留作分隔(原设计)
@@ -245,9 +248,14 @@ export function paintInput(view) {
245
248
  }
246
249
  // 4b. 下线(输入框底):满屏宽细线 ─(cyan),在 model 行上一行(model 行占屏底 rows)
247
250
  buf += cup(g.rows - 1, 1) + esc.clearLine + ui.accent + '─'.repeat(g.cols) + ui.reset;
248
- // 5. 向上菜单(画在内容区底,底栏正上方)
251
+ // 5. 向上菜单(画在内容区底,底栏正上方)。
252
+ // 介入面板经 setMenuReserve 预留了等宽的底部行,正文已重排到菜单上沿之上,故菜单画进预留带、
253
+ // 不再覆盖任何正文;无预留(命令补全等普通 picker)时退回旧的 overlay 行为,直接贴内容区底。
249
254
  if (view.menu && view.menu.lines.length > 0) {
250
- const menuRows = Math.min(view.menu.lines.length, g.contentBottom);
255
+ const reserve = state.menuReserveRows > 0;
256
+ const menuRows = reserve
257
+ ? Math.min(view.menu.lines.length, state.menuReserveRows)
258
+ : Math.min(view.menu.lines.length, g.contentBottom);
251
259
  const menuStart = g.contentBottom - menuRows + 1;
252
260
  for (let i = 0; i < menuRows; i++) {
253
261
  buf += cup(menuStart + i, 1) + esc.clearLine + view.menu.lines[i];
@@ -66,6 +66,15 @@ export function getGeo(fh = state.footerH) {
66
66
  contentBottom: Math.max(1, rows - f),
67
67
  };
68
68
  }
69
+ /**
70
+ * 正文当前真正可用的**内容区底行**:有预留菜单(介入面板)时为 contentBottom - menuReserveRows。
71
+ * viewport 切片、滚动钳位、续写末行重画都用它,保证正文只画到菜单上沿、不与菜单重叠。
72
+ * 无菜单预留时与 getGeo().contentBottom 相同。
73
+ */
74
+ export function getEffectiveContentBottom() {
75
+ const g = getGeo();
76
+ return Math.max(1, g.contentBottom - state.menuReserveRows);
77
+ }
69
78
  /** (重)设滚动区域 [1, rows-footerH];设完 \x1B[H 归位(conhost 设 DECSTBM 时光标留旧位置行为未定义)。 */
70
79
  export function setRegion(fh) {
71
80
  const rows = stdout.rows || 24;
@@ -5,7 +5,7 @@ import { displayWidth, truncateDisplayHead, truncateAnsi, ansiDisplayWidth, padE
5
5
  import { ui } from '../theme.js';
6
6
  import * as content from '../content.js';
7
7
  import { state } from './state.js';
8
- import { esc, cup, getGeo, runningCaretPos } from './screen.js';
8
+ import { esc, cup, getGeo, getEffectiveContentBottom, runningCaretPos } from './screen.js';
9
9
  import { normalizeSelection, highlightRange } from './selection.js';
10
10
  import { repaint } from './input-paint.js';
11
11
  // ── 纯常量(可变运行态在 state.ts)──
@@ -20,10 +20,10 @@ export function isScrolled() {
20
20
  }
21
21
  /** viewport 窗口起点绝对行索引(0-based,对齐 content.sliceFromEnd 的 start)。 */
22
22
  export function viewportAbsStart() {
23
- const g = getGeo();
23
+ const h = getEffectiveContentBottom();
24
24
  const total = content.totalRows();
25
25
  const end = Math.max(0, total - state.scrollOffset);
26
- return Math.max(0, end - g.contentBottom);
26
+ return Math.max(0, end - h);
27
27
  }
28
28
  /** 屏行(1-based,内容区内)→ 绝对缓冲行索引(0-based)。 */
29
29
  export function screenRowToAbsLine(row) {
@@ -43,13 +43,13 @@ export function screenRowToAbsLine(row) {
43
43
  export function repaintContentLine(absIdx, line) {
44
44
  if (!state.active || state.overlayActive)
45
45
  return; // 覆盖层打开中不写屏(缓冲已由调用方更新)
46
- const g = getGeo();
46
+ const bottom = getEffectiveContentBottom();
47
47
  const row = absIdx - viewportAbsStart() + 1;
48
- if (row < 1 || row > g.contentBottom)
49
- return; // 不在视口内:不猜映射,交由上层处理
48
+ if (row < 1 || row > bottom)
49
+ return; // 不在有效视口内(含被预留菜单占住的行):不写
50
50
  // 已提交行自带完整 SGR 前缀(breakRow 落盘的是 `rowStartSgr + curRaw + reset`,见 content.ts),
51
51
  // 故单行重画无需补前缀,只需按当前列宽钳宽(窄窗兜底,防 auto-wrap 破坏「一行=一物理行」)。
52
- const text = truncateAnsi(line, g.cols);
52
+ const text = truncateAnsi(line, getGeo().cols);
53
53
  let out = cup(row, 1) + esc.clearLine + text;
54
54
  // 与 repaintViewport 同约定:运行态光标归输入框(供 IME 锚定),INPUT 态归续写位。
55
55
  if (state.mode === 'running') {
@@ -57,7 +57,7 @@ export function repaintContentLine(absIdx, line) {
57
57
  out += cup(c.row, c.col);
58
58
  }
59
59
  else {
60
- out += cup(state.scrollOffset === 0 ? state.contentRow : g.contentBottom, state.scrollOffset === 0 ? state.contentCol : 1);
60
+ out += cup(state.scrollOffset === 0 ? state.contentRow : bottom, state.scrollOffset === 0 ? state.contentCol : 1);
61
61
  }
62
62
  stdout.write(out);
63
63
  }
@@ -78,7 +78,9 @@ export function repaintViewport() {
78
78
  if (!state.active || state.overlayActive)
79
79
  return;
80
80
  const g = getGeo();
81
- const h = g.contentBottom;
81
+ // 介入面板预留菜单行时,正文只画到菜单上沿;菜单区(其下到 contentBottom)留给 paintInput,
82
+ // 这里绝不能 cup+clearLine 进去,否则会把菜单擦掉或在选项之间漏出正文。
83
+ const h = getEffectiveContentBottom();
82
84
  const slice = content.sliceFromEnd(state.scrollOffset, h);
83
85
  const sel = normalizeSelection();
84
86
  // viewportAbsStart() 无选区时也用:sticky banner 必须按真实窗口头算,不能降级 0(否则 banner 永不出现)。
@@ -140,15 +142,16 @@ export function repaintViewport() {
140
142
  }
141
143
  stdout.write(p);
142
144
  }
143
- /** 滚动 delta 行(正=往新、负=往旧);钳 [0, max(0, total-contentBottom)];变则重画 + 刷底栏(显指示、光标回输入框)。 */
145
+ /** 滚动 delta 行(正=往新、负=往旧);钳 [0, max(0, total-视口高)];变则重画 + 刷底栏(显指示、光标回输入框)。 */
144
146
  export function scrollBy(delta) {
145
147
  if (!state.active)
146
148
  return;
147
149
  if (Date.now() < state.scrollLockUntil)
148
150
  return; // 轮首滚动锁:吸收发消息前后 stdin 残留滚轮事件,保 agent 输出从底部开始
151
+ const h = getEffectiveContentBottom(); // 介入面板期按菜单上沿之上的压缩视口算滚动范围
149
152
  const g = getGeo();
150
153
  const total = content.totalRows();
151
- const maxOff = Math.max(0, total - g.contentBottom);
154
+ const maxOff = Math.max(0, total - h);
152
155
  const off = Math.max(0, Math.min(state.scrollOffset + delta, maxOff));
153
156
  if (off === state.scrollOffset)
154
157
  return;
@@ -188,6 +191,41 @@ export function lockScrollToBottom(ms = SCROLL_LOCK_MS) {
188
191
  export function unlockScroll() {
189
192
  state.scrollLockUntil = 0;
190
193
  }
194
+ /**
195
+ * 设置向上菜单对内容区**底部**的预留行数(介入面板专用)。
196
+ * - rows > 0:正文视口压缩为 contentBottom-rows 行,整体重排到菜单上沿之上,菜单不再盖住正文;
197
+ * - rows = 0:菜单关闭,恢复满内容区。
198
+ * 仅在数值变化时重画正文(↑↓ 导航若菜单高度不变无需重排),避免每帧整屏闪烁。
199
+ * 预留区里被腾出来的行(rows 变小/归零时新增可见的行)由本函数用清行 + 重画补齐,
200
+ * 调用方随后 paintInput 把菜单画在预留区内。
201
+ */
202
+ export function setMenuReserve(rows) {
203
+ if (!state.active)
204
+ return;
205
+ const g = getGeo();
206
+ const clamped = Math.max(0, Math.min(rows, g.contentBottom - 1));
207
+ if (clamped === state.menuReserveRows)
208
+ return;
209
+ const prev = state.menuReserveRows;
210
+ state.menuReserveRows = clamped;
211
+ // 预留变小(菜单缩短/关闭):旧菜单区里 [新上沿+1 .. 旧上沿] 这几行需要先清掉旧菜单残留,
212
+ // 再由 repaintViewport 用正文重画;repaintViewport 只画到新上沿,故这里先清再画。
213
+ if (clamped < prev) {
214
+ const newBottom = g.contentBottom - clamped;
215
+ const oldBottom = g.contentBottom - prev;
216
+ let p = '';
217
+ for (let r = newBottom + 1; r <= oldBottom; r++)
218
+ p += cup(r, 1) + esc.clearLine;
219
+ if (p)
220
+ stdout.write(p);
221
+ }
222
+ // 滚动偏移可能超过压缩视口的新上限:钳回,避免顶部出现空窗。
223
+ const h = g.contentBottom - clamped;
224
+ const maxOff = Math.max(0, content.totalRows() - h);
225
+ if (state.scrollOffset > maxOff)
226
+ state.scrollOffset = maxOff;
227
+ repaintViewport();
228
+ }
191
229
  /** 轮首滚动锁是否生效(测试用)。 */
192
230
  export function isScrollLocked() {
193
231
  return Date.now() < state.scrollLockUntil;
@@ -84,6 +84,14 @@ export const state = {
84
84
  lastView: null,
85
85
  lastMenuStartRow: 0, // 上次菜单起始屏行(供擦除)
86
86
  lastMenuRows: 0,
87
+ /**
88
+ * 当前向上菜单占用内容区**底部**的物理行数(paintInput 画菜单期间 >0)。
89
+ * 介入面板(ask_human / 权限)在 RUNNING 态弹出时,最关键的命令/diff/ask_human 行
90
+ * 恰好位于内容区底——若菜单直接盖上去,用户看不到决策依据。该值让视口有效高度
91
+ * 收缩为 contentBottom - menuReserveRows:正文重排到菜单上沿之上,二者不重叠;
92
+ * 面板内 PgUp/滚轮也只在压缩后的视口里滚动。菜单关闭复位 0,repaintViewport 全量恢复。
93
+ */
94
+ menuReserveRows: 0,
87
95
  /** 上次画过输入框的 lastView 签名(lines 数 + 每行 display_w 累加);变了说明 prompt.ts 改了文本 → 选区锚点失效,清掉。 */
88
96
  lastInputSig: '',
89
97
  pasteHandler: null,