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
@@ -1,10 +1,14 @@
1
1
  (() => {
2
2
  const $ = selector => document.querySelector(selector);
3
3
  let frame = $('#canvas');
4
- let index = { documents: [], skipped: [] }, selected = '', mode = window.__CLADO_WORKSPACE__?.mode || 'mindmap', version = '', history = [], busy = false, design = { theme: window.__CLADO_WORKSPACE__?.theme || 'light' }, pendingView = null, pendingOpen = null, pendingAnchor = '', chainModal = false, deferredRefresh = false;
4
+ let index = { documents: [], skipped: [] }, selected = '', mode = ['cards', 'mindmap', 'doc'].includes(window.__CLADO_WORKSPACE__?.mode) ? window.__CLADO_WORKSPACE__.mode : 'cards', version = '', history = [], busy = false, design = { theme: window.__CLADO_WORKSPACE__?.theme || 'light' }, pendingView = null, pendingOpen = null, pendingAnchor = '', chainModal = false, deferredRefresh = false;
5
5
  const config = window.__CLADO_WORKSPACE__ || {}, offline = config.offline;
6
+ const workspaceId = config.workspaceId || '';
7
+ const withWorkspace = path => !workspaceId ? path : path + (path.includes('?') ? '&' : '?') + 'workspace=' + encodeURIComponent(workspaceId);
8
+ const workspaceUrl = id => id ? '/?workspace=' + encodeURIComponent(id) : '/';
9
+ if (workspaceId) document.title = (config.workspaceName || workspaceId) + ' · Clado';
6
10
  const settings = config.pluginSettings || {};
7
- mode = settings['clado.view-controls']?.defaultMode || mode;
11
+ if (['cards', 'mindmap', 'doc'].includes(settings['clado.view-controls']?.defaultMode)) mode = settings['clado.view-controls'].defaultMode;
8
12
  const pluginKey = 'clado-disabled-plugins:' + (config.pluginPreferenceKey || location.pathname);
9
13
  let disabledPlugins = new Set();
10
14
  try {
@@ -13,14 +17,14 @@
13
17
  } catch {}
14
18
  const items = [
15
19
  { id: 'clado.brand', name: 'Clado 设置', reason: '管理入口,始终启用' },
16
- { id: 'clado.view-controls', name: '视图切换', detail: '脑图、卡片和文档视图' },
20
+ { id: 'clado.view-controls', name: '视图切换', detail: '卡片、脑图和文档视图' },
17
21
  { id: 'clado.directory', name: '文档目录', detail: '查找和打开工作区文档' },
18
22
  { id: 'clado.agent', name: '灵感', detail: '与 Agent 对话并协作修改画布', ...(!config.agent && { reason: offline ? '需要在线服务' : '当前服务已关闭聊天' }) },
19
23
  ...(config.pluginCatalog || []),
20
24
  ];
21
25
  const isEnabled = id => id === 'clado.brand' || !items.some(item => item.id === id && item.reason) && !disabledPlugins.has(id);
22
26
  const ui = window.CladoPluginUI;
23
- const capabilities = window.CladoCapabilityBridge?.();
27
+ const capabilities = window.CladoCapabilityBridge?.(workspaceId);
24
28
  const host = ui.createHost(capabilities, isEnabled);
25
29
  const screenshot = window.CladoScreenshot?.();
26
30
  let lensOpen = false;
@@ -33,7 +37,7 @@
33
37
  }
34
38
  async function editPluginSettings(id, value, expected) {
35
39
  const write = arguments.length > 1;
36
- const response = await fetch('/library/plugin-settings?id=' + encodeURIComponent(id), write ? {
40
+ const response = await fetch(withWorkspace('/library/plugin-settings?id=' + encodeURIComponent(id)), write ? {
37
41
  method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value, expected }),
38
42
  } : { cache: 'no-store' });
39
43
  const result = await response.json();
@@ -46,7 +50,7 @@
46
50
  items, isEnabled,
47
51
  edit: config.hasPluginSettings ? editPluginSettings : null,
48
52
  install: config.canInstallPlugins && (async files => {
49
- const response = await fetch('/library/install-plugin', {
53
+ const response = await fetch(withWorkspace('/library/install-plugin'), {
50
54
  method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ files }),
51
55
  });
52
56
  const result = await response.json();
@@ -91,6 +95,8 @@
91
95
  showFilename: settings['clado.directory']?.showFilename !== false,
92
96
  open: file => open(file),
93
97
  openFromCapability,
98
+ workspaceUrl,
99
+ switchWorkspace: id => { location.href = workspaceUrl(id); },
94
100
  refresh: () => scan(true),
95
101
  back: () => {
96
102
  if (modalLocked()) return;
@@ -101,7 +107,7 @@
101
107
  if (!selected) throw new Error('no document');
102
108
  if (offline) return { file: selected, source: offline.sources[selected], offline: true };
103
109
  const file = selected;
104
- const response = await fetch('/library/source.mdc?file=' + encodeURIComponent(file), { cache: 'no-store' });
110
+ const response = await fetch(withWorkspace('/library/source.mdc?file=' + encodeURIComponent(file)), { cache: 'no-store' });
105
111
  if (!response.ok) throw new Error('source');
106
112
  return { file, source: await response.text() };
107
113
  },
@@ -125,9 +131,34 @@
125
131
  ({ input }) => screenshot.capture(input, readScreenshotCanvas),
126
132
  ).catch(error => console.warn('Clado 截图能力注册失败', error));
127
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
+ }
128
155
  if (isEnabled('clado.agent')) window.CladoAgentPlugin(host, {
129
156
  placeholder: settings['clado.agent']?.placeholder,
130
157
  agentName: config.agentProfile === 'codex' ? 'Codex' : settings['clado.agent']?.name,
158
+ endpoint: withWorkspace('/library/agent'),
159
+ followAi,
160
+ setFollowAi,
161
+ focusTarget,
131
162
  readCanvas() {
132
163
  if (readyCanvas?.frame !== frame) return undefined;
133
164
  const { file, revision } = readyCanvas;
@@ -139,7 +170,7 @@
139
170
  if (!['light', 'dark'].includes(design.theme)) design.theme = 'light';
140
171
  try { const savedTheme = localStorage.getItem('clado-theme'); if (['light', 'dark'].includes(savedTheme)) design.theme = savedTheme; } catch {}
141
172
  if (config.plugins) window.CladoPluginHost({
142
- host, capabilities, isEnabled,
173
+ host, capabilities, isEnabled, workspaceId,
143
174
  readView() {
144
175
  if (readyCanvas?.frame !== frame) return null;
145
176
  const { file, revision } = readyCanvas;
@@ -151,7 +182,7 @@
151
182
  if (selectionTab) frame.contentWindow.postMessage({ type: 'clado-workspace:selection', nodes: aiSelection?.nodes || [] }, location.origin);
152
183
  }
153
184
  async function publishSelection(selection) {
154
- const response = await fetch('/library/selection', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ tab: selectionTab, ...selection }), keepalive: true });
185
+ const response = await fetch(withWorkspace('/library/selection'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ tab: selectionTab, ...selection }), keepalive: true });
155
186
  if (!response.ok) throw new Error('selection');
156
187
  }
157
188
  function setSelection(next, refresh = false) {
@@ -181,12 +212,12 @@
181
212
  if (aiSelection && !pageHidden) publishSelection({ ...aiSelection, refresh: 'heartbeat' }).catch(() => {});
182
213
  }, 20000);
183
214
  }
184
- const storageKey='clado-library-view:v2:'+location.pathname;
215
+ const storageKey='clado-library-view:v2:'+location.pathname+(workspaceId?':'+workspaceId:'');
185
216
  const post = (type, extra = {}) => { if (parent !== window) parent.postMessage({ type: 'clado-prototype:' + type, board: 'library', ...extra }, location.origin); };
186
- try { const saved = JSON.parse(sessionStorage.getItem(storageKey) || '{}'); selected = saved.file || ''; if (!config.mode && ['mindmap','cards','doc'].includes(saved.mode)) mode = saved.mode; } catch {}
217
+ try { const saved = JSON.parse(sessionStorage.getItem(storageKey) || '{}'); selected = saved.file || ''; if (!config.mode && ['cards','mindmap','doc'].includes(saved.mode)) mode = saved.mode; } catch {}
187
218
  try {
188
219
  const restoredMode = sessionStorage.getItem(pluginKey + ':mode');
189
- if (['mindmap','cards','doc'].includes(restoredMode)) mode = restoredMode;
220
+ if (['cards','mindmap','doc'].includes(restoredMode)) mode = restoredMode;
190
221
  if (restoredMode) sessionStorage.removeItem(pluginKey + ':mode');
191
222
  } catch {}
192
223
  const requestedFile = new URLSearchParams(location.search).get('file');
@@ -204,13 +235,43 @@
204
235
  if(!chainModal) { const force=deferredRefresh;deferredRefresh=false;scan(force); }
205
236
  }
206
237
  function renderDirectory() { directory.update(index, selected, history.length > 0); }
238
+ let emptyWorkspaceSignature = '';
239
+ function renderEmptyWorkspaces(list) {
240
+ const others = list.filter(item => item.id !== workspaceId);
241
+ const next = JSON.stringify(others.map(item => [item.id, item.name, item.documents]));
242
+ if (next === emptyWorkspaceSignature) return;
243
+ emptyWorkspaceSignature = next;
244
+ let container = $('#emptyState .empty-workspaces');
245
+ if (!others.length) { container?.remove(); return; }
246
+ if (!container) {
247
+ container = document.createElement('div');
248
+ container.className = 'empty-workspaces';
249
+ $('#emptyState').append(container);
250
+ }
251
+ container.replaceChildren();
252
+ const title = document.createElement('div');
253
+ title.className = 'empty-workspaces-title';
254
+ title.textContent = '已发现的子工作区(点击打开)';
255
+ container.append(title);
256
+ for (const item of others) {
257
+ const link = document.createElement('a');
258
+ link.className = 'empty-workspace-card';
259
+ link.href = workspaceUrl(item.id);
260
+ const name = document.createElement('span');
261
+ name.textContent = item.id || (item.name + '(根目录)');
262
+ const count = document.createElement('small');
263
+ count.textContent = (item.documents ?? 0) + ' 份画布';
264
+ link.append(name, count);
265
+ container.append(link);
266
+ }
267
+ }
207
268
  let renderRequest = 0;
208
269
  async function openFromCapability(file) {
209
270
  const failure = (kind, message) => Object.assign(new Error(message), { kind });
210
271
  if (modalLocked() || lensOpen) throw failure('VIEW_LOCKED', '请先关闭链路或内容放大窗口。');
211
272
  let targetDocument = index.documents.find(entry => entry.file === file);
212
273
  if (!targetDocument) {
213
- const response = await fetch('/library/index.json', { cache: 'no-store' });
274
+ const response = await fetch(withWorkspace('/library/index.json'), { cache: 'no-store' });
214
275
  if (!response.ok) throw failure('NAVIGATION_FAILED', '读取文档目录失败,请重试。');
215
276
  const latest = await response.json();
216
277
  targetDocument = latest.documents.find(entry => entry.file === file);
@@ -254,7 +315,7 @@
254
315
  let html;
255
316
  if(offline) html=offline.canvases[file].replace(/<!--CLADO-ASSET:(\d+)-->/g,(_,id)=>offline.shared?.[id] || '');
256
317
  else {
257
- const response = await fetch('/library/canvas?file=' + encodeURIComponent(file) + '&mode=' + mode + '&theme=' + design.theme + '&chrome=workspace&revision=' + version + (anchor ? '&anchor=' + encodeURIComponent(anchor) : ''), {cache:'no-store'});
318
+ const response = await fetch(withWorkspace('/library/canvas?file=' + encodeURIComponent(file) + '&mode=' + mode + '&theme=' + design.theme + '&chrome=workspace&revision=' + version + (anchor ? '&anchor=' + encodeURIComponent(anchor) : '')), {cache:'no-store'});
258
319
  if(!response.ok)throw new Error('render');
259
320
  html = await response.text();
260
321
  }
@@ -276,12 +337,36 @@
276
337
  $('#updateError').textContent = '画布读取失败,保留上次画面并自动重试。'; $('#updateError').hidden = false; status('当前画布未更新', true);
277
338
  }
278
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
+ }
279
350
  const status = (message, error) => directory.status(message, error);
280
351
  async function scan(force = false) {
281
- if (busy) return; busy = true;
352
+ if (busy) { if (force) pendingRescan = true; return; }
353
+ busy = true;
282
354
  try {
283
355
  if(offline) index=offline.index;
284
- else { const response=await fetch('/library/index.json',{cache:'no-store'});if(!response.ok)throw new Error('scan');index=await response.json(); }
356
+ else {
357
+ const [indexRes, workspacesRes] = await Promise.all([
358
+ fetch(withWorkspace('/library/index.json'), { cache: 'no-store' }),
359
+ config.multiWorkspace ? fetch('/library/workspaces.json', { cache: 'no-store' }).catch(() => null) : Promise.resolve(null),
360
+ ]);
361
+ if(!indexRes.ok)throw new Error('scan');
362
+ index=await indexRes.json();
363
+ if (workspacesRes?.ok) {
364
+ const data = await workspacesRes.json();
365
+ const list = Array.isArray(data.workspaces) ? data.workspaces : [];
366
+ directory.updateWorkspaces?.(workspaceId, list);
367
+ renderEmptyWorkspaces(list);
368
+ }
369
+ }
285
370
  renderDirectory();
286
371
  try{frame.contentWindow.postMessage({type:'clado-workspace:index',index},'*');}catch{}
287
372
  if(modalLocked()) {
@@ -298,10 +383,13 @@
298
383
  const doc = index.documents.find(d => d.file === selected);
299
384
  if (!doc && !version && index.documents.length) open(index.documents[0].file);
300
385
  else if (!doc) { $('#updateError').textContent = '当前 Markdown 已删除或暂时无法解析,保留上次画面。有效文档仍可从目录打开。'; $('#updateError').hidden = false; status('当前画布未更新', true); $('#canvasLoading').hidden = true; post('ready'); }
301
- 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 })); } }
302
387
  }
303
388
  } catch { status('连接中断,正在重连', true); $('#updateError').textContent = '目录连接中断,保留当前画面。服务恢复后自动重连。'; $('#updateError').hidden = false; $('#canvasLoading').hidden = true; post('ready'); }
304
- finally { busy = false; }
389
+ finally {
390
+ busy = false;
391
+ if (pendingRescan) { pendingRescan = false; scan(true); }
392
+ }
305
393
  }
306
394
  addEventListener('message', event => {
307
395
  if ((!offline && event.origin !== location.origin) || event.source !== frame.contentWindow) return;
@@ -351,7 +439,15 @@
351
439
  else if (mode !== data.mode) frame.contentWindow.CladoPrototype?.setMode?.(mode);
352
440
  saveView(); $('#canvasLoading').hidden = true; syncChrome();
353
441
  try{frame.contentWindow.CladoPrototype?.setDesign(design);}catch{}
354
- 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
+ }
355
451
  status('已同步 ' + new Date(index.documents.find(d => d.file === selected)?.modified || Date.now()).toLocaleTimeString('zh-CN', { hour12: false })); post('ready');
356
452
  }
357
453
  });
@@ -359,5 +455,46 @@
359
455
  window.CladoPrototype = { setDesign, fit: () => frame.contentWindow.CladoPrototype?.fit(), closeLens: () => frame.contentWindow.CladoPrototype?.closeLens() };
360
456
  setDesign(design);
361
457
  scan();
362
- 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
+ }
363
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
+ }
@@ -10,7 +10,7 @@ const json=value=>JSON.stringify(value).replace(/</g,'\\u003c');
10
10
  const script=value=>'<script>'+value.replace(/<\/script/gi,'<\\/script')+'</script>';
11
11
  const mime={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'};
12
12
  /** One portable workspace, including all canvases, navigation, sources and local media. */
13
- export function renderWorkspace(jobs,{root,entry,mode='mindmap',theme='light',title}={}) {
13
+ export function renderWorkspace(jobs,{root,entry,mode='cards',theme='light',title}={}) {
14
14
  root=resolve(root);
15
15
  const documents=jobs.map(j=>({file:relative(root,j.file).split('\\').join('/'),title:j.doc.title,version:'offline',modified:0}));
16
16
  const index={root:basename(root)+'/',documents,skipped:[]},canvases={},sources={},shared=[],assetIds=new Map();
package/src/server/mcp.js CHANGED
@@ -25,25 +25,25 @@ const sourcePoint = z.discriminatedUnion('kind', [
25
25
  ]).optional().describe('同画布连线的起点。paragraph 来自 nodes.read;line 是代码块内行,空行计数;row 是表格数据行,不含表头;nodeId 是 Mermaid 节点 ID。行号从1开始。');
26
26
  const targetPoint = z.object({ kind: z.literal('table'), paragraph: indexFromOne, row: indexFromOne }).strict().optional().describe('可选表格落点,位于 targetNode 的正文;paragraph/row 从1开始,row 不含表头。与 sourcePoint 一起使用。');
27
27
  const nodeFields = {
28
- file: z.string().optional().describe('相对 documentRoot 的路径,新文件用 .mdc;旧 .md 兼容。'),
28
+ file: z.string().optional().describe('相对 documentRoot 的路径,支持 .md(推荐)与 .mdc。'),
29
29
  node: path().optional(), parent: path().optional().describe('父节点标题数组;省略表示一级卡片。'),
30
30
  title: z.string().optional(), content: text().optional().describe('仅本节点正文,直接传多行字符串,不含结构标题;更新保留孩子。'),
31
31
  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,
32
+ 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
33
  newFile: z.string().optional(), source: text().optional(), metadata: z.record(z.string(), z.unknown()).optional(), templateId: z.string().optional(),
34
34
  baseTemplateId: z.string().optional(), name: z.string().optional(), purpose: text().optional(), overwrite: z.boolean().optional(), scope: z.enum(['project','user']).optional(), from: templateSource, expectedFileVersion, expectedNodeVersion
35
35
  };
36
36
  const operations = ['document.create','document.copy','document.update','document.rename','document.delete','node.create','node.insert','node.update','node.rename','node.move','node.delete','link.connect','link.disconnect','template.create','template.update','template.delete','template.pull'];
37
37
  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。' });
38
+ 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
39
  const schemas = new Map();
40
- const enrich = (result, args) => {
40
+ const enrich = async (result, args) => {
41
41
  const { diagnostics: _operationDiagnostics, error, ...payload } = result;
42
- const report = invoke.diagnostics(args);
42
+ const report = await invoke.diagnostics(args);
43
43
  return { ...(error ? { error } : {}), ...report, ...payload, valid: report.valid };
44
44
  };
45
45
  const encoded = (result, isError = false) => ({ ...(isError ? { isError: true } : {}), content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: result });
46
- const failure = (error, args) => encoded(enrich({ error: { message: error.message, status: error.status || 500, code: error.details?.code || 'CLADO_OPERATION_FAILED', ...(error.details ? { details: error.details } : {}), ...(error.diagnostics?.length ? { operationDiagnostics: error.diagnostics } : {}) } }, args), true);
46
+ const failure = async (error, args) => encoded(await enrich({ error: { message: error.message, status: error.status || 500, code: error.details?.code || 'CLADO_OPERATION_FAILED', ...(error.details ? { details: error.details } : {}), ...(error.diagnostics?.length ? { operationDiagnostics: error.diagnostics } : {}) } }, args), true);
47
47
  const capabilityResult = result => {
48
48
  if (!isCaptureTarget(result.provider)) return encoded(result);
49
49
  const { pngBase64, ...output } = result.output;
@@ -56,12 +56,12 @@ function createServer(invoke, invokeCapability) {
56
56
  return server.registerTool(name, {
57
57
  description, inputSchema: { workspace, ...schema }, annotations: { readOnlyHint: readOnly, destructiveHint: !readOnly, openWorldHint: false }
58
58
  }, async args => {
59
- try { return encode(enrich(await handler(name, args), args)); }
60
- catch (error) { return failure(error, args); }
59
+ try { return encode(await enrich(await handler(name, args), args)); }
60
+ catch (error) { return await failure(error, args); }
61
61
  });
62
62
  };
63
- register('clado_workspace', '初始化、查看工作区、搜索或校验。用户说“我选的卡片”时用selection,按点选顺序读取标题路径、正文、后代和版本。selectionStatus为empty或stale时请用户选中或重新选择。inspect返回工作区版本和目录;init准备工作区。', {
64
- action: z.enum(['init','inspect','search','validate','selection']), query: z.string().optional(), includeContent: z.boolean().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(100).optional()
63
+ register('clado_workspace', '初始化、查看工作区、列出子工作区、搜索或校验。用户说“我选的卡片”时用selection,按点选顺序读取标题路径、正文、后代和版本。selectionStatus为empty或stale时请用户选中或重新选择。inspect返回工作区版本和目录;workspaces列出当前服务范围内的子工作区;init准备工作区。', {
64
+ action: z.enum(['init','inspect','search','validate','selection','workspaces']), query: z.string().optional(), includeContent: z.boolean().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(100).optional()
65
65
  });
66
66
  register('clado_templates', '管理模板:scope默认project,设user操作用户库。read默认只返回prompt;编辑时view:source读完整MDC,view:full才返回metadata/source/starter/prompt全部内容。按当前项目、逐层上级、用户库查找,返回来源目录。create传templateId及source,或baseTemplateId(可选name/purpose)复制为新模板;update传完整source。模板头包含id/name/version/purpose/hard_constraints/soft_constraints/organization。pull复制到当前项目,默认逐层查找上级项目再查用户库,可用from:ancestor或from:user指定;push同步到用户库。不同内容默认拒绝覆盖,确认后overwrite:true。项目写入需expectedWorkspaceVersion,用户写入需expectedUserTemplateVersion,push需两者;均可dryRun。修改模板不影响已有文档头部。', {
67
67
  action: z.enum(['list','read','create','update','delete','pull','push']), scope: z.enum(['project','user']).optional(),
@@ -70,13 +70,13 @@ function createServer(invoke, invokeCapability) {
70
70
  view: z.enum(['prompt','source','full']).optional().describe('read默认prompt,编辑规则用source,只有需要全部字段时才用full。'),
71
71
  expectedWorkspaceVersion: version, expectedUserTemplateVersion: z.string().optional().describe('读取返回的userTemplateVersion;用户库写入及push必填。'), dryRun: z.boolean().optional()
72
72
  });
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返回最终位置。', {
73
+ 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
74
  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
75
  });
76
76
  register('clado_nodes', '节点read/query/create/insert/update/rename/move/delete。file必填,node用标题数组。read返回nodeVersion、行号、同级index和段落编号。create在同级末尾新增可省略版本;指定index需文件版本。insert追加/置顶或按唯一anchor插入、update用position:{mode:replace,anchor:原文}时可省略版本。按段落编号或整段覆盖用expectedNodeVersion、expectedFileVersion或expectedWorkspaceVersion,均保留孩子。rename/move维护引用;delete有孩子需recursive。results返回最终位置。', {
77
77
  action: z.enum(['read','query','create','insert','update','rename','move','delete']), ...Object.fromEntries(['file','node','parent','title','content','index','position','recursive','unlink','targetFile'].map(key => [key, nodeFields[key]])), relation: z.enum(['parent','children','ancestors','descendants','siblings','upstream','downstream']).optional(), depth: z.number().int().min(1).max(100).optional(), includeContent: z.boolean().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(100).optional(), expectedFileVersion, expectedNodeVersion, expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
78
78
  });
79
- register('clado_links', 'list返回href、sourceText、nodeVersion、linkIndex(从1开始)及位置。connect用源file/node和目标targetFile/targetNode;省略position追加,也可用唯一anchor定位文字。这两种可省略版本。按段落、精确起点连接或disconnect需要节点或文件版本,精确落点需要文件或工作区版本。sourcePoint支持代码行、表格行、Mermaid节点,只用于同画布且与position/before/after互斥。disconnect用linkIndex只断一处,普通链接保留文字。', {
79
+ register('clado_links', 'list返回href、sourceText、nodeVersion、linkIndex(从1开始)及位置。connect用源file/node和目标targetFile/targetNode建立连线:默认从具体内容行出发(用sourcePoint绑定代码行/表格行/Mermaid节点,或用position:{mode:replace,anchor:原文}把正文中的方法/步骤/字段词变成行内链接),不建议在卡片末尾单独追加裸的卡片连卡片。按段落、精确起点连接或disconnect需要节点或文件版本,精确落点需要文件或工作区版本。sourcePoint只用于同画布且与position/before/after互斥。disconnect用linkIndex只断一处,普通链接保留文字。', {
80
80
  action: z.enum(['list','connect','disconnect']), ...Object.fromEntries(['file','node','targetFile','targetNode','label','before','after','position','linkIndex','sourcePoint','targetPoint'].map(key => [key, nodeFields[key]])), expectedFileVersion, expectedNodeVersion, expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
81
81
  });
82
82
  register('clado_batch', '按顺序执行1–100个操作。支持可选的expectedWorkspaceVersion,各操作也可带自己的expectedFileVersion或expectedNodeVersion。每步的版本和标题路径按前序操作后的候选状态校验。模板操作使用工作区版本。任一冲突整批不保存;dryRun只预览。', {
@@ -96,11 +96,11 @@ function createServer(invoke, invokeCapability) {
96
96
  }, (_, { workspace, viewId, mode, source, scope }) => invokeCapability({
97
97
  workspace, viewId, action: 'call', to: captureTarget, input: { ...(mode && { mode }), ...(source && { source }), ...(scope && { scope }) },
98
98
  }), { encode: capabilityResult, readOnly: true });
99
- return { server, checkCall: (name, args) => {
99
+ return { server, checkCall: async (name, args) => {
100
100
  const schema = schemas.get(name);
101
- if (!schema) return failure({ message: '没有这个工具:' + name, status: 400 }, args);
101
+ if (!schema) return await failure({ message: '没有这个工具:' + name, status: 400 }, args);
102
102
  const checked = schema.safeParse(args);
103
- if (!checked.success) return failure({ message: '工具参数不合法。', status: 400, details: { code: 'INVALID_ARGUMENTS', issues: checked.error.issues } }, args);
103
+ if (!checked.success) return await failure({ message: '工具参数不合法。', status: 400, details: { code: 'INVALID_ARGUMENTS', issues: checked.error.issues } }, args);
104
104
  return null;
105
105
  } };
106
106
  }
@@ -118,7 +118,7 @@ export function createMcpHandler(invoke, invokeCapability) {
118
118
  const data = JSON.parse(Buffer.concat(chunks).toString('utf8'));
119
119
  const created = createServer(invoke, invokeCapability); server = created.server;
120
120
  if (data.method === 'tools/call') {
121
- const rejected = created.checkCall(data.params?.name, data.params?.arguments);
121
+ const rejected = await created.checkCall(data.params?.name, data.params?.arguments);
122
122
  if (rejected) { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ jsonrpc: '2.0', id: data.id ?? null, result: rejected })); await server.close(); return true; }
123
123
  }
124
124
  transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });