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.
@@ -1,445 +0,0 @@
1
- /**
2
- * 四段式前缀缓存(Prefix Cache)上下文装配器、工作区持久记忆(.clado/memory.md)与增量画布感知(Baseline @v1 + Tail Delta @v2)。
3
- *
4
- * 存储策略(用户确认规范):
5
- * - 持久记忆 memory.md 与会话记录按子工作区隔离存储于 `<子工作区>/.clado/`,同时只读兼容根工作区 AGENTS.md / CLAUDE.md;
6
- * - 人设模板与调试开关默认全局共享于 `~/.clado/agent-debug-config.json`,并支持 `<子工作区>/.clado/agent-config.json` 局部覆盖。
7
- */
8
-
9
- import { createHash } from 'node:crypto';
10
- import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
11
- import { join, resolve } from 'node:path';
12
- import { parseDocument } from '../core/parse.js';
13
- import { userTemplatePaths } from '../skill/templates.js';
14
- import { scanDirectory, workspacePath } from '../workspace/documents.js';
15
- import { listCanvasObjects, readCanvasObject } from '../workspace/objects.js';
16
- import { PERSONA_TEMPLATES, compactMessages } from './sessions.js';
17
-
18
- export const DEFAULT_COMPACT_PROMPT = [
19
- '请将早期对话压缩为精炼的阶段摘要,保留:',
20
- '1. 核心目标与业务约束;',
21
- '2. 已定稿的画布卡片、Tag 锚点与代码修改;',
22
- '3. 已拍板的架构决策与未完成步骤。',
23
- ].join('\n');
24
-
25
- export const DEFAULT_AGENT_DEBUG_CONFIG = Object.freeze({
26
- canvasMemory: 'delta', // 'delta' (智能增量) | 'outline' (仅大纲) | 'full' (每次全量) | 'off' (关闭)
27
- timeInjection: 'date_only', // 'none' | 'date_only' (仅日期,保缓存) | 'tail_exact' (尾部精确时间) | 'system_head' (系统头时间,破缓存调试对比)
28
- workspaceMap: true, // 是否注入轻量工作区文档与卡片标题目录索引
29
- memoryEnabled: true, // 是否注入 .clado/memory.md 持久记忆
30
- autoArchiveHours: 24, // 空闲会话自动归档时长:6 | 24 | 0 (不自动归档)
31
- commandPermission: 'readonly_free', // 'readonly_free' (只读免审) | 'ask_always' (每次询问) | 'allow_all' (自动允许)
32
- compactThresholdPct: 75, // 上下文压缩触发阈值百分比 (50 - 90)
33
- compactPrompt: DEFAULT_COMPACT_PROMPT,
34
- personas: Object.fromEntries(
35
- PERSONA_TEMPLATES.map(p => [p.id, { prompt: p.prompt, initContext: p.initContext }]),
36
- ),
37
- });
38
-
39
- function safeReadJson(path) {
40
- if (!path || !existsSync(path)) return null;
41
- try {
42
- const raw = JSON.parse(readFileSync(path, 'utf8'));
43
- return raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : null;
44
- } catch {
45
- return null;
46
- }
47
- }
48
-
49
- function sanitizeConfig(raw = {}) {
50
- const out = {
51
- canvasMemory: ['delta', 'outline', 'full', 'off'].includes(raw.canvasMemory) ? raw.canvasMemory : DEFAULT_AGENT_DEBUG_CONFIG.canvasMemory,
52
- timeInjection: ['none', 'date_only', 'tail_exact', 'system_head'].includes(raw.timeInjection) ? raw.timeInjection : DEFAULT_AGENT_DEBUG_CONFIG.timeInjection,
53
- workspaceMap: typeof raw.workspaceMap === 'boolean' ? raw.workspaceMap : DEFAULT_AGENT_DEBUG_CONFIG.workspaceMap,
54
- memoryEnabled: typeof raw.memoryEnabled === 'boolean' ? raw.memoryEnabled : DEFAULT_AGENT_DEBUG_CONFIG.memoryEnabled,
55
- autoArchiveHours: [0, 6, 24].includes(Number(raw.autoArchiveHours)) ? Number(raw.autoArchiveHours) : DEFAULT_AGENT_DEBUG_CONFIG.autoArchiveHours,
56
- commandPermission: ['readonly_free', 'ask_always', 'allow_all'].includes(raw.commandPermission) ? raw.commandPermission : DEFAULT_AGENT_DEBUG_CONFIG.commandPermission,
57
- compactThresholdPct: Math.min(90, Math.max(50, Number(raw.compactThresholdPct) || DEFAULT_AGENT_DEBUG_CONFIG.compactThresholdPct)),
58
- compactPrompt: typeof raw.compactPrompt === 'string' && raw.compactPrompt.trim()
59
- ? raw.compactPrompt.trim().slice(0, 3000)
60
- : DEFAULT_AGENT_DEBUG_CONFIG.compactPrompt,
61
- personas: {},
62
- };
63
-
64
- const rawPersonas = raw.personas && typeof raw.personas === 'object' ? raw.personas : {};
65
- const builtinIds = new Set(PERSONA_TEMPLATES.map(t => t.id));
66
- for (const tpl of PERSONA_TEMPLATES) {
67
- const item = rawPersonas[tpl.id] && typeof rawPersonas[tpl.id] === 'object' ? rawPersonas[tpl.id] : {};
68
- out.personas[tpl.id] = {
69
- name: typeof item.name === 'string' && item.name.trim() ? item.name.trim().slice(0, 40) : tpl.name,
70
- pal: tpl.pal,
71
- summary: tpl.summary,
72
- prompt: typeof item.prompt === 'string' && item.prompt.trim() ? item.prompt.trim().slice(0, 4000) : tpl.prompt,
73
- initContext: typeof item.initContext === 'string' ? item.initContext.trim().slice(0, 2000) : tpl.initContext,
74
- };
75
- }
76
- for (const [k, v] of Object.entries(rawPersonas)) {
77
- if (builtinIds.has(k) || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,31}$/.test(k)) continue;
78
- if (!v || typeof v !== 'object') continue;
79
- out.personas[k] = {
80
- name: typeof v.name === 'string' && v.name.trim() ? v.name.trim().slice(0, 40) : k,
81
- pal: typeof v.pal === 'string' ? v.pal : 'violet',
82
- summary: typeof v.summary === 'string' ? v.summary.slice(0, 80) : (typeof v.prompt === 'string' ? v.prompt.trim().slice(0, 48) : '自定义人设'),
83
- prompt: typeof v.prompt === 'string' ? v.prompt.trim().slice(0, 4000) : '',
84
- initContext: typeof v.initContext === 'string' ? v.initContext.trim().slice(0, 2000) : '',
85
- custom: true,
86
- };
87
- }
88
- return out;
89
- }
90
-
91
- export function globalAgentConfigPath() {
92
- return join(userTemplatePaths().state, 'agent-debug-config.json');
93
- }
94
-
95
- export function workspaceAgentConfigPath(stateDir) {
96
- return stateDir ? join(stateDir, 'agent-config.json') : null;
97
- }
98
-
99
- export function readAgentDebugConfig(stateDir) {
100
- const globalCfg = safeReadJson(globalAgentConfigPath()) || {};
101
- const wsPath = workspaceAgentConfigPath(stateDir);
102
- const wsCfg = safeReadJson(wsPath) || {};
103
- const mergedPersonas = {
104
- ...(globalCfg.personas || {}),
105
- ...(wsCfg.personas || {}),
106
- };
107
- const merged = sanitizeConfig({ ...globalCfg, ...wsCfg, personas: mergedPersonas });
108
- return {
109
- config: merged,
110
- hasWorkspaceOverride: Boolean(wsPath && existsSync(wsPath)),
111
- };
112
- }
113
-
114
- export function saveAgentDebugConfig(stateDir, patch = {}, { scope = 'global' } = {}) {
115
- const current = readAgentDebugConfig(stateDir).config;
116
- const nextPersonas = { ...current.personas };
117
- if (patch.personas && typeof patch.personas === 'object') {
118
- for (const [k, v] of Object.entries(patch.personas)) {
119
- if (v === null) {
120
- delete nextPersonas[k];
121
- } else if (v && typeof v === 'object' && /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,31}$/.test(k)) {
122
- nextPersonas[k] = { ...(nextPersonas[k] || {}), ...v };
123
- }
124
- }
125
- }
126
- const next = sanitizeConfig({ ...current, ...patch, personas: nextPersonas });
127
- const targetPath = scope === 'workspace' && stateDir ? workspaceAgentConfigPath(stateDir) : globalAgentConfigPath();
128
- const dir = resolve(targetPath, '..');
129
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
130
- writeFileSync(targetPath, JSON.stringify(next, null, 2) + '\n');
131
- return readAgentDebugConfig(stateDir);
132
- }
133
-
134
- export function resetAgentDebugConfig(stateDir, section = 'all') {
135
- const current = readAgentDebugConfig(stateDir).config;
136
- let next = { ...current };
137
- if (section === 'all') {
138
- const wsPath = workspaceAgentConfigPath(stateDir);
139
- if (wsPath && existsSync(wsPath)) {
140
- try { unlinkSync(wsPath); } catch {}
141
- }
142
- next = sanitizeConfig({});
143
- } else if (section === 'compact') {
144
- next = sanitizeConfig({
145
- ...current,
146
- compactThresholdPct: DEFAULT_AGENT_DEBUG_CONFIG.compactThresholdPct,
147
- compactPrompt: DEFAULT_AGENT_DEBUG_CONFIG.compactPrompt,
148
- });
149
- } else if (section === 'personas') {
150
- next = sanitizeConfig({ ...current, personas: {} });
151
- }
152
- const targetPath = globalAgentConfigPath();
153
- const dir = resolve(targetPath, '..');
154
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
155
- writeFileSync(targetPath, JSON.stringify(next, null, 2) + '\n');
156
- return readAgentDebugConfig(stateDir);
157
- }
158
-
159
- /**
160
- * 读取子工作区持久记忆 `.clado/memory.md`,并只读合并根工作区的 AGENTS.md / CLAUDE.md。
161
- */
162
- export function readWorkspaceMemory(stateDir, rootWorkspace = '') {
163
- const memPath = stateDir ? join(stateDir, 'memory.md') : '';
164
- let memoryText = '';
165
- if (memPath && existsSync(memPath)) {
166
- try { memoryText = readFileSync(memPath, 'utf8').slice(0, 12000); } catch {}
167
- }
168
-
169
- const inherited = [];
170
- if (rootWorkspace) {
171
- for (const name of ['AGENTS.md', 'CLAUDE.md']) {
172
- const p = join(rootWorkspace, name);
173
- if (existsSync(p)) {
174
- try {
175
- const content = readFileSync(p, 'utf8').trim().slice(0, 6000);
176
- if (content) inherited.push({ file: name, content });
177
- } catch {}
178
- }
179
- }
180
- }
181
- return {
182
- path: '.clado/memory.md',
183
- text: memoryText,
184
- inherited,
185
- };
186
- }
187
-
188
- export function saveWorkspaceMemory(stateDir, text = '') {
189
- if (!stateDir) throw new Error('未找到子工作区状态目录。');
190
- if (!existsSync(stateDir)) mkdirSync(stateDir, { recursive: true });
191
- const clean = String(text || '').replace(/\r\n/g, '\n').slice(0, 12000);
192
- writeFileSync(join(stateDir, 'memory.md'), clean);
193
- return clean;
194
- }
195
-
196
- function shortHash(text) {
197
- return createHash('sha1').update(String(text || '')).digest('hex').slice(0, 10);
198
- }
199
-
200
- function estimateTokens(text) {
201
- const s = String(text || '');
202
- if (!s) return 0;
203
- // 中英混合经验估算:约 2.8 字符 / token
204
- return Math.max(1, Math.ceil(s.length / 2.8));
205
- }
206
-
207
- function buildWorkspaceMapText(documentRoot, stateDir = '') {
208
- const blocks = [];
209
- if (documentRoot && existsSync(documentRoot)) {
210
- try {
211
- const scanned = scanDirectory(documentRoot);
212
- const docs = Array.isArray(scanned?.documents) ? scanned.documents.slice(0, 30) : [];
213
- if (docs.length) {
214
- const lines = docs.map(d => {
215
- const cards = Array.isArray(d.cards) ? d.cards.slice(0, 10).join(' / ') : '';
216
- return `- ${d.file}${d.title ? `(${d.title})` : ''}${cards ? `:${cards}` : ''}`;
217
- });
218
- blocks.push(`【工作区画布全局索引】\n${lines.join('\n')}`);
219
- } else {
220
- blocks.push('(当前工作区暂无画布文档)');
221
- }
222
- } catch {}
223
- }
224
- if (stateDir) {
225
- const objs = listCanvasObjects(stateDir, 30);
226
- if (objs.length) {
227
- const objLines = objs.map(o => `- [${o.id}] ${o.title} (${o.kind})${o.text ? `:${o.text.slice(0, 60)}` : ''}`);
228
- blocks.push(`【画布多实例对象索引 (.clado/objects)】\n${objLines.join('\n')}`);
229
- }
230
- }
231
- return blocks.join('\n\n');
232
- }
233
-
234
- function inspectCanvasCards(documentRoot, relFile) {
235
- if (!documentRoot || !relFile) return null;
236
- try {
237
- const fullPath = workspacePath(documentRoot, relFile);
238
- if (!existsSync(fullPath)) return null;
239
- const raw = readFileSync(fullPath, 'utf8');
240
- const fileHash = shortHash(raw);
241
- const { doc } = parseDocument(raw);
242
- const cards = {};
243
- const outline = [];
244
- const flattenNodes = (nodes = []) => {
245
- const parts = [];
246
- for (const n of nodes) {
247
- parts.push(`${'#'.repeat(n.d || 2)} ${n.title}${n.md ? '\n' + n.md : ''}`);
248
- if (Array.isArray(n.kids) && n.kids.length) parts.push(...flattenNodes(n.kids));
249
- }
250
- return parts;
251
- };
252
- for (const card of doc.cards || []) {
253
- const childNodes = Array.isArray(card.nodes) ? card.nodes : [];
254
- const fullCardText = [card.md || '', ...flattenNodes(childNodes)].filter(Boolean).join('\n').trim();
255
- const snippet = fullCardText.slice(0, 600);
256
- const childTitles = childNodes.map(c => c.title);
257
- const cardSig = shortHash(JSON.stringify([card.title, fullCardText, childTitles]));
258
- cards[card.title] = {
259
- hash: cardSig,
260
- children: childTitles,
261
- snippet,
262
- };
263
- outline.push(`- # ${card.title}${childTitles.length ? `(子节:${childTitles.join('、')})` : ''}`);
264
- }
265
- return {
266
- file: relFile,
267
- fileHash,
268
- raw: raw.slice(0, 14000),
269
- outlineText: outline.join('\n'),
270
- cards,
271
- };
272
- } catch {
273
- return null;
274
- }
275
- }
276
-
277
- /**
278
- * 组装四段式前缀缓存消息队列与增量画布上下文,并输出缓存命中遥测指标。
279
- */
280
- export function buildSegmentedPromptContext({
281
- workspace,
282
- rootWorkspace = workspace,
283
- documentRoot = workspace,
284
- stateDir = '',
285
- debugConfig = DEFAULT_AGENT_DEBUG_CONFIG,
286
- baseSystemPrompt = '',
287
- history = [],
288
- canvas = null,
289
- canvasBaseline = null,
290
- activePeerLocks = [],
291
- incomingPeerMessages = [],
292
- userInstruction = '',
293
- isResumeTool = false,
294
- now = new Date(),
295
- }) {
296
- const cfg = sanitizeConfig(debugConfig);
297
- const isoDate = now.toISOString().slice(0, 10);
298
- const isoExact = now.toISOString();
299
-
300
- // ========== 第 1 段:冰封静态系统头(跨轮次、跨分身 100% 共享前缀缓存) ==========
301
- const seg1Parts = [baseSystemPrompt.trim()];
302
- if (cfg.timeInjection === 'system_head') {
303
- // 仅供用户在调试面板直观观察“系统头塞精确时间破坏缓存”的反面对比模式
304
- seg1Parts.push(`当前系统精确时间:${isoExact}`);
305
- }
306
- const seg1Text = seg1Parts.filter(Boolean).join('\n\n');
307
-
308
- // ========== 第 2 段:工作区静态索引与持久记忆(文件/记忆未改时稳定命中缓存) ==========
309
- const seg2Parts = [];
310
- if (cfg.timeInjection === 'date_only') {
311
- seg2Parts.push(`当前日期:${isoDate}`);
312
- }
313
- if (cfg.memoryEnabled && stateDir) {
314
- const mem = readWorkspaceMemory(stateDir, rootWorkspace);
315
- for (const inh of mem.inherited) {
316
- seg2Parts.push(`【继承根工作区规范 · ${inh.file}(只读)】\n${inh.content}`);
317
- }
318
- if (mem.text.trim()) {
319
- seg2Parts.push(`【当前工作区持久记忆 · .clado/memory.md】\n${mem.text.trim()}`);
320
- }
321
- }
322
- if (cfg.workspaceMap) {
323
- const mapText = buildWorkspaceMapText(documentRoot, stateDir);
324
- if (mapText) seg2Parts.push(mapText);
325
- }
326
- const seg2Text = seg2Parts.filter(Boolean).join('\n\n');
327
- const fullSystemText = [seg1Text, seg2Text].filter(Boolean).join('\n\n---\n\n');
328
-
329
- // ========== 第 3 段:原子级压缩后的历史对话 + 画布基线 @v1 ==========
330
- const compacted = compactMessages(history, {
331
- maxChars: 42000,
332
- thresholdPct: cfg.compactThresholdPct,
333
- compactPrompt: cfg.compactPrompt,
334
- });
335
-
336
- let nextBaseline = canvasBaseline || null;
337
- let canvasBaselineBlock = '';
338
- let canvasDeltaBlock = '';
339
- const snap = canvas?.file ? inspectCanvasCards(documentRoot, canvas.file) : null;
340
-
341
- if (snap && cfg.canvasMemory !== 'off') {
342
- if (cfg.canvasMemory === 'outline') {
343
- canvasDeltaBlock = `【当前画布大纲 · ${snap.file}】\n${snap.outlineText || '(空画布)'}`;
344
- } else if (cfg.canvasMemory === 'full') {
345
- canvasDeltaBlock = `【当前画布全量内容 · ${snap.file}】\n${snap.raw}`;
346
- } else {
347
- // 默认 'delta'(智能增量:Baseline @v1 + Tail Delta @v2)
348
- if (!canvasBaseline || canvasBaseline.file !== snap.file) {
349
- const cardHashes = Object.fromEntries(Object.entries(snap.cards).map(([k, v]) => [k, v.hash]));
350
- const baselineText = [
351
- `【画布基线 @v1 · ${snap.file} (rev:${snap.fileHash})】`,
352
- snap.outlineText || '(空画布)',
353
- ].join('\n');
354
- nextBaseline = { file: snap.file, fileHash: snap.fileHash, cardHashes, baselineText };
355
- canvasBaselineBlock = baselineText;
356
- } else if (canvasBaseline.fileHash === snap.fileHash) {
357
- canvasBaselineBlock = canvasBaseline.baselineText || '';
358
- canvasDeltaBlock = `【画布增量 @v2 · ${snap.file}】自基线以来无外部改动。`;
359
- } else {
360
- canvasBaselineBlock = canvasBaseline.baselineText || '';
361
- const prevHashes = canvasBaseline.cardHashes || {};
362
- const changed = [];
363
- const removed = [];
364
- for (const [title, info] of Object.entries(snap.cards)) {
365
- if (!prevHashes[title]) changed.push(`+ 新增卡片「${title}」:\n${info.snippet}`);
366
- else if (prevHashes[title] !== info.hash) changed.push(`~ 修改卡片「${title}」:\n${info.snippet}`);
367
- }
368
- for (const oldTitle of Object.keys(prevHashes)) {
369
- if (!snap.cards[oldTitle]) removed.push(`- 已移除卡片「${oldTitle}」`);
370
- }
371
- const deltaLines = [...changed, ...removed].slice(0, 12);
372
- canvasDeltaBlock = deltaLines.length
373
- ? `【画布实时增量 @v2 · ${snap.file}】\n${deltaLines.join('\n\n')}`
374
- : `【画布实时增量 @v2 · ${snap.file}】仅非结构性空白变动。`;
375
- }
376
- }
377
- }
378
-
379
- const conversation = [...compacted];
380
- if (canvasBaselineBlock && !conversation.some(m => typeof m?.content === 'string' && m.content.includes('【画布基线 @v1'))) {
381
- conversation.unshift({ role: 'user', content: canvasBaselineBlock });
382
- }
383
-
384
- // ========== 第 4 段:尾部极小动态增量区(选区 / 多实例对象选区 / 同伴锁 / 同伴来信 / 尾部时间 / 当前指令) ==========
385
- const tailMeta = [`当前工作区:${workspace}`];
386
- if (canvas?.file) tailMeta.push(`当前打开画布:${canvas.file}`);
387
- if (Array.isArray(canvas?.selection) && canvas.selection.length) {
388
- tailMeta.push(`用户当前选中项:${JSON.stringify(canvas.selection)}`);
389
- }
390
- if (Array.isArray(canvas?.objectSelection) && canvas.objectSelection.length) {
391
- const objDetails = canvas.objectSelection.map(sel => {
392
- const full = stateDir ? readCanvasObject(stateDir, sel.id) : null;
393
- const bodyPart = full?.text ? ` · 内容:「${full.text.slice(0, 200)}」` : '';
394
- const subPart = sel.subtarget ? ` · 子区域靶点:${sel.subtarget}` : '';
395
- return `- [${sel.id}] ${sel.title || full?.title || sel.kind}${subPart}${bodyPart}`;
396
- });
397
- tailMeta.push(`【用户当前选中的多实例组件/子项】\n${objDetails.join('\n')}`);
398
- }
399
- if (cfg.timeInjection === 'tail_exact') {
400
- tailMeta.push(`当前精确时间:${isoExact}`);
401
- }
402
- if (canvasDeltaBlock) {
403
- tailMeta.push(canvasDeltaBlock);
404
- }
405
- if (Array.isArray(activePeerLocks) && activePeerLocks.length) {
406
- tailMeta.push(`【同伴卡片领地占用提示】\n${activePeerLocks.map(l => `- 同伴「${l.peerName}」正在操作 ${l.target},请避免并发覆写同一卡片`).join('\n')}`);
407
- }
408
- if (Array.isArray(incomingPeerMessages) && incomingPeerMessages.length) {
409
- tailMeta.push(`【收到同伴实时协作消息】\n${incomingPeerMessages.map(m => `- 来自「${m.fromName}」(${m.kind === 'notify' ? '单向通知,无需回执' : '协作请求'}):${m.text}`).join('\n')}`);
410
- }
411
-
412
- const seg4UserContent = isResumeTool
413
- ? ''
414
- : `${tailMeta.join('\n')}\n\n用户指令:\n${userInstruction}`;
415
-
416
- // 计算四段式缓存命中估算
417
- const seg1Tokens = estimateTokens(seg1Text) + 640; // 含固定工具 Schema
418
- const seg2Tokens = estimateTokens(seg2Text);
419
- const seg3Tokens = estimateTokens(JSON.stringify(conversation));
420
- const seg4Tokens = estimateTokens(seg4UserContent || 'tool_result');
421
- const totalTokens = Math.max(1, seg1Tokens + seg2Tokens + seg3Tokens + seg4Tokens);
422
- const brokenBySystemTime = cfg.timeInjection === 'system_head';
423
- const fullCanvasPenalty = cfg.canvasMemory === 'full' ? Math.min(seg4Tokens, Math.floor(totalTokens * 0.18)) : 0;
424
- const cachedTokens = brokenBySystemTime
425
- ? 0
426
- : Math.max(0, seg1Tokens + seg2Tokens + seg3Tokens - fullCanvasPenalty);
427
- const hitRatePct = Number(((cachedTokens / totalTokens) * 100).toFixed(1));
428
-
429
- return {
430
- systemText: fullSystemText,
431
- conversation,
432
- seg4UserContent,
433
- nextBaseline,
434
- telemetry: {
435
- seg1Tokens,
436
- seg2Tokens,
437
- seg3Tokens,
438
- seg4Tokens,
439
- totalTokens,
440
- cachedTokens,
441
- hitRatePct,
442
- brokenBySystemTime,
443
- },
444
- };
445
- }
@@ -1,213 +0,0 @@
1
- /**
2
- * ACP 执行器插件注册、任务包组装与运行记录(.clado/runs/)。
3
- *
4
- * 将外部 Coding Agent(ZCode / Claude Code / Codex / 自定义插件执行器)统一建模为
5
- * 可发现、可派单的 ACP Executor,用户在 Clado 面板内一键外包开发并实时等待结果。
6
- */
7
-
8
- import { randomUUID } from 'node:crypto';
9
- import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
10
- import { join } from 'node:path';
11
- import { z } from 'zod/v4';
12
- import { readDocument, scanDirectory, workspacePath } from '../workspace/documents.js';
13
-
14
- export const executorSchema = z.strictObject({
15
- id: z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/),
16
- name: z.string().trim().min(1).max(80),
17
- protocol: z.literal('acp').default('acp'),
18
- command: z.string().trim().min(1).max(2048),
19
- args: z.array(z.string().max(2048)).max(32).default([]),
20
- env: z.record(z.string(), z.string().max(2048)).default({}),
21
- capabilities: z.array(z.string().min(1).max(64)).max(16).default(['code.write', 'test.run']),
22
- description: z.string().max(400).optional(),
23
- });
24
-
25
- /**
26
- * 发现工作区可用的全部 ACP 执行器(内置/用户配置 + 插件包声明的 contributes.executors)。
27
- */
28
- export function discoverExecutors({ stateDir, settings = {}, pluginDescriptors = [] } = {}) {
29
- const result = [];
30
- const seen = new Set();
31
- const push = item => {
32
- if (!item || seen.has(item.id)) return;
33
- seen.add(item.id);
34
- result.push(item);
35
- };
36
-
37
- if (settings.command) {
38
- push({
39
- id: 'acp.default',
40
- name: settings.name || '默认 ACP 执行器',
41
- protocol: 'acp',
42
- command: settings.command,
43
- args: Array.isArray(settings.args) ? settings.args : [],
44
- env: settings.env && typeof settings.env === 'object' ? settings.env : {},
45
- capabilities: ['code.write', 'test.run'],
46
- description: '来自「灵感」设置的默认外部 ACP Coding Agent',
47
- source: 'settings',
48
- });
49
- }
50
-
51
- for (const raw of Array.isArray(settings.executors) ? settings.executors : []) {
52
- const parsed = executorSchema.safeParse(raw);
53
- if (!parsed.success) continue;
54
- push({ ...parsed.data, source: 'settings' });
55
- }
56
-
57
- // 从已加载插件或 .clado/plugins/*/clado-plugin.json 发现声明式执行器
58
- for (const plugin of pluginDescriptors) {
59
- for (const raw of Array.isArray(plugin?.executors) ? plugin.executors : []) {
60
- const parsed = executorSchema.safeParse(raw);
61
- if (!parsed.success) continue;
62
- push({ ...parsed.data, id: plugin.id + '/' + parsed.data.id, pluginId: plugin.id, source: 'plugin' });
63
- }
64
- }
65
-
66
- if (stateDir) {
67
- const dir = join(stateDir, 'plugins');
68
- if (existsSync(dir) && lstatSync(dir).isDirectory()) {
69
- for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
70
- if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
71
- const manifestPath = join(dir, entry.name, 'clado-plugin.json');
72
- if (!existsSync(manifestPath)) continue;
73
- try {
74
- const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
75
- const declared = manifest?.contributes?.executors;
76
- if (!Array.isArray(declared) || !manifest?.id) continue;
77
- for (const raw of declared) {
78
- const parsed = executorSchema.safeParse(raw);
79
- if (!parsed.success) continue;
80
- push({
81
- ...parsed.data,
82
- id: manifest.id + '/' + parsed.data.id,
83
- pluginId: manifest.id,
84
- source: 'plugin',
85
- });
86
- }
87
- } catch {}
88
- }
89
- }
90
- }
91
-
92
- return result;
93
- }
94
-
95
- /**
96
- * 面向前端的安全摘要(不向浏览器泄露 command/env 敏感细节)。
97
- */
98
- export function publicExecutorList(executors) {
99
- return executors.map(({ id, name, protocol, capabilities, description, source, pluginId }) => ({
100
- id, name, protocol, capabilities, description: description || '', source, ...(pluginId ? { pluginId } : {}),
101
- }));
102
- }
103
-
104
- /**
105
- * 基于当前画布文档与选区,组装发给外部 ACP Coding Agent 的 Executable Spec 任务包。
106
- */
107
- export function buildDispatchPrompt({ workspace, documentRoot, file, selection = [], instruction = '', mcpName = '' }) {
108
- const blocks = [];
109
- let specExcerpt = '';
110
- let relatedTests = [];
111
-
112
- if (documentRoot && file) {
113
- try {
114
- const fullPath = workspacePath(documentRoot, file);
115
- const item = readDocument(fullPath);
116
- specExcerpt = item.source.length > 24000
117
- ? item.source.slice(0, 24000) + '\n\n<!-- spec truncated; use Clado MCP to read full document -->'
118
- : item.source;
119
- } catch {}
120
- try {
121
- const { documents } = scanDirectory(documentRoot);
122
- relatedTests = documents
123
- .filter(d => d.file !== file && /test|用例|qa/i.test(d.file + ' ' + d.title))
124
- .slice(0, 5)
125
- .map(d => `${d.file}(${d.title})`);
126
- } catch {}
127
- }
128
-
129
- blocks.push({
130
- type: 'text',
131
- text: [
132
- '你是通过 Clado ACP 执行器插件被派发的外部开发执行器(Coding Agent)。',
133
- '你的任务是严格依据 Clado 画布中已拍板的设计规格与测试用例在本地仓库完成代码实现与测试验证。',
134
- mcpName ? `执行期间可通过已连接的 ${mcpName} MCP 读取更多画布文档或更新实现备注(workspace: ${workspace})。` : '',
135
- '完成后请给出简明实现总结:改了哪些文件、跑了哪些测试、是否有偏离设计之处。',
136
- ].filter(Boolean).join('\n'),
137
- });
138
-
139
- blocks.push({
140
- type: 'text',
141
- text: JSON.stringify({
142
- workspace,
143
- specFile: file || '',
144
- selection,
145
- relatedTestDocs: relatedTests,
146
- }),
147
- });
148
-
149
- if (specExcerpt) {
150
- blocks.push({
151
- type: 'text',
152
- text: `以下为当前画布规格全文(${file}):\n\n${specExcerpt}`,
153
- });
154
- }
155
-
156
- blocks.push({
157
- type: 'text',
158
- text: '用户派发指令:\n' + (instruction.trim() || '请严格按上述 Clado 设计规格完成代码实现与测试验证。'),
159
- });
160
-
161
- return blocks;
162
- }
163
-
164
- /* ── 轻量运行记录(.clado/runs/<runId>.json) ─────────────────── */
165
-
166
- function runsDir(stateDir) {
167
- const dir = join(stateDir, 'runs');
168
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
169
- return dir;
170
- }
171
-
172
- export function createRunRecord(stateDir, record) {
173
- if (!stateDir) return { id: randomUUID(), ...record, createdAt: new Date().toISOString() };
174
- const id = record.id || randomUUID();
175
- const payload = {
176
- id,
177
- kind: record.kind || 'builtin',
178
- mode: record.mode || 'design',
179
- executorId: record.executorId || null,
180
- file: record.file || '',
181
- instruction: String(record.instruction || '').slice(0, 400),
182
- status: 'running',
183
- createdAt: new Date().toISOString(),
184
- updatedAt: new Date().toISOString(),
185
- summary: '',
186
- touchedFiles: [],
187
- };
188
- try { writeFileSync(join(runsDir(stateDir), id + '.json'), JSON.stringify(payload, null, 2) + '\n'); } catch {}
189
- return payload;
190
- }
191
-
192
- export function updateRunRecord(stateDir, run, patch = {}) {
193
- if (!run) return null;
194
- const next = { ...run, ...patch, updatedAt: new Date().toISOString() };
195
- if (stateDir && next.id) {
196
- try { writeFileSync(join(runsDir(stateDir), next.id + '.json'), JSON.stringify(next, null, 2) + '\n'); } catch {}
197
- }
198
- return next;
199
- }
200
-
201
- export function listRunRecords(stateDir, limit = 12) {
202
- if (!stateDir) return [];
203
- const dir = join(stateDir, 'runs');
204
- if (!existsSync(dir) || !lstatSync(dir).isDirectory()) return [];
205
- const items = [];
206
- for (const entry of readdirSync(dir, { withFileTypes: true })) {
207
- if (!entry.isFile() || !entry.name.endsWith('.json')) continue;
208
- try { items.push(JSON.parse(readFileSync(join(dir, entry.name), 'utf8'))); } catch {}
209
- }
210
- return items
211
- .sort((a, b) => String(b.createdAt || '').localeCompare(String(a.createdAt || '')))
212
- .slice(0, limit);
213
- }