cladogram 0.5.5-beta.9 → 0.6.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +102 -79
- package/bin/clado.js +1 -1
- package/docs/release.md +7 -0
- package/package.json +3 -3
- package/plugins/agent/index.js +928 -3131
- package/plugins/agent/style.css +404 -1511
- package/plugins/brand/index.js +84 -466
- package/plugins/brand/style.css +39 -172
- package/plugins/directory/index.js +10 -10
- package/plugins/view-controls/index.js +17 -1
- package/plugins/view-controls/style.css +47 -29
- package/src/agent/clado-tools.js +299 -0
- package/src/agent/pi-bridge.js +487 -0
- package/src/agent/pi-config.js +630 -0
- package/src/html/plugin-ui.css +159 -134
- package/src/html/plugin-ui.js +3 -2
- package/src/server/agent.js +329 -1590
- package/src/server/assets/library.css +396 -11
- package/src/server/assets/library.html +37 -4
- package/src/server/assets/library.js +428 -203
- package/src/server/plugin-registry.js +7 -7
- package/src/server/plugins.js +1 -1
- package/src/server/workspace-hub.js +50 -0
- package/src/server/workspace.js +4 -15
- package/src/agent/commands.js +0 -204
- package/src/agent/context.js +0 -445
- package/src/agent/executors.js +0 -213
- package/src/agent/mcp-client.js +0 -308
- package/src/agent/probe.js +0 -234
- package/src/agent/providers/anthropic.js +0 -220
- package/src/agent/providers/index.js +0 -235
- package/src/agent/providers/openai.js +0 -146
- package/src/agent/runtime.js +0 -995
- package/src/agent/sessions.js +0 -336
- package/src/agent/skills.js +0 -190
package/src/agent/runtime.js
DELETED
|
@@ -1,995 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Clado 独立垂直 Agent 运行时(系统级内置插件 clado.agent 的大脑引擎)。
|
|
3
|
-
*
|
|
4
|
-
* 核心特性:
|
|
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(平滑镜头引导)。
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
import { randomUUID } from 'node:crypto';
|
|
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';
|
|
17
|
-
import { createRunRecord, updateRunRecord } from './executors.js';
|
|
18
|
-
import { classifyShellCommand, executeWorkspaceCommand, probeGitDiff, probeRead, probeSearch, probeTree } from './probe.js';
|
|
19
|
-
import { streamModelTurn } from './providers/index.js';
|
|
20
|
-
import { resolvePersona } from './sessions.js';
|
|
21
|
-
import { callExternalMcpTool, discoverExternalMcpTools } from './mcp-client.js';
|
|
22
|
-
import { formatSkillsCatalog, listSkills, readSkill } from './skills.js';
|
|
23
|
-
|
|
24
|
-
const MAX_STEPS = 12;
|
|
25
|
-
|
|
26
|
-
const MODE_PROMPTS = {
|
|
27
|
-
design: [
|
|
28
|
-
'当前工作模式:【研发设计与代码架构】',
|
|
29
|
-
'1. 涉及存量代码时,先调用 probe_tree / probe_search / probe_read 核对真实类名、方法名与边界,绝不编造。',
|
|
30
|
-
'2. 先用 clado_templates 读取对应模板(如 call-chain / data-design / business-flow)再创建或修改 .md 画布。',
|
|
31
|
-
'3. 同画布跨卡连线支持「卡片 + Tag」二元目标:可在目标行打唯一语义 Tag(有字胶囊 `[新增]{#id .green}`、无字小圆点 `[]{#id .amber}`、代码行尾 `// {#id .blue}`、Mermaid `%% {#node .green}`),再以 `[文案](#id)` 精准连线,也可兼容 `clado:code:` / `clado:to:`;避免卡片末尾裸卡片连卡片。',
|
|
32
|
-
'4. 遇到需求歧义或方案二选一时,优先调用 ask_user 给出清晰选项让观察者拍板,不要替用户擅自猜测。',
|
|
33
|
-
'5. 多步骤任务可调用 todo_write 维护步骤进度;每次修改后核对 diagnostics,确保 0 error 再给 3–5 行精炼汇报。',
|
|
34
|
-
].join('\n'),
|
|
35
|
-
qa: [
|
|
36
|
-
'当前工作模式:【脑图测试用例编写】',
|
|
37
|
-
'1. 先阅读当前画布或关联源码梳理功能点与边界条件。',
|
|
38
|
-
'2. 优先使用 test-cases 模板创建或完善 .md 测试用例画布(适配脑图视图):每个模块覆盖正常流、边界条件、异常流与回归检查点。',
|
|
39
|
-
'3. 存在待确认验收口径时调用 ask_user 向用户确认;修改后确保 diagnostics 0 error。',
|
|
40
|
-
].join('\n'),
|
|
41
|
-
audit: [
|
|
42
|
-
'当前工作模式:【开发后 Diff 验收与系统归档】',
|
|
43
|
-
'1. 首先调用 probe_git_diff 读取本地真实代码变更,必要时用 probe_read 核对细节。',
|
|
44
|
-
'2. 将真实代码变更与画布设计契约及测试用例逐项比对,明确列出已满足项、遗漏项或偏离项。',
|
|
45
|
-
'3. 如需归档或更新画布状态,使用 clado_nodes / clado_batch 更新并保证 diagnostics 0 error。',
|
|
46
|
-
].join('\n'),
|
|
47
|
-
general: [
|
|
48
|
-
'当前工作模式:【Clado 画布协作】',
|
|
49
|
-
'普通问题直接简明回答;涉及本地源码先用只读探针查证;涉及画布修改直接调用内核工具并保证 diagnostics 0 error;需要用户拍板时调用 ask_user。',
|
|
50
|
-
].join('\n'),
|
|
51
|
-
};
|
|
52
|
-
|
|
53
|
-
function toolDefinitions({ enablePeers = false } = {}) {
|
|
54
|
-
const list = [
|
|
55
|
-
{
|
|
56
|
-
type: 'function',
|
|
57
|
-
function: {
|
|
58
|
-
name: 'ask_user',
|
|
59
|
-
description: '向画布旁的观察者提出结构化问题或方案选项,暂停执行等待用户点击确认后继续。适用于需求歧义、架构权衡或高影响决策。',
|
|
60
|
-
parameters: {
|
|
61
|
-
type: 'object',
|
|
62
|
-
properties: {
|
|
63
|
-
question: { type: 'string', description: '清晰简明的问题正文' },
|
|
64
|
-
options: {
|
|
65
|
-
type: 'array',
|
|
66
|
-
description: '2-4 个供用户一键点选的候选方案',
|
|
67
|
-
items: {
|
|
68
|
-
type: 'object',
|
|
69
|
-
properties: {
|
|
70
|
-
id: { type: 'string' },
|
|
71
|
-
label: { type: 'string', description: '简短选项标题' },
|
|
72
|
-
detail: { type: 'string', description: '可选一句补充说明' },
|
|
73
|
-
},
|
|
74
|
-
required: ['label'],
|
|
75
|
-
},
|
|
76
|
-
},
|
|
77
|
-
allowCustom: { type: 'boolean', description: '是否允许用户输入自定义回答,默认 true' },
|
|
78
|
-
file: { type: 'string', description: '可选关联文档路径,用于高亮对应卡片待决策状态' },
|
|
79
|
-
targetNode: { type: 'array', items: { type: 'string' }, description: '可选关联卡片标题路径' },
|
|
80
|
-
},
|
|
81
|
-
required: ['question'],
|
|
82
|
-
},
|
|
83
|
-
},
|
|
84
|
-
},
|
|
85
|
-
{
|
|
86
|
-
type: 'function',
|
|
87
|
-
function: {
|
|
88
|
-
name: 'todo_write',
|
|
89
|
-
description: '更新当前会话的结构化步骤清单(实时驱动胶囊状态与单人面板折叠进度条)。',
|
|
90
|
-
parameters: {
|
|
91
|
-
type: 'object',
|
|
92
|
-
properties: {
|
|
93
|
-
todos: {
|
|
94
|
-
type: 'array',
|
|
95
|
-
items: {
|
|
96
|
-
type: 'object',
|
|
97
|
-
properties: {
|
|
98
|
-
text: { type: 'string' },
|
|
99
|
-
status: { type: 'string', enum: ['pending', 'in_progress', 'completed'] },
|
|
100
|
-
},
|
|
101
|
-
required: ['text', 'status'],
|
|
102
|
-
},
|
|
103
|
-
},
|
|
104
|
-
},
|
|
105
|
-
required: ['todos'],
|
|
106
|
-
},
|
|
107
|
-
},
|
|
108
|
-
},
|
|
109
|
-
{
|
|
110
|
-
type: 'function',
|
|
111
|
-
function: {
|
|
112
|
-
name: 'canvas_focus',
|
|
113
|
-
description: '引导用户画布镜头平滑平移并高亮指定卡片或小节,方便边讲解边指向具体位置。',
|
|
114
|
-
parameters: {
|
|
115
|
-
type: 'object',
|
|
116
|
-
properties: {
|
|
117
|
-
file: { type: 'string', description: '目标文档相对路径' },
|
|
118
|
-
node: { type: 'array', items: { type: 'string' }, description: '目标卡片或小节标题路径' },
|
|
119
|
-
reason: { type: 'string', description: '展示在画布底部提示条的简短说明' },
|
|
120
|
-
},
|
|
121
|
-
required: ['node'],
|
|
122
|
-
},
|
|
123
|
-
},
|
|
124
|
-
},
|
|
125
|
-
{
|
|
126
|
-
type: 'function',
|
|
127
|
-
function: {
|
|
128
|
-
name: 'load_skill',
|
|
129
|
-
description: '按需加载已挂载技能库(SKILL.md)中的完整专业指南与 SOP。',
|
|
130
|
-
parameters: {
|
|
131
|
-
type: 'object',
|
|
132
|
-
properties: {
|
|
133
|
-
name: { type: 'string', description: '技能标识(slug)或名称' },
|
|
134
|
-
},
|
|
135
|
-
required: ['name'],
|
|
136
|
-
},
|
|
137
|
-
},
|
|
138
|
-
},
|
|
139
|
-
{
|
|
140
|
-
type: 'function',
|
|
141
|
-
function: {
|
|
142
|
-
name: 'probe_tree',
|
|
143
|
-
description: '只读列出本地项目仓库目录树与源码文件(跳过 .git / node_modules / .clado)。',
|
|
144
|
-
parameters: {
|
|
145
|
-
type: 'object',
|
|
146
|
-
properties: {
|
|
147
|
-
path: { type: 'string' },
|
|
148
|
-
maxDepth: { type: 'integer' },
|
|
149
|
-
maxFiles: { type: 'integer' },
|
|
150
|
-
},
|
|
151
|
-
},
|
|
152
|
-
},
|
|
153
|
-
},
|
|
154
|
-
{
|
|
155
|
-
type: 'function',
|
|
156
|
-
function: {
|
|
157
|
-
name: 'probe_search',
|
|
158
|
-
description: '只读在本地代码仓库中检索关键字、类名、方法名或符号调用。',
|
|
159
|
-
parameters: {
|
|
160
|
-
type: 'object',
|
|
161
|
-
properties: {
|
|
162
|
-
query: { type: 'string' },
|
|
163
|
-
path: { type: 'string' },
|
|
164
|
-
glob: { type: 'string' },
|
|
165
|
-
maxResults: { type: 'integer' },
|
|
166
|
-
},
|
|
167
|
-
required: ['query'],
|
|
168
|
-
},
|
|
169
|
-
},
|
|
170
|
-
},
|
|
171
|
-
{
|
|
172
|
-
type: 'function',
|
|
173
|
-
function: {
|
|
174
|
-
name: 'probe_read',
|
|
175
|
-
description: '只读读取本地源码文件的指定行区间(1-indexed,单次最多 400 行)。',
|
|
176
|
-
parameters: {
|
|
177
|
-
type: 'object',
|
|
178
|
-
properties: {
|
|
179
|
-
file: { type: 'string' },
|
|
180
|
-
startLine: { type: 'integer' },
|
|
181
|
-
endLine: { type: 'integer' },
|
|
182
|
-
},
|
|
183
|
-
required: ['file'],
|
|
184
|
-
},
|
|
185
|
-
},
|
|
186
|
-
},
|
|
187
|
-
{
|
|
188
|
-
type: 'function',
|
|
189
|
-
function: {
|
|
190
|
-
name: 'probe_git_diff',
|
|
191
|
-
description: '只读查看本地仓库 git status、变更统计与 diff,用于存量改造分析和外包开发后验收。',
|
|
192
|
-
parameters: {
|
|
193
|
-
type: 'object',
|
|
194
|
-
properties: {
|
|
195
|
-
ref: { type: 'string' },
|
|
196
|
-
statOnly: { type: 'boolean' },
|
|
197
|
-
},
|
|
198
|
-
},
|
|
199
|
-
},
|
|
200
|
-
},
|
|
201
|
-
{
|
|
202
|
-
type: 'function',
|
|
203
|
-
function: {
|
|
204
|
-
name: 'probe_command',
|
|
205
|
-
description: '在当前工作区受控执行终端命令(如运行单测或检查构建;非只读命令将按用户安全策略触发胶囊旁一键审批)。',
|
|
206
|
-
parameters: {
|
|
207
|
-
type: 'object',
|
|
208
|
-
properties: {
|
|
209
|
-
command: { type: 'string', description: '要执行的单行命令,如 pnpm test' },
|
|
210
|
-
},
|
|
211
|
-
required: ['command'],
|
|
212
|
-
},
|
|
213
|
-
},
|
|
214
|
-
},
|
|
215
|
-
{
|
|
216
|
-
type: 'function',
|
|
217
|
-
function: {
|
|
218
|
-
name: 'clado_workspace',
|
|
219
|
-
description: '查看/搜索/校验当前 Clado 工作区或读取用户画布选区(action: inspect|search|validate|selection|workspaces|init)。',
|
|
220
|
-
parameters: {
|
|
221
|
-
type: 'object',
|
|
222
|
-
properties: {
|
|
223
|
-
action: { type: 'string', enum: ['init', 'inspect', 'search', 'validate', 'selection', 'workspaces'] },
|
|
224
|
-
query: { type: 'string' },
|
|
225
|
-
includeContent: { type: 'boolean' },
|
|
226
|
-
},
|
|
227
|
-
required: ['action'],
|
|
228
|
-
},
|
|
229
|
-
},
|
|
230
|
-
},
|
|
231
|
-
{
|
|
232
|
-
type: 'function',
|
|
233
|
-
function: {
|
|
234
|
-
name: 'clado_templates',
|
|
235
|
-
description: '列出或读取模板提示词(action: list|read;支持 call-chain、data-design、business-flow、requirement-overview、system-state、mind-expansion、test-cases)。',
|
|
236
|
-
parameters: {
|
|
237
|
-
type: 'object',
|
|
238
|
-
properties: {
|
|
239
|
-
action: { type: 'string', enum: ['list', 'read'] },
|
|
240
|
-
templateId: { type: 'string' },
|
|
241
|
-
view: { type: 'string', enum: ['prompt', 'source', 'full'] },
|
|
242
|
-
},
|
|
243
|
-
required: ['action'],
|
|
244
|
-
},
|
|
245
|
-
},
|
|
246
|
-
},
|
|
247
|
-
{
|
|
248
|
-
type: 'function',
|
|
249
|
-
function: {
|
|
250
|
-
name: 'clado_documents',
|
|
251
|
-
description: '管理画布文档(action: list|read|create|copy|update|rename|delete;推荐 .md,兼容 .mdc)。',
|
|
252
|
-
parameters: {
|
|
253
|
-
type: 'object',
|
|
254
|
-
properties: {
|
|
255
|
-
action: { type: 'string', enum: ['list', 'read', 'create', 'copy', 'update', 'rename', 'delete'] },
|
|
256
|
-
file: { type: 'string' },
|
|
257
|
-
newFile: { type: 'string' },
|
|
258
|
-
title: { type: 'string' },
|
|
259
|
-
templateId: { type: 'string' },
|
|
260
|
-
source: { type: 'string' },
|
|
261
|
-
view: { type: 'string', enum: ['full', 'nodes', 'source', 'summary'] },
|
|
262
|
-
expectedFileVersion: { type: 'string' },
|
|
263
|
-
expectedWorkspaceVersion: { type: 'string' },
|
|
264
|
-
},
|
|
265
|
-
required: ['action'],
|
|
266
|
-
},
|
|
267
|
-
},
|
|
268
|
-
},
|
|
269
|
-
{
|
|
270
|
-
type: 'function',
|
|
271
|
-
function: {
|
|
272
|
-
name: 'clado_nodes',
|
|
273
|
-
description: '读写画布卡片与小节节点(action: read|query|create|insert|update|rename|move|delete;node/parent 用标题数组)。',
|
|
274
|
-
parameters: {
|
|
275
|
-
type: 'object',
|
|
276
|
-
properties: {
|
|
277
|
-
action: { type: 'string', enum: ['read', 'query', 'create', 'insert', 'update', 'rename', 'move', 'delete'] },
|
|
278
|
-
file: { type: 'string' },
|
|
279
|
-
node: { type: 'array', items: { type: 'string' } },
|
|
280
|
-
parent: { type: 'array', items: { type: 'string' } },
|
|
281
|
-
title: { type: 'string' },
|
|
282
|
-
content: { type: 'string' },
|
|
283
|
-
position: { type: 'object' },
|
|
284
|
-
relation: { type: 'string' },
|
|
285
|
-
expectedNodeVersion: { type: 'string' },
|
|
286
|
-
expectedFileVersion: { type: 'string' },
|
|
287
|
-
expectedWorkspaceVersion: { type: 'string' },
|
|
288
|
-
},
|
|
289
|
-
required: ['action', 'file'],
|
|
290
|
-
},
|
|
291
|
-
},
|
|
292
|
-
},
|
|
293
|
-
{
|
|
294
|
-
type: 'function',
|
|
295
|
-
function: {
|
|
296
|
-
name: 'clado_links',
|
|
297
|
-
description: '建立或断开卡片/内容行连线(action: list|connect|disconnect;支持对称行连行)。',
|
|
298
|
-
parameters: {
|
|
299
|
-
type: 'object',
|
|
300
|
-
properties: {
|
|
301
|
-
action: { type: 'string', enum: ['list', 'connect', 'disconnect'] },
|
|
302
|
-
file: { type: 'string' },
|
|
303
|
-
node: { type: 'array', items: { type: 'string' } },
|
|
304
|
-
targetFile: { type: 'string' },
|
|
305
|
-
targetNode: { type: 'array', items: { type: 'string' } },
|
|
306
|
-
label: { type: 'string' },
|
|
307
|
-
position: { type: 'object' },
|
|
308
|
-
sourcePoint: { type: 'object' },
|
|
309
|
-
targetPoint: { type: 'object' },
|
|
310
|
-
linkIndex: { type: 'integer' },
|
|
311
|
-
expectedNodeVersion: { type: 'string' },
|
|
312
|
-
expectedFileVersion: { type: 'string' },
|
|
313
|
-
expectedWorkspaceVersion: { type: 'string' },
|
|
314
|
-
},
|
|
315
|
-
required: ['action', 'file'],
|
|
316
|
-
},
|
|
317
|
-
},
|
|
318
|
-
},
|
|
319
|
-
{
|
|
320
|
-
type: 'function',
|
|
321
|
-
function: {
|
|
322
|
-
name: 'clado_batch',
|
|
323
|
-
description: '事务化批量执行多个画布操作(operations 数组),任一步失败整批不落盘。',
|
|
324
|
-
parameters: {
|
|
325
|
-
type: 'object',
|
|
326
|
-
properties: {
|
|
327
|
-
operations: { type: 'array', items: { type: 'object' } },
|
|
328
|
-
expectedWorkspaceVersion: { type: 'string' },
|
|
329
|
-
dryRun: { type: 'boolean' },
|
|
330
|
-
},
|
|
331
|
-
required: ['operations'],
|
|
332
|
-
},
|
|
333
|
-
},
|
|
334
|
-
},
|
|
335
|
-
];
|
|
336
|
-
|
|
337
|
-
if (enablePeers) {
|
|
338
|
-
list.push(
|
|
339
|
-
{
|
|
340
|
-
type: 'function',
|
|
341
|
-
function: {
|
|
342
|
-
name: 'spawn_peer',
|
|
343
|
-
description: '在当前工作区派生一位平级同伴会话(自动携带对应人设初始上下文并在后台并行推进,显示于底部会话胶囊栏)。',
|
|
344
|
-
parameters: {
|
|
345
|
-
type: 'object',
|
|
346
|
-
properties: {
|
|
347
|
-
name: { type: 'string', description: '同伴会话简称,如「测试分身」或「后端实现」' },
|
|
348
|
-
persona: { type: 'string', enum: ['architect', 'coder', 'qa', 'auditor'], description: '同伴角色人设' },
|
|
349
|
-
task: { type: 'string', description: '清晰的并行任务目标与关联画布/代码路径' },
|
|
350
|
-
},
|
|
351
|
-
required: ['name', 'persona', 'task'],
|
|
352
|
-
},
|
|
353
|
-
},
|
|
354
|
-
},
|
|
355
|
-
{
|
|
356
|
-
type: 'function',
|
|
357
|
-
function: {
|
|
358
|
-
name: 'message_peer',
|
|
359
|
-
description: '向同一工作区内的另一位平级同伴会话发送实时协作或交接消息(被呼叫方底部边缘条将点亮呼叫方颜色并自动唤醒)。',
|
|
360
|
-
parameters: {
|
|
361
|
-
type: 'object',
|
|
362
|
-
properties: {
|
|
363
|
-
target: { type: 'string', description: '目标同伴会话的 id 或名称(如「测试分身」)' },
|
|
364
|
-
message: { type: 'string', description: '要发送的交接或协作内容' },
|
|
365
|
-
kind: { type: 'string', enum: ['request', 'notify'], description: 'request 表示请求对方处理,notify 为单向通知(禁止礼貌回执防死循环)' },
|
|
366
|
-
},
|
|
367
|
-
required: ['target', 'message'],
|
|
368
|
-
},
|
|
369
|
-
},
|
|
370
|
-
},
|
|
371
|
-
);
|
|
372
|
-
}
|
|
373
|
-
list.push(
|
|
374
|
-
{
|
|
375
|
-
type: 'function',
|
|
376
|
-
function: {
|
|
377
|
-
name: 'canvas_objects_read',
|
|
378
|
-
description: '只读读取当前子工作区 `.clado/objects/` 下的多实例画布组件(如多张便签或专注播放器子项状态),支持按 id 单独读取或列出全部。',
|
|
379
|
-
parameters: {
|
|
380
|
-
type: 'object',
|
|
381
|
-
properties: {
|
|
382
|
-
id: { type: 'string', description: '可选对象 ID(如 note-1);省略则列出全部画布对象' },
|
|
383
|
-
},
|
|
384
|
-
},
|
|
385
|
-
},
|
|
386
|
-
},
|
|
387
|
-
{
|
|
388
|
-
type: 'function',
|
|
389
|
-
function: {
|
|
390
|
-
name: 'canvas_objects_write',
|
|
391
|
-
description: '在画布上新建、修改或删除多实例画布对象(如贴便签 sticky 或更新组件数据),结果实时同步到用户画布。',
|
|
392
|
-
parameters: {
|
|
393
|
-
type: 'object',
|
|
394
|
-
properties: {
|
|
395
|
-
action: { type: 'string', enum: ['save', 'delete'] },
|
|
396
|
-
id: { type: 'string', description: '对象 ID(新建可省略自动生成,修改/删除必填)' },
|
|
397
|
-
kind: { type: 'string', enum: ['sticky', 'music', 'widget'] },
|
|
398
|
-
title: { type: 'string' },
|
|
399
|
-
text: { type: 'string', description: '便签正文内容' },
|
|
400
|
-
tint: { type: 'string', enum: ['amber', 'mint', 'lavender', 'sky'] },
|
|
401
|
-
x: { type: 'number' },
|
|
402
|
-
y: { type: 'number' },
|
|
403
|
-
},
|
|
404
|
-
required: ['action'],
|
|
405
|
-
},
|
|
406
|
-
},
|
|
407
|
-
},
|
|
408
|
-
);
|
|
409
|
-
return list;
|
|
410
|
-
}
|
|
411
|
-
|
|
412
|
-
function summarizeDiagnostics(report) {
|
|
413
|
-
const diags = Array.isArray(report?.diagnostics) ? report.diagnostics : [];
|
|
414
|
-
const errors = diags.filter(d => d.severity === 'error');
|
|
415
|
-
const warnings = diags.filter(d => d.severity === 'warn');
|
|
416
|
-
return {
|
|
417
|
-
valid: errors.length === 0,
|
|
418
|
-
errorCount: errors.length,
|
|
419
|
-
warningCount: warnings.length,
|
|
420
|
-
errors: errors.slice(0, 8).map(d => ({ file: d.path, line: d.line, code: d.code, message: d.message, hint: d.hint })),
|
|
421
|
-
};
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
export function isWriteTool(name, args) {
|
|
425
|
-
if (name === 'clado_batch') return !args?.dryRun;
|
|
426
|
-
if (name === 'clado_documents') return ['create', 'copy', 'update', 'rename', 'delete'].includes(args?.action);
|
|
427
|
-
if (name === 'clado_nodes') return ['create', 'insert', 'update', 'rename', 'move', 'delete'].includes(args?.action);
|
|
428
|
-
if (name === 'clado_links') return ['connect', 'disconnect'].includes(args?.action);
|
|
429
|
-
if (name === 'canvas_objects_write') return true;
|
|
430
|
-
return false;
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
function collectWriteTargetFiles(name, args) {
|
|
434
|
-
const files = new Set();
|
|
435
|
-
if (args?.file) files.add(args.file);
|
|
436
|
-
if (args?.newFile) files.add(args.newFile);
|
|
437
|
-
if (args?.targetFile) files.add(args.targetFile);
|
|
438
|
-
if (name === 'clado_batch' && Array.isArray(args?.operations)) {
|
|
439
|
-
for (const op of args.operations) {
|
|
440
|
-
if (op?.file) files.add(op.file);
|
|
441
|
-
if (op?.newFile) files.add(op.newFile);
|
|
442
|
-
if (op?.targetFile) files.add(op.targetFile);
|
|
443
|
-
}
|
|
444
|
-
}
|
|
445
|
-
return [...files];
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
function describeChange(name, args, result) {
|
|
449
|
-
const file = result?.file || args.targetFile || args.newFile || args.file || '';
|
|
450
|
-
if (name === 'clado_documents') {
|
|
451
|
-
const labels = { create: '新建文档', copy: '复制文档', update: '更新文档', rename: '重命名文档', delete: '删除文档' };
|
|
452
|
-
return [{ kind: args.action, file, node: null, label: `${labels[args.action] || '更新文档'} · ${file}` }];
|
|
453
|
-
}
|
|
454
|
-
if (name === 'clado_nodes') {
|
|
455
|
-
const labels = { create: '新增卡片/小节', insert: '补充正文', update: '更新正文', rename: '重命名', move: '移动节点', delete: '删除节点' };
|
|
456
|
-
const node = result?.results?.[0]?.path
|
|
457
|
-
|| (args.action === 'create' ? [...(args.parent || []), args.title].filter(Boolean) : args.node)
|
|
458
|
-
|| null;
|
|
459
|
-
const title = Array.isArray(node) && node.length ? node.at(-1) : (args.title || file);
|
|
460
|
-
return [{ kind: args.action, file, node, label: `${labels[args.action] || '更新'} · ${title}` }];
|
|
461
|
-
}
|
|
462
|
-
if (name === 'clado_links') {
|
|
463
|
-
const label = args.action === 'connect' ? '建立连线' : '断开连线';
|
|
464
|
-
const from = Array.isArray(args.node) ? args.node.at(-1) : '';
|
|
465
|
-
const to = Array.isArray(args.targetNode) ? args.targetNode.at(-1) : (args.targetFile || '');
|
|
466
|
-
return [{ kind: args.action, file, node: args.node || null, label: `${label} · ${from}${to ? ' → ' + to : ''}` }];
|
|
467
|
-
}
|
|
468
|
-
if (name === 'clado_batch') {
|
|
469
|
-
const out = [];
|
|
470
|
-
for (const op of args.operations || []) {
|
|
471
|
-
const f = op.targetFile || op.newFile || op.file || '';
|
|
472
|
-
const node = op.node || (op.title ? [...(op.parent || []), op.title] : null);
|
|
473
|
-
const title = Array.isArray(node) && node.length ? node.at(-1) : f;
|
|
474
|
-
out.push({ kind: op.type || 'batch', file: f, node, label: `${op.type || '批量变更'} · ${title}` });
|
|
475
|
-
}
|
|
476
|
-
return out.slice(0, 12);
|
|
477
|
-
}
|
|
478
|
-
return [];
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
function humanizeToolStatus(name, args = {}) {
|
|
482
|
-
if (name === 'probe_tree') return '正在扫描项目目录…';
|
|
483
|
-
if (name === 'probe_search') return `正在检索 ${String(args.query || '代码').slice(0, 14)}…`;
|
|
484
|
-
if (name === 'probe_read') return `正在读取 ${String(args.file || '源码').split('/').pop()}…`;
|
|
485
|
-
if (name === 'probe_git_diff') return '正在对比 Git Diff…';
|
|
486
|
-
if (name === 'probe_command') return `正在执行 ${String(args.command || '命令').slice(0, 16)}…`;
|
|
487
|
-
if (name === 'spawn_peer') return `正在派生同伴「${args.name || ''}」…`;
|
|
488
|
-
if (name === 'message_peer') return `正在呼叫「${args.target || ''}」…`;
|
|
489
|
-
if (name === 'canvas_objects_read') return args.id ? `正在读取组件 #${args.id}…` : '正在读取画布组件…';
|
|
490
|
-
if (name === 'canvas_objects_write') return args.action === 'delete' ? `正在移除组件 #${args.id || ''}…` : '正在更新画布便签/组件…';
|
|
491
|
-
if (name === 'load_skill') return `正在读取技能「${args.name || ''}」…`;
|
|
492
|
-
if (name.startsWith('mcp__')) {
|
|
493
|
-
const parts = name.split('__');
|
|
494
|
-
return `正在调用外部 MCP · ${parts[1] || ''}/${parts[2] || name}…`;
|
|
495
|
-
}
|
|
496
|
-
if (name.startsWith('clado_')) {
|
|
497
|
-
const target = (Array.isArray(args.node) && args.node.at(-1)) || args.title || args.file || '画布';
|
|
498
|
-
return `正在编辑画布 · ${String(target).slice(0, 12)}…`;
|
|
499
|
-
}
|
|
500
|
-
return `正在调用 ${name}…`;
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
export async function runVerticalAgent({
|
|
504
|
-
workspace,
|
|
505
|
-
rootWorkspace = workspace,
|
|
506
|
-
documentRoot = workspace,
|
|
507
|
-
stateDir,
|
|
508
|
-
workspaceService,
|
|
509
|
-
events = null,
|
|
510
|
-
config = {},
|
|
511
|
-
debugConfig = null,
|
|
512
|
-
pluginMeta = null,
|
|
513
|
-
preloadedSkill = '',
|
|
514
|
-
history = [],
|
|
515
|
-
canvasBaseline = null,
|
|
516
|
-
activePeerLocks = [],
|
|
517
|
-
incomingPeerMessages = [],
|
|
518
|
-
peerCoordinator = null,
|
|
519
|
-
resumeToolResult = null,
|
|
520
|
-
resumeCommandResult = null,
|
|
521
|
-
sessionCommandAutoAllow = false,
|
|
522
|
-
drainSteering = null,
|
|
523
|
-
input = {},
|
|
524
|
-
mode = 'general',
|
|
525
|
-
execMode = 'act',
|
|
526
|
-
persona = 'architect',
|
|
527
|
-
todos: initialTodos = [],
|
|
528
|
-
emit = () => {},
|
|
529
|
-
signal,
|
|
530
|
-
fetchImpl = fetch,
|
|
531
|
-
}) {
|
|
532
|
-
const effectiveDebug = debugConfig || (stateDir ? readAgentDebugConfig(stateDir).config : undefined);
|
|
533
|
-
const pluginDirs = Array.isArray(pluginMeta?.pluginDirs) ? pluginMeta.pluginDirs : [];
|
|
534
|
-
const pluginMcp = Array.isArray(pluginMeta?.pluginMcp) ? pluginMeta.pluginMcp : [];
|
|
535
|
-
const pluginPersonasMap = Object.fromEntries(
|
|
536
|
-
(Array.isArray(pluginMeta?.pluginPersonas) ? pluginMeta.pluginPersonas : []).map(p => [p.id, p]),
|
|
537
|
-
);
|
|
538
|
-
const mergedPersonas = { ...pluginPersonasMap, ...(effectiveDebug?.personas || {}) };
|
|
539
|
-
const activePersona = resolvePersona(persona || config.persona, config.personaPrompt, mergedPersonas);
|
|
540
|
-
const isPlanOnly = execMode === 'plan';
|
|
541
|
-
|
|
542
|
-
const availableSkills = listSkills(workspace, { pluginDirs });
|
|
543
|
-
const skillsCatalogText = formatSkillsCatalog(availableSkills);
|
|
544
|
-
const preloadedSkillObj = preloadedSkill ? readSkill(workspace, preloadedSkill, { pluginDirs }) : null;
|
|
545
|
-
const externalMcp = await discoverExternalMcpTools(workspace, { pluginMcp }).catch(() => ({ definitions: [], registry: new Map(), errors: [] }));
|
|
546
|
-
|
|
547
|
-
const run = createRunRecord(stateDir, {
|
|
548
|
-
kind: 'builtin',
|
|
549
|
-
mode,
|
|
550
|
-
file: input.canvas?.file || '',
|
|
551
|
-
instruction: resumeToolResult
|
|
552
|
-
? `[回答提问] ${resumeToolResult.answer}`
|
|
553
|
-
: resumeCommandResult
|
|
554
|
-
? `[命令审批] ${resumeCommandResult.decision}`
|
|
555
|
-
: (input.text || ''),
|
|
556
|
-
});
|
|
557
|
-
emit({ type: 'run', run });
|
|
558
|
-
|
|
559
|
-
const touchedFiles = new Set();
|
|
560
|
-
const changes = [];
|
|
561
|
-
const checkpointFiles = {};
|
|
562
|
-
let currentTodos = Array.isArray(initialTodos) ? [...initialTodos] : [];
|
|
563
|
-
|
|
564
|
-
function snapshotFileBeforeWrite(relFile) {
|
|
565
|
-
if (!documentRoot || !relFile || Object.hasOwn(checkpointFiles, relFile)) return;
|
|
566
|
-
try {
|
|
567
|
-
const full = workspacePath(documentRoot, relFile, true);
|
|
568
|
-
if (existsSync(full)) {
|
|
569
|
-
checkpointFiles[relFile] = { existed: true, content: readFileSync(full, 'utf8') };
|
|
570
|
-
} else {
|
|
571
|
-
checkpointFiles[relFile] = { existed: false, content: '' };
|
|
572
|
-
}
|
|
573
|
-
} catch {}
|
|
574
|
-
}
|
|
575
|
-
|
|
576
|
-
const baseSystemPrompt = [
|
|
577
|
-
`你是 Clado 独立可视化研发设计 Agent(当前人设:${activePersona.name})。`,
|
|
578
|
-
activePersona.prompt,
|
|
579
|
-
'核心交互原则:画布是用户的主观察面,聊天回复保持精炼(3–6 行要点),把结构化内容沉淀在画布里。',
|
|
580
|
-
isPlanOnly
|
|
581
|
-
? '【重要限制:当前处于「规划(只读)」模式】严禁修改画布文档或执行写命令;仅允许使用只读探针查证、拆解步骤(todo_write)或调用 ask_user 与用户对齐方案。'
|
|
582
|
-
: '',
|
|
583
|
-
MODE_PROMPTS[mode] || MODE_PROMPTS.general,
|
|
584
|
-
skillsCatalogText,
|
|
585
|
-
preloadedSkillObj ? `【本次命令预加载技能:${preloadedSkillObj.name}】\n${preloadedSkillObj.body}` : '',
|
|
586
|
-
].filter(Boolean).join('\n\n');
|
|
587
|
-
|
|
588
|
-
const isResume = Boolean(resumeToolResult || resumeCommandResult);
|
|
589
|
-
const segmented = buildSegmentedPromptContext({
|
|
590
|
-
workspace,
|
|
591
|
-
rootWorkspace,
|
|
592
|
-
documentRoot,
|
|
593
|
-
stateDir,
|
|
594
|
-
debugConfig: effectiveDebug,
|
|
595
|
-
baseSystemPrompt,
|
|
596
|
-
history,
|
|
597
|
-
canvas: input.canvas || null,
|
|
598
|
-
canvasBaseline,
|
|
599
|
-
activePeerLocks,
|
|
600
|
-
incomingPeerMessages,
|
|
601
|
-
userInstruction: input.text || '',
|
|
602
|
-
isResumeTool: isResume,
|
|
603
|
-
});
|
|
604
|
-
|
|
605
|
-
emit({ type: 'telemetry', telemetry: segmented.telemetry });
|
|
606
|
-
|
|
607
|
-
const conversation = [...segmented.conversation];
|
|
608
|
-
if (resumeToolResult) {
|
|
609
|
-
conversation.push({
|
|
610
|
-
role: 'tool',
|
|
611
|
-
tool_call_id: resumeToolResult.toolCallId,
|
|
612
|
-
content: JSON.stringify({
|
|
613
|
-
answered: true,
|
|
614
|
-
choiceId: resumeToolResult.choiceId || null,
|
|
615
|
-
answer: resumeToolResult.answer,
|
|
616
|
-
}),
|
|
617
|
-
});
|
|
618
|
-
} else if (resumeCommandResult) {
|
|
619
|
-
let cmdPayload;
|
|
620
|
-
if (resumeCommandResult.decision === 'deny') {
|
|
621
|
-
cmdPayload = { approved: false, skipped: true, message: '用户拒绝执行该命令,请在不运行该命令的前提下继续或调整方案。' };
|
|
622
|
-
} else {
|
|
623
|
-
emit({ type: 'status', text: `正在执行已授权命令:${resumeCommandResult.command.slice(0, 28)}…` });
|
|
624
|
-
cmdPayload = await executeWorkspaceCommand(workspace, { command: resumeCommandResult.command });
|
|
625
|
-
}
|
|
626
|
-
conversation.push({
|
|
627
|
-
role: 'tool',
|
|
628
|
-
tool_call_id: resumeCommandResult.toolCallId,
|
|
629
|
-
content: JSON.stringify(cmdPayload),
|
|
630
|
-
});
|
|
631
|
-
} else {
|
|
632
|
-
conversation.push({ role: 'user', content: segmented.seg4UserContent });
|
|
633
|
-
}
|
|
634
|
-
|
|
635
|
-
const tools = [
|
|
636
|
-
...toolDefinitions({ enablePeers: Boolean(peerCoordinator) }),
|
|
637
|
-
...externalMcp.definitions,
|
|
638
|
-
];
|
|
639
|
-
|
|
640
|
-
async function executeTool(name, rawArgs) {
|
|
641
|
-
const args = rawArgs && typeof rawArgs === 'object' ? rawArgs : {};
|
|
642
|
-
if (name === 'load_skill') {
|
|
643
|
-
const found = readSkill(workspace, args.name, { pluginDirs });
|
|
644
|
-
if (!found) return { ok: false, error: `未找到技能:${args.name || ''}` };
|
|
645
|
-
return { ok: true, slug: found.slug, name: found.name, description: found.description, instructions: found.body };
|
|
646
|
-
}
|
|
647
|
-
if (externalMcp.registry.has(name)) {
|
|
648
|
-
const entry = externalMcp.registry.get(name);
|
|
649
|
-
return await callExternalMcpTool(entry, args, workspace);
|
|
650
|
-
}
|
|
651
|
-
if (name === 'todo_write') {
|
|
652
|
-
const list = Array.isArray(args.todos)
|
|
653
|
-
? args.todos.slice(0, 12).map(t => ({
|
|
654
|
-
text: String(t?.text || '').trim().slice(0, 120),
|
|
655
|
-
status: ['pending', 'in_progress', 'completed'].includes(t?.status) ? t.status : 'pending',
|
|
656
|
-
})).filter(t => t.text)
|
|
657
|
-
: [];
|
|
658
|
-
currentTodos = list;
|
|
659
|
-
emit({ type: 'todos', todos: currentTodos });
|
|
660
|
-
const activeIdx = list.findIndex(t => t.status === 'in_progress');
|
|
661
|
-
if (activeIdx >= 0) {
|
|
662
|
-
emit({ type: 'status', text: `[${activeIdx + 1}/${list.length}] ${list[activeIdx].text}` });
|
|
663
|
-
}
|
|
664
|
-
return { ok: true, count: currentTodos.length };
|
|
665
|
-
}
|
|
666
|
-
if (name === 'canvas_focus') {
|
|
667
|
-
const targetFile = args.file || input.canvas?.file || '';
|
|
668
|
-
const targetNode = Array.isArray(args.node) ? args.node : [];
|
|
669
|
-
events?.emit(workspace, 'agent.focus', {
|
|
670
|
-
file: targetFile,
|
|
671
|
-
nodes: targetNode.length ? [targetNode] : [],
|
|
672
|
-
kind: 'read',
|
|
673
|
-
label: args.reason || ('AI 指向 · ' + (targetNode.at(-1) || targetFile)),
|
|
674
|
-
forcePan: true,
|
|
675
|
-
});
|
|
676
|
-
return { focused: true, file: targetFile, node: targetNode };
|
|
677
|
-
}
|
|
678
|
-
if (name === 'probe_tree') return probeTree(workspace, args);
|
|
679
|
-
if (name === 'probe_search') return await probeSearch(workspace, args);
|
|
680
|
-
if (name === 'probe_read') return probeRead(workspace, args);
|
|
681
|
-
if (name === 'probe_git_diff') return await probeGitDiff(workspace, args);
|
|
682
|
-
if (name === 'probe_command') {
|
|
683
|
-
if (isPlanOnly && classifyShellCommand(args.command) !== 'readonly') {
|
|
684
|
-
return { blockedByPlanMode: true, error: '当前处于【规划(只读)】模式,已拦截非只读命令。' };
|
|
685
|
-
}
|
|
686
|
-
return await executeWorkspaceCommand(workspace, args);
|
|
687
|
-
}
|
|
688
|
-
if (name === 'canvas_objects_read') {
|
|
689
|
-
if (!stateDir) return { objects: [] };
|
|
690
|
-
if (args.id) {
|
|
691
|
-
const obj = readCanvasObject(stateDir, args.id);
|
|
692
|
-
return obj ? { object: obj } : { error: `未找到画布对象:${args.id}` };
|
|
693
|
-
}
|
|
694
|
-
return { objects: listCanvasObjects(stateDir, 60) };
|
|
695
|
-
}
|
|
696
|
-
if (name === 'canvas_objects_write') {
|
|
697
|
-
if (isPlanOnly) {
|
|
698
|
-
return { blockedByPlanMode: true, error: '当前处于【规划(只读)】模式,已拦截画布组件写入操作。' };
|
|
699
|
-
}
|
|
700
|
-
if (!stateDir) throw new Error('工作区状态目录未挂载。');
|
|
701
|
-
if (args.action === 'delete') {
|
|
702
|
-
const deleted = deleteCanvasObject(stateDir, args.id);
|
|
703
|
-
if (deleted) events?.emit(workspace, 'objects.updated', { action: 'delete', id: args.id });
|
|
704
|
-
return { deleted, id: args.id };
|
|
705
|
-
}
|
|
706
|
-
const saved = saveCanvasObject(stateDir, args);
|
|
707
|
-
changes.push({ kind: 'object', file: input.canvas?.file || '', node: null, label: `更新组件「${saved.title}」` });
|
|
708
|
-
events?.emit(workspace, 'objects.updated', { action: 'save', object: saved });
|
|
709
|
-
return { saved: true, object: saved };
|
|
710
|
-
}
|
|
711
|
-
if (name === 'spawn_peer' && peerCoordinator) {
|
|
712
|
-
if (isPlanOnly) return { blockedByPlanMode: true, error: '规划只读模式下暂不自动派生执行分身,请先向用户汇报分工方案。' };
|
|
713
|
-
return await peerCoordinator.spawnPeer(args);
|
|
714
|
-
}
|
|
715
|
-
if (name === 'message_peer' && peerCoordinator) {
|
|
716
|
-
return await peerCoordinator.messagePeer(args);
|
|
717
|
-
}
|
|
718
|
-
if (name.startsWith('clado_')) {
|
|
719
|
-
if (!workspaceService) throw new Error('工作区服务未挂载。');
|
|
720
|
-
if (isPlanOnly && isWriteTool(name, args)) {
|
|
721
|
-
return {
|
|
722
|
-
blockedByPlanMode: true,
|
|
723
|
-
error: '当前处于【规划(只读)】模式,已拦截画布写入操作。请先输出方案或让用户切换到「执行」模式。',
|
|
724
|
-
};
|
|
725
|
-
}
|
|
726
|
-
if (isWriteTool(name, args)) {
|
|
727
|
-
for (const f of collectWriteTargetFiles(name, args)) snapshotFileBeforeWrite(f);
|
|
728
|
-
}
|
|
729
|
-
const result = await workspaceService(name, { ...args, workspace });
|
|
730
|
-
if (isWriteTool(name, args)) {
|
|
731
|
-
const file = result?.file || args.file || args.newFile || '';
|
|
732
|
-
if (file) touchedFiles.add(file);
|
|
733
|
-
changes.push(...describeChange(name, args, result));
|
|
734
|
-
if (typeof workspaceService.diagnostics === 'function') {
|
|
735
|
-
const report = await workspaceService.diagnostics({ workspace });
|
|
736
|
-
return { ...result, verification: summarizeDiagnostics(report) };
|
|
737
|
-
}
|
|
738
|
-
}
|
|
739
|
-
return result;
|
|
740
|
-
}
|
|
741
|
-
throw new Error('未知工具:' + name);
|
|
742
|
-
}
|
|
743
|
-
|
|
744
|
-
const buildCheckpoint = () => {
|
|
745
|
-
const keys = Object.keys(checkpointFiles);
|
|
746
|
-
if (!keys.length) return null;
|
|
747
|
-
return {
|
|
748
|
-
id: randomUUID(),
|
|
749
|
-
createdAt: new Date().toISOString(),
|
|
750
|
-
label: changes[0]?.label || `修改 ${keys.join(', ')}`,
|
|
751
|
-
files: checkpointFiles,
|
|
752
|
-
};
|
|
753
|
-
};
|
|
754
|
-
|
|
755
|
-
try {
|
|
756
|
-
let finalText = '';
|
|
757
|
-
for (let step = 1; step <= MAX_STEPS; step++) {
|
|
758
|
-
if (signal?.aborted) {
|
|
759
|
-
updateRunRecord(stateDir, run, { status: 'cancelled', touchedFiles: [...touchedFiles] });
|
|
760
|
-
return {
|
|
761
|
-
stopReason: 'cancelled',
|
|
762
|
-
assistantText: finalText,
|
|
763
|
-
conversation,
|
|
764
|
-
changes,
|
|
765
|
-
todos: currentTodos,
|
|
766
|
-
nextBaseline: segmented.nextBaseline,
|
|
767
|
-
checkpoint: buildCheckpoint(),
|
|
768
|
-
pendingQuestion: null,
|
|
769
|
-
pendingCommand: null,
|
|
770
|
-
run,
|
|
771
|
-
};
|
|
772
|
-
}
|
|
773
|
-
|
|
774
|
-
// 检查是否有运行中途人类插话纠偏(Steering)
|
|
775
|
-
if (typeof drainSteering === 'function') {
|
|
776
|
-
const steered = drainSteering();
|
|
777
|
-
if (Array.isArray(steered) && steered.length) {
|
|
778
|
-
for (const text of steered) {
|
|
779
|
-
conversation.push({ role: 'user', content: `【用户运行中实时插话纠偏】\n${text}` });
|
|
780
|
-
}
|
|
781
|
-
emit({ type: 'status', text: '已吸收插话纠偏,调整执行方向…' });
|
|
782
|
-
}
|
|
783
|
-
}
|
|
784
|
-
|
|
785
|
-
emit({ type: 'status', text: step === 1 ? `${activePersona.name} 正在思考…` : `第 ${step} 步推理与核验…` });
|
|
786
|
-
|
|
787
|
-
const turnResult = await streamModelTurn({
|
|
788
|
-
config,
|
|
789
|
-
messages: [{ role: 'system', content: segmented.systemText }, ...conversation],
|
|
790
|
-
tools,
|
|
791
|
-
signal,
|
|
792
|
-
fetchImpl,
|
|
793
|
-
onEvent: ev => {
|
|
794
|
-
if (ev.type === 'thinking_delta') emit({ type: 'thinking', text: ev.text });
|
|
795
|
-
else if (ev.type === 'text_delta') {
|
|
796
|
-
finalText += ev.text;
|
|
797
|
-
emit({ type: 'text', text: ev.text });
|
|
798
|
-
} else if (ev.type === 'tool_call_start') {
|
|
799
|
-
emit({ type: 'tool', id: ev.id, title: ev.name, status: 'pending' });
|
|
800
|
-
}
|
|
801
|
-
},
|
|
802
|
-
});
|
|
803
|
-
|
|
804
|
-
const msg = turnResult.message;
|
|
805
|
-
conversation.push(msg);
|
|
806
|
-
const calls = Array.isArray(msg.tool_calls) ? msg.tool_calls : [];
|
|
807
|
-
|
|
808
|
-
if (!calls.length) {
|
|
809
|
-
if (changes.length) emit({ type: 'changes', items: changes });
|
|
810
|
-
const saved = updateRunRecord(stateDir, run, {
|
|
811
|
-
status: 'completed',
|
|
812
|
-
summary: finalText.slice(0, 300),
|
|
813
|
-
touchedFiles: [...touchedFiles],
|
|
814
|
-
});
|
|
815
|
-
emit({ type: 'run', run: saved });
|
|
816
|
-
return {
|
|
817
|
-
stopReason: 'end_turn',
|
|
818
|
-
assistantText: finalText,
|
|
819
|
-
conversation,
|
|
820
|
-
changes,
|
|
821
|
-
todos: currentTodos,
|
|
822
|
-
nextBaseline: segmented.nextBaseline,
|
|
823
|
-
checkpoint: buildCheckpoint(),
|
|
824
|
-
pendingQuestion: null,
|
|
825
|
-
pendingCommand: null,
|
|
826
|
-
run: saved,
|
|
827
|
-
};
|
|
828
|
-
}
|
|
829
|
-
|
|
830
|
-
let hadVerifyErrors = false;
|
|
831
|
-
for (const call of calls) {
|
|
832
|
-
const toolName = call?.function?.name || 'unknown';
|
|
833
|
-
const callId = call?.id || `call_${step}_${randomUUID().slice(0, 6)}`;
|
|
834
|
-
let parsedArgs = {};
|
|
835
|
-
try { parsedArgs = JSON.parse(call?.function?.arguments || '{}'); } catch {}
|
|
836
|
-
|
|
837
|
-
// 1. ask_user:暂停当前轮次,等待观察者拍板
|
|
838
|
-
if (toolName === 'ask_user') {
|
|
839
|
-
const options = Array.isArray(parsedArgs.options)
|
|
840
|
-
? parsedArgs.options.slice(0, 6).map((opt, idx) => ({
|
|
841
|
-
id: String(opt.id || ('opt_' + (idx + 1))),
|
|
842
|
-
label: String(opt.label || '').trim(),
|
|
843
|
-
detail: opt.detail ? String(opt.detail).trim() : '',
|
|
844
|
-
})).filter(opt => opt.label)
|
|
845
|
-
: [];
|
|
846
|
-
const pendingQuestion = {
|
|
847
|
-
id: randomUUID(),
|
|
848
|
-
toolCallId: callId,
|
|
849
|
-
question: String(parsedArgs.question || '请确认下一步方案:'),
|
|
850
|
-
options,
|
|
851
|
-
allowCustom: parsedArgs.allowCustom !== false,
|
|
852
|
-
file: parsedArgs.file || input.canvas?.file || '',
|
|
853
|
-
targetNode: Array.isArray(parsedArgs.targetNode) ? parsedArgs.targetNode : [],
|
|
854
|
-
};
|
|
855
|
-
emit({ type: 'tool', id: callId, title: 'ask_user', status: 'completed' });
|
|
856
|
-
if (changes.length) emit({ type: 'changes', items: changes });
|
|
857
|
-
emit({ type: 'question', question: pendingQuestion });
|
|
858
|
-
events?.emit(workspace, 'agent.activity', {
|
|
859
|
-
file: pendingQuestion.file,
|
|
860
|
-
action: 'ask_user',
|
|
861
|
-
kind: 'waiting',
|
|
862
|
-
nodes: pendingQuestion.targetNode.length ? [pendingQuestion.targetNode] : [],
|
|
863
|
-
label: '待你拍板 · ' + pendingQuestion.question.slice(0, 42),
|
|
864
|
-
});
|
|
865
|
-
const paused = updateRunRecord(stateDir, run, {
|
|
866
|
-
status: 'waiting_user',
|
|
867
|
-
summary: pendingQuestion.question.slice(0, 300),
|
|
868
|
-
touchedFiles: [...touchedFiles],
|
|
869
|
-
});
|
|
870
|
-
emit({ type: 'run', run: paused });
|
|
871
|
-
return {
|
|
872
|
-
stopReason: 'awaiting_user',
|
|
873
|
-
assistantText: finalText,
|
|
874
|
-
conversation,
|
|
875
|
-
changes,
|
|
876
|
-
todos: currentTodos,
|
|
877
|
-
nextBaseline: segmented.nextBaseline,
|
|
878
|
-
checkpoint: buildCheckpoint(),
|
|
879
|
-
pendingQuestion,
|
|
880
|
-
pendingCommand: null,
|
|
881
|
-
run: paused,
|
|
882
|
-
};
|
|
883
|
-
}
|
|
884
|
-
|
|
885
|
-
// 2. probe_command:根据安全分级与用户权限策略决定直接放行还是弹出胶囊旁轻量审批条
|
|
886
|
-
if (toolName === 'probe_command') {
|
|
887
|
-
const cmdStr = String(parsedArgs.command || '').trim();
|
|
888
|
-
const safety = classifyShellCommand(cmdStr);
|
|
889
|
-
const permMode = effectiveDebug?.commandPermission || 'readonly_free';
|
|
890
|
-
const needsApproval = !isPlanOnly
|
|
891
|
-
&& safety === 'write_or_exec'
|
|
892
|
-
&& !sessionCommandAutoAllow
|
|
893
|
-
&& permMode !== 'allow_all';
|
|
894
|
-
const forceAsk = !isPlanOnly && safety === 'readonly' && permMode === 'ask_always' && !sessionCommandAutoAllow;
|
|
895
|
-
|
|
896
|
-
if (needsApproval || forceAsk) {
|
|
897
|
-
const pendingCommand = {
|
|
898
|
-
id: randomUUID(),
|
|
899
|
-
toolCallId: callId,
|
|
900
|
-
command: cmdStr.slice(0, 400),
|
|
901
|
-
};
|
|
902
|
-
emit({ type: 'tool', id: callId, title: 'probe_command', status: 'pending' });
|
|
903
|
-
if (changes.length) emit({ type: 'changes', items: changes });
|
|
904
|
-
emit({ type: 'command_approval', approval: pendingCommand });
|
|
905
|
-
const paused = updateRunRecord(stateDir, run, {
|
|
906
|
-
status: 'waiting_user',
|
|
907
|
-
summary: `请求执行命令:${pendingCommand.command}`,
|
|
908
|
-
touchedFiles: [...touchedFiles],
|
|
909
|
-
});
|
|
910
|
-
emit({ type: 'run', run: paused });
|
|
911
|
-
return {
|
|
912
|
-
stopReason: 'awaiting_command',
|
|
913
|
-
assistantText: finalText,
|
|
914
|
-
conversation,
|
|
915
|
-
changes,
|
|
916
|
-
todos: currentTodos,
|
|
917
|
-
nextBaseline: segmented.nextBaseline,
|
|
918
|
-
checkpoint: buildCheckpoint(),
|
|
919
|
-
pendingQuestion: null,
|
|
920
|
-
pendingCommand,
|
|
921
|
-
run: paused,
|
|
922
|
-
};
|
|
923
|
-
}
|
|
924
|
-
}
|
|
925
|
-
|
|
926
|
-
emit({ type: 'status', text: humanizeToolStatus(toolName, parsedArgs) });
|
|
927
|
-
emit({ type: 'tool', id: callId, title: toolName, status: 'in_progress' });
|
|
928
|
-
let output;
|
|
929
|
-
try {
|
|
930
|
-
output = await executeTool(toolName, parsedArgs);
|
|
931
|
-
emit({ type: 'tool', id: callId, title: toolName, status: 'completed' });
|
|
932
|
-
if (output?.verification && !output.verification.valid) hadVerifyErrors = true;
|
|
933
|
-
} catch (error) {
|
|
934
|
-
output = { error: error.message || '工具执行失败' };
|
|
935
|
-
emit({ type: 'tool', id: callId, title: toolName, status: 'failed' });
|
|
936
|
-
}
|
|
937
|
-
const serialized = JSON.stringify(output);
|
|
938
|
-
conversation.push({
|
|
939
|
-
role: 'tool',
|
|
940
|
-
tool_call_id: callId,
|
|
941
|
-
content: serialized.length > 24000 ? serialized.slice(0, 24000) + '...(truncated)' : serialized,
|
|
942
|
-
});
|
|
943
|
-
}
|
|
944
|
-
|
|
945
|
-
if (hadVerifyErrors) {
|
|
946
|
-
conversation.push({
|
|
947
|
-
role: 'user',
|
|
948
|
-
content: '自动校验发现画布存在 diagnostics error,请先根据 verification.errors 修正所有错误后再总结汇报。',
|
|
949
|
-
});
|
|
950
|
-
}
|
|
951
|
-
}
|
|
952
|
-
|
|
953
|
-
if (changes.length) emit({ type: 'changes', items: changes });
|
|
954
|
-
const saved = updateRunRecord(stateDir, run, {
|
|
955
|
-
status: 'completed',
|
|
956
|
-
summary: finalText.slice(0, 300),
|
|
957
|
-
touchedFiles: [...touchedFiles],
|
|
958
|
-
});
|
|
959
|
-
emit({ type: 'run', run: saved });
|
|
960
|
-
return {
|
|
961
|
-
stopReason: 'max_turn_requests',
|
|
962
|
-
assistantText: finalText,
|
|
963
|
-
conversation,
|
|
964
|
-
changes,
|
|
965
|
-
todos: currentTodos,
|
|
966
|
-
nextBaseline: segmented.nextBaseline,
|
|
967
|
-
checkpoint: buildCheckpoint(),
|
|
968
|
-
pendingQuestion: null,
|
|
969
|
-
pendingCommand: null,
|
|
970
|
-
run: saved,
|
|
971
|
-
};
|
|
972
|
-
} catch (error) {
|
|
973
|
-
const cancelled = signal?.aborted || error?.name === 'AbortError';
|
|
974
|
-
updateRunRecord(stateDir, run, {
|
|
975
|
-
status: cancelled ? 'cancelled' : 'failed',
|
|
976
|
-
summary: cancelled ? '已取消' : String(error.message || '').slice(0, 300),
|
|
977
|
-
touchedFiles: [...touchedFiles],
|
|
978
|
-
});
|
|
979
|
-
if (cancelled) {
|
|
980
|
-
return {
|
|
981
|
-
stopReason: 'cancelled',
|
|
982
|
-
assistantText: '',
|
|
983
|
-
conversation,
|
|
984
|
-
changes,
|
|
985
|
-
todos: currentTodos,
|
|
986
|
-
nextBaseline: segmented.nextBaseline,
|
|
987
|
-
checkpoint: buildCheckpoint(),
|
|
988
|
-
pendingQuestion: null,
|
|
989
|
-
pendingCommand: null,
|
|
990
|
-
run,
|
|
991
|
-
};
|
|
992
|
-
}
|
|
993
|
-
throw error;
|
|
994
|
-
}
|
|
995
|
-
}
|