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
|
@@ -4,23 +4,29 @@
|
|
|
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';
|
|
8
|
+
import { withReadFileBatch } from '../tools/builtins/read-file.js';
|
|
7
9
|
import { validateToolArguments } from '../tools/validation.js';
|
|
8
10
|
import { getPlanDisabledTools, getRuntimeDisabledTools, getSkillRuntimeDisabledTools } from '../tools/constants.js';
|
|
9
11
|
import { isMemoryEnabled } from '../config/index.js';
|
|
10
12
|
import { isProactiveEnabled, proactiveHint } from '../memory/proactive.js';
|
|
11
13
|
import { ADD_TOOL_GROUPS_TOOL_NAME } from '../config/profiles.js';
|
|
12
14
|
import { defaultAgentRuntimeContext } from './runtime-context.js';
|
|
15
|
+
import { buildMentionedFilesReminder } from './mentioned-files.js';
|
|
13
16
|
import { runModelTurn } from './model-turn.js';
|
|
14
17
|
import { runToolTurn } from './tool-turn.js';
|
|
18
|
+
import { createShortPathCompletion } from './short-path-completion.js';
|
|
15
19
|
import { createTurnLifecycle } from './turn-lifecycle.js';
|
|
16
20
|
import { parseArgs, argumentErrorHint, isParallelTool, isParallelOrchestrationCall, isResourceLockedCall, deniedOutcome, readDiffContext, pushToolResult, unregisteredToolOutcome, } from './tool-helpers.js';
|
|
17
21
|
import { contextState, summarizeToolArguments } from '../session/index.js';
|
|
18
22
|
import { createReadDedup } from '../tools/read-dedup.js';
|
|
23
|
+
import { createTurnProgressGuard } from './progress-guard.js';
|
|
19
24
|
import { createBudgetScheduler } from '../session/scheduler.js';
|
|
20
25
|
import { invalidateArtifacts, rehydrateArtifacts } from '../context/index.js';
|
|
21
26
|
import { createRelevancePruner } from '../context/relevance.js';
|
|
22
27
|
import { t } from '../i18n/index.js';
|
|
23
28
|
import { createLifecycleEngine } from '../context/lifecycle.js';
|
|
29
|
+
import { capToolResultForHistory } from '../session/compact.js';
|
|
24
30
|
import { createLegacyModelRunner, createStagedModelRunner } from './stages/model-runner.js';
|
|
25
31
|
import { createLegacyContextTrimmer, createStagedContextTrimmer } from './stages/context-trimmer.js';
|
|
26
32
|
import { createLegacyToolDispatcher, createStagedToolDispatcher } from './stages/tool-dispatcher.js';
|
|
@@ -58,6 +64,9 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
58
64
|
// `memory-recall-stats.json` 正常写入)。包一层执行出口而非逐处插桩,5 个调度分支
|
|
59
65
|
// (只读并发 / 串行 / 资源锁 / 编排 / 兜底)自然全覆盖。
|
|
60
66
|
const proactiveOn = isMemoryEnabled() && isProactiveEnabled();
|
|
67
|
+
// #convergence A:本轮的无进展观测器。与 readDedup 同属 turn scope——同一用户轮内
|
|
68
|
+
// 才有「你在原地打转」这个语义,跨轮谈不到。
|
|
69
|
+
const progressGuard = createTurnProgressGuard();
|
|
61
70
|
const runToolWithProactive = async (name, argsRaw, sig, execOpts) => {
|
|
62
71
|
const outcome = await ctx.toolRuntime.executeToolOutcome(name, argsRaw, sig, execOpts);
|
|
63
72
|
if (!proactiveOn)
|
|
@@ -75,6 +84,14 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
75
84
|
// core 不读记忆库,否则每个 agent 单测都会去读真实的 ~/.mocode/memory.jsonl,
|
|
76
85
|
// 测试既失去隔离性、断言也会被本机记忆内容污染;spawn 不传即天然零注入。
|
|
77
86
|
const memoryRecall = opts.memoryRecall ?? '';
|
|
87
|
+
// 短路径优化:从本用户轮文本确定性提取已知名文件(存在性过滤),生成 ephemeral
|
|
88
|
+
// 近因提示。只对 string/含 text part 的输入生效;cwd 即 workspace(REPL 与 eval 一致)。
|
|
89
|
+
const mentionedFilesReminder = buildMentionedFilesReminder(typeof opts.userInput === 'string'
|
|
90
|
+
? opts.userInput
|
|
91
|
+
: opts.userInput
|
|
92
|
+
.filter((part) => part.type === 'text')
|
|
93
|
+
.map((part) => part.text)
|
|
94
|
+
.join('\n'), process.cwd());
|
|
78
95
|
const runtimeToolSchemas = ctx.toolRuntime.tools.map((tool) => ({
|
|
79
96
|
type: 'function',
|
|
80
97
|
function: {
|
|
@@ -92,6 +109,14 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
92
109
|
// 中断还原:repl 的 /plan / /auto / Shift+Tab 等用户面触发 setAgentMode 中途切了模式,
|
|
93
110
|
// abort 时连同模式一起还原回轮首。模型不再持有 switch_mode 工具,无法自切。
|
|
94
111
|
const savedMode = ctx.getAgentMode();
|
|
112
|
+
const shortPath = ctx.config.shortPathCompletion &&
|
|
113
|
+
savedMode === 'auto' &&
|
|
114
|
+
!opts.continueFromHistory &&
|
|
115
|
+
!opts.suppressOpeningAnalysis &&
|
|
116
|
+
typeof userInput === 'string'
|
|
117
|
+
? createShortPathCompletion(userInput, ctx)
|
|
118
|
+
: undefined;
|
|
119
|
+
let shortPathCompleted = false;
|
|
95
120
|
const turnLifecycle = createTurnLifecycle(opts, ctx, stages, savedMode);
|
|
96
121
|
const { usageMeter, emitTrace, traceTurnId } = turnLifecycle;
|
|
97
122
|
const toolTurnPlanState = { stepsSincePlanTouch: 0 };
|
|
@@ -106,10 +131,19 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
106
131
|
let lifecycle = ctx.config.contextLifecycle ? createLifecycleEngine(history) : null;
|
|
107
132
|
runtimeContextState.lifecycleStats = lifecycle?.stats();
|
|
108
133
|
rehydrateArtifacts(runtimeContextState, history);
|
|
134
|
+
// CompactionRuntime 是 session 层的最小依赖面(压缩只看 config / transport / rollback),
|
|
135
|
+
// 这里额外把 hooks.onCompactProgress 转发进去:压缩发生在 session 层,拿不到 AgentHooks,
|
|
136
|
+
// 而「压缩开始了/结束了」正是 work-app 里唯一能让用户感知到自动压缩的信号。
|
|
137
|
+
const compactionRuntime = {
|
|
138
|
+
config: ctx.config,
|
|
139
|
+
modelTransport: ctx.modelTransport,
|
|
140
|
+
rollbackStore: ctx.rollbackStore,
|
|
141
|
+
onCompactProgress: (event) => opts.hooks.onCompactProgress?.(event),
|
|
142
|
+
};
|
|
109
143
|
// The scheduler is the sole automatic history-rewrite entry point. It runs
|
|
110
144
|
// superseded → stale artifact → old logs/search → compact at real pressure.
|
|
111
145
|
// contextBudget=false keeps only the infrastructure compact fallback.
|
|
112
|
-
const scheduler = ctx.config.contextBudget !== false ? createBudgetScheduler(runtimeContextState,
|
|
146
|
+
const scheduler = ctx.config.contextBudget !== false ? createBudgetScheduler(runtimeContextState, compactionRuntime) : null;
|
|
113
147
|
const modelRunner = stages.model.implementation === 'staged'
|
|
114
148
|
? createStagedModelRunner(ctx.modelTransport)
|
|
115
149
|
: createLegacyModelRunner(ctx.modelTransport);
|
|
@@ -125,7 +159,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
125
159
|
? createStagedCapabilityResolver()
|
|
126
160
|
: createLegacyCapabilityResolver();
|
|
127
161
|
const terminationPolicy = stages.termination.implementation === 'staged' ? createStagedTerminationPolicy() : createLegacyTerminationPolicy();
|
|
128
|
-
const trimmerInit = { historyManager, scheduler, contextState: runtimeContextState, runtime:
|
|
162
|
+
const trimmerInit = { historyManager, scheduler, contextState: runtimeContextState, runtime: compactionRuntime };
|
|
129
163
|
const contextTrimmer = stages.context.implementation === 'staged'
|
|
130
164
|
? createStagedContextTrimmer(trimmerInit)
|
|
131
165
|
: createLegacyContextTrimmer(trimmerInit);
|
|
@@ -139,6 +173,38 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
139
173
|
const modelCacheState = { lastStepPromptTokens: 0, providerCacheSeen: false };
|
|
140
174
|
const cancellationLifecycle = turnLifecycle.createCancellation(historyManager, rebuildHistoryIndexes);
|
|
141
175
|
cancellationLifecycle.checkpoint();
|
|
176
|
+
let hasLiveUserUpdates = false;
|
|
177
|
+
let steeringOpeningPending = false;
|
|
178
|
+
const liveUpdateReminder = '## Live user updates — continue the current task\n' +
|
|
179
|
+
'The user sent additional messages while this task was running. Treat these messages as updates to the same ongoing task. ' +
|
|
180
|
+
'Consider the original request and all subsequent user updates together, preserving earlier requirements that were not changed. ' +
|
|
181
|
+
'Use the existing conversation, completed work, and tool results to continue from the current progress. ' +
|
|
182
|
+
'Apply newer corrections where they conflict with earlier requirements. Do not abandon unfinished work or restart from scratch merely because a new message arrived. ' +
|
|
183
|
+
'Only stop or replace the original task when the user explicitly asks to cancel, stop, or switch tasks. ' +
|
|
184
|
+
'Before the final response, check that both the original request and the applicable updates have been addressed.';
|
|
185
|
+
const acceptUserMessages = () => {
|
|
186
|
+
const messages = opts.drainUserMessages?.() ?? [];
|
|
187
|
+
for (const content of messages)
|
|
188
|
+
historyManager.appendUserTurn(content);
|
|
189
|
+
if (messages.length > 0) {
|
|
190
|
+
hasLiveUserUpdates = true;
|
|
191
|
+
steeringOpeningPending = true;
|
|
192
|
+
cancellationLifecycle.checkpoint();
|
|
193
|
+
hooks.onCheckpoint?.(history);
|
|
194
|
+
}
|
|
195
|
+
return messages.length > 0;
|
|
196
|
+
};
|
|
197
|
+
const completeTurn = (finalText) => {
|
|
198
|
+
const finalMutation = ctx.getCurrentTurnMutationState();
|
|
199
|
+
turnLifecycle.markCompleted();
|
|
200
|
+
return {
|
|
201
|
+
completed: true,
|
|
202
|
+
terminationReason: 'completed',
|
|
203
|
+
finalText,
|
|
204
|
+
usage: usageMeter.snapshot(),
|
|
205
|
+
changedFiles: finalMutation.changedFiles.map((item) => item.path),
|
|
206
|
+
};
|
|
207
|
+
};
|
|
142
208
|
try {
|
|
143
209
|
for (let step = 0; step < maxSteps; step++) {
|
|
144
210
|
turnLifecycle.setCurrentStep(step);
|
|
@@ -157,6 +223,15 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
157
223
|
turnLifecycle.markAborted();
|
|
158
224
|
return turnLifecycle.buildAbortedResult();
|
|
159
225
|
}
|
|
226
|
+
acceptUserMessages();
|
|
227
|
+
const opening = opts.suppressOpeningAnalysis
|
|
228
|
+
? undefined
|
|
229
|
+
: steeringOpeningPending
|
|
230
|
+
? 'steering'
|
|
231
|
+
: step === 0
|
|
232
|
+
? 'initial'
|
|
233
|
+
: undefined;
|
|
234
|
+
steeringOpeningPending = false;
|
|
160
235
|
// 本步只捕获一次不可变 policy snapshot。即便 add_tool_groups 在执行阶段扩容,
|
|
161
236
|
// 本次模型响应仍必须按旧 snapshot 校验;新工具只在下一 step 的 schema 中出现。
|
|
162
237
|
const planMode = ctx.getAgentMode() === 'plan';
|
|
@@ -208,9 +283,14 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
208
283
|
activeTools,
|
|
209
284
|
runPolicy,
|
|
210
285
|
step,
|
|
286
|
+
opening,
|
|
211
287
|
maxSteps,
|
|
212
288
|
readDedup,
|
|
213
289
|
memoryRecall,
|
|
290
|
+
mentionedFilesReminder,
|
|
291
|
+
liveUpdateReminder: hasLiveUserUpdates ? liveUpdateReminder : undefined,
|
|
292
|
+
// #convergence A:一次性提醒,取走即清空;未踩线时是 undefined。
|
|
293
|
+
noProgressReminder: progressGuard.takeReminder(),
|
|
214
294
|
cacheState: modelCacheState,
|
|
215
295
|
turnLifecycle,
|
|
216
296
|
cancellationLifecycle,
|
|
@@ -228,6 +308,9 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
228
308
|
modelResult: result,
|
|
229
309
|
});
|
|
230
310
|
if (modelDecision.kind === 'continue') {
|
|
311
|
+
if (result.toolCalls.length !== 1 || result.finishReason === 'length') {
|
|
312
|
+
shortPath?.reject('unexpected_tool');
|
|
313
|
+
}
|
|
231
314
|
await runToolTurn({
|
|
232
315
|
opts,
|
|
233
316
|
ctx,
|
|
@@ -235,6 +318,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
235
318
|
result,
|
|
236
319
|
stream,
|
|
237
320
|
step,
|
|
321
|
+
opening,
|
|
238
322
|
maxSteps,
|
|
239
323
|
planState: toolTurnPlanState,
|
|
240
324
|
turnLifecycle,
|
|
@@ -304,6 +388,8 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
304
388
|
break;
|
|
305
389
|
case 'trace_end': {
|
|
306
390
|
const { outcome, call } = event;
|
|
391
|
+
shortPath?.observe(call, outcome);
|
|
392
|
+
progressGuard.record(call.name, event.argumentSummary.sha256, outcome);
|
|
307
393
|
emitTrace('tool_call_end', {
|
|
308
394
|
tool: call.name,
|
|
309
395
|
argumentHash: event.argumentSummary.sha256,
|
|
@@ -311,6 +397,8 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
311
397
|
code: outcome.code,
|
|
312
398
|
retryable: outcome.retryable,
|
|
313
399
|
durationMs: outcome.durationMs ?? 0,
|
|
400
|
+
outputTokensEstimate: estimateTokens(capToolResultForHistory(call.name, outcome.output)),
|
|
401
|
+
...(outcome.commandTiming ? { commandTiming: outcome.commandTiming } : {}),
|
|
314
402
|
changedFiles: outcome.changedFiles ?? [],
|
|
315
403
|
staleFiles: outcome.staleFiles ?? [],
|
|
316
404
|
...(outcome.changeSet ? { changeSet: outcome.changeSet } : {}),
|
|
@@ -389,10 +477,12 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
389
477
|
});
|
|
390
478
|
}
|
|
391
479
|
const traceToolEnd = (tc, index, outcome) => {
|
|
480
|
+
shortPath?.observe(tc, outcome);
|
|
392
481
|
if (outcome.status === 'success' && outcome.modelAttachments?.length) {
|
|
393
482
|
modelAttachments.push(...outcome.modelAttachments);
|
|
394
483
|
}
|
|
395
484
|
const traceCall = tracedCalls[index];
|
|
485
|
+
progressGuard.record(tc.name, traceCall.args.sha256, outcome);
|
|
396
486
|
emitTrace('tool_call_end', {
|
|
397
487
|
tool: tc.name,
|
|
398
488
|
argumentHash: traceCall.args.sha256,
|
|
@@ -400,6 +490,8 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
400
490
|
code: outcome.code,
|
|
401
491
|
retryable: outcome.retryable,
|
|
402
492
|
durationMs: outcome.durationMs ?? 0,
|
|
493
|
+
outputTokensEstimate: estimateTokens(capToolResultForHistory(tc.name, outcome.output)),
|
|
494
|
+
...(outcome.commandTiming ? { commandTiming: outcome.commandTiming } : {}),
|
|
403
495
|
changedFiles: outcome.changedFiles ?? [],
|
|
404
496
|
staleFiles: outcome.staleFiles ?? [],
|
|
405
497
|
...(outcome.changeSet ? { changeSet: outcome.changeSet } : {}),
|
|
@@ -428,16 +520,18 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
428
520
|
const eligibleReadonly = otherIndexes.filter((index) => isParallelTool(calls[index].name, ctx.toolRuntime) && !isToolDeniedForStep(calls[index].name));
|
|
429
521
|
if (eligibleReadonly.length > 0) {
|
|
430
522
|
hooks.onToolStart?.(calls[eligibleReadonly[0]].name);
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
523
|
+
withReadFileBatch(() => {
|
|
524
|
+
for (const index of eligibleReadonly) {
|
|
525
|
+
startedReadonly[index] = runToolWithProactive(calls[index].name, calls[index].arguments, signal, {
|
|
526
|
+
callId: calls[index].id,
|
|
527
|
+
onOutput: (chunk) => hooks.onToolOutput?.(calls[index], chunk),
|
|
528
|
+
allowedToolNames: currentAllowedToolNames(),
|
|
529
|
+
delegation: delegationForOrchestrator(),
|
|
530
|
+
readDedup,
|
|
531
|
+
...(result.finishReason ? { finishReason: result.finishReason } : {}),
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
});
|
|
441
535
|
}
|
|
442
536
|
const lastReadonlyIndex = eligibleReadonly.length > 0 ? eligibleReadonly[eligibleReadonly.length - 1] : -1;
|
|
443
537
|
for (let index = 0; index < calls.length; index++) {
|
|
@@ -601,14 +695,14 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
601
695
|
for (const tc of batch)
|
|
602
696
|
hooks.onToolHeader?.(tc);
|
|
603
697
|
hooks.onToolStart?.(batch[0].name);
|
|
604
|
-
const started = batch.map((tc) => runToolWithProactive(tc.name, tc.arguments, signal, {
|
|
698
|
+
const started = withReadFileBatch(() => batch.map((tc) => runToolWithProactive(tc.name, tc.arguments, signal, {
|
|
605
699
|
callId: tc.id,
|
|
606
700
|
onOutput: (chunk) => hooks.onToolOutput?.(tc, chunk),
|
|
607
701
|
allowedToolNames: currentAllowedToolNames(),
|
|
608
702
|
delegation: delegationForOrchestrator(),
|
|
609
703
|
readDedup,
|
|
610
704
|
...(result.finishReason ? { finishReason: result.finishReason } : {}),
|
|
611
|
-
}));
|
|
705
|
+
})));
|
|
612
706
|
// 完成即发:usage/onToolOutcome/trace 在各 outcome 落地瞬间发出(1s 的
|
|
613
707
|
// grep 不再被 60s 的 web_fetch 卡住可见性);history 回灌严格按原序。
|
|
614
708
|
await Promise.all(started.map(async (pending, k) => {
|
|
@@ -932,6 +1026,36 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
932
1026
|
}
|
|
933
1027
|
},
|
|
934
1028
|
});
|
|
1029
|
+
if (shortPath && !shortPath.fallback) {
|
|
1030
|
+
if (step === 0 && (!stream.gotText || !result.content?.trim()))
|
|
1031
|
+
shortPath.reject('opening_missing');
|
|
1032
|
+
if (hasLiveUserUpdates)
|
|
1033
|
+
shortPath.reject('user_update');
|
|
1034
|
+
if (signal?.aborted || ctx.getAgentMode() !== 'auto' || step + 1 >= maxSteps) {
|
|
1035
|
+
shortPath.reject('turn_state_changed');
|
|
1036
|
+
}
|
|
1037
|
+
const finalText = shortPath.finalText();
|
|
1038
|
+
if (finalText) {
|
|
1039
|
+
if (acceptUserMessages())
|
|
1040
|
+
shortPath.reject('user_update');
|
|
1041
|
+
else if (signal?.aborted || ctx.getAgentMode() !== 'auto' || ctx.extractActivePlanSection()) {
|
|
1042
|
+
shortPath.reject('turn_state_changed');
|
|
1043
|
+
}
|
|
1044
|
+
else {
|
|
1045
|
+
hooks.onText?.(finalText);
|
|
1046
|
+
hooks.onTextEnd?.();
|
|
1047
|
+
historyManager.appendAssistantTurn({ content: finalText, toolCalls: [] });
|
|
1048
|
+
if (acceptUserMessages())
|
|
1049
|
+
shortPath.reject('user_update');
|
|
1050
|
+
else if (signal?.aborted)
|
|
1051
|
+
shortPath.reject('turn_state_changed');
|
|
1052
|
+
else {
|
|
1053
|
+
shortPathCompleted = true;
|
|
1054
|
+
return completeTurn(finalText);
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
}
|
|
935
1059
|
continue; // 带着工具结果再调一次 LLM
|
|
936
1060
|
}
|
|
937
1061
|
if (modelDecision.kind !== 'completed') {
|
|
@@ -943,16 +1067,15 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
943
1067
|
// 也不因缺少验证证据强制追加模型轮次;agent 仍可自行调用工具验证。
|
|
944
1068
|
if (!gotText)
|
|
945
1069
|
hooks.onNoReply?.();
|
|
946
|
-
historyManager.appendAssistantTurn({
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
};
|
|
1070
|
+
historyManager.appendAssistantTurn({
|
|
1071
|
+
content: result.content,
|
|
1072
|
+
toolCalls: [],
|
|
1073
|
+
reasoningContent: result.reasoningContent,
|
|
1074
|
+
});
|
|
1075
|
+
// A user update received during the final stream keeps this run alive.
|
|
1076
|
+
if (acceptUserMessages())
|
|
1077
|
+
continue;
|
|
1078
|
+
return completeTurn(modelDecision.finalText);
|
|
956
1079
|
}
|
|
957
1080
|
finally {
|
|
958
1081
|
emitTrace('step_end', {
|
|
@@ -1019,6 +1142,14 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
|
|
|
1019
1142
|
};
|
|
1020
1143
|
}
|
|
1021
1144
|
finally {
|
|
1145
|
+
if (shortPath) {
|
|
1146
|
+
emitTrace('short_path_completion', shortPathCompleted
|
|
1147
|
+
? { status: 'completed' }
|
|
1148
|
+
: {
|
|
1149
|
+
status: 'fallback',
|
|
1150
|
+
reason: shortPath.fallback ?? (signal?.aborted ? 'turn_state_changed' : 'model_finished'),
|
|
1151
|
+
});
|
|
1152
|
+
}
|
|
1022
1153
|
turnLifecycle.finalize();
|
|
1023
1154
|
}
|
|
1024
1155
|
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { lstatSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { contentHash } from '../changeset/hash.js';
|
|
3
|
+
import { parseArgs } from './tool-helpers.js';
|
|
4
|
+
// 只接受明确、完整的字面量替换请求。命令仍由模型经正常权限和工具流程调用。
|
|
5
|
+
const ZH = /^将 ?`(?<file>[^`\r\n]+)` ?中的 ?`(?<oldText>[^`\r\n]+)` ?替换为 ?`(?<newText>[^`\r\n]*)`。(?:然后运行 ?`(?<command>[^`\r\n]+)`|无需运行检查)。?$/u;
|
|
6
|
+
const EN = /^Replace `(?<oldText>[^`\r\n]+)` with `(?<newText>[^`\r\n]*)` in `(?<file>[^`\r\n]+)`\. (?:Then run `(?<command>[^`\r\n]+)`|No checks needed)\.?$/iu;
|
|
7
|
+
const MAX_EDIT_BYTES = 256 * 1024;
|
|
8
|
+
export function createShortPathCompletion(input, ctx) {
|
|
9
|
+
const text = input.trim();
|
|
10
|
+
const zh = ZH.exec(text);
|
|
11
|
+
const match = zh ?? EN.exec(text);
|
|
12
|
+
if (!match?.groups)
|
|
13
|
+
return;
|
|
14
|
+
const { file, oldText, newText, command } = match.groups;
|
|
15
|
+
if (oldText === newText)
|
|
16
|
+
return;
|
|
17
|
+
let edit;
|
|
18
|
+
let verified = false;
|
|
19
|
+
let fallback;
|
|
20
|
+
const resolve = (value) => {
|
|
21
|
+
if (typeof value !== 'string')
|
|
22
|
+
return;
|
|
23
|
+
try {
|
|
24
|
+
return ctx.jailResolve(value);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return;
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
return {
|
|
31
|
+
get fallback() {
|
|
32
|
+
return fallback;
|
|
33
|
+
},
|
|
34
|
+
reject(reason) {
|
|
35
|
+
fallback ??= reason;
|
|
36
|
+
},
|
|
37
|
+
observe(call, outcome) {
|
|
38
|
+
if (fallback)
|
|
39
|
+
return;
|
|
40
|
+
if (outcome.status !== 'success') {
|
|
41
|
+
fallback = 'tool_failed';
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
const args = parseArgs(call.arguments);
|
|
45
|
+
if (!edit && call.name === 'read_file' && !outcome.modelAttachments?.length) {
|
|
46
|
+
const target = resolve(file);
|
|
47
|
+
if (target && target === resolve(args?.path))
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
if (!edit && call.name === 'edit_file') {
|
|
51
|
+
const target = resolve(file);
|
|
52
|
+
const change = outcome.changeSet?.changes[0];
|
|
53
|
+
if (target &&
|
|
54
|
+
target === resolve(args?.path) &&
|
|
55
|
+
args?.old_string === oldText &&
|
|
56
|
+
args?.new_string === newText &&
|
|
57
|
+
outcome.exactTextReplacement &&
|
|
58
|
+
outcome.changeSet?.changes.length === 1 &&
|
|
59
|
+
change?.operation === 'update' &&
|
|
60
|
+
change.beforeHash &&
|
|
61
|
+
change.afterHash &&
|
|
62
|
+
target === resolve(change.path)) {
|
|
63
|
+
edit = { path: target, hash: change.afterHash };
|
|
64
|
+
}
|
|
65
|
+
else {
|
|
66
|
+
fallback = 'edit_unproven';
|
|
67
|
+
}
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (edit && command && call.name === 'run_command') {
|
|
71
|
+
if (args?.command === command &&
|
|
72
|
+
args.shell === undefined &&
|
|
73
|
+
outcome.code === 'OK' &&
|
|
74
|
+
!outcome.changedFiles?.length) {
|
|
75
|
+
verified = true;
|
|
76
|
+
}
|
|
77
|
+
else {
|
|
78
|
+
fallback = 'verification_mismatch';
|
|
79
|
+
}
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
fallback = 'unexpected_tool';
|
|
83
|
+
},
|
|
84
|
+
finalText() {
|
|
85
|
+
if (fallback || !edit || (command && !verified))
|
|
86
|
+
return;
|
|
87
|
+
const changes = ctx.getCurrentTurnMutationState().changedFiles;
|
|
88
|
+
if (changes.length !== 1 || resolve(changes[0].path) !== edit.path || resolve(file) !== edit.path) {
|
|
89
|
+
fallback = 'workspace_changed';
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
try {
|
|
93
|
+
const info = lstatSync(edit.path);
|
|
94
|
+
if (!info.isFile() || info.size > MAX_EDIT_BYTES || contentHash(readFileSync(edit.path)) !== edit.hash) {
|
|
95
|
+
fallback = 'workspace_changed';
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
fallback = 'workspace_changed';
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
const target = '`' + file + '`';
|
|
104
|
+
if (zh)
|
|
105
|
+
return command ? `已在${target}完成替换,指定检查已通过。` : `已在${target}完成替换。`;
|
|
106
|
+
return command ? `Updated ${target}. The requested check passed.` : `Updated ${target}.`;
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
}
|
package/dist/agent/spawn.js
CHANGED
|
@@ -24,12 +24,14 @@ import { summarizeToolCall, summarizeToolResult, truncateDisplay } from '../ui/r
|
|
|
24
24
|
import { t } from '../i18n/index.js';
|
|
25
25
|
import { createContextState } from '../session/compact.js';
|
|
26
26
|
import { defaultAgentRuntimeContext, getActiveAgentRuntimeContext, } from './runtime-context.js';
|
|
27
|
+
const SUBAGENT_SILENT_WORK = 'Work silently until your final reply.';
|
|
27
28
|
/** 子 agent 系统提示后缀(仅 legacy 直接调用路径用;共享前缀路径的系统提示直接复用父 agent)。 */
|
|
28
29
|
const SUBAGENT_SUFFIX = `
|
|
29
30
|
|
|
30
31
|
## ⛯ SUB-AGENT MODE (you are a sub-agent)
|
|
31
32
|
You are a sub-agent spawned by the main agent to handle a delegated sub-task, with the same tools and full capabilities as the main agent.
|
|
32
33
|
- Focus on the assigned sub-task and see it through to completion.
|
|
34
|
+
- ${SUBAGENT_SILENT_WORK}
|
|
33
35
|
- When done, your final text reply is returned to the main agent as the result — concise and actionable: what you did, key findings, files changed, blockers.`;
|
|
34
36
|
const SUBAGENT_ROLE = `## Sub-agent execution
|
|
35
37
|
You are executing one delegated sub-task with the same engineering standards and full capabilities as the main agent.
|
|
@@ -112,6 +114,8 @@ export async function spawnAgent(opts) {
|
|
|
112
114
|
`Sub-task:\n${opts.prompt}`,
|
|
113
115
|
[
|
|
114
116
|
"You have the same tools and the same full capabilities as the main agent. Your file writes land directly in the workspace and belong to the main agent's current rollback transaction.",
|
|
117
|
+
// 只在新追加的委派消息里约束静默,保留父会话的缓存前缀。
|
|
118
|
+
SUBAGENT_SILENT_WORK,
|
|
115
119
|
'Your final text reply is returned to the main agent as the result — concise and actionable: what you did, key findings, files changed, blockers.',
|
|
116
120
|
].join('\n'),
|
|
117
121
|
opts.systemPromptSuffix ?? '',
|
|
@@ -145,6 +149,26 @@ export async function spawnAgent(opts) {
|
|
|
145
149
|
? `Task context (authoritative; do not rediscover):\n${opts.context.slice(0, 4000)}\n\nSub-task:\n${opts.prompt}`
|
|
146
150
|
: opts.prompt;
|
|
147
151
|
}
|
|
152
|
+
// ── 结构化进度行(progress 通道的机器可读一半)──
|
|
153
|
+
// 人类可读的 `▸ 工具名 对象` 只有一行、且不含工具输出,GUI 侧没有任何可展开的内容。
|
|
154
|
+
// 这里对每次内部工具调用额外吐 start/end 两条**单行** JSON,宿主可据此把子 agent 的步骤
|
|
155
|
+
// 渲染成可展开条目(GUI 现在就是这么做的)。单行是硬约束:宿主按 \n 累积,JSON.stringify
|
|
156
|
+
// 会把内容里的换行转义掉;超长入参/输出裁到上限,避免一次 read_file 撑大 IPC 与恢复日志。
|
|
157
|
+
//
|
|
158
|
+
// 前缀常量在 packages/work-app/src/sub-agent-progress.ts 有一份同值拷贝:
|
|
159
|
+
// 渲染层是浏览器环境、不能 import src 的模块,故由那个纯函数模块承载解析(两边注释互指)。
|
|
160
|
+
const SUB_TOOL_PREFIX = '[sub-tool]';
|
|
161
|
+
const SUB_TOOL_MAX_CHARS = 6000;
|
|
162
|
+
const clipSubTool = (text) => text.length <= SUB_TOOL_MAX_CHARS
|
|
163
|
+
? text
|
|
164
|
+
: `${text.slice(0, SUB_TOOL_MAX_CHARS)}\n… (${text.length - SUB_TOOL_MAX_CHARS} more chars)`;
|
|
165
|
+
const emitSubTool = (payload) => {
|
|
166
|
+
if (live || !opts.progress)
|
|
167
|
+
return;
|
|
168
|
+
opts.progress(`${SUB_TOOL_PREFIX}${JSON.stringify(payload)}\n`);
|
|
169
|
+
};
|
|
170
|
+
/** 本子 agent 内部工具调用的单调序号:宿主按它对齐 start/end 两条(同一步并行调用时 tc.id 可能缺失)。 */
|
|
171
|
+
let stepToolSeq = 0;
|
|
148
172
|
// 静默 hooks:缓冲中间过程到 transcript,不写主屏。
|
|
149
173
|
let transcript = '';
|
|
150
174
|
const buf = [];
|
|
@@ -254,6 +278,15 @@ export async function spawnAgent(opts) {
|
|
|
254
278
|
if (!live && opts.progress) {
|
|
255
279
|
opts.progress(`▸ ${tc.name} ${summary}\n`);
|
|
256
280
|
}
|
|
281
|
+
// 结构化一条 start:带完整入参,宿主展开时能看到真实命令/替换片段。
|
|
282
|
+
emitSubTool({
|
|
283
|
+
phase: 'start',
|
|
284
|
+
seq: stepToolSeq++,
|
|
285
|
+
id: tc.id ?? '',
|
|
286
|
+
name: tc.name,
|
|
287
|
+
summary,
|
|
288
|
+
args: clipSubTool(tc.arguments ?? ''),
|
|
289
|
+
});
|
|
257
290
|
// 实时写入主内容区:子 agent 的每次工具调用累计到摘要行计数。
|
|
258
291
|
ensureQuietLine(opts.quietLabel ?? t('skill.executing', { name: opts.prompt.slice(0, 40) }));
|
|
259
292
|
ensureLiveBatch();
|
|
@@ -270,6 +303,16 @@ export async function spawnAgent(opts) {
|
|
|
270
303
|
const preview = summarizeToolResult(tc.name, output);
|
|
271
304
|
if (preview)
|
|
272
305
|
writeBuf(` ↳ ${preview}\n`);
|
|
306
|
+
// 结构化一条 end:带该次调用的输出(截断)。这是 GUI 展开子 agent 步骤时唯一的数据来源——
|
|
307
|
+
// 在此之前子 agent 的工具输出从未离开子进程。
|
|
308
|
+
emitSubTool({
|
|
309
|
+
phase: 'end',
|
|
310
|
+
id: tc.id ?? '',
|
|
311
|
+
name: tc.name,
|
|
312
|
+
summary: preview || t('toolSummary.noOutput'),
|
|
313
|
+
failed: isToolErrorOutput(output),
|
|
314
|
+
output: clipSubTool(output),
|
|
315
|
+
});
|
|
273
316
|
if (liveBatchId) {
|
|
274
317
|
// 子 agent 批不展示 diff(其写入已直接落工作区,由主 agent 的当前回滚事务统一追踪);
|
|
275
318
|
// 空 preview 用占位标记 entry 已完成,避免折叠后摘要仍显示"运行中"。
|
|
@@ -16,6 +16,7 @@ function assistantMessage(turn) {
|
|
|
16
16
|
// 「agent 完成了这一轮」写盘。构造点在此收敛,transport 边界另有兜底
|
|
17
17
|
// (src/llm/message-shape.ts)负责让存量中毒会话自愈。
|
|
18
18
|
content: !hasToolCalls && turn.content === null ? '' : turn.content,
|
|
19
|
+
...(turn.reasoningContent ? { reasoning_content: turn.reasoningContent } : {}),
|
|
19
20
|
};
|
|
20
21
|
if (hasToolCalls) {
|
|
21
22
|
// thoughtSignature 不是 OpenAI 字段,是 mocode 给 Gemini/Vertex 透传用的;
|
|
@@ -6,6 +6,7 @@ import { checkPermission as defaultCheckPermission } from '../../permissions/ind
|
|
|
6
6
|
import { jailResolve as defaultJailResolve } from '../../sandbox/index.js';
|
|
7
7
|
import { summarizeToolArguments } from '../../session/index.js';
|
|
8
8
|
import { getPlanDisabledTools } from '../../tools/constants.js';
|
|
9
|
+
import { withReadFileBatch } from '../../tools/builtins/read-file.js';
|
|
9
10
|
import { defaultToolRuntime } from '../../tools/registry.js';
|
|
10
11
|
import { validateToolArguments } from '../../tools/validation.js';
|
|
11
12
|
import { deniedOutcome, isParallelTool, isParallelOrchestrationCall, isResourceLockedCall, parseArgs, readDiffContext, unregisteredToolOutcome, } from '../tool-helpers.js';
|
|
@@ -119,8 +120,10 @@ class LegacyCompatibleToolDispatcher {
|
|
|
119
120
|
const eligibleReadonly = otherIndexes.filter((index) => isParallelTool(calls[index].name, toolRuntime) && !request.isDenied(calls[index].name));
|
|
120
121
|
if (eligibleReadonly.length > 0) {
|
|
121
122
|
request.onEvent({ type: 'start', tool: calls[eligibleReadonly[0]].name });
|
|
122
|
-
|
|
123
|
-
|
|
123
|
+
withReadFileBatch(() => {
|
|
124
|
+
for (const index of eligibleReadonly)
|
|
125
|
+
startedReadonly[index] = execute(calls[index]);
|
|
126
|
+
});
|
|
124
127
|
}
|
|
125
128
|
const lastReadonlyIndex = eligibleReadonly.length > 0 ? eligibleReadonly[eligibleReadonly.length - 1] : -1;
|
|
126
129
|
for (let index = 0; index < calls.length; index++) {
|
|
@@ -262,7 +265,7 @@ class LegacyCompatibleToolDispatcher {
|
|
|
262
265
|
for (const call of batch)
|
|
263
266
|
request.onEvent({ type: 'header', call });
|
|
264
267
|
request.onEvent({ type: 'start', tool: batch[0].name });
|
|
265
|
-
const started = batch.map((call) => execute(call));
|
|
268
|
+
const started = withReadFileBatch(() => batch.map((call) => execute(call)));
|
|
266
269
|
// 完成即发:usage/host_outcome/trace_end 在各 outcome 落地瞬间发出(1s 的 grep 不再
|
|
267
270
|
// 被 60s 的 run_command 卡住可见性);result(history 回灌)严格保持原序。
|
|
268
271
|
await Promise.all(started.map(async (pending, offset) => {
|
|
@@ -201,10 +201,10 @@ export function pushToolResult(history, tc, output, pruner, lifecycle, _schedule
|
|
|
201
201
|
const succeeded = succeededOverride ?? isToolResultSuccess(output);
|
|
202
202
|
const capped = capToolResultForHistory(tc.name, output);
|
|
203
203
|
// push-time 截断兜底:完整结果另存 compacted/result-<id>.txt,并在进 history 的
|
|
204
|
-
//
|
|
204
|
+
// 截断内容尾部留一行全文指针。仅持久化会话落盘——子 agent 的
|
|
205
205
|
// 结果随其临时 history 消亡,不污染主会话。best-effort:存不上就只保留截断内容。
|
|
206
206
|
let content = capped;
|
|
207
|
-
if (capped.length < output.length && runtimeContextState
|
|
207
|
+
if (capped.length < output.length && runtimeContextState.archiveHistory) {
|
|
208
208
|
try {
|
|
209
209
|
const rel = getActiveSessionStore().archiveToolResult(getCurrentSessionId() ?? '', tc.id, output);
|
|
210
210
|
if (rel)
|