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.
Files changed (74) hide show
  1. package/dist/agent/index.js +13 -3
  2. package/dist/agent/mentioned-files.js +71 -0
  3. package/dist/agent/model-turn.js +83 -16
  4. package/dist/agent/progress-guard.js +67 -0
  5. package/dist/agent/run-coordinator.js +151 -23
  6. package/dist/agent/short-path-completion.js +109 -0
  7. package/dist/agent/spawn.js +46 -0
  8. package/dist/agent/stages/history-manager.js +1 -0
  9. package/dist/agent/tool-helpers.js +2 -2
  10. package/dist/agent/tool-turn.js +49 -4
  11. package/dist/agent/work-discipline.js +9 -9
  12. package/dist/changeset/unified-diff.js +59 -0
  13. package/dist/config/index.js +13 -10
  14. package/dist/context/relevance.js +2 -1
  15. package/dist/context/usage-snapshot.js +50 -0
  16. package/dist/headless.js +3 -1
  17. package/dist/host/commit-message.js +41 -0
  18. package/dist/host/protocol.js +205 -10
  19. package/dist/host/stdio.js +1096 -63
  20. package/dist/i18n/index.js +26 -10
  21. package/dist/llm/index.js +28 -3
  22. package/dist/llm/message-shape.js +45 -0
  23. package/dist/llm/providers/anthropic.js +2 -0
  24. package/dist/llm/reasoning.js +17 -0
  25. package/dist/memory/adoption.js +159 -27
  26. package/dist/memory/anchor-relocate.js +227 -0
  27. package/dist/memory/consolidate-skips.js +196 -0
  28. package/dist/memory/health.js +88 -6
  29. package/dist/memory/index.js +2 -1
  30. package/dist/memory/reflect.js +36 -4
  31. package/dist/memory/store.js +30 -0
  32. package/dist/models/reasoning-cap.js +19 -2
  33. package/dist/orchestrator/lane-executor.js +7 -1
  34. package/dist/orchestrator/repl.js +30 -49
  35. package/dist/prompt/system-prompt.js +30 -0
  36. package/dist/repl/commands/appearance.js +1 -2
  37. package/dist/repl/commands/compact.js +4 -0
  38. package/dist/repl/commands/diff.js +5 -46
  39. package/dist/repl/commands/memory.js +77 -4
  40. package/dist/repl/commands/model-actions.js +4 -3
  41. package/dist/repl/commands/model.js +2 -3
  42. package/dist/repl/message-format.js +7 -6
  43. package/dist/repl/running-input.js +27 -65
  44. package/dist/repl/runtime.js +129 -89
  45. package/dist/repl/status-bar.js +4 -38
  46. package/dist/rollback/store.js +36 -23
  47. package/dist/runtime/browser-diagnostics.js +77 -0
  48. package/dist/runtime/browser-manager.js +150 -22
  49. package/dist/runtime/runtime.js +1 -1
  50. package/dist/session/compact.js +44 -4
  51. package/dist/session/retention.js +4 -0
  52. package/dist/session/short-path-metrics.js +185 -0
  53. package/dist/session/store.js +78 -3
  54. package/dist/session/terminal-transcript.js +101 -0
  55. package/dist/tools/builtins/ask-human.js +2 -2
  56. package/dist/tools/builtins/browser.js +4 -1
  57. package/dist/tools/builtins/edit-file.js +28 -5
  58. package/dist/tools/builtins/grep.js +85 -35
  59. package/dist/tools/builtins/memory-save.js +1 -1
  60. package/dist/tools/builtins/memory-update.js +1 -1
  61. package/dist/tools/builtins/plan-update.js +4 -2
  62. package/dist/tools/builtins/read-file.js +95 -44
  63. package/dist/tools/builtins/run-command.js +57 -9
  64. package/dist/tools/builtins/task.js +4 -0
  65. package/dist/tools/constants.js +8 -0
  66. package/dist/tools/ripgrep-client.js +31 -11
  67. package/dist/tools/tool-runtime.js +29 -8
  68. package/dist/ui/layout-internal/content-write.js +7 -3
  69. package/dist/ui/layout-internal/core.js +1 -1
  70. package/dist/ui/layout-internal/state.js +0 -6
  71. package/dist/ui/layout-internal/statusbar.js +0 -30
  72. package/dist/ui/output-sink.js +24 -0
  73. package/dist/ui/spinner.js +3 -1
  74. package/package.json +4 -2
@@ -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, ctx) : null;
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: ctx };
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 } : {}),
@@ -322,7 +409,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
322
409
  break;
323
410
  }
324
411
  case 'result':
325
- hooks.onToolResult?.(event.call, event.outcome.output, event.parsed, event.diff.preWriteOld, event.diff.editStartLine, event.diff.multiHunks);
412
+ hooks.onToolResult?.(event.call, event.outcome.output, event.parsed, event.diff.preWriteOld, event.diff.editStartLine, event.diff.multiHunks, event.outcome);
326
413
  if (event.call.name === 'ask_human' && event.outcome.status === 'success') {
327
414
  askHumanCountThisTurn += 1;
328
415
  emitTrace('ask_human_call', {
@@ -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 } : {}),
@@ -448,7 +539,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
448
539
  usageMeter.add(outcome.usage);
449
540
  opts.onToolOutcome?.(tc.name, parseArgs(tc.arguments) ?? {}, outcome);
450
541
  traceToolEnd(tc, index, outcome);
451
- hooks.onToolResult?.(tc, outcome.output, null, null, 1);
542
+ hooks.onToolResult?.(tc, outcome.output, null, null, 1, undefined, outcome);
452
543
  pushToolResult(history, tc, outcome.output, relprune, lifecycle, scheduler, runtimeContextState, outcome.status === 'success');
453
544
  // done 紧跟最后一个只读结果(控制调用在尾部时与旧事件序完全一致)。
454
545
  if (index === lastReadonlyIndex)
@@ -474,7 +565,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
474
565
  durationMs: 0,
475
566
  };
476
567
  opts.onToolOutcome?.(tc.name, parseArgs(tc.arguments) ?? {}, outcome);
477
- hooks.onToolResult?.(tc, outcome.output, null, null, 1);
568
+ hooks.onToolResult?.(tc, outcome.output, null, null, 1, undefined, outcome);
478
569
  pushToolResult(history, tc, outcome.output, relprune, lifecycle, scheduler, runtimeContextState, false);
479
570
  traceToolEnd(tc, index, outcome);
480
571
  continue;
@@ -554,7 +645,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
554
645
  });
555
646
  }
556
647
  opts.onToolOutcome?.(tc.name, parsed ?? {}, outcome);
557
- hooks.onToolResult?.(tc, outcome.output, null, null, 1);
648
+ hooks.onToolResult?.(tc, outcome.output, null, null, 1, undefined, outcome);
558
649
  pushToolResult(history, tc, outcome.output, relprune, lifecycle, scheduler, runtimeContextState, outcome.status === 'success');
559
650
  traceToolEnd(tc, index, outcome);
560
651
  }
@@ -580,7 +671,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
580
671
  changedFiles: [],
581
672
  durationMs: 0,
582
673
  };
583
- hooks.onToolResult?.(currentCall, error, null, null, 1);
674
+ hooks.onToolResult?.(currentCall, error, null, null, 1, undefined, outcome);
584
675
  pushToolResult(history, currentCall, error, relprune, lifecycle, scheduler, runtimeContextState, false);
585
676
  traceToolEnd(currentCall, i, outcome);
586
677
  i++;
@@ -621,7 +712,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
621
712
  const tc = batch[k];
622
713
  const outcome = await started[k];
623
714
  const output = outcome.output;
624
- hooks.onToolResult?.(tc, output, null, null, 1); // 并行工具无 diff
715
+ hooks.onToolResult?.(tc, output, null, null, 1, undefined, outcome); // 并行工具无 diff
625
716
  if (tc.name === 'ask_human' && outcome.status === 'success') {
626
717
  askHumanCountThisTurn += 1;
627
718
  emitTrace('ask_human_call', {
@@ -722,7 +813,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
722
813
  for (let offset = 0; offset < entries.length; offset++) {
723
814
  const entry = entries[offset];
724
815
  const outcome = await outcomes[offset];
725
- hooks.onToolResult?.(entry.tc, outcome.output, entry.denied ? null : entry.parsed, entry.diff.preWriteOld, entry.diff.editStartLine, entry.diff.multiHunks);
816
+ hooks.onToolResult?.(entry.tc, outcome.output, entry.denied ? null : entry.parsed, entry.diff.preWriteOld, entry.diff.editStartLine, entry.diff.multiHunks, outcome);
726
817
  pushToolResult(history, entry.tc, outcome.output, relprune, lifecycle, scheduler, runtimeContextState, outcome.status === 'success');
727
818
  const invalidatedFiles = [
728
819
  ...new Set([...(outcome.changedFiles ?? []), ...(outcome.staleFiles ?? [])]),
@@ -814,7 +905,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
814
905
  for (let k = 0; k < entries.length; k++) {
815
906
  const entry = entries[k];
816
907
  const outcome = await started[k];
817
- hooks.onToolResult?.(entry.tc, outcome.output, entry.denied ? null : entry.parsed, entry.diff.preWriteOld, entry.diff.editStartLine, entry.diff.multiHunks);
908
+ hooks.onToolResult?.(entry.tc, outcome.output, entry.denied ? null : entry.parsed, entry.diff.preWriteOld, entry.diff.editStartLine, entry.diff.multiHunks, outcome);
818
909
  pushToolResult(history, entry.tc, outcome.output, relprune, lifecycle, scheduler, runtimeContextState, outcome.status === 'success');
819
910
  const invalidatedFiles = [
820
911
  ...new Set([...(outcome.changedFiles ?? []), ...(outcome.staleFiles ?? [])]),
@@ -848,7 +939,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
848
939
  changedFiles: [],
849
940
  durationMs: 0,
850
941
  };
851
- hooks.onToolResult?.(tc, err, null, null, 1);
942
+ hooks.onToolResult?.(tc, err, null, null, 1, undefined, outcome);
852
943
  pushToolResult(history, tc, err, relprune, lifecycle, scheduler);
853
944
  traceToolEnd(tc, i, outcome);
854
945
  i++;
@@ -875,7 +966,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
875
966
  if (perm === 'deny') {
876
967
  hooks.onToolHeader?.(tc);
877
968
  const outcome = deniedOutcome(tc.name);
878
- hooks.onToolResult?.(tc, outcome.output, null, null, 1);
969
+ hooks.onToolResult?.(tc, outcome.output, null, null, 1, undefined, outcome);
879
970
  pushToolResult(history, tc, outcome.output, relprune, lifecycle, scheduler, runtimeContextState, false);
880
971
  traceToolEnd(tc, i, outcome);
881
972
  i++;
@@ -905,7 +996,7 @@ export async function runAgentCoreLegacy(opts, historyManager, stages) {
905
996
  traceToolEnd(tc, i, outcome);
906
997
  const output = outcome.output;
907
998
  hooks.onToolDone?.();
908
- hooks.onToolResult?.(tc, output, mutationParsed, diff.preWriteOld, diff.editStartLine, diff.multiHunks);
999
+ hooks.onToolResult?.(tc, output, mutationParsed, diff.preWriteOld, diff.editStartLine, diff.multiHunks, outcome);
909
1000
  if (tc.name === 'ask_human' && outcome.status === 'success') {
910
1001
  askHumanCountThisTurn += 1;
911
1002
  emitTrace('ask_human_call', {
@@ -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({ content: result.content, toolCalls: [] });
947
- const finalMutation = ctx.getCurrentTurnMutationState();
948
- turnLifecycle.markCompleted();
949
- return {
950
- completed: true,
951
- terminationReason: 'completed',
952
- finalText: modelDecision.finalText,
953
- usage: usageMeter.snapshot(),
954
- changedFiles: finalMutation.changedFiles.map((item) => item.path),
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
  }
@@ -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
+ }
@@ -145,6 +145,26 @@ export async function spawnAgent(opts) {
145
145
  ? `Task context (authoritative; do not rediscover):\n${opts.context.slice(0, 4000)}\n\nSub-task:\n${opts.prompt}`
146
146
  : opts.prompt;
147
147
  }
148
+ // ── 结构化进度行(progress 通道的机器可读一半)──
149
+ // 人类可读的 `▸ 工具名 对象` 只有一行、且不含工具输出,GUI 侧没有任何可展开的内容。
150
+ // 这里对每次内部工具调用额外吐 start/end 两条**单行** JSON,宿主可据此把子 agent 的步骤
151
+ // 渲染成可展开条目(GUI 现在就是这么做的)。单行是硬约束:宿主按 \n 累积,JSON.stringify
152
+ // 会把内容里的换行转义掉;超长入参/输出裁到上限,避免一次 read_file 撑大 IPC 与恢复日志。
153
+ //
154
+ // 前缀常量在 packages/work-app/src/sub-agent-progress.ts 有一份同值拷贝:
155
+ // 渲染层是浏览器环境、不能 import src 的模块,故由那个纯函数模块承载解析(两边注释互指)。
156
+ const SUB_TOOL_PREFIX = '[sub-tool]';
157
+ const SUB_TOOL_MAX_CHARS = 6000;
158
+ const clipSubTool = (text) => text.length <= SUB_TOOL_MAX_CHARS
159
+ ? text
160
+ : `${text.slice(0, SUB_TOOL_MAX_CHARS)}\n… (${text.length - SUB_TOOL_MAX_CHARS} more chars)`;
161
+ const emitSubTool = (payload) => {
162
+ if (live || !opts.progress)
163
+ return;
164
+ opts.progress(`${SUB_TOOL_PREFIX}${JSON.stringify(payload)}\n`);
165
+ };
166
+ /** 本子 agent 内部工具调用的单调序号:宿主按它对齐 start/end 两条(同一步并行调用时 tc.id 可能缺失)。 */
167
+ let stepToolSeq = 0;
148
168
  // 静默 hooks:缓冲中间过程到 transcript,不写主屏。
149
169
  let transcript = '';
150
170
  const buf = [];
@@ -247,6 +267,22 @@ export async function spawnAgent(opts) {
247
267
  const summary = summarizeToolCall(tc.name, tc.arguments);
248
268
  writeBuf(` ● ${tc.name} ${summary}\n`);
249
269
  lastChar = '\n';
270
+ // 无 TUI 的宿主(GUI/headless):把同一条信息经 progress 通道回吐。
271
+ // 子 agent 的中间过程在 GUI 里原本完全不可见 —— 派了任务之后只有一张静止的
272
+ // 「执行中」卡片,用户分不清在跑还是卡死。这里逐条吐出「工具名 + 对象」,
273
+ // 宿主自己决定怎么展示(work-app 走 tool_output 累积到那张卡片里)。
274
+ if (!live && opts.progress) {
275
+ opts.progress(`▸ ${tc.name} ${summary}\n`);
276
+ }
277
+ // 结构化一条 start:带完整入参,宿主展开时能看到真实命令/替换片段。
278
+ emitSubTool({
279
+ phase: 'start',
280
+ seq: stepToolSeq++,
281
+ id: tc.id ?? '',
282
+ name: tc.name,
283
+ summary,
284
+ args: clipSubTool(tc.arguments ?? ''),
285
+ });
250
286
  // 实时写入主内容区:子 agent 的每次工具调用累计到摘要行计数。
251
287
  ensureQuietLine(opts.quietLabel ?? t('skill.executing', { name: opts.prompt.slice(0, 40) }));
252
288
  ensureLiveBatch();
@@ -263,6 +299,16 @@ export async function spawnAgent(opts) {
263
299
  const preview = summarizeToolResult(tc.name, output);
264
300
  if (preview)
265
301
  writeBuf(` ↳ ${preview}\n`);
302
+ // 结构化一条 end:带该次调用的输出(截断)。这是 GUI 展开子 agent 步骤时唯一的数据来源——
303
+ // 在此之前子 agent 的工具输出从未离开子进程。
304
+ emitSubTool({
305
+ phase: 'end',
306
+ id: tc.id ?? '',
307
+ name: tc.name,
308
+ summary: preview || t('toolSummary.noOutput'),
309
+ failed: isToolErrorOutput(output),
310
+ output: clipSubTool(output),
311
+ });
266
312
  if (liveBatchId) {
267
313
  // 子 agent 批不展示 diff(其写入已直接落工作区,由主 agent 的当前回滚事务统一追踪);
268
314
  // 空 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 透传用的;
@@ -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
- // 截断内容尾部留一行全文指针。仅主 agent(共享 contextState)落盘——子 agent 的
204
+ // 截断内容尾部留一行全文指针。仅持久化会话落盘——子 agent 的
205
205
  // 结果随其临时 history 消亡,不污染主会话。best-effort:存不上就只保留截断内容。
206
206
  let content = capped;
207
- if (capped.length < output.length && runtimeContextState === contextState) {
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)