cladogram 0.5.3 → 0.5.5-beta.1

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 +25 -6
  2. package/bin/clado.js +17 -6
  3. package/docs/plugin-development.md +135 -0
  4. package/docs/plugin-ui.md +43 -0
  5. package/docs/release.md +14 -0
  6. package/package.json +7 -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 +201 -0
  13. package/plugins/directory/style.css +59 -0
  14. package/plugins/view-controls/index.js +58 -0
  15. package/plugins/view-controls/style.css +66 -0
  16. package/skills/clado/SKILL.md +19 -15
  17. package/src/html/app-css.js +69 -47
  18. package/src/html/canvas-chain.js +7 -7
  19. package/src/html/canvas-focus.js +2 -4
  20. package/src/html/canvas-screenshot.js +199 -0
  21. package/src/html/canvas-ui.css +5 -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 +188 -0
  26. package/src/html/plugin-ui.js +51 -0
  27. package/src/html/runtime-api.js +41 -0
  28. package/src/html/runtime.js +164 -87
  29. package/src/server/agent.js +223 -0
  30. package/src/server/assets/clado-plugin-sdk.js +111 -0
  31. package/src/server/assets/library-canvas.js +14 -10
  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 +8 -6
  36. package/src/server/assets/library.html +3 -13
  37. package/src/server/assets/library.js +280 -47
  38. package/src/server/canvas-capture.js +47 -0
  39. package/src/server/export.js +6 -3
  40. package/src/server/mcp.js +40 -17
  41. package/src/server/plugin-capabilities.js +188 -0
  42. package/src/server/plugin-settings.js +117 -0
  43. package/src/server/plugins.js +236 -0
  44. package/src/server/workspace.js +222 -29
  45. package/src/skill/install.js +1 -1
  46. package/src/skill/targets.js +3 -3
  47. package/src/util/update.js +3 -2
  48. package/src/vendor/html-to-image.min.js +24 -0
  49. package/src/workspace/service.js +21 -13
  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/src/server/assets/tree.js +0 -26
@@ -1,16 +1,164 @@
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 = ['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
+ 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';
10
+ const settings = config.pluginSettings || {};
11
+ if (['cards', 'mindmap', 'doc'].includes(settings['clado.view-controls']?.defaultMode)) mode = settings['clado.view-controls'].defaultMode;
12
+ const pluginKey = 'clado-disabled-plugins:' + (config.pluginPreferenceKey || location.pathname);
13
+ let disabledPlugins = new Set();
14
+ try {
15
+ const saved = JSON.parse(localStorage.getItem(pluginKey) || '[]');
16
+ if (Array.isArray(saved)) disabledPlugins = new Set(saved);
17
+ } catch {}
18
+ const items = [
19
+ { id: 'clado.brand', name: 'Clado 设置', reason: '管理入口,始终启用' },
20
+ { id: 'clado.view-controls', name: '视图切换', detail: '卡片、脑图和文档视图' },
21
+ { id: 'clado.directory', name: '文档目录', detail: '查找和打开工作区文档' },
22
+ { id: 'clado.agent', name: '灵感', detail: '与 Agent 对话并协作修改画布', ...(!config.agent && { reason: offline ? '需要在线服务' : '当前服务已关闭聊天' }) },
23
+ ...(config.pluginCatalog || []),
24
+ ];
25
+ const isEnabled = id => id === 'clado.brand' || !items.some(item => item.id === id && item.reason) && !disabledPlugins.has(id);
26
+ const ui = window.CladoPluginUI;
27
+ const capabilities = window.CladoCapabilityBridge?.(workspaceId);
28
+ const host = ui.createHost(capabilities, isEnabled);
29
+ const screenshot = window.CladoScreenshot?.();
30
+ let lensOpen = false;
31
+ function reloadWithMode(preserve) {
32
+ try {
33
+ if (preserve) sessionStorage.setItem(pluginKey + ':mode', mode);
34
+ else sessionStorage.removeItem(pluginKey + ':mode');
35
+ } catch {}
36
+ location.reload();
37
+ }
38
+ async function editPluginSettings(id, value, expected) {
39
+ const write = arguments.length > 1;
40
+ const response = await fetch(withWorkspace('/library/plugin-settings?id=' + encodeURIComponent(id)), write ? {
41
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value, expected }),
42
+ } : { cache: 'no-store' });
43
+ const result = await response.json();
44
+ if (!response.ok) throw new Error(result.error);
45
+ if (write) reloadWithMode(id !== 'clado.view-controls');
46
+ return result;
47
+ }
48
+ const brand = ui.mountBrand(host, {
49
+ plugins: {
50
+ items, isEnabled,
51
+ edit: config.hasPluginSettings ? editPluginSettings : null,
52
+ install: config.canInstallPlugins && (async files => {
53
+ const response = await fetch(withWorkspace('/library/install-plugin'), {
54
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ files }),
55
+ });
56
+ const result = await response.json();
57
+ if (!response.ok) throw new Error(result.error);
58
+ return result;
59
+ }),
60
+ refresh: () => reloadWithMode(true),
61
+ save(disabled) {
62
+ const next = new Set(disabledPlugins);
63
+ for (const plugin of items) {
64
+ if (plugin.reason) continue;
65
+ if (disabled.includes(plugin.id)) next.add(plugin.id);
66
+ else next.delete(plugin.id);
67
+ }
68
+ localStorage.setItem(pluginKey, JSON.stringify([...next]));
69
+ reloadWithMode(true);
70
+ },
71
+ },
72
+ setTheme: theme => {
73
+ if (modalLocked()) return;
74
+ try { localStorage.setItem('clado-theme', theme); } catch {}
75
+ setDesign({ theme });
76
+ post('theme', { theme });
77
+ },
78
+ capture: screenshot && settings['clado.brand']?.showScreenshot !== false && (async () => {
79
+ try { await screenshot.download(await screenshot.capture({}, readScreenshotCanvas)); }
80
+ catch (error) { directory.showMessage('截图失败', error.message); }
81
+ }),
82
+ });
83
+ const updateControls = ui.mountViewControls(host, {
84
+ setMode: next => {
85
+ if (modalLocked() || next === mode) return;
86
+ mode = next;
87
+ saveView();
88
+ syncChrome();
89
+ frame.contentWindow.CladoPrototype?.setMode?.(next);
90
+ },
91
+ clearFocus: () => frame.contentWindow.CladoRuntime?.clearFocus(),
92
+ showDiagnostics: () => frame.contentWindow.CladoCanvasControls?.showDiagnostics(),
93
+ });
94
+ const directory = window.CladoDirectoryPlugin(host, {
95
+ showFilename: settings['clado.directory']?.showFilename !== false,
96
+ open: file => open(file),
97
+ openFromCapability,
98
+ workspaceUrl,
99
+ switchWorkspace: id => { location.href = workspaceUrl(id); },
100
+ refresh: () => scan(true),
101
+ back: () => {
102
+ if (modalLocked()) return;
103
+ const previous = history.pop();
104
+ if (previous) open(previous, '', { back: true });
105
+ },
106
+ readSource: async () => {
107
+ if (!selected) throw new Error('no document');
108
+ if (offline) return { file: selected, source: offline.sources[selected], offline: true };
109
+ const file = selected;
110
+ const response = await fetch(withWorkspace('/library/source.mdc?file=' + encodeURIComponent(file)), { cache: 'no-store' });
111
+ if (!response.ok) throw new Error('source');
112
+ return { file, source: await response.text() };
113
+ },
114
+ isLocked: modalLocked,
115
+ });
116
+ function syncChrome() {
117
+ brand.sync(design.theme);
118
+ updateControls({ ...frame.contentWindow.CladoCanvasControls?.state(), mode });
119
+ }
7
120
  const selectionTab = config.selection ? crypto.randomUUID() : null;
8
121
  let aiSelection = null, selectionRequest = Promise.resolve(), pageHidden = false;
122
+ let readyCanvas = null;
123
+ const canvasWaiters = new Set();
124
+ function readScreenshotCanvas() {
125
+ if (!selected || !frame.contentWindow.CladoRuntime || !$('#canvasLoading').hidden ||
126
+ (!offline && readyCanvas?.frame !== frame)) return null;
127
+ return { frame, file: selected, revision: version, mode, design };
128
+ }
129
+ if (screenshot && capabilities) {
130
+ host.capabilities('clado.host', 'canvas')?.provide(
131
+ ({ input }) => screenshot.capture(input, readScreenshotCanvas),
132
+ ).catch(error => console.warn('Clado 截图能力注册失败', error));
133
+ }
134
+ if (isEnabled('clado.agent')) window.CladoAgentPlugin(host, {
135
+ placeholder: settings['clado.agent']?.placeholder,
136
+ agentName: config.agentProfile === 'codex' ? 'Codex' : settings['clado.agent']?.name,
137
+ endpoint: withWorkspace('/library/agent'),
138
+ readCanvas() {
139
+ if (readyCanvas?.frame !== frame) return undefined;
140
+ const { file, revision } = readyCanvas;
141
+ const selection = aiSelection?.file === file && aiSelection.version === revision ? aiSelection.nodes : [];
142
+ return { file, revision, selection };
143
+ },
144
+ viewId: capabilities?.viewId,
145
+ });
146
+ if (!['light', 'dark'].includes(design.theme)) design.theme = 'light';
147
+ try { const savedTheme = localStorage.getItem('clado-theme'); if (['light', 'dark'].includes(savedTheme)) design.theme = savedTheme; } catch {}
148
+ if (config.plugins) window.CladoPluginHost({
149
+ host, capabilities, isEnabled, workspaceId,
150
+ readView() {
151
+ if (readyCanvas?.frame !== frame) return null;
152
+ const { file, revision } = readyCanvas;
153
+ const selection = aiSelection?.file === file && aiSelection.version === revision ? aiSelection.nodes : [];
154
+ return { file, revision, selection, runtime: frame.contentWindow.CladoRuntime };
155
+ },
156
+ });
9
157
  function showSelection() {
10
158
  if (selectionTab) frame.contentWindow.postMessage({ type: 'clado-workspace:selection', nodes: aiSelection?.nodes || [] }, location.origin);
11
159
  }
12
160
  async function publishSelection(selection) {
13
- const response = await fetch('/library/selection', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ tab: selectionTab, ...selection }), keepalive: true });
161
+ const response = await fetch(withWorkspace('/library/selection'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ tab: selectionTab, ...selection }), keepalive: true });
14
162
  if (!response.ok) throw new Error('selection');
15
163
  }
16
164
  function setSelection(next, refresh = false) {
@@ -40,9 +188,14 @@
40
188
  if (aiSelection && !pageHidden) publishSelection({ ...aiSelection, refresh: 'heartbeat' }).catch(() => {});
41
189
  }, 20000);
42
190
  }
43
- const storageKey='clado-library-view:v2:'+location.pathname;
191
+ const storageKey='clado-library-view:v2:'+location.pathname+(workspaceId?':'+workspaceId:'');
44
192
  const post = (type, extra = {}) => { if (parent !== window) parent.postMessage({ type: 'clado-prototype:' + type, board: 'library', ...extra }, location.origin); };
45
- try { const saved = JSON.parse(sessionStorage.getItem(storageKey) || '{}'); selected = saved.file || ''; if (!config.mode && ['mindmap','cards','doc'].includes(saved.mode)) mode = saved.mode; } catch {}
193
+ try { const saved = JSON.parse(sessionStorage.getItem(storageKey) || '{}'); selected = saved.file || ''; if (!config.mode && ['cards','mindmap','doc'].includes(saved.mode)) mode = saved.mode; } catch {}
194
+ try {
195
+ const restoredMode = sessionStorage.getItem(pluginKey + ':mode');
196
+ if (['cards','mindmap','doc'].includes(restoredMode)) mode = restoredMode;
197
+ if (restoredMode) sessionStorage.removeItem(pluginKey + ':mode');
198
+ } catch {}
46
199
  const requestedFile = new URLSearchParams(location.search).get('file');
47
200
  if (requestedFile || config.entry) selected = requestedFile || config.entry;
48
201
  pendingAnchor = new URLSearchParams(location.search).get('anchor') || '';
@@ -50,35 +203,87 @@
50
203
  function modalLocked() { try { return chainModal || !!frame.contentWindow.CladoPrototype?.isChainOpen?.(); } catch { return chainModal; } }
51
204
  function chainLock(value, currentMode) {
52
205
  chainModal=!!value;
206
+ if (chainModal) brand.close();
207
+ host.setHidden(chainModal || lensOpen);
208
+ directory.setLocked(chainModal);
209
+ syncChrome();
53
210
  if(['cards','mindmap','doc'].includes(currentMode)) { mode=currentMode;saveView(); }
54
- if(chainModal) { directory(false);if($('#details').open)$('#details').close(); }
55
- ['#directoryButton','#backButton','#refreshButton','#sourceButton','#skippedButton'].forEach(selector=>{const button=$(selector);button.disabled=chainModal || (selector==='#backButton' && history.length===0);});
56
211
  if(!chainModal) { const force=deferredRefresh;deferredRefresh=false;scan(force); }
57
212
  }
58
- function directory(open) { if(open && modalLocked())return; $('#directory').hidden = !open; $('#directoryButton').setAttribute('aria-expanded', String(open)); }
59
- function details(title, html) { if(modalLocked())return; $('#detailsTitle').textContent = title; $('#detailsBody').innerHTML = html; if (!$('#details').open) $('#details').showModal(); }
60
- function renderDirectory() {
61
- const signature = JSON.stringify({ documents: index.documents, skipped: index.skipped, selected, query:$('#documentSearch').value, history: history.length });
62
- if (signature === directorySignature) return;
63
- directorySignature = signature;
64
- $('#fileCount').textContent = index.documents.length;
65
- document.querySelector('.directory-heading strong').textContent = index.root || 'Markdown';
66
- CladoDocumentTree($('#documentList'),index.documents,{selected,query:$('#documentSearch').value,folders,onOpen:file=>{open(file);directory(false);}});
67
- $('#skippedButton').hidden = !index.skipped.length; $('#skippedButton').textContent = index.skipped.length + ' 份文档未收录 · 查看原因';
68
- $('#backButton').disabled = modalLocked() || history.length === 0;
213
+ function renderDirectory() { directory.update(index, selected, history.length > 0); }
214
+ let emptyWorkspaceSignature = '';
215
+ function renderEmptyWorkspaces(list) {
216
+ const others = list.filter(item => item.id !== workspaceId);
217
+ const next = JSON.stringify(others.map(item => [item.id, item.name, item.documents]));
218
+ if (next === emptyWorkspaceSignature) return;
219
+ emptyWorkspaceSignature = next;
220
+ let container = $('#emptyState .empty-workspaces');
221
+ if (!others.length) { container?.remove(); return; }
222
+ if (!container) {
223
+ container = document.createElement('div');
224
+ container.className = 'empty-workspaces';
225
+ $('#emptyState').append(container);
226
+ }
227
+ container.replaceChildren();
228
+ const title = document.createElement('div');
229
+ title.className = 'empty-workspaces-title';
230
+ title.textContent = '已发现的子工作区(点击打开)';
231
+ container.append(title);
232
+ for (const item of others) {
233
+ const link = document.createElement('a');
234
+ link.className = 'empty-workspace-card';
235
+ link.href = workspaceUrl(item.id);
236
+ const name = document.createElement('span');
237
+ name.textContent = item.id || (item.name + '(根目录)');
238
+ const count = document.createElement('small');
239
+ count.textContent = (item.documents ?? 0) + ' 份画布';
240
+ link.append(name, count);
241
+ container.append(link);
242
+ }
69
243
  }
70
244
  let renderRequest = 0;
245
+ async function openFromCapability(file) {
246
+ const failure = (kind, message) => Object.assign(new Error(message), { kind });
247
+ if (modalLocked() || lensOpen) throw failure('VIEW_LOCKED', '请先关闭链路或内容放大窗口。');
248
+ let targetDocument = index.documents.find(entry => entry.file === file);
249
+ if (!targetDocument) {
250
+ const response = await fetch(withWorkspace('/library/index.json'), { cache: 'no-store' });
251
+ if (!response.ok) throw failure('NAVIGATION_FAILED', '读取文档目录失败,请重试。');
252
+ const latest = await response.json();
253
+ targetDocument = latest.documents.find(entry => entry.file === file);
254
+ if (!targetDocument) throw failure('DOCUMENT_NOT_FOUND', '找不到可展示的画布:' + file);
255
+ index = latest;
256
+ }
257
+ if (readyCanvas?.file === file && readyCanvas.frame === frame && selected === file) return { file, title: targetDocument.title, mode };
258
+ directory.close();
259
+ if (!await open(file)) throw failure('NAVIGATION_FAILED', '未能打开目标画布。');
260
+ const target = frame;
261
+ if (readyCanvas?.frame !== target) await new Promise((resolve, reject) => {
262
+ const timeout = setTimeout(() => {
263
+ canvasWaiters.delete(onReady);
264
+ reject(failure('NAVIGATION_FAILED', '等待目标画布加载超时。'));
265
+ }, 6500);
266
+ function onReady(canvas) {
267
+ canvasWaiters.delete(onReady);
268
+ clearTimeout(timeout);
269
+ if (canvas.frame === target && canvas.file === file) resolve();
270
+ else reject(failure('NAVIGATION_FAILED', '目标画布已被另一次导航替换。'));
271
+ }
272
+ canvasWaiters.add(onReady);
273
+ });
274
+ if (readyCanvas?.frame !== frame || readyCanvas?.file !== file) throw failure('NAVIGATION_FAILED', '目标画布已被另一次导航替换。');
275
+ return { file, title: targetDocument.title, mode };
276
+ }
71
277
  async function open(file, anchor = '', options = {}) {
72
278
  if(modalLocked()) { if(options.update)deferredRefresh=true;return; }
73
279
  pendingAnchor=anchor;
74
280
  const doc = index.documents.find(d => d.file === file);
75
- if (!doc) { details('这个 Markdown 暂未收录', '<p>' + esc(file) + ' 不在有效画布目录中。可以让 AI 检查文件是否存在、路径是否正确,以及能否通过解析。</p>'); return; }
281
+ if (!doc) { directory.showMessage('这个 Markdown 暂未收录', file + ' 不在有效画布目录中。可以让 AI 检查文件路径和解析状态。'); return; }
76
282
  if (selected && file !== selected && !options.back) history.push(selected);
77
- if (options.update) { try { pendingView = frame.contentWindow.CladoPrototype?.captureView?.(); } catch {} }
283
+ if (options.update && readyCanvas?.frame === frame && readyCanvas.file === file) { try { pendingView = frame.contentWindow.CladoPrototype?.captureView?.(); } catch {} }
78
284
  else pendingView = null;
79
285
  const request = ++renderRequest, previousVersion = version, requestedMode = mode;
80
- selected = file; version = doc.version; saveView(); renderDirectory();
81
- $('#currentTitle').textContent = doc.title; $('#currentPath').textContent = (index.root || '') + file;
286
+ selected = file; version = doc.version; saveView(); renderDirectory(); syncChrome();
82
287
  $('#updateError').hidden = true; $('#emptyState').hidden = true; $('#canvasLoading').hidden = false;
83
288
  // Give each render its own browsing context. A late ready/message from the
84
289
  // previous document must never complete a newer render or restore its view.
@@ -86,30 +291,47 @@
86
291
  let html;
87
292
  if(offline) html=offline.canvases[file].replace(/<!--CLADO-ASSET:(\d+)-->/g,(_,id)=>offline.shared?.[id] || '');
88
293
  else {
89
- const response = await fetch('/library/canvas?file=' + encodeURIComponent(file) + '&mode=' + mode + '&revision=' + version + (anchor ? '&anchor=' + encodeURIComponent(anchor) : ''), {cache:'no-store'});
294
+ 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'});
90
295
  if(!response.ok)throw new Error('render');
91
296
  html = await response.text();
92
297
  }
93
298
  if(request !== renderRequest)return;
94
299
  if(modalLocked()) { deferredRefresh=true;version=previousVersion;$('#canvasLoading').hidden=true;return; }
95
- if(mode !== requestedMode) { version=previousVersion;open(file,anchor,{...options,update:true});return; }
300
+ if(mode !== requestedMode) { version=previousVersion;return open(file,anchor,{...options,update:true}); }
96
301
  const nextFrame = document.createElement('iframe');
97
302
  nextFrame.id = 'canvas'; nextFrame.title = frame.title;
98
303
  nextFrame.srcdoc = html;
99
304
  if (aiSelection && aiSelection.file !== file) setSelection(null);
100
305
  frame.replaceWith(nextFrame); frame = nextFrame;
306
+ lensOpen = false;
307
+ host.setHidden(false);
308
+ syncChrome();
309
+ return true;
101
310
  } catch {
102
311
  if(request !== renderRequest)return;
103
312
  version = previousVersion; $('#canvasLoading').hidden = true;
104
313
  $('#updateError').textContent = '画布读取失败,保留上次画面并自动重试。'; $('#updateError').hidden = false; status('当前画布未更新', true);
105
314
  }
106
315
  }
107
- 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; }
316
+ const status = (message, error) => directory.status(message, error);
108
317
  async function scan(force = false) {
109
318
  if (busy) return; busy = true;
110
319
  try {
111
320
  if(offline) index=offline.index;
112
- else { const response=await fetch('/library/index.json',{cache:'no-store'});if(!response.ok)throw new Error('scan');index=await response.json(); }
321
+ else {
322
+ const [indexRes, workspacesRes] = await Promise.all([
323
+ fetch(withWorkspace('/library/index.json'), { cache: 'no-store' }),
324
+ config.multiWorkspace ? fetch('/library/workspaces.json', { cache: 'no-store' }).catch(() => null) : Promise.resolve(null),
325
+ ]);
326
+ if(!indexRes.ok)throw new Error('scan');
327
+ index=await indexRes.json();
328
+ if (workspacesRes?.ok) {
329
+ const data = await workspacesRes.json();
330
+ const list = Array.isArray(data.workspaces) ? data.workspaces : [];
331
+ directory.updateWorkspaces?.(workspaceId, list);
332
+ renderEmptyWorkspaces(list);
333
+ }
334
+ }
113
335
  renderDirectory();
114
336
  try{frame.contentWindow.postMessage({type:'clado-workspace:index',index},'*');}catch{}
115
337
  if(modalLocked()) {
@@ -121,7 +343,7 @@
121
343
  if (pendingOpen && index.documents.some(d=>d.file===pendingOpen)) { const file=pendingOpen;pendingOpen=null;open(file); }
122
344
  if (selected && !version && !index.documents.some(d=>d.file===selected)) { selected='';saveView(); }
123
345
  if (!selected && index.documents.length) open(index.documents[0].file);
124
- else if (!selected) { $('#canvasLoading').hidden = true; $('#emptyState').hidden = false; $('#currentTitle').textContent = '等待 MCP 创建文档'; status('目录已扫描'); post('ready'); }
346
+ else if (!selected) { $('#canvasLoading').hidden = true; $('#emptyState').hidden = false; syncChrome(); status('目录已扫描'); post('ready'); }
125
347
  else {
126
348
  const doc = index.documents.find(d => d.file === selected);
127
349
  if (!doc && !version && index.documents.length) open(index.documents[0].file);
@@ -144,14 +366,31 @@
144
366
  setSelection(nodes.length ? { file: selected, version, nodes } : null);
145
367
  return;
146
368
  }
147
- if(data?.type === 'clado-library:chain-modal') { chainLock(data.value,data.mode);return; }
148
- if(modalLocked() && ['clado-library:open','clado-library:ready','clado-library:mode','clado-library:theme','clado-library:missing'].includes(data?.type))return;
149
- if (data?.type === 'clado-library:open') { directory(false); open(data.target, data.anchor); }
150
- else if (data?.type === 'clado-library:dismiss-directory') directory(false);
151
- else if (data?.type === 'clado-library:missing') details('链接超出当前目录', '<p>请选择当前工作区中的文档。链接:' + esc(data.target) + '</p>');
152
- else if (data?.type === 'clado-library:mode') { mode = data.mode; saveView(); }
153
- else if (data?.type === 'clado-library:theme') { design.theme = data.theme; setDesign(design); post('theme', { theme: data.theme }); }
369
+ if (data?.type === 'clado-library:chain-modal') { chainLock(data.value, data.mode); return; }
370
+ if (data?.type === 'clado-library:lens-modal') {
371
+ lensOpen = !!data.value;
372
+ if (lensOpen) { brand.close(); directory.close(); }
373
+ host.setHidden(chainModal || lensOpen);
374
+ return;
375
+ }
376
+ if(modalLocked() && ['clado-library:open','clado-library:ready','clado-library:missing'].includes(data?.type))return;
377
+ if (data?.type === 'clado-library:open') { directory.close(); open(data.target, data.anchor); }
378
+ else if (data?.type === 'clado-library:dismiss-directory') { brand.close(); directory.close(); }
379
+ else if (data?.type === 'clado-library:missing') directory.showMessage('链接超出当前目录', '请选择当前工作区中的文档。链接:' + data.target);
380
+ else if (data?.type === 'clado-library:view-state') syncChrome();
154
381
  else if (data?.type === 'clado-library:ready') {
382
+ if (data.file === selected && data.version === version) {
383
+ readyCanvas = { frame, file: data.file, revision: data.version };
384
+ if (!offline && window.history) {
385
+ const url = new URL(location.href);
386
+ if (url.searchParams.get('file') !== data.file) {
387
+ url.searchParams.set('file', data.file);
388
+ url.searchParams.delete('anchor');
389
+ window.history.replaceState(window.history.state, '', url);
390
+ }
391
+ }
392
+ for (const notify of canvasWaiters) notify(readyCanvas);
393
+ }
155
394
  if (selectionTab && data.file === selected && data.version && aiSelection && aiSelection.version !== data.version) {
156
395
  const api = frame.contentWindow.CladoRuntime;
157
396
  const nodes = aiSelection.nodes.filter(node => api?.hasSelectionPath(node));
@@ -159,22 +398,16 @@
159
398
  }
160
399
  showSelection();
161
400
  if(offline){frame.contentWindow.postMessage({type:'clado-workspace:display',mode,theme:design.theme,anchor:pendingAnchor},'*');pendingAnchor='';}
162
- else mode = data.mode; saveView(); $('#canvasLoading').hidden = true;
401
+ else if (mode !== data.mode) frame.contentWindow.CladoPrototype?.setMode?.(mode);
402
+ saveView(); $('#canvasLoading').hidden = true; syncChrome();
163
403
  try{frame.contentWindow.CladoPrototype?.setDesign(design);}catch{}
164
404
  if (!offline && pendingView) { const view = pendingView; pendingView = null; requestAnimationFrame(() => requestAnimationFrame(() => frame.contentWindow.CladoPrototype?.restoreView?.(view))); }
165
405
  status('已同步 ' + new Date(index.documents.find(d => d.file === selected)?.modified || Date.now()).toLocaleTimeString('zh-CN', { hour12: false })); post('ready');
166
406
  }
167
407
  });
168
- 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 {} }
408
+ 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(); }
169
409
  window.CladoPrototype = { setDesign, fit: () => frame.contentWindow.CladoPrototype?.fit(), closeLens: () => frame.contentWindow.CladoPrototype?.closeLens() };
170
- $('#documentSearch').oninput=renderDirectory;
171
- $('#directoryButton').onclick = () => directory($('#directory').hidden);
172
- document.addEventListener('pointerdown', event => { if (!event.target.closest('#directory, #directoryButton')) directory(false); });
173
- document.addEventListener('keydown', event => { if (event.key === 'Escape' && !$('#directory').hidden) { directory(false); $('#directoryButton').focus(); } });
174
- $('#refreshButton').onclick = () => scan(true);
175
- $('#backButton').onclick = () => { if(modalLocked())return;const previous = history.pop(); if (previous) open(previous, '', { back: true }); };
176
- $('#closeDetails').onclick = () => $('#details').close();
177
- $('#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(''));
178
- $('#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>'); } };
179
- directory(false); scan(); if(!offline)setInterval(() => scan(), 1200);
410
+ setDesign(design);
411
+ scan();
412
+ if (!offline) setInterval(() => scan(), 1200);
180
413
  })();
@@ -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');
@@ -9,7 +10,7 @@ const json=value=>JSON.stringify(value).replace(/</g,'\\u003c');
9
10
  const script=value=>'<script>'+value.replace(/<\/script/gi,'<\\/script')+'</script>';
10
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'};
11
12
  /** One portable workspace, including all canvases, navigation, sources and local media. */
12
- export function renderWorkspace(jobs,{root,entry,mode='mindmap',theme='light',title}={}) {
13
+ export function renderWorkspace(jobs,{root,entry,mode='cards',theme='light',title}={}) {
13
14
  root=resolve(root);
14
15
  const documents=jobs.map(j=>({file:relative(root,j.file).split('\\').join('/'),title:j.doc.title,version:'offline',modified:0}));
15
16
  const index={root:basename(root)+'/',documents,skipped:[]},canvases={},sources={},shared=[],assetIds=new Map();
@@ -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;