cladogram 0.5.3 → 0.5.5-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -6
- package/bin/clado.js +17 -6
- package/docs/plugin-development.md +135 -0
- package/docs/plugin-ui.md +43 -0
- package/docs/release.md +14 -0
- package/package.json +7 -1
- package/plugins/agent/index.js +181 -0
- package/plugins/agent/style.css +105 -0
- package/plugins/brand/index.js +262 -0
- package/plugins/brand/style.css +162 -0
- package/plugins/directory/capabilities.json +27 -0
- package/plugins/directory/index.js +201 -0
- package/plugins/directory/style.css +59 -0
- package/plugins/view-controls/index.js +58 -0
- package/plugins/view-controls/style.css +66 -0
- package/skills/clado/SKILL.md +19 -15
- package/src/html/app-css.js +69 -47
- package/src/html/canvas-chain.js +7 -7
- package/src/html/canvas-focus.js +2 -4
- package/src/html/canvas-screenshot.js +199 -0
- package/src/html/canvas-ui.css +5 -9
- package/src/html/canvas-ui.js +35 -27
- package/src/html/page.js +11 -37
- package/src/html/plugin-assets.js +33 -0
- package/src/html/plugin-ui.css +188 -0
- package/src/html/plugin-ui.js +51 -0
- package/src/html/runtime-api.js +41 -0
- package/src/html/runtime.js +164 -87
- package/src/server/agent.js +223 -0
- package/src/server/assets/clado-plugin-sdk.js +111 -0
- package/src/server/assets/library-canvas.js +14 -10
- package/src/server/assets/library-plugin-bridge.js +84 -0
- package/src/server/assets/library-plugins.css +39 -0
- package/src/server/assets/library-plugins.js +200 -0
- package/src/server/assets/library.css +8 -6
- package/src/server/assets/library.html +3 -13
- package/src/server/assets/library.js +280 -47
- package/src/server/canvas-capture.js +47 -0
- package/src/server/export.js +6 -3
- package/src/server/mcp.js +40 -17
- package/src/server/plugin-capabilities.js +188 -0
- package/src/server/plugin-settings.js +117 -0
- package/src/server/plugins.js +236 -0
- package/src/server/workspace.js +222 -29
- package/src/skill/install.js +1 -1
- package/src/skill/targets.js +3 -3
- package/src/util/update.js +3 -2
- package/src/vendor/html-to-image.min.js +24 -0
- package/src/workspace/service.js +21 -13
- package/src/workspace/storage.js +88 -20
- package/templates/business-flow.mdc +1 -1
- package/templates/call-chain.mdc +1 -1
- package/templates/data-design.mdc +1 -1
- package/src/server/assets/tree.js +0 -26
package/src/server/mcp.js
CHANGED
|
@@ -2,6 +2,8 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
|
2
2
|
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
3
3
|
import { z } from 'zod/v4';
|
|
4
4
|
import { VERSION } from '../util/version.js';
|
|
5
|
+
import { targetFields } from './plugin-capabilities.js';
|
|
6
|
+
import { captureMode, captureScope, captureTarget, isCaptureTarget } from './canvas-capture.js';
|
|
5
7
|
|
|
6
8
|
const text = () => z.string().max(2_000_000);
|
|
7
9
|
const path = () => z.array(z.string().min(1)).min(1).max(6).describe('读取结果返回的标题数组,保留完整文字;不拼接点号路径或内部ID。');
|
|
@@ -32,27 +34,34 @@ const nodeFields = {
|
|
|
32
34
|
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
|
|
33
35
|
};
|
|
34
36
|
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'];
|
|
35
|
-
function createServer(invoke) {
|
|
37
|
+
function createServer(invoke, invokeCapability) {
|
|
36
38
|
const server = new McpServer({ name: 'clado', version: VERSION }, { instructions: '每次必填workspace。工作区未初始化才调用init;需要目录时用inspect。先读模板prompt再创建.mdc。新建、追加和唯一原文编辑可以直接提交;覆盖、删除和按编号定位时带目标版本。项目模板写入使用expectedWorkspaceVersion;用户模板写入用expectedUserTemplateVersion,push需两者。每次响应返回全量diagnostics;操作成功仍可能valid:false。diagnosticsComplete:false表示未完成检查。dryRun的previewDiagnostics对应候选状态;写入results给出最终位置。文档操作使用MCP。' });
|
|
37
39
|
const schemas = new Map();
|
|
38
|
-
const enrich = (result, args) => {
|
|
40
|
+
const enrich = async (result, args) => {
|
|
39
41
|
const { diagnostics: _operationDiagnostics, error, ...payload } = result;
|
|
40
|
-
const report = invoke.diagnostics(args);
|
|
42
|
+
const report = await invoke.diagnostics(args);
|
|
41
43
|
return { ...(error ? { error } : {}), ...report, ...payload, valid: report.valid };
|
|
42
44
|
};
|
|
43
45
|
const encoded = (result, isError = false) => ({ ...(isError ? { isError: true } : {}), content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: result });
|
|
44
|
-
const failure = (error, args) => encoded(enrich({ error: { message: error.message, status: error.status || 500, code: error.details?.code || 'CLADO_OPERATION_FAILED', ...(error.details ? { details: error.details } : {}), ...(error.diagnostics?.length ? { operationDiagnostics: error.diagnostics } : {}) } }, args), true);
|
|
45
|
-
const
|
|
46
|
+
const failure = async (error, args) => encoded(await enrich({ error: { message: error.message, status: error.status || 500, code: error.details?.code || 'CLADO_OPERATION_FAILED', ...(error.details ? { details: error.details } : {}), ...(error.diagnostics?.length ? { operationDiagnostics: error.diagnostics } : {}) } }, args), true);
|
|
47
|
+
const capabilityResult = result => {
|
|
48
|
+
if (!isCaptureTarget(result.provider)) return encoded(result);
|
|
49
|
+
const { pngBase64, ...output } = result.output;
|
|
50
|
+
const reply = encoded({ ...result, output });
|
|
51
|
+
reply.content.push({ type: 'image', mimeType: 'image/png', data: pngBase64 });
|
|
52
|
+
return reply;
|
|
53
|
+
};
|
|
54
|
+
const register = (name, description, schema, handler = invoke, { encode = encoded, readOnly = false } = {}) => {
|
|
46
55
|
schemas.set(name, z.object({ workspace, ...schema }).strict());
|
|
47
56
|
return server.registerTool(name, {
|
|
48
|
-
description, inputSchema: { workspace, ...schema }, annotations: { readOnlyHint:
|
|
57
|
+
description, inputSchema: { workspace, ...schema }, annotations: { readOnlyHint: readOnly, destructiveHint: !readOnly, openWorldHint: false }
|
|
49
58
|
}, async args => {
|
|
50
|
-
try { return
|
|
51
|
-
catch (error) { return failure(error, args); }
|
|
59
|
+
try { return encode(await enrich(await handler(name, args), args)); }
|
|
60
|
+
catch (error) { return await failure(error, args); }
|
|
52
61
|
});
|
|
53
62
|
};
|
|
54
|
-
register('clado_workspace', '
|
|
55
|
-
action: z.enum(['init','inspect','search','validate','selection']), query: z.string().optional(), includeContent: z.boolean().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(100).optional()
|
|
63
|
+
register('clado_workspace', '初始化、查看工作区、列出子工作区、搜索或校验。用户说“我选的卡片”时用selection,按点选顺序读取标题路径、正文、后代和版本。selectionStatus为empty或stale时请用户选中或重新选择。inspect返回工作区版本和目录;workspaces列出当前服务范围内的子工作区;init准备工作区。', {
|
|
64
|
+
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()
|
|
56
65
|
});
|
|
57
66
|
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。修改模板不影响已有文档头部。', {
|
|
58
67
|
action: z.enum(['list','read','create','update','delete','pull','push']), scope: z.enum(['project','user']).optional(),
|
|
@@ -67,22 +76,36 @@ function createServer(invoke) {
|
|
|
67
76
|
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,均保留孩子。rename/move维护引用;delete有孩子需recursive。results返回最终位置。', {
|
|
68
77
|
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()
|
|
69
78
|
});
|
|
70
|
-
register('clado_links', 'list返回href、sourceText、nodeVersion、linkIndex(从1开始)及位置。connect用源file/node和目标targetFile/targetNode
|
|
79
|
+
register('clado_links', 'list返回href、sourceText、nodeVersion、linkIndex(从1开始)及位置。connect用源file/node和目标targetFile/targetNode建立连线:默认从具体内容行出发(用sourcePoint绑定代码行/表格行/Mermaid节点,或用position:{mode:replace,anchor:原文}把正文中的方法/步骤/字段词变成行内链接),不建议在卡片末尾单独追加裸的卡片连卡片。按段落、精确起点连接或disconnect需要节点或文件版本,精确落点需要文件或工作区版本。sourcePoint只用于同画布且与position/before/after互斥。disconnect用linkIndex只断一处,普通链接保留文字。', {
|
|
71
80
|
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()
|
|
72
81
|
});
|
|
73
82
|
register('clado_batch', '按顺序执行1–100个操作。支持可选的expectedWorkspaceVersion,各操作也可带自己的expectedFileVersion或expectedNodeVersion。每步的版本和标题路径按前序操作后的候选状态校验。模板操作使用工作区版本。任一冲突整批不保存;dryRun只预览。', {
|
|
74
83
|
expectedWorkspaceVersion: version, dryRun: z.boolean().optional(), operations: z.array(z.object({ type: z.enum(operations), ...nodeFields }).strict()).min(1).max(100)
|
|
75
84
|
});
|
|
76
|
-
|
|
85
|
+
if (invokeCapability) register('clado_capabilities', '查询和调用在线画布能力。list 每次读取实时注册的能力、版本、inputSchema 与 outputSchema,可用 to 过滤。call 使用 to:{pluginId,capability,major} 和 input;有多个标签页时传入 viewId。用户要求在画布里打开另一个文件时,调用 clado.directory 的 directory.open。', {
|
|
86
|
+
action: z.enum(['list', 'call']),
|
|
87
|
+
viewId: z.uuid().optional(),
|
|
88
|
+
to: z.strictObject(targetFields).optional(),
|
|
89
|
+
input: z.record(z.string(), z.unknown()).optional(),
|
|
90
|
+
}, (_, args) => invokeCapability(args), { encode: capabilityResult });
|
|
91
|
+
if (invokeCapability) register('clado_screenshot', '直接返回当前 Clado 画布的 PNG。默认保留已展开的分支和聚焦状态,scope:full 用于查看完整调用链。可用 mode 指定截图视图,source:latest 取本标签页最近一次截图。多个在线标签页时传 viewId。', {
|
|
92
|
+
viewId: z.uuid().optional(),
|
|
93
|
+
mode: z.enum(captureMode).optional(),
|
|
94
|
+
source: z.enum(['current', 'latest']).optional(),
|
|
95
|
+
scope: z.enum(captureScope).optional(),
|
|
96
|
+
}, (_, { workspace, viewId, mode, source, scope }) => invokeCapability({
|
|
97
|
+
workspace, viewId, action: 'call', to: captureTarget, input: { ...(mode && { mode }), ...(source && { source }), ...(scope && { scope }) },
|
|
98
|
+
}), { encode: capabilityResult, readOnly: true });
|
|
99
|
+
return { server, checkCall: async (name, args) => {
|
|
77
100
|
const schema = schemas.get(name);
|
|
78
|
-
if (!schema) return failure({ message: '没有这个工具:' + name, status: 400 }, args);
|
|
101
|
+
if (!schema) return await failure({ message: '没有这个工具:' + name, status: 400 }, args);
|
|
79
102
|
const checked = schema.safeParse(args);
|
|
80
|
-
if (!checked.success) return failure({ message: '工具参数不合法。', status: 400, details: { code: 'INVALID_ARGUMENTS', issues: checked.error.issues } }, args);
|
|
103
|
+
if (!checked.success) return await failure({ message: '工具参数不合法。', status: 400, details: { code: 'INVALID_ARGUMENTS', issues: checked.error.issues } }, args);
|
|
81
104
|
return null;
|
|
82
105
|
} };
|
|
83
106
|
}
|
|
84
107
|
|
|
85
|
-
export function createMcpHandler(invoke) {
|
|
108
|
+
export function createMcpHandler(invoke, invokeCapability) {
|
|
86
109
|
return async (req, res, url) => {
|
|
87
110
|
if (url.pathname !== '/mcp') return false;
|
|
88
111
|
const host = req.headers.host;
|
|
@@ -93,9 +116,9 @@ export function createMcpHandler(invoke) {
|
|
|
93
116
|
const chunks = []; let bytes = 0;
|
|
94
117
|
for await (const chunk of req) { bytes += chunk.length; if (bytes > 2_000_000) { res.writeHead(413).end('请求超过2MB。'); return true; } chunks.push(chunk); }
|
|
95
118
|
const data = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
96
|
-
const created = createServer(invoke); server = created.server;
|
|
119
|
+
const created = createServer(invoke, invokeCapability); server = created.server;
|
|
97
120
|
if (data.method === 'tools/call') {
|
|
98
|
-
const rejected = created.checkCall(data.params?.name, data.params?.arguments);
|
|
121
|
+
const rejected = await created.checkCall(data.params?.name, data.params?.arguments);
|
|
99
122
|
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; }
|
|
100
123
|
}
|
|
101
124
|
transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import Ajv from 'ajv';
|
|
3
|
+
import { z } from 'zod/v4';
|
|
4
|
+
import { fail } from '../workspace/storage.js';
|
|
5
|
+
import { captureBase64Limit, isCapturePng, isCaptureTarget } from './canvas-capture.js';
|
|
6
|
+
|
|
7
|
+
export const pluginId = z.string().max(128).regex(/^[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)+$/);
|
|
8
|
+
export const mountId = z.string().max(48).regex(/^[a-z][a-z0-9-]*$/);
|
|
9
|
+
export const capabilityId = pluginId;
|
|
10
|
+
const major = z.int().min(1);
|
|
11
|
+
const object = z.record(z.string(), z.unknown());
|
|
12
|
+
const jsonSchema = object.refine(value => value.type === 'object', '能力入参和出参必须为 JSON 对象');
|
|
13
|
+
export const capabilityDefinition = z.strictObject({
|
|
14
|
+
id: capabilityId,
|
|
15
|
+
mount: mountId,
|
|
16
|
+
version: z.string().max(32).regex(/^[1-9]\d{0,5}\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)$/),
|
|
17
|
+
description: z.string().trim().min(1).max(500),
|
|
18
|
+
inputSchema: jsonSchema,
|
|
19
|
+
outputSchema: jsonSchema,
|
|
20
|
+
exposeToAgent: z.boolean().default(false),
|
|
21
|
+
});
|
|
22
|
+
export const targetFields = { pluginId: pluginId.optional(), capability: capabilityId.optional(), major: major.optional() };
|
|
23
|
+
const target = z.strictObject({ ...targetFields, capability: capabilityId, major });
|
|
24
|
+
export const capabilityPermission = z.string().max(273).regex(/^capability\.call:[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)+\/[a-z][a-z0-9-]*(?:\.[a-z][a-z0-9-]*)+$/);
|
|
25
|
+
const keyOf = ({ pluginId, capability, major }) => JSON.stringify([pluginId, capability, major]);
|
|
26
|
+
|
|
27
|
+
export function compileCapabilities(id, mounts, definitions) {
|
|
28
|
+
const keys = new Set();
|
|
29
|
+
const ajv = new Ajv({ strict: true, addUsedSchema: false });
|
|
30
|
+
return definitions.map(raw => {
|
|
31
|
+
const { id: capability, mount: mountId, version, ...contract } = capabilityDefinition.parse(raw);
|
|
32
|
+
if (!mounts.some(mount => mount.id === mountId)) throw new Error('能力引用了不存在的挂载:' + mountId);
|
|
33
|
+
const descriptor = { pluginId: id, mountId, capability, version, major: Number(version.split('.')[0]), ...contract };
|
|
34
|
+
const key = keyOf(descriptor);
|
|
35
|
+
if (keys.has(key)) throw new Error('能力及其主版本重复:' + capability);
|
|
36
|
+
keys.add(key);
|
|
37
|
+
return { key, descriptor, input: ajv.compile(contract.inputSchema), output: ajv.compile(contract.outputSchema) };
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const fromBrowser = z.discriminatedUnion('action', [
|
|
42
|
+
z.strictObject({ action: z.literal('register'), pluginId, mountId }),
|
|
43
|
+
z.strictObject({ action: z.literal('list'), pluginId, mountId, query: z.strictObject(targetFields) }),
|
|
44
|
+
z.strictObject({ action: z.literal('call'), pluginId, mountId, to: target, input: object }),
|
|
45
|
+
z.strictObject({ action: z.literal('result'), callId: z.uuid(), output: z.unknown() }),
|
|
46
|
+
z.strictObject({ action: z.literal('error'), callId: z.uuid(), kind: z.enum([
|
|
47
|
+
'DOCUMENT_NOT_FOUND', 'VIEW_LOCKED', 'NAVIGATION_FAILED', 'NO_PROVIDER', 'PROVIDER_ERROR',
|
|
48
|
+
'CAPTURE_NOT_READY', 'CAPTURE_FAILED', 'NO_CAPTURE',
|
|
49
|
+
]), message: z.string().min(1).max(500) }),
|
|
50
|
+
]);
|
|
51
|
+
const agent = { kind: 'agent' };
|
|
52
|
+
const timeoutMs = 8000;
|
|
53
|
+
|
|
54
|
+
export function createCapabilityRegistry({
|
|
55
|
+
workspace, workspaceId, providers, grants,
|
|
56
|
+
resolveWorkspace = target => {
|
|
57
|
+
if (target !== workspace) fail('插件能力只绑定到当前 serve 工作区。', 403, { code: 'FORBIDDEN' });
|
|
58
|
+
return workspace;
|
|
59
|
+
},
|
|
60
|
+
providersFor = () => providers,
|
|
61
|
+
grantsFor = () => grants,
|
|
62
|
+
}) {
|
|
63
|
+
const views = new Map();
|
|
64
|
+
const matches = (query, descriptor) => Object.keys(targetFields).every(field => query[field] === undefined || query[field] === descriptor[field]);
|
|
65
|
+
const allowed = (caller, descriptor, targetGrants) => caller.kind === 'agent' ? descriptor.exposeToAgent :
|
|
66
|
+
caller.pluginId === descriptor.pluginId || targetGrants.get(caller.pluginId)?.includes('capability.call:' + descriptor.pluginId + '/' + descriptor.capability);
|
|
67
|
+
|
|
68
|
+
function list(query, caller, viewId, targetWorkspace = workspace) {
|
|
69
|
+
const targetGrants = grantsFor(targetWorkspace);
|
|
70
|
+
const eligible = viewId
|
|
71
|
+
? [views.get(viewId)].filter(view => view && view.workspace === targetWorkspace)
|
|
72
|
+
: [...views.values()].filter(view => view.workspace === targetWorkspace);
|
|
73
|
+
return {
|
|
74
|
+
views: eligible.map(view => ({
|
|
75
|
+
viewId: view.id,
|
|
76
|
+
capabilities: [...view.providers.values()].map(provider => provider.descriptor)
|
|
77
|
+
.filter(descriptor => matches(query, descriptor) && allowed(caller, descriptor, targetGrants)),
|
|
78
|
+
})),
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function finish(view, id, complete) {
|
|
83
|
+
const pending = view.pending.get(id);
|
|
84
|
+
if (!pending) return false;
|
|
85
|
+
view.pending.delete(id);
|
|
86
|
+
clearTimeout(pending.timer);
|
|
87
|
+
complete(pending);
|
|
88
|
+
return true;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function call(viewId, to, input, caller, targetWorkspace = workspace) {
|
|
92
|
+
const scopedViews = [...views.values()].filter(view => view.workspace === targetWorkspace);
|
|
93
|
+
if (!viewId && scopedViews.length > 1) fail('有多个 Clado 标签页在线,请传入 viewId。', 409, { code: 'AMBIGUOUS_VIEW' });
|
|
94
|
+
const matched = viewId ? views.get(viewId) : scopedViews[0];
|
|
95
|
+
const view = matched && matched.workspace === targetWorkspace ? matched : null;
|
|
96
|
+
if (!view) fail('目标 Clado 标签页未连接,请打开工作区页面。', 409, { code: 'VIEW_UNAVAILABLE' });
|
|
97
|
+
const targetGrants = grantsFor(view.workspace);
|
|
98
|
+
const candidates = [...view.providers.values()].filter(({ descriptor }) => matches({ ...to, major: undefined }, descriptor));
|
|
99
|
+
const visible = candidates.filter(({ descriptor }) => allowed(caller, descriptor, targetGrants));
|
|
100
|
+
if (candidates.length && !visible.length) fail('没有调用该能力的权限。', 403, { code: 'FORBIDDEN' });
|
|
101
|
+
const compatible = visible.filter(({ descriptor }) => descriptor.major === to.major);
|
|
102
|
+
if (!compatible.length) fail(visible.length ? '能力主版本不匹配。' : '当前标签页没有注册该能力。', 404, { code: visible.length ? 'UNSUPPORTED_VERSION' : 'NO_PROVIDER' });
|
|
103
|
+
if (compatible.length !== 1) fail('多个插件提供此能力,请指定 pluginId。', 409, { code: 'AMBIGUOUS_PROVIDER' });
|
|
104
|
+
const [provider] = compatible;
|
|
105
|
+
if (!provider.input(input)) fail('能力入参不符合约定。', 400, { code: 'INVALID_INPUT', issues: provider.input.errors });
|
|
106
|
+
if (view.pending.size >= 24) fail('当前标签页能力调用过多。', 429, { code: 'VIEW_BUSY' });
|
|
107
|
+
const id = randomUUID();
|
|
108
|
+
const { descriptor } = provider;
|
|
109
|
+
const waitMs = isCaptureTarget(descriptor) ? 40000 : timeoutMs;
|
|
110
|
+
return new Promise((resolve, reject) => {
|
|
111
|
+
const timer = setTimeout(() => finish(view, id, ({ reject }) =>
|
|
112
|
+
reject(Object.assign(new Error('等待插件响应超时。'), { status: 504, details: { code: 'CAPABILITY_TIMEOUT' } }))), waitMs);
|
|
113
|
+
view.pending.set(id, { resolve, reject, timer, provider });
|
|
114
|
+
view.send('call', {
|
|
115
|
+
id, from: caller,
|
|
116
|
+
to: { pluginId: descriptor.pluginId, mountId: descriptor.mountId, capability: descriptor.capability, major: descriptor.major },
|
|
117
|
+
scope: { workspaceId: view.workspaceId, viewId: view.id }, input,
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function connect(id, res, viewWorkspace = workspace, viewWorkspaceId = workspaceId) {
|
|
123
|
+
if (views.has(id) || views.size >= 64) fail('标签页已连接或已达到连接上限。', 409);
|
|
124
|
+
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store, no-transform', 'x-content-type-options': 'nosniff' });
|
|
125
|
+
const send = (event, data) => res.write('event: ' + event + '\ndata: ' + JSON.stringify(data) + '\n\n');
|
|
126
|
+
const view = { id, workspace: viewWorkspace, workspaceId: viewWorkspaceId, send, res, providers: new Map(), pending: new Map() };
|
|
127
|
+
views.set(id, view);
|
|
128
|
+
const heartbeat = setInterval(() => res.write(': heartbeat\n\n'), 15000);
|
|
129
|
+
res.on('close', () => {
|
|
130
|
+
clearInterval(heartbeat);
|
|
131
|
+
views.delete(id);
|
|
132
|
+
for (const callId of view.pending.keys()) finish(view, callId, ({ reject }) =>
|
|
133
|
+
reject(Object.assign(new Error('插件所在的标签页已断开。'), { status: 409, details: { code: 'VIEW_UNAVAILABLE' } })));
|
|
134
|
+
});
|
|
135
|
+
send('ready', { viewId: id, workspaceId: viewWorkspaceId });
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function receive(id, body) {
|
|
139
|
+
const view = views.get(id);
|
|
140
|
+
if (!view) fail('标签页连接已断开。', 409, { code: 'VIEW_UNAVAILABLE' });
|
|
141
|
+
const parsed = fromBrowser.safeParse(body);
|
|
142
|
+
if (!parsed.success) fail('插件消息参数不合法。', 400, { code: 'INVALID_PARAMS', issues: parsed.error.issues });
|
|
143
|
+
const message = parsed.data;
|
|
144
|
+
if (message.action === 'result' || message.action === 'error') {
|
|
145
|
+
finish(view, message.callId, ({ provider, resolve, reject }) => {
|
|
146
|
+
if (message.action === 'error') {
|
|
147
|
+
const status = { DOCUMENT_NOT_FOUND: 404, VIEW_LOCKED: 409, NAVIGATION_FAILED: 502, NO_PROVIDER: 404, CAPTURE_NOT_READY: 409, NO_CAPTURE: 404 }[message.kind] || 502;
|
|
148
|
+
reject(Object.assign(new Error(message.message), { status, details: { code: message.kind } }));
|
|
149
|
+
} else if (!provider.output(message.output)) {
|
|
150
|
+
reject(Object.assign(new Error('插件输出不符合出参约定。'), { status: 502, details: { code: 'INVALID_OUTPUT', issues: provider.output.errors } }));
|
|
151
|
+
} else if (isCaptureTarget(provider.descriptor) && !isCapturePng(message.output)) {
|
|
152
|
+
reject(Object.assign(new Error('截图不是有效的 PNG。'), { status: 502, details: { code: 'INVALID_OUTPUT' } }));
|
|
153
|
+
} else {
|
|
154
|
+
const { pluginId, mountId, capability, version } = provider.descriptor;
|
|
155
|
+
resolve({ viewId: id, provider: { pluginId, mountId, capability }, version, output: message.output });
|
|
156
|
+
}
|
|
157
|
+
});
|
|
158
|
+
return {};
|
|
159
|
+
}
|
|
160
|
+
const targetGrants = grantsFor(view.workspace);
|
|
161
|
+
const targetProviders = providersFor(view.workspace);
|
|
162
|
+
if (!targetGrants.has(message.pluginId)) fail('插件未启用。', 403, { code: 'FORBIDDEN' });
|
|
163
|
+
if (message.action === 'register') {
|
|
164
|
+
const declared = targetProviders.filter(({ descriptor }) => descriptor.pluginId === message.pluginId && descriptor.mountId === message.mountId);
|
|
165
|
+
if (!declared.length) fail('该挂载未声明可注册的能力。', 400, { code: 'NO_PROVIDER' });
|
|
166
|
+
for (const provider of declared) view.providers.set(provider.key, provider);
|
|
167
|
+
return { capabilities: declared.map(provider => provider.descriptor) };
|
|
168
|
+
}
|
|
169
|
+
const caller = { kind: 'plugin', pluginId: message.pluginId, mountId: message.mountId };
|
|
170
|
+
if (message.action === 'list') return list(message.query, caller, id, view.workspace);
|
|
171
|
+
return await call(id, message.to, message.input, caller, view.workspace);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
return {
|
|
175
|
+
connect, receive,
|
|
176
|
+
captureResultLimit(viewId, callId) {
|
|
177
|
+
return isCaptureTarget(views.get(viewId)?.pending.get(callId)?.provider.descriptor) ? captureBase64Limit + 65536 : 0;
|
|
178
|
+
},
|
|
179
|
+
close() { for (const view of views.values()) view.res.end(); },
|
|
180
|
+
async invoke(args) {
|
|
181
|
+
const targetWorkspace = resolveWorkspace(args.workspace);
|
|
182
|
+
if (args.action === 'list') return list(args.to || {}, agent, args.viewId, targetWorkspace);
|
|
183
|
+
const parsed = target.safeParse(args.to);
|
|
184
|
+
if (!parsed.success || !args.input) fail('调用能力需要 to.capability、to.major 和 input。', 400, { code: 'INVALID_PARAMS' });
|
|
185
|
+
return await call(args.viewId, parsed.data, args.input, agent, targetWorkspace);
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
}
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import Ajv from 'ajv';
|
|
4
|
+
import { z } from 'zod/v4';
|
|
5
|
+
import { locked, safeFile, fail } from '../workspace/storage.js';
|
|
6
|
+
import { userTemplatePaths } from '../skill/templates.js';
|
|
7
|
+
|
|
8
|
+
const object = z.record(z.string(), z.unknown());
|
|
9
|
+
export const pluginConfiguration = z.strictObject({
|
|
10
|
+
schema: object.refine(schema => schema.type === 'object'),
|
|
11
|
+
defaults: object.default({}),
|
|
12
|
+
});
|
|
13
|
+
const specs = {
|
|
14
|
+
'clado.brand': { showScreenshot: { type: 'boolean' } },
|
|
15
|
+
'clado.view-controls': { defaultMode: { enum: ['cards', 'mindmap', 'doc'] } },
|
|
16
|
+
'clado.directory': { showFilename: { type: 'boolean' } },
|
|
17
|
+
'clado.agent': {
|
|
18
|
+
name: { type: 'string', minLength: 1, maxLength: 80 },
|
|
19
|
+
command: { type: 'string', minLength: 1, maxLength: 2048, pattern: '^.+' },
|
|
20
|
+
args: { type: 'array', maxItems: 32, items: { type: 'string', maxLength: 2048 } },
|
|
21
|
+
env: { type: 'object', maxProperties: 32, additionalProperties: { type: 'string', maxLength: 2048 } },
|
|
22
|
+
placeholder: { type: 'string', minLength: 1, maxLength: 120 },
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
const defaults = {
|
|
26
|
+
'clado.brand': { showScreenshot: true },
|
|
27
|
+
'clado.directory': { showFilename: true },
|
|
28
|
+
'clado.agent': { name: 'ZCode', command: process.env.CLADO_ZCODE_ACP_PATH || 'zcode-acp-server', args: [], env: {}, placeholder: '写下一个想法…' },
|
|
29
|
+
};
|
|
30
|
+
const fileName = 'plugin-settings.json';
|
|
31
|
+
const maxBytes = 1024 * 1024;
|
|
32
|
+
|
|
33
|
+
export function compileConfiguration(config) {
|
|
34
|
+
const { schema, defaults } = config || { schema: { type: 'object' }, defaults: {} };
|
|
35
|
+
const validate = new Ajv({ strict: true, addUsedSchema: false, allErrors: true }).compile(schema);
|
|
36
|
+
return { schema, defaults, validate };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function createPluginSettings(ctx, extensions) {
|
|
40
|
+
const userState = userTemplatePaths().state;
|
|
41
|
+
const agentId = 'clado.agent';
|
|
42
|
+
const location = id => id === agentId ? { root: userState, name: 'inspiration.json', label: '用户目录 / inspiration.json' }
|
|
43
|
+
: { root: ctx.state, name: fileName, label: '.clado/' + fileName };
|
|
44
|
+
const contracts = new Map(Object.entries(specs).map(([id, properties]) => [
|
|
45
|
+
id, compileConfiguration({ schema: { type: 'object', properties, additionalProperties: false }, defaults: defaults[id] || {} }),
|
|
46
|
+
]));
|
|
47
|
+
for (const [id, config] of extensions || []) contracts.set(id, config);
|
|
48
|
+
|
|
49
|
+
function readFile({ root, name, label }) {
|
|
50
|
+
if (!existsSync(root)) return {};
|
|
51
|
+
const path = safeFile(root, name, 'settings');
|
|
52
|
+
if (!existsSync(path)) return {};
|
|
53
|
+
const stat = lstatSync(path);
|
|
54
|
+
if (!stat.isFile() || stat.size > maxBytes) fail('插件配置文件类型或大小不符合要求。', 422);
|
|
55
|
+
let data;
|
|
56
|
+
try { data = JSON.parse(readFileSync(path, 'utf8')); }
|
|
57
|
+
catch { fail('请先修复 ' + label + ' 中的 JSON 语法。', 422); }
|
|
58
|
+
if (!object.safeParse(data).success) fail('插件配置文件顶层应是 JSON 对象。', 422);
|
|
59
|
+
return data;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function effective(contract, value) {
|
|
63
|
+
if (!object.safeParse(value).success) fail('插件设置必须是 JSON 对象。', 400);
|
|
64
|
+
const settings = { ...contract.defaults, ...value };
|
|
65
|
+
if (Buffer.byteLength(JSON.stringify(settings)) > 65536) fail('单个插件的配置不能超过 64 KB。', 413);
|
|
66
|
+
if (!contract.validate(settings)) {
|
|
67
|
+
const issues = contract.validate.errors.map(issue => (issue.instancePath || '/') + ' ' + issue.message);
|
|
68
|
+
fail('配置校验失败:' + issues.join(';'), 422);
|
|
69
|
+
}
|
|
70
|
+
return settings;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function read(id) {
|
|
74
|
+
const contract = contracts.get(id);
|
|
75
|
+
if (!contract) fail('没有这个插件。', 404);
|
|
76
|
+
const target = location(id), file = readFile(target);
|
|
77
|
+
const value = id === agentId ? { ...contract.defaults, ...file }
|
|
78
|
+
: Object.hasOwn(file, id) ? file[id] : contract.defaults;
|
|
79
|
+
return { value, defaults: contract.defaults, schema: contract.schema, path: target.label };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
register(id, config) { contracts.set(id, config); },
|
|
84
|
+
agentLaunch() { return effective(contracts.get(agentId), read(agentId).value); },
|
|
85
|
+
values() {
|
|
86
|
+
let file;
|
|
87
|
+
try { file = readFile(location()); } catch { file = {}; }
|
|
88
|
+
return Object.fromEntries([...contracts].map(([id, contract]) => {
|
|
89
|
+
try {
|
|
90
|
+
const settings = effective(contract, id === agentId ? read(id).value : Object.hasOwn(file, id) ? file[id] : {});
|
|
91
|
+
return [id, id === agentId ? { name: settings.name, placeholder: settings.placeholder } : settings];
|
|
92
|
+
}
|
|
93
|
+
catch { return [id, id === agentId ? { name: contract.defaults.name, placeholder: contract.defaults.placeholder } : contract.defaults]; }
|
|
94
|
+
}));
|
|
95
|
+
},
|
|
96
|
+
read,
|
|
97
|
+
save(id, value, expected) {
|
|
98
|
+
const target = location(id);
|
|
99
|
+
const save = () => {
|
|
100
|
+
const current = read(id);
|
|
101
|
+
if (JSON.stringify(current.value) !== JSON.stringify(expected)) fail('配置已被修改,请关闭后重新打开设置。', 409);
|
|
102
|
+
effective(contracts.get(id), value);
|
|
103
|
+
const next = JSON.stringify(id === agentId ? value : { ...readFile(target), [id]: value }, null, 2) + '\n';
|
|
104
|
+
if (Buffer.byteLength(next) > maxBytes) fail('插件配置文件太大。', 413);
|
|
105
|
+
if (!existsSync(target.root)) mkdirSync(target.root, { recursive: true, mode: 0o700 });
|
|
106
|
+
const path = safeFile(target.root, target.name, 'settings');
|
|
107
|
+
const temp = path + '.' + randomUUID() + '.tmp';
|
|
108
|
+
try {
|
|
109
|
+
writeFileSync(temp, next, { flag: 'wx', mode: 0o600 });
|
|
110
|
+
renameSync(temp, path);
|
|
111
|
+
} finally { rmSync(temp, { force: true }); }
|
|
112
|
+
return read(id);
|
|
113
|
+
};
|
|
114
|
+
return locked(id === agentId ? { ...ctx, state: target.root } : ctx, save);
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
}
|