cladogram 0.5.5-beta.1 → 0.5.5-beta.3

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.
@@ -131,10 +131,34 @@
131
131
  ({ input }) => screenshot.capture(input, readScreenshotCanvas),
132
132
  ).catch(error => console.warn('Clado 截图能力注册失败', error));
133
133
  }
134
+ let followAi = true;
135
+ try { followAi = localStorage.getItem('clado-follow-ai') !== 'false'; } catch {}
136
+ function setFollowAi(next) {
137
+ followAi = !!next;
138
+ try { localStorage.setItem('clado-follow-ai', followAi ? 'true' : 'false'); } catch {}
139
+ }
140
+ function focusTarget(file, node, label) {
141
+ const targetFile = file || selected;
142
+ const nodes = node ? (Array.isArray(node) ? [node] : [[node]]) : [];
143
+ if (targetFile && targetFile !== selected) {
144
+ pendingTouch = { file: targetFile, nodes, kind: 'read', label: label || '', forcePan: true, ts: Date.now() };
145
+ open(targetFile);
146
+ return;
147
+ }
148
+ if (nodes.length && readyCanvas?.frame === frame) {
149
+ try { frame.contentWindow.postMessage({ type: 'clado-workspace:focus-node', node: nodes[0], label: label || '' }, offline ? '*' : location.origin); } catch {}
150
+ } else {
151
+ pendingTouch = { file: targetFile, nodes, kind: 'read', label: label || '', forcePan: true, ts: Date.now() };
152
+ flushPendingTouch();
153
+ }
154
+ }
134
155
  if (isEnabled('clado.agent')) window.CladoAgentPlugin(host, {
135
156
  placeholder: settings['clado.agent']?.placeholder,
136
157
  agentName: config.agentProfile === 'codex' ? 'Codex' : settings['clado.agent']?.name,
137
158
  endpoint: withWorkspace('/library/agent'),
159
+ followAi,
160
+ setFollowAi,
161
+ focusTarget,
138
162
  readCanvas() {
139
163
  if (readyCanvas?.frame !== frame) return undefined;
140
164
  const { file, revision } = readyCanvas;
@@ -313,9 +337,20 @@
313
337
  $('#updateError').textContent = '画布读取失败,保留上次画面并自动重试。'; $('#updateError').hidden = false; status('当前画布未更新', true);
314
338
  }
315
339
  }
340
+ let pendingRescan = false, pendingTouch = null;
341
+ function flushPendingTouch() {
342
+ if (!pendingTouch || Date.now() - pendingTouch.ts > 6000) { pendingTouch = null; return; }
343
+ if (pendingTouch.file && pendingTouch.file !== selected) return;
344
+ if (readyCanvas?.frame !== frame || readyCanvas.file !== selected) return;
345
+ const payload = pendingTouch;
346
+ pendingTouch = null;
347
+ const follow = typeof payload.follow === 'boolean' ? payload.follow : followAi;
348
+ try { frame.contentWindow.postMessage({ type: 'clado-workspace:ai-touch', ...payload, follow }, offline ? '*' : location.origin); } catch {}
349
+ }
316
350
  const status = (message, error) => directory.status(message, error);
317
351
  async function scan(force = false) {
318
- if (busy) return; busy = true;
352
+ if (busy) { if (force) pendingRescan = true; return; }
353
+ busy = true;
319
354
  try {
320
355
  if(offline) index=offline.index;
321
356
  else {
@@ -348,10 +383,13 @@
348
383
  const doc = index.documents.find(d => d.file === selected);
349
384
  if (!doc && !version && index.documents.length) open(index.documents[0].file);
350
385
  else if (!doc) { $('#updateError').textContent = '当前 Markdown 已删除或暂时无法解析,保留上次画面。有效文档仍可从目录打开。'; $('#updateError').hidden = false; status('当前画布未更新', true); $('#canvasLoading').hidden = true; post('ready'); }
351
- else { $('#updateError').hidden = true; if (force || doc.version !== version) { open(selected, version ? '' : pendingAnchor, { update: true }); } else status('已同步 ' + new Date(doc.modified).toLocaleTimeString('zh-CN', { hour12: false })); }
386
+ else { $('#updateError').hidden = true; if (force || doc.version !== version) { open(selected, version ? '' : pendingAnchor, { update: true }); } else { flushPendingTouch(); status('已同步 ' + new Date(doc.modified).toLocaleTimeString('zh-CN', { hour12: false })); } }
352
387
  }
353
388
  } catch { status('连接中断,正在重连', true); $('#updateError').textContent = '目录连接中断,保留当前画面。服务恢复后自动重连。'; $('#updateError').hidden = false; $('#canvasLoading').hidden = true; post('ready'); }
354
- finally { busy = false; }
389
+ finally {
390
+ busy = false;
391
+ if (pendingRescan) { pendingRescan = false; scan(true); }
392
+ }
355
393
  }
356
394
  addEventListener('message', event => {
357
395
  if ((!offline && event.origin !== location.origin) || event.source !== frame.contentWindow) return;
@@ -401,7 +439,15 @@
401
439
  else if (mode !== data.mode) frame.contentWindow.CladoPrototype?.setMode?.(mode);
402
440
  saveView(); $('#canvasLoading').hidden = true; syncChrome();
403
441
  try{frame.contentWindow.CladoPrototype?.setDesign(design);}catch{}
404
- if (!offline && pendingView) { const view = pendingView; pendingView = null; requestAnimationFrame(() => requestAnimationFrame(() => frame.contentWindow.CladoPrototype?.restoreView?.(view))); }
442
+ if (!offline && pendingView) {
443
+ const view = pendingView; pendingView = null;
444
+ requestAnimationFrame(() => requestAnimationFrame(() => {
445
+ frame.contentWindow.CladoPrototype?.restoreView?.(view);
446
+ flushPendingTouch();
447
+ }));
448
+ } else {
449
+ requestAnimationFrame(() => flushPendingTouch());
450
+ }
405
451
  status('已同步 ' + new Date(index.documents.find(d => d.file === selected)?.modified || Date.now()).toLocaleTimeString('zh-CN', { hour12: false })); post('ready');
406
452
  }
407
453
  });
@@ -409,5 +455,46 @@
409
455
  window.CladoPrototype = { setDesign, fit: () => frame.contentWindow.CladoPrototype?.fit(), closeLens: () => frame.contentWindow.CladoPrototype?.closeLens() };
410
456
  setDesign(design);
411
457
  scan();
412
- if (!offline) setInterval(() => scan(), 1200);
458
+ if (!offline) {
459
+ let sseReady = false;
460
+ if (typeof EventSource === 'function') {
461
+ try {
462
+ const es = new EventSource(withWorkspace('/library/events'));
463
+ es.addEventListener('ready', () => { sseReady = true; });
464
+ es.addEventListener('doc.updated', event => {
465
+ try {
466
+ const payload = JSON.parse(event.data || '{}');
467
+ if (!payload.file || payload.file === selected) pendingTouch = { ...payload, ts: Date.now() };
468
+ } catch {}
469
+ scan(true);
470
+ });
471
+ es.addEventListener('workspace.updated', () => scan(true));
472
+ es.addEventListener('agent.activity', event => {
473
+ try {
474
+ const payload = JSON.parse(event.data || '{}');
475
+ if (!payload.file || payload.file === selected) {
476
+ pendingTouch = { ...payload, ts: Date.now() };
477
+ flushPendingTouch();
478
+ }
479
+ } catch {}
480
+ });
481
+ es.addEventListener('agent.focus', event => {
482
+ try {
483
+ const payload = JSON.parse(event.data || '{}');
484
+ focusTarget(payload.file || selected, payload.nodes?.[0] || null, payload.label || '');
485
+ } catch {}
486
+ });
487
+ es.onerror = () => { sseReady = false; };
488
+ addEventListener('pagehide', () => es.close());
489
+ } catch {}
490
+ }
491
+ let lastFallbackPoll = Date.now();
492
+ // SSE 断线时按 1.2s 轮询;SSE 在线时退化为 5s 低频兜底,捕获绕过 MCP 的本地文件手改。
493
+ setInterval(() => {
494
+ if (!sseReady || Date.now() - lastFallbackPoll >= 5000) {
495
+ lastFallbackPoll = Date.now();
496
+ scan();
497
+ }
498
+ }, 1200);
499
+ }
413
500
  })();
@@ -0,0 +1,189 @@
1
+ /**
2
+ * 工作区实时事件总线(SSE)。
3
+ *
4
+ * 按子工作区绝对路径隔离订阅者,MCP 写入或读取节点时即时推送给在线画布,
5
+ * 替代纯轮询并驱动「AI 操作现场高亮(Live Presence)」。
6
+ */
7
+
8
+ export function createWorkspaceEvents() {
9
+ const subscribers = new Map();
10
+
11
+ function addSubscriber(key, entry) {
12
+ let bucket = subscribers.get(key);
13
+ if (!bucket) { bucket = new Set(); subscribers.set(key, bucket); }
14
+ bucket.add(entry);
15
+ }
16
+
17
+ function removeSubscriber(key, entry) {
18
+ clearInterval(entry.timer);
19
+ const bucket = subscribers.get(key);
20
+ if (!bucket) return;
21
+ bucket.delete(entry);
22
+ if (!bucket.size) subscribers.delete(key);
23
+ }
24
+
25
+ function subscribe(workspacePath, req, res) {
26
+ res.writeHead(200, {
27
+ 'content-type': 'text/event-stream; charset=utf-8',
28
+ 'cache-control': 'no-cache, no-transform',
29
+ connection: 'keep-alive',
30
+ 'x-accel-buffering': 'no',
31
+ });
32
+ res.write('event: ready\ndata: ' + JSON.stringify({ ok: true, ts: Date.now() }) + '\n\n');
33
+ const entry = {
34
+ res,
35
+ timer: setInterval(() => {
36
+ if (!res.writableEnded) res.write(': ping\n\n');
37
+ }, 25000),
38
+ };
39
+ entry.timer.unref?.();
40
+ addSubscriber(workspacePath, entry);
41
+ req.on('close', () => removeSubscriber(workspacePath, entry));
42
+ }
43
+
44
+ function emit(workspacePath, event, payload = {}) {
45
+ const bucket = subscribers.get(workspacePath);
46
+ if (!bucket || !bucket.size) return;
47
+ const frame = 'event: ' + event + '\ndata: ' + JSON.stringify({ ...payload, ts: Date.now() }) + '\n\n';
48
+ for (const entry of [...bucket]) {
49
+ if (entry.res.writableEnded) { removeSubscriber(workspacePath, entry); continue; }
50
+ try { entry.res.write(frame); }
51
+ catch { removeSubscriber(workspacePath, entry); }
52
+ }
53
+ }
54
+
55
+ function close() {
56
+ for (const [key, bucket] of [...subscribers]) {
57
+ for (const entry of [...bucket]) {
58
+ removeSubscriber(key, entry);
59
+ try { if (!entry.res.writableEnded) entry.res.end(); } catch {}
60
+ }
61
+ }
62
+ subscribers.clear();
63
+ }
64
+
65
+ return { subscribe, emit, close };
66
+ }
67
+
68
+ function uniquePaths(paths) {
69
+ const seen = new Set(), out = [];
70
+ for (const path of paths) {
71
+ if (!Array.isArray(path) || !path.length) continue;
72
+ const key = JSON.stringify(path);
73
+ if (seen.has(key)) continue;
74
+ seen.add(key);
75
+ out.push(path);
76
+ }
77
+ return out;
78
+ }
79
+
80
+ const nodeActionLabels = {
81
+ create: '新增节点',
82
+ insert: '补充正文',
83
+ update: '更新节点',
84
+ rename: '重命名节点',
85
+ move: '移动节点',
86
+ delete: '删除节点',
87
+ };
88
+
89
+ const docActionLabels = {
90
+ create: '新建文档',
91
+ copy: '复制文档',
92
+ update: '更新文档',
93
+ rename: '重命名文档',
94
+ delete: '删除文档',
95
+ };
96
+
97
+ /**
98
+ * 将单次 MCP 工具调用映射为实时画布事件并推送。
99
+ */
100
+ export function broadcastMcpEvent(events, { rootWorkspace, targetWorkspace, tool, input = {}, result }) {
101
+ if (!events || !targetWorkspace || input?.dryRun) return;
102
+ const action = input.action;
103
+
104
+ if (tool === 'clado_workspace') {
105
+ if (action === 'init') {
106
+ events.emit(targetWorkspace, 'workspace.updated', { action });
107
+ if (rootWorkspace && rootWorkspace !== targetWorkspace) {
108
+ events.emit(rootWorkspace, 'workspace.updated', { action });
109
+ }
110
+ }
111
+ return;
112
+ }
113
+
114
+ if (tool === 'clado_templates') {
115
+ if (['create', 'update', 'delete', 'pull', 'push'].includes(action)) {
116
+ events.emit(targetWorkspace, 'workspace.updated', { action: 'template.' + action });
117
+ }
118
+ return;
119
+ }
120
+
121
+ if (tool === 'clado_documents') {
122
+ if (['create', 'copy', 'update', 'rename', 'delete'].includes(action)) {
123
+ const file = result?.file || input.newFile || input.file || '';
124
+ const label = 'AI ' + (docActionLabels[action] || '更新文档') + (file ? ' · ' + file : '');
125
+ events.emit(targetWorkspace, 'doc.updated', { file, action, nodes: [], label });
126
+ if (rootWorkspace && rootWorkspace !== targetWorkspace) {
127
+ events.emit(rootWorkspace, 'workspace.updated', { action: 'doc.' + action });
128
+ }
129
+ }
130
+ return;
131
+ }
132
+
133
+ if (tool === 'clado_nodes') {
134
+ if (['read', 'query'].includes(action) && input.file) {
135
+ const nodes = uniquePaths([input.node]);
136
+ const title = nodes[0]?.at(-1) || input.file;
137
+ events.emit(targetWorkspace, 'agent.activity', {
138
+ file: input.file, action, kind: 'read', nodes, label: 'AI 正在阅读 · ' + title,
139
+ });
140
+ return;
141
+ }
142
+ if (['create', 'insert', 'update', 'rename', 'move', 'delete'].includes(action)) {
143
+ const fromResults = (result?.results || []).map(item => item?.path || item?.node);
144
+ const fallback = action === 'create'
145
+ ? [[...(input.parent || []), input.title].filter(Boolean)]
146
+ : [input.node];
147
+ const nodes = uniquePaths([...fromResults, ...fallback]);
148
+ const title = nodes[0]?.at(-1) || input.title || input.file || '';
149
+ const label = 'AI ' + (nodeActionLabels[action] || '更新节点') + (title ? ' · ' + title : '');
150
+ events.emit(targetWorkspace, 'doc.updated', {
151
+ file: input.targetFile || input.file || '', action, nodes, label,
152
+ });
153
+ }
154
+ return;
155
+ }
156
+
157
+ if (tool === 'clado_links') {
158
+ if (['connect', 'disconnect'].includes(action)) {
159
+ const nodes = uniquePaths([input.node, !input.targetFile ? input.targetNode : null]);
160
+ const title = nodes[0]?.at(-1) || input.file || '';
161
+ const label = 'AI ' + (action === 'connect' ? '建立连线' : '断开连线') + (title ? ' · ' + title : '');
162
+ events.emit(targetWorkspace, 'doc.updated', { file: input.file || '', action, nodes, label });
163
+ }
164
+ return;
165
+ }
166
+
167
+ if (tool === 'clado_batch') {
168
+ const byFile = new Map();
169
+ const record = (file, path) => {
170
+ if (!file) return;
171
+ const list = byFile.get(file) || [];
172
+ if (Array.isArray(path) && path.length) list.push(path);
173
+ byFile.set(file, list);
174
+ };
175
+ for (const item of result?.results || []) record(item?.file, item?.path);
176
+ for (const op of input.operations || []) {
177
+ record(op?.targetFile || op?.newFile || op?.file, op?.node || (op?.title ? [...(op.parent || []), op.title] : null));
178
+ }
179
+ if (!byFile.size) {
180
+ events.emit(targetWorkspace, 'workspace.updated', { action: 'batch' });
181
+ return;
182
+ }
183
+ for (const [file, paths] of byFile) {
184
+ const nodes = uniquePaths(paths);
185
+ const label = 'AI 批量更新 · ' + (nodes[0]?.at(-1) || file);
186
+ events.emit(targetWorkspace, 'doc.updated', { file, action: 'batch', nodes, label });
187
+ }
188
+ }
189
+ }
package/src/server/mcp.js CHANGED
@@ -23,19 +23,24 @@ const sourcePoint = z.discriminatedUnion('kind', [
23
23
  z.object({ kind: z.literal('table'), paragraph: indexFromOne, row: indexFromOne }).strict(),
24
24
  z.object({ kind: z.literal('mermaid'), paragraph: indexFromOne, nodeId: z.string().regex(/^[\w.-]+$/) }).strict()
25
25
  ]).optional().describe('同画布连线的起点。paragraph 来自 nodes.read;line 是代码块内行,空行计数;row 是表格数据行,不含表头;nodeId 是 Mermaid 节点 ID。行号从1开始。');
26
- const targetPoint = z.object({ kind: z.literal('table'), paragraph: indexFromOne, row: indexFromOne }).strict().optional().describe('可选表格落点,位于 targetNode 的正文;paragraph/row 从1开始,row 不含表头。与 sourcePoint 一起使用。');
26
+ const targetPoint = z.discriminatedUnion('kind', [
27
+ z.object({ kind: z.literal('line'), text: z.string().min(1).max(200).regex(/^[^\r\n]*\S[^\r\n]*$/).describe('目标节点正文或列表行中的稳定语义锚点文本,行号变动时仍可精准落点。') }).strict(),
28
+ z.object({ kind: z.literal('code'), paragraph: indexFromOne, line: indexFromOne, text: z.string().min(1).max(200).regex(/^[^\r\n]*\S[^\r\n]*$/).optional().describe('可选代码行内稳定语义锚点,行号微调时自动定位。') }).strict(),
29
+ z.object({ kind: z.literal('table'), paragraph: indexFromOne, row: indexFromOne, text: z.string().min(1).max(200).regex(/^[^\r\n]*\S[^\r\n]*$/).optional() }).strict(),
30
+ z.object({ kind: z.literal('mermaid'), paragraph: indexFromOne, nodeId: z.string().regex(/^[\w.-]+$/) }).strict(),
31
+ ]).optional().describe('同画布连线的精确落点,位于 targetNode 正文;支持正文/列表行(line+text)、代码行(code)、表格行(table)或 Mermaid 节点(mermaid),可与行内链接 position 或 sourcePoint 任意对称组合。');
27
32
  const nodeFields = {
28
- file: z.string().optional().describe('相对 documentRoot 的路径,新文件用 .mdc;旧 .md 兼容。'),
33
+ file: z.string().optional().describe('相对 documentRoot 的路径,支持 .md(推荐)与 .mdc。'),
29
34
  node: path().optional(), parent: path().optional().describe('父节点标题数组;省略表示一级卡片。'),
30
35
  title: z.string().optional(), content: text().optional().describe('仅本节点正文,直接传多行字符串,不含结构标题;更新保留孩子。'),
31
36
  index: z.number().int().nonnegative().optional().describe('同级节点插入序号,从0开始;省略追加到同级末尾。'), position, linkIndex: z.number().int().positive().optional().describe('links.list返回的节点内引用编号,从1开始;disconnect指定它只移除这一处。'), recursive: z.boolean().optional(), unlink: z.boolean().optional().describe('删除被引用目标时显式设true,移除入链但保留链接文字;默认拒绝。'),
32
- targetFile: z.string().optional().describe('相对 documentRoot 的目标文件路径,不是相对源文件目录;例如 iterations/sim-2/flow.mdc,不传 ../iterations/...。'), targetNode: path().optional(), label: z.string().optional(), before: text().optional(), after: text().optional(), sourcePoint, targetPoint,
37
+ targetFile: z.string().optional().describe('相对 documentRoot 的目标文件路径,不是相对源文件目录;例如 iterations/sim-2/flow.md,不传 ../iterations/...。'), targetNode: path().optional(), label: z.string().optional(), before: text().optional(), after: text().optional(), sourcePoint, targetPoint,
33
38
  newFile: z.string().optional(), source: text().optional(), metadata: z.record(z.string(), z.unknown()).optional(), templateId: z.string().optional(),
34
39
  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
35
40
  };
36
41
  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'];
37
42
  function createServer(invoke, invokeCapability) {
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。' });
43
+ const server = new McpServer({ name: 'clado', version: VERSION }, { instructions: '每次必填workspace。工作区未初始化才调用init;需要目录时用inspect。先读模板prompt再创建.md(也兼容.mdc)。新建、追加和唯一原文编辑可以直接提交;覆盖、删除和按编号定位时带目标版本。项目模板写入使用expectedWorkspaceVersion;用户模板写入用expectedUserTemplateVersion,push需两者。每次响应返回全量diagnostics;操作成功仍可能valid:false。diagnosticsComplete:false表示未完成检查。dryRun的previewDiagnostics对应候选状态;写入results给出最终位置。文档操作使用MCP。' });
39
44
  const schemas = new Map();
40
45
  const enrich = async (result, args) => {
41
46
  const { diagnostics: _operationDiagnostics, error, ...payload } = result;
@@ -70,7 +75,7 @@ function createServer(invoke, invokeCapability) {
70
75
  view: z.enum(['prompt','source','full']).optional().describe('read默认prompt,编辑规则用source,只有需要全部字段时才用full。'),
71
76
  expectedWorkspaceVersion: version, expectedUserTemplateVersion: z.string().optional().describe('读取返回的userTemplateVersion;用户库写入及push必填。'), dryRun: z.boolean().optional()
72
77
  });
73
- register('clado_documents', '文档list/read/create/copy/update/rename/delete。read默认full,按需view:nodes/source/summary。create用file(.mdc)/title/templateId,source只传正文。copy用file/newFile保留规则头和正文并重定位副本引用。create/copy检查目标尚不存在,可省略版本。update传完整source,可用metadata替换头;rename用newFile维护引用;delete被引用默认拒绝,unlink才断开。update/rename/delete使用expectedFileVersion或expectedWorkspaceVersion;results返回最终位置。', {
78
+ register('clado_documents', '文档list/read/create/copy/update/rename/delete。read默认full,按需view:nodes/source/summary。create用file(.md或.mdc)/title/templateId,source只传正文。copy用file/newFile保留规则头和正文并重定位副本引用。create/copy检查目标尚不存在,可省略版本。update传完整source,可用metadata替换头;rename用newFile维护引用;delete被引用默认拒绝,unlink才断开。update/rename/delete使用expectedFileVersion或expectedWorkspaceVersion;results返回最终位置。', {
74
79
  action: z.enum(['list','read','create','copy','update','rename','delete']), view: z.enum(['full','nodes','source','summary']).optional(), file: z.string().optional(), query: z.string().optional(), title: z.string().optional(), templateId: z.string().optional(), source: text().optional(), metadata: z.record(z.string(), z.unknown()).optional(), newFile: z.string().optional(), unlink: z.boolean().optional(), expectedFileVersion, expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
75
80
  });
76
81
  register('clado_nodes', '节点read/query/create/insert/update/rename/move/delete。file必填,node用标题数组。read返回nodeVersion、行号、同级index和段落编号。create在同级末尾新增可省略版本;指定index需文件版本。insert追加/置顶或按唯一anchor插入、update用position:{mode:replace,anchor:原文}时可省略版本。按段落编号或整段覆盖用expectedNodeVersion、expectedFileVersion或expectedWorkspaceVersion,均保留孩子。rename/move维护引用;delete有孩子需recursive。results返回最终位置。', {
@@ -16,10 +16,36 @@ const specs = {
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) {
@@ -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
  }
@@ -12,6 +12,7 @@ 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'};
@@ -57,6 +58,20 @@ export function createWorkspaceHandler(directory, options = {}) {
57
58
  options.publishSelection(target.workspace, selection.data);
58
59
  json(res, 200, { ok: true }); return true;
59
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
+ }
60
75
  if (options.agent && url.pathname === '/library/agent') {
61
76
  const target = resolveTarget(url);
62
77
  await options.agent.handle(req, res, target.workspace); return true;
@@ -258,8 +273,30 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
258
273
  const current = selections.get(targetWorkspace);
259
274
  return current?.expiresAt > Date.now() ? current : null;
260
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;
285
+ };
286
+ mcpService.diagnostics = baseService.diagnostics;
261
287
  const agent = agentName !== 'off' ? (await import('./agent.js')).createAgentHandler({
262
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
+ },
263
300
  ...(agentName === 'acp' && { resolveLaunch: () => {
264
301
  const { command, args, env } = rootRuntime.settings.agentLaunch();
265
302
  return { command, args, env };
@@ -285,7 +322,7 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
285
322
  throw new DocumentError('插件资源不存在。', 404);
286
323
  }
287
324
  const handle = createWorkspaceHandler(root,{
288
- entrypoint:true,mode,theme,entry:entryFile,publishSelection,
325
+ entrypoint:true,mode,theme,entry:entryFile,publishSelection,events,
289
326
  plugins:rootRuntime.plugins,experimentalPlugins,servePluginAsset,
290
327
  agent,agentProfile:agentName,capabilities,settings:rootRuntime.settings,installPlugin,
291
328
  resolveWorkspace:resolveWorkspaceParam,
@@ -293,14 +330,15 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
293
330
  scopeName:basename(workspace),
294
331
  inactivePlugins:rootRuntime.inactivePlugins,
295
332
  });
296
- const mcp = createMcpHandler(createWorkspaceService(workspace, { documentRoot: root, readSelection }), capabilities.invoke);
333
+ const mcp = createMcpHandler(mcpService, capabilities.invoke);
297
334
  const server = createServer(async (req,res) => {
298
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'); } }
299
336
  catch { if (!res.headersSent) res.writeHead(500);res.end('预览请求失败'); }
300
337
  });
301
338
  if (agent) server.on('close', agent.close);
339
+ server.on('close', events.close);
302
340
  await new Promise((resolve,reject) => { server.once('error',reject); server.listen(port,'127.0.0.1',resolve); });
303
341
  const file = entryFile ? '?file='+encodeURIComponent(entryFile) : '';
304
342
  const origin = 'http://127.0.0.1:'+server.address().port;
305
- return {server,url:origin+'/'+file,mcpUrl:origin+'/mcp',workspace,root,pluginWarnings:rootRuntime.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};
306
344
  }