cladogram 0.5.5-beta.8 → 0.5.5-beta.9
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/docs/release.md +7 -0
- package/package.json +1 -1
- package/plugins/agent/index.js +615 -41
- package/plugins/agent/style.css +100 -0
- package/plugins/directory/index.js +25 -3
- package/plugins/directory/style.css +47 -0
- package/src/agent/commands.js +204 -0
- package/src/agent/context.js +18 -3
- package/src/agent/mcp-client.js +308 -0
- package/src/agent/runtime.js +50 -2
- package/src/agent/skills.js +190 -0
- package/src/server/agent.js +177 -8
- package/src/server/assets/library.js +46 -0
- package/src/server/plugins.js +61 -9
- package/src/server/workspace-hub.js +28 -1
- package/src/server/workspace.js +28 -0
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Clado 原生 Agent 外部 MCP Client 运行时与配置管理:
|
|
3
|
+
* - 支持全球配置(~/.clado/mcp.json)、工作区配置(.clado/mcp.json)与插件声明(pluginMcp)三层合并;
|
|
4
|
+
* - 兼容标准 mcpServers JSON 格式(Claude Code / Cursor 直接粘贴即用);
|
|
5
|
+
* - 支持 Stdio(本地命令)与 Streamable HTTP(远程/本机 HTTP MCP)双传输协议;
|
|
6
|
+
* - 提供连通性测试、工具发现缓存、与原生 Agent 工具调用桥接(mcp__<server>__<tool>)。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
10
|
+
import { dirname, join } from 'node:path';
|
|
11
|
+
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
12
|
+
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
13
|
+
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
14
|
+
import { userTemplatePaths } from '../skill/templates.js';
|
|
15
|
+
import { VERSION } from '../util/version.js';
|
|
16
|
+
|
|
17
|
+
const NAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/;
|
|
18
|
+
const DEFAULT_TIMEOUT_MS = 12000;
|
|
19
|
+
|
|
20
|
+
function globalMcpPath() {
|
|
21
|
+
return join(userTemplatePaths().state, 'mcp.json');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function workspaceMcpPath(workspace) {
|
|
25
|
+
return workspace ? join(workspace, '.clado', 'mcp.json') : '';
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function readMcpFile(filePath) {
|
|
29
|
+
if (!filePath || !existsSync(filePath)) return {};
|
|
30
|
+
try {
|
|
31
|
+
const raw = JSON.parse(readFileSync(filePath, 'utf8'));
|
|
32
|
+
if (!raw || typeof raw !== 'object') return {};
|
|
33
|
+
const servers = raw.mcpServers && typeof raw.mcpServers === 'object' ? raw.mcpServers : raw;
|
|
34
|
+
return servers && typeof servers === 'object' && !Array.isArray(servers) ? servers : {};
|
|
35
|
+
} catch {
|
|
36
|
+
return {};
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function writeMcpFile(filePath, servers) {
|
|
41
|
+
const dir = dirname(filePath);
|
|
42
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
43
|
+
writeFileSync(filePath, JSON.stringify({ mcpServers: servers }, null, 2) + '\n', { mode: 0o600 });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function normalizeServerConfig(raw = {}) {
|
|
47
|
+
if (!raw || typeof raw !== 'object') throw new Error('MCP 服务配置必须是 JSON 对象。');
|
|
48
|
+
const url = typeof raw.url === 'string' ? raw.url.trim() : '';
|
|
49
|
+
const command = typeof raw.command === 'string' ? raw.command.trim() : '';
|
|
50
|
+
const type = raw.type === 'http' || raw.type === 'streamable-http' || (!command && url) ? 'http' : 'stdio';
|
|
51
|
+
const enabled = raw.enabled !== false;
|
|
52
|
+
|
|
53
|
+
if (type === 'http') {
|
|
54
|
+
if (!/^https?:\/\//i.test(url)) throw new Error('HTTP MCP 服务需要有效的 http(s):// 地址。');
|
|
55
|
+
const headers = raw.headers && typeof raw.headers === 'object' && !Array.isArray(raw.headers)
|
|
56
|
+
? Object.fromEntries(Object.entries(raw.headers).map(([k, v]) => [String(k), String(v)]))
|
|
57
|
+
: {};
|
|
58
|
+
return { type: 'http', url, headers, enabled };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (!command) throw new Error('Stdio MCP 服务需要填写启动命令(command)。');
|
|
62
|
+
const args = Array.isArray(raw.args)
|
|
63
|
+
? raw.args.map(a => String(a))
|
|
64
|
+
: (typeof raw.args === 'string' && raw.args.trim() ? raw.args.trim().split(/\s+/) : []);
|
|
65
|
+
const env = raw.env && typeof raw.env === 'object' && !Array.isArray(raw.env)
|
|
66
|
+
? Object.fromEntries(Object.entries(raw.env).map(([k, v]) => [String(k), String(v)]))
|
|
67
|
+
: {};
|
|
68
|
+
const cwd = typeof raw.cwd === 'string' && raw.cwd.trim() ? raw.cwd.trim() : undefined;
|
|
69
|
+
return { type: 'stdio', command, args, env, ...(cwd ? { cwd } : {}), enabled };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function sanitizeServerForUi(name, cfg, scope, pluginId = '') {
|
|
73
|
+
const envKeys = cfg.env ? Object.keys(cfg.env) : [];
|
|
74
|
+
const headerKeys = cfg.headers ? Object.keys(cfg.headers) : [];
|
|
75
|
+
return {
|
|
76
|
+
name,
|
|
77
|
+
scope,
|
|
78
|
+
...(pluginId ? { pluginId } : {}),
|
|
79
|
+
type: cfg.type || (cfg.url ? 'http' : 'stdio'),
|
|
80
|
+
enabled: cfg.enabled !== false,
|
|
81
|
+
command: cfg.command || '',
|
|
82
|
+
args: Array.isArray(cfg.args) ? cfg.args : [],
|
|
83
|
+
url: cfg.url || '',
|
|
84
|
+
envKeys,
|
|
85
|
+
headerKeys,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function listMcpServers(workspace, { pluginMcp = [], includeSecrets = false } = {}) {
|
|
90
|
+
const merged = new Map();
|
|
91
|
+
|
|
92
|
+
for (const item of pluginMcp || []) {
|
|
93
|
+
if (!item?.name || !NAME_RE.test(item.name)) continue;
|
|
94
|
+
try {
|
|
95
|
+
const cfg = normalizeServerConfig(item);
|
|
96
|
+
merged.set(item.name, { name: item.name, scope: 'plugin', pluginId: item.pluginId || '', config: cfg });
|
|
97
|
+
} catch {}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const globalMap = readMcpFile(globalMcpPath());
|
|
101
|
+
for (const [name, raw] of Object.entries(globalMap)) {
|
|
102
|
+
if (!NAME_RE.test(name)) continue;
|
|
103
|
+
try {
|
|
104
|
+
merged.set(name, { name, scope: 'global', config: normalizeServerConfig(raw) });
|
|
105
|
+
} catch {}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const wsMap = readMcpFile(workspaceMcpPath(workspace));
|
|
109
|
+
for (const [name, raw] of Object.entries(wsMap)) {
|
|
110
|
+
if (!NAME_RE.test(name)) continue;
|
|
111
|
+
try {
|
|
112
|
+
merged.set(name, { name, scope: 'workspace', config: normalizeServerConfig(raw) });
|
|
113
|
+
} catch {}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
return [...merged.values()].map(entry => (
|
|
117
|
+
includeSecrets
|
|
118
|
+
? entry
|
|
119
|
+
: sanitizeServerForUi(entry.name, entry.config, entry.scope, entry.pluginId)
|
|
120
|
+
));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function saveMcpServer(workspace, { name, scope = 'workspace', config } = {}) {
|
|
124
|
+
const cleanName = String(name || '').trim();
|
|
125
|
+
if (!NAME_RE.test(cleanName)) {
|
|
126
|
+
throw new Error('MCP 服务名称仅支持字母、数字、下划线和连字符(1-48 字符)。');
|
|
127
|
+
}
|
|
128
|
+
const normalized = normalizeServerConfig(config);
|
|
129
|
+
const filePath = scope === 'global' || !workspace ? globalMcpPath() : workspaceMcpPath(workspace);
|
|
130
|
+
const current = readMcpFile(filePath);
|
|
131
|
+
current[cleanName] = normalized;
|
|
132
|
+
writeMcpFile(filePath, current);
|
|
133
|
+
return sanitizeServerForUi(cleanName, normalized, scope === 'global' || !workspace ? 'global' : 'workspace');
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function toggleMcpServer(workspace, { name, scope = 'workspace', enabled = true } = {}) {
|
|
137
|
+
const cleanName = String(name || '').trim();
|
|
138
|
+
const filePath = scope === 'global' || !workspace ? globalMcpPath() : workspaceMcpPath(workspace);
|
|
139
|
+
const current = readMcpFile(filePath);
|
|
140
|
+
if (!current[cleanName]) throw new Error(`未找到 MCP 服务:${cleanName}`);
|
|
141
|
+
current[cleanName] = { ...current[cleanName], enabled: Boolean(enabled) };
|
|
142
|
+
writeMcpFile(filePath, current);
|
|
143
|
+
return sanitizeServerForUi(cleanName, normalizeServerConfig(current[cleanName]), scope === 'global' || !workspace ? 'global' : 'workspace');
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function deleteMcpServer(workspace, { name, scope = 'workspace' } = {}) {
|
|
147
|
+
const cleanName = String(name || '').trim();
|
|
148
|
+
const filePath = scope === 'global' || !workspace ? globalMcpPath() : workspaceMcpPath(workspace);
|
|
149
|
+
const current = readMcpFile(filePath);
|
|
150
|
+
if (!current[cleanName]) return false;
|
|
151
|
+
delete current[cleanName];
|
|
152
|
+
writeMcpFile(filePath, current);
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function importMcpJson(workspace, { scope = 'workspace', jsonText = '' } = {}) {
|
|
157
|
+
let parsed;
|
|
158
|
+
try {
|
|
159
|
+
parsed = typeof jsonText === 'string' ? JSON.parse(jsonText) : jsonText;
|
|
160
|
+
} catch {
|
|
161
|
+
throw new Error('粘贴的内容不是合法 JSON。');
|
|
162
|
+
}
|
|
163
|
+
const map = parsed?.mcpServers && typeof parsed.mcpServers === 'object' ? parsed.mcpServers : parsed;
|
|
164
|
+
if (!map || typeof map !== 'object' || Array.isArray(map)) {
|
|
165
|
+
throw new Error('JSON 需要包含 mcpServers 对象或直接为服务名称映射。');
|
|
166
|
+
}
|
|
167
|
+
const entries = Object.entries(map);
|
|
168
|
+
if (!entries.length) throw new Error('JSON 中没有可导入的 MCP 服务。');
|
|
169
|
+
|
|
170
|
+
const filePath = scope === 'global' || !workspace ? globalMcpPath() : workspaceMcpPath(workspace);
|
|
171
|
+
const current = readMcpFile(filePath);
|
|
172
|
+
const imported = [];
|
|
173
|
+
for (const [name, raw] of entries) {
|
|
174
|
+
if (!NAME_RE.test(name)) throw new Error(`服务名称无效:${name}`);
|
|
175
|
+
current[name] = normalizeServerConfig(raw);
|
|
176
|
+
imported.push(name);
|
|
177
|
+
}
|
|
178
|
+
writeMcpFile(filePath, current);
|
|
179
|
+
return imported;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function withMcpClient(serverConfig, workspace, fn, { timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
|
|
183
|
+
const client = new Client({ name: 'clado-native-agent', version: VERSION });
|
|
184
|
+
let transport;
|
|
185
|
+
if (serverConfig.type === 'http') {
|
|
186
|
+
transport = new StreamableHTTPClientTransport(new URL(serverConfig.url), {
|
|
187
|
+
requestInit: serverConfig.headers && Object.keys(serverConfig.headers).length
|
|
188
|
+
? { headers: serverConfig.headers }
|
|
189
|
+
: undefined,
|
|
190
|
+
});
|
|
191
|
+
} else {
|
|
192
|
+
transport = new StdioClientTransport({
|
|
193
|
+
command: serverConfig.command,
|
|
194
|
+
args: serverConfig.args || [],
|
|
195
|
+
env: { ...process.env, ...(serverConfig.env || {}) },
|
|
196
|
+
cwd: serverConfig.cwd || workspace || process.cwd(),
|
|
197
|
+
stderr: 'pipe',
|
|
198
|
+
});
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
let timer;
|
|
202
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
203
|
+
timer = setTimeout(() => reject(new Error(`连接 MCP 服务超时(>${Math.round(timeoutMs / 1000)}s)`)), timeoutMs);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
try {
|
|
207
|
+
await Promise.race([client.connect(transport), timeoutPromise]);
|
|
208
|
+
return await Promise.race([fn(client), timeoutPromise]);
|
|
209
|
+
} finally {
|
|
210
|
+
clearTimeout(timer);
|
|
211
|
+
await client.close().catch(() => {});
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export async function testMcpServer(workspace, serverConfig, { timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
|
|
216
|
+
const started = Date.now();
|
|
217
|
+
try {
|
|
218
|
+
const normalized = normalizeServerConfig(serverConfig);
|
|
219
|
+
const tools = await withMcpClient(normalized, workspace, async client => {
|
|
220
|
+
const res = await client.listTools();
|
|
221
|
+
return Array.isArray(res?.tools) ? res.tools : [];
|
|
222
|
+
}, { timeoutMs });
|
|
223
|
+
return {
|
|
224
|
+
ok: true,
|
|
225
|
+
latencyMs: Date.now() - started,
|
|
226
|
+
toolCount: tools.length,
|
|
227
|
+
tools: tools.map(t => ({ name: t.name, description: t.description || '' })),
|
|
228
|
+
};
|
|
229
|
+
} catch (error) {
|
|
230
|
+
return {
|
|
231
|
+
ok: false,
|
|
232
|
+
latencyMs: Date.now() - started,
|
|
233
|
+
toolCount: 0,
|
|
234
|
+
tools: [],
|
|
235
|
+
error: error?.message || String(error),
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export function encodeMcpToolName(serverName, toolName) {
|
|
241
|
+
const safeTool = String(toolName || '').replace(/[^a-zA-Z0-9_-]/g, '_');
|
|
242
|
+
return `mcp__${serverName}__${safeTool}`;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export async function discoverExternalMcpTools(workspace, { pluginMcp = [], timeoutMs = 6000 } = {}) {
|
|
246
|
+
const servers = listMcpServers(workspace, { pluginMcp, includeSecrets: true }).filter(s => s.config.enabled !== false);
|
|
247
|
+
if (!servers.length) return { definitions: [], registry: new Map(), errors: [] };
|
|
248
|
+
|
|
249
|
+
const definitions = [];
|
|
250
|
+
const registry = new Map();
|
|
251
|
+
const errors = [];
|
|
252
|
+
|
|
253
|
+
await Promise.all(servers.map(async entry => {
|
|
254
|
+
try {
|
|
255
|
+
const tools = await withMcpClient(entry.config, workspace, async client => {
|
|
256
|
+
const res = await client.listTools();
|
|
257
|
+
return Array.isArray(res?.tools) ? res.tools : [];
|
|
258
|
+
}, { timeoutMs });
|
|
259
|
+
|
|
260
|
+
for (const tool of tools) {
|
|
261
|
+
const fnName = encodeMcpToolName(entry.name, tool.name);
|
|
262
|
+
registry.set(fnName, {
|
|
263
|
+
serverName: entry.name,
|
|
264
|
+
toolName: tool.name,
|
|
265
|
+
config: entry.config,
|
|
266
|
+
});
|
|
267
|
+
definitions.push({
|
|
268
|
+
type: 'function',
|
|
269
|
+
function: {
|
|
270
|
+
name: fnName,
|
|
271
|
+
description: `[MCP:${entry.name}] ${tool.description || tool.name}`,
|
|
272
|
+
parameters: tool.inputSchema && typeof tool.inputSchema === 'object'
|
|
273
|
+
? tool.inputSchema
|
|
274
|
+
: { type: 'object', properties: {} },
|
|
275
|
+
},
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
} catch (error) {
|
|
279
|
+
errors.push({ server: entry.name, error: error?.message || String(error) });
|
|
280
|
+
}
|
|
281
|
+
}));
|
|
282
|
+
|
|
283
|
+
return { definitions, registry, errors };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export async function callExternalMcpTool(entry, args = {}, workspace, { timeoutMs = 20000 } = {}) {
|
|
287
|
+
return withMcpClient(entry.config, workspace, async client => {
|
|
288
|
+
const result = await client.callTool({
|
|
289
|
+
name: entry.toolName,
|
|
290
|
+
arguments: args && typeof args === 'object' ? args : {},
|
|
291
|
+
});
|
|
292
|
+
const content = Array.isArray(result?.content) ? result.content : [];
|
|
293
|
+
const textParts = content
|
|
294
|
+
.map(part => {
|
|
295
|
+
if (part?.type === 'text') return part.text || '';
|
|
296
|
+
if (part?.type === 'resource' && part.resource?.text) return part.resource.text;
|
|
297
|
+
return JSON.stringify(part);
|
|
298
|
+
})
|
|
299
|
+
.filter(Boolean);
|
|
300
|
+
return {
|
|
301
|
+
ok: !result?.isError,
|
|
302
|
+
server: entry.serverName,
|
|
303
|
+
tool: entry.toolName,
|
|
304
|
+
text: textParts.join('\n') || (result?.structuredContent ? JSON.stringify(result.structuredContent) : ''),
|
|
305
|
+
...(result?.structuredContent ? { structuredContent: result.structuredContent } : {}),
|
|
306
|
+
};
|
|
307
|
+
}, { timeoutMs });
|
|
308
|
+
}
|
package/src/agent/runtime.js
CHANGED
|
@@ -18,6 +18,8 @@ import { createRunRecord, updateRunRecord } from './executors.js';
|
|
|
18
18
|
import { classifyShellCommand, executeWorkspaceCommand, probeGitDiff, probeRead, probeSearch, probeTree } from './probe.js';
|
|
19
19
|
import { streamModelTurn } from './providers/index.js';
|
|
20
20
|
import { resolvePersona } from './sessions.js';
|
|
21
|
+
import { callExternalMcpTool, discoverExternalMcpTools } from './mcp-client.js';
|
|
22
|
+
import { formatSkillsCatalog, listSkills, readSkill } from './skills.js';
|
|
21
23
|
|
|
22
24
|
const MAX_STEPS = 12;
|
|
23
25
|
|
|
@@ -120,6 +122,20 @@ function toolDefinitions({ enablePeers = false } = {}) {
|
|
|
120
122
|
},
|
|
121
123
|
},
|
|
122
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
|
+
},
|
|
123
139
|
{
|
|
124
140
|
type: 'function',
|
|
125
141
|
function: {
|
|
@@ -472,6 +488,11 @@ function humanizeToolStatus(name, args = {}) {
|
|
|
472
488
|
if (name === 'message_peer') return `正在呼叫「${args.target || ''}」…`;
|
|
473
489
|
if (name === 'canvas_objects_read') return args.id ? `正在读取组件 #${args.id}…` : '正在读取画布组件…';
|
|
474
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
|
+
}
|
|
475
496
|
if (name.startsWith('clado_')) {
|
|
476
497
|
const target = (Array.isArray(args.node) && args.node.at(-1)) || args.title || args.file || '画布';
|
|
477
498
|
return `正在编辑画布 · ${String(target).slice(0, 12)}…`;
|
|
@@ -488,6 +509,8 @@ export async function runVerticalAgent({
|
|
|
488
509
|
events = null,
|
|
489
510
|
config = {},
|
|
490
511
|
debugConfig = null,
|
|
512
|
+
pluginMeta = null,
|
|
513
|
+
preloadedSkill = '',
|
|
491
514
|
history = [],
|
|
492
515
|
canvasBaseline = null,
|
|
493
516
|
activePeerLocks = [],
|
|
@@ -507,9 +530,20 @@ export async function runVerticalAgent({
|
|
|
507
530
|
fetchImpl = fetch,
|
|
508
531
|
}) {
|
|
509
532
|
const effectiveDebug = debugConfig || (stateDir ? readAgentDebugConfig(stateDir).config : undefined);
|
|
510
|
-
const
|
|
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);
|
|
511
540
|
const isPlanOnly = execMode === 'plan';
|
|
512
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
|
+
|
|
513
547
|
const run = createRunRecord(stateDir, {
|
|
514
548
|
kind: 'builtin',
|
|
515
549
|
mode,
|
|
@@ -547,6 +581,8 @@ export async function runVerticalAgent({
|
|
|
547
581
|
? '【重要限制:当前处于「规划(只读)」模式】严禁修改画布文档或执行写命令;仅允许使用只读探针查证、拆解步骤(todo_write)或调用 ask_user 与用户对齐方案。'
|
|
548
582
|
: '',
|
|
549
583
|
MODE_PROMPTS[mode] || MODE_PROMPTS.general,
|
|
584
|
+
skillsCatalogText,
|
|
585
|
+
preloadedSkillObj ? `【本次命令预加载技能:${preloadedSkillObj.name}】\n${preloadedSkillObj.body}` : '',
|
|
550
586
|
].filter(Boolean).join('\n\n');
|
|
551
587
|
|
|
552
588
|
const isResume = Boolean(resumeToolResult || resumeCommandResult);
|
|
@@ -596,10 +632,22 @@ export async function runVerticalAgent({
|
|
|
596
632
|
conversation.push({ role: 'user', content: segmented.seg4UserContent });
|
|
597
633
|
}
|
|
598
634
|
|
|
599
|
-
const tools =
|
|
635
|
+
const tools = [
|
|
636
|
+
...toolDefinitions({ enablePeers: Boolean(peerCoordinator) }),
|
|
637
|
+
...externalMcp.definitions,
|
|
638
|
+
];
|
|
600
639
|
|
|
601
640
|
async function executeTool(name, rawArgs) {
|
|
602
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
|
+
}
|
|
603
651
|
if (name === 'todo_write') {
|
|
604
652
|
const list = Array.isArray(args.todos)
|
|
605
653
|
? args.todos.slice(0, 12).map(t => ({
|
|
@@ -0,0 +1,190 @@
|
|
|
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
|
+
}
|