cladogram 0.5.4 → 0.5.5-beta.2

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 (54) hide show
  1. package/README.md +8 -6
  2. package/bin/clado.js +5 -5
  3. package/docs/release.md +13 -0
  4. package/package.json +1 -1
  5. package/plugins/agent/index.js +458 -25
  6. package/plugins/agent/style.css +299 -8
  7. package/plugins/directory/capabilities.json +1 -1
  8. package/plugins/directory/index.js +57 -2
  9. package/plugins/directory/style.css +11 -0
  10. package/plugins/view-controls/index.js +1 -1
  11. package/plugins/view-controls/style.css +30 -10
  12. package/skills/clado/SKILL.md +17 -16
  13. package/src/agent/executors.js +213 -0
  14. package/src/agent/probe.js +176 -0
  15. package/src/agent/providers/anthropic.js +220 -0
  16. package/src/agent/providers/index.js +52 -0
  17. package/src/agent/providers/openai.js +146 -0
  18. package/src/agent/runtime.js +557 -0
  19. package/src/agent/sessions.js +129 -0
  20. package/src/html/app-css.js +62 -9
  21. package/src/html/canvas-chain.js +2 -1
  22. package/src/html/canvas-ui.css +63 -0
  23. package/src/html/page.js +4 -0
  24. package/src/html/plugin-ui.css +12 -0
  25. package/src/html/plugin-ui.js +8 -2
  26. package/src/html/runtime-api.js +136 -5
  27. package/src/html/runtime.js +160 -290
  28. package/src/html/view-registry.js +95 -0
  29. package/src/html/views/view-cards.js +28 -0
  30. package/src/html/views/view-doc.js +51 -0
  31. package/src/html/views/view-mindmap.js +173 -0
  32. package/src/server/agent.js +335 -17
  33. package/src/server/assets/library-canvas.js +13 -3
  34. package/src/server/assets/library-plugin-bridge.js +2 -2
  35. package/src/server/assets/library-plugins.js +2 -2
  36. package/src/server/assets/library.css +5 -0
  37. package/src/server/assets/library.html +1 -1
  38. package/src/server/assets/library.js +157 -20
  39. package/src/server/events.js +189 -0
  40. package/src/server/export.js +1 -1
  41. package/src/server/mcp.js +16 -16
  42. package/src/server/plugin-capabilities.js +38 -22
  43. package/src/server/plugin-settings.js +27 -1
  44. package/src/server/plugins.js +17 -4
  45. package/src/server/workspace.js +171 -56
  46. package/src/skill/install.js +1 -1
  47. package/src/skill/targets.js +3 -3
  48. package/src/util/update.js +3 -2
  49. package/src/workspace/service.js +23 -15
  50. package/src/workspace/storage.js +88 -20
  51. package/templates/business-flow.mdc +1 -1
  52. package/templates/call-chain.mdc +1 -1
  53. package/templates/data-design.mdc +1 -1
  54. package/templates/test-cases.mdc +47 -0
@@ -51,19 +51,30 @@ const fromBrowser = z.discriminatedUnion('action', [
51
51
  const agent = { kind: 'agent' };
52
52
  const timeoutMs = 8000;
53
53
 
54
- export function createCapabilityRegistry({ workspace, workspaceId, providers, grants }) {
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
+ }) {
55
63
  const views = new Map();
56
64
  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);
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);
59
67
 
60
- function list(query, caller, viewId) {
61
- const eligible = viewId ? [views.get(viewId)].filter(Boolean) : [...views.values()];
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);
62
73
  return {
63
74
  views: eligible.map(view => ({
64
75
  viewId: view.id,
65
76
  capabilities: [...view.providers.values()].map(provider => provider.descriptor)
66
- .filter(descriptor => matches(query, descriptor) && allowed(caller, descriptor)),
77
+ .filter(descriptor => matches(query, descriptor) && allowed(caller, descriptor, targetGrants)),
67
78
  })),
68
79
  };
69
80
  }
@@ -77,12 +88,15 @@ export function createCapabilityRegistry({ workspace, workspaceId, providers, gr
77
88
  return true;
78
89
  }
79
90
 
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;
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;
83
96
  if (!view) fail('目标 Clado 标签页未连接,请打开工作区页面。', 409, { code: 'VIEW_UNAVAILABLE' });
97
+ const targetGrants = grantsFor(view.workspace);
84
98
  const candidates = [...view.providers.values()].filter(({ descriptor }) => matches({ ...to, major: undefined }, descriptor));
85
- const visible = candidates.filter(({ descriptor }) => allowed(caller, descriptor));
99
+ const visible = candidates.filter(({ descriptor }) => allowed(caller, descriptor, targetGrants));
86
100
  if (candidates.length && !visible.length) fail('没有调用该能力的权限。', 403, { code: 'FORBIDDEN' });
87
101
  const compatible = visible.filter(({ descriptor }) => descriptor.major === to.major);
88
102
  if (!compatible.length) fail(visible.length ? '能力主版本不匹配。' : '当前标签页没有注册该能力。', 404, { code: visible.length ? 'UNSUPPORTED_VERSION' : 'NO_PROVIDER' });
@@ -100,16 +114,16 @@ export function createCapabilityRegistry({ workspace, workspaceId, providers, gr
100
114
  view.send('call', {
101
115
  id, from: caller,
102
116
  to: { pluginId: descriptor.pluginId, mountId: descriptor.mountId, capability: descriptor.capability, major: descriptor.major },
103
- scope: { workspaceId, viewId: view.id }, input,
117
+ scope: { workspaceId: view.workspaceId, viewId: view.id }, input,
104
118
  });
105
119
  });
106
120
  }
107
121
 
108
- function connect(id, res) {
109
- if (views.has(id) || views.size >= 32) fail('标签页已连接或已达到连接上限。', 409);
122
+ function connect(id, res, viewWorkspace = workspace, viewWorkspaceId = workspaceId) {
123
+ if (views.has(id) || views.size >= 64) fail('标签页已连接或已达到连接上限。', 409);
110
124
  res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store, no-transform', 'x-content-type-options': 'nosniff' });
111
125
  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() };
126
+ const view = { id, workspace: viewWorkspace, workspaceId: viewWorkspaceId, send, res, providers: new Map(), pending: new Map() };
113
127
  views.set(id, view);
114
128
  const heartbeat = setInterval(() => res.write(': heartbeat\n\n'), 15000);
115
129
  res.on('close', () => {
@@ -118,7 +132,7 @@ export function createCapabilityRegistry({ workspace, workspaceId, providers, gr
118
132
  for (const callId of view.pending.keys()) finish(view, callId, ({ reject }) =>
119
133
  reject(Object.assign(new Error('插件所在的标签页已断开。'), { status: 409, details: { code: 'VIEW_UNAVAILABLE' } })));
120
134
  });
121
- send('ready', { viewId: id, workspaceId });
135
+ send('ready', { viewId: id, workspaceId: viewWorkspaceId });
122
136
  }
123
137
 
124
138
  async function receive(id, body) {
@@ -143,16 +157,18 @@ export function createCapabilityRegistry({ workspace, workspaceId, providers, gr
143
157
  });
144
158
  return {};
145
159
  }
146
- if (!grants.has(message.pluginId)) fail('插件未启用。', 403, { code: 'FORBIDDEN' });
160
+ const targetGrants = grantsFor(view.workspace);
161
+ const targetProviders = providersFor(view.workspace);
162
+ if (!targetGrants.has(message.pluginId)) fail('插件未启用。', 403, { code: 'FORBIDDEN' });
147
163
  if (message.action === 'register') {
148
- const declared = providers.filter(({ descriptor }) => descriptor.pluginId === message.pluginId && descriptor.mountId === message.mountId);
164
+ const declared = targetProviders.filter(({ descriptor }) => descriptor.pluginId === message.pluginId && descriptor.mountId === message.mountId);
149
165
  if (!declared.length) fail('该挂载未声明可注册的能力。', 400, { code: 'NO_PROVIDER' });
150
166
  for (const provider of declared) view.providers.set(provider.key, provider);
151
167
  return { capabilities: declared.map(provider => provider.descriptor) };
152
168
  }
153
169
  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);
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);
156
172
  }
157
173
 
158
174
  return {
@@ -162,11 +178,11 @@ export function createCapabilityRegistry({ workspace, workspaceId, providers, gr
162
178
  },
163
179
  close() { for (const view of views.values()) view.res.end(); },
164
180
  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);
181
+ const targetWorkspace = resolveWorkspace(args.workspace);
182
+ if (args.action === 'list') return list(args.to || {}, agent, args.viewId, targetWorkspace);
167
183
  const parsed = target.safeParse(args.to);
168
184
  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);
185
+ return await call(args.viewId, parsed.data, args.input, agent, targetWorkspace);
170
186
  },
171
187
  };
172
188
  }
@@ -12,14 +12,40 @@ export const pluginConfiguration = z.strictObject({
12
12
  });
13
13
  const specs = {
14
14
  'clado.brand': { showScreenshot: { type: 'boolean' } },
15
- 'clado.view-controls': { defaultMode: { enum: ['mindmap', 'cards', 'doc'] } },
15
+ 'clado.view-controls': { defaultMode: { enum: ['cards', 'mindmap', 'doc'] } },
16
16
  'clado.directory': { showFilename: { type: 'boolean' } },
17
17
  'clado.agent': {
18
18
  name: { type: 'string', minLength: 1, maxLength: 80 },
19
+ mode: { enum: ['auto', 'builtin', 'acp'] },
20
+ provider: { enum: ['auto', 'openai', 'anthropic'] },
21
+ baseUrl: { type: 'string', minLength: 1, maxLength: 512 },
22
+ apiKey: { type: 'string', maxLength: 512 },
23
+ model: { type: 'string', minLength: 1, maxLength: 128 },
24
+ persona: { enum: ['architect', 'qa', 'auditor', 'custom'] },
25
+ personaPrompt: { type: 'string', maxLength: 4000 },
19
26
  command: { type: 'string', minLength: 1, maxLength: 2048, pattern: '^.+' },
20
27
  args: { type: 'array', maxItems: 32, items: { type: 'string', maxLength: 2048 } },
21
28
  env: { type: 'object', maxProperties: 32, additionalProperties: { type: 'string', maxLength: 2048 } },
22
29
  placeholder: { type: 'string', minLength: 1, maxLength: 120 },
30
+ executors: {
31
+ type: 'array',
32
+ maxItems: 16,
33
+ items: {
34
+ type: 'object',
35
+ required: ['id', 'name', 'command'],
36
+ additionalProperties: false,
37
+ properties: {
38
+ id: { type: 'string', minLength: 1, maxLength: 64 },
39
+ name: { type: 'string', minLength: 1, maxLength: 80 },
40
+ protocol: { enum: ['acp'] },
41
+ command: { type: 'string', minLength: 1, maxLength: 2048 },
42
+ args: { type: 'array', maxItems: 32, items: { type: 'string', maxLength: 2048 } },
43
+ env: { type: 'object', maxProperties: 32, additionalProperties: { type: 'string', maxLength: 2048 } },
44
+ capabilities: { type: 'array', maxItems: 16, items: { type: 'string', maxLength: 64 } },
45
+ description: { type: 'string', maxLength: 400 },
46
+ },
47
+ },
48
+ },
23
49
  },
24
50
  };
25
51
  const defaults = {
@@ -8,6 +8,7 @@ import { DocumentError } from '../workspace/documents.js';
8
8
  import { capabilityDefinition, capabilityPermission, compileCapabilities, mountId, pluginId } from './plugin-capabilities.js';
9
9
  import { captureDefinition } from './canvas-capture.js';
10
10
  import { compileConfiguration, pluginConfiguration } from './plugin-settings.js';
11
+ import { executorSchema } from '../agent/executors.js';
11
12
  import { locked, fail } from '../workspace/storage.js';
12
13
 
13
14
  export const PLUGIN_PROTOCOL = '1.0';
@@ -40,11 +41,22 @@ const manifest = z.strictObject({
40
41
  id: mountId, slot: z.enum(PLUGIN_SLOTS),
41
42
  })).min(1).max(8),
42
43
  capabilities: z.array(capabilityDefinition).max(16).default([]),
44
+ executors: z.array(executorSchema).max(8).default([]),
43
45
  events: z.tuple([]).optional(),
44
46
  }),
45
47
  });
48
+ export const BUILT_IN_VIEWS = Object.freeze([
49
+ Object.freeze({ id: 'clado.view.cards', mode: 'cards', label: '卡片', kind: 'view', protected: true, default: true }),
50
+ Object.freeze({ id: 'clado.view.mindmap', mode: 'mindmap', label: '脑图', kind: 'view', protected: true, default: false }),
51
+ Object.freeze({ id: 'clado.view.doc', mode: 'doc', label: '文档', kind: 'view', protected: true, default: false }),
52
+ ]);
46
53
  const builtInMounts = ['brand', 'view-controls', 'directory', 'agent'];
47
- const builtInIds = ['clado.host', ...builtInMounts.map(mount => 'clado.' + mount)];
54
+ const builtInIds = ['clado.host', ...BUILT_IN_VIEWS.map(view => view.id), ...builtInMounts.map(mount => 'clado.' + mount)];
55
+ export const isReservedPluginId = id => id === 'clado' || String(id || '').startsWith('clado.');
56
+ export const BUILT_IN_PLUGINS = Object.freeze([
57
+ ...BUILT_IN_VIEWS,
58
+ ...builtInMounts.map(mount => Object.freeze({ id: 'clado.' + mount, mount, kind: 'ui', protected: true })),
59
+ ]);
48
60
  export function builtInCapabilities(agentEnabled) {
49
61
  const screenshot = compileCapabilities('clado.host', [{ id: 'canvas' }], [captureDefinition]);
50
62
  const extensions = builtInMounts.filter(mount => mount !== 'agent' || agentEnabled).flatMap(mount => {
@@ -93,7 +105,7 @@ function readManifest(root) {
93
105
  throw new Error(`清单字段 ${issue.path.join('.') || '根对象'} 无效:${issue.message}`);
94
106
  }
95
107
  const data = result.data;
96
- if (builtInIds.includes(data.id)) throw new Error(data.id + ' 是 Clado 保留 ID。');
108
+ if (isReservedPluginId(data.id)) throw new Error(data.id + ' 使用了 Clado 保留命名空间(clado.*)。');
97
109
  if (!semver.validRange(data.engines.clado) || !semver.satisfies(VERSION, data.engines.clado)) {
98
110
  throw new Error(`插件需要 Clado ${data.engines.clado},当前版本为 ${VERSION}。`);
99
111
  }
@@ -175,6 +187,7 @@ export function loadWorkspacePlugins(state) {
175
187
  id: data.id, name: data.name, version: data.version,
176
188
  entry: ASSETS + key + '/' + data.entrypoints.ui.path,
177
189
  permissions: data.permissions, mounts: data.contributes.mounts, capabilities: declared.map(item => item.descriptor),
190
+ ...(data.contributes.executors?.length ? { executors: data.contributes.executors } : {}),
178
191
  });
179
192
  }
180
193
  for (const entry of entries) {
@@ -219,7 +232,7 @@ export function loadWorkspacePlugins(state) {
219
232
  });
220
233
  res.end(req.method === 'HEAD' ? undefined : body);
221
234
  }
222
- return { descriptor, warnings, serveAsset, capabilities, configurations, register };
235
+ return { descriptor, warnings, serveAsset, hasAsset: key => packages.has(key), capabilities, configurations, register };
223
236
  }
224
237
 
225
238
  export function inspectWorkspacePlugins(state) {
@@ -230,7 +243,7 @@ export function inspectWorkspacePlugins(state) {
230
243
  try {
231
244
  const raw = JSON.parse(readPackageFile(join(directory, entry.name), ['clado-plugin.json'], 64 * 1024));
232
245
  const { id, name, version } = manifest.parse(raw);
233
- return builtInIds.includes(id) ? [] : [{ id, name, version, pending: true, reason: '待启用第三方插件' }];
246
+ return isReservedPluginId(id) ? [] : [{ id, name, version, pending: true, reason: '待启用第三方插件' }];
234
247
  } catch { return []; }
235
248
  });
236
249
  }
@@ -1,17 +1,18 @@
1
1
  import { createServer } from 'node:http';
2
2
  import { createHash, randomUUID } from 'node:crypto';
3
3
  import { readFileSync, statSync, existsSync, mkdirSync } from 'node:fs';
4
- import { dirname, resolve, basename, join, relative } from 'node:path';
4
+ import { dirname, resolve, basename, join, relative, sep, isAbsolute } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { renderHtml } from '../html/page.js';
7
7
  import { pluginMarkup, workspacePluginAssets } from '../html/plugin-assets.js';
8
8
  import { scanDirectory, workspacePath, readDocument, DocumentError } from '../workspace/documents.js';
9
- import { contextFor, initialize } from '../workspace/storage.js';
9
+ import { contextFor, discoverWorkspaces, initialize } from '../workspace/storage.js';
10
10
  import { createWorkspaceService } from '../workspace/service.js';
11
11
  import { createMcpHandler } from './mcp.js';
12
12
  import { builtInCapabilities, builtInGrants, inspectWorkspacePlugins, installWorkspacePlugin, loadWorkspacePlugins } from './plugins.js';
13
13
  import { createCapabilityRegistry } from './plugin-capabilities.js';
14
14
  import { createPluginSettings } from './plugin-settings.js';
15
+ import { createWorkspaceEvents, broadcastMcpEvent } from './events.js';
15
16
  import { z } from 'zod/v4';
16
17
  const assets = join(dirname(fileURLToPath(import.meta.url)), 'assets');
17
18
  const resourceTypes = {png:'image/png',jpg:'image/jpeg',jpeg:'image/jpeg',gif:'image/gif',webp:'image/webp',svg:'image/svg+xml',pdf:'application/pdf',txt:'text/plain',csv:'text/csv',json:'application/json'};
@@ -25,10 +26,13 @@ export function createWorkspaceHandler(directory, options = {}) {
25
26
  const root = resolve(directory);
26
27
  const assetNames = new Set(['library.html','library.css','library.js','library-canvas.js']);
27
28
  if (options.capabilities) assetNames.add('library-plugin-bridge.js');
28
- if (options.plugins) for (const name of ['library-plugins.js', 'library-plugins.css', 'clado-plugin-sdk.js']) assetNames.add(name);
29
+ if (options.plugins || options.experimentalPlugins) for (const name of ['library-plugins.js', 'library-plugins.css', 'clado-plugin-sdk.js']) assetNames.add(name);
29
30
  const send = (res, status, type, body) => { res.writeHead(status, { 'content-type': type + '; charset=utf-8', 'cache-control':'no-store', 'x-content-type-options':'nosniff' }); res.end(body); };
30
31
  const json = (res, status, data) => send(res, status, types.json, JSON.stringify(data));
31
32
  const safeJson = data => JSON.stringify(data).replace(/</g,'\\u003c');
33
+ const resolveTarget = url => options.resolveWorkspace
34
+ ? options.resolveWorkspace(url.searchParams.get('workspace'))
35
+ : { id: '', workspace: root, root, workspaceId: options.plugins?.descriptor.workspaceId || '', plugins: options.plugins || null, settings: options.settings || null, inactivePlugins: options.inactivePlugins };
32
36
  return async function handle(req, res, url) {
33
37
  const route = url.pathname.slice(1);
34
38
  const pluginFile = workspacePluginAssets.get(url.pathname);
@@ -36,10 +40,12 @@ export function createWorkspaceHandler(directory, options = {}) {
36
40
  try {
37
41
  const host = req.headers.host;
38
42
  if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host || '')) throw new DocumentError('只接受本机预览请求。',403);
39
- const pluginAsset = options.plugins && url.pathname.startsWith('/library/plugin-assets/');
43
+ const pluginsEnabled = !!(options.plugins || options.experimentalPlugins);
44
+ const pluginAsset = pluginsEnabled && url.pathname.startsWith('/library/plugin-assets/');
40
45
  if (req.headers.origin && req.headers.origin !== 'http://' + host && !(pluginAsset && req.headers.origin === 'null')) throw new DocumentError('来源不匹配。',403);
41
46
  if (url.pathname === '/library/selection' && options.publishSelection && req.method === 'POST') {
42
47
  if (req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') throw new DocumentError('选区只接受同源页面请求。', 403);
48
+ const target = resolveTarget(url);
43
49
  const chunks = []; let size = 0;
44
50
  for await (const chunk of req) {
45
51
  size += chunk.length;
@@ -48,16 +54,33 @@ export function createWorkspaceHandler(directory, options = {}) {
48
54
  }
49
55
  const selection = viewSelection.safeParse(JSON.parse(Buffer.concat(chunks).toString('utf8')));
50
56
  if (!selection.success) throw new DocumentError('选区参数不合法。', 400);
51
- workspacePath(root, selection.data.file, selection.data.nodes.length === 0);
52
- options.publishSelection(selection.data);
57
+ workspacePath(target.root, selection.data.file, selection.data.nodes.length === 0);
58
+ options.publishSelection(target.workspace, selection.data);
53
59
  json(res, 200, { ok: true }); return true;
54
60
  }
61
+ if (url.pathname === '/library/events' && options.events) {
62
+ if (req.method !== 'GET') throw new DocumentError('事件流仅支持 GET。', 405);
63
+ const target = resolveTarget(url);
64
+ options.events.subscribe(target.workspace, req, res);
65
+ return true;
66
+ }
67
+ if (options.agent && url.pathname === '/library/agent/meta') {
68
+ const target = resolveTarget(url);
69
+ options.agent.handleMeta(req, res, target.workspace); return true;
70
+ }
71
+ if (options.agent && url.pathname === '/library/agent/sessions') {
72
+ const target = resolveTarget(url);
73
+ options.agent.handleSessions(req, res, url, target.workspace); return true;
74
+ }
55
75
  if (options.agent && url.pathname === '/library/agent') {
56
- await options.agent.handle(req, res); return true;
76
+ const target = resolveTarget(url);
77
+ await options.agent.handle(req, res, target.workspace); return true;
57
78
  }
58
- if (options.settings && url.pathname === '/library/plugin-settings') {
79
+ if (url.pathname === '/library/plugin-settings') {
80
+ const target = resolveTarget(url);
81
+ if (!target.settings) throw new DocumentError('没有这个预览入口;文档操作请使用 /mcp。',404);
59
82
  const id = url.searchParams.get('id');
60
- if (req.method === 'GET') { json(res, 200, options.settings.read(id)); return true; }
83
+ if (req.method === 'GET') { json(res, 200, target.settings.read(id)); return true; }
61
84
  if (req.method !== 'POST' || req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') {
62
85
  throw new DocumentError('插件设置只接受同源页面写入。', 403);
63
86
  }
@@ -68,20 +91,21 @@ export function createWorkspaceHandler(directory, options = {}) {
68
91
  chunks.push(chunk);
69
92
  }
70
93
  const { value, expected } = JSON.parse(Buffer.concat(chunks).toString('utf8'));
71
- json(res, 200, options.settings.save(id, value, expected));
94
+ json(res, 200, target.settings.save(id, value, expected));
72
95
  return true;
73
96
  }
74
97
  if (options.installPlugin && url.pathname === '/library/install-plugin') {
75
98
  if (req.method !== 'POST' || req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') {
76
99
  throw new DocumentError('插件安装需要在工作区页面操作。', 403);
77
100
  }
101
+ const target = resolveTarget(url);
78
102
  const chunks = []; let size = 0;
79
103
  for await (const chunk of req) {
80
104
  size += chunk.length;
81
105
  if (size > 12 * 1024 * 1024) throw new DocumentError('插件包太大。', 413);
82
106
  chunks.push(chunk);
83
107
  }
84
- json(res, 201, options.installPlugin(JSON.parse(Buffer.concat(chunks).toString('utf8'))?.files));
108
+ json(res, 201, options.installPlugin(target.workspace, JSON.parse(Buffer.concat(chunks).toString('utf8'))?.files));
85
109
  return true;
86
110
  }
87
111
  if (options.capabilities && url.pathname === '/library/plugin-bridge') {
@@ -89,7 +113,8 @@ export function createWorkspaceHandler(directory, options = {}) {
89
113
  if (!view.success) throw new DocumentError('需要有效的 viewId。', 400);
90
114
  if (req.method === 'GET' && req.headers.accept === 'text/event-stream' &&
91
115
  (!req.headers['sec-fetch-site'] || req.headers['sec-fetch-site'] === 'same-origin')) {
92
- options.capabilities.connect(view.data, res); return true;
116
+ const target = resolveTarget(url);
117
+ options.capabilities.connect(view.data, res, target.workspace, target.workspaceId); return true;
93
118
  }
94
119
  if (req.method !== 'POST' || req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') {
95
120
  throw new DocumentError('插件通信只接受同源页面请求。', 403);
@@ -111,13 +136,22 @@ export function createWorkspaceHandler(directory, options = {}) {
111
136
  return true;
112
137
  }
113
138
  if (req.method !== 'GET' && req.method !== 'HEAD') throw new DocumentError('不支持这个请求方法。',405);
114
- if (options.plugins && url.pathname === '/library/plugins.json') {
115
- const values = options.settings?.values() || {};
116
- const descriptor = options.plugins.descriptor;
139
+ if (url.pathname === '/library/workspaces.json') {
140
+ const workspaces = options.listWorkspaces
141
+ ? options.listWorkspaces()
142
+ : [{ id: '', name: basename(root), workspace: root, documentRoot: root, documents: scanDirectory(root).documents.length }];
143
+ json(res, 200, { scope: options.scopeName || basename(root), workspaces }); return true;
144
+ }
145
+ if (pluginsEnabled && url.pathname === '/library/plugins.json') {
146
+ const target = resolveTarget(url);
147
+ const values = target.settings?.values() || {};
148
+ const descriptor = target.plugins.descriptor;
117
149
  json(res, 200, { ...descriptor, plugins: descriptor.plugins.map(plugin => ({ ...plugin, settings: values[plugin.id] || {} })) }); return true;
118
150
  }
119
151
  if (pluginAsset) {
120
- options.plugins.serveAsset(req, res, url); return true;
152
+ if (options.servePluginAsset) options.servePluginAsset(req, res, url);
153
+ else options.plugins.serveAsset(req, res, url);
154
+ return true;
121
155
  }
122
156
  if (pluginFile) {
123
157
  send(res, 200, types[route.split('.').pop()], readFileSync(pluginFile, 'utf8')); return true;
@@ -125,45 +159,49 @@ export function createWorkspaceHandler(directory, options = {}) {
125
159
  if (assetNames.has(route) || (options.entrypoint && route === '')) {
126
160
  const name = route || 'library.html'; let body = readFileSync(join(assets, name),'utf8');
127
161
  if (name === 'library.html') {
162
+ const target = resolveTarget(url);
128
163
  const plugins = pluginMarkup({ workspace: true, agent: !!options.agent });
129
164
  body = body.replace('<!--CLADO-PLUGIN-STYLES-->', () => plugins.styles)
130
165
  .replace('<!--CLADO-PLUGIN-SCRIPTS-->', () => plugins.scripts);
131
166
  const pluginAssets = (options.capabilities ? '<script src="/library-plugin-bridge.js"></script>' : '') +
132
- (options.plugins ? '<link rel="stylesheet" href="/library-plugins.css"><script src="/library-plugins.js"></script>' : '');
167
+ (target.plugins ? '<link rel="stylesheet" href="/library-plugins.css"><script src="/library-plugins.js"></script>' : '');
133
168
  body = body.replace('</head>', pluginAssets + '</head>');
134
- const pluginCatalog = options.plugins?.descriptor.plugins.map(({ id, name, version }) => ({ id, name, version })) || options.inactivePlugins?.() || [];
135
- const pluginPreferenceKey = createHash('sha256').update(root).digest('hex');
136
- const pluginSettings = Object.fromEntries(Object.entries(options.settings?.values() || {}).filter(([id]) => id.startsWith('clado.') && !pluginCatalog.some(plugin => plugin.id === id)));
137
- body = body.replace('<script src="library.js">','<script>window.__CLADO_WORKSPACE__='+safeJson({mode:options.mode || 'mindmap',theme:options.theme || 'light',entry:options.entry || '',selection:!!options.publishSelection,plugins:!!options.plugins,agent:!!options.agent,agentProfile:options.agentProfile,pluginCatalog,pluginPreferenceKey,pluginSettings,hasPluginSettings:!!options.settings,canInstallPlugins:!!options.installPlugin})+';</script><script src="library.js">');
169
+ const pluginCatalog = target.plugins?.descriptor.plugins.map(({ id, name, version }) => ({ id, name, version })) || target.inactivePlugins?.() || [];
170
+ const pluginPreferenceKey = createHash('sha256').update(target.workspace).digest('hex');
171
+ const pluginSettings = Object.fromEntries(Object.entries(target.settings?.values() || {}).filter(([id]) => id.startsWith('clado.') && !pluginCatalog.some(plugin => plugin.id === id)));
172
+ body = body.replace('<script src="library.js">','<script>window.__CLADO_WORKSPACE__='+safeJson({mode:options.mode || 'cards',theme:options.theme || 'light',entry:target.id ? '' : (options.entry || ''),workspaceId:target.id,workspaceName:basename(target.workspace),workspacePath:target.workspace,multiWorkspace:!!options.listWorkspaces,selection:!!options.publishSelection,plugins:!!target.plugins,agent:!!options.agent,agentProfile:options.agentProfile,pluginCatalog,pluginPreferenceKey,pluginSettings,hasPluginSettings:!!target.settings,canInstallPlugins:!!options.installPlugin})+';</script><script src="library.js">');
138
173
  }
139
174
  send(res,200,types[name.split('.').pop()],body); return true;
140
175
  }
141
176
  if (url.pathname === '/library/index.json') {
142
- const result = scanDirectory(root);
143
- json(res,200,{root:basename(root)+'/',documents:result.documents,skipped:result.skipped}); return true;
177
+ const target = resolveTarget(url);
178
+ const result = scanDirectory(target.root);
179
+ json(res,200,{root:(target.id || basename(target.root))+'/',workspaceId:target.id,workspace:target.workspace,documents:result.documents,skipped:result.skipped}); return true;
144
180
  }
145
181
  const name = url.searchParams.get('file');
146
182
  if (url.pathname === '/library/resource') {
183
+ const target = resolveTarget(url);
147
184
  const type = resourceTypes[String(name).split('.').pop().toLowerCase()];
148
185
  if (!type) throw new DocumentError('不支持的资源类型。',415);
149
- const path=workspacePath(root,name,false,true);
186
+ const path=workspacePath(target.root,name,false,true);
150
187
  res.writeHead(200,{'content-type':type,'x-content-type-options':'nosniff','content-security-policy':"default-src 'none'; sandbox",'cache-control':'no-store'});res.end(readFileSync(path));return true;
151
188
  }
152
189
  if (!['/library/source.mdc','/library/canvas'].includes(url.pathname)) throw new DocumentError('没有这个预览入口;文档操作请使用 /mcp。',404);
153
- const file = workspacePath(root,name), item = readDocument(file);
190
+ const target = resolveTarget(url);
191
+ const file = workspacePath(target.root,name), item = readDocument(file);
154
192
  if (url.pathname === '/library/source.mdc') { send(res,200,types.md,item.source); return true; }
155
193
  if (item.diagnostics.some(d=>d.severity==='error')) throw new DocumentError('文档暂时无法解析。',422,item.diagnostics);
156
- const mode = ['doc','cards','mindmap'].includes(url.searchParams.get('mode')) ? url.searchParams.get('mode') : options.mode || 'mindmap';
194
+ const mode = ['cards','mindmap','doc'].includes(url.searchParams.get('mode')) ? url.searchParams.get('mode') : (options.mode || 'cards');
157
195
  let html = (options.render || renderHtml)(item.doc,item.diagnostics,{file:name,title:item.doc.title,mode,theme:['light','dark'].includes(url.searchParams.get('theme')) ? url.searchParams.get('theme') : options.theme || 'light',library:true,workspaceChrome:url.searchParams.get('chrome') === 'workspace'});
158
196
  const bodyEnd = html.lastIndexOf('</body>');
159
- html = html.slice(0,bodyEnd) + '<script>window.__CLADO_FILE_PATH__='+safeJson(name)+';window.__CLADO_FILE_VERSION__='+safeJson(item.version)+';window.__CLADO_ANCHOR__='+safeJson(url.searchParams.get('anchor') || '')+';</script><script src="/library-canvas.js"></script>' + html.slice(bodyEnd);
197
+ html = html.slice(0,bodyEnd) + '<script>window.__CLADO_FILE_PATH__='+safeJson(name)+';window.__CLADO_FILE_VERSION__='+safeJson(item.version)+';window.__CLADO_ANCHOR__='+safeJson(url.searchParams.get('anchor') || '')+';window.__CLADO_WORKSPACE_ID__='+safeJson(target.id)+';</script><script src="/library-canvas.js"></script>' + html.slice(bodyEnd);
160
198
  send(res,200,types.html,html); return true;
161
199
  } catch (error) {
162
200
  json(res,error.status || (error instanceof SyntaxError ? 400 : 500),{error:error.message,diagnostics:error.diagnostics || [], ...(error.details && { details: error.details })}); return true;
163
201
  }
164
202
  };
165
203
  }
166
- export async function startWorkspace(input, { port = 4317, mode = 'mindmap', theme = 'light', entry, project = false, experimentalPlugins = false, agent: agentName = 'acp' } = {}) {
204
+ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme = 'light', entry, project = false, experimentalPlugins = false, agent: agentName = 'acp' } = {}) {
167
205
  const path = resolve(input);
168
206
  if (!existsSync(path) && !/\.mdc?$/i.test(path)) mkdirSync(path, { recursive: true });
169
207
  if (statSync(path).isFile() && !/\.mdc?$/i.test(path)) throw new DocumentError('serve 文件需要 .mdc 或 .md 扩展名。');
@@ -172,58 +210,135 @@ export async function startWorkspace(input, { port = 4317, mode = 'mindmap', the
172
210
  else if (project || existsSync(join(root, '.clado/workspace.json')) || existsSync(join(root, 'package.json')) || existsSync(join(root, '.git')) || (statSync(path).isDirectory() && !scanDirectory(root).documents.some(d => !/^readme\.md$/i.test(d.file)))) {
173
211
  const ctx = contextFor(root, root); workspace = root; root = ctx.documents;
174
212
  }
175
- const ctx = contextFor(workspace, workspace, root); initialize(ctx);
176
- const plugins = experimentalPlugins ? loadWorkspacePlugins(ctx.state) : null;
177
- const settings = createPluginSettings(ctx, plugins?.configurations);
178
- const grants = builtInGrants();
179
- for (const { id, permissions } of plugins?.descriptor.plugins || []) grants.set(id, permissions);
180
- const providers = [...builtInCapabilities(agentName !== 'off'), ...(plugins?.capabilities || [])];
213
+ const rootCtx = contextFor(workspace, workspace, root); initialize(rootCtx);
214
+ const runtimes = new Map();
215
+ function runtimeFor(ctx) {
216
+ const existing = runtimes.get(ctx.workspace);
217
+ if (existing) { existing.ctx = ctx; existing.root = ctx.documents; return existing; }
218
+ const wsPlugins = experimentalPlugins ? loadWorkspacePlugins(ctx.state) : null;
219
+ const wsSettings = createPluginSettings(ctx, wsPlugins?.configurations);
220
+ const wsGrants = builtInGrants();
221
+ for (const { id, permissions } of wsPlugins?.descriptor.plugins || []) wsGrants.set(id, permissions);
222
+ const wsProviders = [...builtInCapabilities(agentName !== 'off'), ...(wsPlugins?.capabilities || [])];
223
+ const rt = {
224
+ id: relative(workspace, ctx.workspace).split(sep).join('/'),
225
+ workspace: ctx.workspace,
226
+ root: ctx.documents,
227
+ ctx,
228
+ workspaceId: wsPlugins?.descriptor.workspaceId || randomUUID(),
229
+ plugins: wsPlugins,
230
+ settings: wsSettings,
231
+ grants: wsGrants,
232
+ providers: wsProviders,
233
+ inactivePlugins: () => inspectWorkspacePlugins(ctx.state),
234
+ };
235
+ runtimes.set(ctx.workspace, rt);
236
+ return rt;
237
+ }
238
+ const rootRuntime = runtimeFor(rootCtx);
239
+ function resolveWorkspaceParam(param) {
240
+ if (!param) return rootRuntime;
241
+ if (typeof param !== 'string' || isAbsolute(param) || param.includes('\\') || param.includes('\0') ||
242
+ param.split('/').some(segment => !segment || segment === '.' || segment === '..' || segment.startsWith('.'))) {
243
+ throw new DocumentError('工作区路径不合法。', 400);
244
+ }
245
+ const ctx = contextFor(workspace, resolve(workspace, param), root);
246
+ if (!existsSync(ctx.documents) && !existsSync(ctx.state)) throw new DocumentError('工作区不存在或尚未初始化。', 404);
247
+ return runtimeFor(ctx);
248
+ }
249
+ const resolveMcpWorkspace = target => runtimeFor(contextFor(workspace, target, root)).workspace;
181
250
  const capabilities = createCapabilityRegistry({
182
- workspace, workspaceId: plugins?.descriptor.workspaceId || randomUUID(),
183
- providers, grants,
251
+ workspace, workspaceId: rootRuntime.workspaceId,
252
+ providers: rootRuntime.providers, grants: rootRuntime.grants,
253
+ resolveWorkspace: resolveMcpWorkspace,
254
+ providersFor: target => runtimeFor(contextFor(workspace, target, root)).providers,
255
+ grantsFor: target => runtimeFor(contextFor(workspace, target, root)).grants,
184
256
  });
185
257
  const entryFile = entry ? relative(root,workspacePath(root,entry)).split('\\').join('/') : (statSync(path).isFile() ? basename(path) : '');
186
258
  if (entryFile) {
187
259
  const item=readDocument(workspacePath(root,entryFile));
188
260
  if(item.diagnostics.some(d=>d.severity==='error'))throw new DocumentError('入口 Markdown 无法解析。',422,item.diagnostics);
189
261
  }
190
- let selection;
191
- const publishSelection = next => {
262
+ const selections = new Map();
263
+ const publishSelection = (targetWorkspace, next) => {
264
+ const current = selections.get(targetWorkspace);
192
265
  if (next.refresh) {
193
- if (selection?.tab !== next.tab || selection.file !== next.file) return;
194
- if (next.refresh === 'render') selection = { ...next, expiresAt: Date.now() + 120000 };
195
- else if (selection.version === next.version) selection.expiresAt = Date.now() + 120000;
196
- } else if (next.nodes.length) selection = { ...next, expiresAt: Date.now() + 120000 };
197
- else if (selection?.tab === next.tab) selection = undefined;
266
+ if (current?.tab !== next.tab || current.file !== next.file) return;
267
+ if (next.refresh === 'render') selections.set(targetWorkspace, { ...next, expiresAt: Date.now() + 120000 });
268
+ else if (current.version === next.version) current.expiresAt = Date.now() + 120000;
269
+ } else if (next.nodes.length) selections.set(targetWorkspace, { ...next, expiresAt: Date.now() + 120000 });
270
+ else if (current?.tab === next.tab) selections.delete(targetWorkspace);
271
+ };
272
+ const readSelection = targetWorkspace => {
273
+ const current = selections.get(targetWorkspace);
274
+ return current?.expiresAt > Date.now() ? current : null;
275
+ };
276
+ const events = createWorkspaceEvents();
277
+ const baseService = createWorkspaceService(workspace, { documentRoot: root, readSelection });
278
+ const mcpService = async (tool, input = {}) => {
279
+ const result = await baseService(tool, input);
280
+ try {
281
+ const targetWorkspace = input?.workspace ? resolve(input.workspace) : workspace;
282
+ broadcastMcpEvent(events, { rootWorkspace: workspace, targetWorkspace, tool, input, result });
283
+ } catch {}
284
+ return result;
198
285
  };
286
+ mcpService.diagnostics = baseService.diagnostics;
199
287
  const agent = agentName !== 'off' ? (await import('./agent.js')).createAgentHandler({
200
288
  workspace, mcpUrl: () => 'http://127.0.0.1:' + server.address().port + '/mcp',
289
+ workspaceService: mcpService,
290
+ events,
291
+ resolveSettings: () => rootRuntime.settings.agentLaunch(),
292
+ resolveRuntimeInfo: targetWorkspace => {
293
+ const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
294
+ return {
295
+ stateDir: rt.ctx.state,
296
+ documentRoot: rt.root,
297
+ pluginDescriptors: rt.plugins?.descriptor.plugins || [],
298
+ };
299
+ },
201
300
  ...(agentName === 'acp' && { resolveLaunch: () => {
202
- const { command, args, env } = settings.agentLaunch();
301
+ const { command, args, env } = rootRuntime.settings.agentLaunch();
203
302
  return { command, args, env };
204
303
  } }),
205
304
  }) : null;
206
- function installPlugin(files) {
207
- const previous = plugins?.capabilities.length || 0;
208
- const installed = installWorkspacePlugin(ctx, files, plugins);
209
- if (plugins) {
210
- const descriptor = plugins.descriptor.plugins.find(plugin => plugin.id === installed.id);
211
- grants.set(installed.id, descriptor.permissions);
212
- providers.push(...plugins.capabilities.slice(previous));
213
- settings.register(installed.id, plugins.configurations.get(installed.id));
305
+ function installPlugin(targetWorkspace, files) {
306
+ const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
307
+ const previous = rt.plugins?.capabilities.length || 0;
308
+ const installed = installWorkspacePlugin(rt.ctx, files, rt.plugins);
309
+ if (rt.plugins) {
310
+ const descriptor = rt.plugins.descriptor.plugins.find(plugin => plugin.id === installed.id);
311
+ rt.grants.set(installed.id, descriptor.permissions);
312
+ rt.providers.push(...rt.plugins.capabilities.slice(previous));
313
+ rt.settings.register(installed.id, rt.plugins.configurations.get(installed.id));
214
314
  }
215
315
  return installed;
216
316
  }
217
- const handle = createWorkspaceHandler(root,{entrypoint:true,mode,theme,entry:entryFile,publishSelection,plugins,agent,agentProfile:agentName,capabilities,settings,installPlugin,
218
- inactivePlugins: () => inspectWorkspacePlugins(ctx.state)});
219
- const mcp = createMcpHandler(createWorkspaceService(workspace, { documentRoot: root, readSelection: () => selection?.expiresAt > Date.now() ? selection : null }), capabilities.invoke);
317
+ function servePluginAsset(req, res, url) {
318
+ const key = decodeURIComponent(url.pathname.slice('/library/plugin-assets/'.length).split('/')[0] || '');
319
+ for (const rt of runtimes.values()) {
320
+ if (rt.plugins?.hasAsset(key)) { rt.plugins.serveAsset(req, res, url); return; }
321
+ }
322
+ throw new DocumentError('插件资源不存在。', 404);
323
+ }
324
+ const handle = createWorkspaceHandler(root,{
325
+ entrypoint:true,mode,theme,entry:entryFile,publishSelection,events,
326
+ plugins:rootRuntime.plugins,experimentalPlugins,servePluginAsset,
327
+ agent,agentProfile:agentName,capabilities,settings:rootRuntime.settings,installPlugin,
328
+ resolveWorkspace:resolveWorkspaceParam,
329
+ listWorkspaces:() => discoverWorkspaces(workspace, root),
330
+ scopeName:basename(workspace),
331
+ inactivePlugins:rootRuntime.inactivePlugins,
332
+ });
333
+ const mcp = createMcpHandler(mcpService, capabilities.invoke);
220
334
  const server = createServer(async (req,res) => {
221
335
  try { const url = new URL(req.url,'http://127.0.0.1'); if (!await mcp(req,res,url) && !await handle(req,res,url)) { res.writeHead(404);res.end('Not found'); } }
222
336
  catch { if (!res.headersSent) res.writeHead(500);res.end('预览请求失败'); }
223
337
  });
224
338
  if (agent) server.on('close', agent.close);
339
+ server.on('close', events.close);
225
340
  await new Promise((resolve,reject) => { server.once('error',reject); server.listen(port,'127.0.0.1',resolve); });
226
341
  const file = entryFile ? '?file='+encodeURIComponent(entryFile) : '';
227
342
  const origin = 'http://127.0.0.1:'+server.address().port;
228
- return {server,url:origin+'/'+file,mcpUrl:origin+'/mcp',workspace,root,pluginWarnings:plugins?.warnings || [],stopAgent:agent?.close,stopCapabilities:capabilities.close};
343
+ return {server,url:origin+'/'+file,mcpUrl:origin+'/mcp',workspace,root,pluginWarnings:rootRuntime.plugins?.warnings || [],stopAgent:agent?.close,stopCapabilities:capabilities.close,stopEvents:events.close};
229
344
  }
@@ -312,6 +312,6 @@ export function installTo(cwd, ids, opts = {}) {
312
312
  * 是无害的额外键,于是统一都带上,省得一张表里两套写法。
313
313
  */
314
314
  function ownFileText(body) {
315
- const desc = '用 clado 把 Markdown 编译成自包含的网页(文档 / 卡片 / 脑图三种模式)';
315
+ const desc = '用 clado 把 Markdown 编译成自包含的网页(卡片 / 脑图 / 文档三种模式)';
316
316
  return `---\ndescription: ${desc}\nalwaysApply: false\n---\n\n${body}`;
317
317
  }