cladogram 0.5.2 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +30 -2
  2. package/bin/clado.js +55 -3
  3. package/docs/plugin-development.md +135 -0
  4. package/docs/plugin-ui.md +43 -0
  5. package/docs/release.md +26 -0
  6. package/package.json +8 -1
  7. package/plugins/agent/index.js +181 -0
  8. package/plugins/agent/style.css +105 -0
  9. package/plugins/brand/index.js +262 -0
  10. package/plugins/brand/style.css +162 -0
  11. package/plugins/directory/capabilities.json +27 -0
  12. package/plugins/directory/index.js +146 -0
  13. package/plugins/directory/style.css +48 -0
  14. package/plugins/view-controls/index.js +58 -0
  15. package/plugins/view-controls/style.css +46 -0
  16. package/skills/clado/SKILL.md +31 -17
  17. package/src/html/app-css.js +11 -42
  18. package/src/html/canvas-chain.js +5 -6
  19. package/src/html/canvas-focus.js +3 -4
  20. package/src/html/canvas-screenshot.js +199 -0
  21. package/src/html/canvas-ui.css +37 -9
  22. package/src/html/canvas-ui.js +35 -27
  23. package/src/html/page.js +11 -37
  24. package/src/html/plugin-assets.js +33 -0
  25. package/src/html/plugin-ui.css +176 -0
  26. package/src/html/plugin-ui.js +45 -0
  27. package/src/html/runtime-api.js +47 -0
  28. package/src/html/runtime.js +15 -12
  29. package/src/server/agent.js +222 -0
  30. package/src/server/assets/clado-plugin-sdk.js +111 -0
  31. package/src/server/assets/library-canvas.js +72 -11
  32. package/src/server/assets/library-plugin-bridge.js +84 -0
  33. package/src/server/assets/library-plugins.css +39 -0
  34. package/src/server/assets/library-plugins.js +200 -0
  35. package/src/server/assets/library.css +3 -6
  36. package/src/server/assets/library.html +2 -12
  37. package/src/server/assets/library.js +280 -44
  38. package/src/server/canvas-capture.js +47 -0
  39. package/src/server/export.js +5 -2
  40. package/src/server/mcp.js +44 -19
  41. package/src/server/plugin-capabilities.js +172 -0
  42. package/src/server/plugin-settings.js +117 -0
  43. package/src/server/plugins.js +236 -0
  44. package/src/server/workspace.js +157 -12
  45. package/src/skill/targets.js +1 -1
  46. package/src/util/update.js +58 -0
  47. package/src/vendor/html-to-image.min.js +24 -0
  48. package/src/workspace/content.js +3 -2
  49. package/src/workspace/service.js +81 -21
  50. package/src/workspace/tree.js +38 -0
  51. package/src/server/assets/tree.js +0 -26
@@ -1,12 +1,194 @@
1
1
  (() => {
2
2
  const $ = selector => document.querySelector(selector);
3
3
  let frame = $('#canvas');
4
- const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
5
- let index = { documents: [], skipped: [] }, selected = '', mode = window.__CLADO_WORKSPACE__?.mode || 'mindmap', version = '', history = [], busy = false, design = { theme: window.__CLADO_WORKSPACE__?.theme || 'light' }, pendingView = null, directorySignature = '', pendingOpen = null, pendingAnchor = '', chainModal = false, deferredRefresh = false;
6
- const config=window.__CLADO_WORKSPACE__ || {}, offline=config.offline, folders=new Set();
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;
5
+ const config = window.__CLADO_WORKSPACE__ || {}, offline = config.offline;
6
+ const settings = config.pluginSettings || {};
7
+ mode = settings['clado.view-controls']?.defaultMode || mode;
8
+ const pluginKey = 'clado-disabled-plugins:' + (config.pluginPreferenceKey || location.pathname);
9
+ let disabledPlugins = new Set();
10
+ try {
11
+ const saved = JSON.parse(localStorage.getItem(pluginKey) || '[]');
12
+ if (Array.isArray(saved)) disabledPlugins = new Set(saved);
13
+ } catch {}
14
+ const items = [
15
+ { id: 'clado.brand', name: 'Clado 设置', reason: '管理入口,始终启用' },
16
+ { id: 'clado.view-controls', name: '视图切换', detail: '脑图、卡片和文档视图' },
17
+ { id: 'clado.directory', name: '文档目录', detail: '查找和打开工作区文档' },
18
+ { id: 'clado.agent', name: '灵感', detail: '与 Agent 对话并协作修改画布', ...(!config.agent && { reason: offline ? '需要在线服务' : '当前服务已关闭聊天' }) },
19
+ ...(config.pluginCatalog || []),
20
+ ];
21
+ const isEnabled = id => id === 'clado.brand' || !items.some(item => item.id === id && item.reason) && !disabledPlugins.has(id);
22
+ const ui = window.CladoPluginUI;
23
+ const capabilities = window.CladoCapabilityBridge?.();
24
+ const host = ui.createHost(capabilities, isEnabled);
25
+ const screenshot = window.CladoScreenshot?.();
26
+ let lensOpen = false;
27
+ function reloadWithMode(preserve) {
28
+ try {
29
+ if (preserve) sessionStorage.setItem(pluginKey + ':mode', mode);
30
+ else sessionStorage.removeItem(pluginKey + ':mode');
31
+ } catch {}
32
+ location.reload();
33
+ }
34
+ async function editPluginSettings(id, value, expected) {
35
+ const write = arguments.length > 1;
36
+ const response = await fetch('/library/plugin-settings?id=' + encodeURIComponent(id), write ? {
37
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value, expected }),
38
+ } : { cache: 'no-store' });
39
+ const result = await response.json();
40
+ if (!response.ok) throw new Error(result.error);
41
+ if (write) reloadWithMode(id !== 'clado.view-controls');
42
+ return result;
43
+ }
44
+ const brand = ui.mountBrand(host, {
45
+ plugins: {
46
+ items, isEnabled,
47
+ edit: config.hasPluginSettings ? editPluginSettings : null,
48
+ install: config.canInstallPlugins && (async files => {
49
+ const response = await fetch('/library/install-plugin', {
50
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ files }),
51
+ });
52
+ const result = await response.json();
53
+ if (!response.ok) throw new Error(result.error);
54
+ return result;
55
+ }),
56
+ refresh: () => reloadWithMode(true),
57
+ save(disabled) {
58
+ const next = new Set(disabledPlugins);
59
+ for (const plugin of items) {
60
+ if (plugin.reason) continue;
61
+ if (disabled.includes(plugin.id)) next.add(plugin.id);
62
+ else next.delete(plugin.id);
63
+ }
64
+ localStorage.setItem(pluginKey, JSON.stringify([...next]));
65
+ reloadWithMode(true);
66
+ },
67
+ },
68
+ setTheme: theme => {
69
+ if (modalLocked()) return;
70
+ try { localStorage.setItem('clado-theme', theme); } catch {}
71
+ setDesign({ theme });
72
+ post('theme', { theme });
73
+ },
74
+ capture: screenshot && settings['clado.brand']?.showScreenshot !== false && (async () => {
75
+ try { await screenshot.download(await screenshot.capture({}, readScreenshotCanvas)); }
76
+ catch (error) { directory.showMessage('截图失败', error.message); }
77
+ }),
78
+ });
79
+ const updateControls = ui.mountViewControls(host, {
80
+ setMode: next => {
81
+ if (modalLocked() || next === mode) return;
82
+ mode = next;
83
+ saveView();
84
+ syncChrome();
85
+ frame.contentWindow.CladoPrototype?.setMode?.(next);
86
+ },
87
+ clearFocus: () => frame.contentWindow.CladoRuntime?.clearFocus(),
88
+ showDiagnostics: () => frame.contentWindow.CladoCanvasControls?.showDiagnostics(),
89
+ });
90
+ const directory = window.CladoDirectoryPlugin(host, {
91
+ showFilename: settings['clado.directory']?.showFilename !== false,
92
+ open: file => open(file),
93
+ openFromCapability,
94
+ refresh: () => scan(true),
95
+ back: () => {
96
+ if (modalLocked()) return;
97
+ const previous = history.pop();
98
+ if (previous) open(previous, '', { back: true });
99
+ },
100
+ readSource: async () => {
101
+ if (!selected) throw new Error('no document');
102
+ if (offline) return { file: selected, source: offline.sources[selected], offline: true };
103
+ const file = selected;
104
+ const response = await fetch('/library/source.mdc?file=' + encodeURIComponent(file), { cache: 'no-store' });
105
+ if (!response.ok) throw new Error('source');
106
+ return { file, source: await response.text() };
107
+ },
108
+ isLocked: modalLocked,
109
+ });
110
+ function syncChrome() {
111
+ brand.sync(design.theme);
112
+ updateControls({ ...frame.contentWindow.CladoCanvasControls?.state(), mode });
113
+ }
114
+ const selectionTab = config.selection ? crypto.randomUUID() : null;
115
+ let aiSelection = null, selectionRequest = Promise.resolve(), pageHidden = false;
116
+ let readyCanvas = null;
117
+ const canvasWaiters = new Set();
118
+ function readScreenshotCanvas() {
119
+ if (!selected || !frame.contentWindow.CladoRuntime || !$('#canvasLoading').hidden ||
120
+ (!offline && readyCanvas?.frame !== frame)) return null;
121
+ return { frame, file: selected, revision: version, mode, design };
122
+ }
123
+ if (screenshot && capabilities) {
124
+ host.capabilities('clado.host', 'canvas')?.provide(
125
+ ({ input }) => screenshot.capture(input, readScreenshotCanvas),
126
+ ).catch(error => console.warn('Clado 截图能力注册失败', error));
127
+ }
128
+ if (isEnabled('clado.agent')) window.CladoAgentPlugin(host, {
129
+ placeholder: settings['clado.agent']?.placeholder,
130
+ agentName: config.agentProfile === 'codex' ? 'Codex' : settings['clado.agent']?.name,
131
+ readCanvas() {
132
+ if (readyCanvas?.frame !== frame) return undefined;
133
+ const { file, revision } = readyCanvas;
134
+ const selection = aiSelection?.file === file && aiSelection.version === revision ? aiSelection.nodes : [];
135
+ return { file, revision, selection };
136
+ },
137
+ viewId: capabilities?.viewId,
138
+ });
139
+ if (!['light', 'dark'].includes(design.theme)) design.theme = 'light';
140
+ try { const savedTheme = localStorage.getItem('clado-theme'); if (['light', 'dark'].includes(savedTheme)) design.theme = savedTheme; } catch {}
141
+ if (config.plugins) window.CladoPluginHost({
142
+ host, capabilities, isEnabled,
143
+ readView() {
144
+ if (readyCanvas?.frame !== frame) return null;
145
+ const { file, revision } = readyCanvas;
146
+ const selection = aiSelection?.file === file && aiSelection.version === revision ? aiSelection.nodes : [];
147
+ return { file, revision, selection, runtime: frame.contentWindow.CladoRuntime };
148
+ },
149
+ });
150
+ function showSelection() {
151
+ if (selectionTab) frame.contentWindow.postMessage({ type: 'clado-workspace:selection', nodes: aiSelection?.nodes || [] }, location.origin);
152
+ }
153
+ 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 });
155
+ if (!response.ok) throw new Error('selection');
156
+ }
157
+ function setSelection(next, refresh = false) {
158
+ const update = next || (aiSelection && { ...aiSelection, nodes: [] });
159
+ if (!update) return;
160
+ aiSelection = next;
161
+ showSelection();
162
+ selectionRequest = selectionRequest.then(() => pageHidden ? null : publishSelection(refresh ? { ...update, refresh: 'render' } : update)).catch(() => {
163
+ if (aiSelection === next) {
164
+ aiSelection = null;
165
+ showSelection();
166
+ status('选区同步失败,请重新选择', true);
167
+ }
168
+ });
169
+ }
170
+ if (selectionTab) {
171
+ addEventListener('pagehide', () => {
172
+ pageHidden = true;
173
+ if (aiSelection) {
174
+ publishSelection({ ...aiSelection, nodes: [] }).catch(() => {});
175
+ aiSelection = null;
176
+ showSelection();
177
+ }
178
+ });
179
+ addEventListener('pageshow', () => { pageHidden = false; });
180
+ setInterval(() => {
181
+ if (aiSelection && !pageHidden) publishSelection({ ...aiSelection, refresh: 'heartbeat' }).catch(() => {});
182
+ }, 20000);
183
+ }
7
184
  const storageKey='clado-library-view:v2:'+location.pathname;
8
185
  const post = (type, extra = {}) => { if (parent !== window) parent.postMessage({ type: 'clado-prototype:' + type, board: 'library', ...extra }, location.origin); };
9
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 {}
187
+ try {
188
+ const restoredMode = sessionStorage.getItem(pluginKey + ':mode');
189
+ if (['mindmap','cards','doc'].includes(restoredMode)) mode = restoredMode;
190
+ if (restoredMode) sessionStorage.removeItem(pluginKey + ':mode');
191
+ } catch {}
10
192
  const requestedFile = new URLSearchParams(location.search).get('file');
11
193
  if (requestedFile || config.entry) selected = requestedFile || config.entry;
12
194
  pendingAnchor = new URLSearchParams(location.search).get('anchor') || '';
@@ -14,35 +196,57 @@
14
196
  function modalLocked() { try { return chainModal || !!frame.contentWindow.CladoPrototype?.isChainOpen?.(); } catch { return chainModal; } }
15
197
  function chainLock(value, currentMode) {
16
198
  chainModal=!!value;
199
+ if (chainModal) brand.close();
200
+ host.setHidden(chainModal || lensOpen);
201
+ directory.setLocked(chainModal);
202
+ syncChrome();
17
203
  if(['cards','mindmap','doc'].includes(currentMode)) { mode=currentMode;saveView(); }
18
- if(chainModal) { directory(false);if($('#details').open)$('#details').close(); }
19
- ['#directoryButton','#backButton','#refreshButton','#sourceButton','#skippedButton'].forEach(selector=>{const button=$(selector);button.disabled=chainModal || (selector==='#backButton' && history.length===0);});
20
204
  if(!chainModal) { const force=deferredRefresh;deferredRefresh=false;scan(force); }
21
205
  }
22
- function directory(open) { if(open && modalLocked())return; $('#directory').hidden = !open; $('#directoryButton').setAttribute('aria-expanded', String(open)); }
23
- function details(title, html) { if(modalLocked())return; $('#detailsTitle').textContent = title; $('#detailsBody').innerHTML = html; if (!$('#details').open) $('#details').showModal(); }
24
- function renderDirectory() {
25
- const signature = JSON.stringify({ documents: index.documents, skipped: index.skipped, selected, query:$('#documentSearch').value, history: history.length });
26
- if (signature === directorySignature) return;
27
- directorySignature = signature;
28
- $('#fileCount').textContent = index.documents.length;
29
- document.querySelector('.directory-heading strong').textContent = index.root || 'Markdown';
30
- CladoDocumentTree($('#documentList'),index.documents,{selected,query:$('#documentSearch').value,folders,onOpen:file=>{open(file);directory(false);}});
31
- $('#skippedButton').hidden = !index.skipped.length; $('#skippedButton').textContent = index.skipped.length + ' 份文档未收录 · 查看原因';
32
- $('#backButton').disabled = modalLocked() || history.length === 0;
33
- }
206
+ function renderDirectory() { directory.update(index, selected, history.length > 0); }
34
207
  let renderRequest = 0;
208
+ async function openFromCapability(file) {
209
+ const failure = (kind, message) => Object.assign(new Error(message), { kind });
210
+ if (modalLocked() || lensOpen) throw failure('VIEW_LOCKED', '请先关闭链路或内容放大窗口。');
211
+ let targetDocument = index.documents.find(entry => entry.file === file);
212
+ if (!targetDocument) {
213
+ const response = await fetch('/library/index.json', { cache: 'no-store' });
214
+ if (!response.ok) throw failure('NAVIGATION_FAILED', '读取文档目录失败,请重试。');
215
+ const latest = await response.json();
216
+ targetDocument = latest.documents.find(entry => entry.file === file);
217
+ if (!targetDocument) throw failure('DOCUMENT_NOT_FOUND', '找不到可展示的画布:' + file);
218
+ index = latest;
219
+ }
220
+ if (readyCanvas?.file === file && readyCanvas.frame === frame && selected === file) return { file, title: targetDocument.title, mode };
221
+ directory.close();
222
+ if (!await open(file)) throw failure('NAVIGATION_FAILED', '未能打开目标画布。');
223
+ const target = frame;
224
+ if (readyCanvas?.frame !== target) await new Promise((resolve, reject) => {
225
+ const timeout = setTimeout(() => {
226
+ canvasWaiters.delete(onReady);
227
+ reject(failure('NAVIGATION_FAILED', '等待目标画布加载超时。'));
228
+ }, 6500);
229
+ function onReady(canvas) {
230
+ canvasWaiters.delete(onReady);
231
+ clearTimeout(timeout);
232
+ if (canvas.frame === target && canvas.file === file) resolve();
233
+ else reject(failure('NAVIGATION_FAILED', '目标画布已被另一次导航替换。'));
234
+ }
235
+ canvasWaiters.add(onReady);
236
+ });
237
+ if (readyCanvas?.frame !== frame || readyCanvas?.file !== file) throw failure('NAVIGATION_FAILED', '目标画布已被另一次导航替换。');
238
+ return { file, title: targetDocument.title, mode };
239
+ }
35
240
  async function open(file, anchor = '', options = {}) {
36
241
  if(modalLocked()) { if(options.update)deferredRefresh=true;return; }
37
242
  pendingAnchor=anchor;
38
243
  const doc = index.documents.find(d => d.file === file);
39
- if (!doc) { details('这个 Markdown 暂未收录', '<p>' + esc(file) + ' 不在有效画布目录中。可以让 AI 检查文件是否存在、路径是否正确,以及能否通过解析。</p>'); return; }
244
+ if (!doc) { directory.showMessage('这个 Markdown 暂未收录', file + ' 不在有效画布目录中。可以让 AI 检查文件路径和解析状态。'); return; }
40
245
  if (selected && file !== selected && !options.back) history.push(selected);
41
- if (options.update) { try { pendingView = frame.contentWindow.CladoPrototype?.captureView?.(); } catch {} }
246
+ if (options.update && readyCanvas?.frame === frame && readyCanvas.file === file) { try { pendingView = frame.contentWindow.CladoPrototype?.captureView?.(); } catch {} }
42
247
  else pendingView = null;
43
248
  const request = ++renderRequest, previousVersion = version, requestedMode = mode;
44
- selected = file; version = doc.version; saveView(); renderDirectory();
45
- $('#currentTitle').textContent = doc.title; $('#currentPath').textContent = (index.root || '') + file;
249
+ selected = file; version = doc.version; saveView(); renderDirectory(); syncChrome();
46
250
  $('#updateError').hidden = true; $('#emptyState').hidden = true; $('#canvasLoading').hidden = false;
47
251
  // Give each render its own browsing context. A late ready/message from the
48
252
  // previous document must never complete a newer render or restore its view.
@@ -50,24 +254,29 @@
50
254
  let html;
51
255
  if(offline) html=offline.canvases[file].replace(/<!--CLADO-ASSET:(\d+)-->/g,(_,id)=>offline.shared?.[id] || '');
52
256
  else {
53
- const response = await fetch('/library/canvas?file=' + encodeURIComponent(file) + '&mode=' + mode + '&revision=' + version + (anchor ? '&anchor=' + encodeURIComponent(anchor) : ''), {cache:'no-store'});
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'});
54
258
  if(!response.ok)throw new Error('render');
55
259
  html = await response.text();
56
260
  }
57
261
  if(request !== renderRequest)return;
58
262
  if(modalLocked()) { deferredRefresh=true;version=previousVersion;$('#canvasLoading').hidden=true;return; }
59
- if(mode !== requestedMode) { version=previousVersion;open(file,anchor,{...options,update:true});return; }
263
+ if(mode !== requestedMode) { version=previousVersion;return open(file,anchor,{...options,update:true}); }
60
264
  const nextFrame = document.createElement('iframe');
61
265
  nextFrame.id = 'canvas'; nextFrame.title = frame.title;
62
266
  nextFrame.srcdoc = html;
267
+ if (aiSelection && aiSelection.file !== file) setSelection(null);
63
268
  frame.replaceWith(nextFrame); frame = nextFrame;
269
+ lensOpen = false;
270
+ host.setHidden(false);
271
+ syncChrome();
272
+ return true;
64
273
  } catch {
65
274
  if(request !== renderRequest)return;
66
275
  version = previousVersion; $('#canvasLoading').hidden = true;
67
276
  $('#updateError').textContent = '画布读取失败,保留上次画面并自动重试。'; $('#updateError').hidden = false; status('当前画布未更新', true);
68
277
  }
69
278
  }
70
- function status(text, error = false) { $('#syncStatus').textContent = text; $('#syncStatus').className = error ? 'sync-error' : 'sync-good'; $('#directoryButton').dataset.sync = error ? 'error' : 'ok'; $('#directoryButton').title = '切换 Markdown 画布 · ' + text; }
279
+ const status = (message, error) => directory.status(message, error);
71
280
  async function scan(force = false) {
72
281
  if (busy) return; busy = true;
73
282
  try {
@@ -84,7 +293,7 @@
84
293
  if (pendingOpen && index.documents.some(d=>d.file===pendingOpen)) { const file=pendingOpen;pendingOpen=null;open(file); }
85
294
  if (selected && !version && !index.documents.some(d=>d.file===selected)) { selected='';saveView(); }
86
295
  if (!selected && index.documents.length) open(index.documents[0].file);
87
- else if (!selected) { $('#canvasLoading').hidden = true; $('#emptyState').hidden = false; $('#currentTitle').textContent = '等待 MCP 创建文档'; status('目录已扫描'); post('ready'); }
296
+ else if (!selected) { $('#canvasLoading').hidden = true; $('#emptyState').hidden = false; syncChrome(); status('目录已扫描'); post('ready'); }
88
297
  else {
89
298
  const doc = index.documents.find(d => d.file === selected);
90
299
  if (!doc && !version && index.documents.length) open(index.documents[0].file);
@@ -97,31 +306,58 @@
97
306
  addEventListener('message', event => {
98
307
  if ((!offline && event.origin !== location.origin) || event.source !== frame.contentWindow) return;
99
308
  const data = event.data;
100
- if(data?.type === 'clado-library:chain-modal') { chainLock(data.value,data.mode);return; }
101
- if(modalLocked() && ['clado-library:open','clado-library:ready','clado-library:mode','clado-library:theme','clado-library:missing'].includes(data?.type))return;
102
- if (data?.type === 'clado-library:open') { directory(false); open(data.target, data.anchor); }
103
- else if (data?.type === 'clado-library:dismiss-directory') directory(false);
104
- else if (data?.type === 'clado-library:missing') details('链接超出当前目录', '<p>请选择当前工作区中的文档。链接:' + esc(data.target) + '</p>');
105
- else if (data?.type === 'clado-library:mode') { mode = data.mode; saveView(); }
106
- else if (data?.type === 'clado-library:theme') { design.theme = data.theme; setDesign(design); post('theme', { theme: data.theme }); }
309
+ if (selectionTab && data?.type === 'clado-library:selection' && data.file === selected && data.version === version) {
310
+ const nodes = [...(aiSelection?.nodes || [])];
311
+ const at = nodes.findIndex(node => JSON.stringify(node) === JSON.stringify(data.node));
312
+ if (!data.node) nodes.length = 0;
313
+ else if (at >= 0) nodes.splice(at, 1);
314
+ else if (nodes.length < 200) nodes.push(data.node);
315
+ else { status('选区已达到 200 个标题,请先取消部分选中项', true); return; }
316
+ setSelection(nodes.length ? { file: selected, version, nodes } : null);
317
+ return;
318
+ }
319
+ if (data?.type === 'clado-library:chain-modal') { chainLock(data.value, data.mode); return; }
320
+ if (data?.type === 'clado-library:lens-modal') {
321
+ lensOpen = !!data.value;
322
+ if (lensOpen) { brand.close(); directory.close(); }
323
+ host.setHidden(chainModal || lensOpen);
324
+ return;
325
+ }
326
+ if(modalLocked() && ['clado-library:open','clado-library:ready','clado-library:missing'].includes(data?.type))return;
327
+ if (data?.type === 'clado-library:open') { directory.close(); open(data.target, data.anchor); }
328
+ else if (data?.type === 'clado-library:dismiss-directory') { brand.close(); directory.close(); }
329
+ else if (data?.type === 'clado-library:missing') directory.showMessage('链接超出当前目录', '请选择当前工作区中的文档。链接:' + data.target);
330
+ else if (data?.type === 'clado-library:view-state') syncChrome();
107
331
  else if (data?.type === 'clado-library:ready') {
332
+ if (data.file === selected && data.version === version) {
333
+ readyCanvas = { frame, file: data.file, revision: data.version };
334
+ if (!offline && window.history) {
335
+ const url = new URL(location.href);
336
+ if (url.searchParams.get('file') !== data.file) {
337
+ url.searchParams.set('file', data.file);
338
+ url.searchParams.delete('anchor');
339
+ window.history.replaceState(window.history.state, '', url);
340
+ }
341
+ }
342
+ for (const notify of canvasWaiters) notify(readyCanvas);
343
+ }
344
+ if (selectionTab && data.file === selected && data.version && aiSelection && aiSelection.version !== data.version) {
345
+ const api = frame.contentWindow.CladoRuntime;
346
+ const nodes = aiSelection.nodes.filter(node => api?.hasSelectionPath(node));
347
+ setSelection(nodes.length ? { file: selected, version: data.version, nodes } : null, nodes.length > 0);
348
+ }
349
+ showSelection();
108
350
  if(offline){frame.contentWindow.postMessage({type:'clado-workspace:display',mode,theme:design.theme,anchor:pendingAnchor},'*');pendingAnchor='';}
109
- else mode = data.mode; saveView(); $('#canvasLoading').hidden = true;
351
+ else if (mode !== data.mode) frame.contentWindow.CladoPrototype?.setMode?.(mode);
352
+ saveView(); $('#canvasLoading').hidden = true; syncChrome();
110
353
  try{frame.contentWindow.CladoPrototype?.setDesign(design);}catch{}
111
354
  if (!offline && pendingView) { const view = pendingView; pendingView = null; requestAnimationFrame(() => requestAnimationFrame(() => frame.contentWindow.CladoPrototype?.restoreView?.(view))); }
112
355
  status('已同步 ' + new Date(index.documents.find(d => d.file === selected)?.modified || Date.now()).toLocaleTimeString('zh-CN', { hour12: false })); post('ready');
113
356
  }
114
357
  });
115
- function setDesign(next) { design = { ...design, ...next }; document.documentElement.dataset.theme = design.theme || 'light'; if (design.accent) document.documentElement.style.setProperty('--accent', design.accent); try { frame.contentWindow.CladoPrototype?.setDesign(design); } catch {} }
358
+ function setDesign(next) { design = { ...design, ...next }; document.documentElement.dataset.theme = design.theme || 'light'; if (design.accent) document.documentElement.style.setProperty('--accent', design.accent); try { frame.contentWindow.CladoPrototype?.setDesign(design); } catch {} syncChrome(); }
116
359
  window.CladoPrototype = { setDesign, fit: () => frame.contentWindow.CladoPrototype?.fit(), closeLens: () => frame.contentWindow.CladoPrototype?.closeLens() };
117
- $('#documentSearch').oninput=renderDirectory;
118
- $('#directoryButton').onclick = () => directory($('#directory').hidden);
119
- document.addEventListener('pointerdown', event => { if (!event.target.closest('#directory, #directoryButton')) directory(false); });
120
- document.addEventListener('keydown', event => { if (event.key === 'Escape' && !$('#directory').hidden) { directory(false); $('#directoryButton').focus(); } });
121
- $('#refreshButton').onclick = () => scan(true);
122
- $('#backButton').onclick = () => { if(modalLocked())return;const previous = history.pop(); if (previous) open(previous, '', { back: true }); };
123
- $('#closeDetails').onclick = () => $('#details').close();
124
- $('#skippedButton').onclick = () => details('扫描后未收录的 Markdown', '<p>目录只显示能通过解析的画布。解析失败可能来自普通说明文档,也可能需要修正内容;具体原因如下。</p>' + index.skipped.map(item => '<section class="skip-item"><strong>' + esc(item.file) + '</strong>' + item.diagnostics.map(d => '<p><code>' + esc(d.code) + '</code> · ' + esc(d.message) + '</p>').join('') + '</section>').join(''));
125
- $('#sourceButton').onclick = async () => { if(modalLocked())return;try { const response = offline ? {ok:true,text:async()=>offline.sources[selected]} : await fetch('/library/source.mdc?file=' + encodeURIComponent(selected), { cache: 'no-store' }); if (!response.ok) throw new Error('source'); details(selected, (offline?'<p>这是 HTML 内嵌的只读源文。通过 MCP 修改工作区后重新构建以更新交付文件。</p><pre>':'<p>源文只读预览。请通过 Clado MCP 修改内容,保存后当前画布自动同步。</p><pre>') + esc(await response.text()) + '</pre>'); } catch { details('暂时读不到源文', '<p>请检查文档是否已删除,或是否出现解析错误。</p>'); } };
126
- directory(false); scan(); if(!offline)setInterval(() => scan(), 1200);
360
+ setDesign(design);
361
+ scan();
362
+ if (!offline) setInterval(() => scan(), 1200);
127
363
  })();
@@ -0,0 +1,47 @@
1
+ export const captureTarget = { pluginId: 'clado.host', capability: 'canvas.capture', major: 1 };
2
+ export const captureMode = ['cards', 'mindmap', 'doc'];
3
+ export const captureScope = ['current', 'full'];
4
+ export const captureBase64Limit = Math.ceil(4 * 1024 * 1024 / 3) * 4;
5
+ export const captureDefinition = {
6
+ id: captureTarget.capability,
7
+ mount: 'canvas',
8
+ version: '1.0.0',
9
+ description: '截取当前画布的 PNG,默认保留展开和聚焦状态,可指定视图、展开全图或读取最近一次截图。',
10
+ exposeToAgent: true,
11
+ inputSchema: {
12
+ type: 'object',
13
+ properties: {
14
+ mode: { enum: captureMode },
15
+ source: { enum: ['current', 'latest'] },
16
+ scope: { enum: captureScope },
17
+ },
18
+ additionalProperties: false,
19
+ },
20
+ outputSchema: {
21
+ type: 'object',
22
+ properties: {
23
+ file: { type: 'string', minLength: 1, maxLength: 1500 },
24
+ revision: { type: 'string', pattern: '^[a-f0-9]{64}$' },
25
+ mode: { enum: captureMode },
26
+ width: { type: 'integer', minimum: 1, maximum: 4096 },
27
+ height: { type: 'integer', minimum: 1, maximum: 4096 },
28
+ layoutWidth: { type: 'integer', minimum: 1 },
29
+ layoutHeight: { type: 'integer', minimum: 1 },
30
+ pngBase64: { type: 'string', maxLength: captureBase64Limit, minLength: 32 },
31
+ },
32
+ required: ['file', 'revision', 'mode', 'width', 'height', 'layoutWidth', 'layoutHeight', 'pngBase64'],
33
+ additionalProperties: false,
34
+ },
35
+ };
36
+
37
+ export function isCaptureTarget(provider) {
38
+ return provider?.pluginId === captureTarget.pluginId && provider.capability === captureTarget.capability;
39
+ }
40
+
41
+ export function isCapturePng(output) {
42
+ const png = Buffer.from(output.pngBase64, 'base64');
43
+ return png.length >= 33 && png.length <= 4 * 1024 * 1024 &&
44
+ png.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex')) &&
45
+ png.toString('ascii', 12, 16) === 'IHDR' &&
46
+ png.readUInt32BE(16) === output.width && png.readUInt32BE(20) === output.height;
47
+ }
@@ -2,6 +2,7 @@ import { readFileSync, existsSync } from 'node:fs';
2
2
  import { dirname, join, relative, resolve, basename } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { renderHtml } from '../html/page.js';
5
+ import { pluginMarkup } from '../html/plugin-assets.js';
5
6
  import { workspacePath } from '../workspace/documents.js';
6
7
  const assets=join(dirname(fileURLToPath(import.meta.url)),'assets');
7
8
  const read=name=>readFileSync(join(assets,name),'utf8');
@@ -32,7 +33,7 @@ export function renderWorkspace(jobs,{root,entry,mode='mindmap',theme='light',ti
32
33
  if(existsSync(path))resources[name]='data:'+type+';base64,'+readFileSync(path).toString('base64');
33
34
  }catch{}
34
35
  }
35
- let html=renderHtml(job.doc,job.diagnostics,{file,title:job.doc.title,mode,theme,library:true});
36
+ let html=renderHtml(job.doc,job.diagnostics,{file,title:job.doc.title,mode,theme,library:true,workspaceChrome:true});
36
37
  const end=html.lastIndexOf('</body>');
37
38
  const boot='window.__CLADO_OFFLINE__=true;window.__CLADO_FILE_PATH__='+json(file)+';window.__CLADO_WORKSPACE_INDEX__='+json(index)+';window.__CLADO_RESOURCES__='+json(resources)+';';
38
39
  html=html.slice(0,end)+script(boot)+script(read('library-canvas.js'))+html.slice(end);
@@ -46,7 +47,9 @@ export function renderWorkspace(jobs,{root,entry,mode='mindmap',theme='light',ti
46
47
  }
47
48
  let html=read('library.html');
48
49
  html=html.replace('<link rel="stylesheet" href="library.css">',()=>'<style>'+read('library.css')+'</style>');
49
- html=html.replace('<script src="/tree.js"></script>',()=>script(read('tree.js')));
50
+ const plugins = pluginMarkup({ workspace: true, inline: true });
51
+ html = html.replace('<!--CLADO-PLUGIN-STYLES-->', () => plugins.styles)
52
+ .replace('<!--CLADO-PLUGIN-SCRIPTS-->', () => plugins.scripts);
50
53
  html=html.replace('<script src="library.js"></script>',()=>script('window.__CLADO_WORKSPACE__='+json({entry,mode,theme,offline:{index,canvases,sources,shared}})+';')+script(read('library.js')));
51
54
  html=html.replace('<title>Clado · Markdown 目录预览</title>','<title>'+String(title || 'Clado').replace(/[&<>]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;'}[c]))+'</title>');
52
55
  return html;
package/src/server/mcp.js CHANGED
@@ -2,11 +2,15 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
3
3
  import { z } from 'zod/v4';
4
4
  import { VERSION } from '../util/version.js';
5
+ import { targetFields } from './plugin-capabilities.js';
6
+ import { captureMode, captureScope, captureTarget, isCaptureTarget } from './canvas-capture.js';
5
7
 
6
8
  const text = () => z.string().max(2_000_000);
7
9
  const path = () => z.array(z.string().min(1)).min(1).max(6).describe('读取结果返回的标题数组,保留完整文字;不拼接点号路径或内部ID。');
8
10
  const workspace = z.string().min(1).describe('工作区绝对路径,每次调用必填,必须位于 serve 启动目录内。');
9
- const version = z.string().describe('最近一次读取返回的 workspaceVersion,写入必填;冲突后重新读取并合并。').optional();
11
+ const version = z.string().min(1).describe('可选的全工作区写入保护。传读取返回的 workspaceVersion;项目模板写入必填。').optional();
12
+ const expectedFileVersion = z.string().min(1).optional().describe('文档读取返回的 version;整文覆盖/改名/删除使用此参数,或传 expectedWorkspaceVersion。也可保护按位置编辑。');
13
+ const expectedNodeVersion = z.string().min(1).optional().describe('节点返回的 nodeVersion,用来核对目标和后代。适用于覆盖正文、改名、移动、删除、段落和节点内引用编号。');
10
14
  const templateSource = z.enum(['ancestor','user']).optional().describe('仅用于 pull,明确选择上级项目或用户库。省略时逐层向上查找,全部缺失再查用户库。');
11
15
  const position = z.object({
12
16
  mode: z.enum(['append','prepend','before','after','replace']),
@@ -27,11 +31,11 @@ const nodeFields = {
27
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,移除入链但保留链接文字;默认拒绝。'),
28
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,
29
33
  newFile: z.string().optional(), source: text().optional(), metadata: z.record(z.string(), z.unknown()).optional(), templateId: z.string().optional(),
30
- baseTemplateId: z.string().optional(), name: z.string().optional(), purpose: text().optional(), overwrite: z.boolean().optional(), scope: z.enum(['project','user']).optional(), from: templateSource
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
31
35
  };
32
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'];
33
- function createServer(invoke) {
34
- const server = new McpServer({ name: 'clado', version: VERSION }, { instructions: '先 clado_workspace inspect/init;每次必填workspace。读模板prompt后创建.mdc,通过节点和链接逐步丰富。项目写入需expectedWorkspaceVersion;用户模板写入需expectedUserTemplateVersion,push需两者。每次工具响应的diagnostics是当前工作区及模板库全量诊断,不截断;操作成功仍可能valid:false,继续处理剩余问题。diagnosticsComplete:false表示未能完成检查,不能视为零错误。dryRun的previewDiagnostics只表示未保存的候选状态。read返回段落和行号,写入results给最终位置。网页只展示,文档操作使用MCP。' });
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。' });
35
39
  const schemas = new Map();
36
40
  const enrich = (result, args) => {
37
41
  const { diagnostics: _operationDiagnostics, error, ...payload } = result;
@@ -40,17 +44,24 @@ function createServer(invoke) {
40
44
  };
41
45
  const encoded = (result, isError = false) => ({ ...(isError ? { isError: true } : {}), content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: result });
42
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);
43
- const register = (name, description, schema) => {
47
+ const capabilityResult = result => {
48
+ if (!isCaptureTarget(result.provider)) return encoded(result);
49
+ const { pngBase64, ...output } = result.output;
50
+ const reply = encoded({ ...result, output });
51
+ reply.content.push({ type: 'image', mimeType: 'image/png', data: pngBase64 });
52
+ return reply;
53
+ };
54
+ const register = (name, description, schema, handler = invoke, { encode = encoded, readOnly = false } = {}) => {
44
55
  schemas.set(name, z.object({ workspace, ...schema }).strict());
45
56
  return server.registerTool(name, {
46
- description, inputSchema: { workspace, ...schema }, annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false }
57
+ description, inputSchema: { workspace, ...schema }, annotations: { readOnlyHint: readOnly, destructiveHint: !readOnly, openWorldHint: false }
47
58
  }, async args => {
48
- try { return encoded(enrich(invoke(name, args), args)); }
59
+ try { return encode(enrich(await handler(name, args), args)); }
49
60
  catch (error) { return failure(error, args); }
50
61
  });
51
62
  };
52
- register('clado_workspace', '初始化、查看工作区;全文检索或交付校验。init创建.clado/doc;首次合并磁盘根到当前目录的上级项目模板及用户库,近处同名优先,不覆盖已有文件。inspect返回工作区版本、文档根、各级模板目录和userTemplateVersion。', {
53
- action: z.enum(['init','inspect','search','validate']), 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返回工作区版本和目录;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()
54
65
  });
55
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。修改模板不影响已有文档头部。', {
56
67
  action: z.enum(['list','read','create','update','delete','pull','push']), scope: z.enum(['project','user']).optional(),
@@ -59,18 +70,32 @@ function createServer(invoke) {
59
70
  view: z.enum(['prompt','source','full']).optional().describe('read默认prompt,编辑规则用source,只有需要全部字段时才用full。'),
60
71
  expectedWorkspaceVersion: version, expectedUserTemplateVersion: z.string().optional().describe('读取返回的userTemplateVersion;用户库写入及push必填。'), dryRun: z.boolean().optional()
61
72
  });
62
- register('clado_documents', '文档list/read/create/copy/update/rename/delete。read默认full兼容全部字段;按需view:nodes只读节点内容和位置,view:source只读原文,view:summary只取摘要,避免正文重复。create需file(.mdc)/title/templateId,source只传正文。copy用file/newFile保留原规则头和正文,重定位副本引用,不改变原文或原有入链。update传完整source,可用metadata替换头。rename用newFile维护引用;delete被引用默认拒绝,unlink才断开。写入需工作区版本,results返回最终位置。', {
63
- 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(), expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
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返回最终位置。', {
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()
64
75
  });
65
- register('clado_nodes', '节点read/query/create/insert/update/rename/move/delete。file必填,现有节点用node标题数组。read返回行号、同级index和paragraphs段落编号(从1开始)。create用title/parent/content/index,index从0开始;省略追加到同级末尾。insert追加或按position插入正文;update不传position替换整段正文,position:replace只改指定段落或唯一anchor,均保留孩子。写入results返回最终文件/节点/段落/行号;批量重命名和移动后定位会更新。query支持层级和调用关系;rename/move维护入链;delete有孩子需recursive。', {
66
- 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(), expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
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
+ 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()
67
78
  });
68
- register('clado_links', 'list返回引用href、sourceText、节点内linkIndex(从1开始)、所在段落与行号。connect需要源file/node和目标targetFile/targetNode;targetFile相对documentRoot。默认在源节点正文末尾新增一段;position可定位到段落前后,或用唯一anchor把原文替换为内联链接。sourcePoint可指定代码行、表格数据行或Mermaid节点的右侧作为起点,返回实际位置,只支持同画布;与position/before/after互斥。disconnect可按linkIndex移除单处;普通链接保留文字,精确连线仅移除独立标注。', {
69
- action: z.enum(['list','connect','disconnect']), ...Object.fromEntries(['file','node','targetFile','targetNode','label','before','after','position','linkIndex','sourcePoint','targetPoint'].map(key => [key, nodeFields[key]])), expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
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只断一处,普通链接保留文字。', {
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()
70
81
  });
71
- register('clado_batch', '以一个工作区版本按顺序执行1–100个文档/节点/链接/模板操作,全部校验成功才保存;失败整批不变。后续操作使用前面操作完成后的标题路径。dryRun只返回计划。跨文件保存带恢复日志;读写同一工作区串行化。', {
72
- expectedWorkspaceVersion: z.string(), dryRun: z.boolean().optional(), operations: z.array(z.object({ type: z.enum(operations), ...nodeFields }).strict()).min(1).max(100)
82
+ register('clado_batch', '按顺序执行1–100个操作。支持可选的expectedWorkspaceVersion,各操作也可带自己的expectedFileVersion或expectedNodeVersion。每步的版本和标题路径按前序操作后的候选状态校验。模板操作使用工作区版本。任一冲突整批不保存;dryRun只预览。', {
83
+ expectedWorkspaceVersion: version, dryRun: z.boolean().optional(), operations: z.array(z.object({ type: z.enum(operations), ...nodeFields }).strict()).min(1).max(100)
73
84
  });
85
+ if (invokeCapability) register('clado_capabilities', '查询和调用在线画布能力。list 每次读取实时注册的能力、版本、inputSchema 与 outputSchema,可用 to 过滤。call 使用 to:{pluginId,capability,major} 和 input;有多个标签页时传入 viewId。用户要求在画布里打开另一个文件时,调用 clado.directory 的 directory.open。', {
86
+ action: z.enum(['list', 'call']),
87
+ viewId: z.uuid().optional(),
88
+ to: z.strictObject(targetFields).optional(),
89
+ input: z.record(z.string(), z.unknown()).optional(),
90
+ }, (_, args) => invokeCapability(args), { encode: capabilityResult });
91
+ if (invokeCapability) register('clado_screenshot', '直接返回当前 Clado 画布的 PNG。默认保留已展开的分支和聚焦状态,scope:full 用于查看完整调用链。可用 mode 指定截图视图,source:latest 取本标签页最近一次截图。多个在线标签页时传 viewId。', {
92
+ viewId: z.uuid().optional(),
93
+ mode: z.enum(captureMode).optional(),
94
+ source: z.enum(['current', 'latest']).optional(),
95
+ scope: z.enum(captureScope).optional(),
96
+ }, (_, { workspace, viewId, mode, source, scope }) => invokeCapability({
97
+ workspace, viewId, action: 'call', to: captureTarget, input: { ...(mode && { mode }), ...(source && { source }), ...(scope && { scope }) },
98
+ }), { encode: capabilityResult, readOnly: true });
74
99
  return { server, checkCall: (name, args) => {
75
100
  const schema = schemas.get(name);
76
101
  if (!schema) return failure({ message: '没有这个工具:' + name, status: 400 }, args);
@@ -80,7 +105,7 @@ function createServer(invoke) {
80
105
  } };
81
106
  }
82
107
 
83
- export function createMcpHandler(invoke) {
108
+ export function createMcpHandler(invoke, invokeCapability) {
84
109
  return async (req, res, url) => {
85
110
  if (url.pathname !== '/mcp') return false;
86
111
  const host = req.headers.host;
@@ -91,7 +116,7 @@ export function createMcpHandler(invoke) {
91
116
  const chunks = []; let bytes = 0;
92
117
  for await (const chunk of req) { bytes += chunk.length; if (bytes > 2_000_000) { res.writeHead(413).end('请求超过2MB。'); return true; } chunks.push(chunk); }
93
118
  const data = JSON.parse(Buffer.concat(chunks).toString('utf8'));
94
- const created = createServer(invoke); server = created.server;
119
+ const created = createServer(invoke, invokeCapability); server = created.server;
95
120
  if (data.method === 'tools/call') {
96
121
  const rejected = created.checkCall(data.params?.name, data.params?.arguments);
97
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; }