mocode-ai 1.9.9 → 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 +83 -16
- package/dist/agent/progress-guard.js +67 -0
- package/dist/agent/run-coordinator.js +151 -23
- package/dist/agent/short-path-completion.js +109 -0
- package/dist/agent/spawn.js +46 -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/changeset/unified-diff.js +59 -0
- package/dist/config/index.js +13 -10
- package/dist/context/relevance.js +2 -1
- package/dist/context/usage-snapshot.js +50 -0
- package/dist/headless.js +3 -1
- package/dist/host/commit-message.js +41 -0
- package/dist/host/protocol.js +205 -10
- package/dist/host/stdio.js +1096 -63
- package/dist/i18n/index.js +26 -10
- package/dist/llm/index.js +28 -3
- package/dist/llm/message-shape.js +45 -0
- package/dist/llm/providers/anthropic.js +2 -0
- package/dist/llm/reasoning.js +17 -0
- package/dist/memory/adoption.js +159 -27
- package/dist/memory/anchor-relocate.js +227 -0
- package/dist/memory/consolidate-skips.js +196 -0
- package/dist/memory/health.js +88 -6
- package/dist/memory/index.js +2 -1
- package/dist/memory/reflect.js +36 -4
- package/dist/memory/store.js +30 -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/prompt/system-prompt.js +30 -0
- package/dist/repl/commands/appearance.js +1 -2
- package/dist/repl/commands/compact.js +4 -0
- package/dist/repl/commands/diff.js +5 -46
- package/dist/repl/commands/memory.js +77 -4
- 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 +129 -89
- package/dist/repl/status-bar.js +4 -38
- package/dist/rollback/store.js +36 -23
- package/dist/runtime/browser-diagnostics.js +77 -0
- package/dist/runtime/browser-manager.js +150 -22
- package/dist/runtime/runtime.js +1 -1
- package/dist/session/compact.js +44 -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/browser.js +4 -1
- package/dist/tools/builtins/edit-file.js +28 -5
- package/dist/tools/builtins/grep.js +85 -35
- package/dist/tools/builtins/memory-save.js +1 -1
- package/dist/tools/builtins/memory-update.js +1 -1
- 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/builtins/task.js +4 -0
- package/dist/tools/constants.js +8 -0
- 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,18 +261,40 @@ 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');
|
|
275
|
+
// 快照必须统计真实请求里的整段临时 system,而不只是 memory/session 两段。
|
|
276
|
+
// 放在这里统一更新:首次请求与 overflow 重建都会经过,UI 不会拿旧一段继续外推。
|
|
277
|
+
runtimeContextState.ephemeralText = ephemeralReminder || undefined;
|
|
278
|
+
onContextUpdate?.();
|
|
232
279
|
return ephemeralReminder ? [...history, { role: 'system', content: ephemeralReminder }] : history;
|
|
233
280
|
};
|
|
234
281
|
let requestHistory = buildRequestHistory();
|
|
235
|
-
|
|
282
|
+
// 每次真正发请求前刷新:overflow 去图/压缩会替换 requestHistory,锚点不能钉在首次尝试上。
|
|
283
|
+
let requestEphemeral = '';
|
|
284
|
+
let requestHistoryLen = history.length;
|
|
285
|
+
let requestBaseRaw = 0;
|
|
236
286
|
let stepPromptEst = estimatePromptTokens(requestHistory, activeTools, runtimeContextState.correction);
|
|
237
287
|
const reportLive = (progress) => {
|
|
288
|
+
// 流式首包可能已带真实 prompt usage:立刻钉住锚点,GUI 不能继续显示旧一轮的累计值。
|
|
289
|
+
if (progress.promptTokens && progress.promptTokens > 0) {
|
|
290
|
+
runtimeContextState.promptAnchor = {
|
|
291
|
+
measuredPromptTokens: progress.promptTokens,
|
|
292
|
+
baseRaw: requestBaseRaw,
|
|
293
|
+
historyLen: requestHistoryLen,
|
|
294
|
+
tools: activeTools,
|
|
295
|
+
ephemeralText: requestEphemeral,
|
|
296
|
+
};
|
|
297
|
+
}
|
|
238
298
|
const completedUsage = usageMeter.snapshot();
|
|
239
299
|
const curPrompt = progress.promptTokens ?? stepPromptEst;
|
|
240
300
|
const curCached = progress.cachedTokens ??
|
|
@@ -266,6 +326,13 @@ export async function runModelTurn(input) {
|
|
|
266
326
|
},
|
|
267
327
|
};
|
|
268
328
|
const runChatOnce = async () => {
|
|
329
|
+
// buildRequestHistory 还包含策略/步骤/恢复提醒,不能只取 memory/session 两段。
|
|
330
|
+
const appended = requestHistory.length > history.length ? requestHistory[requestHistory.length - 1] : undefined;
|
|
331
|
+
requestEphemeral = appended?.role === 'system' && typeof appended.content === 'string' ? appended.content : '';
|
|
332
|
+
requestHistoryLen = requestEphemeral ? requestHistory.length - 1 : requestHistory.length;
|
|
333
|
+
requestBaseRaw = estimatePromptTokens(requestHistory, activeTools);
|
|
334
|
+
// 让共享快照与真实请求使用同一份完整临时上下文,实测锚点才会命中。
|
|
335
|
+
runtimeContextState.ephemeralText = requestEphemeral || undefined;
|
|
269
336
|
try {
|
|
270
337
|
return await modelRunner.run({ history: requestHistory, handlers: chatHandlers, tools: activeTools }, signal);
|
|
271
338
|
}
|
|
@@ -519,22 +586,22 @@ export async function runModelTurn(input) {
|
|
|
519
586
|
cacheState.providerCacheSeen = true;
|
|
520
587
|
}
|
|
521
588
|
if (result.usage?.promptTokens && result.usage.promptTokens > 100) {
|
|
522
|
-
const estimated =
|
|
589
|
+
const estimated = requestBaseRaw;
|
|
523
590
|
const updated = ctx.updateTokenCalibration(requestBaseURL, requestModel, activeTools, estimated, result.usage.promptTokens);
|
|
524
591
|
runtimeContextState.correction = updated.correction;
|
|
525
592
|
runtimeContextState.calibrationSamples = updated.samples;
|
|
526
593
|
// 钉住底栏用量条:此刻 requestHistory == 真实发出的请求,实测 promptTokens 是它的真实大小。
|
|
527
594
|
// 记录基线裸估算/history 长度/工具集/ephemeral,供底栏对随后增长的消息做精确外推。
|
|
528
|
-
const requestHistoryLen = requestHistory.length;
|
|
529
595
|
runtimeContextState.promptAnchor = {
|
|
530
596
|
measuredPromptTokens: result.usage.promptTokens,
|
|
531
597
|
baseRaw: estimated,
|
|
532
|
-
historyLen:
|
|
598
|
+
historyLen: requestHistoryLen,
|
|
533
599
|
tools: activeTools,
|
|
534
|
-
ephemeralText:
|
|
600
|
+
ephemeralText: requestEphemeral,
|
|
535
601
|
};
|
|
536
602
|
}
|
|
537
|
-
|
|
603
|
+
if (!input.opening || !result.toolCalls.length)
|
|
604
|
+
hooks.onChatDone?.();
|
|
538
605
|
onContextUpdate?.();
|
|
539
606
|
return { kind: 'result', result, stream };
|
|
540
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
|
+
}
|