cladogram 0.5.5-beta.9 → 0.6.0-beta.2
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 +15 -0
- package/package.json +3 -3
- package/plugins/agent/index.js +1575 -3081
- package/plugins/agent/style.css +724 -1438
- 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 +621 -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 +334 -1589
- 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/sessions.js
DELETED
|
@@ -1,336 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 系统级内置 Agent 人设模板、统一多会话池(活跃排序 · 24h 自动归档 · 手动归档/删除 · 轮次快照)与原子级上下文压缩。
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
6
|
-
import { join } from 'node:path';
|
|
7
|
-
|
|
8
|
-
export const SESSION_PALETTE_KEYS = Object.freeze(['blue', 'teal', 'violet', 'amber', 'cyan', 'rose']);
|
|
9
|
-
|
|
10
|
-
export const PERSONA_TEMPLATES = Object.freeze([
|
|
11
|
-
Object.freeze({
|
|
12
|
-
id: 'architect',
|
|
13
|
-
name: '研发架构师',
|
|
14
|
-
pal: 'blue',
|
|
15
|
-
summary: '严谨查证本地源码,擅长调用链、数据契约与系统边界拆解',
|
|
16
|
-
prompt: '你是一名资深研发架构师。先看真实代码证据再画设计,严禁编造类名和字段;拆卡片讲究单一职责,跨卡连线必须从具体内容行出发;遇到方案权衡或需求歧义时,主动调用 ask_user 给出清晰选项让用户拍板。',
|
|
17
|
-
initContext: '当核心接口契约卡片定稿后,可通过 spawn_peer 或 message_peer 呼叫下游实现/测试同伴并行跟进。',
|
|
18
|
-
}),
|
|
19
|
-
Object.freeze({
|
|
20
|
-
id: 'coder',
|
|
21
|
-
name: '后端实现者',
|
|
22
|
-
pal: 'teal',
|
|
23
|
-
summary: '依据定稿画布契约编写高内聚代码并通过单测验证',
|
|
24
|
-
prompt: '你是一名务实的后端实现工程师。严格对齐画布中已拍板的接口契约与 Tag 锚点,先读存量代码再做最小侵入实现,完成后主动验证单测或诊断状态。',
|
|
25
|
-
initContext: '收到上游交接后核对幂等与异常分支,跑通相关测试命令后用 notify 同步结论。',
|
|
26
|
-
}),
|
|
27
|
-
Object.freeze({
|
|
28
|
-
id: 'qa',
|
|
29
|
-
name: 'QA 测试专家',
|
|
30
|
-
pal: 'violet',
|
|
31
|
-
summary: '擅长脑图测试用例树,系统化覆盖正常、边界、异常与回归点',
|
|
32
|
-
prompt: '你是一名资深 QA 测试架构师。擅长用脑图结构拆解测试场景,坚持每个模块覆盖正常流、边界条件、异常流和回归检查点;每条用例写清前置条件、操作步骤与可观察预期,不写空泛描述。',
|
|
33
|
-
initContext: '重点审查超时重发、并发重入与空值边界,将用例直接沉淀到 test-cases 画布中。',
|
|
34
|
-
}),
|
|
35
|
-
Object.freeze({
|
|
36
|
-
id: 'auditor',
|
|
37
|
-
name: '验收审计官',
|
|
38
|
-
pal: 'amber',
|
|
39
|
-
summary: '对比本地 Git Diff 与画布设计契约,精准指出遗漏与偏离',
|
|
40
|
-
prompt: '你是一名严谨的交付验收审计官。优先查看本地 git diff 与源码细节,逐项核对实现是否满足画布设计契约和测试用例;清晰列出已满足项、风险偏离项与归档建议。',
|
|
41
|
-
initContext: '默认只读审查签名校验、越权访问与异常吞没风险,发现偏差精准指向对应卡片或代码行。',
|
|
42
|
-
}),
|
|
43
|
-
]);
|
|
44
|
-
|
|
45
|
-
// 保持既有 3 项 BUILTIN_PERSONAS 导出,确保旧版元信息测试 100% 兼容
|
|
46
|
-
export const BUILTIN_PERSONAS = Object.freeze(
|
|
47
|
-
PERSONA_TEMPLATES.filter(p => p.id !== 'coder').map(({ id, name, summary, prompt }) => Object.freeze({ id, name, summary, prompt })),
|
|
48
|
-
);
|
|
49
|
-
|
|
50
|
-
export function paletteForPersona(personaId, fallbackIdx = 0) {
|
|
51
|
-
const found = PERSONA_TEMPLATES.find(p => p.id === personaId);
|
|
52
|
-
if (found) return found.pal;
|
|
53
|
-
return SESSION_PALETTE_KEYS[Math.abs(Number(fallbackIdx) || 0) % SESSION_PALETTE_KEYS.length];
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
export function resolvePersona(personaId, customPrompt = '', personaOverrides = null) {
|
|
57
|
-
if (personaId === 'custom' && String(customPrompt || '').trim()) {
|
|
58
|
-
return {
|
|
59
|
-
id: 'custom',
|
|
60
|
-
name: '自定义人设',
|
|
61
|
-
pal: 'cyan',
|
|
62
|
-
summary: '用户自定义系统提示词',
|
|
63
|
-
prompt: String(customPrompt).trim().slice(0, 4000),
|
|
64
|
-
initContext: '',
|
|
65
|
-
};
|
|
66
|
-
}
|
|
67
|
-
const base = PERSONA_TEMPLATES.find(p => p.id === personaId) || PERSONA_TEMPLATES[0];
|
|
68
|
-
const ov = personaOverrides && typeof personaOverrides === 'object' ? personaOverrides[base.id] : null;
|
|
69
|
-
if (!ov || typeof ov !== 'object') return base;
|
|
70
|
-
return {
|
|
71
|
-
...base,
|
|
72
|
-
prompt: typeof ov.prompt === 'string' && ov.prompt.trim() ? ov.prompt.trim().slice(0, 4000) : base.prompt,
|
|
73
|
-
initContext: typeof ov.initContext === 'string' ? ov.initContext.trim().slice(0, 2000) : base.initContext,
|
|
74
|
-
};
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
function sessionsDir(stateDir) {
|
|
78
|
-
const dir = join(stateDir, 'sessions');
|
|
79
|
-
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
80
|
-
return dir;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
export function safeSessionId(id) {
|
|
84
|
-
if (typeof id !== 'string' || !/^[a-zA-Z0-9_-]{4,80}$/.test(id)) return null;
|
|
85
|
-
return id;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
function parseTimestampMs(isoOrMs) {
|
|
89
|
-
if (typeof isoOrMs === 'number' && Number.isFinite(isoOrMs)) return isoOrMs;
|
|
90
|
-
if (typeof isoOrMs === 'string' && isoOrMs) {
|
|
91
|
-
const t = Date.parse(isoOrMs);
|
|
92
|
-
if (Number.isFinite(t)) return t;
|
|
93
|
-
}
|
|
94
|
-
return Date.now();
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
export function loadSessionRecord(stateDir, id) {
|
|
98
|
-
const clean = safeSessionId(id);
|
|
99
|
-
if (!stateDir || !clean) return null;
|
|
100
|
-
const path = join(sessionsDir(stateDir), clean + '.json');
|
|
101
|
-
if (!existsSync(path)) return null;
|
|
102
|
-
try {
|
|
103
|
-
const data = JSON.parse(readFileSync(path, 'utf8'));
|
|
104
|
-
if (!data || typeof data !== 'object') return null;
|
|
105
|
-
return {
|
|
106
|
-
...data,
|
|
107
|
-
id: data.id || clean,
|
|
108
|
-
persona: data.persona || 'architect',
|
|
109
|
-
pal: data.pal || paletteForPersona(data.persona || 'architect'),
|
|
110
|
-
mode: data.mode || 'design',
|
|
111
|
-
execMode: data.execMode === 'plan' ? 'plan' : 'act',
|
|
112
|
-
archived: Boolean(data.archived),
|
|
113
|
-
lastActiveAt: parseTimestampMs(data.lastActiveAt || data.updatedAt),
|
|
114
|
-
};
|
|
115
|
-
} catch {
|
|
116
|
-
return null;
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
export function saveSessionRecord(stateDir, record) {
|
|
121
|
-
const clean = safeSessionId(record?.id);
|
|
122
|
-
if (!stateDir || !clean) return null;
|
|
123
|
-
const existing = loadSessionRecord(stateDir, clean);
|
|
124
|
-
const nowIso = new Date().toISOString();
|
|
125
|
-
const touchActivity = record.touchActivity !== false;
|
|
126
|
-
const lastActiveAt = touchActivity
|
|
127
|
-
? (typeof record.lastActiveAt === 'number' ? record.lastActiveAt : Date.now())
|
|
128
|
-
: (existing?.lastActiveAt || Date.now());
|
|
129
|
-
const persona = record.persona || existing?.persona || 'architect';
|
|
130
|
-
|
|
131
|
-
const payload = {
|
|
132
|
-
id: clean,
|
|
133
|
-
title: String(record.title || existing?.title || '新会话').slice(0, 60),
|
|
134
|
-
persona,
|
|
135
|
-
pal: record.pal || existing?.pal || paletteForPersona(persona),
|
|
136
|
-
engine: (record.engine || existing?.engine) === 'acp' ? 'acp' : 'builtin',
|
|
137
|
-
mode: record.mode || existing?.mode || 'design',
|
|
138
|
-
execMode: (record.execMode || existing?.execMode) === 'plan' ? 'plan' : 'act',
|
|
139
|
-
archived: record.archived !== undefined ? Boolean(record.archived) : Boolean(existing?.archived),
|
|
140
|
-
archivedAt: record.archived ? (record.archivedAt || existing?.archivedAt || nowIso) : null,
|
|
141
|
-
createdAt: existing?.createdAt || record.createdAt || nowIso,
|
|
142
|
-
updatedAt: nowIso,
|
|
143
|
-
lastActiveAt,
|
|
144
|
-
liveStatus: record.liveStatus !== undefined ? String(record.liveStatus || '').slice(0, 120) : (existing?.liveStatus || ''),
|
|
145
|
-
todos: Array.isArray(record.todos) ? record.todos.slice(0, 16) : (Array.isArray(existing?.todos) ? existing.todos : []),
|
|
146
|
-
calledBy: record.calledBy !== undefined ? record.calledBy : (existing?.calledBy || null),
|
|
147
|
-
peerHopCount: typeof record.peerHopCount === 'number' ? record.peerHopCount : (existing?.peerHopCount || 0),
|
|
148
|
-
canvasBaseline: record.canvasBaseline !== undefined ? record.canvasBaseline : (existing?.canvasBaseline || null),
|
|
149
|
-
checkpoints: Array.isArray(record.checkpoints) ? record.checkpoints.slice(-6) : (Array.isArray(existing?.checkpoints) ? existing.checkpoints.slice(-6) : []),
|
|
150
|
-
messages: Array.isArray(record.messages) ? record.messages.slice(-60) : (Array.isArray(existing?.messages) ? existing.messages : []),
|
|
151
|
-
uiMessages: Array.isArray(record.uiMessages) ? record.uiMessages.slice(-80) : (Array.isArray(existing?.uiMessages) ? existing.uiMessages : []),
|
|
152
|
-
pendingQuestion: record.pendingQuestion !== undefined ? record.pendingQuestion : (existing?.pendingQuestion || null),
|
|
153
|
-
pendingCommand: record.pendingCommand !== undefined ? record.pendingCommand : (existing?.pendingCommand || null),
|
|
154
|
-
};
|
|
155
|
-
try {
|
|
156
|
-
writeFileSync(join(sessionsDir(stateDir), clean + '.json'), JSON.stringify(payload, null, 2) + '\n');
|
|
157
|
-
} catch {}
|
|
158
|
-
return payload;
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
export function archiveSessionRecord(stateDir, id, archived = true) {
|
|
162
|
-
const existing = loadSessionRecord(stateDir, id);
|
|
163
|
-
if (!existing) return null;
|
|
164
|
-
return saveSessionRecord(stateDir, {
|
|
165
|
-
...existing,
|
|
166
|
-
archived: Boolean(archived),
|
|
167
|
-
archivedAt: archived ? new Date().toISOString() : null,
|
|
168
|
-
touchActivity: !archived,
|
|
169
|
-
lastActiveAt: archived ? existing.lastActiveAt : Date.now(),
|
|
170
|
-
});
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
export function listSessionRecords(stateDir, limitOrOptions = 20) {
|
|
174
|
-
if (!stateDir) return [];
|
|
175
|
-
const dir = join(stateDir, 'sessions');
|
|
176
|
-
if (!existsSync(dir) || !lstatSync(dir).isDirectory()) return [];
|
|
177
|
-
|
|
178
|
-
const opts = typeof limitOrOptions === 'number'
|
|
179
|
-
? { limit: limitOrOptions, includeArchived: false, autoArchiveHours: 24, runningIds: new Set(), now: Date.now() }
|
|
180
|
-
: {
|
|
181
|
-
limit: Number(limitOrOptions?.limit) || 40,
|
|
182
|
-
includeArchived: Boolean(limitOrOptions?.includeArchived),
|
|
183
|
-
autoArchiveHours: limitOrOptions?.autoArchiveHours !== undefined ? Number(limitOrOptions.autoArchiveHours) : 24,
|
|
184
|
-
runningIds: limitOrOptions?.runningIds instanceof Set ? limitOrOptions.runningIds : new Set(),
|
|
185
|
-
now: Number(limitOrOptions?.now) || Date.now(),
|
|
186
|
-
};
|
|
187
|
-
|
|
188
|
-
const ttlMs = opts.autoArchiveHours > 0 ? opts.autoArchiveHours * 3600_000 : 0;
|
|
189
|
-
const items = [];
|
|
190
|
-
|
|
191
|
-
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
192
|
-
if (!entry.isFile() || !entry.name.endsWith('.json')) continue;
|
|
193
|
-
const full = join(dir, entry.name);
|
|
194
|
-
try {
|
|
195
|
-
const data = JSON.parse(readFileSync(full, 'utf8'));
|
|
196
|
-
if (!data || !data.id) continue;
|
|
197
|
-
const isRunning = opts.runningIds.has(data.id);
|
|
198
|
-
const lastActiveAt = parseTimestampMs(data.lastActiveAt || data.updatedAt);
|
|
199
|
-
let archived = Boolean(data.archived);
|
|
200
|
-
|
|
201
|
-
// 空闲超期自动归档(默认 24 小时,正在运行或待用户拍板的会话不自动归档)
|
|
202
|
-
if (!archived && !isRunning && !data.pendingQuestion && !data.pendingCommand && ttlMs > 0 && (opts.now - lastActiveAt) >= ttlMs) {
|
|
203
|
-
archived = true;
|
|
204
|
-
data.archived = true;
|
|
205
|
-
data.archivedAt = new Date(opts.now).toISOString();
|
|
206
|
-
try { writeFileSync(full, JSON.stringify(data, null, 2) + '\n'); } catch {}
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
if (archived && !opts.includeArchived) continue;
|
|
210
|
-
|
|
211
|
-
const idleMs = Math.max(0, opts.now - lastActiveAt);
|
|
212
|
-
const active = !archived && (isRunning || idleMs < 30_000);
|
|
213
|
-
items.push({
|
|
214
|
-
id: data.id,
|
|
215
|
-
title: data.title || '未命名会话',
|
|
216
|
-
persona: data.persona || 'architect',
|
|
217
|
-
pal: data.pal || paletteForPersona(data.persona || 'architect'),
|
|
218
|
-
engine: data.engine === 'acp' ? 'acp' : 'builtin',
|
|
219
|
-
mode: data.mode || 'design',
|
|
220
|
-
execMode: data.execMode === 'plan' ? 'plan' : 'act',
|
|
221
|
-
archived,
|
|
222
|
-
archivedAt: data.archivedAt || null,
|
|
223
|
-
updatedAt: data.updatedAt || '',
|
|
224
|
-
lastActiveAt,
|
|
225
|
-
idleSecs: Math.floor(idleMs / 1000),
|
|
226
|
-
active,
|
|
227
|
-
running: isRunning,
|
|
228
|
-
liveStatus: data.liveStatus || '',
|
|
229
|
-
todos: Array.isArray(data.todos) ? data.todos : [],
|
|
230
|
-
calledBy: data.calledBy && (opts.now - (data.calledBy.at || 0) < 8_000) ? data.calledBy : null,
|
|
231
|
-
hasPendingQuestion: Boolean(data.pendingQuestion),
|
|
232
|
-
pendingCommand: data.pendingCommand || null,
|
|
233
|
-
messageCount: Array.isArray(data.uiMessages) ? data.uiMessages.length : 0,
|
|
234
|
-
});
|
|
235
|
-
} catch {}
|
|
236
|
-
}
|
|
237
|
-
|
|
238
|
-
// 严格按【未归档 -> 30s 内活跃置顶 -> 最近活跃时间倒序】排列
|
|
239
|
-
return items
|
|
240
|
-
.sort((a, b) => {
|
|
241
|
-
if (a.archived !== b.archived) return a.archived ? 1 : -1;
|
|
242
|
-
if (a.active !== b.active) return a.active ? -1 : 1;
|
|
243
|
-
if (b.lastActiveAt !== a.lastActiveAt) return b.lastActiveAt - a.lastActiveAt;
|
|
244
|
-
return String(b.updatedAt).localeCompare(String(a.updatedAt));
|
|
245
|
-
})
|
|
246
|
-
.slice(0, opts.limit);
|
|
247
|
-
}
|
|
248
|
-
|
|
249
|
-
export function deleteSessionRecord(stateDir, id) {
|
|
250
|
-
const clean = safeSessionId(id);
|
|
251
|
-
if (!stateDir || !clean) return false;
|
|
252
|
-
const path = join(sessionsDir(stateDir), clean + '.json');
|
|
253
|
-
if (!existsSync(path)) return false;
|
|
254
|
-
try { unlinkSync(path); return true; } catch { return false; }
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
/**
|
|
258
|
-
* 将消息序列按原子交互块分组,严禁从 assistant(tool_calls) 与后续 tool(tool_call_id) 中间切断!
|
|
259
|
-
*/
|
|
260
|
-
function groupAtomicMessageBlocks(messages) {
|
|
261
|
-
const blocks = [];
|
|
262
|
-
let i = 0;
|
|
263
|
-
while (i < messages.length) {
|
|
264
|
-
const msg = messages[i];
|
|
265
|
-
if (msg?.role === 'assistant' && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
|
|
266
|
-
const expectedIds = new Set(msg.tool_calls.map(tc => tc?.id).filter(Boolean));
|
|
267
|
-
const group = [msg];
|
|
268
|
-
let j = i + 1;
|
|
269
|
-
while (j < messages.length && messages[j]?.role === 'tool') {
|
|
270
|
-
group.push(messages[j]);
|
|
271
|
-
expectedIds.delete(messages[j].tool_call_id);
|
|
272
|
-
j++;
|
|
273
|
-
}
|
|
274
|
-
blocks.push(group);
|
|
275
|
-
i = j;
|
|
276
|
-
} else if (msg?.role === 'tool') {
|
|
277
|
-
// 兜底丢弃孤立的游离 tool 结果,防止上游协议报 400
|
|
278
|
-
i += 1;
|
|
279
|
-
} else {
|
|
280
|
-
blocks.push([msg]);
|
|
281
|
-
i += 1;
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
return blocks;
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
/**
|
|
288
|
-
* 原子级上下文窗口压缩:支持自定义触发百分比阈值与压缩提示词摘要指引,绝不撕裂 tool_call / tool_result 配对。
|
|
289
|
-
*/
|
|
290
|
-
export function compactMessages(messages, maxCharsOrOpts = 36000) {
|
|
291
|
-
if (!Array.isArray(messages) || !messages.length) return [];
|
|
292
|
-
const opts = typeof maxCharsOrOpts === 'number'
|
|
293
|
-
? { maxChars: maxCharsOrOpts, thresholdPct: 100, compactPrompt: '' }
|
|
294
|
-
: {
|
|
295
|
-
maxChars: Number(maxCharsOrOpts?.maxChars) || 48000,
|
|
296
|
-
thresholdPct: Math.min(95, Math.max(40, Number(maxCharsOrOpts?.thresholdPct) || 75)),
|
|
297
|
-
compactPrompt: String(maxCharsOrOpts?.compactPrompt || '').trim(),
|
|
298
|
-
};
|
|
299
|
-
|
|
300
|
-
const budgetChars = Math.floor(opts.maxChars * (opts.thresholdPct / 100));
|
|
301
|
-
const blocks = groupAtomicMessageBlocks(messages);
|
|
302
|
-
const flatClean = blocks.flat();
|
|
303
|
-
const sizeOf = list => list.reduce((sum, m) => sum + JSON.stringify(m).length, 0);
|
|
304
|
-
if (sizeOf(flatClean) <= budgetChars || blocks.length <= 3) return flatClean;
|
|
305
|
-
|
|
306
|
-
// 从尾部向前保留完整的原子块,确保预算充裕且配对 100% 闭合
|
|
307
|
-
const tailBlocks = [];
|
|
308
|
-
let tailChars = 0;
|
|
309
|
-
const maxTailChars = Math.floor(budgetChars * 0.65);
|
|
310
|
-
for (let idx = blocks.length - 1; idx >= 1; idx--) {
|
|
311
|
-
const bSize = sizeOf(blocks[idx]);
|
|
312
|
-
if (tailBlocks.length >= 2 && tailChars + bSize > maxTailChars) break;
|
|
313
|
-
tailBlocks.unshift(blocks[idx]);
|
|
314
|
-
tailChars += bSize;
|
|
315
|
-
if (tailBlocks.length >= 8) break;
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
const headMessages = blocks.slice(0, blocks.length - tailBlocks.length).flat();
|
|
319
|
-
const digestLines = [];
|
|
320
|
-
for (const m of headMessages) {
|
|
321
|
-
if ((m?.role === 'user' || m?.role === 'assistant') && typeof m.content === 'string' && m.content.trim()) {
|
|
322
|
-
const clean = m.content.replace(/^【前序对话压缩摘要】[\s\S]*?\n\n/, '').trim();
|
|
323
|
-
if (clean) digestLines.push(`${m.role === 'user' ? '用户' : 'Agent'}:${clean.slice(0, 160)}`);
|
|
324
|
-
} else if (m?.role === 'assistant' && Array.isArray(m.tool_calls) && m.tool_calls.length) {
|
|
325
|
-
const names = m.tool_calls.map(tc => tc?.function?.name).filter(Boolean).join(', ');
|
|
326
|
-
if (names) digestLines.push(`Agent 调用工具:${names}`);
|
|
327
|
-
}
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
const guide = opts.compactPrompt ? `(压缩准则:${opts.compactPrompt.slice(0, 240)})\n` : '';
|
|
331
|
-
const digest = digestLines.slice(-12).join('\n');
|
|
332
|
-
return [
|
|
333
|
-
...(digest ? [{ role: 'user', content: `【前序对话压缩摘要】\n${guide}${digest}` }] : []),
|
|
334
|
-
...tailBlocks.flat(),
|
|
335
|
-
];
|
|
336
|
-
}
|
package/src/agent/skills.js
DELETED
|
@@ -1,190 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Clado 原生 Agent 技能体系(Skills):
|
|
3
|
-
* - 标准 SKILL.md(YAML Frontmatter + Markdown 正文),兼容主流 Agent 技能规范;
|
|
4
|
-
* - 三层发现优先级:工作区(.clado/skills/<slug>/SKILL.md) > 全局(~/.clado/skills/<slug>/SKILL.md) > 已安装插件(<pluginDir>/skills/<slug>/SKILL.md);
|
|
5
|
-
* - 渐进式披露:系统提示词仅注入紧凑目录(name + description),Agent 按需调用 load_skill 工具拉取完整指南。
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
9
|
-
import { join } from 'node:path';
|
|
10
|
-
import YAML from 'yaml';
|
|
11
|
-
import { userTemplatePaths } from '../skill/templates.js';
|
|
12
|
-
|
|
13
|
-
const SLUG_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;
|
|
14
|
-
|
|
15
|
-
function globalSkillsDir() {
|
|
16
|
-
return join(userTemplatePaths().state, 'skills');
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
function workspaceSkillsDir(workspace) {
|
|
20
|
-
return workspace ? join(workspace, '.clado', 'skills') : '';
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export function parseSkillMarkdown(raw, fallbackSlug = '') {
|
|
24
|
-
const text = String(raw || '').replace(/\r\n/g, '\n');
|
|
25
|
-
let meta = {};
|
|
26
|
-
let body = text.trim();
|
|
27
|
-
|
|
28
|
-
const fm = text.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
|
|
29
|
-
if (fm) {
|
|
30
|
-
try {
|
|
31
|
-
const parsed = YAML.parse(fm[1]);
|
|
32
|
-
if (parsed && typeof parsed === 'object') meta = parsed;
|
|
33
|
-
} catch {}
|
|
34
|
-
body = fm[2].trim();
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
const name = typeof meta.name === 'string' && meta.name.trim() ? meta.name.trim() : fallbackSlug;
|
|
38
|
-
const description = typeof meta.description === 'string' && meta.description.trim()
|
|
39
|
-
? meta.description.trim()
|
|
40
|
-
: (body.split('\n').find(line => line.trim() && !line.startsWith('#')) || '自定义 Agent 技能').slice(0, 140);
|
|
41
|
-
const tags = Array.isArray(meta.tags) ? meta.tags.map(t => String(t).trim()).filter(Boolean) : [];
|
|
42
|
-
return { name, description, tags, body };
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export function serializeSkillMarkdown({ name, description, tags = [], body = '' }) {
|
|
46
|
-
const fm = { name: String(name || '').trim(), description: String(description || '').trim() };
|
|
47
|
-
if (Array.isArray(tags) && tags.length) fm.tags = tags;
|
|
48
|
-
return `---\n${YAML.stringify(fm).trim()}\n---\n\n${String(body || '').trim()}\n`;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
function scanSkillsInDir(dir, scope, pluginId = '') {
|
|
52
|
-
if (!dir || !existsSync(dir)) return [];
|
|
53
|
-
const items = [];
|
|
54
|
-
let entries = [];
|
|
55
|
-
try {
|
|
56
|
-
entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
|
|
57
|
-
} catch {
|
|
58
|
-
return [];
|
|
59
|
-
}
|
|
60
|
-
for (const entry of entries) {
|
|
61
|
-
if (entry.name.startsWith('.')) continue;
|
|
62
|
-
const full = join(dir, entry.name);
|
|
63
|
-
try {
|
|
64
|
-
const st = lstatSync(full);
|
|
65
|
-
if (st.isSymbolicLink()) continue;
|
|
66
|
-
if (st.isDirectory()) {
|
|
67
|
-
const skillFile = join(full, 'SKILL.md');
|
|
68
|
-
if (!existsSync(skillFile) || !lstatSync(skillFile).isFile()) continue;
|
|
69
|
-
const parsed = parseSkillMarkdown(readFileSync(skillFile, 'utf8'), entry.name);
|
|
70
|
-
items.push({
|
|
71
|
-
slug: entry.name,
|
|
72
|
-
name: parsed.name || entry.name,
|
|
73
|
-
description: parsed.description,
|
|
74
|
-
tags: parsed.tags,
|
|
75
|
-
body: parsed.body,
|
|
76
|
-
scope,
|
|
77
|
-
...(pluginId ? { pluginId } : {}),
|
|
78
|
-
path: skillFile,
|
|
79
|
-
});
|
|
80
|
-
} else if (st.isFile() && /\.md$/i.test(entry.name)) {
|
|
81
|
-
const slug = entry.name.replace(/\.md$/i, '');
|
|
82
|
-
const parsed = parseSkillMarkdown(readFileSync(full, 'utf8'), slug);
|
|
83
|
-
items.push({
|
|
84
|
-
slug,
|
|
85
|
-
name: parsed.name || slug,
|
|
86
|
-
description: parsed.description,
|
|
87
|
-
tags: parsed.tags,
|
|
88
|
-
body: parsed.body,
|
|
89
|
-
scope,
|
|
90
|
-
...(pluginId ? { pluginId } : {}),
|
|
91
|
-
path: full,
|
|
92
|
-
});
|
|
93
|
-
}
|
|
94
|
-
} catch {}
|
|
95
|
-
}
|
|
96
|
-
return items;
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
export function listSkills(workspace, { pluginDirs = [], includeBody = false } = {}) {
|
|
100
|
-
const merged = new Map();
|
|
101
|
-
|
|
102
|
-
for (const p of pluginDirs || []) {
|
|
103
|
-
if (!p?.dir) continue;
|
|
104
|
-
for (const item of scanSkillsInDir(join(p.dir, 'skills'), 'plugin', p.id || '')) {
|
|
105
|
-
merged.set(item.slug, item);
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
for (const item of scanSkillsInDir(globalSkillsDir(), 'global')) {
|
|
109
|
-
merged.set(item.slug, item);
|
|
110
|
-
}
|
|
111
|
-
for (const item of scanSkillsInDir(workspaceSkillsDir(workspace), 'workspace')) {
|
|
112
|
-
merged.set(item.slug, item);
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
return [...merged.values()].map(item => (
|
|
116
|
-
includeBody
|
|
117
|
-
? item
|
|
118
|
-
: {
|
|
119
|
-
slug: item.slug,
|
|
120
|
-
name: item.name,
|
|
121
|
-
description: item.description,
|
|
122
|
-
tags: item.tags,
|
|
123
|
-
scope: item.scope,
|
|
124
|
-
...(item.pluginId ? { pluginId: item.pluginId } : {}),
|
|
125
|
-
}
|
|
126
|
-
));
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
export function readSkill(workspace, nameOrSlug, { pluginDirs = [] } = {}) {
|
|
130
|
-
const needle = String(nameOrSlug || '').trim().toLowerCase();
|
|
131
|
-
if (!needle) return null;
|
|
132
|
-
const all = listSkills(workspace, { pluginDirs, includeBody: true });
|
|
133
|
-
return all.find(s => s.slug.toLowerCase() === needle || s.name.toLowerCase() === needle) || null;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
export function saveSkill(workspace, { slug, name, description, tags = [], body = '', scope = 'workspace' } = {}) {
|
|
137
|
-
const cleanSlug = String(slug || name || '')
|
|
138
|
-
.trim()
|
|
139
|
-
.toLowerCase()
|
|
140
|
-
.replace(/[^a-z0-9_-]+/g, '-')
|
|
141
|
-
.replace(/^-+|-+$/g, '')
|
|
142
|
-
.slice(0, 63);
|
|
143
|
-
if (!SLUG_RE.test(cleanSlug)) {
|
|
144
|
-
throw new Error('技能标识(slug)需使用英文字母、数字、连字符或下划线,如 api-contract。');
|
|
145
|
-
}
|
|
146
|
-
const cleanName = String(name || cleanSlug).trim().slice(0, 80);
|
|
147
|
-
const cleanDesc = String(description || '').trim().slice(0, 260) || '自定义 Agent 技能';
|
|
148
|
-
const cleanBody = String(body || '').trim();
|
|
149
|
-
if (!cleanBody) throw new Error('技能正文内容不能为空。');
|
|
150
|
-
|
|
151
|
-
const baseDir = scope === 'global' || !workspace ? globalSkillsDir() : workspaceSkillsDir(workspace);
|
|
152
|
-
const skillDir = join(baseDir, cleanSlug);
|
|
153
|
-
mkdirSync(skillDir, { recursive: true, mode: 0o700 });
|
|
154
|
-
const filePath = join(skillDir, 'SKILL.md');
|
|
155
|
-
writeFileSync(filePath, serializeSkillMarkdown({ name: cleanName, description: cleanDesc, tags, body: cleanBody }), 'utf8');
|
|
156
|
-
return {
|
|
157
|
-
slug: cleanSlug,
|
|
158
|
-
name: cleanName,
|
|
159
|
-
description: cleanDesc,
|
|
160
|
-
tags,
|
|
161
|
-
body: cleanBody,
|
|
162
|
-
scope: scope === 'global' || !workspace ? 'global' : 'workspace',
|
|
163
|
-
};
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
export function deleteSkill(workspace, { slug, scope = 'workspace' } = {}) {
|
|
167
|
-
const cleanSlug = String(slug || '').trim();
|
|
168
|
-
if (!SLUG_RE.test(cleanSlug)) return false;
|
|
169
|
-
const baseDir = scope === 'global' || !workspace ? globalSkillsDir() : workspaceSkillsDir(workspace);
|
|
170
|
-
const targetDir = join(baseDir, cleanSlug);
|
|
171
|
-
const targetFile = join(baseDir, cleanSlug + '.md');
|
|
172
|
-
if (existsSync(targetDir)) {
|
|
173
|
-
rmSync(targetDir, { recursive: true, force: true });
|
|
174
|
-
return true;
|
|
175
|
-
}
|
|
176
|
-
if (existsSync(targetFile)) {
|
|
177
|
-
rmSync(targetFile, { force: true });
|
|
178
|
-
return true;
|
|
179
|
-
}
|
|
180
|
-
return false;
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
export function formatSkillsCatalog(skills = []) {
|
|
184
|
-
if (!Array.isArray(skills) || !skills.length) return '';
|
|
185
|
-
const lines = [
|
|
186
|
-
'【已挂载技能库(按需调用 load_skill 工具读取完整指南)】',
|
|
187
|
-
...skills.slice(0, 40).map(s => `- ${s.slug} (${s.name}): ${s.description}`),
|
|
188
|
-
];
|
|
189
|
-
return lines.join('\n');
|
|
190
|
-
}
|