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.
- package/dist/agent/index.js +13 -3
- package/dist/agent/mentioned-files.js +71 -0
- package/dist/agent/model-turn.js +55 -11
- package/dist/agent/progress-guard.js +67 -0
- package/dist/agent/run-coordinator.js +140 -12
- package/dist/agent/short-path-completion.js +109 -0
- package/dist/agent/spawn.js +39 -0
- package/dist/agent/stages/history-manager.js +1 -0
- package/dist/agent/tool-helpers.js +2 -2
- package/dist/agent/tool-turn.js +49 -4
- package/dist/agent/work-discipline.js +9 -9
- package/dist/config/index.js +13 -10
- package/dist/context/relevance.js +2 -1
- package/dist/host/stdio.js +88 -27
- package/dist/i18n/index.js +26 -10
- package/dist/llm/index.js +27 -3
- package/dist/llm/message-shape.js +18 -0
- package/dist/llm/reasoning.js +17 -0
- package/dist/models/reasoning-cap.js +19 -2
- package/dist/orchestrator/lane-executor.js +7 -1
- package/dist/orchestrator/repl.js +30 -49
- package/dist/repl/commands/appearance.js +1 -2
- package/dist/repl/commands/compact.js +4 -0
- package/dist/repl/commands/model-actions.js +4 -3
- package/dist/repl/commands/model.js +2 -3
- package/dist/repl/message-format.js +7 -6
- package/dist/repl/running-input.js +27 -65
- package/dist/repl/runtime.js +118 -76
- package/dist/rollback/store.js +36 -23
- package/dist/runtime/runtime.js +1 -1
- package/dist/session/compact.js +41 -4
- package/dist/session/retention.js +4 -0
- package/dist/session/short-path-metrics.js +185 -0
- package/dist/session/store.js +78 -3
- package/dist/session/terminal-transcript.js +101 -0
- package/dist/tools/builtins/ask-human.js +2 -2
- package/dist/tools/builtins/edit-file.js +28 -5
- package/dist/tools/builtins/grep.js +85 -35
- package/dist/tools/builtins/plan-update.js +4 -2
- package/dist/tools/builtins/read-file.js +95 -44
- package/dist/tools/builtins/run-command.js +57 -9
- package/dist/tools/ripgrep-client.js +31 -11
- package/dist/tools/tool-runtime.js +29 -8
- package/dist/ui/layout-internal/content-write.js +7 -3
- package/dist/ui/layout-internal/core.js +1 -1
- package/dist/ui/layout-internal/state.js +0 -6
- package/dist/ui/layout-internal/statusbar.js +0 -30
- package/dist/ui/output-sink.js +24 -0
- package/dist/ui/spinner.js +3 -1
- package/package.json +4 -2
package/dist/agent/index.js
CHANGED
|
@@ -15,7 +15,7 @@ import { createPetHooks } from '../pet/state.js';
|
|
|
15
15
|
import { defaultAgentRuntimeContext } from './runtime-context.js';
|
|
16
16
|
import { t } from '../i18n/index.js';
|
|
17
17
|
import { isToolErrorOutput } from '../tools/result.js';
|
|
18
|
-
import { appendCurrentSessionTraceEvent } from '../session/index.js';
|
|
18
|
+
import { appendCurrentSessionTraceEvent, capToolResultForHistory } from '../session/index.js';
|
|
19
19
|
import { buildTurnRecallSection, isTurnRecallEnabled } from '../memory/turn-recall.js';
|
|
20
20
|
import { memoryTailChangedIds } from '../memory/tail.js';
|
|
21
21
|
import { createHandoffStripper, handoffDisplaySuppressed } from '../ui/handoff-block.js';
|
|
@@ -308,7 +308,7 @@ initialToolRoute,
|
|
|
308
308
|
*/
|
|
309
309
|
memoryTail,
|
|
310
310
|
/** TUI composition root 绑定的 Runtime;旧调用传 AgentRuntimeContext 仍兼容。 */
|
|
311
|
-
runtimeOrContext = defaultRuntime) {
|
|
311
|
+
runtimeOrContext = defaultRuntime, drainUserMessages, transcript) {
|
|
312
312
|
const runtime = runtimeOrContext instanceof Runtime
|
|
313
313
|
? runtimeOrContext
|
|
314
314
|
: runtimeOrContext === defaultAgentRuntimeContext
|
|
@@ -382,6 +382,7 @@ runtimeOrContext = defaultRuntime) {
|
|
|
382
382
|
layout.normalizeMutationBoundary();
|
|
383
383
|
spinner.stop(); // 任何正文 token 都停 spinner(首 token 停「思考中」;onToolCall 重启后若又来文本则停「生成中」)。未旋转时 stop 为 no-op。
|
|
384
384
|
layout.contentWriteMd(visible); // 正文走 markdown 渲染(代码块高亮 / 标题 / 列表 / 行内 …),见 ui/markdown.ts
|
|
385
|
+
transcript?.addText(visible);
|
|
385
386
|
if (visible) {
|
|
386
387
|
lastChar = visible[visible.length - 1];
|
|
387
388
|
if (visible.trim().length > 0) {
|
|
@@ -487,7 +488,15 @@ runtimeOrContext = defaultRuntime) {
|
|
|
487
488
|
onToolStart: (name) => spinner.start(t('agent.executing', { tool: name })),
|
|
488
489
|
onToolOutput: (tc, chunk) => batch.recordOutput(tc.id, chunk, layout),
|
|
489
490
|
onToolDone: () => spinner.stop(),
|
|
490
|
-
onToolResult: (tc, output, parsed, preWriteOld, editStartLine, multiHunks) =>
|
|
491
|
+
onToolResult: (tc, output, parsed, preWriteOld, editStartLine, multiHunks) => {
|
|
492
|
+
if (transcript)
|
|
493
|
+
transcript.addTool(tc, capToolResultForHistory(tc.name, output));
|
|
494
|
+
writeToolResult(tc, output, parsed, preWriteOld, editStartLine, runtime.context.toolRuntime, multiHunks);
|
|
495
|
+
},
|
|
496
|
+
onCompactProgress: (event) => {
|
|
497
|
+
if (event.phase === 'done' && event.compacted)
|
|
498
|
+
transcript?.compacted();
|
|
499
|
+
},
|
|
491
500
|
onToolBatchEnd: () => {
|
|
492
501
|
// 一次工具轮次结束不再切 UI batch;下一轮若仍无正文,继续复用 currentBatchId。
|
|
493
502
|
},
|
|
@@ -546,6 +555,7 @@ runtimeOrContext = defaultRuntime) {
|
|
|
546
555
|
turnLabel: truncateDisplay(firstLineOf(userInput), 40),
|
|
547
556
|
history,
|
|
548
557
|
userInput,
|
|
558
|
+
drainUserMessages,
|
|
549
559
|
signal,
|
|
550
560
|
onContextUpdate,
|
|
551
561
|
hooks: combinedHooks,
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
// 已知文件提示(短路径优化)的**确定性提取器**。
|
|
2
|
+
//
|
|
3
|
+
// 背景(eval trace 实测):任务文本里已点名目标文件时,弱指令遵循模型(flash/低思考档)
|
|
4
|
+
// 仍会先 grep/glob "确认位置",白烧一个完整模型往返;而把「直接读它」写进**任务文本**
|
|
5
|
+
// (近因位置)后模型立刻照做——系统提示中段的同义规则对它几乎无效。
|
|
6
|
+
//
|
|
7
|
+
// 因此这里只做机械提取 + 存在性过滤,不做语义判断:
|
|
8
|
+
// 1. 从用户文本里抓「看起来像文件」的 token(反引号包裹或裸词,带代码扩展名);
|
|
9
|
+
// 2. 按 cwd 解析并要求真实存在(误报如 "step 3."、"v1.2" 被扩展名白名单和存在性双双挡掉);
|
|
10
|
+
// 3. 去重、上限 5 个,空结果 = 零注入。
|
|
11
|
+
// 提示只说「这些文件已知,直接读」——不禁止探索,复杂任务不受影响。
|
|
12
|
+
import { existsSync } from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
const FILE_TOKEN_RE = /(?:`([^`\n]+)`|([\w./\\-]+))\.([A-Za-z][A-Za-z0-9]{0,7})/g;
|
|
15
|
+
const CODE_EXTENSIONS = new Set([
|
|
16
|
+
'ts',
|
|
17
|
+
'tsx',
|
|
18
|
+
'js',
|
|
19
|
+
'jsx',
|
|
20
|
+
'mjs',
|
|
21
|
+
'cjs',
|
|
22
|
+
'mts',
|
|
23
|
+
'cts',
|
|
24
|
+
'json',
|
|
25
|
+
'md',
|
|
26
|
+
'py',
|
|
27
|
+
'go',
|
|
28
|
+
'rs',
|
|
29
|
+
'java',
|
|
30
|
+
'rb',
|
|
31
|
+
'php',
|
|
32
|
+
'css',
|
|
33
|
+
'scss',
|
|
34
|
+
'html',
|
|
35
|
+
'yaml',
|
|
36
|
+
'yml',
|
|
37
|
+
'toml',
|
|
38
|
+
'sh',
|
|
39
|
+
'sql',
|
|
40
|
+
'vue',
|
|
41
|
+
'svelte',
|
|
42
|
+
]);
|
|
43
|
+
const MAX_MENTIONED_FILES = 5;
|
|
44
|
+
export function buildMentionedFilesReminder(userText, cwd) {
|
|
45
|
+
const files = extractMentionedFiles(userText, cwd);
|
|
46
|
+
if (files.length === 0)
|
|
47
|
+
return '';
|
|
48
|
+
return (`Files named in this request (verified present in the workspace): ${files.join(', ')} — ` +
|
|
49
|
+
'read_file them directly as your first action; do not grep/glob to locate these files first.');
|
|
50
|
+
}
|
|
51
|
+
export function extractMentionedFiles(userText, cwd) {
|
|
52
|
+
if (!userText)
|
|
53
|
+
return [];
|
|
54
|
+
const found = [];
|
|
55
|
+
const seen = new Set();
|
|
56
|
+
for (const match of userText.matchAll(FILE_TOKEN_RE)) {
|
|
57
|
+
const token = `${match[1] ?? match[2]}.${match[3]}`.replace(/\\/g, '/');
|
|
58
|
+
if (token.length > 200 || seen.has(token))
|
|
59
|
+
continue;
|
|
60
|
+
if (!CODE_EXTENSIONS.has(match[3].toLowerCase()))
|
|
61
|
+
continue;
|
|
62
|
+
const candidate = path.isAbsolute(token) ? token : path.resolve(cwd, token);
|
|
63
|
+
if (!existsSync(candidate))
|
|
64
|
+
continue;
|
|
65
|
+
seen.add(token);
|
|
66
|
+
found.push(token);
|
|
67
|
+
if (found.length >= MAX_MENTIONED_FILES)
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
return found;
|
|
71
|
+
}
|
package/dist/agent/model-turn.js
CHANGED
|
@@ -43,7 +43,16 @@ export async function runModelTurn(input) {
|
|
|
43
43
|
// 与压缩压力线会持续低估(召回段 + 尾注的字数并不小)。
|
|
44
44
|
const memoryRecallText = input.memoryRecall ?? '';
|
|
45
45
|
const memoryTailText = opts.memoryTail ?? '';
|
|
46
|
-
const ephemeralJoined = () => [
|
|
46
|
+
const ephemeralJoined = () => [
|
|
47
|
+
sessionStateText,
|
|
48
|
+
memoryRecallText,
|
|
49
|
+
memoryTailText,
|
|
50
|
+
input.mentionedFilesReminder ?? '',
|
|
51
|
+
input.liveUpdateReminder ?? '',
|
|
52
|
+
input.noProgressReminder ?? '',
|
|
53
|
+
]
|
|
54
|
+
.filter((s) => s.length > 0)
|
|
55
|
+
.join('\n\n');
|
|
47
56
|
/** 与 ephemeralJoined() 同源,保证「发了多少」与「算多大」永不漂移。 */
|
|
48
57
|
const ephemeralTokenEstimate = () => {
|
|
49
58
|
const joined = ephemeralJoined();
|
|
@@ -166,7 +175,9 @@ export async function runModelTurn(input) {
|
|
|
166
175
|
// 流中即发 onTextEnd 会让 UI 在词中间硬换行并封死 markdown 段(「继续通读:d / ispatcher」
|
|
167
176
|
// 断词 bug)。onToolCall 此刻只驱动「生成中」spinner;正文收尾换行统一由流末
|
|
168
177
|
// (tool-turn / run-coordinator)依据 stream.lastChar 发一次 onTextEnd,届时全部 content 已到齐。
|
|
169
|
-
|
|
178
|
+
// 新任务或收到引导后的首步,从 tool-turn 发开场后的工具状态。
|
|
179
|
+
if (!input.opening)
|
|
180
|
+
hooks.onToolCall?.(name);
|
|
170
181
|
};
|
|
171
182
|
let result;
|
|
172
183
|
const modelStartedAt = Date.now();
|
|
@@ -183,7 +194,7 @@ export async function runModelTurn(input) {
|
|
|
183
194
|
// step 0 由 Opening analysis 独自承担:那里既没有工具结果可复述,也没有"已说过的观点",
|
|
184
195
|
// 而"能直接答就直接答"的授权已写在 Answer-first 里,本段三条约束在 step 0 均无对象。
|
|
185
196
|
// 子 agent 静默执行、不写屏,沿用 suppressOpeningAnalysis 一并免注入。
|
|
186
|
-
!opts.suppressOpeningAnalysis && step > 0
|
|
197
|
+
!opts.suppressOpeningAnalysis && step > 0 && !input.opening
|
|
187
198
|
? '## Silent work\n' +
|
|
188
199
|
// 禁令范围收在「调用之间」,而不是「不要宣布你要做什么」:后者与 step 0 的
|
|
189
200
|
// Opening analysis(要求说明打算怎么入手)字面冲突,只能靠下面的白名单化解,
|
|
@@ -197,13 +208,40 @@ export async function runModelTurn(input) {
|
|
|
197
208
|
"direct answers to the user's questions, blocking questions, " +
|
|
198
209
|
'findings that change the next action, and the final report.'
|
|
199
210
|
: '',
|
|
200
|
-
// 仅 step 0
|
|
201
|
-
//
|
|
202
|
-
//
|
|
203
|
-
//
|
|
204
|
-
//
|
|
205
|
-
|
|
206
|
-
? '## Opening analysis\
|
|
211
|
+
// 仅 step 0:就近重申 Answer-first,并保留「开场一句」这条祈使要求。
|
|
212
|
+
// 859b974 曾把它改写成条件句(only when ... needs a user decision or complex),
|
|
213
|
+
// 于是「清晰的小改动」全被划进「直接调工具」一档,开场白彻底消失——那句原本无条件的
|
|
214
|
+
// 祈使主语在重写时丢了。这里把「先说一句」恢复成无条件的,Answer-first 只决定这一句
|
|
215
|
+
// 之后是回答还是动手,不再决定说不说。
|
|
216
|
+
input.opening === 'initial'
|
|
217
|
+
? '## Opening analysis\n' +
|
|
218
|
+
'Before your first tool call in every user-facing turn, you MUST output exactly one short visible sentence ' +
|
|
219
|
+
'telling the user what you will check or change first and what it will help you establish. ' +
|
|
220
|
+
'Use plain language and put the sentence first in the SAME assistant response as the tool calls. ' +
|
|
221
|
+
'If no tools are needed, answer directly. After this opening, work silently.'
|
|
222
|
+
: '',
|
|
223
|
+
input.opening === 'steering'
|
|
224
|
+
? '## Steering opening\n' +
|
|
225
|
+
'If you need tools after the latest user updates, start the same response with one short visible sentence ' +
|
|
226
|
+
'explaining how the update changes what you will do next. Continue from the work already done. ' +
|
|
227
|
+
'If you can answer directly, do so. After the opening, work silently.'
|
|
228
|
+
: '',
|
|
229
|
+
// 就近重申 Answer-first。动机(2026-11-18):用户反馈「很简单的问题也要兜一大圈」。
|
|
230
|
+
// history[0] 的 Workflow 里已有 Answer first,但它离当前决策最远,而每轮都在的
|
|
231
|
+
// 具体指令(codegraph 段、知识图谱段、「Do not stop prematurely」)更容易被遵守,
|
|
232
|
+
// 结果是「一句话能答的问题先跑三条 grep」。ephemeral 段不写回 history,
|
|
233
|
+
// 所以这里补一次近场重申,不破坏前缀缓存。
|
|
234
|
+
// 措辞刻意压到三句:这段每步都发,长一倍的禁令换不来一倍遵守度,只换 token。
|
|
235
|
+
// 禁令范围收在「已有同源证据时的确认性查询」——早期写法是「核实不算回答的一部分」,
|
|
236
|
+
// 过宽,会把「证据不全时的必要核查」一起禁掉;这里要求先有同源证据才允许跳过。
|
|
237
|
+
// 末句把实现任务排除在外,否则会被读成「改到一半就下结论也合规」。
|
|
238
|
+
// 与 Silent work 无冲突:前者管「要不要动手」,后者管「要不要说」。
|
|
239
|
+
!opts.suppressOpeningAnalysis
|
|
240
|
+
? '## Answer before investigating\n' +
|
|
241
|
+
'For a judgment, explanation or advice (not a code change), if the evidence already sits in this ' +
|
|
242
|
+
'conversation, the tool results above, or the injected project context, answer now — skip the ' +
|
|
243
|
+
'confirm-again read or re-run. Look up only a fact that is genuinely missing. Code changes keep ' +
|
|
244
|
+
'the normal edit-and-check loop.'
|
|
207
245
|
: '',
|
|
208
246
|
remainingSteps <= 3
|
|
209
247
|
? `## Step budget warning\nOnly ${remainingSteps} step(s) remain before the hard step limit (${maxSteps}). ` +
|
|
@@ -223,9 +261,14 @@ export async function runModelTurn(input) {
|
|
|
223
261
|
// R18:每轮静默召回。放在 R17 尾注之前:尾注说的是「刚变了什么」(时间上最新),
|
|
224
262
|
// 召回说的是「这轮可能用得上什么」(topic 相关),新的信息靠后更能被看见。
|
|
225
263
|
input.memoryRecall ?? '',
|
|
264
|
+
// 短路径优化:已知名文件近因提示(见 mentioned-files.ts)。放在召回段之后:
|
|
265
|
+
// 它是本 turn 的任务级事实,靠后位置对弱指令遵循模型更可见。
|
|
266
|
+
input.mentionedFilesReminder ?? '',
|
|
226
267
|
// R17:会话内记忆尾注。放最后——它是最"新"的信息,且每轮可能不同,
|
|
227
268
|
// 放在固定段之后能最大限度保住前缀缓存的可复用部分。
|
|
228
269
|
opts.memoryTail ?? '',
|
|
270
|
+
input.liveUpdateReminder ?? '',
|
|
271
|
+
input.noProgressReminder ?? '',
|
|
229
272
|
]
|
|
230
273
|
.filter(Boolean)
|
|
231
274
|
.join('\n\n');
|
|
@@ -557,7 +600,8 @@ export async function runModelTurn(input) {
|
|
|
557
600
|
ephemeralText: requestEphemeral,
|
|
558
601
|
};
|
|
559
602
|
}
|
|
560
|
-
|
|
603
|
+
if (!input.opening || !result.toolCalls.length)
|
|
604
|
+
hooks.onChatDone?.();
|
|
561
605
|
onContextUpdate?.();
|
|
562
606
|
return { kind: 'result', result, stream };
|
|
563
607
|
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
const WINDOW_STEPS = 6;
|
|
3
|
+
const REPEATED_STEPS = 3;
|
|
4
|
+
const MAX_REMINDERS = 3;
|
|
5
|
+
/** 每次模型决策只计一轮。观察重复的结果或错误类型,工具本身始终照常执行。 */
|
|
6
|
+
export class TurnProgressGuard {
|
|
7
|
+
recent = [];
|
|
8
|
+
current;
|
|
9
|
+
remindersSent = 0;
|
|
10
|
+
record(tool, argsHash, outcome) {
|
|
11
|
+
if (this.remindersSent >= MAX_REMINDERS || outcome.status === 'aborted')
|
|
12
|
+
return;
|
|
13
|
+
const step = (this.current ??= {
|
|
14
|
+
successes: new Set(),
|
|
15
|
+
failures: new Set(),
|
|
16
|
+
observedChange: false,
|
|
17
|
+
committed: false,
|
|
18
|
+
});
|
|
19
|
+
if (outcome.status !== 'success') {
|
|
20
|
+
step.failures.add(`${tool} (${outcome.code})`);
|
|
21
|
+
}
|
|
22
|
+
else if (outcome.changeSet?.changedFiles.length) {
|
|
23
|
+
step.committed = true;
|
|
24
|
+
}
|
|
25
|
+
else if (outcome.changedFiles?.length || outcome.modelAttachments?.length) {
|
|
26
|
+
// 进程周围的文件扫描也能看到外部写入。保留本批观察,但只有明确提交的改动重置历史。
|
|
27
|
+
step.observedChange = true;
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
const hash = createHash('sha256').update(outcome.output).digest('hex');
|
|
31
|
+
step.successes.add(`${tool}/${argsHash}/${hash}`);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** 下一次模型请求前结算整批。并行工具的完成顺序不影响判断。 */
|
|
35
|
+
takeReminder() {
|
|
36
|
+
const step = this.current;
|
|
37
|
+
if (!step)
|
|
38
|
+
return;
|
|
39
|
+
this.current = undefined;
|
|
40
|
+
if (step.committed) {
|
|
41
|
+
this.recent = [];
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
if (this.recent.length === WINDOW_STEPS)
|
|
45
|
+
this.recent.shift();
|
|
46
|
+
const previous = this.recent.slice();
|
|
47
|
+
this.recent.push(step);
|
|
48
|
+
if (step.observedChange || previous.length < REPEATED_STEPS - 1)
|
|
49
|
+
return;
|
|
50
|
+
if ([...step.successes].some((key) => !previous.some((s) => s.successes.has(key))))
|
|
51
|
+
return;
|
|
52
|
+
const repeated = (key, kind) => previous.filter((s) => s[kind].has(key)).length >= REPEATED_STEPS - 1;
|
|
53
|
+
const failure = [...step.failures].find((key) => repeated(key, 'failures'));
|
|
54
|
+
const repeatedResult = [...step.successes].some((key) => repeated(key, 'successes'));
|
|
55
|
+
if (!failure && !repeatedResult)
|
|
56
|
+
return;
|
|
57
|
+
this.remindersSent++;
|
|
58
|
+
this.recent = [];
|
|
59
|
+
const evidence = failure ? `${failure} recurred` : 'The same call returned the same result';
|
|
60
|
+
return (`## Repeated tool results\n${evidence} on at least ${REPEATED_STEPS} recent model steps. ` +
|
|
61
|
+
'Use the evidence already gathered. If the requested outcome is verified, finish. ' +
|
|
62
|
+
'Otherwise choose a check or action that can resolve the remaining uncertainty.');
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
export function createTurnProgressGuard() {
|
|
66
|
+
return new TurnProgressGuard();
|
|
67
|
+
}
|
|
@@ -4,23 +4,28 @@
|
|
|
4
4
|
//
|
|
5
5
|
// 与 index.ts 的关系:index.ts 的 runAgent = runAgentCore + TUI hooks 薄封装(行为不变)。
|
|
6
6
|
// spawn.ts 的 spawnAgent = runAgentCore + 静默 hooks(子 agent)。
|
|
7
|
+
import { estimateTokens } from '../llm/index.js';
|
|
7
8
|
import { validateToolArguments } from '../tools/validation.js';
|
|
8
9
|
import { getPlanDisabledTools, getRuntimeDisabledTools, getSkillRuntimeDisabledTools } from '../tools/constants.js';
|
|
9
10
|
import { isMemoryEnabled } from '../config/index.js';
|
|
10
11
|
import { isProactiveEnabled, proactiveHint } from '../memory/proactive.js';
|
|
11
12
|
import { ADD_TOOL_GROUPS_TOOL_NAME } from '../config/profiles.js';
|
|
12
13
|
import { defaultAgentRuntimeContext } from './runtime-context.js';
|
|
14
|
+
import { buildMentionedFilesReminder } from './mentioned-files.js';
|
|
13
15
|
import { runModelTurn } from './model-turn.js';
|
|
14
16
|
import { runToolTurn } from './tool-turn.js';
|
|
17
|
+
import { createShortPathCompletion } from './short-path-completion.js';
|
|
15
18
|
import { createTurnLifecycle } from './turn-lifecycle.js';
|
|
16
19
|
import { parseArgs, argumentErrorHint, isParallelTool, isParallelOrchestrationCall, isResourceLockedCall, deniedOutcome, readDiffContext, pushToolResult, unregisteredToolOutcome, } from './tool-helpers.js';
|
|
17
20
|
import { contextState, summarizeToolArguments } from '../session/index.js';
|
|
18
21
|
import { createReadDedup } from '../tools/read-dedup.js';
|
|
22
|
+
import { createTurnProgressGuard } from './progress-guard.js';
|
|
19
23
|
import { createBudgetScheduler } from '../session/scheduler.js';
|
|
20
24
|
import { invalidateArtifacts, rehydrateArtifacts } from '../context/index.js';
|
|
21
25
|
import { createRelevancePruner } from '../context/relevance.js';
|
|
22
26
|
import { t } from '../i18n/index.js';
|
|
23
27
|
import { createLifecycleEngine } from '../context/lifecycle.js';
|
|
28
|
+
import { capToolResultForHistory } from '../session/compact.js';
|
|
24
29
|
import { createLegacyModelRunner, createStagedModelRunner } from './stages/model-runner.js';
|
|
25
30
|
import { createLegacyContextTrimmer, createStagedContextTrimmer } from './stages/context-trimmer.js';
|
|
26
31
|
import { createLegacyToolDispatcher, createStagedToolDispatcher } from './stages/tool-dispatcher.js';
|
|
@@ -58,6 +63,9 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
58
63
|
// `memory-recall-stats.json` 正常写入)。包一层执行出口而非逐处插桩,5 个调度分支
|
|
59
64
|
// (只读并发 / 串行 / 资源锁 / 编排 / 兜底)自然全覆盖。
|
|
60
65
|
const proactiveOn = isMemoryEnabled() && isProactiveEnabled();
|
|
66
|
+
// #convergence A:本轮的无进展观测器。与 readDedup 同属 turn scope——同一用户轮内
|
|
67
|
+
// 才有「你在原地打转」这个语义,跨轮谈不到。
|
|
68
|
+
const progressGuard = createTurnProgressGuard();
|
|
61
69
|
const runToolWithProactive = async (name, argsRaw, sig, execOpts) => {
|
|
62
70
|
const outcome = await ctx.toolRuntime.executeToolOutcome(name, argsRaw, sig, execOpts);
|
|
63
71
|
if (!proactiveOn)
|
|
@@ -75,6 +83,14 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
75
83
|
// core 不读记忆库,否则每个 agent 单测都会去读真实的 ~/.mocode/memory.jsonl,
|
|
76
84
|
// 测试既失去隔离性、断言也会被本机记忆内容污染;spawn 不传即天然零注入。
|
|
77
85
|
const memoryRecall = opts.memoryRecall ?? '';
|
|
86
|
+
// 短路径优化:从本用户轮文本确定性提取已知名文件(存在性过滤),生成 ephemeral
|
|
87
|
+
// 近因提示。只对 string/含 text part 的输入生效;cwd 即 workspace(REPL 与 eval 一致)。
|
|
88
|
+
const mentionedFilesReminder = buildMentionedFilesReminder(typeof opts.userInput === 'string'
|
|
89
|
+
? opts.userInput
|
|
90
|
+
: opts.userInput
|
|
91
|
+
.filter((part) => part.type === 'text')
|
|
92
|
+
.map((part) => part.text)
|
|
93
|
+
.join('\n'), process.cwd());
|
|
78
94
|
const runtimeToolSchemas = ctx.toolRuntime.tools.map((tool) => ({
|
|
79
95
|
type: 'function',
|
|
80
96
|
function: {
|
|
@@ -92,6 +108,14 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
92
108
|
// 中断还原:repl 的 /plan / /auto / Shift+Tab 等用户面触发 setAgentMode 中途切了模式,
|
|
93
109
|
// abort 时连同模式一起还原回轮首。模型不再持有 switch_mode 工具,无法自切。
|
|
94
110
|
const savedMode = ctx.getAgentMode();
|
|
111
|
+
const shortPath = ctx.config.shortPathCompletion &&
|
|
112
|
+
savedMode === 'auto' &&
|
|
113
|
+
!opts.continueFromHistory &&
|
|
114
|
+
!opts.suppressOpeningAnalysis &&
|
|
115
|
+
typeof userInput === 'string'
|
|
116
|
+
? createShortPathCompletion(userInput, ctx)
|
|
117
|
+
: undefined;
|
|
118
|
+
let shortPathCompleted = false;
|
|
95
119
|
const turnLifecycle = createTurnLifecycle(opts, ctx, stages, savedMode);
|
|
96
120
|
const { usageMeter, emitTrace, traceTurnId } = turnLifecycle;
|
|
97
121
|
const toolTurnPlanState = { stepsSincePlanTouch: 0 };
|
|
@@ -106,10 +130,19 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
106
130
|
let lifecycle = ctx.config.contextLifecycle ? createLifecycleEngine(history) : null;
|
|
107
131
|
runtimeContextState.lifecycleStats = lifecycle?.stats();
|
|
108
132
|
rehydrateArtifacts(runtimeContextState, history);
|
|
133
|
+
// CompactionRuntime 是 session 层的最小依赖面(压缩只看 config / transport / rollback),
|
|
134
|
+
// 这里额外把 hooks.onCompactProgress 转发进去:压缩发生在 session 层,拿不到 AgentHooks,
|
|
135
|
+
// 而「压缩开始了/结束了」正是 work-app 里唯一能让用户感知到自动压缩的信号。
|
|
136
|
+
const compactionRuntime = {
|
|
137
|
+
config: ctx.config,
|
|
138
|
+
modelTransport: ctx.modelTransport,
|
|
139
|
+
rollbackStore: ctx.rollbackStore,
|
|
140
|
+
onCompactProgress: (event) => opts.hooks.onCompactProgress?.(event),
|
|
141
|
+
};
|
|
109
142
|
// The scheduler is the sole automatic history-rewrite entry point. It runs
|
|
110
143
|
// superseded → stale artifact → old logs/search → compact at real pressure.
|
|
111
144
|
// contextBudget=false keeps only the infrastructure compact fallback.
|
|
112
|
-
const scheduler = ctx.config.contextBudget !== false ? createBudgetScheduler(runtimeContextState,
|
|
145
|
+
const scheduler = ctx.config.contextBudget !== false ? createBudgetScheduler(runtimeContextState, compactionRuntime) : null;
|
|
113
146
|
const modelRunner = stages.model.implementation === 'staged'
|
|
114
147
|
? createStagedModelRunner(ctx.modelTransport)
|
|
115
148
|
: createLegacyModelRunner(ctx.modelTransport);
|
|
@@ -125,7 +158,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
125
158
|
? createStagedCapabilityResolver()
|
|
126
159
|
: createLegacyCapabilityResolver();
|
|
127
160
|
const terminationPolicy = stages.termination.implementation === 'staged' ? createStagedTerminationPolicy() : createLegacyTerminationPolicy();
|
|
128
|
-
const trimmerInit = { historyManager, scheduler, contextState: runtimeContextState, runtime:
|
|
161
|
+
const trimmerInit = { historyManager, scheduler, contextState: runtimeContextState, runtime: compactionRuntime };
|
|
129
162
|
const contextTrimmer = stages.context.implementation === 'staged'
|
|
130
163
|
? createStagedContextTrimmer(trimmerInit)
|
|
131
164
|
: createLegacyContextTrimmer(trimmerInit);
|
|
@@ -139,6 +172,38 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
139
172
|
const modelCacheState = { lastStepPromptTokens: 0, providerCacheSeen: false };
|
|
140
173
|
const cancellationLifecycle = turnLifecycle.createCancellation(historyManager, rebuildHistoryIndexes);
|
|
141
174
|
cancellationLifecycle.checkpoint();
|
|
175
|
+
let hasLiveUserUpdates = false;
|
|
176
|
+
let steeringOpeningPending = false;
|
|
177
|
+
const liveUpdateReminder = '## Live user updates — continue the current task\n' +
|
|
178
|
+
'The user sent additional messages while this task was running. Treat these messages as updates to the same ongoing task. ' +
|
|
179
|
+
'Consider the original request and all subsequent user updates together, preserving earlier requirements that were not changed. ' +
|
|
180
|
+
'Use the existing conversation, completed work, and tool results to continue from the current progress. ' +
|
|
181
|
+
'Apply newer corrections where they conflict with earlier requirements. Do not abandon unfinished work or restart from scratch merely because a new message arrived. ' +
|
|
182
|
+
'Only stop or replace the original task when the user explicitly asks to cancel, stop, or switch tasks. ' +
|
|
183
|
+
'Before the final response, check that both the original request and the applicable updates have been addressed.';
|
|
184
|
+
const acceptUserMessages = () => {
|
|
185
|
+
const messages = opts.drainUserMessages?.() ?? [];
|
|
186
|
+
for (const content of messages)
|
|
187
|
+
historyManager.appendUserTurn(content);
|
|
188
|
+
if (messages.length > 0) {
|
|
189
|
+
hasLiveUserUpdates = true;
|
|
190
|
+
steeringOpeningPending = true;
|
|
191
|
+
cancellationLifecycle.checkpoint();
|
|
192
|
+
hooks.onCheckpoint?.(history);
|
|
193
|
+
}
|
|
194
|
+
return messages.length > 0;
|
|
195
|
+
};
|
|
196
|
+
const completeTurn = (finalText) => {
|
|
197
|
+
const finalMutation = ctx.getCurrentTurnMutationState();
|
|
198
|
+
turnLifecycle.markCompleted();
|
|
199
|
+
return {
|
|
200
|
+
completed: true,
|
|
201
|
+
terminationReason: 'completed',
|
|
202
|
+
finalText,
|
|
203
|
+
usage: usageMeter.snapshot(),
|
|
204
|
+
changedFiles: finalMutation.changedFiles.map((item) => item.path),
|
|
205
|
+
};
|
|
206
|
+
};
|
|
142
207
|
try {
|
|
143
208
|
for (let step = 0; step < maxSteps; step++) {
|
|
144
209
|
turnLifecycle.setCurrentStep(step);
|
|
@@ -157,6 +222,15 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
157
222
|
turnLifecycle.markAborted();
|
|
158
223
|
return turnLifecycle.buildAbortedResult();
|
|
159
224
|
}
|
|
225
|
+
acceptUserMessages();
|
|
226
|
+
const opening = opts.suppressOpeningAnalysis
|
|
227
|
+
? undefined
|
|
228
|
+
: steeringOpeningPending
|
|
229
|
+
? 'steering'
|
|
230
|
+
: step === 0
|
|
231
|
+
? 'initial'
|
|
232
|
+
: undefined;
|
|
233
|
+
steeringOpeningPending = false;
|
|
160
234
|
// 本步只捕获一次不可变 policy snapshot。即便 add_tool_groups 在执行阶段扩容,
|
|
161
235
|
// 本次模型响应仍必须按旧 snapshot 校验;新工具只在下一 step 的 schema 中出现。
|
|
162
236
|
const planMode = ctx.getAgentMode() === 'plan';
|
|
@@ -208,9 +282,14 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
208
282
|
activeTools,
|
|
209
283
|
runPolicy,
|
|
210
284
|
step,
|
|
285
|
+
opening,
|
|
211
286
|
maxSteps,
|
|
212
287
|
readDedup,
|
|
213
288
|
memoryRecall,
|
|
289
|
+
mentionedFilesReminder,
|
|
290
|
+
liveUpdateReminder: hasLiveUserUpdates ? liveUpdateReminder : undefined,
|
|
291
|
+
// #convergence A:一次性提醒,取走即清空;未踩线时是 undefined。
|
|
292
|
+
noProgressReminder: progressGuard.takeReminder(),
|
|
214
293
|
cacheState: modelCacheState,
|
|
215
294
|
turnLifecycle,
|
|
216
295
|
cancellationLifecycle,
|
|
@@ -228,6 +307,9 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
228
307
|
modelResult: result,
|
|
229
308
|
});
|
|
230
309
|
if (modelDecision.kind === 'continue') {
|
|
310
|
+
if (result.toolCalls.length !== 1 || result.finishReason === 'length') {
|
|
311
|
+
shortPath?.reject('unexpected_tool');
|
|
312
|
+
}
|
|
231
313
|
await runToolTurn({
|
|
232
314
|
opts,
|
|
233
315
|
ctx,
|
|
@@ -235,6 +317,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
235
317
|
result,
|
|
236
318
|
stream,
|
|
237
319
|
step,
|
|
320
|
+
opening,
|
|
238
321
|
maxSteps,
|
|
239
322
|
planState: toolTurnPlanState,
|
|
240
323
|
turnLifecycle,
|
|
@@ -304,6 +387,8 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
304
387
|
break;
|
|
305
388
|
case 'trace_end': {
|
|
306
389
|
const { outcome, call } = event;
|
|
390
|
+
shortPath?.observe(call, outcome);
|
|
391
|
+
progressGuard.record(call.name, event.argumentSummary.sha256, outcome);
|
|
307
392
|
emitTrace('tool_call_end', {
|
|
308
393
|
tool: call.name,
|
|
309
394
|
argumentHash: event.argumentSummary.sha256,
|
|
@@ -311,6 +396,8 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
311
396
|
code: outcome.code,
|
|
312
397
|
retryable: outcome.retryable,
|
|
313
398
|
durationMs: outcome.durationMs ?? 0,
|
|
399
|
+
outputTokensEstimate: estimateTokens(capToolResultForHistory(call.name, outcome.output)),
|
|
400
|
+
...(outcome.commandTiming ? { commandTiming: outcome.commandTiming } : {}),
|
|
314
401
|
changedFiles: outcome.changedFiles ?? [],
|
|
315
402
|
staleFiles: outcome.staleFiles ?? [],
|
|
316
403
|
...(outcome.changeSet ? { changeSet: outcome.changeSet } : {}),
|
|
@@ -389,10 +476,12 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
389
476
|
});
|
|
390
477
|
}
|
|
391
478
|
const traceToolEnd = (tc, index, outcome) => {
|
|
479
|
+
shortPath?.observe(tc, outcome);
|
|
392
480
|
if (outcome.status === 'success' && outcome.modelAttachments?.length) {
|
|
393
481
|
modelAttachments.push(...outcome.modelAttachments);
|
|
394
482
|
}
|
|
395
483
|
const traceCall = tracedCalls[index];
|
|
484
|
+
progressGuard.record(tc.name, traceCall.args.sha256, outcome);
|
|
396
485
|
emitTrace('tool_call_end', {
|
|
397
486
|
tool: tc.name,
|
|
398
487
|
argumentHash: traceCall.args.sha256,
|
|
@@ -400,6 +489,8 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
400
489
|
code: outcome.code,
|
|
401
490
|
retryable: outcome.retryable,
|
|
402
491
|
durationMs: outcome.durationMs ?? 0,
|
|
492
|
+
outputTokensEstimate: estimateTokens(capToolResultForHistory(tc.name, outcome.output)),
|
|
493
|
+
...(outcome.commandTiming ? { commandTiming: outcome.commandTiming } : {}),
|
|
403
494
|
changedFiles: outcome.changedFiles ?? [],
|
|
404
495
|
staleFiles: outcome.staleFiles ?? [],
|
|
405
496
|
...(outcome.changeSet ? { changeSet: outcome.changeSet } : {}),
|
|
@@ -932,6 +1023,36 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
932
1023
|
}
|
|
933
1024
|
},
|
|
934
1025
|
});
|
|
1026
|
+
if (shortPath && !shortPath.fallback) {
|
|
1027
|
+
if (step === 0 && (!stream.gotText || !result.content?.trim()))
|
|
1028
|
+
shortPath.reject('opening_missing');
|
|
1029
|
+
if (hasLiveUserUpdates)
|
|
1030
|
+
shortPath.reject('user_update');
|
|
1031
|
+
if (signal?.aborted || ctx.getAgentMode() !== 'auto' || step + 1 >= maxSteps) {
|
|
1032
|
+
shortPath.reject('turn_state_changed');
|
|
1033
|
+
}
|
|
1034
|
+
const finalText = shortPath.finalText();
|
|
1035
|
+
if (finalText) {
|
|
1036
|
+
if (acceptUserMessages())
|
|
1037
|
+
shortPath.reject('user_update');
|
|
1038
|
+
else if (signal?.aborted || ctx.getAgentMode() !== 'auto' || ctx.extractActivePlanSection()) {
|
|
1039
|
+
shortPath.reject('turn_state_changed');
|
|
1040
|
+
}
|
|
1041
|
+
else {
|
|
1042
|
+
hooks.onText?.(finalText);
|
|
1043
|
+
hooks.onTextEnd?.();
|
|
1044
|
+
historyManager.appendAssistantTurn({ content: finalText, toolCalls: [] });
|
|
1045
|
+
if (acceptUserMessages())
|
|
1046
|
+
shortPath.reject('user_update');
|
|
1047
|
+
else if (signal?.aborted)
|
|
1048
|
+
shortPath.reject('turn_state_changed');
|
|
1049
|
+
else {
|
|
1050
|
+
shortPathCompleted = true;
|
|
1051
|
+
return completeTurn(finalText);
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
935
1056
|
continue; // 带着工具结果再调一次 LLM
|
|
936
1057
|
}
|
|
937
1058
|
if (modelDecision.kind !== 'completed') {
|
|
@@ -943,16 +1064,15 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
943
1064
|
// 也不因缺少验证证据强制追加模型轮次;agent 仍可自行调用工具验证。
|
|
944
1065
|
if (!gotText)
|
|
945
1066
|
hooks.onNoReply?.();
|
|
946
|
-
historyManager.appendAssistantTurn({
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
};
|
|
1067
|
+
historyManager.appendAssistantTurn({
|
|
1068
|
+
content: result.content,
|
|
1069
|
+
toolCalls: [],
|
|
1070
|
+
reasoningContent: result.reasoningContent,
|
|
1071
|
+
});
|
|
1072
|
+
// A user update received during the final stream keeps this run alive.
|
|
1073
|
+
if (acceptUserMessages())
|
|
1074
|
+
continue;
|
|
1075
|
+
return completeTurn(modelDecision.finalText);
|
|
956
1076
|
}
|
|
957
1077
|
finally {
|
|
958
1078
|
emitTrace('step_end', {
|
|
@@ -1019,6 +1139,14 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
1019
1139
|
};
|
|
1020
1140
|
}
|
|
1021
1141
|
finally {
|
|
1142
|
+
if (shortPath) {
|
|
1143
|
+
emitTrace('short_path_completion', shortPathCompleted
|
|
1144
|
+
? { status: 'completed' }
|
|
1145
|
+
: {
|
|
1146
|
+
status: 'fallback',
|
|
1147
|
+
reason: shortPath.fallback ?? (signal?.aborted ? 'turn_state_changed' : 'model_finished'),
|
|
1148
|
+
});
|
|
1149
|
+
}
|
|
1022
1150
|
turnLifecycle.finalize();
|
|
1023
1151
|
}
|
|
1024
1152
|
}
|