cladogram 0.4.0 → 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.
- package/README.md +59 -108
- package/bin/clado.js +73 -101
- package/package.json +11 -8
- package/skills/clado/SKILL.md +170 -53
- package/src/core/links.js +37 -0
- package/src/core/media-links.js +99 -0
- package/src/core/parse.js +65 -77
- package/src/html/app-css.js +10 -20
- package/src/html/canvas-card.js +1 -2
- package/src/html/canvas-chain.js +64 -36
- package/src/html/canvas-focus.js +81 -81
- package/src/html/canvas-ui.css +22 -5
- package/src/html/canvas-ui.js +3 -1
- package/src/html/canvas-wires.js +28 -11
- package/src/html/media-anchors.js +212 -0
- package/src/html/mindmap-connectors.js +33 -12
- package/src/html/page.js +8 -5
- package/src/html/runtime-api.js +7 -18
- package/src/html/runtime-fixes.js +0 -9
- package/src/html/runtime.js +156 -131
- package/src/server/assets/library-canvas.js +18 -12
- package/src/server/assets/library.html +2 -2
- package/src/server/assets/library.js +56 -23
- package/src/server/assets/tree.js +1 -1
- package/src/server/export.js +1 -1
- package/src/server/mcp.js +108 -0
- package/src/server/workspace.js +26 -37
- package/src/skill/install.js +16 -18
- package/src/skill/targets.js +17 -10
- package/src/skill/templates.js +60 -0
- package/src/util/version.js +3 -0
- package/src/workspace/content.js +72 -0
- package/src/workspace/documents.js +4 -82
- package/src/workspace/references.js +101 -0
- package/src/workspace/service.js +457 -0
- package/src/workspace/storage.js +169 -0
- package/src/workspace/tree.js +66 -0
- package/templates/business-flow.mdc +29 -0
- package/templates/call-chain.mdc +62 -0
- package/templates/data-design.mdc +35 -0
- package/templates/mind-expansion.mdc +52 -0
- package/templates/requirement-overview.mdc +29 -0
- package/templates/system-state.mdc +29 -0
- package/examples/showcase/README.md +0 -117
- package/examples/showcase/baseline.md +0 -365
- package/examples/showcase/build.sh +0 -48
- package/examples/showcase/calls.md +0 -136
- package/examples/showcase/fulfill-cn.md +0 -351
- package/examples/showcase/fulfill.md +0 -271
- package/examples/showcase/index.md +0 -187
- package/examples/showcase/order.md +0 -195
- package/examples/showcase/promo.md +0 -580
- package/examples/showcase/refund.md +0 -966
- package/examples/showcase/seckill.md +0 -787
- package/skills/clado/examples/01-/351/234/200/346/261/202/346/240/221.md +0 -32
- package/skills/clado/examples/02-/346/225/260/346/215/256/350/241/250.md +0 -44
- package/skills/clado/examples/03-/346/216/245/345/217/243/346/270/205/345/215/225.md +0 -51
- package/skills/clado/examples/04-/346/226/271/346/263/225/351/223/276.md +0 -70
- package/skills/clado/examples/05-/346/216/245/345/217/243/350/260/203/347/224/250.md +0 -58
- package/skills/clado/examples/06-/350/260/203/347/224/250/351/223/276.md +0 -49
- package/skills/clado/examples/07-/346/213/206/346/226/207/346/241/243/index.md +0 -38
- package/skills/clado/examples/07-/346/213/206/346/226/207/346/241/243/refund.md +0 -33
- package/skills/clado/examples/07-/346/213/206/346/226/207/346/241/243/seckill.md +0 -56
- 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
- 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
- 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
- package/skills/clado/examples/09-/345/215/217/344/275/234/347/224/273/345/270/203/backend.md +0 -80
- package/skills/clado/examples/09-/345/215/217/344/275/234/347/224/273/345/270/203/data.md +0 -53
- package/skills/clado/examples/09-/345/215/217/344/275/234/347/224/273/345/270/203/interaction.md +0 -70
- package/skills/clado/examples/09-/345/215/217/344/275/234/347/224/273/345/270/203/overview.md +0 -30
- package/skills/clado/examples/09-/345/215/217/344/275/234/347/224/273/345/270/203/verify.md +0 -35
- package/skills/clado/examples/10-/346/235/203/351/231/220/347/224/263/350/257/267/approval.md +0 -69
- package/skills/clado/examples/10-/346/235/203/351/231/220/347/224/263/350/257/267/data-verify.md +0 -49
- package/skills/clado/examples/10-/346/235/203/351/231/220/347/224/263/350/257/267/interaction.md +0 -47
- package/skills/clado/examples/10-/346/235/203/351/231/220/347/224/263/350/257/267/overview.md +0 -39
- package/skills/clado/examples/11-/344/272/213/346/225/205/345/223/215/345/272/224/evidence.md +0 -42
- package/skills/clado/examples/11-/344/272/213/346/225/205/345/223/215/345/272/224/overview.md +0 -26
- package/skills/clado/examples/11-/344/272/213/346/225/205/345/223/215/345/272/224/response.md +0 -64
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/api.md +0 -127
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/caller.md +0 -50
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/calls.md +0 -185
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/code.md +0 -249
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/consumer.md +0 -93
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/contracts.md +0 -89
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/data.md +0 -237
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/overview.md +0 -75
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/publisher.md +0 -175
- package/skills/clado/examples/12-/346/216/245/345/217/243/345/210/260/344/273/243/347/240/201/verify.md +0 -53
- package/skills/clado/examples/13-/346/216/245/345/217/243/346/226/271/346/263/225/345/210/260SQL/01-/347/224/263/350/257/267/350/275/254/345/215/225.md +0 -499
- package/skills/clado/examples/13-/346/216/245/345/217/243/346/226/271/346/263/225/345/210/260SQL/02-/345/267/262/346/234/211/350/256/242/345/215/225/346/216/245/345/217/243.md +0 -46
- package/skills/clado/examples/13-/346/216/245/345/217/243/346/226/271/346/263/225/345/210/260SQL/03-/350/241/250/347/273/223/346/236/204.md +0 -100
- package/skills/clado/examples/13-/346/216/245/345/217/243/346/226/271/346/263/225/345/210/260SQL/overview.md +0 -47
- package/skills/clado/examples/build.sh +0 -47
- package/skills/clado/references/content-patterns.md +0 -61
- package/skills/clado/references/data.md +0 -37
- package/skills/clado/references/delivery.md +0 -57
- package/skills/clado/references/diagnostics.md +0 -26
- package/skills/clado/references/editing.md +0 -49
- package/skills/clado/references/engineering.md +0 -167
- package/skills/clado/references/flows.md +0 -53
- package/skills/clado/references/interactions.md +0 -46
- package/skills/clado/references/operations.md +0 -39
- package/skills/clado/references/requirements.md +0 -37
- package/skills/clado/references/verification.md +0 -27
- package/src/html/mindmap-motion.js +0 -69
- package/src/server/assets/editor.css +0 -1
- package/src/server/assets/editor.js +0 -79
- package/src/workspace/commands.js +0 -42
|
@@ -8,11 +8,11 @@
|
|
|
8
8
|
<label class="directory-search"><input id="documentSearch" type="search" aria-label="搜索文档" placeholder="搜索名称或路径…"></label>
|
|
9
9
|
<nav id="documentList" aria-label="可用 Markdown"></nav>
|
|
10
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
|
|
11
|
+
<div class="directory-actions"><button id="backButton" disabled>← 返回</button><button id="refreshButton" title="重新扫描目录并刷新当前文档">刷新</button><button id="sourceButton">源文</button></div>
|
|
12
12
|
<button id="skippedButton" class="skipped" hidden></button>
|
|
13
13
|
</aside>
|
|
14
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
|
|
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
16
|
</div>
|
|
17
17
|
<dialog id="details"><header><strong id="detailsTitle"></strong><button id="closeDetails" aria-label="关闭详情">×</button></header><div id="detailsBody"></div></dialog>
|
|
18
18
|
<script src="/tree.js"></script>
|
|
@@ -1,17 +1,26 @@
|
|
|
1
1
|
(() => {
|
|
2
|
-
const $ = selector => document.querySelector(selector)
|
|
2
|
+
const $ = selector => document.querySelector(selector);
|
|
3
|
+
let frame = $('#canvas');
|
|
3
4
|
const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
|
|
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, directorySignature = '', pendingOpen = null, pendingAnchor = '',
|
|
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;
|
|
5
6
|
const config=window.__CLADO_WORKSPACE__ || {}, offline=config.offline, folders=new Set();
|
|
6
7
|
const storageKey='clado-library-view:v2:'+location.pathname;
|
|
7
8
|
const post = (type, extra = {}) => { if (parent !== window) parent.postMessage({ type: 'clado-prototype:' + type, board: 'library', ...extra }, location.origin); };
|
|
8
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 {}
|
|
9
10
|
const requestedFile = new URLSearchParams(location.search).get('file');
|
|
10
11
|
if (requestedFile || config.entry) selected = requestedFile || config.entry;
|
|
11
|
-
|
|
12
|
+
pendingAnchor = new URLSearchParams(location.search).get('anchor') || '';
|
|
12
13
|
function saveView() { try { sessionStorage.setItem(storageKey, JSON.stringify({ file: selected, mode })); } catch {} }
|
|
13
|
-
function
|
|
14
|
-
function
|
|
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(); }
|
|
15
24
|
function renderDirectory() {
|
|
16
25
|
const signature = JSON.stringify({ documents: index.documents, skipped: index.skipped, selected, query:$('#documentSearch').value, history: history.length });
|
|
17
26
|
if (signature === directorySignature) return;
|
|
@@ -19,23 +28,44 @@
|
|
|
19
28
|
$('#fileCount').textContent = index.documents.length;
|
|
20
29
|
document.querySelector('.directory-heading strong').textContent = index.root || 'Markdown';
|
|
21
30
|
CladoDocumentTree($('#documentList'),index.documents,{selected,query:$('#documentSearch').value,folders,onOpen:file=>{open(file);directory(false);}});
|
|
22
|
-
$('#skippedButton').hidden = !index.skipped.length; $('#skippedButton').textContent = index.skipped.length + '
|
|
23
|
-
$('#backButton').disabled = history.length === 0;
|
|
31
|
+
$('#skippedButton').hidden = !index.skipped.length; $('#skippedButton').textContent = index.skipped.length + ' 份文档未收录 · 查看原因';
|
|
32
|
+
$('#backButton').disabled = modalLocked() || history.length === 0;
|
|
24
33
|
}
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
34
|
+
let renderRequest = 0;
|
|
35
|
+
async function open(file, anchor = '', options = {}) {
|
|
36
|
+
if(modalLocked()) { if(options.update)deferredRefresh=true;return; }
|
|
37
|
+
pendingAnchor=anchor;
|
|
28
38
|
const doc = index.documents.find(d => d.file === file);
|
|
29
39
|
if (!doc) { details('这个 Markdown 暂未收录', '<p>' + esc(file) + ' 不在有效画布目录中。可以让 AI 检查文件是否存在、路径是否正确,以及能否通过解析。</p>'); return; }
|
|
30
40
|
if (selected && file !== selected && !options.back) history.push(selected);
|
|
31
41
|
if (options.update) { try { pendingView = frame.contentWindow.CladoPrototype?.captureView?.(); } catch {} }
|
|
32
42
|
else pendingView = null;
|
|
43
|
+
const request = ++renderRequest, previousVersion = version, requestedMode = mode;
|
|
33
44
|
selected = file; version = doc.version; saveView(); renderDirectory();
|
|
34
45
|
$('#currentTitle').textContent = doc.title; $('#currentPath').textContent = (index.root || '') + file;
|
|
35
46
|
$('#updateError').hidden = true; $('#emptyState').hidden = true; $('#canvasLoading').hidden = false;
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
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
|
+
}
|
|
39
69
|
}
|
|
40
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; }
|
|
41
71
|
async function scan(force = false) {
|
|
@@ -45,16 +75,21 @@
|
|
|
45
75
|
else { const response=await fetch('/library/index.json',{cache:'no-store'});if(!response.ok)throw new Error('scan');index=await response.json(); }
|
|
46
76
|
renderDirectory();
|
|
47
77
|
try{frame.contentWindow.postMessage({type:'clado-workspace:index',index},'*');}catch{}
|
|
48
|
-
if(
|
|
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
|
+
}
|
|
49
84
|
if (pendingOpen && index.documents.some(d=>d.file===pendingOpen)) { const file=pendingOpen;pendingOpen=null;open(file); }
|
|
50
85
|
if (selected && !version && !index.documents.some(d=>d.file===selected)) { selected='';saveView(); }
|
|
51
86
|
if (!selected && index.documents.length) open(index.documents[0].file);
|
|
52
|
-
else if (!selected) { $('#canvasLoading').hidden = true; $('#emptyState').hidden = false; $('#currentTitle').textContent = '等待
|
|
87
|
+
else if (!selected) { $('#canvasLoading').hidden = true; $('#emptyState').hidden = false; $('#currentTitle').textContent = '等待 MCP 创建文档'; status('目录已扫描'); post('ready'); }
|
|
53
88
|
else {
|
|
54
89
|
const doc = index.documents.find(d => d.file === selected);
|
|
55
90
|
if (!doc && !version && index.documents.length) open(index.documents[0].file);
|
|
56
91
|
else if (!doc) { $('#updateError').textContent = '当前 Markdown 已删除或暂时无法解析,保留上次画面。有效文档仍可从目录打开。'; $('#updateError').hidden = false; status('当前画布未更新', true); $('#canvasLoading').hidden = true; post('ready'); }
|
|
57
|
-
else { $('#updateError').hidden = true; if (force || doc.version !== version) {
|
|
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 })); }
|
|
58
93
|
}
|
|
59
94
|
} catch { status('连接中断,正在重连', true); $('#updateError').textContent = '目录连接中断,保留当前画面。服务恢复后自动重连。'; $('#updateError').hidden = false; $('#canvasLoading').hidden = true; post('ready'); }
|
|
60
95
|
finally { busy = false; }
|
|
@@ -62,12 +97,11 @@
|
|
|
62
97
|
addEventListener('message', event => {
|
|
63
98
|
if ((!offline && event.origin !== location.origin) || event.source !== frame.contentWindow) return;
|
|
64
99
|
const data = event.data;
|
|
65
|
-
if(data?.type === 'clado-library:
|
|
66
|
-
if(
|
|
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;
|
|
67
102
|
if (data?.type === 'clado-library:open') { directory(false); open(data.target, data.anchor); }
|
|
68
|
-
else if (data?.type === 'clado-library:changed') { editing=false;creating=false; if (data.file !== selected) pendingOpen=data.file; scan(true); }
|
|
69
103
|
else if (data?.type === 'clado-library:dismiss-directory') directory(false);
|
|
70
|
-
else if (data?.type === 'clado-library:missing') details('链接超出当前目录', '<p
|
|
104
|
+
else if (data?.type === 'clado-library:missing') details('链接超出当前目录', '<p>请选择当前工作区中的文档。链接:' + esc(data.target) + '</p>');
|
|
71
105
|
else if (data?.type === 'clado-library:mode') { mode = data.mode; saveView(); }
|
|
72
106
|
else if (data?.type === 'clado-library:theme') { design.theme = data.theme; setDesign(design); post('theme', { theme: data.theme }); }
|
|
73
107
|
else if (data?.type === 'clado-library:ready') {
|
|
@@ -81,14 +115,13 @@
|
|
|
81
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 {} }
|
|
82
116
|
window.CladoPrototype = { setDesign, fit: () => frame.contentWindow.CladoPrototype?.fit(), closeLens: () => frame.contentWindow.CladoPrototype?.closeLens() };
|
|
83
117
|
$('#documentSearch').oninput=renderDirectory;
|
|
84
|
-
$('#newDocument').onclick = () => { if(editing)return;creating=true;directory(false);$('#emptyState').hidden=true;$('#updateError').hidden=true;$('#canvasLoading').hidden=false;frame.removeAttribute('srcdoc');frame.src='/library/new'; };
|
|
85
118
|
$('#directoryButton').onclick = () => directory($('#directory').hidden);
|
|
86
119
|
document.addEventListener('pointerdown', event => { if (!event.target.closest('#directory, #directoryButton')) directory(false); });
|
|
87
120
|
document.addEventListener('keydown', event => { if (event.key === 'Escape' && !$('#directory').hidden) { directory(false); $('#directoryButton').focus(); } });
|
|
88
121
|
$('#refreshButton').onclick = () => scan(true);
|
|
89
|
-
$('#backButton').onclick = () => { if(
|
|
122
|
+
$('#backButton').onclick = () => { if(modalLocked())return;const previous = history.pop(); if (previous) open(previous, '', { back: true }); };
|
|
90
123
|
$('#closeDetails').onclick = () => $('#details').close();
|
|
91
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(''));
|
|
92
|
-
$('#sourceButton').onclick = async () => { try { const response = offline ? {ok:true,text:async()=>offline.sources[selected]} : await fetch('/library/source.
|
|
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>'); } };
|
|
93
126
|
directory(false); scan(); if(!offline)setInterval(() => scan(), 1200);
|
|
94
127
|
})();
|
|
@@ -21,6 +21,6 @@
|
|
|
21
21
|
}
|
|
22
22
|
}
|
|
23
23
|
render(root,container);
|
|
24
|
-
if(!container.childElementCount){const empty=document.createElement('p');empty.className='tree-empty';empty.textContent=needle?'没有匹配的文档':'
|
|
24
|
+
if(!container.childElementCount){const empty=document.createElement('p');empty.className='tree-empty';empty.textContent=needle?'没有匹配的文档':'还没有可展示的文档';container.append(empty);}
|
|
25
25
|
};
|
|
26
26
|
})();
|
package/src/server/export.js
CHANGED
|
@@ -37,7 +37,7 @@ export function renderWorkspace(jobs,{root,entry,mode='mindmap',theme='light',ti
|
|
|
37
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
38
|
html=html.slice(0,end)+script(boot)+script(read('library-canvas.js'))+html.slice(end);
|
|
39
39
|
// Store identical renderer/style blocks once, then hydrate each iframe locally.
|
|
40
|
-
html=html.replace(/<(script|style)
|
|
40
|
+
html=html.replace(/<(script|style)\b[^>]*>([\s\S]*?)<\/\1>/g,(block)=>{
|
|
41
41
|
if(block.length<4096)return block;
|
|
42
42
|
if(!assetIds.has(block)){assetIds.set(block,shared.length);shared.push(block);}
|
|
43
43
|
return '<!--CLADO-ASSET:'+assetIds.get(block)+'-->';
|
|
@@ -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
|
+
}
|
package/src/server/workspace.js
CHANGED
|
@@ -1,16 +1,18 @@
|
|
|
1
1
|
import { createServer } from 'node:http';
|
|
2
|
-
import { readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import { readFileSync, statSync, existsSync, mkdirSync } from 'node:fs';
|
|
3
3
|
import { dirname, resolve, basename, join, relative } from 'node:path';
|
|
4
4
|
import { fileURLToPath } from 'node:url';
|
|
5
|
-
import { randomBytes } from 'node:crypto';
|
|
6
5
|
import { renderHtml } from '../html/page.js';
|
|
7
|
-
import { scanDirectory, workspacePath, readDocument,
|
|
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';
|
|
8
10
|
const assets = join(dirname(fileURLToPath(import.meta.url)), 'assets');
|
|
9
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'};
|
|
10
12
|
const types = { html: 'text/html', css: 'text/css', js: 'text/javascript', json: 'application/json', md: 'text/markdown' };
|
|
11
13
|
export function createWorkspaceHandler(directory, options = {}) {
|
|
12
|
-
const root = resolve(directory)
|
|
13
|
-
const assetNames = new Set(['library.html','library.css','library.js','library-canvas.js','
|
|
14
|
+
const root = resolve(directory);
|
|
15
|
+
const assetNames = new Set(['library.html','library.css','library.js','library-canvas.js','tree.js']);
|
|
14
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); };
|
|
15
17
|
const json = (res, status, data) => send(res, status, types.json, JSON.stringify(data));
|
|
16
18
|
const safeJson = data => JSON.stringify(data).replace(/</g,'\\u003c');
|
|
@@ -21,21 +23,6 @@ export function createWorkspaceHandler(directory, options = {}) {
|
|
|
21
23
|
const host = req.headers.host;
|
|
22
24
|
if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host || '')) throw new DocumentError('只接受本机预览请求。',403);
|
|
23
25
|
if (req.headers.origin && req.headers.origin !== 'http://' + host) throw new DocumentError('来源不匹配。',403);
|
|
24
|
-
if (req.method === 'POST') {
|
|
25
|
-
if (req.headers['x-clado-token'] !== token) throw new DocumentError('编辑凭证不匹配,请刷新页面。',403);
|
|
26
|
-
if (!String(req.headers['content-type']).startsWith('application/json')) throw new DocumentError('只接受 JSON 请求。',415);
|
|
27
|
-
let body = ''; for await (const chunk of req) { body += chunk; if (Buffer.byteLength(body) > 2_000_000) throw new DocumentError('内容超过 2 MB。',413); }
|
|
28
|
-
const data = JSON.parse(body);
|
|
29
|
-
if (!data || Array.isArray(data) || typeof data !== 'object') throw new DocumentError('需要 JSON 对象。');
|
|
30
|
-
if (url.pathname === '/library/document' && !['create','update'].includes(data.action || 'update')) throw new DocumentError('文档操作只能是 create / update。');
|
|
31
|
-
const file = workspacePath(root, data.file, data.action === 'create');
|
|
32
|
-
if (data.action !== 'create' && !data.version) throw new DocumentError('保存前需要读取最新版本。',409);
|
|
33
|
-
let result;
|
|
34
|
-
if (url.pathname === '/library/document') result = writeDocument(file, data.source, { create: data.action === 'create', version: data.version });
|
|
35
|
-
else if (url.pathname === '/library/node') result = mutateNode(file, data.action, data);
|
|
36
|
-
else throw new DocumentError('没有这个编辑入口。',404);
|
|
37
|
-
json(res,200,{file:data.file,version:result.version,diagnostics:result.diagnostics}); return true;
|
|
38
|
-
}
|
|
39
26
|
if (req.method !== 'GET' && req.method !== 'HEAD') throw new DocumentError('不支持这个请求方法。',405);
|
|
40
27
|
if (assetNames.has(route) || (options.entrypoint && route === '')) {
|
|
41
28
|
const name = route || 'library.html'; let body = readFileSync(join(assets,name),'utf8');
|
|
@@ -55,41 +42,43 @@ export function createWorkspaceHandler(directory, options = {}) {
|
|
|
55
42
|
const path=workspacePath(root,name,false,true);
|
|
56
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;
|
|
57
44
|
}
|
|
58
|
-
|
|
59
|
-
const file =
|
|
60
|
-
|
|
61
|
-
if (
|
|
62
|
-
|
|
63
|
-
json(res,200,{source:item.source,version:item.version,sections:item.sections,diagnostics:item.diagnostics}); return true;
|
|
64
|
-
}
|
|
65
|
-
if (url.pathname !== '/library/canvas' && !creating) throw new DocumentError('没有这个预览入口。',404);
|
|
66
|
-
if (item.diagnostics.some(d=>d.severity==='error')) throw new DocumentError('Markdown 暂时无法解析。',422,item.diagnostics);
|
|
67
|
-
const mode = creating ? 'doc' : ['doc','cards','mindmap'].includes(url.searchParams.get('mode')) ? url.searchParams.get('mode') : options.mode || 'mindmap';
|
|
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';
|
|
68
50
|
let html = (options.render || renderHtml)(item.doc,item.diagnostics,{file:name,title:item.doc.title,mode,theme:options.theme || 'light',library:true});
|
|
69
|
-
html = html.replace('</head>','<link rel="stylesheet" href="/editor.css"></head>');
|
|
70
51
|
const bodyEnd = html.lastIndexOf('</body>');
|
|
71
|
-
html = html.slice(0,bodyEnd) + '<script>window.
|
|
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);
|
|
72
53
|
send(res,200,types.html,html); return true;
|
|
73
54
|
} catch (error) {
|
|
74
55
|
json(res,error.status || (error instanceof SyntaxError ? 400 : 500),{error:error.message,diagnostics:error.diagnostics || []}); return true;
|
|
75
56
|
}
|
|
76
57
|
};
|
|
77
58
|
}
|
|
78
|
-
export async function startWorkspace(input, { port = 4317, mode = 'mindmap', theme = 'light', entry } = {}) {
|
|
59
|
+
export async function startWorkspace(input, { port = 4317, mode = 'mindmap', theme = 'light', entry, project = false } = {}) {
|
|
79
60
|
const path = resolve(input);
|
|
80
|
-
if (
|
|
81
|
-
|
|
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);
|
|
82
69
|
const entryFile = entry ? relative(root,workspacePath(root,entry)).split('\\').join('/') : (statSync(path).isFile() ? basename(path) : '');
|
|
83
70
|
if (entryFile) {
|
|
84
71
|
const item=readDocument(workspacePath(root,entryFile));
|
|
85
72
|
if(item.diagnostics.some(d=>d.severity==='error'))throw new DocumentError('入口 Markdown 无法解析。',422,item.diagnostics);
|
|
86
73
|
}
|
|
87
74
|
const handle = createWorkspaceHandler(root,{entrypoint:true,mode,theme,entry:entryFile});
|
|
75
|
+
const mcp = createMcpHandler(createWorkspaceService(workspace, { documentRoot: root }));
|
|
88
76
|
const server = createServer(async (req,res) => {
|
|
89
|
-
try {
|
|
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'); } }
|
|
90
78
|
catch { if (!res.headersSent) res.writeHead(500);res.end('预览请求失败'); }
|
|
91
79
|
});
|
|
92
80
|
await new Promise((resolve,reject) => { server.once('error',reject); server.listen(port,'127.0.0.1',resolve); });
|
|
93
81
|
const file = entryFile ? '?file='+encodeURIComponent(entryFile) : '';
|
|
94
|
-
|
|
82
|
+
const origin = 'http://127.0.0.1:'+server.address().port;
|
|
83
|
+
return {server,url:origin+'/'+file,mcpUrl:origin+'/mcp',workspace,root};
|
|
95
84
|
}
|
package/src/skill/install.js
CHANGED
|
@@ -6,18 +6,16 @@
|
|
|
6
6
|
* ② 让用户勾
|
|
7
7
|
* ③ 装。已经装过的**先整个删掉再拷**,所以升级之后不会留上一个版本的文件。
|
|
8
8
|
*
|
|
9
|
-
*
|
|
10
|
-
* (`references/diagnostics.md` 改过、例子改过名)。只覆盖同名文件的话,上个版本
|
|
11
|
-
* 多出来的那些会永远留在用户项目里,而且没有任何提示 —— 用户看到的是一份两个版本
|
|
12
|
-
* 混在一起的 skill。整个目录换掉是唯一能保证「装上之后 = 这个版本」的做法。
|
|
9
|
+
* 重装清理受管理目录的旧附件,再写入唯一的 SKILL.md,避免遗留其它版本的资料。
|
|
13
10
|
*/
|
|
14
11
|
|
|
15
|
-
import { existsSync, statSync, readFileSync, writeFileSync, mkdirSync, rmSync,
|
|
16
|
-
import { resolve, join, dirname,
|
|
12
|
+
import { existsSync, statSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
|
|
13
|
+
import { resolve, join, dirname, relative, sep } from 'node:path';
|
|
17
14
|
import { fileURLToPath } from 'node:url';
|
|
18
15
|
|
|
19
16
|
import { c } from '../util/term.js';
|
|
20
17
|
import { TARGETS, SKILL_NAME, BUNDLE_REL, MARK_BEGIN, MARK_END, findTarget, ruleBody } from './targets.js';
|
|
18
|
+
import { installUserTemplates } from './templates.js';
|
|
21
19
|
|
|
22
20
|
const HERE = dirname(fileURLToPath(import.meta.url));
|
|
23
21
|
const PKG_ROOT = resolve(HERE, '..', '..');
|
|
@@ -29,10 +27,7 @@ export class UsageError extends Error {}
|
|
|
29
27
|
// ---------------------------------------------------------------- 文件小工具
|
|
30
28
|
|
|
31
29
|
/**
|
|
32
|
-
*
|
|
33
|
-
* ★ `out` 是 `examples/build.sh` 编出来的产物(三模式 36 个页面、50 多 MB),
|
|
34
|
-
* `.gitignore` 里是有的,但 `cpSync` 不读 `.gitignore` —— 跟着 bundle 一起搬过去
|
|
35
|
-
* 会把用户的项目撑爆。
|
|
30
|
+
* 统计旧安装时忽略构建产物、依赖及本机元数据。
|
|
36
31
|
*/
|
|
37
32
|
const SKIP = new Set(['out', 'node_modules', '.git', '.DS_Store']);
|
|
38
33
|
|
|
@@ -213,15 +208,18 @@ export function pick(entries) {
|
|
|
213
208
|
export function installTo(cwd, ids, opts = {}) {
|
|
214
209
|
const { dryRun = false, force = false } = opts;
|
|
215
210
|
|
|
216
|
-
// `--to all` =
|
|
211
|
+
// `--to all` = 全都装,不必逐个填写 id。
|
|
217
212
|
if (ids.includes('all')) ids = TARGETS.map((t) => t.id);
|
|
218
213
|
|
|
219
214
|
for (const id of ids) if (!findTarget(id)) throw new UsageError(`不认识这个工具:"${id}"`);
|
|
220
215
|
|
|
221
|
-
|
|
222
|
-
|
|
216
|
+
const entry = join(BUNDLE, 'SKILL.md');
|
|
217
|
+
if (!existsSync(entry)) {
|
|
218
|
+
throw new UsageError(`包里找不到 Skill 入口:${entry}`);
|
|
223
219
|
}
|
|
224
|
-
|
|
220
|
+
// 安装清单固定为一个入口,旧包即使仍有 references/examples 也不会整包复制。
|
|
221
|
+
const skillSource = readFileSync(entry, 'utf8');
|
|
222
|
+
const files = ['SKILL.md'];
|
|
225
223
|
|
|
226
224
|
// 规则型的正文要指向一份真实存在的 SKILL.md。
|
|
227
225
|
// 优先指本次已经装好的目录型目标(省一份重复的拷贝),一个都没选才落到 `.clado/`。
|
|
@@ -257,9 +255,8 @@ export function installTo(cwd, ids, opts = {}) {
|
|
|
257
255
|
}
|
|
258
256
|
if (!dryRun) {
|
|
259
257
|
rmSync(destAbs, { recursive: true, force: true });
|
|
260
|
-
mkdirSync(
|
|
261
|
-
|
|
262
|
-
cpSync(BUNDLE, destAbs, { recursive: true, filter: (src) => !SKIP.has(basename(src)) });
|
|
258
|
+
mkdirSync(destAbs, { recursive: true });
|
|
259
|
+
writeFileSync(join(destAbs, 'SKILL.md'), skillSource);
|
|
263
260
|
}
|
|
264
261
|
results.push({
|
|
265
262
|
id: t.id,
|
|
@@ -303,7 +300,8 @@ export function installTo(cwd, ids, opts = {}) {
|
|
|
303
300
|
});
|
|
304
301
|
}
|
|
305
302
|
|
|
306
|
-
|
|
303
|
+
const userTemplates = installUserTemplates({ dryRun });
|
|
304
|
+
return { results, files: files.length, anchor, dryRun, userTemplates };
|
|
307
305
|
}
|
|
308
306
|
|
|
309
307
|
/**
|
package/src/skill/targets.js
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
* 所以新增一条之前先去翻文档,把链接填进 `doc`。
|
|
7
7
|
*
|
|
8
8
|
* 三种落点:
|
|
9
|
-
* dir 自家的 skills
|
|
9
|
+
* dir 自家的 skills 目录,仅安装 `<dest>/SKILL.md`
|
|
10
10
|
* own 自家独占的规则文件,直接覆写
|
|
11
11
|
* append 和别人共用的规则文件(AGENTS.md 之类),往里写一段**带标记**的内容,
|
|
12
12
|
* 重装时替换那一段而不是再追加一段
|
|
@@ -62,6 +62,14 @@ export const TARGETS = [
|
|
|
62
62
|
marker: '.lingma',
|
|
63
63
|
doc: 'https://docs.qoder.cn/user-guide/skills',
|
|
64
64
|
},
|
|
65
|
+
{
|
|
66
|
+
id: 'zcode',
|
|
67
|
+
name: 'ZCode(智谱)',
|
|
68
|
+
kind: 'dir',
|
|
69
|
+
dest: '.zcode/skills/clado',
|
|
70
|
+
marker: '.zcode',
|
|
71
|
+
doc: 'https://www.zcode.network/cn/docs/qa/',
|
|
72
|
+
},
|
|
65
73
|
{
|
|
66
74
|
id: 'root',
|
|
67
75
|
name: `项目根目录(丢一个 ${SKILL_NAME}/ 让 AI 自己去搬)`,
|
|
@@ -142,8 +150,7 @@ export function findTarget(id) {
|
|
|
142
150
|
/**
|
|
143
151
|
* 规则文件里的正文。
|
|
144
152
|
*
|
|
145
|
-
*
|
|
146
|
-
* 上下文都撑爆,而且升级之后两边就对不上了。指过去,让工具按需去读。
|
|
153
|
+
* 规则文件只保留指针,详细操作统一放在 SKILL.md。
|
|
147
154
|
*
|
|
148
155
|
* @param {string} skillPath bundle 在本项目里的相对路径(正斜杠)
|
|
149
156
|
*/
|
|
@@ -156,22 +163,22 @@ export function ruleBody(skillPath) {
|
|
|
156
163
|
|
|
157
164
|
${skillPath}/SKILL.md
|
|
158
165
|
|
|
159
|
-
|
|
166
|
+
指南列出常用命令与 MCP 工具;具体场景通过 clado_templates read 读取模板 prompt。用户模板在 ~/.clado/templates/,项目副本在 .clado/templates/,文档在 .clado/doc/。
|
|
160
167
|
|
|
161
168
|
先确认 CLI 版本与能力:
|
|
162
169
|
|
|
163
170
|
clado version
|
|
164
171
|
clado help
|
|
165
172
|
|
|
166
|
-
|
|
173
|
+
使用源码时先 npm install,再用 node /Clado源码路径/bin/clado.js serve。
|
|
167
174
|
|
|
168
175
|
从项目根开始:
|
|
169
176
|
|
|
170
|
-
clado
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
177
|
+
clado serve
|
|
178
|
+
|
|
179
|
+
连接输出的 Streamable HTTP MCP。每次调用提供输出的 workspace,先 clado_workspace inspect,再 clado_templates read 提示词,用 clado_documents create 按模板初始化 .mdc;节点、链接与批量操作也用MCP。正文直接传多行字符串,项目写入带 expectedWorkspaceVersion。模板可在项目 create/update,用 pull 从用户库复制,用 push 同步到用户库;push 同时带 expectedUserTemplateVersion。
|
|
180
|
+
|
|
181
|
+
网页只展示脑图/卡片/文档,保存后自动更新。交付可用 clado build --entry overview.mdc --mode cards;默认生成只读 clado.html。工具不执行文档里的SQL、脚本或发布任务。
|
|
174
182
|
|
|
175
|
-
init 保留已有文件;先读后改。build 默认生成 clado.html,离线只读;网页编辑位于 serve 的文档视图左上角阅读/编辑切换中。工具不执行文档内的 SQL、脚本或上线步骤。
|
|
176
183
|
`;
|
|
177
184
|
}
|