cladogram 0.3.1 → 0.5.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 (70) hide show
  1. package/README.md +57 -365
  2. package/bin/clado.js +126 -72
  3. package/package.json +11 -8
  4. package/skills/clado/SKILL.md +123 -747
  5. package/src/core/links.js +37 -0
  6. package/src/core/media-links.js +99 -0
  7. package/src/core/parse.js +81 -82
  8. package/src/html/app-css.js +51 -75
  9. package/src/html/canvas-card.js +65 -0
  10. package/src/html/canvas-chain.js +231 -0
  11. package/src/html/canvas-focus.js +175 -0
  12. package/src/html/canvas-ui.css +38 -0
  13. package/src/html/canvas-ui.js +40 -0
  14. package/src/html/canvas-wires.js +73 -0
  15. package/src/html/media-anchors.js +212 -0
  16. package/src/html/mindmap-connectors.js +78 -0
  17. package/src/html/mindmap-media.js +39 -0
  18. package/src/html/page.js +23 -4
  19. package/src/html/runtime-api.js +51 -0
  20. package/src/html/runtime-fixes.js +32 -0
  21. package/src/html/runtime.js +322 -272
  22. package/src/server/assets/library-canvas.js +96 -0
  23. package/src/server/assets/library.css +9 -0
  24. package/src/server/assets/library.html +20 -0
  25. package/src/server/assets/library.js +127 -0
  26. package/src/server/assets/tree.js +26 -0
  27. package/src/server/export.js +53 -0
  28. package/src/server/mcp.js +108 -0
  29. package/src/server/workspace.js +84 -0
  30. package/src/skill/install.js +16 -18
  31. package/src/skill/targets.js +28 -12
  32. package/src/skill/templates.js +60 -0
  33. package/src/util/version.js +3 -0
  34. package/src/workspace/content.js +72 -0
  35. package/src/workspace/documents.js +65 -0
  36. package/src/workspace/references.js +101 -0
  37. package/src/workspace/service.js +457 -0
  38. package/src/workspace/storage.js +169 -0
  39. package/src/workspace/tree.js +66 -0
  40. package/templates/business-flow.mdc +29 -0
  41. package/templates/call-chain.mdc +62 -0
  42. package/templates/data-design.mdc +35 -0
  43. package/templates/mind-expansion.mdc +52 -0
  44. package/templates/requirement-overview.mdc +29 -0
  45. package/templates/system-state.mdc +29 -0
  46. package/examples/showcase/README.md +0 -115
  47. package/examples/showcase/baseline.md +0 -365
  48. package/examples/showcase/build.sh +0 -48
  49. package/examples/showcase/calls.md +0 -136
  50. package/examples/showcase/fulfill-cn.md +0 -351
  51. package/examples/showcase/fulfill.md +0 -271
  52. package/examples/showcase/index.md +0 -187
  53. package/examples/showcase/order.md +0 -195
  54. package/examples/showcase/promo.md +0 -580
  55. package/examples/showcase/refund.md +0 -966
  56. package/examples/showcase/seckill.md +0 -787
  57. package/skills/clado/examples/01-/351/234/200/346/261/202/346/240/221.md +0 -32
  58. package/skills/clado/examples/02-/346/225/260/346/215/256/350/241/250.md +0 -44
  59. package/skills/clado/examples/03-/346/216/245/345/217/243/346/270/205/345/215/225.md +0 -51
  60. package/skills/clado/examples/04-/346/226/271/346/263/225/351/223/276.md +0 -70
  61. package/skills/clado/examples/05-/346/216/245/345/217/243/350/260/203/347/224/250.md +0 -58
  62. package/skills/clado/examples/06-/350/260/203/347/224/250/351/223/276.md +0 -49
  63. package/skills/clado/examples/07-/346/213/206/346/226/207/346/241/243/index.md +0 -38
  64. package/skills/clado/examples/07-/346/213/206/346/226/207/346/241/243/refund.md +0 -33
  65. package/skills/clado/examples/07-/346/213/206/346/226/207/346/241/243/seckill.md +0 -56
  66. package/skills/clado/examples/08-/347/234/237/345/256/236/350/247/204/346/250/241//346/216/245/345/217/243/345/245/221/347/272/246.md +0 -122
  67. package/skills/clado/examples/08-/347/234/237/345/256/236/350/247/204/346/250/241//346/225/205/351/232/234/345/244/215/347/233/230.md +0 -99
  68. package/skills/clado/examples/08-/347/234/237/345/256/236/350/247/204/346/250/241//350/260/203/347/224/250/351/223/276.md +0 -219
  69. package/skills/clado/examples/build.sh +0 -44
  70. package/skills/clado/references/diagnostics.md +0 -129
@@ -0,0 +1,96 @@
1
+ (() => {
2
+ const runtime = window.CladoRuntime;
3
+ const params = new URLSearchParams(location.search), file = window.__CLADO_FILE_PATH__ || params.get('file');
4
+ let designKey = '', cardsInitialized = false, deferredDisplay = null, deferredDesign = null;
5
+ const chainOpen = () => !!runtime.isChainOpen?.();
6
+ const post = (type, detail = {}) => parent.postMessage({ type: 'clado-library:' + type, file, ...detail }, '*');
7
+ const labels = { mindmap: '脑图', cards: '卡片', doc: '文档' };
8
+ const modes = document.querySelector('#modes');
9
+ ['mindmap','cards','doc'].forEach(mode => { const button = modes.querySelector('[data-mode="' + mode + '"]'); button.textContent = labels[mode]; modes.append(button); });
10
+ document.addEventListener('pointerdown', () => post('dismiss-directory'), true);
11
+ document.addEventListener('keydown', event => { if (event.key === 'Escape') post('dismiss-directory'); });
12
+ function resourceUrl(href) {
13
+ const target = new URL(href,'https://clado.local/documents/'+file);
14
+ if (!target.pathname.startsWith('/documents/')) return null;
15
+ const path=decodeURIComponent(target.pathname.slice('/documents/'.length));
16
+ return window.__CLADO_RESOURCES__?.[path] || (window.__CLADO_OFFLINE__ ? null : '/library/resource?file='+encodeURIComponent(path));
17
+ }
18
+ function rewriteDocumentLinks() {
19
+ document.querySelectorAll('img[src]:not([data-resource])').forEach(img=>{
20
+ const src=img.getAttribute('src');if (!src || /^(?:[a-z][a-z0-9+.-]*:|\/\/|\/)/i.test(src))return;
21
+ try { const url=resourceUrl(src);if(url){img.dataset.resource='1';img.src=url;} } catch {}
22
+ });
23
+ document.querySelectorAll('a[href]:not(.edge):not([data-resource])').forEach(a=>{
24
+ const href=a.getAttribute('href');if (!href || /^(?:[a-z][a-z0-9+.-]*:|\/\/|\/|#)/i.test(href) || /\.mdc?(?:#|$)/i.test(href))return;
25
+ if (!/\.(?:png|jpe?g|gif|webp|svg|pdf|txt|csv|json)(?:#|$)/i.test(href))return;
26
+ try { const url=resourceUrl(href);if(url){a.dataset.resource='1';a.href=url;} } catch {}
27
+ });
28
+ document.querySelectorAll('a[href]:not(.edge):not([data-canvas-file])').forEach(a => {
29
+ const href = a.getAttribute('href');
30
+ if (!href || /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(href)) return;
31
+ const parts = href.split('#'); if (!/\.mdc?$/i.test(parts[0])) return;
32
+ const target = new URL(parts[0], 'https://clado.local/documents/' + file);
33
+ if (!target.pathname.startsWith('/documents/')) return;
34
+ let targetFile; try { targetFile = decodeURIComponent(target.pathname.slice('/documents/'.length)); } catch { return; }
35
+ a.dataset.canvasFile = targetFile; a.dataset.canvasAnchor = parts.slice(1).join('#');
36
+ a.href = '/library.html?file=' + encodeURIComponent(targetFile);
37
+ a.removeAttribute('target');
38
+ });
39
+ }
40
+ new MutationObserver(rewriteDocumentLinks).observe(document.querySelector('#world'), { childList: true, subtree: true });
41
+ rewriteDocumentLinks();
42
+ async function settle() {
43
+ await new Promise(resolve => requestAnimationFrame(resolve));
44
+ if (document.body.dataset.mode === 'cards') { if (!cardsInitialized) { cardsInitialized=true; await runtime.allEdges(true); } else { await runtime.whenMedia(); runtime.refresh(); } }
45
+ else { await runtime.whenMedia(); if (document.body.dataset.mode === 'mindmap') runtime.refresh(); }
46
+ }
47
+ document.addEventListener('click', event => {
48
+ const a = event.target.closest('a[href]');
49
+ if (!a || a.classList.contains('edge')) return;
50
+ if (a.dataset.canvasFile) { event.preventDefault(); event.stopImmediatePropagation(); post('open', { target: a.dataset.canvasFile, anchor: a.dataset.canvasAnchor }); return; }
51
+ const href = a.getAttribute('href');
52
+ if (!href || /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i.test(href)) return;
53
+ const parts = href.split('#');
54
+ if (!/\.mdc?$/i.test(parts[0])) return;
55
+ event.preventDefault(); event.stopImmediatePropagation();
56
+ const target = new URL(parts[0], 'https://clado.local/documents/' + file);
57
+ if (!target.pathname.startsWith('/documents/')) { post('missing', { target: href }); return; }
58
+ let targetFile; try { targetFile = decodeURIComponent(target.pathname.slice('/documents/'.length)); } catch { return; }
59
+ post('open', { target: targetFile, anchor: parts.slice(1).join('#') });
60
+ }, true);
61
+ modes.addEventListener('click', async event => { if (!event.target.closest('button')) return; await settle(); post('mode', { mode: document.body.dataset.mode }); });
62
+ document.querySelector('#theme').addEventListener('click', () => post('theme', { theme: document.documentElement.dataset.theme }));
63
+ function setDesign(design) {
64
+ if (chainOpen()) { deferredDesign=design;return; }
65
+ const key = JSON.stringify(design); if (key === designKey) return; designKey = key;
66
+ const root = document.documentElement;
67
+ if (root.dataset.theme !== design.theme) runtime.setTheme(design.theme || 'light', false);
68
+ root.style.setProperty('--proto-font', (design.font || 14) + 'px'); root.style.setProperty('--proto-radius', (design.radius ?? 11) + 'px'); root.style.setProperty('--proto-reading-width', (design.readingWidth || 1000) + 'px');
69
+ if (design.accent) { root.style.setProperty('--accent', design.accent); root.style.setProperty('--accent-soft', 'color-mix(in srgb,' + design.accent + ' 12%,var(--panel))'); }
70
+ if (design.cardWidth) root.style.setProperty('--canvas-card-width', design.cardWidth + 'px');
71
+ requestAnimationFrame(() => { if (document.body.dataset.mode !== 'doc') runtime.refresh(); });
72
+ }
73
+ document.addEventListener('clado:chain-open', () => post('chain-modal', { value: true, mode: document.body.dataset.mode }));
74
+ document.addEventListener('clado:chain-close', () => {
75
+ post('chain-modal', { value: false, mode: document.body.dataset.mode });
76
+ if (deferredDesign) { const next=deferredDesign;deferredDesign=null;setDesign(next); }
77
+ if (deferredDisplay) { const next=deferredDisplay;deferredDisplay=null;window.dispatchEvent(new MessageEvent('message', { source:parent,data:next })); }
78
+ });
79
+ window.addEventListener('message', async event => {
80
+ if(event.source!==parent || event.data?.type!=='clado-workspace:display')return;
81
+ if (runtime.isChainOpen?.()) { deferredDisplay=event.data;return; }
82
+ const {mode,theme,anchor}=event.data;
83
+ if(['doc','cards','mindmap'].includes(mode))runtime.setMode(mode);
84
+ if(['light','dark'].includes(theme))runtime.setTheme(theme,false);
85
+ await settle();
86
+ if(anchor) { let title=anchor;try{title=decodeURIComponent(anchor);}catch{}runtime.focusTitle(title); }
87
+ post('mode',{mode:document.body.dataset.mode});
88
+ });
89
+ window.CladoPrototype = { setDesign, isChainOpen: chainOpen, fit: () => { if(!chainOpen())runtime.refresh(); }, closeLens: runtime.closeLens, captureView: runtime.captureView, restoreView: runtime.restoreView };
90
+ let resizeTimer; addEventListener('resize', () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(() => { if (!chainOpen() && document.body.dataset.mode !== 'doc') runtime.refresh(); }, 120); });
91
+ settle().then(() => {
92
+ let anchor; try { anchor = decodeURIComponent(window.__CLADO_ANCHOR__ || params.get('anchor') || ''); } catch { anchor = ''; }
93
+ post('ready', { mode: document.body.dataset.mode });
94
+ if (anchor) requestAnimationFrame(() => requestAnimationFrame(() => runtime.focusTitle(anchor)));
95
+ }).catch(() => post('ready', { mode: document.body.dataset.mode }));
96
+ })();
@@ -0,0 +1,9 @@
1
+ :root{color-scheme:light;--panel:#fff;--bg:#f6f8fb;--ink:#263140;--muted:#8290a0;--line:#e2e7ef;--accent:#0969da;--soft:#edf4ff;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;font-size:12px}
2
+ *{box-sizing:border-box}body{margin:0;height:100vh;overflow:hidden;color:var(--ink);background:var(--panel)}button{font:inherit;border:1px solid var(--line);background:var(--panel);color:var(--muted);border-radius:6px;padding:5px 9px;cursor:pointer;white-space:nowrap}button:hover{color:var(--accent);border-color:var(--accent)}button:disabled{opacity:.4;cursor:default}button:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
3
+ .viewer,.viewer main{position:absolute;inset:0}iframe{height:100%;width:100%;display:block;border:0}.directory-toggle{position:fixed;left:18px;bottom:18px;z-index:20;border-radius:22px;padding:10px 15px;color:var(--ink);box-shadow:0 3px 15px #172b4318;background:var(--panel);font-size:12px}.directory-toggle span{font-size:10px;margin-left:7px;color:var(--muted)}.directory-toggle[data-sync="ok"]:before,.directory-toggle[data-sync="error"]:before{content:'';display:inline-block;width:5px;height:5px;border-radius:50%;background:#6ba882;vertical-align:middle;margin-right:7px}.directory-toggle[data-sync="error"]:before{background:#c99b40}
4
+ #directory{position:fixed;left:18px;bottom:68px;width:288px;max-height:calc(100vh - 94px);overflow:auto;padding:17px 10px 10px;border:1px solid var(--line);border-radius:12px;background:var(--panel);z-index:25;box-shadow:0 12px 40px #15243b24}.directory-heading{padding:0 9px 13px}.directory-heading strong{font-size:12px;font-weight:600}.directory-heading span{display:block;font-size:10px;color:var(--muted);margin-top:5px}#documentList{display:flex;flex-direction:column;gap:4px}.document-button{display:block;text-align:left;padding:9px 10px;white-space:normal;border-color:transparent;width:100%}.document-button strong{font-size:11px;font-weight:500;display:block;color:var(--ink)}.document-button small{font-size:9px;color:var(--muted);display:block;margin-top:4px;overflow-wrap:anywhere}.document-button[aria-current="page"]{background:var(--soft);border-color:var(--soft)}.document-button[aria-current="page"] strong{color:var(--accent)}.directory-current{padding:12px 10px 8px;margin-top:10px;border-top:1px solid var(--line)}.directory-current strong{font-size:10px;font-weight:500;display:block;color:var(--muted)}.directory-current span{display:block;color:var(--muted);font-size:9px;margin-top:4px;overflow-wrap:anywhere}.directory-actions{display:flex;gap:7px;padding:0 10px}.directory-actions button{font-size:10px;padding:4px 7px}.directory-actions #sourceButton{margin-left:auto}.skipped{margin-top:10px;border:0;border-top:1px solid var(--line);border-radius:0;width:100%;text-align:left;padding:11px 10px 2px;font-size:9px;color:var(--muted);white-space:normal}
5
+ .canvas-loading{position:absolute;inset:0;background:var(--panel);color:var(--muted);display:grid;place-items:center;font-size:12px;z-index:2}.canvas-loading[hidden],#directory[hidden],.update-error[hidden],.empty-state[hidden],.skipped[hidden]{display:none}.update-error{position:absolute;top:60px;left:16px;right:16px;z-index:5;background:#fff6dd;color:#896213;border:1px solid #ecd9a6;border-radius:7px;padding:10px 13px;font-size:11px;box-shadow:0 3px 12px #0001}.empty-state{position:absolute;inset:0;background:var(--panel);padding:70px 35px;text-align:center}.empty-state h1{font-size:17px;font-weight:550}.empty-state p{font-size:12px;line-height:1.9;color:var(--muted);max-width:360px;margin:15px auto}
6
+ .sync-error{color:#b88628!important}.sync-good:before{content:'';display:inline-block;width:4px;height:4px;border-radius:50%;background:#69a57f;vertical-align:middle;margin-right:5px}dialog{width:min(660px,calc(100vw - 32px));max-height:calc(100vh - 36px);border:1px solid var(--line);border-radius:10px;padding:0;background:var(--panel);color:var(--ink);box-shadow:0 15px 70px #13213e33}dialog::backdrop{background:#15243a66;backdrop-filter:blur(2px)}dialog>header{padding:15px 20px;border-bottom:1px solid var(--line);display:flex;align-items:center;gap:12px}dialog>header strong{font-size:13px;font-weight:600}dialog>header button{margin-left:auto;font-size:19px;line-height:1;border:0}#detailsBody{padding:18px 20px;max-height:calc(100vh - 130px);overflow:auto}#detailsBody p{font-size:11px;color:var(--muted);line-height:1.8;margin:0 0 14px}#detailsBody pre{font:11px/1.9 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre-wrap;overflow-wrap:anywhere;margin:0;background:var(--bg);padding:15px;border:1px solid var(--line);border-radius:7px}.skip-item{padding:10px 0;border-bottom:1px solid var(--line)}.skip-item strong{font-size:12px}.skip-item p{margin:5px 0!important}.skip-item code{font-size:10px}
7
+ [data-theme="dark"]{color-scheme:dark;--panel:#1c222b;--bg:#151a22;--ink:#dfe7ef;--muted:#9ba8b8;--line:#343e4c;--soft:#203753}@media(max-width:450px){.directory-toggle{left:12px;bottom:12px;padding:8px 12px}#directory{left:12px;bottom:58px;width:min(288px,calc(100vw - 24px));max-height:calc(100vh - 80px)}}
8
+ [hidden]{display:none!important}
9
+ .directory-search{display:block;padding:0 9px 10px}.directory-search input{box-sizing:border-box;width:100%;border:1px solid var(--line);border-radius:7px;background:var(--bg);color:var(--ink);font:inherit;padding:8px 10px;outline-color:var(--accent)}.tree-folder>summary{cursor:pointer;padding:8px;color:var(--ink);font-size:12px;font-weight:550}.tree-children{margin-left:11px;padding-left:5px;border-left:1px solid var(--line)}.tree-empty{padding:8px;color:var(--muted);font-size:12px}
@@ -0,0 +1,20 @@
1
+ <!doctype html>
2
+ <html lang="zh-CN" data-theme="light">
3
+ <head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Clado · Markdown 目录预览</title><link rel="stylesheet" href="library.css"></head>
4
+ <body>
5
+ <button id="directoryButton" class="directory-toggle" aria-expanded="false" aria-controls="directory" title="切换 Markdown 画布">文档 <span id="fileCount">…</span></button>
6
+ <aside id="directory" aria-label="Markdown 画布目录" hidden>
7
+ <div class="directory-heading"><strong>Markdown/</strong><span>选择文档,打开对应画布</span></div>
8
+ <label class="directory-search"><input id="documentSearch" type="search" aria-label="搜索文档" placeholder="搜索名称或路径…"></label>
9
+ <nav id="documentList" aria-label="可用 Markdown"></nav>
10
+ <div class="directory-current"><strong id="currentTitle" hidden>正在扫描 Markdown…</strong><span id="currentPath" hidden>Markdown/</span><span id="syncStatus" role="status">连接本地目录</span></div>
11
+ <div class="directory-actions"><button id="backButton" disabled>← 返回</button><button id="refreshButton" title="重新扫描目录并刷新当前文档">刷新</button><button id="sourceButton">源文</button></div>
12
+ <button id="skippedButton" class="skipped" hidden></button>
13
+ </aside>
14
+ <div class="viewer">
15
+ <main><div id="updateError" class="update-error" role="alert" hidden></div><iframe id="canvas" title="当前 Markdown 的脑图、卡片与文档"></iframe><div id="canvasLoading" class="canvas-loading">正在读取 Markdown…</div><div id="emptyState" class="empty-state" hidden><h1>目录中还没有可展示的画布</h1><p>让 AI 连接当前服务的 MCP,读取模板并创建 .mdc 文档,保存后会自动出现在这里。</p></div></main>
16
+ </div>
17
+ <dialog id="details"><header><strong id="detailsTitle"></strong><button id="closeDetails" aria-label="关闭详情">×</button></header><div id="detailsBody"></div></dialog>
18
+ <script src="/tree.js"></script>
19
+ <script src="library.js"></script>
20
+ </body></html>
@@ -0,0 +1,127 @@
1
+ (() => {
2
+ const $ = selector => document.querySelector(selector);
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();
7
+ const storageKey='clado-library-view:v2:'+location.pathname;
8
+ const post = (type, extra = {}) => { if (parent !== window) parent.postMessage({ type: 'clado-prototype:' + type, board: 'library', ...extra }, location.origin); };
9
+ try { const saved = JSON.parse(sessionStorage.getItem(storageKey) || '{}'); selected = saved.file || ''; if (!config.mode && ['mindmap','cards','doc'].includes(saved.mode)) mode = saved.mode; } catch {}
10
+ const requestedFile = new URLSearchParams(location.search).get('file');
11
+ if (requestedFile || config.entry) selected = requestedFile || config.entry;
12
+ pendingAnchor = new URLSearchParams(location.search).get('anchor') || '';
13
+ function saveView() { try { sessionStorage.setItem(storageKey, JSON.stringify({ file: selected, mode })); } catch {} }
14
+ function modalLocked() { try { return chainModal || !!frame.contentWindow.CladoPrototype?.isChainOpen?.(); } catch { return chainModal; } }
15
+ function chainLock(value, currentMode) {
16
+ chainModal=!!value;
17
+ 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
+ if(!chainModal) { const force=deferredRefresh;deferredRefresh=false;scan(force); }
21
+ }
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
+ }
34
+ let renderRequest = 0;
35
+ async function open(file, anchor = '', options = {}) {
36
+ if(modalLocked()) { if(options.update)deferredRefresh=true;return; }
37
+ pendingAnchor=anchor;
38
+ const doc = index.documents.find(d => d.file === file);
39
+ if (!doc) { details('这个 Markdown 暂未收录', '<p>' + esc(file) + ' 不在有效画布目录中。可以让 AI 检查文件是否存在、路径是否正确,以及能否通过解析。</p>'); return; }
40
+ if (selected && file !== selected && !options.back) history.push(selected);
41
+ if (options.update) { try { pendingView = frame.contentWindow.CladoPrototype?.captureView?.(); } catch {} }
42
+ else pendingView = null;
43
+ 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;
46
+ $('#updateError').hidden = true; $('#emptyState').hidden = true; $('#canvasLoading').hidden = false;
47
+ // Give each render its own browsing context. A late ready/message from the
48
+ // previous document must never complete a newer render or restore its view.
49
+ try {
50
+ let html;
51
+ if(offline) html=offline.canvases[file].replace(/<!--CLADO-ASSET:(\d+)-->/g,(_,id)=>offline.shared?.[id] || '');
52
+ else {
53
+ const response = await fetch('/library/canvas?file=' + encodeURIComponent(file) + '&mode=' + mode + '&revision=' + version + (anchor ? '&anchor=' + encodeURIComponent(anchor) : ''), {cache:'no-store'});
54
+ if(!response.ok)throw new Error('render');
55
+ html = await response.text();
56
+ }
57
+ if(request !== renderRequest)return;
58
+ if(modalLocked()) { deferredRefresh=true;version=previousVersion;$('#canvasLoading').hidden=true;return; }
59
+ if(mode !== requestedMode) { version=previousVersion;open(file,anchor,{...options,update:true});return; }
60
+ const nextFrame = document.createElement('iframe');
61
+ nextFrame.id = 'canvas'; nextFrame.title = frame.title;
62
+ nextFrame.srcdoc = html;
63
+ frame.replaceWith(nextFrame); frame = nextFrame;
64
+ } catch {
65
+ if(request !== renderRequest)return;
66
+ version = previousVersion; $('#canvasLoading').hidden = true;
67
+ $('#updateError').textContent = '画布读取失败,保留上次画面并自动重试。'; $('#updateError').hidden = false; status('当前画布未更新', true);
68
+ }
69
+ }
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; }
71
+ async function scan(force = false) {
72
+ if (busy) return; busy = true;
73
+ try {
74
+ if(offline) index=offline.index;
75
+ else { const response=await fetch('/library/index.json',{cache:'no-store'});if(!response.ok)throw new Error('scan');index=await response.json(); }
76
+ renderDirectory();
77
+ try{frame.contentWindow.postMessage({type:'clado-workspace:index',index},'*');}catch{}
78
+ if(modalLocked()) {
79
+ const current=index.documents.find(d=>d.file===selected);
80
+ if(force || !current || current.version!==version)deferredRefresh=true;
81
+ status(deferredRefresh?'源文已更新,关闭链路画布后同步':'链路画布打开中');
82
+ return;
83
+ }
84
+ if (pendingOpen && index.documents.some(d=>d.file===pendingOpen)) { const file=pendingOpen;pendingOpen=null;open(file); }
85
+ if (selected && !version && !index.documents.some(d=>d.file===selected)) { selected='';saveView(); }
86
+ 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'); }
88
+ else {
89
+ const doc = index.documents.find(d => d.file === selected);
90
+ if (!doc && !version && index.documents.length) open(index.documents[0].file);
91
+ else if (!doc) { $('#updateError').textContent = '当前 Markdown 已删除或暂时无法解析,保留上次画面。有效文档仍可从目录打开。'; $('#updateError').hidden = false; status('当前画布未更新', true); $('#canvasLoading').hidden = true; post('ready'); }
92
+ 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 })); }
93
+ }
94
+ } catch { status('连接中断,正在重连', true); $('#updateError').textContent = '目录连接中断,保留当前画面。服务恢复后自动重连。'; $('#updateError').hidden = false; $('#canvasLoading').hidden = true; post('ready'); }
95
+ finally { busy = false; }
96
+ }
97
+ addEventListener('message', event => {
98
+ if ((!offline && event.origin !== location.origin) || event.source !== frame.contentWindow) return;
99
+ 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 }); }
107
+ else if (data?.type === 'clado-library:ready') {
108
+ 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;
110
+ try{frame.contentWindow.CladoPrototype?.setDesign(design);}catch{}
111
+ if (!offline && pendingView) { const view = pendingView; pendingView = null; requestAnimationFrame(() => requestAnimationFrame(() => frame.contentWindow.CladoPrototype?.restoreView?.(view))); }
112
+ status('已同步 ' + new Date(index.documents.find(d => d.file === selected)?.modified || Date.now()).toLocaleTimeString('zh-CN', { hour12: false })); post('ready');
113
+ }
114
+ });
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 {} }
116
+ 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);
127
+ })();
@@ -0,0 +1,26 @@
1
+ (() => {
2
+ window.CladoDocumentTree = function (container, documents, { selected='', query='', onOpen=()=>{}, folders=new Set() } = {}) {
3
+ const needle=query.trim().toLocaleLowerCase(), root={folders:new Map(),files:[]};
4
+ for(const doc of documents) {
5
+ if(needle && !(doc.title+' '+doc.file).toLocaleLowerCase().includes(needle))continue;
6
+ const parts=doc.file.split('/');let node=root;
7
+ parts.slice(0,-1).forEach((name,i)=>{const path=parts.slice(0,i+1).join('/');if(!node.folders.has(name))node.folders.set(name,{path,folders:new Map(),files:[]});node=node.folders.get(name);});node.files.push(doc);
8
+ }
9
+ container.replaceChildren();
10
+ function render(node, parent) {
11
+ for(const [name,folder] of node.folders) {
12
+ const details=document.createElement('details');details.className='tree-folder';details.open=!!needle||!folders.has('closed:'+folder.path);
13
+ const summary=document.createElement('summary');summary.textContent=name;details.append(summary);
14
+ details.addEventListener('toggle',()=>{if(!needle){if(details.open)folders.delete('closed:'+folder.path);else folders.add('closed:'+folder.path);}});
15
+ const children=document.createElement('div');children.className='tree-children';details.append(children);render(folder,children);parent.append(details);
16
+ }
17
+ for(const doc of node.files) {
18
+ const button=document.createElement('button');button.className='document-button';button.dataset.file=doc.file;if(doc.file===selected)button.setAttribute('aria-current','page');
19
+ const strong=document.createElement('strong');strong.textContent=doc.title;
20
+ const small=document.createElement('small');small.textContent=doc.file.split('/').pop();button.append(strong,small);button.onclick=()=>onOpen(doc.file);parent.append(button);
21
+ }
22
+ }
23
+ render(root,container);
24
+ if(!container.childElementCount){const empty=document.createElement('p');empty.className='tree-empty';empty.textContent=needle?'没有匹配的文档':'还没有可展示的文档';container.append(empty);}
25
+ };
26
+ })();
@@ -0,0 +1,53 @@
1
+ import { readFileSync, existsSync } from 'node:fs';
2
+ import { dirname, join, relative, resolve, basename } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { renderHtml } from '../html/page.js';
5
+ import { workspacePath } from '../workspace/documents.js';
6
+ const assets=join(dirname(fileURLToPath(import.meta.url)),'assets');
7
+ const read=name=>readFileSync(join(assets,name),'utf8');
8
+ const json=value=>JSON.stringify(value).replace(/</g,'\\u003c');
9
+ const script=value=>'<script>'+value.replace(/<\/script/gi,'<\\/script')+'</script>';
10
+ 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
+ /** One portable workspace, including all canvases, navigation, sources and local media. */
12
+ export function renderWorkspace(jobs,{root,entry,mode='mindmap',theme='light',title}={}) {
13
+ root=resolve(root);
14
+ const documents=jobs.map(j=>({file:relative(root,j.file).split('\\').join('/'),title:j.doc.title,version:'offline',modified:0}));
15
+ const index={root:basename(root)+'/',documents,skipped:[]},canvases={},sources={},shared=[],assetIds=new Map();
16
+ for(let i=0;i<jobs.length;i++) {
17
+ const job=jobs[i],file=documents[i].file,source=readFileSync(job.file,'utf8'),resources={};
18
+ // Resolve only contained local resources; remote URLs remain ordinary remote links.
19
+ const refs=[
20
+ ...Array.from(source.matchAll(/!?\[[^\]]*\]\(\s*(?:<([^>]+)>|([^\s)]+))/g),m=>m[1] || m[2]),
21
+ ...Array.from(source.matchAll(/^ {0,3}\[[^\]]+\]:\s*(?:<([^>]+)>|(\S+))/gm),m=>m[1] || m[2]),
22
+ ...Array.from(source.matchAll(/<(?:img|a)\b[^>]*?\b(?:src|href)\s*=\s*(?:"([^"]+)"|'([^']+)')/gi),m=>m[1] || m[2])
23
+ ];
24
+ for(const ref of refs) {
25
+ if(/^(?:[a-z][a-z0-9+.-]*:|\/|#)/i.test(ref))continue;
26
+ try {
27
+ const url=new URL(ref,'https://clado.local/documents/'+file);
28
+ if(!url.pathname.startsWith('/documents/'))continue;
29
+ const name=decodeURIComponent(url.pathname.slice(11)),type=mime[name.split('.').pop().toLowerCase()];
30
+ if(!type)continue;
31
+ const path=workspacePath(root,name,false,true);
32
+ if(existsSync(path))resources[name]='data:'+type+';base64,'+readFileSync(path).toString('base64');
33
+ }catch{}
34
+ }
35
+ let html=renderHtml(job.doc,job.diagnostics,{file,title:job.doc.title,mode,theme,library:true});
36
+ const end=html.lastIndexOf('</body>');
37
+ const boot='window.__CLADO_OFFLINE__=true;window.__CLADO_FILE_PATH__='+json(file)+';window.__CLADO_WORKSPACE_INDEX__='+json(index)+';window.__CLADO_RESOURCES__='+json(resources)+';';
38
+ html=html.slice(0,end)+script(boot)+script(read('library-canvas.js'))+html.slice(end);
39
+ // Store identical renderer/style blocks once, then hydrate each iframe locally.
40
+ html=html.replace(/<(script|style)\b[^>]*>([\s\S]*?)<\/\1>/g,(block)=>{
41
+ if(block.length<4096)return block;
42
+ if(!assetIds.has(block)){assetIds.set(block,shared.length);shared.push(block);}
43
+ return '<!--CLADO-ASSET:'+assetIds.get(block)+'-->';
44
+ });
45
+ canvases[file]=html;sources[file]=source;
46
+ }
47
+ let html=read('library.html');
48
+ 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
+ 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
+ html=html.replace('<title>Clado · Markdown 目录预览</title>','<title>'+String(title || 'Clado').replace(/[&<>]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;'}[c]))+'</title>');
52
+ return html;
53
+ }
@@ -0,0 +1,108 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
3
+ import { z } from 'zod/v4';
4
+ import { VERSION } from '../util/version.js';
5
+
6
+ const text = () => z.string().max(2_000_000);
7
+ const path = () => z.array(z.string().min(1)).min(1).max(6).describe('读取结果返回的标题数组,保留完整文字;不拼接点号路径或内部ID。');
8
+ const workspace = z.string().min(1).describe('工作区绝对路径,每次调用必填,必须位于 serve 启动目录内。');
9
+ const version = z.string().describe('最近一次读取返回的 workspaceVersion,写入必填;冲突后重新读取并合并。').optional();
10
+ const templateSource = z.enum(['ancestor','user']).optional().describe('仅用于 pull,明确选择上级项目或用户库。省略时逐层向上查找,全部缺失再查用户库。');
11
+ const position = z.object({
12
+ mode: z.enum(['append','prepend','before','after','replace']),
13
+ paragraph: z.number().int().positive().optional().describe('正文段落编号,从1开始,使用read返回的paragraphs.index;代码围栏整体计1段。'),
14
+ anchor: z.string().min(1).optional().describe('唯一原文;before/after围绕这段文字插入,replace替换这段文字,与paragraph只选一个。'),
15
+ }).strict().optional().describe('默认append到节点正文末尾。prepend置顶;before/after/replace用paragraph或唯一anchor定位。');
16
+ const indexFromOne = z.number().int().positive();
17
+ const sourcePoint = z.discriminatedUnion('kind', [
18
+ z.object({ kind: z.literal('code'), paragraph: indexFromOne, line: indexFromOne, text: z.string().min(1).max(200).regex(/^[^\r\n]*\S[^\r\n]*$/).optional().describe('可用这一行唯一的原文核对定位,例如 replay。线从该行右侧出发。') }).strict(),
19
+ z.object({ kind: z.literal('table'), paragraph: indexFromOne, row: indexFromOne }).strict(),
20
+ z.object({ kind: z.literal('mermaid'), paragraph: indexFromOne, nodeId: z.string().regex(/^[\w.-]+$/) }).strict()
21
+ ]).optional().describe('同画布连线的起点。paragraph 来自 nodes.read;line 是代码块内行,空行计数;row 是表格数据行,不含表头;nodeId 是 Mermaid 节点 ID。行号从1开始。');
22
+ const targetPoint = z.object({ kind: z.literal('table'), paragraph: indexFromOne, row: indexFromOne }).strict().optional().describe('可选表格落点,位于 targetNode 的正文;paragraph/row 从1开始,row 不含表头。与 sourcePoint 一起使用。');
23
+ const nodeFields = {
24
+ file: z.string().optional().describe('相对 documentRoot 的路径,新文件用 .mdc;旧 .md 兼容。'),
25
+ node: path().optional(), parent: path().optional().describe('父节点标题数组;省略表示一级卡片。'),
26
+ title: z.string().optional(), content: text().optional().describe('仅本节点正文,直接传多行字符串,不含结构标题;更新保留孩子。'),
27
+ 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
+ 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
+ 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
31
+ };
32
+ 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。' });
35
+ const schemas = new Map();
36
+ const enrich = (result, args) => {
37
+ const { diagnostics: _operationDiagnostics, error, ...payload } = result;
38
+ const report = invoke.diagnostics(args);
39
+ return { ...(error ? { error } : {}), ...report, ...payload, valid: report.valid };
40
+ };
41
+ const encoded = (result, isError = false) => ({ ...(isError ? { isError: true } : {}), content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: result });
42
+ 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) => {
44
+ schemas.set(name, z.object({ workspace, ...schema }).strict());
45
+ return server.registerTool(name, {
46
+ description, inputSchema: { workspace, ...schema }, annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false }
47
+ }, async args => {
48
+ try { return encoded(enrich(invoke(name, args), args)); }
49
+ catch (error) { return failure(error, args); }
50
+ });
51
+ };
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()
54
+ });
55
+ 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
+ action: z.enum(['list','read','create','update','delete','pull','push']), scope: z.enum(['project','user']).optional(),
57
+ ...Object.fromEntries(['templateId','source','baseTemplateId','name','purpose','overwrite'].map(key => [key, nodeFields[key]])),
58
+ from: templateSource,
59
+ view: z.enum(['prompt','source','full']).optional().describe('read默认prompt,编辑规则用source,只有需要全部字段时才用full。'),
60
+ expectedWorkspaceVersion: version, expectedUserTemplateVersion: z.string().optional().describe('读取返回的userTemplateVersion;用户库写入及push必填。'), dryRun: z.boolean().optional()
61
+ });
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()
64
+ });
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()
67
+ });
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()
70
+ });
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)
73
+ });
74
+ return { server, checkCall: (name, args) => {
75
+ const schema = schemas.get(name);
76
+ if (!schema) return failure({ message: '没有这个工具:' + name, status: 400 }, args);
77
+ const checked = schema.safeParse(args);
78
+ if (!checked.success) return failure({ message: '工具参数不合法。', status: 400, details: { code: 'INVALID_ARGUMENTS', issues: checked.error.issues } }, args);
79
+ return null;
80
+ } };
81
+ }
82
+
83
+ export function createMcpHandler(invoke) {
84
+ return async (req, res, url) => {
85
+ if (url.pathname !== '/mcp') return false;
86
+ const host = req.headers.host;
87
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host || '') || (req.headers.origin && req.headers.origin !== 'http://' + host)) { res.writeHead(403).end('只接受本机可信来源。'); return true; }
88
+ if (req.method !== 'POST') { res.writeHead(405, { allow: 'POST' }).end(); return true; }
89
+ let server, transport;
90
+ try {
91
+ const chunks = []; let bytes = 0;
92
+ 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
+ const data = JSON.parse(Buffer.concat(chunks).toString('utf8'));
94
+ const created = createServer(invoke); server = created.server;
95
+ if (data.method === 'tools/call') {
96
+ const rejected = created.checkCall(data.params?.name, data.params?.arguments);
97
+ 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; }
98
+ }
99
+ transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
100
+ res.on('close', () => { transport.close().catch(() => {}); server.close().catch(() => {}); });
101
+ await server.connect(transport); await transport.handleRequest(req, res, data);
102
+ } catch (error) {
103
+ if (!res.headersSent) res.writeHead(error instanceof SyntaxError ? 400 : 500, { 'content-type': 'application/json' });
104
+ if (!res.writableEnded) res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32603, message: error.message } }));
105
+ }
106
+ return true;
107
+ };
108
+ }
@@ -0,0 +1,84 @@
1
+ import { createServer } from 'node:http';
2
+ import { readFileSync, statSync, existsSync, mkdirSync } from 'node:fs';
3
+ import { dirname, resolve, basename, join, relative } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { renderHtml } from '../html/page.js';
6
+ import { scanDirectory, workspacePath, readDocument, DocumentError } from '../workspace/documents.js';
7
+ import { contextFor, initialize } from '../workspace/storage.js';
8
+ import { createWorkspaceService } from '../workspace/service.js';
9
+ import { createMcpHandler } from './mcp.js';
10
+ const assets = join(dirname(fileURLToPath(import.meta.url)), 'assets');
11
+ const resourceTypes = {png:'image/png',jpg:'image/jpeg',jpeg:'image/jpeg',gif:'image/gif',webp:'image/webp',svg:'image/svg+xml',pdf:'application/pdf',txt:'text/plain',csv:'text/csv',json:'application/json'};
12
+ const types = { html: 'text/html', css: 'text/css', js: 'text/javascript', json: 'application/json', md: 'text/markdown' };
13
+ export function createWorkspaceHandler(directory, options = {}) {
14
+ const root = resolve(directory);
15
+ const assetNames = new Set(['library.html','library.css','library.js','library-canvas.js','tree.js']);
16
+ const send = (res, status, type, body) => { res.writeHead(status, { 'content-type': type + '; charset=utf-8', 'cache-control':'no-store', 'x-content-type-options':'nosniff' }); res.end(body); };
17
+ const json = (res, status, data) => send(res, status, types.json, JSON.stringify(data));
18
+ const safeJson = data => JSON.stringify(data).replace(/</g,'\\u003c');
19
+ return async function handle(req, res, url) {
20
+ const route = url.pathname.slice(1);
21
+ if (!url.pathname.startsWith('/library/') && !assetNames.has(route) && !(options.entrypoint && route === '')) return false;
22
+ try {
23
+ const host = req.headers.host;
24
+ if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host || '')) throw new DocumentError('只接受本机预览请求。',403);
25
+ if (req.headers.origin && req.headers.origin !== 'http://' + host) throw new DocumentError('来源不匹配。',403);
26
+ if (req.method !== 'GET' && req.method !== 'HEAD') throw new DocumentError('不支持这个请求方法。',405);
27
+ if (assetNames.has(route) || (options.entrypoint && route === '')) {
28
+ const name = route || 'library.html'; let body = readFileSync(join(assets,name),'utf8');
29
+ if (name === 'library.html') {
30
+ body = body.replace('<script src="library.js">','<script>window.__CLADO_WORKSPACE__='+safeJson({mode:options.mode || 'mindmap',theme:options.theme || 'light',entry:options.entry || ''})+';</script><script src="library.js">');
31
+ }
32
+ send(res,200,types[name.split('.').pop()],body); return true;
33
+ }
34
+ if (url.pathname === '/library/index.json') {
35
+ const result = scanDirectory(root);
36
+ json(res,200,{root:basename(root)+'/',documents:result.documents,skipped:result.skipped}); return true;
37
+ }
38
+ const name = url.searchParams.get('file');
39
+ if (url.pathname === '/library/resource') {
40
+ const type = resourceTypes[String(name).split('.').pop().toLowerCase()];
41
+ if (!type) throw new DocumentError('不支持的资源类型。',415);
42
+ const path=workspacePath(root,name,false,true);
43
+ res.writeHead(200,{'content-type':type,'x-content-type-options':'nosniff','content-security-policy':"default-src 'none'; sandbox",'cache-control':'no-store'});res.end(readFileSync(path));return true;
44
+ }
45
+ if (!['/library/source.mdc','/library/canvas'].includes(url.pathname)) throw new DocumentError('没有这个预览入口;文档操作请使用 /mcp。',404);
46
+ const file = workspacePath(root,name), item = readDocument(file);
47
+ if (url.pathname === '/library/source.mdc') { send(res,200,types.md,item.source); return true; }
48
+ if (item.diagnostics.some(d=>d.severity==='error')) throw new DocumentError('文档暂时无法解析。',422,item.diagnostics);
49
+ const mode = ['doc','cards','mindmap'].includes(url.searchParams.get('mode')) ? url.searchParams.get('mode') : options.mode || 'mindmap';
50
+ let html = (options.render || renderHtml)(item.doc,item.diagnostics,{file:name,title:item.doc.title,mode,theme:options.theme || 'light',library:true});
51
+ const bodyEnd = html.lastIndexOf('</body>');
52
+ html = html.slice(0,bodyEnd) + '<script>window.__CLADO_FILE_PATH__='+safeJson(name)+';window.__CLADO_ANCHOR__='+safeJson(url.searchParams.get('anchor') || '')+';</script><script src="/library-canvas.js"></script>' + html.slice(bodyEnd);
53
+ send(res,200,types.html,html); return true;
54
+ } catch (error) {
55
+ json(res,error.status || (error instanceof SyntaxError ? 400 : 500),{error:error.message,diagnostics:error.diagnostics || []}); return true;
56
+ }
57
+ };
58
+ }
59
+ export async function startWorkspace(input, { port = 4317, mode = 'mindmap', theme = 'light', entry, project = false } = {}) {
60
+ const path = resolve(input);
61
+ if (!existsSync(path) && !/\.mdc?$/i.test(path)) mkdirSync(path, { recursive: true });
62
+ if (statSync(path).isFile() && !/\.mdc?$/i.test(path)) throw new DocumentError('serve 文件需要 .mdc 或 .md 扩展名。');
63
+ let root = statSync(path).isDirectory() ? path : dirname(path), workspace = root;
64
+ if (basename(root) === 'doc' && basename(dirname(root)) === '.clado') workspace = dirname(dirname(root));
65
+ else if (project || existsSync(join(root, '.clado/workspace.json')) || existsSync(join(root, 'package.json')) || existsSync(join(root, '.git')) || (statSync(path).isDirectory() && !scanDirectory(root).documents.some(d => !/^readme\.md$/i.test(d.file)))) {
66
+ const ctx = contextFor(root, root); workspace = root; root = ctx.documents;
67
+ }
68
+ const ctx = contextFor(workspace, workspace, root); initialize(ctx);
69
+ const entryFile = entry ? relative(root,workspacePath(root,entry)).split('\\').join('/') : (statSync(path).isFile() ? basename(path) : '');
70
+ if (entryFile) {
71
+ const item=readDocument(workspacePath(root,entryFile));
72
+ if(item.diagnostics.some(d=>d.severity==='error'))throw new DocumentError('入口 Markdown 无法解析。',422,item.diagnostics);
73
+ }
74
+ const handle = createWorkspaceHandler(root,{entrypoint:true,mode,theme,entry:entryFile});
75
+ const mcp = createMcpHandler(createWorkspaceService(workspace, { documentRoot: root }));
76
+ const server = createServer(async (req,res) => {
77
+ try { const url = new URL(req.url,'http://127.0.0.1'); if (!await mcp(req,res,url) && !await handle(req,res,url)) { res.writeHead(404);res.end('Not found'); } }
78
+ catch { if (!res.headersSent) res.writeHead(500);res.end('预览请求失败'); }
79
+ });
80
+ await new Promise((resolve,reject) => { server.once('error',reject); server.listen(port,'127.0.0.1',resolve); });
81
+ const file = entryFile ? '?file='+encodeURIComponent(entryFile) : '';
82
+ const origin = 'http://127.0.0.1:'+server.address().port;
83
+ return {server,url:origin+'/'+file,mcpUrl:origin+'/mcp',workspace,root};
84
+ }