cladogram 0.5.3 → 0.5.4

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.
Files changed (46) hide show
  1. package/README.md +19 -0
  2. package/bin/clado.js +13 -2
  3. package/docs/plugin-development.md +135 -0
  4. package/docs/plugin-ui.md +43 -0
  5. package/docs/release.md +7 -0
  6. package/package.json +7 -1
  7. package/plugins/agent/index.js +181 -0
  8. package/plugins/agent/style.css +105 -0
  9. package/plugins/brand/index.js +262 -0
  10. package/plugins/brand/style.css +162 -0
  11. package/plugins/directory/capabilities.json +27 -0
  12. package/plugins/directory/index.js +146 -0
  13. package/plugins/directory/style.css +48 -0
  14. package/plugins/view-controls/index.js +58 -0
  15. package/plugins/view-controls/style.css +46 -0
  16. package/skills/clado/SKILL.md +4 -0
  17. package/src/html/app-css.js +9 -40
  18. package/src/html/canvas-chain.js +5 -6
  19. package/src/html/canvas-focus.js +2 -4
  20. package/src/html/canvas-screenshot.js +199 -0
  21. package/src/html/canvas-ui.css +5 -9
  22. package/src/html/canvas-ui.js +35 -27
  23. package/src/html/page.js +11 -37
  24. package/src/html/plugin-assets.js +33 -0
  25. package/src/html/plugin-ui.css +176 -0
  26. package/src/html/plugin-ui.js +45 -0
  27. package/src/html/runtime-api.js +41 -0
  28. package/src/html/runtime.js +15 -12
  29. package/src/server/agent.js +222 -0
  30. package/src/server/assets/clado-plugin-sdk.js +111 -0
  31. package/src/server/assets/library-canvas.js +12 -9
  32. package/src/server/assets/library-plugin-bridge.js +84 -0
  33. package/src/server/assets/library-plugins.css +39 -0
  34. package/src/server/assets/library-plugins.js +200 -0
  35. package/src/server/assets/library.css +3 -6
  36. package/src/server/assets/library.html +2 -12
  37. package/src/server/assets/library.js +227 -44
  38. package/src/server/canvas-capture.js +47 -0
  39. package/src/server/export.js +5 -2
  40. package/src/server/mcp.js +29 -6
  41. package/src/server/plugin-capabilities.js +172 -0
  42. package/src/server/plugin-settings.js +117 -0
  43. package/src/server/plugins.js +236 -0
  44. package/src/server/workspace.js +127 -11
  45. package/src/vendor/html-to-image.min.js +24 -0
  46. package/src/server/assets/tree.js +0 -26
@@ -0,0 +1,47 @@
1
+ export const captureTarget = { pluginId: 'clado.host', capability: 'canvas.capture', major: 1 };
2
+ export const captureMode = ['cards', 'mindmap', 'doc'];
3
+ export const captureScope = ['current', 'full'];
4
+ export const captureBase64Limit = Math.ceil(4 * 1024 * 1024 / 3) * 4;
5
+ export const captureDefinition = {
6
+ id: captureTarget.capability,
7
+ mount: 'canvas',
8
+ version: '1.0.0',
9
+ description: '截取当前画布的 PNG,默认保留展开和聚焦状态,可指定视图、展开全图或读取最近一次截图。',
10
+ exposeToAgent: true,
11
+ inputSchema: {
12
+ type: 'object',
13
+ properties: {
14
+ mode: { enum: captureMode },
15
+ source: { enum: ['current', 'latest'] },
16
+ scope: { enum: captureScope },
17
+ },
18
+ additionalProperties: false,
19
+ },
20
+ outputSchema: {
21
+ type: 'object',
22
+ properties: {
23
+ file: { type: 'string', minLength: 1, maxLength: 1500 },
24
+ revision: { type: 'string', pattern: '^[a-f0-9]{64}$' },
25
+ mode: { enum: captureMode },
26
+ width: { type: 'integer', minimum: 1, maximum: 4096 },
27
+ height: { type: 'integer', minimum: 1, maximum: 4096 },
28
+ layoutWidth: { type: 'integer', minimum: 1 },
29
+ layoutHeight: { type: 'integer', minimum: 1 },
30
+ pngBase64: { type: 'string', maxLength: captureBase64Limit, minLength: 32 },
31
+ },
32
+ required: ['file', 'revision', 'mode', 'width', 'height', 'layoutWidth', 'layoutHeight', 'pngBase64'],
33
+ additionalProperties: false,
34
+ },
35
+ };
36
+
37
+ export function isCaptureTarget(provider) {
38
+ return provider?.pluginId === captureTarget.pluginId && provider.capability === captureTarget.capability;
39
+ }
40
+
41
+ export function isCapturePng(output) {
42
+ const png = Buffer.from(output.pngBase64, 'base64');
43
+ return png.length >= 33 && png.length <= 4 * 1024 * 1024 &&
44
+ png.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')) &&
45
+ png.toString('ascii', 12, 16) === 'IHDR' &&
46
+ png.readUInt32BE(16) === output.width && png.readUInt32BE(20) === output.height;
47
+ }
@@ -2,6 +2,7 @@ import { readFileSync, existsSync } from 'node:fs';
2
2
  import { dirname, join, relative, resolve, basename } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { renderHtml } from '../html/page.js';
5
+ import { pluginMarkup } from '../html/plugin-assets.js';
5
6
  import { workspacePath } from '../workspace/documents.js';
6
7
  const assets=join(dirname(fileURLToPath(import.meta.url)),'assets');
7
8
  const read=name=>readFileSync(join(assets,name),'utf8');
@@ -32,7 +33,7 @@ export function renderWorkspace(jobs,{root,entry,mode='mindmap',theme='light',ti
32
33
  if(existsSync(path))resources[name]='data:'+type+';base64,'+readFileSync(path).toString('base64');
33
34
  }catch{}
34
35
  }
35
- let html=renderHtml(job.doc,job.diagnostics,{file,title:job.doc.title,mode,theme,library:true});
36
+ let html=renderHtml(job.doc,job.diagnostics,{file,title:job.doc.title,mode,theme,library:true,workspaceChrome:true});
36
37
  const end=html.lastIndexOf('</body>');
37
38
  const boot='window.__CLADO_OFFLINE__=true;window.__CLADO_FILE_PATH__='+json(file)+';window.__CLADO_WORKSPACE_INDEX__='+json(index)+';window.__CLADO_RESOURCES__='+json(resources)+';';
38
39
  html=html.slice(0,end)+script(boot)+script(read('library-canvas.js'))+html.slice(end);
@@ -46,7 +47,9 @@ export function renderWorkspace(jobs,{root,entry,mode='mindmap',theme='light',ti
46
47
  }
47
48
  let html=read('library.html');
48
49
  html=html.replace('<link rel="stylesheet" href="library.css">',()=>'<style>'+read('library.css')+'</style>');
49
- html=html.replace('<script src="/tree.js"></script>',()=>script(read('tree.js')));
50
+ const plugins = pluginMarkup({ workspace: true, inline: true });
51
+ html = html.replace('<!--CLADO-PLUGIN-STYLES-->', () => plugins.styles)
52
+ .replace('<!--CLADO-PLUGIN-SCRIPTS-->', () => plugins.scripts);
50
53
  html=html.replace('<script src="library.js"></script>',()=>script('window.__CLADO_WORKSPACE__='+json({entry,mode,theme,offline:{index,canvases,sources,shared}})+';')+script(read('library.js')));
51
54
  html=html.replace('<title>Clado · Markdown 目录预览</title>','<title>'+String(title || 'Clado').replace(/[&<>]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;'}[c]))+'</title>');
52
55
  return html;
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,7 +34,7 @@ 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
40
  const enrich = (result, args) => {
@@ -42,12 +44,19 @@ function createServer(invoke) {
42
44
  };
43
45
  const encoded = (result, isError = false) => ({ ...(isError ? { isError: true } : {}), content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: result });
44
46
  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 register = (name, description, schema) => {
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: false, destructiveHint: true, openWorldHint: false }
57
+ description, inputSchema: { workspace, ...schema }, annotations: { readOnlyHint: readOnly, destructiveHint: !readOnly, openWorldHint: false }
49
58
  }, async args => {
50
- try { return encoded(enrich(invoke(name, args), args)); }
59
+ try { return encode(enrich(await handler(name, args), args)); }
51
60
  catch (error) { return failure(error, args); }
52
61
  });
53
62
  };
@@ -73,6 +82,20 @@ function createServer(invoke) {
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
  });
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 });
76
99
  return { server, checkCall: (name, args) => {
77
100
  const schema = schemas.get(name);
78
101
  if (!schema) return failure({ message: '没有这个工具:' + name, status: 400 }, args);
@@ -82,7 +105,7 @@ function createServer(invoke) {
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,7 +116,7 @@ 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
121
  const rejected = 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; }
@@ -0,0 +1,172 @@
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({ workspace, workspaceId, providers, grants }) {
55
+ const views = new Map();
56
+ const matches = (query, descriptor) => Object.keys(targetFields).every(field => query[field] === undefined || query[field] === descriptor[field]);
57
+ const allowed = (caller, descriptor) => caller.kind === 'agent' ? descriptor.exposeToAgent :
58
+ caller.pluginId === descriptor.pluginId || grants.get(caller.pluginId)?.includes('capability.call:' + descriptor.pluginId + '/' + descriptor.capability);
59
+
60
+ function list(query, caller, viewId) {
61
+ const eligible = viewId ? [views.get(viewId)].filter(Boolean) : [...views.values()];
62
+ return {
63
+ views: eligible.map(view => ({
64
+ viewId: view.id,
65
+ capabilities: [...view.providers.values()].map(provider => provider.descriptor)
66
+ .filter(descriptor => matches(query, descriptor) && allowed(caller, descriptor)),
67
+ })),
68
+ };
69
+ }
70
+
71
+ function finish(view, id, complete) {
72
+ const pending = view.pending.get(id);
73
+ if (!pending) return false;
74
+ view.pending.delete(id);
75
+ clearTimeout(pending.timer);
76
+ complete(pending);
77
+ return true;
78
+ }
79
+
80
+ async function call(viewId, to, input, caller) {
81
+ if (!viewId && views.size > 1) fail('有多个 Clado 标签页在线,请传入 viewId。', 409, { code: 'AMBIGUOUS_VIEW' });
82
+ const view = viewId ? views.get(viewId) : views.values().next().value;
83
+ if (!view) fail('目标 Clado 标签页未连接,请打开工作区页面。', 409, { code: 'VIEW_UNAVAILABLE' });
84
+ const candidates = [...view.providers.values()].filter(({ descriptor }) => matches({ ...to, major: undefined }, descriptor));
85
+ const visible = candidates.filter(({ descriptor }) => allowed(caller, descriptor));
86
+ if (candidates.length && !visible.length) fail('没有调用该能力的权限。', 403, { code: 'FORBIDDEN' });
87
+ const compatible = visible.filter(({ descriptor }) => descriptor.major === to.major);
88
+ if (!compatible.length) fail(visible.length ? '能力主版本不匹配。' : '当前标签页没有注册该能力。', 404, { code: visible.length ? 'UNSUPPORTED_VERSION' : 'NO_PROVIDER' });
89
+ if (compatible.length !== 1) fail('多个插件提供此能力,请指定 pluginId。', 409, { code: 'AMBIGUOUS_PROVIDER' });
90
+ const [provider] = compatible;
91
+ if (!provider.input(input)) fail('能力入参不符合约定。', 400, { code: 'INVALID_INPUT', issues: provider.input.errors });
92
+ if (view.pending.size >= 24) fail('当前标签页能力调用过多。', 429, { code: 'VIEW_BUSY' });
93
+ const id = randomUUID();
94
+ const { descriptor } = provider;
95
+ const waitMs = isCaptureTarget(descriptor) ? 40000 : timeoutMs;
96
+ return new Promise((resolve, reject) => {
97
+ const timer = setTimeout(() => finish(view, id, ({ reject }) =>
98
+ reject(Object.assign(new Error('等待插件响应超时。'), { status: 504, details: { code: 'CAPABILITY_TIMEOUT' } }))), waitMs);
99
+ view.pending.set(id, { resolve, reject, timer, provider });
100
+ view.send('call', {
101
+ id, from: caller,
102
+ to: { pluginId: descriptor.pluginId, mountId: descriptor.mountId, capability: descriptor.capability, major: descriptor.major },
103
+ scope: { workspaceId, viewId: view.id }, input,
104
+ });
105
+ });
106
+ }
107
+
108
+ function connect(id, res) {
109
+ if (views.has(id) || views.size >= 32) fail('标签页已连接或已达到连接上限。', 409);
110
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store, no-transform', 'x-content-type-options': 'nosniff' });
111
+ const send = (event, data) => res.write('event: ' + event + '\ndata: ' + JSON.stringify(data) + '\n\n');
112
+ const view = { id, send, res, providers: new Map(), pending: new Map() };
113
+ views.set(id, view);
114
+ const heartbeat = setInterval(() => res.write(': heartbeat\n\n'), 15000);
115
+ res.on('close', () => {
116
+ clearInterval(heartbeat);
117
+ views.delete(id);
118
+ for (const callId of view.pending.keys()) finish(view, callId, ({ reject }) =>
119
+ reject(Object.assign(new Error('插件所在的标签页已断开。'), { status: 409, details: { code: 'VIEW_UNAVAILABLE' } })));
120
+ });
121
+ send('ready', { viewId: id, workspaceId });
122
+ }
123
+
124
+ async function receive(id, body) {
125
+ const view = views.get(id);
126
+ if (!view) fail('标签页连接已断开。', 409, { code: 'VIEW_UNAVAILABLE' });
127
+ const parsed = fromBrowser.safeParse(body);
128
+ if (!parsed.success) fail('插件消息参数不合法。', 400, { code: 'INVALID_PARAMS', issues: parsed.error.issues });
129
+ const message = parsed.data;
130
+ if (message.action === 'result' || message.action === 'error') {
131
+ finish(view, message.callId, ({ provider, resolve, reject }) => {
132
+ if (message.action === 'error') {
133
+ 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;
134
+ reject(Object.assign(new Error(message.message), { status, details: { code: message.kind } }));
135
+ } else if (!provider.output(message.output)) {
136
+ reject(Object.assign(new Error('插件输出不符合出参约定。'), { status: 502, details: { code: 'INVALID_OUTPUT', issues: provider.output.errors } }));
137
+ } else if (isCaptureTarget(provider.descriptor) && !isCapturePng(message.output)) {
138
+ reject(Object.assign(new Error('截图不是有效的 PNG。'), { status: 502, details: { code: 'INVALID_OUTPUT' } }));
139
+ } else {
140
+ const { pluginId, mountId, capability, version } = provider.descriptor;
141
+ resolve({ viewId: id, provider: { pluginId, mountId, capability }, version, output: message.output });
142
+ }
143
+ });
144
+ return {};
145
+ }
146
+ if (!grants.has(message.pluginId)) fail('插件未启用。', 403, { code: 'FORBIDDEN' });
147
+ if (message.action === 'register') {
148
+ const declared = providers.filter(({ descriptor }) => descriptor.pluginId === message.pluginId && descriptor.mountId === message.mountId);
149
+ if (!declared.length) fail('该挂载未声明可注册的能力。', 400, { code: 'NO_PROVIDER' });
150
+ for (const provider of declared) view.providers.set(provider.key, provider);
151
+ return { capabilities: declared.map(provider => provider.descriptor) };
152
+ }
153
+ const caller = { kind: 'plugin', pluginId: message.pluginId, mountId: message.mountId };
154
+ if (message.action === 'list') return list(message.query, caller, id);
155
+ return await call(id, message.to, message.input, caller);
156
+ }
157
+
158
+ return {
159
+ connect, receive,
160
+ captureResultLimit(viewId, callId) {
161
+ return isCaptureTarget(views.get(viewId)?.pending.get(callId)?.provider.descriptor) ? captureBase64Limit + 65536 : 0;
162
+ },
163
+ close() { for (const view of views.values()) view.res.end(); },
164
+ async invoke(args) {
165
+ if (args.workspace !== workspace) fail('插件能力只绑定到当前 serve 工作区。', 403, { code: 'FORBIDDEN' });
166
+ if (args.action === 'list') return list(args.to || {}, agent, args.viewId);
167
+ const parsed = target.safeParse(args.to);
168
+ if (!parsed.success || !args.input) fail('调用能力需要 to.capability、to.major 和 input。', 400, { code: 'INVALID_PARAMS' });
169
+ return await call(args.viewId, parsed.data, args.input, agent);
170
+ },
171
+ };
172
+ }
@@ -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: ['mindmap', 'cards', '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
+ }