cladogram 0.5.5-beta.1 → 0.5.5-beta.3

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.
@@ -0,0 +1,557 @@
1
+ /**
2
+ * Clado 独立垂直 Agent 运行时(系统级内置插件 clado.agent 的大脑引擎)。
3
+ *
4
+ * 核心特性:
5
+ * 1. 双协议真 Token 流式输出(OpenAI 兼容 + Anthropic 原生,含 thinking 与 Prompt Caching);
6
+ * 2. 进程内直调内核画布操作引擎(零网络开销)+ 只读本地代码探针;
7
+ * 3. 原生观察者交互工具:ask_user(结构化提问决策卡,暂停待人拍板并无损续跑)与 canvas_focus(平滑镜头引导);
8
+ * 4. 变更清单自动汇总(changes)+ diagnostics 自动校验自纠闭环。
9
+ */
10
+
11
+ import { randomUUID } from 'node:crypto';
12
+ import { probeGitDiff, probeRead, probeSearch, probeTree } from './probe.js';
13
+ import { createRunRecord, updateRunRecord } from './executors.js';
14
+ import { streamModelTurn } from './providers/index.js';
15
+ import { compactMessages, resolvePersona } from './sessions.js';
16
+
17
+ const MAX_STEPS = 12;
18
+
19
+ const MODE_PROMPTS = {
20
+ design: [
21
+ '当前工作模式:【研发设计与代码架构】',
22
+ '1. 涉及存量代码时,先调用 probe_tree / probe_search / probe_read 核对真实类名、方法名与边界,绝不编造。',
23
+ '2. 先用 clado_templates 读取对应模板(如 call-chain / data-design / business-flow)再创建或修改 .md 画布。',
24
+ '3. 同画布跨卡连线必须从具体内容行出发(sourcePoint 或行内 anchor 链接),避免卡片末尾裸卡片连卡片。',
25
+ '4. 遇到需求歧义或方案二选一时,优先调用 ask_user 给出清晰选项让观察者拍板,不要替用户擅自猜测。',
26
+ '5. 每次修改后核对 diagnostics,确保 0 error 再给 3–5 行精炼汇报。',
27
+ ].join('\n'),
28
+ qa: [
29
+ '当前工作模式:【脑图测试用例编写】',
30
+ '1. 先阅读当前画布或关联源码梳理功能点与边界条件。',
31
+ '2. 优先使用 test-cases 模板创建或完善 .md 测试用例画布(适配脑图视图):每个模块覆盖正常流、边界条件、异常流与回归检查点。',
32
+ '3. 存在待确认验收口径时调用 ask_user 向用户确认;修改后确保 diagnostics 0 error。',
33
+ ].join('\n'),
34
+ audit: [
35
+ '当前工作模式:【开发后 Diff 验收与系统归档】',
36
+ '1. 首先调用 probe_git_diff 读取本地真实代码变更,必要时用 probe_read 核对细节。',
37
+ '2. 将真实代码变更与画布设计契约及测试用例逐项比对,明确列出已满足项、遗漏项或偏离项。',
38
+ '3. 如需归档或更新画布状态,使用 clado_nodes / clado_batch 更新并保证 diagnostics 0 error。',
39
+ ].join('\n'),
40
+ general: [
41
+ '当前工作模式:【Clado 画布协作】',
42
+ '普通问题直接简明回答;涉及本地源码先用只读探针查证;涉及画布修改直接调用内核工具并保证 diagnostics 0 error;需要用户拍板时调用 ask_user。',
43
+ ].join('\n'),
44
+ };
45
+
46
+ function toolDefinitions() {
47
+ return [
48
+ {
49
+ type: 'function',
50
+ function: {
51
+ name: 'ask_user',
52
+ description: '向画布旁的观察者提出结构化问题或方案选项,暂停执行等待用户点击确认后继续。适用于需求歧义、架构权衡或高影响决策。',
53
+ parameters: {
54
+ type: 'object',
55
+ properties: {
56
+ question: { type: 'string', description: '清晰简明的问题正文' },
57
+ options: {
58
+ type: 'array',
59
+ description: '2-4 个供用户一键点选的候选方案',
60
+ items: {
61
+ type: 'object',
62
+ properties: {
63
+ id: { type: 'string' },
64
+ label: { type: 'string', description: '简短选项标题' },
65
+ detail: { type: 'string', description: '可选一句补充说明' },
66
+ },
67
+ required: ['label'],
68
+ },
69
+ },
70
+ allowCustom: { type: 'boolean', description: '是否允许用户输入自定义回答,默认 true' },
71
+ file: { type: 'string', description: '可选关联文档路径,用于高亮对应卡片待决策状态' },
72
+ targetNode: { type: 'array', items: { type: 'string' }, description: '可选关联卡片标题路径' },
73
+ },
74
+ required: ['question'],
75
+ },
76
+ },
77
+ },
78
+ {
79
+ type: 'function',
80
+ function: {
81
+ name: 'canvas_focus',
82
+ description: '引导用户画布镜头平滑平移并高亮指定卡片或小节,方便边讲解边指向具体位置。',
83
+ parameters: {
84
+ type: 'object',
85
+ properties: {
86
+ file: { type: 'string', description: '目标文档相对路径' },
87
+ node: { type: 'array', items: { type: 'string' }, description: '目标卡片或小节标题路径' },
88
+ reason: { type: 'string', description: '展示在画布底部提示条的简短说明' },
89
+ },
90
+ required: ['node'],
91
+ },
92
+ },
93
+ },
94
+ {
95
+ type: 'function',
96
+ function: {
97
+ name: 'probe_tree',
98
+ description: '只读列出本地项目仓库目录树与源码文件(跳过 .git / node_modules / .clado)。',
99
+ parameters: {
100
+ type: 'object',
101
+ properties: {
102
+ path: { type: 'string' },
103
+ maxDepth: { type: 'integer' },
104
+ maxFiles: { type: 'integer' },
105
+ },
106
+ },
107
+ },
108
+ },
109
+ {
110
+ type: 'function',
111
+ function: {
112
+ name: 'probe_search',
113
+ description: '只读在本地代码仓库中检索关键字、类名、方法名或符号调用。',
114
+ parameters: {
115
+ type: 'object',
116
+ properties: {
117
+ query: { type: 'string' },
118
+ path: { type: 'string' },
119
+ glob: { type: 'string' },
120
+ maxResults: { type: 'integer' },
121
+ },
122
+ required: ['query'],
123
+ },
124
+ },
125
+ },
126
+ {
127
+ type: 'function',
128
+ function: {
129
+ name: 'probe_read',
130
+ description: '只读读取本地源码文件的指定行区间(1-indexed,单次最多 400 行)。',
131
+ parameters: {
132
+ type: 'object',
133
+ properties: {
134
+ file: { type: 'string' },
135
+ startLine: { type: 'integer' },
136
+ endLine: { type: 'integer' },
137
+ },
138
+ required: ['file'],
139
+ },
140
+ },
141
+ },
142
+ {
143
+ type: 'function',
144
+ function: {
145
+ name: 'probe_git_diff',
146
+ description: '只读查看本地仓库 git status、变更统计与 diff,用于存量改造分析和外包开发后验收。',
147
+ parameters: {
148
+ type: 'object',
149
+ properties: {
150
+ ref: { type: 'string' },
151
+ statOnly: { type: 'boolean' },
152
+ },
153
+ },
154
+ },
155
+ },
156
+ {
157
+ type: 'function',
158
+ function: {
159
+ name: 'clado_workspace',
160
+ description: '查看/搜索/校验当前 Clado 工作区或读取用户画布选区(action: inspect|search|validate|selection|workspaces|init)。',
161
+ parameters: {
162
+ type: 'object',
163
+ properties: {
164
+ action: { type: 'string', enum: ['init', 'inspect', 'search', 'validate', 'selection', 'workspaces'] },
165
+ query: { type: 'string' },
166
+ includeContent: { type: 'boolean' },
167
+ },
168
+ required: ['action'],
169
+ },
170
+ },
171
+ },
172
+ {
173
+ type: 'function',
174
+ function: {
175
+ name: 'clado_templates',
176
+ description: '列出或读取模板提示词(action: list|read;支持 call-chain、data-design、business-flow、requirement-overview、system-state、mind-expansion、test-cases)。',
177
+ parameters: {
178
+ type: 'object',
179
+ properties: {
180
+ action: { type: 'string', enum: ['list', 'read'] },
181
+ templateId: { type: 'string' },
182
+ view: { type: 'string', enum: ['prompt', 'source', 'full'] },
183
+ },
184
+ required: ['action'],
185
+ },
186
+ },
187
+ },
188
+ {
189
+ type: 'function',
190
+ function: {
191
+ name: 'clado_documents',
192
+ description: '管理画布文档(action: list|read|create|copy|update|rename|delete;推荐 .md,兼容 .mdc)。',
193
+ parameters: {
194
+ type: 'object',
195
+ properties: {
196
+ action: { type: 'string', enum: ['list', 'read', 'create', 'copy', 'update', 'rename', 'delete'] },
197
+ file: { type: 'string' },
198
+ newFile: { type: 'string' },
199
+ title: { type: 'string' },
200
+ templateId: { type: 'string' },
201
+ source: { type: 'string' },
202
+ view: { type: 'string', enum: ['full', 'nodes', 'source', 'summary'] },
203
+ expectedFileVersion: { type: 'string' },
204
+ expectedWorkspaceVersion: { type: 'string' },
205
+ },
206
+ required: ['action'],
207
+ },
208
+ },
209
+ },
210
+ {
211
+ type: 'function',
212
+ function: {
213
+ name: 'clado_nodes',
214
+ description: '读写画布卡片与小节节点(action: read|query|create|insert|update|rename|move|delete;node/parent 用标题数组)。',
215
+ parameters: {
216
+ type: 'object',
217
+ properties: {
218
+ action: { type: 'string', enum: ['read', 'query', 'create', 'insert', 'update', 'rename', 'move', 'delete'] },
219
+ file: { type: 'string' },
220
+ node: { type: 'array', items: { type: 'string' } },
221
+ parent: { type: 'array', items: { type: 'string' } },
222
+ title: { type: 'string' },
223
+ content: { type: 'string' },
224
+ position: { type: 'object' },
225
+ relation: { type: 'string' },
226
+ expectedNodeVersion: { type: 'string' },
227
+ expectedFileVersion: { type: 'string' },
228
+ expectedWorkspaceVersion: { type: 'string' },
229
+ },
230
+ required: ['action', 'file'],
231
+ },
232
+ },
233
+ },
234
+ {
235
+ type: 'function',
236
+ function: {
237
+ name: 'clado_links',
238
+ description: '建立或断开卡片/内容行连线(action: list|connect|disconnect;支持对称行连行:起点可用行内 position:{mode:"replace",anchor} 或 sourcePoint,落点可用 targetPoint 指定正文行 line+text / 代码行 code / 表格行 table / Mermaid 节点 mermaid)。',
239
+ parameters: {
240
+ type: 'object',
241
+ properties: {
242
+ action: { type: 'string', enum: ['list', 'connect', 'disconnect'] },
243
+ file: { type: 'string' },
244
+ node: { type: 'array', items: { type: 'string' } },
245
+ targetFile: { type: 'string' },
246
+ targetNode: { type: 'array', items: { type: 'string' } },
247
+ label: { type: 'string' },
248
+ position: { type: 'object' },
249
+ sourcePoint: { type: 'object' },
250
+ targetPoint: { type: 'object' },
251
+ linkIndex: { type: 'integer' },
252
+ expectedNodeVersion: { type: 'string' },
253
+ expectedFileVersion: { type: 'string' },
254
+ expectedWorkspaceVersion: { type: 'string' },
255
+ },
256
+ required: ['action', 'file'],
257
+ },
258
+ },
259
+ },
260
+ {
261
+ type: 'function',
262
+ function: {
263
+ name: 'clado_batch',
264
+ description: '事务化批量执行多个画布操作(operations 数组),任一步失败整批不落盘。',
265
+ parameters: {
266
+ type: 'object',
267
+ properties: {
268
+ operations: { type: 'array', items: { type: 'object' } },
269
+ expectedWorkspaceVersion: { type: 'string' },
270
+ dryRun: { type: 'boolean' },
271
+ },
272
+ required: ['operations'],
273
+ },
274
+ },
275
+ },
276
+ ];
277
+ }
278
+
279
+ function summarizeDiagnostics(report) {
280
+ const diags = Array.isArray(report?.diagnostics) ? report.diagnostics : [];
281
+ const errors = diags.filter(d => d.severity === 'error');
282
+ const warnings = diags.filter(d => d.severity === 'warn');
283
+ return {
284
+ valid: errors.length === 0,
285
+ errorCount: errors.length,
286
+ warningCount: warnings.length,
287
+ errors: errors.slice(0, 8).map(d => ({ file: d.path, line: d.line, code: d.code, message: d.message, hint: d.hint })),
288
+ };
289
+ }
290
+
291
+ function isWriteTool(name, args) {
292
+ if (name === 'clado_batch') return !args?.dryRun;
293
+ if (name === 'clado_documents') return ['create', 'copy', 'update', 'rename', 'delete'].includes(args?.action);
294
+ if (name === 'clado_nodes') return ['create', 'insert', 'update', 'rename', 'move', 'delete'].includes(args?.action);
295
+ if (name === 'clado_links') return ['connect', 'disconnect'].includes(args?.action);
296
+ return false;
297
+ }
298
+
299
+ function describeChange(name, args, result) {
300
+ const file = result?.file || args.targetFile || args.newFile || args.file || '';
301
+ if (name === 'clado_documents') {
302
+ const labels = { create: '新建文档', copy: '复制文档', update: '更新文档', rename: '重命名文档', delete: '删除文档' };
303
+ return [{ kind: args.action, file, node: null, label: `${labels[args.action] || '更新文档'} · ${file}` }];
304
+ }
305
+ if (name === 'clado_nodes') {
306
+ const labels = { create: '新增卡片/小节', insert: '补充正文', update: '更新正文', rename: '重命名', move: '移动节点', delete: '删除节点' };
307
+ const node = result?.results?.[0]?.path
308
+ || (args.action === 'create' ? [...(args.parent || []), args.title].filter(Boolean) : args.node)
309
+ || null;
310
+ const title = Array.isArray(node) && node.length ? node.at(-1) : (args.title || file);
311
+ return [{ kind: args.action, file, node, label: `${labels[args.action] || '更新'} · ${title}` }];
312
+ }
313
+ if (name === 'clado_links') {
314
+ const label = args.action === 'connect' ? '建立连线' : '断开连线';
315
+ const from = Array.isArray(args.node) ? args.node.at(-1) : '';
316
+ const to = Array.isArray(args.targetNode) ? args.targetNode.at(-1) : (args.targetFile || '');
317
+ return [{ kind: args.action, file, node: args.node || null, label: `${label} · ${from}${to ? ' → ' + to : ''}` }];
318
+ }
319
+ if (name === 'clado_batch') {
320
+ const out = [];
321
+ for (const op of args.operations || []) {
322
+ const f = op.targetFile || op.newFile || op.file || '';
323
+ const node = op.node || (op.title ? [...(op.parent || []), op.title] : null);
324
+ const title = Array.isArray(node) && node.length ? node.at(-1) : f;
325
+ out.push({ kind: op.type || 'batch', file: f, node, label: `${op.type || '批量变更'} · ${title}` });
326
+ }
327
+ return out.slice(0, 12);
328
+ }
329
+ return [];
330
+ }
331
+
332
+ export async function runVerticalAgent({
333
+ workspace,
334
+ stateDir,
335
+ workspaceService,
336
+ events = null,
337
+ config = {},
338
+ history = [],
339
+ resumeToolResult = null,
340
+ input = {},
341
+ mode = 'general',
342
+ persona = 'architect',
343
+ emit = () => {},
344
+ signal,
345
+ fetchImpl = fetch,
346
+ }) {
347
+ const activePersona = resolvePersona(persona || config.persona, config.personaPrompt);
348
+ const run = createRunRecord(stateDir, {
349
+ kind: 'builtin',
350
+ mode,
351
+ file: input.canvas?.file || '',
352
+ instruction: resumeToolResult ? `[回答提问] ${resumeToolResult.answer}` : (input.text || ''),
353
+ });
354
+ emit({ type: 'run', run });
355
+
356
+ const touchedFiles = new Set();
357
+ const changes = [];
358
+ const systemText = [
359
+ `你是 Clado 独立可视化研发设计 Agent(当前人设:${activePersona.name})。`,
360
+ activePersona.prompt,
361
+ '核心交互原则:画布是用户的主观察面,聊天回复保持精炼(3–6 行要点),把结构化内容沉淀在画布里。',
362
+ MODE_PROMPTS[mode] || MODE_PROMPTS.general,
363
+ ].join('\n\n');
364
+
365
+ const prior = compactMessages(history);
366
+ const conversation = [...prior];
367
+ if (resumeToolResult) {
368
+ conversation.push({
369
+ role: 'tool',
370
+ tool_call_id: resumeToolResult.toolCallId,
371
+ content: JSON.stringify({
372
+ answered: true,
373
+ choiceId: resumeToolResult.choiceId || null,
374
+ answer: resumeToolResult.answer,
375
+ }),
376
+ });
377
+ } 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}` });
382
+ }
383
+
384
+ const tools = toolDefinitions();
385
+
386
+ async function executeTool(name, rawArgs) {
387
+ const args = rawArgs && typeof rawArgs === 'object' ? rawArgs : {};
388
+ if (name === 'canvas_focus') {
389
+ const targetFile = args.file || input.canvas?.file || '';
390
+ const targetNode = Array.isArray(args.node) ? args.node : [];
391
+ events?.emit(workspace, 'agent.focus', {
392
+ file: targetFile,
393
+ nodes: targetNode.length ? [targetNode] : [],
394
+ kind: 'read',
395
+ label: args.reason || ('AI 指向 · ' + (targetNode.at(-1) || targetFile)),
396
+ forcePan: true,
397
+ });
398
+ return { focused: true, file: targetFile, node: targetNode };
399
+ }
400
+ if (name === 'probe_tree') return probeTree(workspace, args);
401
+ if (name === 'probe_search') return await probeSearch(workspace, args);
402
+ if (name === 'probe_read') return probeRead(workspace, args);
403
+ if (name === 'probe_git_diff') return await probeGitDiff(workspace, args);
404
+ if (name.startsWith('clado_')) {
405
+ if (!workspaceService) throw new Error('工作区服务未挂载。');
406
+ const result = await workspaceService(name, { ...args, workspace });
407
+ if (isWriteTool(name, args)) {
408
+ const file = result?.file || args.file || args.newFile || '';
409
+ if (file) touchedFiles.add(file);
410
+ changes.push(...describeChange(name, args, result));
411
+ if (typeof workspaceService.diagnostics === 'function') {
412
+ const report = await workspaceService.diagnostics({ workspace });
413
+ return { ...result, verification: summarizeDiagnostics(report) };
414
+ }
415
+ }
416
+ return result;
417
+ }
418
+ throw new Error('未知工具:' + name);
419
+ }
420
+
421
+ try {
422
+ let finalText = '';
423
+ for (let step = 1; step <= MAX_STEPS; step++) {
424
+ if (signal?.aborted) {
425
+ updateRunRecord(stateDir, run, { status: 'cancelled', touchedFiles: [...touchedFiles] });
426
+ return { stopReason: 'cancelled', assistantText: finalText, conversation, changes, pendingQuestion: null, run };
427
+ }
428
+ emit({ type: 'status', text: step === 1 ? `${activePersona.name} 正在思考…` : `第 ${step} 步推理与核验…` });
429
+
430
+ const turnResult = await streamModelTurn({
431
+ config,
432
+ messages: [{ role: 'system', content: systemText }, ...conversation],
433
+ tools,
434
+ signal,
435
+ fetchImpl,
436
+ onEvent: ev => {
437
+ if (ev.type === 'thinking_delta') emit({ type: 'thinking', text: ev.text });
438
+ else if (ev.type === 'text_delta') {
439
+ finalText += ev.text;
440
+ emit({ type: 'text', text: ev.text });
441
+ } else if (ev.type === 'tool_call_start') {
442
+ emit({ type: 'tool', id: ev.id, title: ev.name, status: 'pending' });
443
+ }
444
+ },
445
+ });
446
+
447
+ const msg = turnResult.message;
448
+ conversation.push(msg);
449
+ const calls = Array.isArray(msg.tool_calls) ? msg.tool_calls : [];
450
+
451
+ if (!calls.length) {
452
+ if (changes.length) emit({ type: 'changes', items: changes });
453
+ const saved = updateRunRecord(stateDir, run, {
454
+ status: 'completed',
455
+ summary: finalText.slice(0, 300),
456
+ touchedFiles: [...touchedFiles],
457
+ });
458
+ emit({ type: 'run', run: saved });
459
+ return { stopReason: 'end_turn', assistantText: finalText, conversation, changes, pendingQuestion: null, run: saved };
460
+ }
461
+
462
+ let hadVerifyErrors = false;
463
+ for (const call of calls) {
464
+ const toolName = call?.function?.name || 'unknown';
465
+ const callId = call?.id || `call_${step}_${randomUUID().slice(0, 6)}`;
466
+ let parsedArgs = {};
467
+ try { parsedArgs = JSON.parse(call?.function?.arguments || '{}'); } catch {}
468
+
469
+ // ask_user:暂停当前轮次,向观察者展示结构化决策卡并高亮目标卡片
470
+ if (toolName === 'ask_user') {
471
+ const options = Array.isArray(parsedArgs.options)
472
+ ? parsedArgs.options.slice(0, 6).map((opt, idx) => ({
473
+ id: String(opt.id || ('opt_' + (idx + 1))),
474
+ label: String(opt.label || '').trim(),
475
+ detail: opt.detail ? String(opt.detail).trim() : '',
476
+ })).filter(opt => opt.label)
477
+ : [];
478
+ const pendingQuestion = {
479
+ id: randomUUID(),
480
+ toolCallId: callId,
481
+ question: String(parsedArgs.question || '请确认下一步方案:'),
482
+ options,
483
+ allowCustom: parsedArgs.allowCustom !== false,
484
+ file: parsedArgs.file || input.canvas?.file || '',
485
+ targetNode: Array.isArray(parsedArgs.targetNode) ? parsedArgs.targetNode : [],
486
+ };
487
+ emit({ type: 'tool', id: callId, title: 'ask_user', status: 'completed' });
488
+ if (changes.length) emit({ type: 'changes', items: changes });
489
+ emit({ type: 'question', question: pendingQuestion });
490
+ events?.emit(workspace, 'agent.activity', {
491
+ file: pendingQuestion.file,
492
+ action: 'ask_user',
493
+ kind: 'waiting',
494
+ nodes: pendingQuestion.targetNode.length ? [pendingQuestion.targetNode] : [],
495
+ label: '待你拍板 · ' + pendingQuestion.question.slice(0, 42),
496
+ });
497
+ const paused = updateRunRecord(stateDir, run, {
498
+ status: 'waiting_user',
499
+ summary: pendingQuestion.question.slice(0, 300),
500
+ touchedFiles: [...touchedFiles],
501
+ });
502
+ emit({ type: 'run', run: paused });
503
+ return {
504
+ stopReason: 'awaiting_user',
505
+ assistantText: finalText,
506
+ conversation,
507
+ changes,
508
+ pendingQuestion,
509
+ run: paused,
510
+ };
511
+ }
512
+
513
+ emit({ type: 'tool', id: callId, title: toolName, status: 'in_progress' });
514
+ let output;
515
+ try {
516
+ output = await executeTool(toolName, parsedArgs);
517
+ emit({ type: 'tool', id: callId, title: toolName, status: 'completed' });
518
+ if (output?.verification && !output.verification.valid) hadVerifyErrors = true;
519
+ } catch (error) {
520
+ output = { error: error.message || '工具执行失败' };
521
+ emit({ type: 'tool', id: callId, title: toolName, status: 'failed' });
522
+ }
523
+ const serialized = JSON.stringify(output);
524
+ conversation.push({
525
+ role: 'tool',
526
+ tool_call_id: callId,
527
+ content: serialized.length > 24000 ? serialized.slice(0, 24000) + '...(truncated)' : serialized,
528
+ });
529
+ }
530
+
531
+ if (hadVerifyErrors) {
532
+ conversation.push({
533
+ role: 'user',
534
+ content: '自动校验发现画布存在 diagnostics error,请先根据 verification.errors 修正所有错误后再总结汇报。',
535
+ });
536
+ }
537
+ }
538
+
539
+ if (changes.length) emit({ type: 'changes', items: changes });
540
+ const saved = updateRunRecord(stateDir, run, {
541
+ status: 'completed',
542
+ summary: finalText.slice(0, 300),
543
+ touchedFiles: [...touchedFiles],
544
+ });
545
+ emit({ type: 'run', run: saved });
546
+ return { stopReason: 'max_turn_requests', assistantText: finalText, conversation, changes, pendingQuestion: null, run: saved };
547
+ } catch (error) {
548
+ const cancelled = signal?.aborted || error?.name === 'AbortError';
549
+ updateRunRecord(stateDir, run, {
550
+ status: cancelled ? 'cancelled' : 'failed',
551
+ summary: cancelled ? '已取消' : String(error.message || '').slice(0, 300),
552
+ touchedFiles: [...touchedFiles],
553
+ });
554
+ if (cancelled) return { stopReason: 'cancelled', assistantText: '', conversation, changes, pendingQuestion: null, run };
555
+ throw error;
556
+ }
557
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * 系统级内置 Agent 人设预设与多会话持久化(.clado/sessions/<id>.json)。
3
+ */
4
+
5
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+
8
+ export const BUILTIN_PERSONAS = Object.freeze([
9
+ Object.freeze({
10
+ id: 'architect',
11
+ name: '研发架构师',
12
+ summary: '严谨查证本地源码,擅长调用链、数据契约与系统边界拆解',
13
+ prompt: '你是一名资深研发架构师。先看真实代码证据再画设计,严禁编造类名和字段;拆卡片讲究单一职责,跨卡连线必须从具体内容行出发;遇到方案权衡或需求歧义时,主动调用 ask_user 给出清晰选项让用户拍板。',
14
+ }),
15
+ Object.freeze({
16
+ id: 'qa',
17
+ name: 'QA 测试专家',
18
+ summary: '擅长脑图测试用例树,系统化覆盖正常、边界、异常与回归点',
19
+ prompt: '你是一名资深 QA 测试架构师。擅长用脑图结构拆解测试场景,坚持每个模块覆盖正常流、边界条件、异常流和回归检查点;每条用例写清前置条件、操作步骤与可观察预期,不写空泛描述。',
20
+ }),
21
+ Object.freeze({
22
+ id: 'auditor',
23
+ name: '验收审计官',
24
+ summary: '对比本地 Git Diff 与画布设计契约,精准指出遗漏与偏离',
25
+ prompt: '你是一名严谨的交付验收审计官。优先查看本地 git diff 与源码细节,逐项核对实现是否满足画布设计契约和测试用例;清晰列出已满足项、风险偏离项与归档建议。',
26
+ }),
27
+ ]);
28
+
29
+ export function resolvePersona(personaId, customPrompt = '') {
30
+ if (personaId === 'custom' && String(customPrompt || '').trim()) {
31
+ return {
32
+ id: 'custom',
33
+ name: '自定义人设',
34
+ summary: '用户自定义系统提示词',
35
+ prompt: String(customPrompt).trim().slice(0, 4000),
36
+ };
37
+ }
38
+ return BUILTIN_PERSONAS.find(p => p.id === personaId) || BUILTIN_PERSONAS[0];
39
+ }
40
+
41
+ function sessionsDir(stateDir) {
42
+ const dir = join(stateDir, 'sessions');
43
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
44
+ return dir;
45
+ }
46
+
47
+ function safeSessionId(id) {
48
+ if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]{4,80}$/.test(id)) return null;
49
+ return id;
50
+ }
51
+
52
+ export function loadSessionRecord(stateDir, id) {
53
+ const clean = safeSessionId(id);
54
+ if (!stateDir || !clean) return null;
55
+ const path = join(sessionsDir(stateDir), clean + '.json');
56
+ if (!existsSync(path)) return null;
57
+ try { return JSON.parse(readFileSync(path, 'utf8')); } catch { return null; }
58
+ }
59
+
60
+ export function saveSessionRecord(stateDir, record) {
61
+ const clean = safeSessionId(record?.id);
62
+ if (!stateDir || !clean) return null;
63
+ const payload = {
64
+ id: clean,
65
+ title: String(record.title || '新对话').slice(0, 60),
66
+ persona: record.persona || 'architect',
67
+ mode: record.mode || 'design',
68
+ updatedAt: new Date().toISOString(),
69
+ messages: Array.isArray(record.messages) ? record.messages.slice(-40) : [],
70
+ uiMessages: Array.isArray(record.uiMessages) ? record.uiMessages.slice(-60) : [],
71
+ pendingQuestion: record.pendingQuestion || null,
72
+ };
73
+ try { writeFileSync(join(sessionsDir(stateDir), clean + '.json'), JSON.stringify(payload, null, 2) + '\n'); } catch {}
74
+ return payload;
75
+ }
76
+
77
+ export function listSessionRecords(stateDir, limit = 20) {
78
+ if (!stateDir) return [];
79
+ const dir = join(stateDir, 'sessions');
80
+ if (!existsSync(dir) || !lstatSync(dir).isDirectory()) return [];
81
+ const items = [];
82
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
83
+ if (!entry.isFile() || !entry.name.endsWith('.json')) continue;
84
+ try {
85
+ const data = JSON.parse(readFileSync(join(dir, entry.name), 'utf8'));
86
+ items.push({
87
+ id: data.id,
88
+ title: data.title || '未命名会话',
89
+ persona: data.persona || 'architect',
90
+ mode: data.mode || 'design',
91
+ updatedAt: data.updatedAt || '',
92
+ hasPendingQuestion: !!data.pendingQuestion,
93
+ messageCount: Array.isArray(data.uiMessages) ? data.uiMessages.length : 0,
94
+ });
95
+ } catch {}
96
+ }
97
+ return items
98
+ .sort((a, b) => String(b.updatedAt).localeCompare(String(a.updatedAt)))
99
+ .slice(0, limit);
100
+ }
101
+
102
+ export function deleteSessionRecord(stateDir, id) {
103
+ const clean = safeSessionId(id);
104
+ if (!stateDir || !clean) return false;
105
+ const path = join(sessionsDir(stateDir), clean + '.json');
106
+ if (!existsSync(path)) return false;
107
+ try { unlinkSync(path); return true; } catch { return false; }
108
+ }
109
+
110
+ /**
111
+ * 上下文窗口轻量压缩:总字符超限时保留最早的目标背景 + 最近若干轮完整消息,避免上下文爆炸。
112
+ */
113
+ export function compactMessages(messages, maxChars = 36000) {
114
+ if (!Array.isArray(messages) || !messages.length) return [];
115
+ const sizeOf = list => list.reduce((sum, m) => sum + JSON.stringify(m).length, 0);
116
+ if (sizeOf(messages) <= maxChars) return messages;
117
+ const keepTail = Math.min(messages.length, 10);
118
+ const head = messages.slice(0, messages.length - keepTail);
119
+ const tail = messages.slice(-keepTail);
120
+ const digest = head
121
+ .filter(m => (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string' && m.content.trim())
122
+ .slice(-8)
123
+ .map(m => `${m.role === 'user' ? '用户' : 'Agent'}:${m.content.trim().slice(0, 120)}`)
124
+ .join('\n');
125
+ return [
126
+ ...(digest ? [{ role: 'user', content: `【前序对话压缩摘要】\n${digest}` }] : []),
127
+ ...tail,
128
+ ];
129
+ }