cladogram 0.6.0-beta.1 → 0.6.0-beta.10
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 +50 -47
- package/bin/clado.js +34 -2
- package/docs/agent-context.md +63 -0
- package/docs/agent-reference.md +219 -0
- package/docs/release.md +116 -0
- package/package.json +3 -1
- package/plugins/agent/index.js +2429 -723
- package/plugins/agent/settings.js +3592 -0
- package/plugins/agent/style.css +1327 -94
- package/plugins/view-controls/index.js +0 -11
- package/plugins/view-controls/style.css +7 -14
- package/skills/clado/SKILL.md +4 -2
- package/src/agent/automations.js +454 -0
- package/src/agent/clado-tools.js +597 -104
- package/src/agent/pi-bridge.js +2184 -112
- package/src/agent/pi-config.js +1889 -108
- package/src/agent/pi-hooks-perms.js +621 -0
- package/src/html/app-css.js +69 -1
- package/src/html/canvas-chain.js +32 -6
- package/src/html/canvas-focus.js +19 -13
- package/src/html/canvas-live-diff.js +1373 -0
- package/src/html/canvas-ui.css +503 -2
- package/src/html/canvas-wires.js +5 -1
- package/src/html/page.js +4 -2
- package/src/html/plugin-assets.js +5 -1
- package/src/html/plugin-ui.css +1 -1
- package/src/html/runtime-api.js +152 -10
- package/src/html/runtime.js +546 -37
- package/src/server/agent.js +594 -37
- package/src/server/assets/library-canvas.js +256 -9
- package/src/server/assets/library.css +567 -12
- package/src/server/assets/library.html +2 -0
- package/src/server/assets/library.js +1028 -32
- package/src/server/code-inspect.js +183 -0
- package/src/server/mcp.js +90 -22
- package/src/server/plugin-registry.js +664 -2
- package/src/server/workspace.js +551 -25
- package/src/workspace/graph-snapshot.js +695 -0
- package/src/workspace/service.js +201 -9
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Safe workspace source code reader, symbol resolver & Git diff inspector
|
|
3
|
+
* for Clado's Right-Side Live Code & Git Diff Drawer.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { execFileSync } from 'node:child_process';
|
|
7
|
+
import { existsSync, lstatSync, readdirSync, readFileSync } from 'node:fs';
|
|
8
|
+
import { extname, join, relative, resolve, sep } from 'node:path';
|
|
9
|
+
import { DocumentError } from '../workspace/documents.js';
|
|
10
|
+
|
|
11
|
+
const MAX_CODE_BYTES = 256 * 1024;
|
|
12
|
+
const SKIP_DIRS = new Set(['node_modules', '.git', '.clado', 'dist', 'build', '.next', 'coverage', '.cache', 'target', 'vendor']);
|
|
13
|
+
const LANG_BY_EXT = {
|
|
14
|
+
'.js': 'javascript', '.mjs': 'javascript', '.cjs': 'javascript', '.jsx': 'jsx',
|
|
15
|
+
'.ts': 'typescript', '.tsx': 'tsx', '.py': 'python', '.go': 'go', '.rs': 'rust',
|
|
16
|
+
'.java': 'java', '.kt': 'kotlin', '.rb': 'ruby', '.php': 'php', '.cs': 'csharp',
|
|
17
|
+
'.c': 'c', '.cpp': 'cpp', '.h': 'c', '.hpp': 'cpp', '.css': 'css', '.scss': 'scss',
|
|
18
|
+
'.html': 'html', '.json': 'json', '.yaml': 'yaml', '.yml': 'yaml', '.xml': 'xml',
|
|
19
|
+
'.sql': 'sql', '.sh': 'bash', '.md': 'markdown', '.mdc': 'markdown', '.vue': 'vue',
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export function safeWorkspaceSourcePath(workspaceRoot, relPath) {
|
|
23
|
+
const clean = String(relPath || '').trim().replace(/^\/+/, '');
|
|
24
|
+
if (!clean || clean.includes('\0') || clean.includes('..') || clean.startsWith('.git/') || clean === '.git') {
|
|
25
|
+
throw new DocumentError('文件路径超出工作区安全范围。', 403);
|
|
26
|
+
}
|
|
27
|
+
const base = resolve(workspaceRoot);
|
|
28
|
+
const full = resolve(base, clean);
|
|
29
|
+
if (full !== base && !full.startsWith(base + sep)) {
|
|
30
|
+
throw new DocumentError('文件路径超出工作区安全范围。', 403);
|
|
31
|
+
}
|
|
32
|
+
return { full, rel: relative(base, full).split('\\').join('/') };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function isLikelyBinary(buf) {
|
|
36
|
+
const sample = buf.subarray(0, Math.min(buf.length, 4096));
|
|
37
|
+
for (let i = 0; i < sample.length; i++) {
|
|
38
|
+
if (sample[i] === 0) return true;
|
|
39
|
+
}
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function readWorkspaceCodeFile(workspaceRoot, relPath) {
|
|
44
|
+
const { full, rel } = safeWorkspaceSourcePath(workspaceRoot, relPath);
|
|
45
|
+
if (!existsSync(full)) throw new DocumentError('找不到文件:' + rel, 404);
|
|
46
|
+
const stat = lstatSync(full);
|
|
47
|
+
if (!stat.isFile()) throw new DocumentError('目标不是普通文件:' + rel, 400);
|
|
48
|
+
if (stat.size > MAX_CODE_BYTES) throw new DocumentError('源码文件超过 256 KB 预览限制。', 413);
|
|
49
|
+
const buf = readFileSync(full);
|
|
50
|
+
if (isLikelyBinary(buf)) throw new DocumentError('不支持预览二进制文件。', 415);
|
|
51
|
+
const content = buf.toString('utf8');
|
|
52
|
+
const lines = content.split(/\r?\n/);
|
|
53
|
+
const ext = extname(rel).toLowerCase();
|
|
54
|
+
return {
|
|
55
|
+
path: rel,
|
|
56
|
+
content,
|
|
57
|
+
totalLines: lines.length,
|
|
58
|
+
language: LANG_BY_EXT[ext] || ext.replace(/^\./, '') || 'text',
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function readFileGitState(workspaceRoot, relPath) {
|
|
63
|
+
const { full, rel } = safeWorkspaceSourcePath(workspaceRoot, relPath);
|
|
64
|
+
let headContent = null;
|
|
65
|
+
let gitDiff = '';
|
|
66
|
+
let tracked = false;
|
|
67
|
+
try {
|
|
68
|
+
headContent = execFileSync('git', ['show', `HEAD:${rel}`], {
|
|
69
|
+
cwd: workspaceRoot,
|
|
70
|
+
encoding: 'utf8',
|
|
71
|
+
maxBuffer: MAX_CODE_BYTES * 2,
|
|
72
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
73
|
+
});
|
|
74
|
+
tracked = true;
|
|
75
|
+
} catch {
|
|
76
|
+
headContent = null;
|
|
77
|
+
}
|
|
78
|
+
try {
|
|
79
|
+
gitDiff = execFileSync('git', ['diff', 'HEAD', '--', rel], {
|
|
80
|
+
cwd: workspaceRoot,
|
|
81
|
+
encoding: 'utf8',
|
|
82
|
+
maxBuffer: MAX_CODE_BYTES * 2,
|
|
83
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
84
|
+
});
|
|
85
|
+
} catch {
|
|
86
|
+
gitDiff = '';
|
|
87
|
+
}
|
|
88
|
+
const currentContent = existsSync(full) && lstatSync(full).isFile() && lstatSync(full).size <= MAX_CODE_BYTES
|
|
89
|
+
? readFileSync(full, 'utf8')
|
|
90
|
+
: null;
|
|
91
|
+
return {
|
|
92
|
+
path: rel,
|
|
93
|
+
tracked,
|
|
94
|
+
headContent,
|
|
95
|
+
currentContent,
|
|
96
|
+
gitDiff,
|
|
97
|
+
changed: headContent !== null && currentContent !== null ? headContent !== currentContent : (!tracked && currentContent !== null),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function resolveSymbolInWorkspace(workspaceRoot, symbolQuery) {
|
|
102
|
+
const raw = String(symbolQuery || '').trim();
|
|
103
|
+
if (!raw) throw new DocumentError('缺少符号或文件路径参数。', 400);
|
|
104
|
+
|
|
105
|
+
// Direct relative path check first
|
|
106
|
+
const strippedLine = raw.replace(/:(\d+)$/, '');
|
|
107
|
+
const explicitLine = Number(raw.match(/:(\d+)$/)?.[1] || 0);
|
|
108
|
+
try {
|
|
109
|
+
const { full, rel } = safeWorkspaceSourcePath(workspaceRoot, strippedLine);
|
|
110
|
+
if (existsSync(full) && lstatSync(full).isFile()) {
|
|
111
|
+
const fileData = readWorkspaceCodeFile(workspaceRoot, rel);
|
|
112
|
+
return { ...fileData, matchedLine: explicitLine || 1 };
|
|
113
|
+
}
|
|
114
|
+
} catch {}
|
|
115
|
+
|
|
116
|
+
// Parse ClassName#methodName or ClassName.methodName or filename
|
|
117
|
+
const [rawClass, rawMethod] = raw.split(/[#.]/);
|
|
118
|
+
const className = String(rawClass || '').replace(/\(.*\)$/, '').trim();
|
|
119
|
+
const methodName = String(rawMethod || '').replace(/\(.*\)$/, '').trim();
|
|
120
|
+
if (!className) throw new DocumentError('无法解析符号:' + raw, 404);
|
|
121
|
+
|
|
122
|
+
const candidates = [];
|
|
123
|
+
const walk = (dir, depth = 0) => {
|
|
124
|
+
if (depth > 6 || candidates.length >= 250) return;
|
|
125
|
+
let entries;
|
|
126
|
+
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
127
|
+
for (const ent of entries) {
|
|
128
|
+
if (ent.name.startsWith('.') && ent.name !== '.env.example') continue;
|
|
129
|
+
if (ent.isDirectory()) {
|
|
130
|
+
if (!SKIP_DIRS.has(ent.name)) walk(join(dir, ent.name), depth + 1);
|
|
131
|
+
} else if (ent.isFile()) {
|
|
132
|
+
const ext = extname(ent.name).toLowerCase();
|
|
133
|
+
if (!(ext in LANG_BY_EXT) || ext === '.md' || ext === '.mdc') continue;
|
|
134
|
+
const full = join(dir, ent.name);
|
|
135
|
+
const rel = relative(workspaceRoot, full).split('\\').join('/');
|
|
136
|
+
const stem = ent.name.slice(0, ent.name.length - ext.length);
|
|
137
|
+
const exactFile = stem.toLowerCase() === className.toLowerCase()
|
|
138
|
+
|| ent.name.toLowerCase() === raw.toLowerCase()
|
|
139
|
+
|| stem.replace(/[-_]/g, '').toLowerCase() === className.replace(/[-_]/g, '').toLowerCase();
|
|
140
|
+
candidates.push({ full, rel, score: exactFile ? 10 : (rel.toLowerCase().includes(className.toLowerCase()) ? 5 : 1) });
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
};
|
|
144
|
+
walk(workspaceRoot);
|
|
145
|
+
candidates.sort((a, b) => b.score - a.score);
|
|
146
|
+
|
|
147
|
+
const classRegex = new RegExp(`\\b${className.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
|
|
148
|
+
const methodRegex = methodName
|
|
149
|
+
? new RegExp(`\\b${methodName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`)
|
|
150
|
+
: null;
|
|
151
|
+
|
|
152
|
+
for (const cand of candidates.slice(0, 80)) {
|
|
153
|
+
try {
|
|
154
|
+
const stat = lstatSync(cand.full);
|
|
155
|
+
if (stat.size > MAX_CODE_BYTES) continue;
|
|
156
|
+
const text = readFileSync(cand.full, 'utf8');
|
|
157
|
+
if (cand.score < 10 && !classRegex.test(text)) continue;
|
|
158
|
+
const lines = text.split(/\r?\n/);
|
|
159
|
+
let matchedLine = 1;
|
|
160
|
+
if (methodRegex) {
|
|
161
|
+
const mIdx = lines.findIndex(l => methodRegex.test(l));
|
|
162
|
+
if (mIdx >= 0) matchedLine = mIdx + 1;
|
|
163
|
+
else {
|
|
164
|
+
const cIdx = lines.findIndex(l => classRegex.test(l));
|
|
165
|
+
if (cIdx >= 0) matchedLine = cIdx + 1;
|
|
166
|
+
}
|
|
167
|
+
} else {
|
|
168
|
+
const cIdx = lines.findIndex(l => classRegex.test(l));
|
|
169
|
+
if (cIdx >= 0) matchedLine = cIdx + 1;
|
|
170
|
+
}
|
|
171
|
+
const ext = extname(cand.rel).toLowerCase();
|
|
172
|
+
return {
|
|
173
|
+
path: cand.rel,
|
|
174
|
+
content: text,
|
|
175
|
+
totalLines: lines.length,
|
|
176
|
+
language: LANG_BY_EXT[ext] || ext.replace(/^\./, '') || 'text',
|
|
177
|
+
matchedLine,
|
|
178
|
+
};
|
|
179
|
+
} catch {}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
throw new DocumentError(`在工作区源码中未找到匹配「${raw}」的文件。`, 404);
|
|
183
|
+
}
|
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,36 +79,40 @@ 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
|
-
register('clado_workspace', '
|
|
69
|
-
action: z.enum(['init','inspect','search','validate','selection','workspaces']), query: z.string().optional(), includeContent: z.boolean().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(100).optional()
|
|
95
|
+
register('clado_workspace', '初始化、查看工作区、列出子工作区、读取画布拓扑树(graph)、搜索或校验。用户说“我选的卡片”时用selection,按点选顺序读取标题路径、正文、后代和版本。selectionStatus为empty或stale时请用户选中或重新选择。graph返回类似DOM树的卡片列布局、跨卡连线、语义Tag、孤立卡与断链快照。inspect返回工作区版本和目录;workspaces列出当前服务范围内的子工作区;init准备工作区。', {
|
|
96
|
+
action: z.enum(['init','inspect','search','validate','selection','workspaces','graph']), file: z.string().optional(), query: z.string().optional(), includeContent: z.boolean().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(100).optional()
|
|
70
97
|
});
|
|
71
98
|
register('clado_templates', '管理模板:scope默认project,设user操作用户库。read默认只返回prompt;编辑时view:source读完整MDC,view:full才返回metadata/source/starter/prompt全部内容。按当前项目、逐层上级、用户库查找,返回来源目录。create传templateId及source,或baseTemplateId(可选name/purpose)复制为新模板;update传完整source。模板头包含id/name/version/purpose/hard_constraints/soft_constraints/organization。pull复制到当前项目,默认逐层查找上级项目再查用户库,可用from:ancestor或from:user指定;push同步到用户库。不同内容默认拒绝覆盖,确认后overwrite:true。项目写入需expectedWorkspaceVersion,用户写入需expectedUserTemplateVersion,push需两者;均可dryRun。修改模板不影响已有文档头部。', {
|
|
72
99
|
action: z.enum(['list','read','create','update','delete','pull','push']), scope: z.enum(['project','user']).optional(),
|
|
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
|
|
79
|
-
action: z.enum(['list','read','create','copy','update','rename','delete']), view: z.enum(['full','nodes','source','summary']).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; }
|