mocode-ai 1.10.0 → 1.11.0
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 +18 -7
- package/dist/agent/mentioned-files.js +71 -0
- package/dist/agent/model-turn.js +68 -30
- package/dist/agent/progress-guard.js +67 -0
- package/dist/agent/run-coordinator.js +155 -24
- package/dist/agent/short-path-completion.js +109 -0
- package/dist/agent/spawn.js +43 -0
- package/dist/agent/stages/history-manager.js +1 -0
- package/dist/agent/stages/tool-dispatcher.js +6 -3
- package/dist/agent/tool-helpers.js +2 -2
- package/dist/agent/tool-turn.js +49 -4
- package/dist/agent/work-discipline.js +12 -9
- package/dist/changeset/index.js +2 -1
- package/dist/config/index.js +12 -10
- package/dist/context/overlapping-reads.js +66 -0
- package/dist/context/relevance.js +11 -2
- package/dist/context/usage-snapshot.js +9 -6
- package/dist/host/stdio.js +96 -42
- 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/memory/index.js +1 -1
- package/dist/memory/tail.js +9 -26
- 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 +119 -77
- package/dist/rollback/index.js +2 -2
- package/dist/rollback/store.js +73 -38
- 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 +79 -19
- package/dist/tools/builtins/grep.js +161 -42
- package/dist/tools/builtins/plan-update.js +4 -2
- package/dist/tools/builtins/read-file.js +148 -55
- package/dist/tools/builtins/run-command.js +57 -9
- package/dist/tools/ripgrep-client.js +72 -26
- 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/render.js +3 -0
- package/dist/ui/spinner.js +3 -1
- package/dist/verification/evidence.js +52 -0
- package/package.json +4 -2
package/dist/agent/index.js
CHANGED
|
@@ -15,9 +15,8 @@ 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
|
-
import { memoryTailChangedIds } from '../memory/tail.js';
|
|
21
20
|
import { createHandoffStripper, handoffDisplaySuppressed } from '../ui/handoff-block.js';
|
|
22
21
|
/** 当前 turn 的 batch id(runAgent 内闭包变量;一条 turn 一轮 tool batch 结束即清空)。 */
|
|
23
22
|
let currentBatchId = null;
|
|
@@ -308,7 +307,7 @@ initialToolRoute,
|
|
|
308
307
|
*/
|
|
309
308
|
memoryTail,
|
|
310
309
|
/** TUI composition root 绑定的 Runtime;旧调用传 AgentRuntimeContext 仍兼容。 */
|
|
311
|
-
runtimeOrContext = defaultRuntime) {
|
|
310
|
+
runtimeOrContext = defaultRuntime, drainUserMessages, transcript) {
|
|
312
311
|
const runtime = runtimeOrContext instanceof Runtime
|
|
313
312
|
? runtimeOrContext
|
|
314
313
|
: runtimeOrContext === defaultAgentRuntimeContext
|
|
@@ -382,6 +381,7 @@ runtimeOrContext = defaultRuntime) {
|
|
|
382
381
|
layout.normalizeMutationBoundary();
|
|
383
382
|
spinner.stop(); // 任何正文 token 都停 spinner(首 token 停「思考中」;onToolCall 重启后若又来文本则停「生成中」)。未旋转时 stop 为 no-op。
|
|
384
383
|
layout.contentWriteMd(visible); // 正文走 markdown 渲染(代码块高亮 / 标题 / 列表 / 行内 …),见 ui/markdown.ts
|
|
384
|
+
transcript?.addText(visible);
|
|
385
385
|
if (visible) {
|
|
386
386
|
lastChar = visible[visible.length - 1];
|
|
387
387
|
if (visible.trim().length > 0) {
|
|
@@ -487,7 +487,15 @@ runtimeOrContext = defaultRuntime) {
|
|
|
487
487
|
onToolStart: (name) => spinner.start(t('agent.executing', { tool: name })),
|
|
488
488
|
onToolOutput: (tc, chunk) => batch.recordOutput(tc.id, chunk, layout),
|
|
489
489
|
onToolDone: () => spinner.stop(),
|
|
490
|
-
onToolResult: (tc, output, parsed, preWriteOld, editStartLine, multiHunks) =>
|
|
490
|
+
onToolResult: (tc, output, parsed, preWriteOld, editStartLine, multiHunks) => {
|
|
491
|
+
if (transcript)
|
|
492
|
+
transcript.addTool(tc, capToolResultForHistory(tc.name, output));
|
|
493
|
+
writeToolResult(tc, output, parsed, preWriteOld, editStartLine, runtime.context.toolRuntime, multiHunks);
|
|
494
|
+
},
|
|
495
|
+
onCompactProgress: (event) => {
|
|
496
|
+
if (event.phase === 'done' && event.compacted)
|
|
497
|
+
transcript?.compacted();
|
|
498
|
+
},
|
|
491
499
|
onToolBatchEnd: () => {
|
|
492
500
|
// 一次工具轮次结束不再切 UI batch;下一轮若仍无正文,继续复用 currentBatchId。
|
|
493
501
|
},
|
|
@@ -530,7 +538,7 @@ runtimeOrContext = defaultRuntime) {
|
|
|
530
538
|
// ① runAgent 是 TUI 组合根,只有真实用户轮会走到;runAgentCore 被全部 agent 单测
|
|
531
539
|
// 直接调用,在那儿读记忆库会让测试读到本机真实记忆、失去隔离性;
|
|
532
540
|
// ② spawn 走 runtime.run 不经过这里,子 agent 天然零注入。
|
|
533
|
-
//
|
|
541
|
+
// R17 尾注的正文和排除集来自同一份快照。
|
|
534
542
|
const userText = Array.isArray(userInput)
|
|
535
543
|
? userInput
|
|
536
544
|
.filter((part) => part.type === 'text')
|
|
@@ -538,7 +546,9 @@ runtimeOrContext = defaultRuntime) {
|
|
|
538
546
|
.join(' ')
|
|
539
547
|
: userInput;
|
|
540
548
|
const memoryRecall = isMemoryEnabled() && isTurnRecallEnabled()
|
|
541
|
-
? buildTurnRecallSection(userText, {
|
|
549
|
+
? buildTurnRecallSection(userText, {
|
|
550
|
+
excludeIds: typeof memoryTail === 'string' ? undefined : memoryTail?.shownIds,
|
|
551
|
+
})
|
|
542
552
|
: '';
|
|
543
553
|
try {
|
|
544
554
|
result = await runtime.run({
|
|
@@ -546,12 +556,13 @@ runtimeOrContext = defaultRuntime) {
|
|
|
546
556
|
turnLabel: truncateDisplay(firstLineOf(userInput), 40),
|
|
547
557
|
history,
|
|
548
558
|
userInput,
|
|
559
|
+
drainUserMessages,
|
|
549
560
|
signal,
|
|
550
561
|
onContextUpdate,
|
|
551
562
|
hooks: combinedHooks,
|
|
552
563
|
toolPolicy,
|
|
553
564
|
initialToolRoute,
|
|
554
|
-
memoryTail,
|
|
565
|
+
memoryTail: typeof memoryTail === 'string' ? memoryTail : memoryTail?.text,
|
|
555
566
|
memoryRecall,
|
|
556
567
|
onTraceEvent: appendCurrentSessionTraceEvent,
|
|
557
568
|
});
|
|
@@ -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
|
@@ -3,6 +3,7 @@ import { imageTurnAgingEnabled, visionBatch, visionKeep } from '../config/index.
|
|
|
3
3
|
import { estimateRequestBytes, learnRequestByteLimit, requestByteLimit } from '../context/request-limit.js';
|
|
4
4
|
import { createImageDescriber, relieveRequestBytes } from './request-governor.js';
|
|
5
5
|
import { countOversizedImages } from '../context/vision-window.js';
|
|
6
|
+
import { compactOverlappingReads } from '../context/overlapping-reads.js';
|
|
6
7
|
import { getActiveSessionStore } from '../session/store.js';
|
|
7
8
|
import { getCurrentSessionId } from '../session/state.js';
|
|
8
9
|
import { appendGlobalUsage } from '../session/global-usage.js';
|
|
@@ -43,7 +44,16 @@ export async function runModelTurn(input) {
|
|
|
43
44
|
// 与压缩压力线会持续低估(召回段 + 尾注的字数并不小)。
|
|
44
45
|
const memoryRecallText = input.memoryRecall ?? '';
|
|
45
46
|
const memoryTailText = opts.memoryTail ?? '';
|
|
46
|
-
const ephemeralJoined = () => [
|
|
47
|
+
const ephemeralJoined = () => [
|
|
48
|
+
sessionStateText,
|
|
49
|
+
memoryRecallText,
|
|
50
|
+
memoryTailText,
|
|
51
|
+
input.mentionedFilesReminder ?? '',
|
|
52
|
+
input.liveUpdateReminder ?? '',
|
|
53
|
+
input.noProgressReminder ?? '',
|
|
54
|
+
]
|
|
55
|
+
.filter((s) => s.length > 0)
|
|
56
|
+
.join('\n\n');
|
|
47
57
|
/** 与 ephemeralJoined() 同源,保证「发了多少」与「算多大」永不漂移。 */
|
|
48
58
|
const ephemeralTokenEstimate = () => {
|
|
49
59
|
const joined = ephemeralJoined();
|
|
@@ -166,7 +176,9 @@ export async function runModelTurn(input) {
|
|
|
166
176
|
// 流中即发 onTextEnd 会让 UI 在词中间硬换行并封死 markdown 段(「继续通读:d / ispatcher」
|
|
167
177
|
// 断词 bug)。onToolCall 此刻只驱动「生成中」spinner;正文收尾换行统一由流末
|
|
168
178
|
// (tool-turn / run-coordinator)依据 stream.lastChar 发一次 onTextEnd,届时全部 content 已到齐。
|
|
169
|
-
|
|
179
|
+
// 新任务或收到引导后的首步,从 tool-turn 发开场后的工具状态。
|
|
180
|
+
if (!input.opening)
|
|
181
|
+
hooks.onToolCall?.(name);
|
|
170
182
|
};
|
|
171
183
|
let result;
|
|
172
184
|
const modelStartedAt = Date.now();
|
|
@@ -176,34 +188,53 @@ export async function runModelTurn(input) {
|
|
|
176
188
|
const remainingSteps = maxSteps - step;
|
|
177
189
|
const ephemeralReminder = [
|
|
178
190
|
runPolicy.reminder,
|
|
179
|
-
//
|
|
180
|
-
//
|
|
181
|
-
|
|
182
|
-
// (实测:同一结论换个措辞每步复述一遍,屏幕上像卡死循环)。
|
|
183
|
-
// step 0 由 Opening analysis 独自承担:那里既没有工具结果可复述,也没有"已说过的观点",
|
|
184
|
-
// 而"能直接答就直接答"的授权已写在 Answer-first 里,本段三条约束在 step 0 均无对象。
|
|
185
|
-
// 子 agent 静默执行、不写屏,沿用 suppressOpeningAnalysis 一并免注入。
|
|
186
|
-
!opts.suppressOpeningAnalysis && step > 0
|
|
191
|
+
// 主 agent 在后续请求中就近约束工具期间的正文。首轮与引导开场由各自的动态段负责。
|
|
192
|
+
// 子 agent 由委派提示约束静默,本段随 suppressOpeningAnalysis 跳过。
|
|
193
|
+
!opts.suppressOpeningAnalysis && step > 0 && !input.opening
|
|
187
194
|
? '## Silent work\n' +
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
'
|
|
192
|
-
'
|
|
193
|
-
'
|
|
194
|
-
'the same conclusion read to the user as a stuck loop. If something genuinely must be said ' +
|
|
195
|
-
'mid-task (a blocking decision, or a finding that changes what happens next), say it in one ' +
|
|
196
|
-
'short sentence and keep going. Never repeat a point already made in this turn. Text is for: ' +
|
|
197
|
-
"direct answers to the user's questions, blocking questions, " +
|
|
198
|
-
'findings that change the next action, and the final report.'
|
|
195
|
+
'When continuing independently with tools, emit only tool calls. ' +
|
|
196
|
+
'Handle findings, recoverable errors, and verification silently. ' +
|
|
197
|
+
'If you need user input to proceed, ask one concise question. ' +
|
|
198
|
+
'Use `ask_human` when available, or ask in a text-only reply and wait. ' +
|
|
199
|
+
'Answer direct questions and save material findings for the final report. ' +
|
|
200
|
+
'Never repeat a point already made in this turn.'
|
|
199
201
|
: '',
|
|
200
|
-
// 仅 step 0
|
|
201
|
-
//
|
|
202
|
-
//
|
|
203
|
-
//
|
|
204
|
-
//
|
|
205
|
-
|
|
206
|
-
? '## Opening analysis\
|
|
202
|
+
// 仅 step 0:就近重申 Answer-first,并保留「开场一句」这条祈使要求。
|
|
203
|
+
// 859b974 曾把它改写成条件句(only when ... needs a user decision or complex),
|
|
204
|
+
// 于是「清晰的小改动」全被划进「直接调工具」一档,开场白彻底消失——那句原本无条件的
|
|
205
|
+
// 祈使主语在重写时丢了。这里把「先说一句」恢复成无条件的,Answer-first 只决定这一句
|
|
206
|
+
// 之后是回答还是动手,不再决定说不说。
|
|
207
|
+
input.opening === 'initial'
|
|
208
|
+
? '## Opening analysis\n' +
|
|
209
|
+
'Before your first tool call in every user-facing turn, you MUST output exactly one short visible sentence ' +
|
|
210
|
+
'telling the user what you will check or change first and what it will help you establish. ' +
|
|
211
|
+
'Use plain language and put the sentence first in the SAME assistant response as the tool calls. ' +
|
|
212
|
+
'If no tools are needed, answer directly. ' +
|
|
213
|
+
'If the task already warrants a new plan and `plan_update` is available, make it your first tool call. ' +
|
|
214
|
+
'After this opening, work silently.'
|
|
215
|
+
: '',
|
|
216
|
+
input.opening === 'steering'
|
|
217
|
+
? '## Steering opening\n' +
|
|
218
|
+
'If you need tools after the latest user updates, start the same response with one short visible sentence ' +
|
|
219
|
+
'explaining how the update changes what you will do next. Continue from the work already done. ' +
|
|
220
|
+
'If you can answer directly, do so. After the opening, work silently.'
|
|
221
|
+
: '',
|
|
222
|
+
// 就近重申 Answer-first。动机(2026-11-18):用户反馈「很简单的问题也要兜一大圈」。
|
|
223
|
+
// history[0] 的 Workflow 里已有 Answer first,但它离当前决策最远,而每轮都在的
|
|
224
|
+
// 具体指令(codegraph 段、知识图谱段、「Do not stop prematurely」)更容易被遵守,
|
|
225
|
+
// 结果是「一句话能答的问题先跑三条 grep」。ephemeral 段不写回 history,
|
|
226
|
+
// 所以这里补一次近场重申,不破坏前缀缓存。
|
|
227
|
+
// 措辞刻意压到三句:这段每步都发,长一倍的禁令换不来一倍遵守度,只换 token。
|
|
228
|
+
// 禁令范围收在「已有同源证据时的确认性查询」——早期写法是「核实不算回答的一部分」,
|
|
229
|
+
// 过宽,会把「证据不全时的必要核查」一起禁掉;这里要求先有同源证据才允许跳过。
|
|
230
|
+
// 末句把实现任务排除在外,否则会被读成「改到一半就下结论也合规」。
|
|
231
|
+
// 与 Silent work 无冲突:前者管「要不要动手」,后者管「要不要说」。
|
|
232
|
+
!opts.suppressOpeningAnalysis
|
|
233
|
+
? '## Answer before investigating\n' +
|
|
234
|
+
'For a judgment, explanation or advice (not a code change), if the evidence already sits in this ' +
|
|
235
|
+
'conversation, the tool results above, or the injected project context, answer now — skip the ' +
|
|
236
|
+
'confirm-again read or re-run. Look up only a fact that is genuinely missing. Code changes keep ' +
|
|
237
|
+
'the normal edit-and-check loop.'
|
|
207
238
|
: '',
|
|
208
239
|
remainingSteps <= 3
|
|
209
240
|
? `## Step budget warning\nOnly ${remainingSteps} step(s) remain before the hard step limit (${maxSteps}). ` +
|
|
@@ -223,9 +254,14 @@ export async function runModelTurn(input) {
|
|
|
223
254
|
// R18:每轮静默召回。放在 R17 尾注之前:尾注说的是「刚变了什么」(时间上最新),
|
|
224
255
|
// 召回说的是「这轮可能用得上什么」(topic 相关),新的信息靠后更能被看见。
|
|
225
256
|
input.memoryRecall ?? '',
|
|
257
|
+
// 短路径优化:已知名文件近因提示(见 mentioned-files.ts)。放在召回段之后:
|
|
258
|
+
// 它是本 turn 的任务级事实,靠后位置对弱指令遵循模型更可见。
|
|
259
|
+
input.mentionedFilesReminder ?? '',
|
|
226
260
|
// R17:会话内记忆尾注。放最后——它是最"新"的信息,且每轮可能不同,
|
|
227
261
|
// 放在固定段之后能最大限度保住前缀缓存的可复用部分。
|
|
228
262
|
opts.memoryTail ?? '',
|
|
263
|
+
input.liveUpdateReminder ?? '',
|
|
264
|
+
input.noProgressReminder ?? '',
|
|
229
265
|
]
|
|
230
266
|
.filter(Boolean)
|
|
231
267
|
.join('\n\n');
|
|
@@ -233,7 +269,8 @@ export async function runModelTurn(input) {
|
|
|
233
269
|
// 放在这里统一更新:首次请求与 overflow 重建都会经过,UI 不会拿旧一段继续外推。
|
|
234
270
|
runtimeContextState.ephemeralText = ephemeralReminder || undefined;
|
|
235
271
|
onContextUpdate?.();
|
|
236
|
-
|
|
272
|
+
const request = compactOverlappingReads(history);
|
|
273
|
+
return ephemeralReminder ? [...request, { role: 'system', content: ephemeralReminder }] : request;
|
|
237
274
|
};
|
|
238
275
|
let requestHistory = buildRequestHistory();
|
|
239
276
|
// 每次真正发请求前刷新:overflow 去图/压缩会替换 requestHistory,锚点不能钉在首次尝试上。
|
|
@@ -557,7 +594,8 @@ export async function runModelTurn(input) {
|
|
|
557
594
|
ephemeralText: requestEphemeral,
|
|
558
595
|
};
|
|
559
596
|
}
|
|
560
|
-
|
|
597
|
+
if (!input.opening || !result.toolCalls.length)
|
|
598
|
+
hooks.onChatDone?.();
|
|
561
599
|
onContextUpdate?.();
|
|
562
600
|
return { kind: 'result', result, stream };
|
|
563
601
|
}
|
|
@@ -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
|
+
}
|