cladogram 0.6.0-beta.5 → 0.6.0-beta.7
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 +18 -13
- package/docs/agent-context.md +3 -2
- package/docs/agent-reference.md +11 -0
- package/docs/release.md +28 -0
- package/package.json +1 -1
- package/plugins/agent/index.js +795 -39
- package/plugins/agent/style.css +142 -2
- package/skills/clado/SKILL.md +3 -1
- package/src/agent/automations.js +454 -0
- package/src/agent/clado-tools.js +160 -1
- package/src/agent/pi-bridge.js +771 -58
- package/src/html/canvas-live-diff.js +208 -91
- package/src/html/canvas-ui.css +0 -8
- package/src/html/runtime-api.js +6 -0
- package/src/server/agent.js +239 -9
- package/src/server/assets/library-canvas.js +4 -0
- package/src/server/assets/library.js +233 -6
- package/src/server/mcp.js +88 -20
- package/src/server/workspace.js +165 -3
- package/src/workspace/service.js +190 -8
package/src/server/mcp.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
1
2
|
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
3
|
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
3
4
|
import { z } from 'zod/v4';
|
|
@@ -11,6 +12,7 @@ const workspace = z.string().min(1).describe('工作区绝对路径,每次调
|
|
|
11
12
|
const version = z.string().min(1).describe('可选的全工作区写入保护。传读取返回的 workspaceVersion;项目模板写入必填。').optional();
|
|
12
13
|
const expectedFileVersion = z.string().min(1).optional().describe('文档读取返回的 version;整文覆盖/改名/删除使用此参数,或传 expectedWorkspaceVersion。也可保护按位置编辑。');
|
|
13
14
|
const expectedNodeVersion = z.string().min(1).optional().describe('节点返回的 nodeVersion,用来核对目标和后代。适用于覆盖正文、改名、移动、删除、段落和节点内引用编号。');
|
|
15
|
+
const idempotencyKey = z.string().min(1).max(128).optional().describe('可选幂等键;5 分钟内重复提交相同幂等键直接返回首次结果,避免网络重试重复写入。');
|
|
14
16
|
const templateSource = z.enum(['ancestor','user']).optional().describe('仅用于 pull,明确选择上级项目或用户库。省略时逐层向上查找,全部缺失再查用户库。');
|
|
15
17
|
const position = z.object({
|
|
16
18
|
mode: z.enum(['append','prepend','before','after','replace']),
|
|
@@ -39,8 +41,29 @@ const nodeFields = {
|
|
|
39
41
|
baseTemplateId: z.string().optional(), name: z.string().optional(), purpose: text().optional(), overwrite: z.boolean().optional(), scope: z.enum(['project','user']).optional(), from: templateSource, expectedFileVersion, expectedNodeVersion
|
|
40
42
|
};
|
|
41
43
|
const operations = ['document.create','document.copy','document.update','document.rename','document.delete','node.create','node.insert','node.update','node.rename','node.move','node.delete','link.connect','link.disconnect','template.create','template.update','template.delete','template.pull'];
|
|
42
|
-
|
|
43
|
-
|
|
44
|
+
|
|
45
|
+
function safeTokenMatch(actual, expected) {
|
|
46
|
+
if (!actual || !expected) return false;
|
|
47
|
+
const a = createHash('sha256').update(String(actual)).digest();
|
|
48
|
+
const b = createHash('sha256').update(String(expected)).digest();
|
|
49
|
+
return timingSafeEqual(a, b);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function readMcpCookie(req, name) {
|
|
53
|
+
const header = String(req.headers.cookie || '');
|
|
54
|
+
for (const part of header.split(';')) {
|
|
55
|
+
const idx = part.indexOf('=');
|
|
56
|
+
if (idx < 0) continue;
|
|
57
|
+
if (part.slice(0, idx).trim() === name) {
|
|
58
|
+
try { return decodeURIComponent(part.slice(idx + 1).trim()); } catch { return part.slice(idx + 1).trim(); }
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return '';
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function createServer(invoke, invokeCapability, extras = {}) {
|
|
65
|
+
const { invokeSession = null, invokeAutomation = null } = extras || {};
|
|
66
|
+
const server = new McpServer({ name: 'clado', version: VERSION }, { instructions: '每次必填workspace。工作区未初始化才调用init;需要目录时用inspect。先读模板prompt再创建.md(也兼容.mdc)。新建、追加和唯一原文编辑可以直接提交;覆盖、删除和按编号定位时带目标版本(多会话改不同卡片时服务端自动重排无冲突)。写入支持可选 idempotencyKey 幂等去重。项目模板写入使用expectedWorkspaceVersion;用户模板写入用expectedUserTemplateVersion,push需两者。每次响应返回全量diagnostics;操作成功仍可能valid:false。diagnosticsComplete:false表示未完成检查。dryRun的previewDiagnostics对应候选状态;写入results给出最终位置。文档操作使用MCP。' });
|
|
44
67
|
const schemas = new Map();
|
|
45
68
|
const enrich = async (result, args) => {
|
|
46
69
|
const { diagnostics: _operationDiagnostics, error, ...payload } = result;
|
|
@@ -56,13 +79,17 @@ function createServer(invoke, invokeCapability) {
|
|
|
56
79
|
reply.content.push({ type: 'image', mimeType: 'image/png', data: pngBase64 });
|
|
57
80
|
return reply;
|
|
58
81
|
};
|
|
59
|
-
const register = (name, description, schema, handler = invoke, { encode = encoded, readOnly = false } = {}) => {
|
|
82
|
+
const register = (name, description, schema, handler = invoke, { encode = encoded, readOnly = false, skipEnrich = false } = {}) => {
|
|
60
83
|
schemas.set(name, z.object({ workspace, ...schema }).strict());
|
|
61
84
|
return server.registerTool(name, {
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
85
|
+
description, inputSchema: { workspace, ...schema }, annotations: { readOnlyHint: readOnly, destructiveHint: !readOnly, openWorldHint: false }
|
|
86
|
+
}, async args => {
|
|
87
|
+
try {
|
|
88
|
+
const res = await handler(name, args);
|
|
89
|
+
return encode(skipEnrich ? res : await enrich(res, args));
|
|
90
|
+
} catch (error) {
|
|
91
|
+
return await failure(error, args);
|
|
92
|
+
}
|
|
66
93
|
});
|
|
67
94
|
};
|
|
68
95
|
register('clado_workspace', '初始化、查看工作区、列出子工作区、读取画布拓扑树(graph)、搜索或校验。用户说“我选的卡片”时用selection,按点选顺序读取标题路径、正文、后代和版本。selectionStatus为empty或stale时请用户选中或重新选择。graph返回类似DOM树的卡片列布局、跨卡连线、语义Tag、孤立卡与断链快照。inspect返回工作区版本和目录;workspaces列出当前服务范围内的子工作区;init准备工作区。', {
|
|
@@ -73,19 +100,19 @@ function createServer(invoke, invokeCapability) {
|
|
|
73
100
|
...Object.fromEntries(['templateId','source','baseTemplateId','name','purpose','overwrite'].map(key => [key, nodeFields[key]])),
|
|
74
101
|
from: templateSource,
|
|
75
102
|
view: z.enum(['prompt','source','full']).optional().describe('read默认prompt,编辑规则用source,只有需要全部字段时才用full。'),
|
|
76
|
-
expectedWorkspaceVersion: version, expectedUserTemplateVersion: z.string().optional().describe('读取返回的userTemplateVersion;用户库写入及push必填。'), dryRun: z.boolean().optional()
|
|
103
|
+
expectedWorkspaceVersion: version, expectedUserTemplateVersion: z.string().optional().describe('读取返回的userTemplateVersion;用户库写入及push必填。'), idempotencyKey, dryRun: z.boolean().optional()
|
|
77
104
|
});
|
|
78
|
-
register('clado_documents', '文档list/read/create/copy/update/rename/delete。read默认full,按需view:nodes/source/summary/graph(graph返回卡片列布局、跨卡连线、语义Tag、孤立卡与断链拓扑树)。create用file(.md或.mdc)/title/templateId,source只传正文。copy用file/newFile保留规则头和正文并重定位副本引用。create/copy检查目标尚不存在,可省略版本。update传完整source,可用metadata替换头;rename用newFile维护引用;delete被引用默认拒绝,unlink才断开。update/rename/delete使用expectedFileVersion或expectedWorkspaceVersion
|
|
79
|
-
action: z.enum(['list','read','create','copy','update','rename','delete']), view: z.enum(['full','nodes','source','summary','graph']).optional(), file: z.string().optional(), query: z.string().optional(), title: z.string().optional(), templateId: z.string().optional(), source: text().optional(), metadata: z.record(z.string(), z.unknown()).optional(), newFile: z.string().optional(), unlink: z.boolean().optional(), expectedFileVersion, expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
|
|
105
|
+
register('clado_documents', '文档list/read/create/copy/update/rename/delete。read默认full,按需view:nodes/source/summary/graph(graph返回卡片列布局、跨卡连线、语义Tag、孤立卡与断链拓扑树)。create用file(.md或.mdc)/title/templateId,source只传正文。copy用file/newFile保留规则头和正文并重定位副本引用。create/copy检查目标尚不存在,可省略版本。update传完整source,可用metadata替换头;rename用newFile维护引用;delete被引用默认拒绝,unlink才断开。update/rename/delete使用expectedFileVersion或expectedWorkspaceVersion;支持可选 idempotencyKey 幂等去重;results返回最终位置。', {
|
|
106
|
+
action: z.enum(['list','read','create','copy','update','rename','delete']), view: z.enum(['full','nodes','source','summary','graph']).optional(), file: z.string().optional(), query: z.string().optional(), title: z.string().optional(), templateId: z.string().optional(), source: text().optional(), metadata: z.record(z.string(), z.unknown()).optional(), newFile: z.string().optional(), unlink: z.boolean().optional(), expectedFileVersion, expectedWorkspaceVersion: version, idempotencyKey, dryRun: z.boolean().optional()
|
|
80
107
|
});
|
|
81
|
-
register('clado_nodes', '节点read/query/create/insert/update/rename/move/delete。file必填,node用标题数组。read返回nodeVersion、行号、同级index和段落编号。create在同级末尾新增可省略版本;指定index需文件版本。insert追加/置顶或按唯一anchor插入、update用position:{mode:replace,anchor:原文}时可省略版本。按段落编号或整段覆盖用expectedNodeVersion、expectedFileVersion或expectedWorkspaceVersion
|
|
82
|
-
action: z.enum(['read','query','create','insert','update','rename','move','delete']), ...Object.fromEntries(['file','node','parent','title','content','index','position','recursive','unlink','targetFile'].map(key => [key, nodeFields[key]])), relation: z.enum(['parent','children','ancestors','descendants','siblings','upstream','downstream']).optional(), depth: z.number().int().min(1).max(100).optional(), includeContent: z.boolean().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(100).optional(), expectedFileVersion, expectedNodeVersion, expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
|
|
108
|
+
register('clado_nodes', '节点read/query/create/insert/update/rename/move/delete。file必填,node用标题数组。read返回nodeVersion、行号、同级index和段落编号。create在同级末尾新增可省略版本;指定index需文件版本。insert追加/置顶或按唯一anchor插入、update用position:{mode:replace,anchor:原文}时可省略版本。按段落编号或整段覆盖用expectedNodeVersion、expectedFileVersion或expectedWorkspaceVersion,均保留孩子(同文档并发修改不同卡片时服务端自动重排无冲突)。支持可选 idempotencyKey 幂等去重。rename/move维护引用;delete有孩子需recursive。results返回最终位置。', {
|
|
109
|
+
action: z.enum(['read','query','create','insert','update','rename','move','delete']), ...Object.fromEntries(['file','node','parent','title','content','index','position','recursive','unlink','targetFile'].map(key => [key, nodeFields[key]])), relation: z.enum(['parent','children','ancestors','descendants','siblings','upstream','downstream']).optional(), depth: z.number().int().min(1).max(100).optional(), includeContent: z.boolean().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(100).optional(), expectedFileVersion, expectedNodeVersion, expectedWorkspaceVersion: version, idempotencyKey, dryRun: z.boolean().optional()
|
|
83
110
|
});
|
|
84
|
-
register('clado_links', 'list返回href、sourceText、nodeVersion、linkIndex(从1开始)及位置。connect用源file/node和目标targetFile/targetNode建立连线:默认从具体内容行出发(用sourcePoint绑定代码行/表格行/Mermaid节点,或用position:{mode:replace,anchor:原文}把正文中的方法/步骤/字段词变成行内链接),不建议在卡片末尾单独追加裸的卡片连卡片。按段落、精确起点连接或disconnect
|
|
85
|
-
action: z.enum(['list','connect','disconnect']), ...Object.fromEntries(['file','node','targetFile','targetNode','label','before','after','position','linkIndex','sourcePoint','targetPoint'].map(key => [key, nodeFields[key]])), expectedFileVersion, expectedNodeVersion, expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
|
|
111
|
+
register('clado_links', 'list返回href、sourceText、nodeVersion、linkIndex(从1开始)及位置。connect用源file/node和目标targetFile/targetNode建立连线:默认从具体内容行出发(用sourcePoint绑定代码行/表格行/Mermaid节点,或用position:{mode:replace,anchor:原文}把正文中的方法/步骤/字段词变成行内链接),不建议在卡片末尾单独追加裸的卡片连卡片。按段落、精确起点连接或disconnect需要节点或文件版本,精确落点需要文件或工作区版本。支持可选 idempotencyKey。sourcePoint只用于同画布且与position/before/after互斥。disconnect用linkIndex只断一处,普通链接保留文字。', {
|
|
112
|
+
action: z.enum(['list','connect','disconnect']), ...Object.fromEntries(['file','node','targetFile','targetNode','label','before','after','position','linkIndex','sourcePoint','targetPoint'].map(key => [key, nodeFields[key]])), expectedFileVersion, expectedNodeVersion, expectedWorkspaceVersion: version, idempotencyKey, dryRun: z.boolean().optional()
|
|
86
113
|
});
|
|
87
|
-
register('clado_batch', '按顺序执行1–100个操作。支持可选的expectedWorkspaceVersion,各操作也可带自己的expectedFileVersion或expectedNodeVersion。每步的版本和标题路径按前序操作后的候选状态校验。模板操作使用工作区版本。任一冲突整批不保存;dryRun只预览。', {
|
|
88
|
-
expectedWorkspaceVersion: version, dryRun: z.boolean().optional(), operations: z.array(z.object({ type: z.enum(operations), ...nodeFields }).strict()).min(1).max(100)
|
|
114
|
+
register('clado_batch', '按顺序执行1–100个操作。支持可选的expectedWorkspaceVersion与idempotencyKey,各操作也可带自己的expectedFileVersion或expectedNodeVersion。每步的版本和标题路径按前序操作后的候选状态校验。模板操作使用工作区版本。任一冲突整批不保存;dryRun只预览。', {
|
|
115
|
+
expectedWorkspaceVersion: version, idempotencyKey, dryRun: z.boolean().optional(), operations: z.array(z.object({ type: z.enum(operations), ...nodeFields }).strict()).min(1).max(100)
|
|
89
116
|
});
|
|
90
117
|
if (invokeCapability) register('clado_capabilities', '查询和调用在线画布能力。list 每次读取实时注册的能力、版本、inputSchema 与 outputSchema,可用 to 过滤。call 使用 to:{pluginId,capability,major} 和 input;有多个标签页时传入 viewId。用户要求在画布里打开另一个文件时,调用 clado.directory 的 directory.open。', {
|
|
91
118
|
action: z.enum(['list', 'call']),
|
|
@@ -101,6 +128,27 @@ function createServer(invoke, invokeCapability) {
|
|
|
101
128
|
}, (_, { workspace, viewId, mode, source, scope }) => invokeCapability({
|
|
102
129
|
workspace, viewId, action: 'call', to: captureTarget, input: { ...(mode && { mode }), ...(source && { source }), ...(scope && { scope }) },
|
|
103
130
|
}), { encode: capabilityResult, readOnly: true });
|
|
131
|
+
if (invokeSession) register('clado_sessions', '与内部多角色主会话完全同源的协作工具:list(支持 sinceMinutes 过滤最近活跃会话)、read(读取指定会话最近对话与工具轨迹)、open(按角色拉起或复用主会话)、send(向指定会话或角色发送协作消息并唤醒/插话)。', {
|
|
132
|
+
action: z.enum(['list', 'read', 'open', 'send']),
|
|
133
|
+
sinceMinutes: z.number().nonnegative().optional(),
|
|
134
|
+
includeArchived: z.boolean().optional(),
|
|
135
|
+
sessionId: z.string().optional(),
|
|
136
|
+
limit: z.number().int().min(1).max(60).optional(),
|
|
137
|
+
roleId: z.string().optional(),
|
|
138
|
+
title: z.string().optional(),
|
|
139
|
+
reuseLatest: z.boolean().optional(),
|
|
140
|
+
fromSessionId: z.string().optional(),
|
|
141
|
+
fromRoleName: z.string().optional(),
|
|
142
|
+
targetSessionId: z.string().optional(),
|
|
143
|
+
targetRoleId: z.string().optional(),
|
|
144
|
+
message: z.string().optional(),
|
|
145
|
+
wait: z.boolean().optional(),
|
|
146
|
+
}, (_, args) => invokeSession(args), { skipEnrich: true });
|
|
147
|
+
if (invokeAutomation) register('clado_automations', '与内部同源的工作区定时唤醒与系统事件订阅管理:支持 list / save / delete / pause / resume / run_now / events_catalog。', {
|
|
148
|
+
action: z.enum(['list', 'save', 'delete', 'pause', 'resume', 'run_now', 'events_catalog']),
|
|
149
|
+
ruleId: z.string().optional(),
|
|
150
|
+
rule: z.record(z.string(), z.unknown()).optional(),
|
|
151
|
+
}, (_, args) => invokeAutomation(args), { skipEnrich: true });
|
|
104
152
|
return { server, checkCall: async (name, args) => {
|
|
105
153
|
const schema = schemas.get(name);
|
|
106
154
|
if (!schema) return await failure({ message: '没有这个工具:' + name, status: 400 }, args);
|
|
@@ -110,18 +158,38 @@ function createServer(invoke, invokeCapability) {
|
|
|
110
158
|
} };
|
|
111
159
|
}
|
|
112
160
|
|
|
113
|
-
export function createMcpHandler(invoke, invokeCapability) {
|
|
161
|
+
export function createMcpHandler(invoke, invokeCapability, options = {}) {
|
|
162
|
+
const { remote = false, remoteToken = '', invokeSession = null, invokeAutomation = null } = options || {};
|
|
114
163
|
return async (req, res, url) => {
|
|
115
164
|
if (url.pathname !== '/mcp') return false;
|
|
116
|
-
const host = req.headers.host;
|
|
117
|
-
if (
|
|
165
|
+
const host = String(req.headers.host || '').trim();
|
|
166
|
+
if (remote) {
|
|
167
|
+
if (!host || /[\s/@]/.test(host)) { res.writeHead(403).end('请求主机头不合法。'); return true; }
|
|
168
|
+
} else if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) || (req.headers.origin && req.headers.origin !== 'http://' + host)) {
|
|
169
|
+
res.writeHead(403).end('只接受本机可信来源。');
|
|
170
|
+
return true;
|
|
171
|
+
}
|
|
172
|
+
if (remoteToken) {
|
|
173
|
+
const queryToken = url.searchParams.get('token') || '';
|
|
174
|
+
const authHeader = String(req.headers.authorization || '');
|
|
175
|
+
const bearerToken = authHeader.startsWith('Bearer ') ? authHeader.slice(7).trim() : '';
|
|
176
|
+
const cookieToken = readMcpCookie(req, 'clado_remote_token');
|
|
177
|
+
const authed = safeTokenMatch(bearerToken, remoteToken)
|
|
178
|
+
|| safeTokenMatch(queryToken, remoteToken)
|
|
179
|
+
|| safeTokenMatch(cookieToken, remoteToken);
|
|
180
|
+
if (!authed) {
|
|
181
|
+
res.writeHead(401, { 'content-type': 'application/json' });
|
|
182
|
+
res.end(JSON.stringify({ error: '需要远程访问口令(Bearer Token 或 ?token=)。' }));
|
|
183
|
+
return true;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
118
186
|
if (req.method !== 'POST') { res.writeHead(405, { allow: 'POST' }).end(); return true; }
|
|
119
187
|
let server, transport;
|
|
120
188
|
try {
|
|
121
189
|
const chunks = []; let bytes = 0;
|
|
122
190
|
for await (const chunk of req) { bytes += chunk.length; if (bytes > 2_000_000) { res.writeHead(413).end('请求超过2MB。'); return true; } chunks.push(chunk); }
|
|
123
191
|
const data = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
124
|
-
const created = createServer(invoke, invokeCapability); server = created.server;
|
|
192
|
+
const created = createServer(invoke, invokeCapability, { invokeSession, invokeAutomation }); server = created.server;
|
|
125
193
|
if (data.method === 'tools/call') {
|
|
126
194
|
const rejected = await created.checkCall(data.params?.name, data.params?.arguments);
|
|
127
195
|
if (rejected) { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ jsonrpc: '2.0', id: data.id ?? null, result: rejected })); await server.close(); return true; }
|
package/src/server/workspace.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createServer } from 'node:http';
|
|
2
2
|
import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
3
|
-
import { readFileSync, statSync, existsSync, mkdirSync } from 'node:fs';
|
|
3
|
+
import { readFileSync, readdirSync, statSync, existsSync, mkdirSync } from 'node:fs';
|
|
4
4
|
import { dirname, resolve, basename, join, relative, sep, isAbsolute } from 'node:path';
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
6
|
import { renderHtml } from '../html/page.js';
|
|
@@ -39,6 +39,7 @@ const resourceTypes = {
|
|
|
39
39
|
};
|
|
40
40
|
const types = { html: 'text/html', css: 'text/css', js: 'text/javascript', json: 'application/json', md: 'text/markdown' };
|
|
41
41
|
const REMOTE_COOKIE = 'clado_remote_token';
|
|
42
|
+
const listWorkspaceFilesCache = new Map();
|
|
42
43
|
|
|
43
44
|
function isTrustedOrigin(req, remote = false) {
|
|
44
45
|
const origin = req.headers.origin;
|
|
@@ -193,6 +194,10 @@ export function createWorkspaceHandler(directory, options = {}) {
|
|
|
193
194
|
const target = resolveTarget(url);
|
|
194
195
|
await options.agent.handleConfig(req, res, target.workspace); return true;
|
|
195
196
|
}
|
|
197
|
+
if (options.agent && url.pathname === '/library/agent/automations' && options.agent.handleAutomations) {
|
|
198
|
+
const target = resolveTarget(url);
|
|
199
|
+
await options.agent.handleAutomations(req, res, url, target.workspace); return true;
|
|
200
|
+
}
|
|
196
201
|
if (options.agent && url.pathname === '/library/agent') {
|
|
197
202
|
const target = resolveTarget(url);
|
|
198
203
|
await options.agent.handle(req, res, target.workspace); return true;
|
|
@@ -402,6 +407,41 @@ export function createWorkspaceHandler(directory, options = {}) {
|
|
|
402
407
|
json(res, 200, readFileGitState(target.workspace, relPath));
|
|
403
408
|
return true;
|
|
404
409
|
}
|
|
410
|
+
if (url.pathname === '/library/workspace-files') {
|
|
411
|
+
const target = resolveTarget(url);
|
|
412
|
+
const q = String(url.searchParams.get('q') || '').trim().toLowerCase();
|
|
413
|
+
const cache = listWorkspaceFilesCache.get(target.workspace);
|
|
414
|
+
const now = Date.now();
|
|
415
|
+
let files;
|
|
416
|
+
if (cache && now - cache.ts < 5000) {
|
|
417
|
+
files = cache.files;
|
|
418
|
+
} else {
|
|
419
|
+
files = [];
|
|
420
|
+
const skipDirs = new Set(['.git', 'node_modules', 'dist', 'build', '.next', '.nuxt', '.cache', 'coverage', '.venv', 'venv', '__pycache__', 'target', 'vendor', '.clado', '.pi']);
|
|
421
|
+
const walk = (dir, depth) => {
|
|
422
|
+
if (depth > 5 || files.length >= 400) return;
|
|
423
|
+
let entries;
|
|
424
|
+
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
425
|
+
for (const ent of entries) {
|
|
426
|
+
if (files.length >= 400) break;
|
|
427
|
+
if (ent.name.startsWith('.') && ent.name !== '.env.example') continue;
|
|
428
|
+
if (skipDirs.has(ent.name)) continue;
|
|
429
|
+
const full = join(dir, ent.name);
|
|
430
|
+
if (ent.isDirectory()) {
|
|
431
|
+
walk(full, depth + 1);
|
|
432
|
+
} else if (ent.isFile()) {
|
|
433
|
+
files.push(relative(target.workspace, full).split(sep).join('/'));
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
};
|
|
437
|
+
walk(target.workspace, 0);
|
|
438
|
+
files.sort((a, b) => a.localeCompare(b));
|
|
439
|
+
listWorkspaceFilesCache.set(target.workspace, { ts: now, files });
|
|
440
|
+
}
|
|
441
|
+
const matched = q ? files.filter(f => f.toLowerCase().includes(q)) : files;
|
|
442
|
+
json(res, 200, { files: matched.slice(0, 80), total: matched.length });
|
|
443
|
+
return true;
|
|
444
|
+
}
|
|
405
445
|
if (pluginsEnabled && url.pathname === '/library/plugins.json') {
|
|
406
446
|
const target = resolveTarget(url);
|
|
407
447
|
const values = target.settings?.values() || {};
|
|
@@ -545,7 +585,40 @@ export async function startWorkspace(input, { port = 4317, host = '', remote = f
|
|
|
545
585
|
return current?.expiresAt > Date.now() ? current : null;
|
|
546
586
|
};
|
|
547
587
|
const events = createWorkspaceEvents();
|
|
588
|
+
let agent = null;
|
|
548
589
|
let baseService = createWorkspaceService(workspace, { documentRoot: root, readSelection });
|
|
590
|
+
const emitWorkspaceSystemEvents = (targetWorkspace, tool, input, result, sourceMeta = {}) => {
|
|
591
|
+
if (!agent?.notifySystemEvent || !result || input?.dryRun) return;
|
|
592
|
+
const file = String(input?.file || result?.changes?.[0]?.file || '').trim();
|
|
593
|
+
if (Array.isArray(result.cardChanges) && result.cardChanges.length) {
|
|
594
|
+
for (const ch of result.cardChanges) {
|
|
595
|
+
agent.notifySystemEvent(targetWorkspace, `card.${ch.action}`, {
|
|
596
|
+
file: ch.file,
|
|
597
|
+
card: ch.card,
|
|
598
|
+
addedTags: ch.addedTags,
|
|
599
|
+
removedTags: ch.removedTags,
|
|
600
|
+
...sourceMeta,
|
|
601
|
+
});
|
|
602
|
+
if ((ch.addedTags?.length || 0) > 0 || (ch.removedTags?.length || 0) > 0) {
|
|
603
|
+
agent.notifySystemEvent(targetWorkspace, 'tag.changed', {
|
|
604
|
+
file: ch.file,
|
|
605
|
+
card: ch.card,
|
|
606
|
+
addedTags: ch.addedTags,
|
|
607
|
+
removedTags: ch.removedTags,
|
|
608
|
+
...sourceMeta,
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
if (tool === 'clado_documents') {
|
|
614
|
+
const map = { create: 'doc.created', update: 'doc.updated', rename: 'doc.renamed', delete: 'doc.deleted' };
|
|
615
|
+
const evt = map[input?.action];
|
|
616
|
+
if (evt) agent.notifySystemEvent(targetWorkspace, evt, { file, ...sourceMeta });
|
|
617
|
+
} else if (tool === 'clado_links') {
|
|
618
|
+
if (input?.action === 'connect') agent.notifySystemEvent(targetWorkspace, 'link.connected', { file, card: input?.node?.[0] || '', ...sourceMeta });
|
|
619
|
+
if (input?.action === 'disconnect') agent.notifySystemEvent(targetWorkspace, 'link.disconnected', { file, card: input?.node?.[0] || '', ...sourceMeta });
|
|
620
|
+
}
|
|
621
|
+
};
|
|
549
622
|
const mcpService = async (tool, input = {}) => {
|
|
550
623
|
const result = await baseService(tool, input);
|
|
551
624
|
try {
|
|
@@ -555,8 +628,92 @@ export async function startWorkspace(input, { port = 4317, host = '', remote = f
|
|
|
555
628
|
return result;
|
|
556
629
|
};
|
|
557
630
|
mcpService.diagnostics = (...a) => baseService.diagnostics(...a);
|
|
631
|
+
|
|
632
|
+
const externalMcpService = async (tool, input = {}) => {
|
|
633
|
+
const targetWorkspace = input?.workspace ? resolve(input.workspace) : workspace;
|
|
634
|
+
const isWrite = !input?.dryRun && (
|
|
635
|
+
tool === 'clado_batch'
|
|
636
|
+
|| (tool === 'clado_documents' && ['create', 'copy', 'update', 'rename', 'delete'].includes(input?.action))
|
|
637
|
+
|| (tool === 'clado_nodes' && ['create', 'insert', 'update', 'rename', 'move', 'delete'].includes(input?.action))
|
|
638
|
+
|| (tool === 'clado_links' && ['connect', 'disconnect'].includes(input?.action))
|
|
639
|
+
);
|
|
640
|
+
const mcpCards = [];
|
|
641
|
+
if (Array.isArray(input?.node) && input.node.length) mcpCards.push(String(input.node[0]));
|
|
642
|
+
if (Array.isArray(input?.targetNode) && input.targetNode.length && !input.targetFile) mcpCards.push(String(input.targetNode[0]));
|
|
643
|
+
if (input?.title) mcpCards.push(String(input.title));
|
|
644
|
+
const mcpVerb = input?.action === 'delete' ? '正在删除'
|
|
645
|
+
: input?.action === 'create' ? '正在新建'
|
|
646
|
+
: input?.action === 'connect' ? '正在连线'
|
|
647
|
+
: input?.action === 'disconnect' ? '正在移除连线'
|
|
648
|
+
: '正在编辑';
|
|
649
|
+
const mcpSessionId = 'mcp_external';
|
|
650
|
+
if (isWrite && mcpCards.length) {
|
|
651
|
+
events.emit(targetWorkspace, 'agent.presence', {
|
|
652
|
+
sessionId: mcpSessionId,
|
|
653
|
+
roleId: 'mcp',
|
|
654
|
+
roleName: '外部 MCP',
|
|
655
|
+
tone: 'amber',
|
|
656
|
+
file: String(input?.file || ''),
|
|
657
|
+
cards: [...new Set(mcpCards)],
|
|
658
|
+
label: mcpVerb,
|
|
659
|
+
phase: 'active',
|
|
660
|
+
ts: Date.now(),
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
try {
|
|
664
|
+
const result = await mcpService(tool, input);
|
|
665
|
+
if (isWrite) {
|
|
666
|
+
const resultCards = Array.isArray(result?.cardChanges)
|
|
667
|
+
? [...new Set(result.cardChanges.map(c => c.card).filter(Boolean))]
|
|
668
|
+
: [];
|
|
669
|
+
if (resultCards.length) {
|
|
670
|
+
events.emit(targetWorkspace, 'agent.presence', {
|
|
671
|
+
sessionId: mcpSessionId,
|
|
672
|
+
roleId: 'mcp',
|
|
673
|
+
roleName: '外部 MCP',
|
|
674
|
+
tone: 'amber',
|
|
675
|
+
file: String(result.cardChanges[0]?.file || input?.file || ''),
|
|
676
|
+
cards: resultCards,
|
|
677
|
+
label: mcpVerb,
|
|
678
|
+
phase: 'active',
|
|
679
|
+
ts: Date.now(),
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
events.emit(targetWorkspace, 'agent.presence', {
|
|
683
|
+
sessionId: mcpSessionId,
|
|
684
|
+
roleId: 'mcp',
|
|
685
|
+
roleName: '外部 MCP',
|
|
686
|
+
tone: 'amber',
|
|
687
|
+
file: String(input?.file || ''),
|
|
688
|
+
cards: [],
|
|
689
|
+
label: '刚刚编辑了',
|
|
690
|
+
phase: 'afterglow',
|
|
691
|
+
ts: Date.now(),
|
|
692
|
+
});
|
|
693
|
+
emitWorkspaceSystemEvents(targetWorkspace, tool, input, result, { originRoleId: 'mcp', originSessionId: mcpSessionId });
|
|
694
|
+
}
|
|
695
|
+
return result;
|
|
696
|
+
} catch (err) {
|
|
697
|
+
if (isWrite) {
|
|
698
|
+
events.emit(targetWorkspace, 'agent.presence', {
|
|
699
|
+
sessionId: mcpSessionId,
|
|
700
|
+
roleId: 'mcp',
|
|
701
|
+
roleName: '外部 MCP',
|
|
702
|
+
tone: 'amber',
|
|
703
|
+
file: String(input?.file || ''),
|
|
704
|
+
cards: [],
|
|
705
|
+
label: '刚刚编辑了',
|
|
706
|
+
phase: 'afterglow',
|
|
707
|
+
ts: Date.now(),
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
throw err;
|
|
711
|
+
}
|
|
712
|
+
};
|
|
713
|
+
externalMcpService.diagnostics = (...a) => baseService.diagnostics(...a);
|
|
714
|
+
|
|
558
715
|
const liveMcpUrl = () => 'http://127.0.0.1:' + server.address().port + '/mcp';
|
|
559
|
-
|
|
716
|
+
agent = agentName !== 'off' ? (await import('./agent.js')).createAgentHandler({
|
|
560
717
|
workspace: () => workspace,
|
|
561
718
|
mcpUrl: liveMcpUrl,
|
|
562
719
|
workspaceService: mcpService,
|
|
@@ -810,7 +967,12 @@ export async function startWorkspace(input, { port = 4317, host = '', remote = f
|
|
|
810
967
|
scopeName:() => basename(workspace),
|
|
811
968
|
inactivePlugins:() => rootRuntime.inactivePlugins(),
|
|
812
969
|
});
|
|
813
|
-
const mcp = createMcpHandler(
|
|
970
|
+
const mcp = createMcpHandler(externalMcpService, capabilities.invoke, {
|
|
971
|
+
remote: isRemote,
|
|
972
|
+
remoteToken,
|
|
973
|
+
invokeSession: agent ? args => agent.handleMcpSessions(args) : null,
|
|
974
|
+
invokeAutomation: agent ? args => agent.handleMcpAutomations(args) : null,
|
|
975
|
+
});
|
|
814
976
|
const server = createServer(async (req,res) => {
|
|
815
977
|
try { const url = new URL(req.url,'http://127.0.0.1'); if (!await mcp(req,res,url) && !await handle(req,res,url)) { res.writeHead(404);res.end('Not found'); } }
|
|
816
978
|
catch { if (!res.headersSent) res.writeHead(500);res.end('预览请求失败'); }
|