cladogram 0.5.4 → 0.5.5-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server/mcp.js CHANGED
@@ -37,13 +37,13 @@ const operations = ['document.create','document.copy','document.update','documen
37
37
  function createServer(invoke, invokeCapability) {
38
38
  const server = new McpServer({ name: 'clado', version: VERSION }, { instructions: '每次必填workspace。工作区未初始化才调用init;需要目录时用inspect。先读模板prompt再创建.mdc。新建、追加和唯一原文编辑可以直接提交;覆盖、删除和按编号定位时带目标版本。项目模板写入使用expectedWorkspaceVersion;用户模板写入用expectedUserTemplateVersion,push需两者。每次响应返回全量diagnostics;操作成功仍可能valid:false。diagnosticsComplete:false表示未完成检查。dryRun的previewDiagnostics对应候选状态;写入results给出最终位置。文档操作使用MCP。' });
39
39
  const schemas = new Map();
40
- const enrich = (result, args) => {
40
+ const enrich = async (result, args) => {
41
41
  const { diagnostics: _operationDiagnostics, error, ...payload } = result;
42
- const report = invoke.diagnostics(args);
42
+ const report = await invoke.diagnostics(args);
43
43
  return { ...(error ? { error } : {}), ...report, ...payload, valid: report.valid };
44
44
  };
45
45
  const encoded = (result, isError = false) => ({ ...(isError ? { isError: true } : {}), content: [{ type: 'text', text: JSON.stringify(result) }], structuredContent: result });
46
- const failure = (error, args) => encoded(enrich({ error: { message: error.message, status: error.status || 500, code: error.details?.code || 'CLADO_OPERATION_FAILED', ...(error.details ? { details: error.details } : {}), ...(error.diagnostics?.length ? { operationDiagnostics: error.diagnostics } : {}) } }, args), true);
46
+ const failure = async (error, args) => encoded(await 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);
47
47
  const capabilityResult = result => {
48
48
  if (!isCaptureTarget(result.provider)) return encoded(result);
49
49
  const { pngBase64, ...output } = result.output;
@@ -56,12 +56,12 @@ function createServer(invoke, invokeCapability) {
56
56
  return server.registerTool(name, {
57
57
  description, inputSchema: { workspace, ...schema }, annotations: { readOnlyHint: readOnly, destructiveHint: !readOnly, openWorldHint: false }
58
58
  }, async args => {
59
- try { return encode(enrich(await handler(name, args), args)); }
60
- catch (error) { return failure(error, args); }
59
+ try { return encode(await enrich(await handler(name, args), args)); }
60
+ catch (error) { return await failure(error, args); }
61
61
  });
62
62
  };
63
- register('clado_workspace', '初始化、查看工作区、搜索或校验。用户说“我选的卡片”时用selection,按点选顺序读取标题路径、正文、后代和版本。selectionStatus为empty或stale时请用户选中或重新选择。inspect返回工作区版本和目录;init准备工作区。', {
64
- action: z.enum(['init','inspect','search','validate','selection']), query: z.string().optional(), includeContent: z.boolean().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(100).optional()
63
+ register('clado_workspace', '初始化、查看工作区、列出子工作区、搜索或校验。用户说“我选的卡片”时用selection,按点选顺序读取标题路径、正文、后代和版本。selectionStatus为empty或stale时请用户选中或重新选择。inspect返回工作区版本和目录;workspaces列出当前服务范围内的子工作区;init准备工作区。', {
64
+ action: z.enum(['init','inspect','search','validate','selection','workspaces']), query: z.string().optional(), includeContent: z.boolean().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(100).optional()
65
65
  });
66
66
  register('clado_templates', '管理模板:scope默认project,设user操作用户库。read默认只返回prompt;编辑时view:source读完整MDC,view:full才返回metadata/source/starter/prompt全部内容。按当前项目、逐层上级、用户库查找,返回来源目录。create传templateId及source,或baseTemplateId(可选name/purpose)复制为新模板;update传完整source。模板头包含id/name/version/purpose/hard_constraints/soft_constraints/organization。pull复制到当前项目,默认逐层查找上级项目再查用户库,可用from:ancestor或from:user指定;push同步到用户库。不同内容默认拒绝覆盖,确认后overwrite:true。项目写入需expectedWorkspaceVersion,用户写入需expectedUserTemplateVersion,push需两者;均可dryRun。修改模板不影响已有文档头部。', {
67
67
  action: z.enum(['list','read','create','update','delete','pull','push']), scope: z.enum(['project','user']).optional(),
@@ -76,7 +76,7 @@ function createServer(invoke, invokeCapability) {
76
76
  register('clado_nodes', '节点read/query/create/insert/update/rename/move/delete。file必填,node用标题数组。read返回nodeVersion、行号、同级index和段落编号。create在同级末尾新增可省略版本;指定index需文件版本。insert追加/置顶或按唯一anchor插入、update用position:{mode:replace,anchor:原文}时可省略版本。按段落编号或整段覆盖用expectedNodeVersion、expectedFileVersion或expectedWorkspaceVersion,均保留孩子。rename/move维护引用;delete有孩子需recursive。results返回最终位置。', {
77
77
  action: z.enum(['read','query','create','insert','update','rename','move','delete']), ...Object.fromEntries(['file','node','parent','title','content','index','position','recursive','unlink','targetFile'].map(key => [key, nodeFields[key]])), relation: z.enum(['parent','children','ancestors','descendants','siblings','upstream','downstream']).optional(), depth: z.number().int().min(1).max(100).optional(), includeContent: z.boolean().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(100).optional(), expectedFileVersion, expectedNodeVersion, expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
78
78
  });
79
- register('clado_links', 'list返回href、sourceText、nodeVersion、linkIndex(从1开始)及位置。connect用源file/node和目标targetFile/targetNode;省略position追加,也可用唯一anchor定位文字。这两种可省略版本。按段落、精确起点连接或disconnect需要节点或文件版本,精确落点需要文件或工作区版本。sourcePoint支持代码行、表格行、Mermaid节点,只用于同画布且与position/before/after互斥。disconnect用linkIndex只断一处,普通链接保留文字。', {
79
+ 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只断一处,普通链接保留文字。', {
80
80
  action: z.enum(['list','connect','disconnect']), ...Object.fromEntries(['file','node','targetFile','targetNode','label','before','after','position','linkIndex','sourcePoint','targetPoint'].map(key => [key, nodeFields[key]])), expectedFileVersion, expectedNodeVersion, expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
81
81
  });
82
82
  register('clado_batch', '按顺序执行1–100个操作。支持可选的expectedWorkspaceVersion,各操作也可带自己的expectedFileVersion或expectedNodeVersion。每步的版本和标题路径按前序操作后的候选状态校验。模板操作使用工作区版本。任一冲突整批不保存;dryRun只预览。', {
@@ -96,11 +96,11 @@ function createServer(invoke, invokeCapability) {
96
96
  }, (_, { workspace, viewId, mode, source, scope }) => invokeCapability({
97
97
  workspace, viewId, action: 'call', to: captureTarget, input: { ...(mode && { mode }), ...(source && { source }), ...(scope && { scope }) },
98
98
  }), { encode: capabilityResult, readOnly: true });
99
- return { server, checkCall: (name, args) => {
99
+ return { server, checkCall: async (name, args) => {
100
100
  const schema = schemas.get(name);
101
- if (!schema) return failure({ message: '没有这个工具:' + name, status: 400 }, args);
101
+ if (!schema) return await failure({ message: '没有这个工具:' + name, status: 400 }, args);
102
102
  const checked = schema.safeParse(args);
103
- if (!checked.success) return failure({ message: '工具参数不合法。', status: 400, details: { code: 'INVALID_ARGUMENTS', issues: checked.error.issues } }, args);
103
+ if (!checked.success) return await failure({ message: '工具参数不合法。', status: 400, details: { code: 'INVALID_ARGUMENTS', issues: checked.error.issues } }, args);
104
104
  return null;
105
105
  } };
106
106
  }
@@ -118,7 +118,7 @@ export function createMcpHandler(invoke, invokeCapability) {
118
118
  const data = JSON.parse(Buffer.concat(chunks).toString('utf8'));
119
119
  const created = createServer(invoke, invokeCapability); server = created.server;
120
120
  if (data.method === 'tools/call') {
121
- const rejected = created.checkCall(data.params?.name, data.params?.arguments);
121
+ const rejected = await created.checkCall(data.params?.name, data.params?.arguments);
122
122
  if (rejected) { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ jsonrpc: '2.0', id: data.id ?? null, result: rejected })); await server.close(); return true; }
123
123
  }
124
124
  transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
@@ -51,19 +51,30 @@ const fromBrowser = z.discriminatedUnion('action', [
51
51
  const agent = { kind: 'agent' };
52
52
  const timeoutMs = 8000;
53
53
 
54
- export function createCapabilityRegistry({ workspace, workspaceId, providers, grants }) {
54
+ export function createCapabilityRegistry({
55
+ workspace, workspaceId, providers, grants,
56
+ resolveWorkspace = target => {
57
+ if (target !== workspace) fail('插件能力只绑定到当前 serve 工作区。', 403, { code: 'FORBIDDEN' });
58
+ return workspace;
59
+ },
60
+ providersFor = () => providers,
61
+ grantsFor = () => grants,
62
+ }) {
55
63
  const views = new Map();
56
64
  const matches = (query, descriptor) => Object.keys(targetFields).every(field => query[field] === undefined || query[field] === descriptor[field]);
57
- const allowed = (caller, descriptor) => caller.kind === 'agent' ? descriptor.exposeToAgent :
58
- caller.pluginId === descriptor.pluginId || grants.get(caller.pluginId)?.includes('capability.call:' + descriptor.pluginId + '/' + descriptor.capability);
65
+ const allowed = (caller, descriptor, targetGrants) => caller.kind === 'agent' ? descriptor.exposeToAgent :
66
+ caller.pluginId === descriptor.pluginId || targetGrants.get(caller.pluginId)?.includes('capability.call:' + descriptor.pluginId + '/' + descriptor.capability);
59
67
 
60
- function list(query, caller, viewId) {
61
- const eligible = viewId ? [views.get(viewId)].filter(Boolean) : [...views.values()];
68
+ function list(query, caller, viewId, targetWorkspace = workspace) {
69
+ const targetGrants = grantsFor(targetWorkspace);
70
+ const eligible = viewId
71
+ ? [views.get(viewId)].filter(view => view && view.workspace === targetWorkspace)
72
+ : [...views.values()].filter(view => view.workspace === targetWorkspace);
62
73
  return {
63
74
  views: eligible.map(view => ({
64
75
  viewId: view.id,
65
76
  capabilities: [...view.providers.values()].map(provider => provider.descriptor)
66
- .filter(descriptor => matches(query, descriptor) && allowed(caller, descriptor)),
77
+ .filter(descriptor => matches(query, descriptor) && allowed(caller, descriptor, targetGrants)),
67
78
  })),
68
79
  };
69
80
  }
@@ -77,12 +88,15 @@ export function createCapabilityRegistry({ workspace, workspaceId, providers, gr
77
88
  return true;
78
89
  }
79
90
 
80
- async function call(viewId, to, input, caller) {
81
- if (!viewId && views.size > 1) fail('有多个 Clado 标签页在线,请传入 viewId。', 409, { code: 'AMBIGUOUS_VIEW' });
82
- const view = viewId ? views.get(viewId) : views.values().next().value;
91
+ async function call(viewId, to, input, caller, targetWorkspace = workspace) {
92
+ const scopedViews = [...views.values()].filter(view => view.workspace === targetWorkspace);
93
+ if (!viewId && scopedViews.length > 1) fail('有多个 Clado 标签页在线,请传入 viewId。', 409, { code: 'AMBIGUOUS_VIEW' });
94
+ const matched = viewId ? views.get(viewId) : scopedViews[0];
95
+ const view = matched && matched.workspace === targetWorkspace ? matched : null;
83
96
  if (!view) fail('目标 Clado 标签页未连接,请打开工作区页面。', 409, { code: 'VIEW_UNAVAILABLE' });
97
+ const targetGrants = grantsFor(view.workspace);
84
98
  const candidates = [...view.providers.values()].filter(({ descriptor }) => matches({ ...to, major: undefined }, descriptor));
85
- const visible = candidates.filter(({ descriptor }) => allowed(caller, descriptor));
99
+ const visible = candidates.filter(({ descriptor }) => allowed(caller, descriptor, targetGrants));
86
100
  if (candidates.length && !visible.length) fail('没有调用该能力的权限。', 403, { code: 'FORBIDDEN' });
87
101
  const compatible = visible.filter(({ descriptor }) => descriptor.major === to.major);
88
102
  if (!compatible.length) fail(visible.length ? '能力主版本不匹配。' : '当前标签页没有注册该能力。', 404, { code: visible.length ? 'UNSUPPORTED_VERSION' : 'NO_PROVIDER' });
@@ -100,16 +114,16 @@ export function createCapabilityRegistry({ workspace, workspaceId, providers, gr
100
114
  view.send('call', {
101
115
  id, from: caller,
102
116
  to: { pluginId: descriptor.pluginId, mountId: descriptor.mountId, capability: descriptor.capability, major: descriptor.major },
103
- scope: { workspaceId, viewId: view.id }, input,
117
+ scope: { workspaceId: view.workspaceId, viewId: view.id }, input,
104
118
  });
105
119
  });
106
120
  }
107
121
 
108
- function connect(id, res) {
109
- if (views.has(id) || views.size >= 32) fail('标签页已连接或已达到连接上限。', 409);
122
+ function connect(id, res, viewWorkspace = workspace, viewWorkspaceId = workspaceId) {
123
+ if (views.has(id) || views.size >= 64) fail('标签页已连接或已达到连接上限。', 409);
110
124
  res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store, no-transform', 'x-content-type-options': 'nosniff' });
111
125
  const send = (event, data) => res.write('event: ' + event + '\ndata: ' + JSON.stringify(data) + '\n\n');
112
- const view = { id, send, res, providers: new Map(), pending: new Map() };
126
+ const view = { id, workspace: viewWorkspace, workspaceId: viewWorkspaceId, send, res, providers: new Map(), pending: new Map() };
113
127
  views.set(id, view);
114
128
  const heartbeat = setInterval(() => res.write(': heartbeat\n\n'), 15000);
115
129
  res.on('close', () => {
@@ -118,7 +132,7 @@ export function createCapabilityRegistry({ workspace, workspaceId, providers, gr
118
132
  for (const callId of view.pending.keys()) finish(view, callId, ({ reject }) =>
119
133
  reject(Object.assign(new Error('插件所在的标签页已断开。'), { status: 409, details: { code: 'VIEW_UNAVAILABLE' } })));
120
134
  });
121
- send('ready', { viewId: id, workspaceId });
135
+ send('ready', { viewId: id, workspaceId: viewWorkspaceId });
122
136
  }
123
137
 
124
138
  async function receive(id, body) {
@@ -143,16 +157,18 @@ export function createCapabilityRegistry({ workspace, workspaceId, providers, gr
143
157
  });
144
158
  return {};
145
159
  }
146
- if (!grants.has(message.pluginId)) fail('插件未启用。', 403, { code: 'FORBIDDEN' });
160
+ const targetGrants = grantsFor(view.workspace);
161
+ const targetProviders = providersFor(view.workspace);
162
+ if (!targetGrants.has(message.pluginId)) fail('插件未启用。', 403, { code: 'FORBIDDEN' });
147
163
  if (message.action === 'register') {
148
- const declared = providers.filter(({ descriptor }) => descriptor.pluginId === message.pluginId && descriptor.mountId === message.mountId);
164
+ const declared = targetProviders.filter(({ descriptor }) => descriptor.pluginId === message.pluginId && descriptor.mountId === message.mountId);
149
165
  if (!declared.length) fail('该挂载未声明可注册的能力。', 400, { code: 'NO_PROVIDER' });
150
166
  for (const provider of declared) view.providers.set(provider.key, provider);
151
167
  return { capabilities: declared.map(provider => provider.descriptor) };
152
168
  }
153
169
  const caller = { kind: 'plugin', pluginId: message.pluginId, mountId: message.mountId };
154
- if (message.action === 'list') return list(message.query, caller, id);
155
- return await call(id, message.to, message.input, caller);
170
+ if (message.action === 'list') return list(message.query, caller, id, view.workspace);
171
+ return await call(id, message.to, message.input, caller, view.workspace);
156
172
  }
157
173
 
158
174
  return {
@@ -162,11 +178,11 @@ export function createCapabilityRegistry({ workspace, workspaceId, providers, gr
162
178
  },
163
179
  close() { for (const view of views.values()) view.res.end(); },
164
180
  async invoke(args) {
165
- if (args.workspace !== workspace) fail('插件能力只绑定到当前 serve 工作区。', 403, { code: 'FORBIDDEN' });
166
- if (args.action === 'list') return list(args.to || {}, agent, args.viewId);
181
+ const targetWorkspace = resolveWorkspace(args.workspace);
182
+ if (args.action === 'list') return list(args.to || {}, agent, args.viewId, targetWorkspace);
167
183
  const parsed = target.safeParse(args.to);
168
184
  if (!parsed.success || !args.input) fail('调用能力需要 to.capability、to.major 和 input。', 400, { code: 'INVALID_PARAMS' });
169
- return await call(args.viewId, parsed.data, args.input, agent);
185
+ return await call(args.viewId, parsed.data, args.input, agent, targetWorkspace);
170
186
  },
171
187
  };
172
188
  }
@@ -12,7 +12,7 @@ export const pluginConfiguration = z.strictObject({
12
12
  });
13
13
  const specs = {
14
14
  'clado.brand': { showScreenshot: { type: 'boolean' } },
15
- 'clado.view-controls': { defaultMode: { enum: ['mindmap', 'cards', 'doc'] } },
15
+ 'clado.view-controls': { defaultMode: { enum: ['cards', 'mindmap', 'doc'] } },
16
16
  'clado.directory': { showFilename: { type: 'boolean' } },
17
17
  'clado.agent': {
18
18
  name: { type: 'string', minLength: 1, maxLength: 80 },
@@ -219,7 +219,7 @@ export function loadWorkspacePlugins(state) {
219
219
  });
220
220
  res.end(req.method === 'HEAD' ? undefined : body);
221
221
  }
222
- return { descriptor, warnings, serveAsset, capabilities, configurations, register };
222
+ return { descriptor, warnings, serveAsset, hasAsset: key => packages.has(key), capabilities, configurations, register };
223
223
  }
224
224
 
225
225
  export function inspectWorkspacePlugins(state) {
@@ -1,12 +1,12 @@
1
1
  import { createServer } from 'node:http';
2
2
  import { createHash, randomUUID } from 'node:crypto';
3
3
  import { readFileSync, statSync, existsSync, mkdirSync } from 'node:fs';
4
- import { dirname, resolve, basename, join, relative } from 'node:path';
4
+ import { dirname, resolve, basename, join, relative, sep, isAbsolute } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { renderHtml } from '../html/page.js';
7
7
  import { pluginMarkup, workspacePluginAssets } from '../html/plugin-assets.js';
8
8
  import { scanDirectory, workspacePath, readDocument, DocumentError } from '../workspace/documents.js';
9
- import { contextFor, initialize } from '../workspace/storage.js';
9
+ import { contextFor, discoverWorkspaces, initialize } from '../workspace/storage.js';
10
10
  import { createWorkspaceService } from '../workspace/service.js';
11
11
  import { createMcpHandler } from './mcp.js';
12
12
  import { builtInCapabilities, builtInGrants, inspectWorkspacePlugins, installWorkspacePlugin, loadWorkspacePlugins } from './plugins.js';
@@ -25,10 +25,13 @@ export function createWorkspaceHandler(directory, options = {}) {
25
25
  const root = resolve(directory);
26
26
  const assetNames = new Set(['library.html','library.css','library.js','library-canvas.js']);
27
27
  if (options.capabilities) assetNames.add('library-plugin-bridge.js');
28
- if (options.plugins) for (const name of ['library-plugins.js', 'library-plugins.css', 'clado-plugin-sdk.js']) assetNames.add(name);
28
+ if (options.plugins || options.experimentalPlugins) for (const name of ['library-plugins.js', 'library-plugins.css', 'clado-plugin-sdk.js']) assetNames.add(name);
29
29
  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); };
30
30
  const json = (res, status, data) => send(res, status, types.json, JSON.stringify(data));
31
31
  const safeJson = data => JSON.stringify(data).replace(/</g,'\\u003c');
32
+ const resolveTarget = url => options.resolveWorkspace
33
+ ? options.resolveWorkspace(url.searchParams.get('workspace'))
34
+ : { id: '', workspace: root, root, workspaceId: options.plugins?.descriptor.workspaceId || '', plugins: options.plugins || null, settings: options.settings || null, inactivePlugins: options.inactivePlugins };
32
35
  return async function handle(req, res, url) {
33
36
  const route = url.pathname.slice(1);
34
37
  const pluginFile = workspacePluginAssets.get(url.pathname);
@@ -36,10 +39,12 @@ export function createWorkspaceHandler(directory, options = {}) {
36
39
  try {
37
40
  const host = req.headers.host;
38
41
  if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host || '')) throw new DocumentError('只接受本机预览请求。',403);
39
- const pluginAsset = options.plugins && url.pathname.startsWith('/library/plugin-assets/');
42
+ const pluginsEnabled = !!(options.plugins || options.experimentalPlugins);
43
+ const pluginAsset = pluginsEnabled && url.pathname.startsWith('/library/plugin-assets/');
40
44
  if (req.headers.origin && req.headers.origin !== 'http://' + host && !(pluginAsset && req.headers.origin === 'null')) throw new DocumentError('来源不匹配。',403);
41
45
  if (url.pathname === '/library/selection' && options.publishSelection && req.method === 'POST') {
42
46
  if (req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') throw new DocumentError('选区只接受同源页面请求。', 403);
47
+ const target = resolveTarget(url);
43
48
  const chunks = []; let size = 0;
44
49
  for await (const chunk of req) {
45
50
  size += chunk.length;
@@ -48,16 +53,19 @@ export function createWorkspaceHandler(directory, options = {}) {
48
53
  }
49
54
  const selection = viewSelection.safeParse(JSON.parse(Buffer.concat(chunks).toString('utf8')));
50
55
  if (!selection.success) throw new DocumentError('选区参数不合法。', 400);
51
- workspacePath(root, selection.data.file, selection.data.nodes.length === 0);
52
- options.publishSelection(selection.data);
56
+ workspacePath(target.root, selection.data.file, selection.data.nodes.length === 0);
57
+ options.publishSelection(target.workspace, selection.data);
53
58
  json(res, 200, { ok: true }); return true;
54
59
  }
55
60
  if (options.agent && url.pathname === '/library/agent') {
56
- await options.agent.handle(req, res); return true;
61
+ const target = resolveTarget(url);
62
+ await options.agent.handle(req, res, target.workspace); return true;
57
63
  }
58
- if (options.settings && url.pathname === '/library/plugin-settings') {
64
+ if (url.pathname === '/library/plugin-settings') {
65
+ const target = resolveTarget(url);
66
+ if (!target.settings) throw new DocumentError('没有这个预览入口;文档操作请使用 /mcp。',404);
59
67
  const id = url.searchParams.get('id');
60
- if (req.method === 'GET') { json(res, 200, options.settings.read(id)); return true; }
68
+ if (req.method === 'GET') { json(res, 200, target.settings.read(id)); return true; }
61
69
  if (req.method !== 'POST' || req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') {
62
70
  throw new DocumentError('插件设置只接受同源页面写入。', 403);
63
71
  }
@@ -68,20 +76,21 @@ export function createWorkspaceHandler(directory, options = {}) {
68
76
  chunks.push(chunk);
69
77
  }
70
78
  const { value, expected } = JSON.parse(Buffer.concat(chunks).toString('utf8'));
71
- json(res, 200, options.settings.save(id, value, expected));
79
+ json(res, 200, target.settings.save(id, value, expected));
72
80
  return true;
73
81
  }
74
82
  if (options.installPlugin && url.pathname === '/library/install-plugin') {
75
83
  if (req.method !== 'POST' || req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') {
76
84
  throw new DocumentError('插件安装需要在工作区页面操作。', 403);
77
85
  }
86
+ const target = resolveTarget(url);
78
87
  const chunks = []; let size = 0;
79
88
  for await (const chunk of req) {
80
89
  size += chunk.length;
81
90
  if (size > 12 * 1024 * 1024) throw new DocumentError('插件包太大。', 413);
82
91
  chunks.push(chunk);
83
92
  }
84
- json(res, 201, options.installPlugin(JSON.parse(Buffer.concat(chunks).toString('utf8'))?.files));
93
+ json(res, 201, options.installPlugin(target.workspace, JSON.parse(Buffer.concat(chunks).toString('utf8'))?.files));
85
94
  return true;
86
95
  }
87
96
  if (options.capabilities && url.pathname === '/library/plugin-bridge') {
@@ -89,7 +98,8 @@ export function createWorkspaceHandler(directory, options = {}) {
89
98
  if (!view.success) throw new DocumentError('需要有效的 viewId。', 400);
90
99
  if (req.method === 'GET' && req.headers.accept === 'text/event-stream' &&
91
100
  (!req.headers['sec-fetch-site'] || req.headers['sec-fetch-site'] === 'same-origin')) {
92
- options.capabilities.connect(view.data, res); return true;
101
+ const target = resolveTarget(url);
102
+ options.capabilities.connect(view.data, res, target.workspace, target.workspaceId); return true;
93
103
  }
94
104
  if (req.method !== 'POST' || req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') {
95
105
  throw new DocumentError('插件通信只接受同源页面请求。', 403);
@@ -111,13 +121,22 @@ export function createWorkspaceHandler(directory, options = {}) {
111
121
  return true;
112
122
  }
113
123
  if (req.method !== 'GET' && req.method !== 'HEAD') throw new DocumentError('不支持这个请求方法。',405);
114
- if (options.plugins && url.pathname === '/library/plugins.json') {
115
- const values = options.settings?.values() || {};
116
- const descriptor = options.plugins.descriptor;
124
+ if (url.pathname === '/library/workspaces.json') {
125
+ const workspaces = options.listWorkspaces
126
+ ? options.listWorkspaces()
127
+ : [{ id: '', name: basename(root), workspace: root, documentRoot: root, documents: scanDirectory(root).documents.length }];
128
+ json(res, 200, { scope: options.scopeName || basename(root), workspaces }); return true;
129
+ }
130
+ if (pluginsEnabled && url.pathname === '/library/plugins.json') {
131
+ const target = resolveTarget(url);
132
+ const values = target.settings?.values() || {};
133
+ const descriptor = target.plugins.descriptor;
117
134
  json(res, 200, { ...descriptor, plugins: descriptor.plugins.map(plugin => ({ ...plugin, settings: values[plugin.id] || {} })) }); return true;
118
135
  }
119
136
  if (pluginAsset) {
120
- options.plugins.serveAsset(req, res, url); return true;
137
+ if (options.servePluginAsset) options.servePluginAsset(req, res, url);
138
+ else options.plugins.serveAsset(req, res, url);
139
+ return true;
121
140
  }
122
141
  if (pluginFile) {
123
142
  send(res, 200, types[route.split('.').pop()], readFileSync(pluginFile, 'utf8')); return true;
@@ -125,45 +144,49 @@ export function createWorkspaceHandler(directory, options = {}) {
125
144
  if (assetNames.has(route) || (options.entrypoint && route === '')) {
126
145
  const name = route || 'library.html'; let body = readFileSync(join(assets, name),'utf8');
127
146
  if (name === 'library.html') {
147
+ const target = resolveTarget(url);
128
148
  const plugins = pluginMarkup({ workspace: true, agent: !!options.agent });
129
149
  body = body.replace('<!--CLADO-PLUGIN-STYLES-->', () => plugins.styles)
130
150
  .replace('<!--CLADO-PLUGIN-SCRIPTS-->', () => plugins.scripts);
131
151
  const pluginAssets = (options.capabilities ? '<script src="/library-plugin-bridge.js"></script>' : '') +
132
- (options.plugins ? '<link rel="stylesheet" href="/library-plugins.css"><script src="/library-plugins.js"></script>' : '');
152
+ (target.plugins ? '<link rel="stylesheet" href="/library-plugins.css"><script src="/library-plugins.js"></script>' : '');
133
153
  body = body.replace('</head>', pluginAssets + '</head>');
134
- const pluginCatalog = options.plugins?.descriptor.plugins.map(({ id, name, version }) => ({ id, name, version })) || options.inactivePlugins?.() || [];
135
- const pluginPreferenceKey = createHash('sha256').update(root).digest('hex');
136
- const pluginSettings = Object.fromEntries(Object.entries(options.settings?.values() || {}).filter(([id]) => id.startsWith('clado.') && !pluginCatalog.some(plugin => plugin.id === id)));
137
- body = body.replace('<script src="library.js">','<script>window.__CLADO_WORKSPACE__='+safeJson({mode:options.mode || 'mindmap',theme:options.theme || 'light',entry:options.entry || '',selection:!!options.publishSelection,plugins:!!options.plugins,agent:!!options.agent,agentProfile:options.agentProfile,pluginCatalog,pluginPreferenceKey,pluginSettings,hasPluginSettings:!!options.settings,canInstallPlugins:!!options.installPlugin})+';</script><script src="library.js">');
154
+ const pluginCatalog = target.plugins?.descriptor.plugins.map(({ id, name, version }) => ({ id, name, version })) || target.inactivePlugins?.() || [];
155
+ const pluginPreferenceKey = createHash('sha256').update(target.workspace).digest('hex');
156
+ const pluginSettings = Object.fromEntries(Object.entries(target.settings?.values() || {}).filter(([id]) => id.startsWith('clado.') && !pluginCatalog.some(plugin => plugin.id === id)));
157
+ body = body.replace('<script src="library.js">','<script>window.__CLADO_WORKSPACE__='+safeJson({mode:options.mode || 'cards',theme:options.theme || 'light',entry:target.id ? '' : (options.entry || ''),workspaceId:target.id,workspaceName:basename(target.workspace),workspacePath:target.workspace,multiWorkspace:!!options.listWorkspaces,selection:!!options.publishSelection,plugins:!!target.plugins,agent:!!options.agent,agentProfile:options.agentProfile,pluginCatalog,pluginPreferenceKey,pluginSettings,hasPluginSettings:!!target.settings,canInstallPlugins:!!options.installPlugin})+';</script><script src="library.js">');
138
158
  }
139
159
  send(res,200,types[name.split('.').pop()],body); return true;
140
160
  }
141
161
  if (url.pathname === '/library/index.json') {
142
- const result = scanDirectory(root);
143
- json(res,200,{root:basename(root)+'/',documents:result.documents,skipped:result.skipped}); return true;
162
+ const target = resolveTarget(url);
163
+ const result = scanDirectory(target.root);
164
+ json(res,200,{root:(target.id || basename(target.root))+'/',workspaceId:target.id,workspace:target.workspace,documents:result.documents,skipped:result.skipped}); return true;
144
165
  }
145
166
  const name = url.searchParams.get('file');
146
167
  if (url.pathname === '/library/resource') {
168
+ const target = resolveTarget(url);
147
169
  const type = resourceTypes[String(name).split('.').pop().toLowerCase()];
148
170
  if (!type) throw new DocumentError('不支持的资源类型。',415);
149
- const path=workspacePath(root,name,false,true);
171
+ const path=workspacePath(target.root,name,false,true);
150
172
  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;
151
173
  }
152
174
  if (!['/library/source.mdc','/library/canvas'].includes(url.pathname)) throw new DocumentError('没有这个预览入口;文档操作请使用 /mcp。',404);
153
- const file = workspacePath(root,name), item = readDocument(file);
175
+ const target = resolveTarget(url);
176
+ const file = workspacePath(target.root,name), item = readDocument(file);
154
177
  if (url.pathname === '/library/source.mdc') { send(res,200,types.md,item.source); return true; }
155
178
  if (item.diagnostics.some(d=>d.severity==='error')) throw new DocumentError('文档暂时无法解析。',422,item.diagnostics);
156
- const mode = ['doc','cards','mindmap'].includes(url.searchParams.get('mode')) ? url.searchParams.get('mode') : options.mode || 'mindmap';
179
+ const mode = ['cards','mindmap','doc'].includes(url.searchParams.get('mode')) ? url.searchParams.get('mode') : (options.mode || 'cards');
157
180
  let html = (options.render || renderHtml)(item.doc,item.diagnostics,{file:name,title:item.doc.title,mode,theme:['light','dark'].includes(url.searchParams.get('theme')) ? url.searchParams.get('theme') : options.theme || 'light',library:true,workspaceChrome:url.searchParams.get('chrome') === 'workspace'});
158
181
  const bodyEnd = html.lastIndexOf('</body>');
159
- html = html.slice(0,bodyEnd) + '<script>window.__CLADO_FILE_PATH__='+safeJson(name)+';window.__CLADO_FILE_VERSION__='+safeJson(item.version)+';window.__CLADO_ANCHOR__='+safeJson(url.searchParams.get('anchor') || '')+';</script><script src="/library-canvas.js"></script>' + html.slice(bodyEnd);
182
+ html = html.slice(0,bodyEnd) + '<script>window.__CLADO_FILE_PATH__='+safeJson(name)+';window.__CLADO_FILE_VERSION__='+safeJson(item.version)+';window.__CLADO_ANCHOR__='+safeJson(url.searchParams.get('anchor') || '')+';window.__CLADO_WORKSPACE_ID__='+safeJson(target.id)+';</script><script src="/library-canvas.js"></script>' + html.slice(bodyEnd);
160
183
  send(res,200,types.html,html); return true;
161
184
  } catch (error) {
162
185
  json(res,error.status || (error instanceof SyntaxError ? 400 : 500),{error:error.message,diagnostics:error.diagnostics || [], ...(error.details && { details: error.details })}); return true;
163
186
  }
164
187
  };
165
188
  }
166
- export async function startWorkspace(input, { port = 4317, mode = 'mindmap', theme = 'light', entry, project = false, experimentalPlugins = false, agent: agentName = 'acp' } = {}) {
189
+ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme = 'light', entry, project = false, experimentalPlugins = false, agent: agentName = 'acp' } = {}) {
167
190
  const path = resolve(input);
168
191
  if (!existsSync(path) && !/\.mdc?$/i.test(path)) mkdirSync(path, { recursive: true });
169
192
  if (statSync(path).isFile() && !/\.mdc?$/i.test(path)) throw new DocumentError('serve 文件需要 .mdc 或 .md 扩展名。');
@@ -172,51 +195,105 @@ export async function startWorkspace(input, { port = 4317, mode = 'mindmap', the
172
195
  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)))) {
173
196
  const ctx = contextFor(root, root); workspace = root; root = ctx.documents;
174
197
  }
175
- const ctx = contextFor(workspace, workspace, root); initialize(ctx);
176
- const plugins = experimentalPlugins ? loadWorkspacePlugins(ctx.state) : null;
177
- const settings = createPluginSettings(ctx, plugins?.configurations);
178
- const grants = builtInGrants();
179
- for (const { id, permissions } of plugins?.descriptor.plugins || []) grants.set(id, permissions);
180
- const providers = [...builtInCapabilities(agentName !== 'off'), ...(plugins?.capabilities || [])];
198
+ const rootCtx = contextFor(workspace, workspace, root); initialize(rootCtx);
199
+ const runtimes = new Map();
200
+ function runtimeFor(ctx) {
201
+ const existing = runtimes.get(ctx.workspace);
202
+ if (existing) { existing.ctx = ctx; existing.root = ctx.documents; return existing; }
203
+ const wsPlugins = experimentalPlugins ? loadWorkspacePlugins(ctx.state) : null;
204
+ const wsSettings = createPluginSettings(ctx, wsPlugins?.configurations);
205
+ const wsGrants = builtInGrants();
206
+ for (const { id, permissions } of wsPlugins?.descriptor.plugins || []) wsGrants.set(id, permissions);
207
+ const wsProviders = [...builtInCapabilities(agentName !== 'off'), ...(wsPlugins?.capabilities || [])];
208
+ const rt = {
209
+ id: relative(workspace, ctx.workspace).split(sep).join('/'),
210
+ workspace: ctx.workspace,
211
+ root: ctx.documents,
212
+ ctx,
213
+ workspaceId: wsPlugins?.descriptor.workspaceId || randomUUID(),
214
+ plugins: wsPlugins,
215
+ settings: wsSettings,
216
+ grants: wsGrants,
217
+ providers: wsProviders,
218
+ inactivePlugins: () => inspectWorkspacePlugins(ctx.state),
219
+ };
220
+ runtimes.set(ctx.workspace, rt);
221
+ return rt;
222
+ }
223
+ const rootRuntime = runtimeFor(rootCtx);
224
+ function resolveWorkspaceParam(param) {
225
+ if (!param) return rootRuntime;
226
+ if (typeof param !== 'string' || isAbsolute(param) || param.includes('\\') || param.includes('\0') ||
227
+ param.split('/').some(segment => !segment || segment === '.' || segment === '..' || segment.startsWith('.'))) {
228
+ throw new DocumentError('工作区路径不合法。', 400);
229
+ }
230
+ const ctx = contextFor(workspace, resolve(workspace, param), root);
231
+ if (!existsSync(ctx.documents) && !existsSync(ctx.state)) throw new DocumentError('工作区不存在或尚未初始化。', 404);
232
+ return runtimeFor(ctx);
233
+ }
234
+ const resolveMcpWorkspace = target => runtimeFor(contextFor(workspace, target, root)).workspace;
181
235
  const capabilities = createCapabilityRegistry({
182
- workspace, workspaceId: plugins?.descriptor.workspaceId || randomUUID(),
183
- providers, grants,
236
+ workspace, workspaceId: rootRuntime.workspaceId,
237
+ providers: rootRuntime.providers, grants: rootRuntime.grants,
238
+ resolveWorkspace: resolveMcpWorkspace,
239
+ providersFor: target => runtimeFor(contextFor(workspace, target, root)).providers,
240
+ grantsFor: target => runtimeFor(contextFor(workspace, target, root)).grants,
184
241
  });
185
242
  const entryFile = entry ? relative(root,workspacePath(root,entry)).split('\\').join('/') : (statSync(path).isFile() ? basename(path) : '');
186
243
  if (entryFile) {
187
244
  const item=readDocument(workspacePath(root,entryFile));
188
245
  if(item.diagnostics.some(d=>d.severity==='error'))throw new DocumentError('入口 Markdown 无法解析。',422,item.diagnostics);
189
246
  }
190
- let selection;
191
- const publishSelection = next => {
247
+ const selections = new Map();
248
+ const publishSelection = (targetWorkspace, next) => {
249
+ const current = selections.get(targetWorkspace);
192
250
  if (next.refresh) {
193
- if (selection?.tab !== next.tab || selection.file !== next.file) return;
194
- if (next.refresh === 'render') selection = { ...next, expiresAt: Date.now() + 120000 };
195
- else if (selection.version === next.version) selection.expiresAt = Date.now() + 120000;
196
- } else if (next.nodes.length) selection = { ...next, expiresAt: Date.now() + 120000 };
197
- else if (selection?.tab === next.tab) selection = undefined;
251
+ if (current?.tab !== next.tab || current.file !== next.file) return;
252
+ if (next.refresh === 'render') selections.set(targetWorkspace, { ...next, expiresAt: Date.now() + 120000 });
253
+ else if (current.version === next.version) current.expiresAt = Date.now() + 120000;
254
+ } else if (next.nodes.length) selections.set(targetWorkspace, { ...next, expiresAt: Date.now() + 120000 });
255
+ else if (current?.tab === next.tab) selections.delete(targetWorkspace);
256
+ };
257
+ const readSelection = targetWorkspace => {
258
+ const current = selections.get(targetWorkspace);
259
+ return current?.expiresAt > Date.now() ? current : null;
198
260
  };
199
261
  const agent = agentName !== 'off' ? (await import('./agent.js')).createAgentHandler({
200
262
  workspace, mcpUrl: () => 'http://127.0.0.1:' + server.address().port + '/mcp',
201
263
  ...(agentName === 'acp' && { resolveLaunch: () => {
202
- const { command, args, env } = settings.agentLaunch();
264
+ const { command, args, env } = rootRuntime.settings.agentLaunch();
203
265
  return { command, args, env };
204
266
  } }),
205
267
  }) : null;
206
- function installPlugin(files) {
207
- const previous = plugins?.capabilities.length || 0;
208
- const installed = installWorkspacePlugin(ctx, files, plugins);
209
- if (plugins) {
210
- const descriptor = plugins.descriptor.plugins.find(plugin => plugin.id === installed.id);
211
- grants.set(installed.id, descriptor.permissions);
212
- providers.push(...plugins.capabilities.slice(previous));
213
- settings.register(installed.id, plugins.configurations.get(installed.id));
268
+ function installPlugin(targetWorkspace, files) {
269
+ const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
270
+ const previous = rt.plugins?.capabilities.length || 0;
271
+ const installed = installWorkspacePlugin(rt.ctx, files, rt.plugins);
272
+ if (rt.plugins) {
273
+ const descriptor = rt.plugins.descriptor.plugins.find(plugin => plugin.id === installed.id);
274
+ rt.grants.set(installed.id, descriptor.permissions);
275
+ rt.providers.push(...rt.plugins.capabilities.slice(previous));
276
+ rt.settings.register(installed.id, rt.plugins.configurations.get(installed.id));
214
277
  }
215
278
  return installed;
216
279
  }
217
- const handle = createWorkspaceHandler(root,{entrypoint:true,mode,theme,entry:entryFile,publishSelection,plugins,agent,agentProfile:agentName,capabilities,settings,installPlugin,
218
- inactivePlugins: () => inspectWorkspacePlugins(ctx.state)});
219
- const mcp = createMcpHandler(createWorkspaceService(workspace, { documentRoot: root, readSelection: () => selection?.expiresAt > Date.now() ? selection : null }), capabilities.invoke);
280
+ function servePluginAsset(req, res, url) {
281
+ const key = decodeURIComponent(url.pathname.slice('/library/plugin-assets/'.length).split('/')[0] || '');
282
+ for (const rt of runtimes.values()) {
283
+ if (rt.plugins?.hasAsset(key)) { rt.plugins.serveAsset(req, res, url); return; }
284
+ }
285
+ throw new DocumentError('插件资源不存在。', 404);
286
+ }
287
+ const handle = createWorkspaceHandler(root,{
288
+ entrypoint:true,mode,theme,entry:entryFile,publishSelection,
289
+ plugins:rootRuntime.plugins,experimentalPlugins,servePluginAsset,
290
+ agent,agentProfile:agentName,capabilities,settings:rootRuntime.settings,installPlugin,
291
+ resolveWorkspace:resolveWorkspaceParam,
292
+ listWorkspaces:() => discoverWorkspaces(workspace, root),
293
+ scopeName:basename(workspace),
294
+ inactivePlugins:rootRuntime.inactivePlugins,
295
+ });
296
+ const mcp = createMcpHandler(createWorkspaceService(workspace, { documentRoot: root, readSelection }), capabilities.invoke);
220
297
  const server = createServer(async (req,res) => {
221
298
  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'); } }
222
299
  catch { if (!res.headersSent) res.writeHead(500);res.end('预览请求失败'); }
@@ -225,5 +302,5 @@ export async function startWorkspace(input, { port = 4317, mode = 'mindmap', the
225
302
  await new Promise((resolve,reject) => { server.once('error',reject); server.listen(port,'127.0.0.1',resolve); });
226
303
  const file = entryFile ? '?file='+encodeURIComponent(entryFile) : '';
227
304
  const origin = 'http://127.0.0.1:'+server.address().port;
228
- return {server,url:origin+'/'+file,mcpUrl:origin+'/mcp',workspace,root,pluginWarnings:plugins?.warnings || [],stopAgent:agent?.close,stopCapabilities:capabilities.close};
305
+ return {server,url:origin+'/'+file,mcpUrl:origin+'/mcp',workspace,root,pluginWarnings:rootRuntime.plugins?.warnings || [],stopAgent:agent?.close,stopCapabilities:capabilities.close};
229
306
  }
@@ -312,6 +312,6 @@ export function installTo(cwd, ids, opts = {}) {
312
312
  * 是无害的额外键,于是统一都带上,省得一张表里两套写法。
313
313
  */
314
314
  function ownFileText(body) {
315
- const desc = '用 clado 把 Markdown 编译成自包含的网页(文档 / 卡片 / 脑图三种模式)';
315
+ const desc = '用 clado 把 Markdown 编译成自包含的网页(卡片 / 脑图 / 文档三种模式)';
316
316
  return `---\ndescription: ${desc}\nalwaysApply: false\n---\n\n${body}`;
317
317
  }
@@ -157,7 +157,7 @@ export function findTarget(id) {
157
157
  export function ruleBody(skillPath) {
158
158
  return `# clado —— Markdown 三视图工作区
159
159
 
160
- 这个项目用 Clado 维护 Markdown 画布,在脑图、卡片和文档视图中讨论与迭代,也可打包成单个离线 HTML。
160
+ 这个项目用 Clado 维护 Markdown 画布,在卡片、脑图和文档视图中讨论与迭代,也可打包成单个离线 HTML。
161
161
 
162
162
  写或改画布前,先读 Skill 入口:
163
163
 
@@ -176,9 +176,9 @@ export function ruleBody(skillPath) {
176
176
 
177
177
  clado serve
178
178
 
179
- 连接输出的 Streamable HTTP MCP。每次调用提供输出的 workspace,先 clado_workspace inspect,再 clado_templates read 提示词,用 clado_documents create 按模板初始化 .mdc;节点、链接与批量操作也用MCP。正文直接传多行字符串。新建、追加和唯一原文编辑可直接提交;覆盖和删除使用对应的版本。用户提到选中的卡片时通过 clado_workspace selection 读取。模板可在项目 create/update,用 pull 从用户库复制,用 push 同步到用户库;push 同时带 expectedUserTemplateVersion。
179
+ 连接输出的 Streamable HTTP MCP。每次调用提供输出的 workspace,先 clado_workspace inspect,再 clado_templates read 提示词,用 clado_documents create 按模板初始化 .mdc;节点、链接与批量操作也用MCP。跨卡连接优先从具体内容行出发(代码行、表格数据行、Mermaid 节点或步骤正文内的行内链接),避免为凑连线单独追加裸的卡片连卡片。正文直接传多行字符串。新建、追加和唯一原文编辑可直接提交;覆盖和删除使用对应的版本。用户提到选中的卡片时通过 clado_workspace selection 读取。模板可在项目 create/update,用 pull 从用户库复制,用 push 同步到用户库;push 同时带 expectedUserTemplateVersion。
180
180
 
181
- 网页只展示脑图/卡片/文档,保存后自动更新。交付可用 clado build --entry overview.mdc --mode cards;默认生成只读 clado.html。工具不执行文档里的SQL、脚本或发布任务。
181
+ 网页只展示卡片/脑图/文档,保存后自动更新。交付可用 clado build --entry overview.mdc --mode cards;默认生成只读 clado.html。工具不执行文档里的SQL、脚本或发布任务。
182
182
 
183
183
  `;
184
184
  }
@@ -10,9 +10,10 @@ const cacheLifetime = 24 * 60 * 60 * 1000;
10
10
 
11
11
  function updateInfo(latest) {
12
12
  if (typeof latest !== 'string' || !stableVersion.test(latest)) throw new Error('npm 未返回可用的稳定版本。');
13
- const installed = VERSION.split('.').map(Number), remote = latest.split('.').map(Number);
13
+ const [core, pre = ''] = VERSION.split('-');
14
+ const installed = core.split('.').map(Number), remote = latest.split('.').map(Number);
14
15
  const difference = remote.map((part, index) => part - installed[index]).find(value => value !== 0) || 0;
15
- return { current: VERSION, latest, updateAvailable: difference > 0 };
16
+ return { current: VERSION, latest, updateAvailable: difference > 0 || (difference === 0 && Boolean(pre)) };
16
17
  }
17
18
 
18
19
  export async function checkUpdate() {