cladogram 0.5.5-beta.6 → 0.5.5-beta.8

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.
@@ -2,17 +2,22 @@
2
2
  * Clado 独立垂直 Agent 运行时(系统级内置插件 clado.agent 的大脑引擎)。
3
3
  *
4
4
  * 核心特性:
5
- * 1. 双协议真 Token 流式输出(OpenAI 兼容 + Anthropic 原生,含 thinking 与 Prompt Caching);
6
- * 2. 进程内直调内核画布操作引擎(零网络开销)+ 只读本地代码探针;
7
- * 3. 原生观察者交互工具:ask_user(结构化提问决策卡,暂停待人拍板并无损续跑)与 canvas_focus(平滑镜头引导);
8
- * 4. 变更清单自动汇总(changes)+ diagnostics 自动校验自纠闭环。
5
+ * 1. 双协议真 Token 流式输出(OpenAI 兼容 + Anthropic 原生,含 thinking 与四段式前缀缓存);
6
+ * 2. 进程内直调内核画布操作引擎 + 只读代码探针 + 受控命令行审批(probe_command);
7
+ * 3. 规划(只读)/ 执行(读写)模式硬隔离 + 轮次级画布快照回退(Checkpoints)+ 运行中途插话纠偏;
8
+ * 4. 平级分身团队协作(spawn_peer / message_peer,含单向 notify 与 8 跳防死循环熔断);
9
+ * 5. 原生观察者交互工具:ask_user(结构化提问决策卡)与 canvas_focus(平滑镜头引导)。
9
10
  */
10
11
 
11
12
  import { randomUUID } from 'node:crypto';
12
- import { probeGitDiff, probeRead, probeSearch, probeTree } from './probe.js';
13
+ import { existsSync, readFileSync } from 'node:fs';
14
+ import { workspacePath } from '../workspace/documents.js';
15
+ import { deleteCanvasObject, listCanvasObjects, readCanvasObject, saveCanvasObject } from '../workspace/objects.js';
16
+ import { buildSegmentedPromptContext, readAgentDebugConfig } from './context.js';
13
17
  import { createRunRecord, updateRunRecord } from './executors.js';
18
+ import { classifyShellCommand, executeWorkspaceCommand, probeGitDiff, probeRead, probeSearch, probeTree } from './probe.js';
14
19
  import { streamModelTurn } from './providers/index.js';
15
- import { compactMessages, resolvePersona } from './sessions.js';
20
+ import { resolvePersona } from './sessions.js';
16
21
 
17
22
  const MAX_STEPS = 12;
18
23
 
@@ -23,7 +28,7 @@ const MODE_PROMPTS = {
23
28
  '2. 先用 clado_templates 读取对应模板(如 call-chain / data-design / business-flow)再创建或修改 .md 画布。',
24
29
  '3. 同画布跨卡连线支持「卡片 + Tag」二元目标:可在目标行打唯一语义 Tag(有字胶囊 `[新增]{#id .green}`、无字小圆点 `[]{#id .amber}`、代码行尾 `// {#id .blue}`、Mermaid `%% {#node .green}`),再以 `[文案](#id)` 精准连线,也可兼容 `clado:code:` / `clado:to:`;避免卡片末尾裸卡片连卡片。',
25
30
  '4. 遇到需求歧义或方案二选一时,优先调用 ask_user 给出清晰选项让观察者拍板,不要替用户擅自猜测。',
26
- '5. 每次修改后核对 diagnostics,确保 0 error 再给 3–5 行精炼汇报。',
31
+ '5. 多步骤任务可调用 todo_write 维护步骤进度;每次修改后核对 diagnostics,确保 0 error 再给 3–5 行精炼汇报。',
27
32
  ].join('\n'),
28
33
  qa: [
29
34
  '当前工作模式:【脑图测试用例编写】',
@@ -43,8 +48,8 @@ const MODE_PROMPTS = {
43
48
  ].join('\n'),
44
49
  };
45
50
 
46
- function toolDefinitions() {
47
- return [
51
+ function toolDefinitions({ enablePeers = false } = {}) {
52
+ const list = [
48
53
  {
49
54
  type: 'function',
50
55
  function: {
@@ -75,6 +80,30 @@ function toolDefinitions() {
75
80
  },
76
81
  },
77
82
  },
83
+ {
84
+ type: 'function',
85
+ function: {
86
+ name: 'todo_write',
87
+ description: '更新当前会话的结构化步骤清单(实时驱动胶囊状态与单人面板折叠进度条)。',
88
+ parameters: {
89
+ type: 'object',
90
+ properties: {
91
+ todos: {
92
+ type: 'array',
93
+ items: {
94
+ type: 'object',
95
+ properties: {
96
+ text: { type: 'string' },
97
+ status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] },
98
+ },
99
+ required: ['text', 'status'],
100
+ },
101
+ },
102
+ },
103
+ required: ['todos'],
104
+ },
105
+ },
106
+ },
78
107
  {
79
108
  type: 'function',
80
109
  function: {
@@ -153,6 +182,20 @@ function toolDefinitions() {
153
182
  },
154
183
  },
155
184
  },
185
+ {
186
+ type: 'function',
187
+ function: {
188
+ name: 'probe_command',
189
+ description: '在当前工作区受控执行终端命令(如运行单测或检查构建;非只读命令将按用户安全策略触发胶囊旁一键审批)。',
190
+ parameters: {
191
+ type: 'object',
192
+ properties: {
193
+ command: { type: 'string', description: '要执行的单行命令,如 pnpm test' },
194
+ },
195
+ required: ['command'],
196
+ },
197
+ },
198
+ },
156
199
  {
157
200
  type: 'function',
158
201
  function: {
@@ -235,7 +278,7 @@ function toolDefinitions() {
235
278
  type: 'function',
236
279
  function: {
237
280
  name: 'clado_links',
238
- description: '建立或断开卡片/内容行连线(action: list|connect|disconnect;支持对称行连行:起点可用行内 position:{mode:"replace",anchor} 或 sourcePoint,落点可用 targetPoint 指定正文行 line+text / 代码行 code / 表格行 table / Mermaid 节点 mermaid)。',
281
+ description: '建立或断开卡片/内容行连线(action: list|connect|disconnect;支持对称行连行)。',
239
282
  parameters: {
240
283
  type: 'object',
241
284
  properties: {
@@ -274,6 +317,80 @@ function toolDefinitions() {
274
317
  },
275
318
  },
276
319
  ];
320
+
321
+ if (enablePeers) {
322
+ list.push(
323
+ {
324
+ type: 'function',
325
+ function: {
326
+ name: 'spawn_peer',
327
+ description: '在当前工作区派生一位平级同伴会话(自动携带对应人设初始上下文并在后台并行推进,显示于底部会话胶囊栏)。',
328
+ parameters: {
329
+ type: 'object',
330
+ properties: {
331
+ name: { type: 'string', description: '同伴会话简称,如「测试分身」或「后端实现」' },
332
+ persona: { type: 'string', enum: ['architect', 'coder', 'qa', 'auditor'], description: '同伴角色人设' },
333
+ task: { type: 'string', description: '清晰的并行任务目标与关联画布/代码路径' },
334
+ },
335
+ required: ['name', 'persona', 'task'],
336
+ },
337
+ },
338
+ },
339
+ {
340
+ type: 'function',
341
+ function: {
342
+ name: 'message_peer',
343
+ description: '向同一工作区内的另一位平级同伴会话发送实时协作或交接消息(被呼叫方底部边缘条将点亮呼叫方颜色并自动唤醒)。',
344
+ parameters: {
345
+ type: 'object',
346
+ properties: {
347
+ target: { type: 'string', description: '目标同伴会话的 id 或名称(如「测试分身」)' },
348
+ message: { type: 'string', description: '要发送的交接或协作内容' },
349
+ kind: { type: 'string', enum: ['request', 'notify'], description: 'request 表示请求对方处理,notify 为单向通知(禁止礼貌回执防死循环)' },
350
+ },
351
+ required: ['target', 'message'],
352
+ },
353
+ },
354
+ },
355
+ );
356
+ }
357
+ list.push(
358
+ {
359
+ type: 'function',
360
+ function: {
361
+ name: 'canvas_objects_read',
362
+ description: '只读读取当前子工作区 `.clado/objects/` 下的多实例画布组件(如多张便签或专注播放器子项状态),支持按 id 单独读取或列出全部。',
363
+ parameters: {
364
+ type: 'object',
365
+ properties: {
366
+ id: { type: 'string', description: '可选对象 ID(如 note-1);省略则列出全部画布对象' },
367
+ },
368
+ },
369
+ },
370
+ },
371
+ {
372
+ type: 'function',
373
+ function: {
374
+ name: 'canvas_objects_write',
375
+ description: '在画布上新建、修改或删除多实例画布对象(如贴便签 sticky 或更新组件数据),结果实时同步到用户画布。',
376
+ parameters: {
377
+ type: 'object',
378
+ properties: {
379
+ action: { type: 'string', enum: ['save', 'delete'] },
380
+ id: { type: 'string', description: '对象 ID(新建可省略自动生成,修改/删除必填)' },
381
+ kind: { type: 'string', enum: ['sticky', 'music', 'widget'] },
382
+ title: { type: 'string' },
383
+ text: { type: 'string', description: '便签正文内容' },
384
+ tint: { type: 'string', enum: ['amber', 'mint', 'lavender', 'sky'] },
385
+ x: { type: 'number' },
386
+ y: { type: 'number' },
387
+ },
388
+ required: ['action'],
389
+ },
390
+ },
391
+ },
392
+ );
393
+ return list;
277
394
  }
278
395
 
279
396
  function summarizeDiagnostics(report) {
@@ -288,14 +405,30 @@ function summarizeDiagnostics(report) {
288
405
  };
289
406
  }
290
407
 
291
- function isWriteTool(name, args) {
408
+ export function isWriteTool(name, args) {
292
409
  if (name === 'clado_batch') return !args?.dryRun;
293
410
  if (name === 'clado_documents') return ['create', 'copy', 'update', 'rename', 'delete'].includes(args?.action);
294
411
  if (name === 'clado_nodes') return ['create', 'insert', 'update', 'rename', 'move', 'delete'].includes(args?.action);
295
412
  if (name === 'clado_links') return ['connect', 'disconnect'].includes(args?.action);
413
+ if (name === 'canvas_objects_write') return true;
296
414
  return false;
297
415
  }
298
416
 
417
+ function collectWriteTargetFiles(name, args) {
418
+ const files = new Set();
419
+ if (args?.file) files.add(args.file);
420
+ if (args?.newFile) files.add(args.newFile);
421
+ if (args?.targetFile) files.add(args.targetFile);
422
+ if (name === 'clado_batch' && Array.isArray(args?.operations)) {
423
+ for (const op of args.operations) {
424
+ if (op?.file) files.add(op.file);
425
+ if (op?.newFile) files.add(op.newFile);
426
+ if (op?.targetFile) files.add(op.targetFile);
427
+ }
428
+ }
429
+ return [...files];
430
+ }
431
+
299
432
  function describeChange(name, args, result) {
300
433
  const file = result?.file || args.targetFile || args.newFile || args.file || '';
301
434
  if (name === 'clado_documents') {
@@ -329,41 +462,113 @@ function describeChange(name, args, result) {
329
462
  return [];
330
463
  }
331
464
 
465
+ function humanizeToolStatus(name, args = {}) {
466
+ if (name === 'probe_tree') return '正在扫描项目目录…';
467
+ if (name === 'probe_search') return `正在检索 ${String(args.query || '代码').slice(0, 14)}…`;
468
+ if (name === 'probe_read') return `正在读取 ${String(args.file || '源码').split('/').pop()}…`;
469
+ if (name === 'probe_git_diff') return '正在对比 Git Diff…';
470
+ if (name === 'probe_command') return `正在执行 ${String(args.command || '命令').slice(0, 16)}…`;
471
+ if (name === 'spawn_peer') return `正在派生同伴「${args.name || ''}」…`;
472
+ if (name === 'message_peer') return `正在呼叫「${args.target || ''}」…`;
473
+ if (name === 'canvas_objects_read') return args.id ? `正在读取组件 #${args.id}…` : '正在读取画布组件…';
474
+ if (name === 'canvas_objects_write') return args.action === 'delete' ? `正在移除组件 #${args.id || ''}…` : '正在更新画布便签/组件…';
475
+ if (name.startsWith('clado_')) {
476
+ const target = (Array.isArray(args.node) && args.node.at(-1)) || args.title || args.file || '画布';
477
+ return `正在编辑画布 · ${String(target).slice(0, 12)}…`;
478
+ }
479
+ return `正在调用 ${name}…`;
480
+ }
481
+
332
482
  export async function runVerticalAgent({
333
483
  workspace,
484
+ rootWorkspace = workspace,
485
+ documentRoot = workspace,
334
486
  stateDir,
335
487
  workspaceService,
336
488
  events = null,
337
489
  config = {},
490
+ debugConfig = null,
338
491
  history = [],
492
+ canvasBaseline = null,
493
+ activePeerLocks = [],
494
+ incomingPeerMessages = [],
495
+ peerCoordinator = null,
339
496
  resumeToolResult = null,
497
+ resumeCommandResult = null,
498
+ sessionCommandAutoAllow = false,
499
+ drainSteering = null,
340
500
  input = {},
341
501
  mode = 'general',
502
+ execMode = 'act',
342
503
  persona = 'architect',
504
+ todos: initialTodos = [],
343
505
  emit = () => {},
344
506
  signal,
345
507
  fetchImpl = fetch,
346
508
  }) {
347
- const activePersona = resolvePersona(persona || config.persona, config.personaPrompt);
509
+ const effectiveDebug = debugConfig || (stateDir ? readAgentDebugConfig(stateDir).config : undefined);
510
+ const activePersona = resolvePersona(persona || config.persona, config.personaPrompt, effectiveDebug?.personas);
511
+ const isPlanOnly = execMode === 'plan';
512
+
348
513
  const run = createRunRecord(stateDir, {
349
514
  kind: 'builtin',
350
515
  mode,
351
516
  file: input.canvas?.file || '',
352
- instruction: resumeToolResult ? `[回答提问] ${resumeToolResult.answer}` : (input.text || ''),
517
+ instruction: resumeToolResult
518
+ ? `[回答提问] ${resumeToolResult.answer}`
519
+ : resumeCommandResult
520
+ ? `[命令审批] ${resumeCommandResult.decision}`
521
+ : (input.text || ''),
353
522
  });
354
523
  emit({ type: 'run', run });
355
524
 
356
525
  const touchedFiles = new Set();
357
526
  const changes = [];
358
- const systemText = [
527
+ const checkpointFiles = {};
528
+ let currentTodos = Array.isArray(initialTodos) ? [...initialTodos] : [];
529
+
530
+ function snapshotFileBeforeWrite(relFile) {
531
+ if (!documentRoot || !relFile || Object.hasOwn(checkpointFiles, relFile)) return;
532
+ try {
533
+ const full = workspacePath(documentRoot, relFile, true);
534
+ if (existsSync(full)) {
535
+ checkpointFiles[relFile] = { existed: true, content: readFileSync(full, 'utf8') };
536
+ } else {
537
+ checkpointFiles[relFile] = { existed: false, content: '' };
538
+ }
539
+ } catch {}
540
+ }
541
+
542
+ const baseSystemPrompt = [
359
543
  `你是 Clado 独立可视化研发设计 Agent(当前人设:${activePersona.name})。`,
360
544
  activePersona.prompt,
361
545
  '核心交互原则:画布是用户的主观察面,聊天回复保持精炼(3–6 行要点),把结构化内容沉淀在画布里。',
546
+ isPlanOnly
547
+ ? '【重要限制:当前处于「规划(只读)」模式】严禁修改画布文档或执行写命令;仅允许使用只读探针查证、拆解步骤(todo_write)或调用 ask_user 与用户对齐方案。'
548
+ : '',
362
549
  MODE_PROMPTS[mode] || MODE_PROMPTS.general,
363
- ].join('\n\n');
550
+ ].filter(Boolean).join('\n\n');
364
551
 
365
- const prior = compactMessages(history);
366
- const conversation = [...prior];
552
+ const isResume = Boolean(resumeToolResult || resumeCommandResult);
553
+ const segmented = buildSegmentedPromptContext({
554
+ workspace,
555
+ rootWorkspace,
556
+ documentRoot,
557
+ stateDir,
558
+ debugConfig: effectiveDebug,
559
+ baseSystemPrompt,
560
+ history,
561
+ canvas: input.canvas || null,
562
+ canvasBaseline,
563
+ activePeerLocks,
564
+ incomingPeerMessages,
565
+ userInstruction: input.text || '',
566
+ isResumeTool: isResume,
567
+ });
568
+
569
+ emit({ type: 'telemetry', telemetry: segmented.telemetry });
570
+
571
+ const conversation = [...segmented.conversation];
367
572
  if (resumeToolResult) {
368
573
  conversation.push({
369
574
  role: 'tool',
@@ -374,17 +579,42 @@ export async function runVerticalAgent({
374
579
  answer: resumeToolResult.answer,
375
580
  }),
376
581
  });
582
+ } else if (resumeCommandResult) {
583
+ let cmdPayload;
584
+ if (resumeCommandResult.decision === 'deny') {
585
+ cmdPayload = { approved: false, skipped: true, message: '用户拒绝执行该命令,请在不运行该命令的前提下继续或调整方案。' };
586
+ } else {
587
+ emit({ type: 'status', text: `正在执行已授权命令:${resumeCommandResult.command.slice(0, 28)}…` });
588
+ cmdPayload = await executeWorkspaceCommand(workspace, { command: resumeCommandResult.command });
589
+ }
590
+ conversation.push({
591
+ role: 'tool',
592
+ tool_call_id: resumeCommandResult.toolCallId,
593
+ content: JSON.stringify(cmdPayload),
594
+ });
377
595
  } else {
378
- const contextMsg = input.canvas
379
- ? `当前工作区:${workspace}\n当前画布:${input.canvas.file}\n当前选中标题:${JSON.stringify(input.canvas.selection || [])}`
380
- : `当前工作区:${workspace}`;
381
- conversation.push({ role: 'user', content: `${contextMsg}\n\n用户指令:\n${input.text}` });
596
+ conversation.push({ role: 'user', content: segmented.seg4UserContent });
382
597
  }
383
598
 
384
- const tools = toolDefinitions();
599
+ const tools = toolDefinitions({ enablePeers: Boolean(peerCoordinator) });
385
600
 
386
601
  async function executeTool(name, rawArgs) {
387
602
  const args = rawArgs && typeof rawArgs === 'object' ? rawArgs : {};
603
+ if (name === 'todo_write') {
604
+ const list = Array.isArray(args.todos)
605
+ ? args.todos.slice(0, 12).map(t => ({
606
+ text: String(t?.text || '').trim().slice(0, 120),
607
+ status: ['pending', 'in_progress', 'completed'].includes(t?.status) ? t.status : 'pending',
608
+ })).filter(t => t.text)
609
+ : [];
610
+ currentTodos = list;
611
+ emit({ type: 'todos', todos: currentTodos });
612
+ const activeIdx = list.findIndex(t => t.status === 'in_progress');
613
+ if (activeIdx >= 0) {
614
+ emit({ type: 'status', text: `[${activeIdx + 1}/${list.length}] ${list[activeIdx].text}` });
615
+ }
616
+ return { ok: true, count: currentTodos.length };
617
+ }
388
618
  if (name === 'canvas_focus') {
389
619
  const targetFile = args.file || input.canvas?.file || '';
390
620
  const targetNode = Array.isArray(args.node) ? args.node : [];
@@ -401,8 +631,53 @@ export async function runVerticalAgent({
401
631
  if (name === 'probe_search') return await probeSearch(workspace, args);
402
632
  if (name === 'probe_read') return probeRead(workspace, args);
403
633
  if (name === 'probe_git_diff') return await probeGitDiff(workspace, args);
634
+ if (name === 'probe_command') {
635
+ if (isPlanOnly && classifyShellCommand(args.command) !== 'readonly') {
636
+ return { blockedByPlanMode: true, error: '当前处于【规划(只读)】模式,已拦截非只读命令。' };
637
+ }
638
+ return await executeWorkspaceCommand(workspace, args);
639
+ }
640
+ if (name === 'canvas_objects_read') {
641
+ if (!stateDir) return { objects: [] };
642
+ if (args.id) {
643
+ const obj = readCanvasObject(stateDir, args.id);
644
+ return obj ? { object: obj } : { error: `未找到画布对象:${args.id}` };
645
+ }
646
+ return { objects: listCanvasObjects(stateDir, 60) };
647
+ }
648
+ if (name === 'canvas_objects_write') {
649
+ if (isPlanOnly) {
650
+ return { blockedByPlanMode: true, error: '当前处于【规划(只读)】模式,已拦截画布组件写入操作。' };
651
+ }
652
+ if (!stateDir) throw new Error('工作区状态目录未挂载。');
653
+ if (args.action === 'delete') {
654
+ const deleted = deleteCanvasObject(stateDir, args.id);
655
+ if (deleted) events?.emit(workspace, 'objects.updated', { action: 'delete', id: args.id });
656
+ return { deleted, id: args.id };
657
+ }
658
+ const saved = saveCanvasObject(stateDir, args);
659
+ changes.push({ kind: 'object', file: input.canvas?.file || '', node: null, label: `更新组件「${saved.title}」` });
660
+ events?.emit(workspace, 'objects.updated', { action: 'save', object: saved });
661
+ return { saved: true, object: saved };
662
+ }
663
+ if (name === 'spawn_peer' && peerCoordinator) {
664
+ if (isPlanOnly) return { blockedByPlanMode: true, error: '规划只读模式下暂不自动派生执行分身,请先向用户汇报分工方案。' };
665
+ return await peerCoordinator.spawnPeer(args);
666
+ }
667
+ if (name === 'message_peer' && peerCoordinator) {
668
+ return await peerCoordinator.messagePeer(args);
669
+ }
404
670
  if (name.startsWith('clado_')) {
405
671
  if (!workspaceService) throw new Error('工作区服务未挂载。');
672
+ if (isPlanOnly && isWriteTool(name, args)) {
673
+ return {
674
+ blockedByPlanMode: true,
675
+ error: '当前处于【规划(只读)】模式,已拦截画布写入操作。请先输出方案或让用户切换到「执行」模式。',
676
+ };
677
+ }
678
+ if (isWriteTool(name, args)) {
679
+ for (const f of collectWriteTargetFiles(name, args)) snapshotFileBeforeWrite(f);
680
+ }
406
681
  const result = await workspaceService(name, { ...args, workspace });
407
682
  if (isWriteTool(name, args)) {
408
683
  const file = result?.file || args.file || args.newFile || '';
@@ -418,18 +693,52 @@ export async function runVerticalAgent({
418
693
  throw new Error('未知工具:' + name);
419
694
  }
420
695
 
696
+ const buildCheckpoint = () => {
697
+ const keys = Object.keys(checkpointFiles);
698
+ if (!keys.length) return null;
699
+ return {
700
+ id: randomUUID(),
701
+ createdAt: new Date().toISOString(),
702
+ label: changes[0]?.label || `修改 ${keys.join(', ')}`,
703
+ files: checkpointFiles,
704
+ };
705
+ };
706
+
421
707
  try {
422
708
  let finalText = '';
423
709
  for (let step = 1; step <= MAX_STEPS; step++) {
424
710
  if (signal?.aborted) {
425
711
  updateRunRecord(stateDir, run, { status: 'cancelled', touchedFiles: [...touchedFiles] });
426
- return { stopReason: 'cancelled', assistantText: finalText, conversation, changes, pendingQuestion: null, run };
712
+ return {
713
+ stopReason: 'cancelled',
714
+ assistantText: finalText,
715
+ conversation,
716
+ changes,
717
+ todos: currentTodos,
718
+ nextBaseline: segmented.nextBaseline,
719
+ checkpoint: buildCheckpoint(),
720
+ pendingQuestion: null,
721
+ pendingCommand: null,
722
+ run,
723
+ };
724
+ }
725
+
726
+ // 检查是否有运行中途人类插话纠偏(Steering)
727
+ if (typeof drainSteering === 'function') {
728
+ const steered = drainSteering();
729
+ if (Array.isArray(steered) && steered.length) {
730
+ for (const text of steered) {
731
+ conversation.push({ role: 'user', content: `【用户运行中实时插话纠偏】\n${text}` });
732
+ }
733
+ emit({ type: 'status', text: '已吸收插话纠偏,调整执行方向…' });
734
+ }
427
735
  }
736
+
428
737
  emit({ type: 'status', text: step === 1 ? `${activePersona.name} 正在思考…` : `第 ${step} 步推理与核验…` });
429
738
 
430
739
  const turnResult = await streamModelTurn({
431
740
  config,
432
- messages: [{ role: 'system', content: systemText }, ...conversation],
741
+ messages: [{ role: 'system', content: segmented.systemText }, ...conversation],
433
742
  tools,
434
743
  signal,
435
744
  fetchImpl,
@@ -456,7 +765,18 @@ export async function runVerticalAgent({
456
765
  touchedFiles: [...touchedFiles],
457
766
  });
458
767
  emit({ type: 'run', run: saved });
459
- return { stopReason: 'end_turn', assistantText: finalText, conversation, changes, pendingQuestion: null, run: saved };
768
+ return {
769
+ stopReason: 'end_turn',
770
+ assistantText: finalText,
771
+ conversation,
772
+ changes,
773
+ todos: currentTodos,
774
+ nextBaseline: segmented.nextBaseline,
775
+ checkpoint: buildCheckpoint(),
776
+ pendingQuestion: null,
777
+ pendingCommand: null,
778
+ run: saved,
779
+ };
460
780
  }
461
781
 
462
782
  let hadVerifyErrors = false;
@@ -466,7 +786,7 @@ export async function runVerticalAgent({
466
786
  let parsedArgs = {};
467
787
  try { parsedArgs = JSON.parse(call?.function?.arguments || '{}'); } catch {}
468
788
 
469
- // ask_user:暂停当前轮次,向观察者展示结构化决策卡并高亮目标卡片
789
+ // 1. ask_user:暂停当前轮次,等待观察者拍板
470
790
  if (toolName === 'ask_user') {
471
791
  const options = Array.isArray(parsedArgs.options)
472
792
  ? parsedArgs.options.slice(0, 6).map((opt, idx) => ({
@@ -505,11 +825,57 @@ export async function runVerticalAgent({
505
825
  assistantText: finalText,
506
826
  conversation,
507
827
  changes,
828
+ todos: currentTodos,
829
+ nextBaseline: segmented.nextBaseline,
830
+ checkpoint: buildCheckpoint(),
508
831
  pendingQuestion,
832
+ pendingCommand: null,
509
833
  run: paused,
510
834
  };
511
835
  }
512
836
 
837
+ // 2. probe_command:根据安全分级与用户权限策略决定直接放行还是弹出胶囊旁轻量审批条
838
+ if (toolName === 'probe_command') {
839
+ const cmdStr = String(parsedArgs.command || '').trim();
840
+ const safety = classifyShellCommand(cmdStr);
841
+ const permMode = effectiveDebug?.commandPermission || 'readonly_free';
842
+ const needsApproval = !isPlanOnly
843
+ && safety === 'write_or_exec'
844
+ && !sessionCommandAutoAllow
845
+ && permMode !== 'allow_all';
846
+ const forceAsk = !isPlanOnly && safety === 'readonly' && permMode === 'ask_always' && !sessionCommandAutoAllow;
847
+
848
+ if (needsApproval || forceAsk) {
849
+ const pendingCommand = {
850
+ id: randomUUID(),
851
+ toolCallId: callId,
852
+ command: cmdStr.slice(0, 400),
853
+ };
854
+ emit({ type: 'tool', id: callId, title: 'probe_command', status: 'pending' });
855
+ if (changes.length) emit({ type: 'changes', items: changes });
856
+ emit({ type: 'command_approval', approval: pendingCommand });
857
+ const paused = updateRunRecord(stateDir, run, {
858
+ status: 'waiting_user',
859
+ summary: `请求执行命令:${pendingCommand.command}`,
860
+ touchedFiles: [...touchedFiles],
861
+ });
862
+ emit({ type: 'run', run: paused });
863
+ return {
864
+ stopReason: 'awaiting_command',
865
+ assistantText: finalText,
866
+ conversation,
867
+ changes,
868
+ todos: currentTodos,
869
+ nextBaseline: segmented.nextBaseline,
870
+ checkpoint: buildCheckpoint(),
871
+ pendingQuestion: null,
872
+ pendingCommand,
873
+ run: paused,
874
+ };
875
+ }
876
+ }
877
+
878
+ emit({ type: 'status', text: humanizeToolStatus(toolName, parsedArgs) });
513
879
  emit({ type: 'tool', id: callId, title: toolName, status: 'in_progress' });
514
880
  let output;
515
881
  try {
@@ -543,7 +909,18 @@ export async function runVerticalAgent({
543
909
  touchedFiles: [...touchedFiles],
544
910
  });
545
911
  emit({ type: 'run', run: saved });
546
- return { stopReason: 'max_turn_requests', assistantText: finalText, conversation, changes, pendingQuestion: null, run: saved };
912
+ return {
913
+ stopReason: 'max_turn_requests',
914
+ assistantText: finalText,
915
+ conversation,
916
+ changes,
917
+ todos: currentTodos,
918
+ nextBaseline: segmented.nextBaseline,
919
+ checkpoint: buildCheckpoint(),
920
+ pendingQuestion: null,
921
+ pendingCommand: null,
922
+ run: saved,
923
+ };
547
924
  } catch (error) {
548
925
  const cancelled = signal?.aborted || error?.name === 'AbortError';
549
926
  updateRunRecord(stateDir, run, {
@@ -551,7 +928,20 @@ export async function runVerticalAgent({
551
928
  summary: cancelled ? '已取消' : String(error.message || '').slice(0, 300),
552
929
  touchedFiles: [...touchedFiles],
553
930
  });
554
- if (cancelled) return { stopReason: 'cancelled', assistantText: '', conversation, changes, pendingQuestion: null, run };
931
+ if (cancelled) {
932
+ return {
933
+ stopReason: 'cancelled',
934
+ assistantText: '',
935
+ conversation,
936
+ changes,
937
+ todos: currentTodos,
938
+ nextBaseline: segmented.nextBaseline,
939
+ checkpoint: buildCheckpoint(),
940
+ pendingQuestion: null,
941
+ pendingCommand: null,
942
+ run,
943
+ };
944
+ }
555
945
  throw error;
556
946
  }
557
947
  }