cladogram 0.5.2 → 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 (51) hide show
  1. package/README.md +30 -2
  2. package/bin/clado.js +55 -3
  3. package/docs/plugin-development.md +135 -0
  4. package/docs/plugin-ui.md +43 -0
  5. package/docs/release.md +26 -0
  6. package/package.json +8 -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 +31 -17
  17. package/src/html/app-css.js +11 -42
  18. package/src/html/canvas-chain.js +5 -6
  19. package/src/html/canvas-focus.js +3 -4
  20. package/src/html/canvas-screenshot.js +199 -0
  21. package/src/html/canvas-ui.css +37 -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 +47 -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 +72 -11
  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 +280 -44
  38. package/src/server/canvas-capture.js +47 -0
  39. package/src/server/export.js +5 -2
  40. package/src/server/mcp.js +44 -19
  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 +157 -12
  45. package/src/skill/targets.js +1 -1
  46. package/src/util/update.js +58 -0
  47. package/src/vendor/html-to-image.min.js +24 -0
  48. package/src/workspace/content.js +3 -2
  49. package/src/workspace/service.js +81 -21
  50. package/src/workspace/tree.js +38 -0
  51. package/src/server/assets/tree.js +0 -26
@@ -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
+ }
@@ -0,0 +1,236 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { join, extname } from 'node:path';
4
+ import semver from 'semver';
5
+ import { z } from 'zod/v4';
6
+ import { VERSION } from '../util/version.js';
7
+ import { DocumentError } from '../workspace/documents.js';
8
+ import { capabilityDefinition, capabilityPermission, compileCapabilities, mountId, pluginId } from './plugin-capabilities.js';
9
+ import { captureDefinition } from './canvas-capture.js';
10
+ import { compileConfiguration, pluginConfiguration } from './plugin-settings.js';
11
+ import { locked, fail } from '../workspace/storage.js';
12
+
13
+ export const PLUGIN_PROTOCOL = '1.0';
14
+ export const PLUGIN_SLOTS = ['topbar', 'bottombar', 'sidebar', 'bottom-left', 'canvas-overlay', 'top-left', 'top-right', 'bottom-right'];
15
+ export const PLUGIN_FIELDS = ['document', 'selection', 'graph', 'viewport'];
16
+ const ASSETS = '/library/plugin-assets/';
17
+ const SDK = '/clado-plugin-sdk.js';
18
+ const UI_CSS = '/plugin-ui.css';
19
+ const segment = /^[a-zA-Z0-9_-][a-zA-Z0-9_.-]*$/;
20
+ const uiPath = /^ui\/(?:[a-zA-Z0-9_-][a-zA-Z0-9_.-]*\/)*[a-zA-Z0-9_-][a-zA-Z0-9_.-]*\.html$/;
21
+ const permission = z.enum([
22
+ ...PLUGIN_SLOTS.map(slot => 'ui.mount:' + slot),
23
+ ...PLUGIN_FIELDS.map(field => 'canvas.' + field + '.read'),
24
+ ]);
25
+ const manifest = z.strictObject({
26
+ manifestVersion: z.literal(1),
27
+ id: pluginId,
28
+ name: z.string().trim().min(1).max(80),
29
+ version: z.string().max(128).refine(value => {
30
+ const parsed = semver.parse(value);
31
+ return parsed && parsed.version + (parsed.build.length ? '+' + parsed.build.join('.') : '') === value;
32
+ }, '需要有效 SemVer'),
33
+ engines: z.strictObject({ clado: z.string().min(1).max(200) }),
34
+ protocols: z.array(z.string().regex(/^\d+\.\d+$/)).min(1).max(16),
35
+ entrypoints: z.strictObject({ ui: z.strictObject({ path: z.string().max(240).regex(uiPath) }) }),
36
+ permissions: z.array(z.union([permission, capabilityPermission])).max(64).default([]),
37
+ configuration: pluginConfiguration.optional(),
38
+ contributes: z.strictObject({
39
+ mounts: z.array(z.strictObject({
40
+ id: mountId, slot: z.enum(PLUGIN_SLOTS),
41
+ })).min(1).max(8),
42
+ capabilities: z.array(capabilityDefinition).max(16).default([]),
43
+ events: z.tuple([]).optional(),
44
+ }),
45
+ });
46
+ const builtInMounts = ['brand', 'view-controls', 'directory', 'agent'];
47
+ const builtInIds = ['clado.host', ...builtInMounts.map(mount => 'clado.' + mount)];
48
+ export function builtInCapabilities(agentEnabled) {
49
+ const screenshot = compileCapabilities('clado.host', [{ id: 'canvas' }], [captureDefinition]);
50
+ const extensions = builtInMounts.filter(mount => mount !== 'agent' || agentEnabled).flatMap(mount => {
51
+ let raw;
52
+ try { raw = readFileSync(new URL('../../plugins/' + mount + '/capabilities.json', import.meta.url), 'utf8'); }
53
+ catch (error) { if (error.code === 'ENOENT') return []; throw error; }
54
+ return compileCapabilities('clado.' + mount, [{ id: mount }], JSON.parse(raw));
55
+ });
56
+ return [...screenshot, ...extensions];
57
+ }
58
+ export const builtInGrants = () => new Map(builtInIds.map(id => [id, id === 'clado.agent' ? ['capability.call:clado.directory/directory.open'] : []]));
59
+ const contentTypes = new Map(Object.entries({
60
+ '.html': 'text/html; charset=utf-8',
61
+ '.js': 'text/javascript; charset=utf-8',
62
+ '.mjs': 'text/javascript; charset=utf-8',
63
+ '.css': 'text/css; charset=utf-8',
64
+ '.json': 'application/json; charset=utf-8',
65
+ '.svg': 'image/svg+xml',
66
+ '.png': 'image/png',
67
+ '.jpg': 'image/jpeg',
68
+ '.jpeg': 'image/jpeg',
69
+ '.gif': 'image/gif',
70
+ '.webp': 'image/webp',
71
+ '.woff2': 'font/woff2',
72
+ }));
73
+
74
+ // The workspace opted into loading these packages. Still keep every file read
75
+ // inside its package, and avoid following symlinks or opening special files.
76
+ function readPackageFile(root, parts, maxBytes) {
77
+ let path = root;
78
+ if (!lstatSync(path).isDirectory()) throw new Error('插件包需要是实体目录。');
79
+ for (const part of parts.slice(0, -1)) {
80
+ path = join(path, part);
81
+ if (!lstatSync(path).isDirectory()) throw new Error('插件资源目录无效。');
82
+ }
83
+ path = join(path, parts.at(-1));
84
+ const info = lstatSync(path);
85
+ if (!info.isFile() || info.size > maxBytes) throw new Error('插件文件类型或大小无效。');
86
+ return readFileSync(path);
87
+ }
88
+
89
+ function readManifest(root) {
90
+ const result = manifest.safeParse(JSON.parse(readPackageFile(root, ['clado-plugin.json'], 64 * 1024).toString('utf8')));
91
+ if (!result.success) {
92
+ const issue = result.error.issues[0];
93
+ throw new Error(`清单字段 ${issue.path.join('.') || '根对象'} 无效:${issue.message}`);
94
+ }
95
+ const data = result.data;
96
+ if (builtInIds.includes(data.id)) throw new Error(data.id + ' 是 Clado 保留 ID。');
97
+ if (!semver.validRange(data.engines.clado) || !semver.satisfies(VERSION, data.engines.clado)) {
98
+ throw new Error(`插件需要 Clado ${data.engines.clado},当前版本为 ${VERSION}。`);
99
+ }
100
+ if (!data.protocols.includes(PLUGIN_PROTOCOL)) throw new Error(`插件需要声明协议 ${PLUGIN_PROTOCOL}。`);
101
+ const mounts = data.contributes.mounts;
102
+ if (new Set(mounts.map(mount => mount.id)).size !== mounts.length) throw new Error('挂载 ID 重复。');
103
+ for (const { slot } of mounts) {
104
+ if (!data.permissions.includes('ui.mount:' + slot)) throw new Error(`缺少挂载权限 ui.mount:${slot}。`);
105
+ }
106
+ readPackageFile(root, data.entrypoints.ui.path.split('/'), 2 * 1024 * 1024);
107
+ return { data, capabilities: compileCapabilities(data.id, mounts, data.contributes.capabilities),
108
+ configuration: compileConfiguration(data.configuration) };
109
+ }
110
+
111
+ export function installWorkspacePlugin(ctx, files, runtime) {
112
+ if (!Array.isArray(files) || !files.length || files.length > 256) fail('请选择一个插件目录,最多 256 个文件。');
113
+ const parsed = new Map();
114
+ let size = 0;
115
+ for (const file of files) {
116
+ if (typeof file?.path !== 'string' || typeof file.data !== 'string' || file.path.length > 240) fail('插件文件参数无效。');
117
+ const parts = file.path.split('/');
118
+ if (!parts.every(part => segment.test(part)) ||
119
+ (file.path !== 'clado-plugin.json' && (parts[0] !== 'ui' || !contentTypes.has(extname(file.path).toLowerCase())))) fail('插件包仅接受清单和 ui 目录中的资源。');
120
+ if (parsed.has(file.path)) fail('插件包中有重复的文件路径。');
121
+ const data = Buffer.from(file.data, 'base64');
122
+ if (data.toString('base64') !== file.data) fail('插件文件编码无效。');
123
+ size += data.length;
124
+ if (data.length > 2 * 1024 * 1024 || size > 8 * 1024 * 1024) fail('插件包超过大小限制。', 413);
125
+ parsed.set(file.path, data);
126
+ }
127
+ if (!parsed.has('clado-plugin.json')) fail('插件目录缺少 clado-plugin.json。');
128
+ return locked(ctx, () => {
129
+ const directory = join(ctx.state, 'plugins');
130
+ if (!existsSync(directory)) mkdirSync(directory);
131
+ if (!lstatSync(directory).isDirectory()) fail('插件目录需要是实体目录。');
132
+ const stage = join(directory, '.install-' + randomUUID());
133
+ mkdirSync(stage, { mode: 0o700 });
134
+ try {
135
+ for (const [file, body] of parsed) {
136
+ const target = join(stage, file);
137
+ if (file.includes('/')) mkdirSync(join(target, '..'), { recursive: true });
138
+ writeFileSync(target, body, { flag: 'wx' });
139
+ }
140
+ let definition;
141
+ try { definition = readManifest(stage); }
142
+ catch (error) { fail(error.message, 422); }
143
+ const { id, name, version } = definition.data;
144
+ const target = join(directory, id);
145
+ const duplicate = readdirSync(directory, { withFileTypes: true }).some(entry => {
146
+ if (!entry.isDirectory() || entry.name.startsWith('.')) return false;
147
+ try { return readManifest(join(directory, entry.name)).data.id === id; }
148
+ catch { return false; }
149
+ });
150
+ if (existsSync(target) || duplicate) fail('已经安装了同 ID 的插件。', 409);
151
+ renameSync(stage, target);
152
+ runtime?.register(target, definition);
153
+ return { id, name, version, active: !!runtime };
154
+ } finally { rmSync(stage, { recursive: true, force: true }); }
155
+ });
156
+ }
157
+
158
+ export function loadWorkspacePlugins(state) {
159
+ const directory = join(state, 'plugins');
160
+ const plugins = [], warnings = [], packages = new Map(), capabilities = [], configurations = new Map();
161
+ let entries = [];
162
+ try {
163
+ if (!lstatSync(directory).isDirectory()) throw new Error('插件目录需要是实体目录。');
164
+ entries = readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name));
165
+ } catch (error) {
166
+ if (error.code !== 'ENOENT') warnings.push({ directory: '.clado/plugins', message: error.message });
167
+ }
168
+ const candidates = new Map();
169
+ function register(root, { data, capabilities: declared, configuration }) {
170
+ configurations.set(data.id, configuration);
171
+ capabilities.push(...declared);
172
+ const key = randomUUID();
173
+ packages.set(key, root);
174
+ plugins.push({
175
+ id: data.id, name: data.name, version: data.version,
176
+ entry: ASSETS + key + '/' + data.entrypoints.ui.path,
177
+ permissions: data.permissions, mounts: data.contributes.mounts, capabilities: declared.map(item => item.descriptor),
178
+ });
179
+ }
180
+ for (const entry of entries) {
181
+ if (entry.name.startsWith('.') || (!entry.isDirectory() && !entry.isSymbolicLink())) continue;
182
+ const root = join(directory, entry.name);
183
+ try {
184
+ const { data, capabilities, configuration } = readManifest(root);
185
+ const copies = candidates.get(data.id) || [];
186
+ copies.push({ data, capabilities, configuration, root, directory: entry.name });
187
+ candidates.set(data.id, copies);
188
+ } catch (error) {
189
+ warnings.push({ directory: entry.name, message: error.code === 'ENOENT' ? '缺少插件清单或 UI 入口。' : error.message });
190
+ }
191
+ }
192
+ for (const copies of candidates.values()) {
193
+ if (copies.length !== 1) {
194
+ for (const copy of copies) warnings.push({ directory: copy.directory, message: '插件 ID 重复:' + copy.data.id });
195
+ continue;
196
+ }
197
+ register(copies[0].root, copies[0]);
198
+ }
199
+ const descriptor = { workspaceId: randomUUID(), protocol: PLUGIN_PROTOCOL, slots: PLUGIN_SLOTS, fields: PLUGIN_FIELDS, plugins };
200
+ function serveAsset(req, res, url) {
201
+ const [key, ...parts] = url.pathname.slice(ASSETS.length).split('/').map(decodeURIComponent);
202
+ const root = packages.get(key), type = contentTypes.get(extname(parts.at(-1) || '').toLowerCase());
203
+ if (!root || !type || parts[0] !== 'ui' || !parts.every(part => segment.test(part))) {
204
+ throw new DocumentError('插件资源不存在。', 404);
205
+ }
206
+ let body;
207
+ try {
208
+ if (!lstatSync(directory).isDirectory()) throw new Error();
209
+ body = readPackageFile(root, parts, 2 * 1024 * 1024);
210
+ } catch {
211
+ throw new DocumentError('插件资源不可读。', 404);
212
+ }
213
+ const origin = 'http://' + req.headers.host;
214
+ const ui = origin + ASSETS + key + '/ui/';
215
+ res.writeHead(200, {
216
+ 'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff',
217
+ 'access-control-allow-origin': 'null',
218
+ 'content-security-policy': `sandbox allow-scripts; default-src 'none'; script-src ${ui} ${origin + SDK}; style-src ${ui} ${origin + UI_CSS}; img-src ${ui} data:; font-src ${ui}; form-action 'none'; base-uri 'none'; frame-ancestors ${origin}`,
219
+ });
220
+ res.end(req.method === 'HEAD' ? undefined : body);
221
+ }
222
+ return { descriptor, warnings, serveAsset, capabilities, configurations, register };
223
+ }
224
+
225
+ export function inspectWorkspacePlugins(state) {
226
+ const directory = join(state, 'plugins');
227
+ if (!existsSync(directory) || !lstatSync(directory).isDirectory()) return [];
228
+ return readdirSync(directory, { withFileTypes: true }).flatMap(entry => {
229
+ if (!entry.isDirectory() || entry.name.startsWith('.')) return [];
230
+ try {
231
+ const raw = JSON.parse(readPackageFile(join(directory, entry.name), ['clado-plugin.json'], 64 * 1024));
232
+ const { id, name, version } = manifest.parse(raw);
233
+ return builtInIds.includes(id) ? [] : [{ id, name, version, pending: true, reason: '待启用第三方插件' }];
234
+ } catch { return []; }
235
+ });
236
+ }