cladogram 0.6.0-beta.4 → 0.6.0-beta.6

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.
@@ -178,10 +178,10 @@
178
178
  saveView();
179
179
  syncChrome();
180
180
  frame.contentWindow.CladoPrototype?.setMode?.(next);
181
+ armPresenceAfterglowForFile(selected);
181
182
  },
182
183
  clearFocus: () => frame.contentWindow.CladoRuntime?.clearFocus(),
183
184
  showDiagnostics: () => frame.contentWindow.CladoCanvasControls?.showDiagnostics(),
184
- openHandoff: !offline && config.agent ? () => window.CladoVNext?.openHandoff?.() : null,
185
185
  });
186
186
  const directory = window.CladoDirectoryPlugin(host, {
187
187
  showFilename: settings['clado.directory']?.showFilename !== false,
@@ -574,6 +574,9 @@
574
574
  renderLobbyView(cachedHubData || {});
575
575
  }
576
576
 
577
+ let discoveredWorkspaces = [];
578
+ let emptyWorkspaceSignature = '';
579
+
577
580
  function renderEmptyOnboarding(profile = {}) {
578
581
  const emptyEl = $('#emptyState');
579
582
  if (!emptyEl) return;
@@ -627,6 +630,10 @@
627
630
  showToast('主架构师正在分析源码并绘制画布…');
628
631
  window.CladoVNext?.startCodeAnalysis?.(selectedTpl);
629
632
  };
633
+ if (discoveredWorkspaces.length) {
634
+ emptyWorkspaceSignature = '';
635
+ renderEmptyWorkspaces(discoveredWorkspaces);
636
+ }
630
637
  }
631
638
 
632
639
  if (config.canSwitchWorkspace && !offline) {
@@ -992,14 +999,10 @@
992
999
  selectionBarEl.innerHTML = `
993
1000
  <span class="clado-selection-dot"></span>
994
1001
  <span class="clado-selection-text" data-sel-summary>已选 0 项</span>
995
- <button type="button" class="clado-selection-send" data-sel-dev>交给开发落地</button>
996
- <button type="button" class="clado-selection-secondary" data-sel-qa>生成并跑测试</button>
1002
+ <button type="button" class="clado-selection-send" data-sel-send>发给当前会话</button>
997
1003
  <button type="button" class="clado-selection-clear" data-sel-clear>完成</button>`;
998
- selectionBarEl.querySelector('[data-sel-dev]').onclick = () => {
999
- window.CladoVNext?.triggerHandoff?.('developer');
1000
- };
1001
- selectionBarEl.querySelector('[data-sel-qa]').onclick = () => {
1002
- window.CladoVNext?.triggerHandoff?.('tester');
1004
+ selectionBarEl.querySelector('[data-sel-send]').onclick = () => {
1005
+ window.CladoVNext?.focusComposer?.();
1003
1006
  };
1004
1007
  selectionBarEl.querySelector('[data-sel-clear]').onclick = () => {
1005
1008
  objectSelection.clear();
@@ -1492,35 +1495,64 @@
1492
1495
  if(!chainModal) { const force=deferredRefresh;deferredRefresh=false;scan(force); }
1493
1496
  }
1494
1497
  function renderDirectory() { directory.update(index, selected, history.length > 0); }
1495
- let emptyWorkspaceSignature = '';
1496
1498
  function renderEmptyWorkspaces(list) {
1497
- const others = list.filter(item => item.id !== workspaceId);
1499
+ discoveredWorkspaces = Array.isArray(list) ? list : [];
1500
+ const others = discoveredWorkspaces.filter(item => item.id !== workspaceId);
1498
1501
  const next = JSON.stringify(others.map(item => [item.id, item.name, item.documents]));
1499
- if (next === emptyWorkspaceSignature) return;
1502
+ if (next === emptyWorkspaceSignature && $('#emptyState .empty-workspaces')) return;
1500
1503
  emptyWorkspaceSignature = next;
1501
1504
  let container = $('#emptyState .empty-workspaces');
1502
1505
  if (!others.length) { container?.remove(); return; }
1506
+ const hostEl = $('#emptyState .clado-empty-card') || $('#emptyState .clado-launchpad-card') || $('#emptyState');
1503
1507
  if (!container) {
1504
1508
  container = document.createElement('div');
1505
1509
  container.className = 'empty-workspaces';
1506
- ($('#emptyState .clado-launchpad-card') || $('#emptyState')).append(container);
1510
+ hostEl.append(container);
1511
+ } else if (container.parentElement !== hostEl) {
1512
+ hostEl.append(container);
1507
1513
  }
1508
1514
  container.replaceChildren();
1515
+ const head = document.createElement('div');
1516
+ head.className = 'empty-workspaces-head';
1509
1517
  const title = document.createElement('div');
1510
1518
  title.className = 'empty-workspaces-title';
1511
- title.textContent = '已发现的子工作区(点击打开)';
1512
- container.append(title);
1519
+ title.textContent = '已发现的子工作区';
1520
+ const badge = document.createElement('span');
1521
+ badge.className = 'empty-workspaces-count';
1522
+ badge.textContent = `${others.length} 个工作区`;
1523
+ head.append(title, badge);
1524
+ container.append(head);
1525
+
1526
+ const grid = document.createElement('div');
1527
+ grid.className = 'empty-workspaces-grid';
1513
1528
  for (const item of others) {
1514
1529
  const link = document.createElement('a');
1515
1530
  link.className = 'empty-workspace-card';
1516
1531
  link.href = workspaceUrl(item.id);
1532
+ const label = item.id || (item.name + '(根目录)');
1533
+ link.title = label;
1534
+
1535
+ const ico = document.createElement('span');
1536
+ ico.className = 'empty-workspace-ico';
1537
+ ico.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>';
1538
+
1539
+ const meta = document.createElement('span');
1540
+ meta.className = 'empty-workspace-meta';
1517
1541
  const name = document.createElement('span');
1518
- name.textContent = item.id || (item.name + '(根目录)');
1542
+ name.className = 'empty-workspace-name';
1543
+ name.textContent = label;
1519
1544
  const count = document.createElement('small');
1520
1545
  count.textContent = (item.documents ?? 0) + ' 份画布';
1521
- link.append(name, count);
1522
- container.append(link);
1546
+ meta.append(name, count);
1547
+
1548
+ const arrow = document.createElement('span');
1549
+ arrow.className = 'empty-workspace-arrow';
1550
+ arrow.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 18l6-6-6-6"/></svg>';
1551
+
1552
+ link.append(ico, meta, arrow);
1553
+ grid.append(link);
1523
1554
  }
1555
+ container.append(grid);
1524
1556
  }
1525
1557
  let renderRequest = 0;
1526
1558
  async function openFromCapability(file) {
@@ -1812,6 +1844,10 @@
1812
1844
  if (data.codePath) openCodeDrawerFile(data.codePath);
1813
1845
  return;
1814
1846
  }
1847
+ if (data?.type === 'clado-library:canvas-interacted') {
1848
+ armPresenceAfterglowForFile(selected);
1849
+ return;
1850
+ }
1815
1851
  if (data?.type === 'clado-library:chain-modal') { chainLock(data.value, data.mode); return; }
1816
1852
  if (data?.type === 'clado-library:lens-modal') {
1817
1853
  lensOpen = !!data.value;
@@ -1845,6 +1881,7 @@
1845
1881
  showSelection();
1846
1882
  syncFrameObjects();
1847
1883
  syncPresenceConfigToCanvas();
1884
+ syncPresenceSnapshotToCanvas();
1848
1885
  if(offline){frame.contentWindow.postMessage({type:'clado-workspace:display',mode,theme:design.theme,anchor:pendingAnchor},'*');pendingAnchor='';}
1849
1886
  else if (mode !== data.mode) frame.contentWindow.CladoPrototype?.setMode?.(mode);
1850
1887
  saveView(); $('#canvasLoading').hidden = true; syncChrome();
@@ -1861,6 +1898,29 @@
1861
1898
  status('已同步 ' + new Date(index.documents.find(d => d.file === selected)?.modified || Date.now()).toLocaleTimeString('zh-CN', { hour12: false })); post('ready');
1862
1899
  }
1863
1900
  });
1901
+
1902
+ const PRESENCE_HARD_MAX_MS = 30 * 60 * 1000;
1903
+ const presenceByFile = new Map(); // file -> Map<cardKey, Map<sessionId, entry>>
1904
+ let presenceSweepTimer = 0;
1905
+
1906
+ function toAfterglowPresenceLabel(activeLabel, fallback) {
1907
+ const raw = String(activeLabel || '').trim();
1908
+ if (!raw) return fallback || '刚刚编辑了';
1909
+ if (raw.startsWith('刚刚')) return raw;
1910
+ if (/^正在(?:新建|创建)/.test(raw)) return '刚刚新建了';
1911
+ if (/^正在删除/.test(raw)) return '刚刚删除了';
1912
+ if (/^正在移除连线/.test(raw)) return '刚刚移除了连线';
1913
+ if (/^正在连线/.test(raw)) return '刚刚连线了';
1914
+ if (/^正在调整/.test(raw)) return '刚刚调整了';
1915
+ if (/^正在修改\s+(.+)$/.test(raw)) return raw.replace(/^正在修改\s+/, '刚刚修改了 ');
1916
+ if (/^正在查看\s+(.+)$/.test(raw)) return raw.replace(/^正在查看\s+/, '刚刚查看了 ');
1917
+ if (/^正在查看/.test(raw)) return '刚刚查看了';
1918
+ if (/^正在编辑/.test(raw)) return '刚刚编辑了';
1919
+ if (/^修改\s+(.+)$/.test(raw)) return raw.replace(/^修改\s+/, '刚刚修改了 ');
1920
+ if (/^查看\s+(.+)$/.test(raw)) return raw.replace(/^查看\s+/, '刚刚查看了 ');
1921
+ return fallback || '刚刚编辑了';
1922
+ }
1923
+
1864
1924
  function readPresenceAfterglowMs() {
1865
1925
  try {
1866
1926
  const raw = localStorage.getItem('clado-presence-ttl');
@@ -1869,23 +1929,223 @@
1869
1929
  if (Number.isFinite(sec) && sec >= 0) return Math.round(sec * 1000);
1870
1930
  }
1871
1931
  } catch {}
1872
- return 15000;
1932
+ return 30000;
1933
+ }
1934
+
1935
+ function collectPresenceEntriesForFile(file) {
1936
+ if (!file) return [];
1937
+ const fileMap = presenceByFile.get(file);
1938
+ if (!fileMap) return [];
1939
+ const out = [];
1940
+ for (const cardMap of fileMap.values()) {
1941
+ for (const entry of cardMap.values()) out.push({ ...entry });
1942
+ }
1943
+ return out;
1944
+ }
1945
+
1946
+ function syncPresenceSnapshotToCanvas() {
1947
+ if (readyCanvas?.frame !== frame || !selected) return;
1948
+ try {
1949
+ frame.contentWindow.postMessage({
1950
+ type: 'clado-workspace:presence-sync',
1951
+ entries: collectPresenceEntriesForFile(selected),
1952
+ }, offline ? '*' : location.origin);
1953
+ } catch {}
1954
+ }
1955
+
1956
+ function ensurePresenceSweepTimer() {
1957
+ if (presenceByFile.size > 0 && !presenceSweepTimer) {
1958
+ presenceSweepTimer = setInterval(sweepPresenceRegistry, 1000);
1959
+ } else if (presenceByFile.size === 0 && presenceSweepTimer) {
1960
+ clearInterval(presenceSweepTimer);
1961
+ presenceSweepTimer = 0;
1962
+ }
1873
1963
  }
1964
+
1965
+ function sweepPresenceRegistry() {
1966
+ const now = Date.now();
1967
+ let selectedChanged = false;
1968
+ for (const [file, fileMap] of presenceByFile.entries()) {
1969
+ for (const [cardKey, cardMap] of fileMap.entries()) {
1970
+ for (const [sid, entry] of cardMap.entries()) {
1971
+ const hardCap = entry.hardExpiresAt || (entry.ts + PRESENCE_HARD_MAX_MS);
1972
+ const exp = entry.expiresAt || hardCap;
1973
+ if (now >= hardCap || (entry.phase === 'afterglow' && entry.armedAt && now >= exp)) {
1974
+ cardMap.delete(sid);
1975
+ if (file === selected) selectedChanged = true;
1976
+ }
1977
+ }
1978
+ if (!cardMap.size) fileMap.delete(cardKey);
1979
+ }
1980
+ if (!fileMap.size) presenceByFile.delete(file);
1981
+ }
1982
+ ensurePresenceSweepTimer();
1983
+ if (selectedChanged) syncPresenceSnapshotToCanvas();
1984
+ }
1985
+
1986
+ function armPresenceAfterglowForFile(file) {
1987
+ if (!file) return;
1988
+ const fileMap = presenceByFile.get(file);
1989
+ if (!fileMap) return;
1990
+ const now = Date.now();
1991
+ const afterglowMs = readPresenceAfterglowMs();
1992
+ let changed = false;
1993
+ for (const [cardKey, cardMap] of fileMap.entries()) {
1994
+ for (const [sid, entry] of cardMap.entries()) {
1995
+ if (entry.phase !== 'afterglow' || entry.armedAt) continue;
1996
+ if (afterglowMs <= 0) {
1997
+ cardMap.delete(sid);
1998
+ } else {
1999
+ entry.armedAt = now;
2000
+ const hardCap = entry.hardExpiresAt || (now + PRESENCE_HARD_MAX_MS);
2001
+ entry.expiresAt = Math.min(hardCap, now + afterglowMs);
2002
+ }
2003
+ changed = true;
2004
+ }
2005
+ if (!cardMap.size) fileMap.delete(cardKey);
2006
+ }
2007
+ if (!fileMap.size) presenceByFile.delete(file);
2008
+ ensurePresenceSweepTimer();
2009
+ if (changed && file === selected) syncPresenceSnapshotToCanvas();
2010
+ }
2011
+
2012
+ function applyPresenceEventToRegistry(payload) {
2013
+ if (!payload || typeof payload !== 'object') return;
2014
+ const sid = String(payload.sessionId || payload.roleId || 'agent');
2015
+ const phase = payload.phase || 'active';
2016
+ const now = Date.now();
2017
+ const afterglowMs = readPresenceAfterglowMs();
2018
+
2019
+ if (phase === 'clear') {
2020
+ const targetFile = String(payload.file || '').trim();
2021
+ const rawCards = (Array.isArray(payload.cards) ? payload.cards : [])
2022
+ .map(c => (Array.isArray(c) ? String(c[0] || '').trim() : String(c || '').trim()))
2023
+ .filter(Boolean);
2024
+ const files = targetFile ? [targetFile] : Array.from(presenceByFile.keys());
2025
+ for (const f of files) {
2026
+ const fileMap = presenceByFile.get(f);
2027
+ if (!fileMap) continue;
2028
+ const keys = rawCards.length ? rawCards : Array.from(fileMap.keys());
2029
+ for (const k of keys) {
2030
+ const cardMap = fileMap.get(k);
2031
+ if (!cardMap) continue;
2032
+ cardMap.delete(sid);
2033
+ if (!cardMap.size) fileMap.delete(k);
2034
+ }
2035
+ if (!fileMap.size) presenceByFile.delete(f);
2036
+ }
2037
+ ensurePresenceSweepTimer();
2038
+ syncPresenceSnapshotToCanvas();
2039
+ return;
2040
+ }
2041
+
2042
+ if (phase === 'afterglow') {
2043
+ // Transition ALL active entries of this session across ALL files into '刚刚编辑了' (unarmed until user interacts with that specific canvas)
2044
+ for (const [f, fileMap] of presenceByFile.entries()) {
2045
+ for (const [k, cardMap] of fileMap.entries()) {
2046
+ const existing = cardMap.get(sid);
2047
+ if (!existing || existing.phase !== 'active') continue;
2048
+ if (afterglowMs <= 0) {
2049
+ cardMap.delete(sid);
2050
+ } else {
2051
+ existing.phase = 'afterglow';
2052
+ existing.label = toAfterglowPresenceLabel(existing.label, payload.label || '刚刚编辑了');
2053
+ existing.ts = now;
2054
+ existing.armedAt = 0;
2055
+ existing.hardExpiresAt = now + PRESENCE_HARD_MAX_MS;
2056
+ existing.expiresAt = existing.hardExpiresAt;
2057
+ }
2058
+ if (!cardMap.size) fileMap.delete(k);
2059
+ }
2060
+ if (!fileMap.size) presenceByFile.delete(f);
2061
+ }
2062
+ ensurePresenceSweepTimer();
2063
+ syncPresenceSnapshotToCanvas();
2064
+ return;
2065
+ }
2066
+
2067
+ // phase === 'active': accumulate all cards touched in this turn on targetFile
2068
+ const targetFile = String(payload.file || selected || '').trim();
2069
+ const rawCards = (Array.isArray(payload.cards) ? payload.cards : [])
2070
+ .map(c => (Array.isArray(c) ? String(c[0] || '').trim() : String(c || '').trim()))
2071
+ .filter(Boolean);
2072
+ if (!targetFile || !rawCards.length) return;
2073
+
2074
+ // Refresh 30m hard cap on other still-active entries of this session
2075
+ for (const fileMap of presenceByFile.values()) {
2076
+ for (const cardMap of fileMap.values()) {
2077
+ const existing = cardMap.get(sid);
2078
+ if (existing && existing.phase === 'active') {
2079
+ existing.hardExpiresAt = now + PRESENCE_HARD_MAX_MS;
2080
+ existing.expiresAt = existing.hardExpiresAt;
2081
+ }
2082
+ }
2083
+ }
2084
+
2085
+ let fileMap = presenceByFile.get(targetFile);
2086
+ if (!fileMap) {
2087
+ fileMap = new Map();
2088
+ presenceByFile.set(targetFile, fileMap);
2089
+ }
2090
+ for (const cardKey of rawCards) {
2091
+ let cardMap = fileMap.get(cardKey);
2092
+ if (!cardMap) {
2093
+ cardMap = new Map();
2094
+ fileMap.set(cardKey, cardMap);
2095
+ }
2096
+ cardMap.set(sid, {
2097
+ file: targetFile,
2098
+ cardKey,
2099
+ sessionId: sid,
2100
+ roleId: String(payload.roleId || ''),
2101
+ roleName: String(payload.roleName || 'AI 角色'),
2102
+ tone: String(payload.tone || 'sky'),
2103
+ label: String(payload.label || '正在编辑'),
2104
+ codePath: String(payload.codePath || ''),
2105
+ phase: 'active',
2106
+ ts: now,
2107
+ armedAt: 0,
2108
+ hardExpiresAt: now + PRESENCE_HARD_MAX_MS,
2109
+ expiresAt: now + PRESENCE_HARD_MAX_MS,
2110
+ });
2111
+ }
2112
+ ensurePresenceSweepTimer();
2113
+ if (targetFile === selected) syncPresenceSnapshotToCanvas();
2114
+ }
2115
+
1874
2116
  function syncPresenceConfigToCanvas(overrideMs) {
1875
- if (readyCanvas?.frame !== frame) return;
1876
2117
  const afterglowMs = typeof overrideMs === 'number' && Number.isFinite(overrideMs) ? overrideMs : readPresenceAfterglowMs();
2118
+ const now = Date.now();
2119
+ for (const [f, fileMap] of presenceByFile.entries()) {
2120
+ for (const [k, cardMap] of fileMap.entries()) {
2121
+ for (const [sid, entry] of cardMap.entries()) {
2122
+ if (entry.phase !== 'afterglow') continue;
2123
+ if (afterglowMs <= 0) {
2124
+ cardMap.delete(sid);
2125
+ } else if (entry.armedAt) {
2126
+ const hardCap = entry.hardExpiresAt || (now + PRESENCE_HARD_MAX_MS);
2127
+ entry.expiresAt = Math.min(hardCap, entry.armedAt + afterglowMs);
2128
+ }
2129
+ }
2130
+ if (!cardMap.size) fileMap.delete(k);
2131
+ }
2132
+ if (!fileMap.size) presenceByFile.delete(f);
2133
+ }
2134
+ ensurePresenceSweepTimer();
2135
+ if (readyCanvas?.frame !== frame) return;
1877
2136
  try {
1878
2137
  frame.contentWindow.postMessage({
1879
2138
  type: 'clado-workspace:presence-config',
1880
2139
  config: { afterglowMs },
1881
2140
  }, offline ? '*' : location.origin);
1882
2141
  } catch {}
2142
+ syncPresenceSnapshotToCanvas();
1883
2143
  }
1884
2144
  addEventListener('clado:presence-config', ev => {
1885
2145
  syncPresenceConfigToCanvas(ev.detail?.afterglowMs);
1886
2146
  });
1887
2147
  function setDesign(next) { design = { ...design, ...next }; document.documentElement.dataset.theme = design.theme || 'light'; if (design.accent) document.documentElement.style.setProperty('--accent', design.accent); try { frame.contentWindow.CladoPrototype?.setDesign(design); } catch {} syncChrome(); }
1888
- window.CladoPrototype = { setDesign, fit: () => frame.contentWindow.CladoPrototype?.fit(), closeLens: () => frame.contentWindow.CladoPrototype?.closeLens() };
2148
+ window.CladoPrototype = { setDesign, fit: () => { armPresenceAfterglowForFile(selected); return frame.contentWindow.CladoPrototype?.fit(); }, closeLens: () => frame.contentWindow.CladoPrototype?.closeLens() };
1889
2149
  setDesign(design);
1890
2150
  scan();
1891
2151
  if (!offline) {
@@ -1921,9 +2181,7 @@
1921
2181
  es.addEventListener('agent.presence', event => {
1922
2182
  try {
1923
2183
  const payload = JSON.parse(event.data || '{}');
1924
- if (readyCanvas?.frame === frame && (!payload.file || payload.file === selected || payload.phase === 'afterglow' || payload.phase === 'clear')) {
1925
- frame.contentWindow.postMessage({ type: 'clado-workspace:presence', presence: payload }, location.origin);
1926
- }
2184
+ applyPresenceEventToRegistry(payload);
1927
2185
  } catch {}
1928
2186
  });
1929
2187
  es.addEventListener('agent.focus', event => {
package/src/server/mcp.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
1
2
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
3
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
3
4
  import { z } from 'zod/v4';
@@ -11,6 +12,7 @@ const workspace = z.string().min(1).describe('工作区绝对路径,每次调
11
12
  const version = z.string().min(1).describe('可选的全工作区写入保护。传读取返回的 workspaceVersion;项目模板写入必填。').optional();
12
13
  const expectedFileVersion = z.string().min(1).optional().describe('文档读取返回的 version;整文覆盖/改名/删除使用此参数,或传 expectedWorkspaceVersion。也可保护按位置编辑。');
13
14
  const expectedNodeVersion = z.string().min(1).optional().describe('节点返回的 nodeVersion,用来核对目标和后代。适用于覆盖正文、改名、移动、删除、段落和节点内引用编号。');
15
+ const idempotencyKey = z.string().min(1).max(128).optional().describe('可选幂等键;5 分钟内重复提交相同幂等键直接返回首次结果,避免网络重试重复写入。');
14
16
  const templateSource = z.enum(['ancestor','user']).optional().describe('仅用于 pull,明确选择上级项目或用户库。省略时逐层向上查找,全部缺失再查用户库。');
15
17
  const position = z.object({
16
18
  mode: z.enum(['append','prepend','before','after','replace']),
@@ -39,8 +41,29 @@ const nodeFields = {
39
41
  baseTemplateId: z.string().optional(), name: z.string().optional(), purpose: text().optional(), overwrite: z.boolean().optional(), scope: z.enum(['project','user']).optional(), from: templateSource, expectedFileVersion, expectedNodeVersion
40
42
  };
41
43
  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'];
42
- function createServer(invoke, invokeCapability) {
43
- const server = new McpServer({ name: 'clado', version: VERSION }, { instructions: '每次必填workspace。工作区未初始化才调用init;需要目录时用inspect。先读模板prompt再创建.md(也兼容.mdc)。新建、追加和唯一原文编辑可以直接提交;覆盖、删除和按编号定位时带目标版本。项目模板写入使用expectedWorkspaceVersion;用户模板写入用expectedUserTemplateVersion,push需两者。每次响应返回全量diagnostics;操作成功仍可能valid:false。diagnosticsComplete:false表示未完成检查。dryRun的previewDiagnostics对应候选状态;写入results给出最终位置。文档操作使用MCP。' });
44
+
45
+ function safeTokenMatch(actual, expected) {
46
+ if (!actual || !expected) return false;
47
+ const a = createHash('sha256').update(String(actual)).digest();
48
+ const b = createHash('sha256').update(String(expected)).digest();
49
+ return timingSafeEqual(a, b);
50
+ }
51
+
52
+ function readMcpCookie(req, name) {
53
+ const header = String(req.headers.cookie || '');
54
+ for (const part of header.split(';')) {
55
+ const idx = part.indexOf('=');
56
+ if (idx < 0) continue;
57
+ if (part.slice(0, idx).trim() === name) {
58
+ try { return decodeURIComponent(part.slice(idx + 1).trim()); } catch { return part.slice(idx + 1).trim(); }
59
+ }
60
+ }
61
+ return '';
62
+ }
63
+
64
+ function createServer(invoke, invokeCapability, extras = {}) {
65
+ const { invokeSession = null, invokeAutomation = null } = extras || {};
66
+ const server = new McpServer({ name: 'clado', version: VERSION }, { instructions: '每次必填workspace。工作区未初始化才调用init;需要目录时用inspect。先读模板prompt再创建.md(也兼容.mdc)。新建、追加和唯一原文编辑可以直接提交;覆盖、删除和按编号定位时带目标版本(多会话改不同卡片时服务端自动重排无冲突)。写入支持可选 idempotencyKey 幂等去重。项目模板写入使用expectedWorkspaceVersion;用户模板写入用expectedUserTemplateVersion,push需两者。每次响应返回全量diagnostics;操作成功仍可能valid:false。diagnosticsComplete:false表示未完成检查。dryRun的previewDiagnostics对应候选状态;写入results给出最终位置。文档操作使用MCP。' });
44
67
  const schemas = new Map();
45
68
  const enrich = async (result, args) => {
46
69
  const { diagnostics: _operationDiagnostics, error, ...payload } = result;
@@ -56,13 +79,17 @@ function createServer(invoke, invokeCapability) {
56
79
  reply.content.push({ type: 'image', mimeType: 'image/png', data: pngBase64 });
57
80
  return reply;
58
81
  };
59
- const register = (name, description, schema, handler = invoke, { encode = encoded, readOnly = false } = {}) => {
82
+ const register = (name, description, schema, handler = invoke, { encode = encoded, readOnly = false, skipEnrich = false } = {}) => {
60
83
  schemas.set(name, z.object({ workspace, ...schema }).strict());
61
84
  return server.registerTool(name, {
62
- description, inputSchema: { workspace, ...schema }, annotations: { readOnlyHint: readOnly, destructiveHint: !readOnly, openWorldHint: false }
63
- }, async args => {
64
- try { return encode(await enrich(await handler(name, args), args)); }
65
- catch (error) { return await failure(error, args); }
85
+ description, inputSchema: { workspace, ...schema }, annotations: { readOnlyHint: readOnly, destructiveHint: !readOnly, openWorldHint: false }
86
+ }, async args => {
87
+ try {
88
+ const res = await handler(name, args);
89
+ return encode(skipEnrich ? res : await enrich(res, args));
90
+ } catch (error) {
91
+ return await failure(error, args);
92
+ }
66
93
  });
67
94
  };
68
95
  register('clado_workspace', '初始化、查看工作区、列出子工作区、读取画布拓扑树(graph)、搜索或校验。用户说“我选的卡片”时用selection,按点选顺序读取标题路径、正文、后代和版本。selectionStatus为empty或stale时请用户选中或重新选择。graph返回类似DOM树的卡片列布局、跨卡连线、语义Tag、孤立卡与断链快照。inspect返回工作区版本和目录;workspaces列出当前服务范围内的子工作区;init准备工作区。', {
@@ -73,19 +100,19 @@ function createServer(invoke, invokeCapability) {
73
100
  ...Object.fromEntries(['templateId','source','baseTemplateId','name','purpose','overwrite'].map(key => [key, nodeFields[key]])),
74
101
  from: templateSource,
75
102
  view: z.enum(['prompt','source','full']).optional().describe('read默认prompt,编辑规则用source,只有需要全部字段时才用full。'),
76
- expectedWorkspaceVersion: version, expectedUserTemplateVersion: z.string().optional().describe('读取返回的userTemplateVersion;用户库写入及push必填。'), dryRun: z.boolean().optional()
103
+ expectedWorkspaceVersion: version, expectedUserTemplateVersion: z.string().optional().describe('读取返回的userTemplateVersion;用户库写入及push必填。'), idempotencyKey, dryRun: z.boolean().optional()
77
104
  });
78
- register('clado_documents', '文档list/read/create/copy/update/rename/delete。read默认full,按需view:nodes/source/summary/graph(graph返回卡片列布局、跨卡连线、语义Tag、孤立卡与断链拓扑树)。create用file(.md或.mdc)/title/templateId,source只传正文。copy用file/newFile保留规则头和正文并重定位副本引用。create/copy检查目标尚不存在,可省略版本。update传完整source,可用metadata替换头;rename用newFile维护引用;delete被引用默认拒绝,unlink才断开。update/rename/delete使用expectedFileVersion或expectedWorkspaceVersion;results返回最终位置。', {
79
- action: z.enum(['list','read','create','copy','update','rename','delete']), view: z.enum(['full','nodes','source','summary','graph']).optional(), file: z.string().optional(), query: z.string().optional(), title: z.string().optional(), templateId: z.string().optional(), source: text().optional(), metadata: z.record(z.string(), z.unknown()).optional(), newFile: z.string().optional(), unlink: z.boolean().optional(), expectedFileVersion, expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
105
+ register('clado_documents', '文档list/read/create/copy/update/rename/delete。read默认full,按需view:nodes/source/summary/graph(graph返回卡片列布局、跨卡连线、语义Tag、孤立卡与断链拓扑树)。create用file(.md或.mdc)/title/templateId,source只传正文。copy用file/newFile保留规则头和正文并重定位副本引用。create/copy检查目标尚不存在,可省略版本。update传完整source,可用metadata替换头;rename用newFile维护引用;delete被引用默认拒绝,unlink才断开。update/rename/delete使用expectedFileVersion或expectedWorkspaceVersion;支持可选 idempotencyKey 幂等去重;results返回最终位置。', {
106
+ action: z.enum(['list','read','create','copy','update','rename','delete']), view: z.enum(['full','nodes','source','summary','graph']).optional(), file: z.string().optional(), query: z.string().optional(), title: z.string().optional(), templateId: z.string().optional(), source: text().optional(), metadata: z.record(z.string(), z.unknown()).optional(), newFile: z.string().optional(), unlink: z.boolean().optional(), expectedFileVersion, expectedWorkspaceVersion: version, idempotencyKey, dryRun: z.boolean().optional()
80
107
  });
81
- register('clado_nodes', '节点read/query/create/insert/update/rename/move/delete。file必填,node用标题数组。read返回nodeVersion、行号、同级index和段落编号。create在同级末尾新增可省略版本;指定index需文件版本。insert追加/置顶或按唯一anchor插入、update用position:{mode:replace,anchor:原文}时可省略版本。按段落编号或整段覆盖用expectedNodeVersion、expectedFileVersion或expectedWorkspaceVersion,均保留孩子。rename/move维护引用;delete有孩子需recursive。results返回最终位置。', {
82
- action: z.enum(['read','query','create','insert','update','rename','move','delete']), ...Object.fromEntries(['file','node','parent','title','content','index','position','recursive','unlink','targetFile'].map(key => [key, nodeFields[key]])), relation: z.enum(['parent','children','ancestors','descendants','siblings','upstream','downstream']).optional(), depth: z.number().int().min(1).max(100).optional(), includeContent: z.boolean().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(100).optional(), expectedFileVersion, expectedNodeVersion, expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
108
+ register('clado_nodes', '节点read/query/create/insert/update/rename/move/delete。file必填,node用标题数组。read返回nodeVersion、行号、同级index和段落编号。create在同级末尾新增可省略版本;指定index需文件版本。insert追加/置顶或按唯一anchor插入、update用position:{mode:replace,anchor:原文}时可省略版本。按段落编号或整段覆盖用expectedNodeVersion、expectedFileVersion或expectedWorkspaceVersion,均保留孩子(同文档并发修改不同卡片时服务端自动重排无冲突)。支持可选 idempotencyKey 幂等去重。rename/move维护引用;delete有孩子需recursive。results返回最终位置。', {
109
+ action: z.enum(['read','query','create','insert','update','rename','move','delete']), ...Object.fromEntries(['file','node','parent','title','content','index','position','recursive','unlink','targetFile'].map(key => [key, nodeFields[key]])), relation: z.enum(['parent','children','ancestors','descendants','siblings','upstream','downstream']).optional(), depth: z.number().int().min(1).max(100).optional(), includeContent: z.boolean().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(100).optional(), expectedFileVersion, expectedNodeVersion, expectedWorkspaceVersion: version, idempotencyKey, dryRun: z.boolean().optional()
83
110
  });
84
- register('clado_links', 'list返回href、sourceText、nodeVersion、linkIndex(从1开始)及位置。connect用源file/node和目标targetFile/targetNode建立连线:默认从具体内容行出发(用sourcePoint绑定代码行/表格行/Mermaid节点,或用position:{mode:replace,anchor:原文}把正文中的方法/步骤/字段词变成行内链接),不建议在卡片末尾单独追加裸的卡片连卡片。按段落、精确起点连接或disconnect需要节点或文件版本,精确落点需要文件或工作区版本。sourcePoint只用于同画布且与position/before/after互斥。disconnect用linkIndex只断一处,普通链接保留文字。', {
85
- action: z.enum(['list','connect','disconnect']), ...Object.fromEntries(['file','node','targetFile','targetNode','label','before','after','position','linkIndex','sourcePoint','targetPoint'].map(key => [key, nodeFields[key]])), expectedFileVersion, expectedNodeVersion, expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
111
+ register('clado_links', 'list返回href、sourceText、nodeVersion、linkIndex(从1开始)及位置。connect用源file/node和目标targetFile/targetNode建立连线:默认从具体内容行出发(用sourcePoint绑定代码行/表格行/Mermaid节点,或用position:{mode:replace,anchor:原文}把正文中的方法/步骤/字段词变成行内链接),不建议在卡片末尾单独追加裸的卡片连卡片。按段落、精确起点连接或disconnect需要节点或文件版本,精确落点需要文件或工作区版本。支持可选 idempotencyKey。sourcePoint只用于同画布且与position/before/after互斥。disconnect用linkIndex只断一处,普通链接保留文字。', {
112
+ action: z.enum(['list','connect','disconnect']), ...Object.fromEntries(['file','node','targetFile','targetNode','label','before','after','position','linkIndex','sourcePoint','targetPoint'].map(key => [key, nodeFields[key]])), expectedFileVersion, expectedNodeVersion, expectedWorkspaceVersion: version, idempotencyKey, dryRun: z.boolean().optional()
86
113
  });
87
- register('clado_batch', '按顺序执行1–100个操作。支持可选的expectedWorkspaceVersion,各操作也可带自己的expectedFileVersion或expectedNodeVersion。每步的版本和标题路径按前序操作后的候选状态校验。模板操作使用工作区版本。任一冲突整批不保存;dryRun只预览。', {
88
- expectedWorkspaceVersion: version, dryRun: z.boolean().optional(), operations: z.array(z.object({ type: z.enum(operations), ...nodeFields }).strict()).min(1).max(100)
114
+ register('clado_batch', '按顺序执行1–100个操作。支持可选的expectedWorkspaceVersion与idempotencyKey,各操作也可带自己的expectedFileVersion或expectedNodeVersion。每步的版本和标题路径按前序操作后的候选状态校验。模板操作使用工作区版本。任一冲突整批不保存;dryRun只预览。', {
115
+ expectedWorkspaceVersion: version, idempotencyKey, dryRun: z.boolean().optional(), operations: z.array(z.object({ type: z.enum(operations), ...nodeFields }).strict()).min(1).max(100)
89
116
  });
90
117
  if (invokeCapability) register('clado_capabilities', '查询和调用在线画布能力。list 每次读取实时注册的能力、版本、inputSchema 与 outputSchema,可用 to 过滤。call 使用 to:{pluginId,capability,major} 和 input;有多个标签页时传入 viewId。用户要求在画布里打开另一个文件时,调用 clado.directory 的 directory.open。', {
91
118
  action: z.enum(['list', 'call']),
@@ -101,6 +128,27 @@ function createServer(invoke, invokeCapability) {
101
128
  }, (_, { workspace, viewId, mode, source, scope }) => invokeCapability({
102
129
  workspace, viewId, action: 'call', to: captureTarget, input: { ...(mode && { mode }), ...(source && { source }), ...(scope && { scope }) },
103
130
  }), { encode: capabilityResult, readOnly: true });
131
+ if (invokeSession) register('clado_sessions', '与内部多角色主会话完全同源的协作工具:list(支持 sinceMinutes 过滤最近活跃会话)、read(读取指定会话最近对话与工具轨迹)、open(按角色拉起或复用主会话)、send(向指定会话或角色发送协作消息并唤醒/插话)。', {
132
+ action: z.enum(['list', 'read', 'open', 'send']),
133
+ sinceMinutes: z.number().nonnegative().optional(),
134
+ includeArchived: z.boolean().optional(),
135
+ sessionId: z.string().optional(),
136
+ limit: z.number().int().min(1).max(60).optional(),
137
+ roleId: z.string().optional(),
138
+ title: z.string().optional(),
139
+ reuseLatest: z.boolean().optional(),
140
+ fromSessionId: z.string().optional(),
141
+ fromRoleName: z.string().optional(),
142
+ targetSessionId: z.string().optional(),
143
+ targetRoleId: z.string().optional(),
144
+ message: z.string().optional(),
145
+ wait: z.boolean().optional(),
146
+ }, (_, args) => invokeSession(args), { skipEnrich: true });
147
+ if (invokeAutomation) register('clado_automations', '与内部同源的工作区定时唤醒与系统事件订阅管理:支持 list / save / delete / pause / resume / run_now / events_catalog。', {
148
+ action: z.enum(['list', 'save', 'delete', 'pause', 'resume', 'run_now', 'events_catalog']),
149
+ ruleId: z.string().optional(),
150
+ rule: z.record(z.string(), z.unknown()).optional(),
151
+ }, (_, args) => invokeAutomation(args), { skipEnrich: true });
104
152
  return { server, checkCall: async (name, args) => {
105
153
  const schema = schemas.get(name);
106
154
  if (!schema) return await failure({ message: '没有这个工具:' + name, status: 400 }, args);
@@ -110,18 +158,38 @@ function createServer(invoke, invokeCapability) {
110
158
  } };
111
159
  }
112
160
 
113
- export function createMcpHandler(invoke, invokeCapability) {
161
+ export function createMcpHandler(invoke, invokeCapability, options = {}) {
162
+ const { remote = false, remoteToken = '', invokeSession = null, invokeAutomation = null } = options || {};
114
163
  return async (req, res, url) => {
115
164
  if (url.pathname !== '/mcp') return false;
116
- const host = req.headers.host;
117
- if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host || '') || (req.headers.origin && req.headers.origin !== 'http://' + host)) { res.writeHead(403).end('只接受本机可信来源。'); return true; }
165
+ const host = String(req.headers.host || '').trim();
166
+ if (remote) {
167
+ if (!host || /[\s/@]/.test(host)) { res.writeHead(403).end('请求主机头不合法。'); return true; }
168
+ } else if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host) || (req.headers.origin && req.headers.origin !== 'http://' + host)) {
169
+ res.writeHead(403).end('只接受本机可信来源。');
170
+ return true;
171
+ }
172
+ if (remoteToken) {
173
+ const queryToken = url.searchParams.get('token') || '';
174
+ const authHeader = String(req.headers.authorization || '');
175
+ const bearerToken = authHeader.startsWith('Bearer ') ? authHeader.slice(7).trim() : '';
176
+ const cookieToken = readMcpCookie(req, 'clado_remote_token');
177
+ const authed = safeTokenMatch(bearerToken, remoteToken)
178
+ || safeTokenMatch(queryToken, remoteToken)
179
+ || safeTokenMatch(cookieToken, remoteToken);
180
+ if (!authed) {
181
+ res.writeHead(401, { 'content-type': 'application/json' });
182
+ res.end(JSON.stringify({ error: '需要远程访问口令(Bearer Token 或 ?token=)。' }));
183
+ return true;
184
+ }
185
+ }
118
186
  if (req.method !== 'POST') { res.writeHead(405, { allow: 'POST' }).end(); return true; }
119
187
  let server, transport;
120
188
  try {
121
189
  const chunks = []; let bytes = 0;
122
190
  for await (const chunk of req) { bytes += chunk.length; if (bytes > 2_000_000) { res.writeHead(413).end('请求超过2MB。'); return true; } chunks.push(chunk); }
123
191
  const data = JSON.parse(Buffer.concat(chunks).toString('utf8'));
124
- const created = createServer(invoke, invokeCapability); server = created.server;
192
+ const created = createServer(invoke, invokeCapability, { invokeSession, invokeAutomation }); server = created.server;
125
193
  if (data.method === 'tools/call') {
126
194
  const rejected = await created.checkCall(data.params?.name, data.params?.arguments);
127
195
  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; }