cladogram 0.5.5-beta.9 → 0.6.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +106 -80
  2. package/bin/clado.js +35 -3
  3. package/docs/agent-context.md +63 -0
  4. package/docs/agent-reference.md +219 -0
  5. package/docs/release.md +123 -0
  6. package/package.json +5 -3
  7. package/plugins/agent/index.js +2485 -2982
  8. package/plugins/agent/settings.js +3592 -0
  9. package/plugins/agent/style.css +1441 -1315
  10. package/plugins/brand/index.js +84 -466
  11. package/plugins/brand/style.css +39 -172
  12. package/plugins/directory/index.js +10 -10
  13. package/plugins/view-controls/index.js +6 -1
  14. package/plugins/view-controls/style.css +41 -30
  15. package/skills/clado/SKILL.md +4 -2
  16. package/src/agent/automations.js +454 -0
  17. package/src/agent/clado-tools.js +792 -0
  18. package/src/agent/pi-bridge.js +2559 -0
  19. package/src/agent/pi-config.js +2411 -0
  20. package/src/agent/pi-hooks-perms.js +621 -0
  21. package/src/html/app-css.js +69 -1
  22. package/src/html/canvas-chain.js +32 -6
  23. package/src/html/canvas-focus.js +19 -13
  24. package/src/html/canvas-live-diff.js +1373 -0
  25. package/src/html/canvas-ui.css +503 -2
  26. package/src/html/canvas-wires.js +5 -1
  27. package/src/html/page.js +4 -2
  28. package/src/html/plugin-assets.js +5 -1
  29. package/src/html/plugin-ui.css +159 -134
  30. package/src/html/plugin-ui.js +3 -2
  31. package/src/html/runtime-api.js +152 -10
  32. package/src/html/runtime.js +546 -37
  33. package/src/server/agent.js +862 -1566
  34. package/src/server/assets/library-canvas.js +256 -9
  35. package/src/server/assets/library.css +951 -11
  36. package/src/server/assets/library.html +39 -4
  37. package/src/server/assets/library.js +1445 -224
  38. package/src/server/code-inspect.js +183 -0
  39. package/src/server/mcp.js +90 -22
  40. package/src/server/plugin-registry.js +671 -9
  41. package/src/server/plugins.js +1 -1
  42. package/src/server/workspace-hub.js +50 -0
  43. package/src/server/workspace.js +554 -39
  44. package/src/workspace/graph-snapshot.js +695 -0
  45. package/src/workspace/service.js +201 -9
  46. package/src/agent/commands.js +0 -204
  47. package/src/agent/context.js +0 -445
  48. package/src/agent/executors.js +0 -213
  49. package/src/agent/mcp-client.js +0 -308
  50. package/src/agent/probe.js +0 -234
  51. package/src/agent/providers/anthropic.js +0 -220
  52. package/src/agent/providers/index.js +0 -235
  53. package/src/agent/providers/openai.js +0 -146
  54. package/src/agent/runtime.js +0 -995
  55. package/src/agent/sessions.js +0 -336
  56. package/src/agent/skills.js +0 -190
@@ -1,33 +1,120 @@
1
1
  import { createServer } from 'node:http';
2
- import { createHash, randomUUID } from 'node:crypto';
3
- import { readFileSync, statSync, existsSync, mkdirSync } from 'node:fs';
2
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
3
+ import { readFileSync, readdirSync, statSync, existsSync, mkdirSync } from 'node:fs';
4
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 { paragraphs } from '../workspace/content.js';
10
+ import { findNode, treeOf } from '../workspace/tree.js';
11
+ import { blockMedia, mediaPointFits } from '../core/media-links.js';
9
12
  import { contextFor, discoverWorkspaces, initialize } from '../workspace/storage.js';
10
13
  import { deleteCanvasObject, listCanvasObjects, readCanvasObject, saveCanvasObject } from '../workspace/objects.js';
11
14
  import { createWorkspaceService } from '../workspace/service.js';
12
15
  import { createMcpHandler } from './mcp.js';
13
16
  import { builtInCapabilities, builtInGrants, inspectWorkspacePlugins, installWorkspacePlugin, loadWorkspacePlugins } from './plugins.js';
14
- import { installCatalogPlugin, listInstalledWorkspacePlugins, loadRegistryIndex, removeWorkspacePlugin, searchRegistry } from './plugin-registry.js';
17
+ import {
18
+ addPluginSource,
19
+ installCatalogPlugin,
20
+ installLocalMarketItem,
21
+ listInstalledWorkspacePlugins,
22
+ loadRegistryIndex,
23
+ removePluginSource,
24
+ removeWorkspacePlugin,
25
+ scanAllPluginSources,
26
+ searchRegistry,
27
+ togglePluginSource,
28
+ uninstallLocalMarketItem,
29
+ } from './plugin-registry.js';
15
30
  import { createCapabilityRegistry } from './plugin-capabilities.js';
16
- import { createPluginSettings } from './plugin-settings.js';
31
+ import { compileConfiguration, createPluginSettings } from './plugin-settings.js';
17
32
  import { createWorkspaceEvents, broadcastMcpEvent } from './events.js';
18
33
  import {
19
34
  browseLocalFolders,
20
35
  createStarterCanvas,
21
36
  deleteCanvasDocument,
37
+ detectWorkspaceProfile,
22
38
  readRecentWorkspaces,
23
39
  recordRecentWorkspace,
24
40
  renameCanvasDocument,
25
41
  resolveWorkspaceSelection,
26
42
  } from './workspace-hub.js';
43
+ import { readFileGitState, readWorkspaceCodeFile, resolveSymbolInWorkspace } from './code-inspect.js';
27
44
  import { z } from 'zod/v4';
28
45
  const assets = join(dirname(fileURLToPath(import.meta.url)), 'assets');
29
- 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'};
46
+ const resourceTypes = {
47
+ png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', svg: 'image/svg+xml',
48
+ pdf: 'application/pdf', txt: 'text/plain', csv: 'text/csv', json: 'application/json',
49
+ mp4: 'video/mp4', webm: 'video/webm', mov: 'video/quicktime', ogv: 'video/ogg',
50
+ mp3: 'audio/mpeg', wav: 'audio/wav', m4a: 'audio/mp4', ogg: 'audio/ogg', flac: 'audio/flac',
51
+ };
30
52
  const types = { html: 'text/html', css: 'text/css', js: 'text/javascript', json: 'application/json', md: 'text/markdown' };
53
+ const REMOTE_COOKIE = 'clado_remote_token';
54
+ const listWorkspaceFilesCache = new Map();
55
+
56
+ function isTrustedOrigin(req, remote = false) {
57
+ const origin = req.headers.origin;
58
+ if (!origin) return true;
59
+ const host = String(req.headers.host || '').trim();
60
+ if (!host) return false;
61
+ if (origin === 'http://' + host) return true;
62
+ if (!remote) return false;
63
+ const forwardedHost = String(req.headers['x-forwarded-host'] || '').split(',')[0].trim();
64
+ const allowed = new Set([host]);
65
+ if (forwardedHost) allowed.add(forwardedHost);
66
+ for (const h of allowed) {
67
+ if (h && (origin === 'http://' + h || origin === 'https://' + h)) return true;
68
+ }
69
+ return false;
70
+ }
71
+
72
+ function hasTrustedSameOrigin(req, remote = false) {
73
+ return Boolean(req.headers.origin) && isTrustedOrigin(req, remote);
74
+ }
75
+
76
+ function readCookie(req, name) {
77
+ const raw = String(req.headers.cookie || '');
78
+ if (!raw) return '';
79
+ for (const part of raw.split(';')) {
80
+ const idx = part.indexOf('=');
81
+ if (idx < 0) continue;
82
+ if (part.slice(0, idx).trim() === name) {
83
+ try { return decodeURIComponent(part.slice(idx + 1).trim()); } catch { return part.slice(idx + 1).trim(); }
84
+ }
85
+ }
86
+ return '';
87
+ }
88
+
89
+ function safeTokenMatch(candidate, expected) {
90
+ if (!candidate || !expected) return false;
91
+ const a = Buffer.from(String(candidate));
92
+ const b = Buffer.from(String(expected));
93
+ return a.length === b.length && timingSafeEqual(a, b);
94
+ }
95
+
96
+ function renderRemoteUnlockPage(errorMsg = '') {
97
+ const errHtml = errorMsg ? `<p class="err">${String(errorMsg).replace(/[<>&"]/g, '')}</p>` : '';
98
+ return `<!doctype html>
99
+ <html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
100
+ <title>Clado 远程调试验证</title>
101
+ <style>
102
+ *{box-sizing:border-box}body{margin:0;min-height:100dvh;display:grid;place-items:center;padding:20px;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC",sans-serif;background:radial-gradient(circle at 20% 20%,#e0f2fe 0%,#f8fafc 45%,#eef2ff 100%);color:#0f172a}
103
+ .card{width:min(380px,100%);padding:26px 24px;border-radius:22px;background:rgba(255,255,255,.82);backdrop-filter:blur(22px);border:1px solid rgba(148,163,184,.32);box-shadow:0 24px 48px -20px rgba(15,23,42,.22)}
104
+ h1{margin:0 0 6px;font-size:18px;font-weight:650}p{margin:0 0 16px;font-size:13px;line-height:1.55;color:#475569}
105
+ .err{color:#be123c;background:rgba(244,63,94,.1);padding:8px 10px;border-radius:10px;margin-bottom:12px}
106
+ input{width:100%;padding:10px 12px;border-radius:12px;border:1px solid rgba(148,163,184,.45);font:inherit;font-size:14px;outline:none;margin-bottom:12px}
107
+ input:focus{border-color:#0284c7}button{width:100%;padding:10px 14px;border:0;border-radius:12px;background:#0f172a;color:#fff;font:inherit;font-size:14px;font-weight:600;cursor:pointer}
108
+ </style></head><body>
109
+ <form class="card" method="GET" action="/">
110
+ <h1>Clado 远程调试验证</h1>
111
+ <p>当前工作台运行在安全远程模式,请输入终端打印的访问口令(Token)继续。</p>
112
+ ${errHtml}
113
+ <input name="token" type="password" placeholder="粘贴访问口令…" autocomplete="off" required autofocus>
114
+ <button type="submit">进入空间画布</button>
115
+ </form></body></html>`;
116
+ }
117
+
31
118
  const viewSelection = z.object({
32
119
  tab: z.uuid(), file: z.string().min(1), version: z.string().regex(/^[a-f0-9]{64}$/),
33
120
  nodes: z.array(z.array(z.string().min(1)).min(1).max(6)).max(200),
@@ -35,6 +122,8 @@ const viewSelection = z.object({
35
122
  }).strict();
36
123
  export function createWorkspaceHandler(directory, options = {}) {
37
124
  const root = resolve(directory);
125
+ const remote = Boolean(options.remote);
126
+ const remoteToken = remote && options.remoteToken ? String(options.remoteToken) : '';
38
127
  const assetNames = new Set(['library.html','library.css','library.js','library-canvas.js']);
39
128
  if (options.capabilities) assetNames.add('library-plugin-bridge.js');
40
129
  if (options.plugins || options.experimentalPlugins) for (const name of ['library-plugins.js', 'library-plugins.css', 'clado-plugin-sdk.js']) assetNames.add(name);
@@ -49,13 +138,43 @@ export function createWorkspaceHandler(directory, options = {}) {
49
138
  const pluginFile = workspacePluginAssets.get(url.pathname);
50
139
  if (!url.pathname.startsWith('/library/') && !assetNames.has(route) && !pluginFile && !(options.entrypoint && route === '')) return false;
51
140
  try {
52
- const host = req.headers.host;
53
- if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host || '')) throw new DocumentError('只接受本机预览请求。',403);
141
+ const host = String(req.headers.host || '').trim();
142
+ if (remote) {
143
+ if (!host || /[\s/@]/.test(host)) throw new DocumentError('请求主机头不合法。', 403);
144
+ } else if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) {
145
+ throw new DocumentError('只接受本机预览请求。', 403);
146
+ }
147
+ if (remoteToken) {
148
+ const queryToken = url.searchParams.get('token') || '';
149
+ const authHeader = String(req.headers.authorization || '');
150
+ const bearerToken = authHeader.startsWith('Bearer ') ? authHeader.slice(7).trim() : '';
151
+ const cookieToken = readCookie(req, REMOTE_COOKIE);
152
+ if (queryToken && safeTokenMatch(queryToken, remoteToken) && req.method === 'GET') {
153
+ const isHttps = String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim() === 'https';
154
+ const cleanUrl = new URL(url.pathname + url.search, 'http://clado.local');
155
+ cleanUrl.searchParams.delete('token');
156
+ const dest = cleanUrl.pathname + (cleanUrl.search || '');
157
+ const cookie = `${REMOTE_COOKIE}=${encodeURIComponent(remoteToken)}; Path=/; HttpOnly; SameSite=Lax${isHttps ? '; Secure' : ''}`;
158
+ res.writeHead(302, { 'set-cookie': cookie, location: dest, 'cache-control': 'no-store' });
159
+ res.end();
160
+ return true;
161
+ }
162
+ const authed = safeTokenMatch(cookieToken, remoteToken)
163
+ || safeTokenMatch(bearerToken, remoteToken)
164
+ || safeTokenMatch(queryToken, remoteToken);
165
+ if (!authed) {
166
+ if (req.method === 'GET' && String(req.headers.accept || '').includes('text/html')) {
167
+ send(res, 401, types.html, renderRemoteUnlockPage(queryToken ? '口令不正确,请重新输入。' : ''));
168
+ return true;
169
+ }
170
+ throw new DocumentError('需要远程访问口令(token)。', 401);
171
+ }
172
+ }
54
173
  const pluginsEnabled = !!(options.plugins || options.experimentalPlugins);
55
174
  const pluginAsset = pluginsEnabled && url.pathname.startsWith('/library/plugin-assets/');
56
- if (req.headers.origin && req.headers.origin !== 'http://' + host && !(pluginAsset && req.headers.origin === 'null')) throw new DocumentError('来源不匹配。',403);
175
+ if (req.headers.origin && !isTrustedOrigin(req, remote) && !(pluginAsset && req.headers.origin === 'null')) throw new DocumentError('来源不匹配。',403);
57
176
  if (url.pathname === '/library/selection' && options.publishSelection && req.method === 'POST') {
58
- if (req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') throw new DocumentError('选区只接受同源页面请求。', 403);
177
+ if (!hasTrustedSameOrigin(req, remote) || req.headers['content-type'] !== 'application/json') throw new DocumentError('选区只接受同源页面请求。', 403);
59
178
  const target = resolveTarget(url);
60
179
  const chunks = []; let size = 0;
61
180
  for await (const chunk of req) {
@@ -77,7 +196,7 @@ export function createWorkspaceHandler(directory, options = {}) {
77
196
  }
78
197
  if (options.agent && url.pathname === '/library/agent/meta') {
79
198
  const target = resolveTarget(url);
80
- options.agent.handleMeta(req, res, target.workspace); return true;
199
+ await options.agent.handleMeta(req, res, target.workspace); return true;
81
200
  }
82
201
  if (options.agent && url.pathname === '/library/agent/sessions') {
83
202
  const target = resolveTarget(url);
@@ -87,6 +206,10 @@ export function createWorkspaceHandler(directory, options = {}) {
87
206
  const target = resolveTarget(url);
88
207
  await options.agent.handleConfig(req, res, target.workspace); return true;
89
208
  }
209
+ if (options.agent && url.pathname === '/library/agent/automations' && options.agent.handleAutomations) {
210
+ const target = resolveTarget(url);
211
+ await options.agent.handleAutomations(req, res, url, target.workspace); return true;
212
+ }
90
213
  if (options.agent && url.pathname === '/library/agent') {
91
214
  const target = resolveTarget(url);
92
215
  await options.agent.handle(req, res, target.workspace); return true;
@@ -96,7 +219,7 @@ export function createWorkspaceHandler(directory, options = {}) {
96
219
  if (!target.settings) throw new DocumentError('没有这个预览入口;文档操作请使用 /mcp。',404);
97
220
  const id = url.searchParams.get('id');
98
221
  if (req.method === 'GET') { json(res, 200, target.settings.read(id)); return true; }
99
- if (req.method !== 'POST' || req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') {
222
+ if (req.method !== 'POST' || !hasTrustedSameOrigin(req, remote) || req.headers['content-type'] !== 'application/json') {
100
223
  throw new DocumentError('插件设置只接受同源页面写入。', 403);
101
224
  }
102
225
  const chunks = []; let size = 0;
@@ -111,12 +234,12 @@ export function createWorkspaceHandler(directory, options = {}) {
111
234
  }
112
235
  if (options.installPlugin && url.pathname === '/library/install-plugin') {
113
236
  if (req.method === 'DELETE' && options.removePlugin) {
114
- if (req.headers.origin !== 'http://' + host) throw new DocumentError('卸载插件需要在工作区页面操作。', 403);
237
+ if (!hasTrustedSameOrigin(req, remote)) throw new DocumentError('卸载插件需要在工作区页面操作。', 403);
115
238
  const target = resolveTarget(url);
116
239
  json(res, 200, options.removePlugin(target.workspace, url.searchParams.get('id')));
117
240
  return true;
118
241
  }
119
- if (req.method !== 'POST' || req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') {
242
+ if (req.method !== 'POST' || !hasTrustedSameOrigin(req, remote) || req.headers['content-type'] !== 'application/json') {
120
243
  throw new DocumentError('插件安装需要在工作区页面操作。', 403);
121
244
  }
122
245
  const target = resolveTarget(url);
@@ -136,7 +259,7 @@ export function createWorkspaceHandler(directory, options = {}) {
136
259
  return true;
137
260
  }
138
261
  if (req.method === 'POST' && options.installCatalog) {
139
- if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
262
+ if (!hasTrustedSameOrigin(req, remote) || req.headers['content-type']?.split(';')[0] !== 'application/json') {
140
263
  throw new DocumentError('插件市场安装只接受同源页面请求。', 403);
141
264
  }
142
265
  const chunks = []; let size = 0;
@@ -152,6 +275,28 @@ export function createWorkspaceHandler(directory, options = {}) {
152
275
  }
153
276
  throw new DocumentError('插件市场索引仅支持 GET 或 POST。', 405);
154
277
  }
278
+ if (url.pathname === '/library/plugin-sources' && options.pluginSources) {
279
+ const target = resolveTarget(url);
280
+ if (req.method === 'GET') {
281
+ json(res, 200, await options.pluginSources.scan(target.workspace, url.searchParams.get('q') || ''));
282
+ return true;
283
+ }
284
+ if (req.method === 'POST') {
285
+ if (!hasTrustedSameOrigin(req, remote) || req.headers['content-type']?.split(';')[0] !== 'application/json') {
286
+ throw new DocumentError('插件市场源操作只接受同源页面请求。', 403);
287
+ }
288
+ const chunks = []; let size = 0;
289
+ for await (const chunk of req) {
290
+ size += chunk.length;
291
+ if (size > 131072) throw new DocumentError('请求体过大。', 413);
292
+ chunks.push(chunk);
293
+ }
294
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
295
+ json(res, 200, await options.pluginSources.handleAction(target.workspace, body));
296
+ return true;
297
+ }
298
+ throw new DocumentError('插件市场源接口仅支持 GET 或 POST。', 405);
299
+ }
155
300
  if (url.pathname === '/library/objects' && options.canvasObjects) {
156
301
  const target = resolveTarget(url);
157
302
  if (req.method === 'GET') {
@@ -166,7 +311,7 @@ export function createWorkspaceHandler(directory, options = {}) {
166
311
  return true;
167
312
  }
168
313
  if (req.method === 'POST') {
169
- if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
314
+ if (!hasTrustedSameOrigin(req, remote) || req.headers['content-type']?.split(';')[0] !== 'application/json') {
170
315
  throw new DocumentError('画布组件操作只接受同源页面请求。', 403);
171
316
  }
172
317
  const chunks = []; let size = 0;
@@ -193,7 +338,7 @@ export function createWorkspaceHandler(directory, options = {}) {
193
338
  return true;
194
339
  }
195
340
  if (req.method === 'POST') {
196
- if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
341
+ if (!hasTrustedSameOrigin(req, remote) || req.headers['content-type']?.split(';')[0] !== 'application/json') {
197
342
  throw new DocumentError('工作区切换只接受同源页面请求。', 403);
198
343
  }
199
344
  const chunks = []; let size = 0;
@@ -231,7 +376,7 @@ export function createWorkspaceHandler(directory, options = {}) {
231
376
  const target = resolveTarget(url);
232
377
  options.capabilities.connect(view.data, res, target.workspace, target.workspaceId); return true;
233
378
  }
234
- if (req.method !== 'POST' || req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') {
379
+ if (req.method !== 'POST' || !hasTrustedSameOrigin(req, remote) || req.headers['content-type'] !== 'application/json') {
235
380
  throw new DocumentError('插件通信只接受同源页面请求。', 403);
236
381
  }
237
382
  const captureId = url.searchParams.get('captureId');
@@ -250,6 +395,21 @@ export function createWorkspaceHandler(directory, options = {}) {
250
395
  json(res, 200, await options.capabilities.receive(view.data, message));
251
396
  return true;
252
397
  }
398
+ if (options.linkNode && url.pathname === '/library/link') {
399
+ if (req.method !== 'POST' || !hasTrustedSameOrigin(req, remote) || req.headers['content-type']?.split(';')[0] !== 'application/json') {
400
+ throw new DocumentError('画布连线只接受同源页面 POST 请求。', 403);
401
+ }
402
+ const chunks = []; let size = 0;
403
+ for await (const chunk of req) {
404
+ size += chunk.length;
405
+ if (size > 65536) throw new DocumentError('连线参数过大。', 413);
406
+ chunks.push(chunk);
407
+ }
408
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
409
+ const target = resolveTarget(url);
410
+ json(res, 200, await options.linkNode(target, body));
411
+ return true;
412
+ }
253
413
  if (req.method !== 'GET' && req.method !== 'HEAD') throw new DocumentError('不支持这个请求方法。',405);
254
414
  if (url.pathname === '/library/workspaces.json') {
255
415
  const workspaces = options.listWorkspaces
@@ -257,6 +417,65 @@ export function createWorkspaceHandler(directory, options = {}) {
257
417
  : [{ id: '', name: basename(root), workspace: root, documentRoot: root, documents: scanDirectory(root).documents.length }];
258
418
  json(res, 200, { scope: options.scopeName ? (typeof options.scopeName === 'function' ? options.scopeName() : options.scopeName) : basename(root), workspaces }); return true;
259
419
  }
420
+ if (url.pathname === '/library/code-file') {
421
+ const target = resolveTarget(url);
422
+ const relPath = url.searchParams.get('path');
423
+ const symbol = url.searchParams.get('symbol');
424
+ const data = relPath
425
+ ? readWorkspaceCodeFile(target.workspace, relPath)
426
+ : resolveSymbolInWorkspace(target.workspace, symbol);
427
+ let git = null;
428
+ try { git = readFileGitState(target.workspace, data.path); } catch {}
429
+ json(res, 200, {
430
+ ...data,
431
+ gitDiff: git?.gitDiff || '',
432
+ headContent: git?.headContent ?? null,
433
+ changed: Boolean(git?.changed),
434
+ });
435
+ return true;
436
+ }
437
+ if (url.pathname === '/library/git-diff') {
438
+ const target = resolveTarget(url);
439
+ const relPath = url.searchParams.get('path');
440
+ if (!relPath) throw new DocumentError('缺少 path 参数。', 400);
441
+ json(res, 200, readFileGitState(target.workspace, relPath));
442
+ return true;
443
+ }
444
+ if (url.pathname === '/library/workspace-files') {
445
+ const target = resolveTarget(url);
446
+ const q = String(url.searchParams.get('q') || '').trim().toLowerCase();
447
+ const cache = listWorkspaceFilesCache.get(target.workspace);
448
+ const now = Date.now();
449
+ let files;
450
+ if (cache && now - cache.ts < 5000) {
451
+ files = cache.files;
452
+ } else {
453
+ files = [];
454
+ const skipDirs = new Set(['.git', 'node_modules', 'dist', 'build', '.next', '.nuxt', '.cache', 'coverage', '.venv', 'venv', '__pycache__', 'target', 'vendor', '.clado', '.pi']);
455
+ const walk = (dir, depth) => {
456
+ if (depth > 5 || files.length >= 400) return;
457
+ let entries;
458
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
459
+ for (const ent of entries) {
460
+ if (files.length >= 400) break;
461
+ if (ent.name.startsWith('.') && ent.name !== '.env.example') continue;
462
+ if (skipDirs.has(ent.name)) continue;
463
+ const full = join(dir, ent.name);
464
+ if (ent.isDirectory()) {
465
+ walk(full, depth + 1);
466
+ } else if (ent.isFile()) {
467
+ files.push(relative(target.workspace, full).split(sep).join('/'));
468
+ }
469
+ }
470
+ };
471
+ walk(target.workspace, 0);
472
+ files.sort((a, b) => a.localeCompare(b));
473
+ listWorkspaceFilesCache.set(target.workspace, { ts: now, files });
474
+ }
475
+ const matched = q ? files.filter(f => f.toLowerCase().includes(q)) : files;
476
+ json(res, 200, { files: matched.slice(0, 80), total: matched.length });
477
+ return true;
478
+ }
260
479
  if (pluginsEnabled && url.pathname === '/library/plugins.json') {
261
480
  const target = resolveTarget(url);
262
481
  const values = target.settings?.values() || {};
@@ -301,11 +520,15 @@ export function createWorkspaceHandler(directory, options = {}) {
301
520
  const path=workspacePath(target.root,name,false,true);
302
521
  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;
303
522
  }
304
- if (!['/library/source.mdc','/library/canvas'].includes(url.pathname)) throw new DocumentError('没有这个预览入口;文档操作请使用 /mcp。',404);
523
+ if (!['/library/source.mdc','/library/canvas','/library/doc.json'].includes(url.pathname)) throw new DocumentError('没有这个预览入口;文档操作请使用 /mcp。',404);
305
524
  const target = resolveTarget(url);
306
525
  const file = workspacePath(target.root,name), item = readDocument(file);
307
526
  if (url.pathname === '/library/source.mdc') { send(res,200,types.md,item.source); return true; }
308
527
  if (item.diagnostics.some(d=>d.severity==='error')) throw new DocumentError('文档暂时无法解析。',422,item.diagnostics);
528
+ if (url.pathname === '/library/doc.json') {
529
+ json(res, 200, { file: name, version: item.version, doc: item.doc, diagnostics: item.diagnostics });
530
+ return true;
531
+ }
309
532
  const mode = ['cards','mindmap','doc'].includes(url.searchParams.get('mode')) ? url.searchParams.get('mode') : (options.mode || 'cards');
310
533
  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'});
311
534
  const bodyEnd = html.lastIndexOf('</body>');
@@ -316,7 +539,12 @@ export function createWorkspaceHandler(directory, options = {}) {
316
539
  }
317
540
  };
318
541
  }
319
- export async function startWorkspace(input, { port = 4317, mode = 'cards', theme = 'light', entry, project = false, hubMode = false, experimentalPlugins = false, agent: agentName = 'acp' } = {}) {
542
+ export async function startWorkspace(input, { port = 4317, host = '', remote = false, token = '', noToken = false, mode = 'cards', theme = 'light', entry, project = false, hubMode = false, experimentalPlugins = false, agent: agentName = 'pi' } = {}) {
543
+ const isRemote = Boolean(remote);
544
+ const remoteToken = isRemote && !noToken
545
+ ? (String(token || '').trim() || randomBytes(12).toString('hex'))
546
+ : '';
547
+ const listenHost = String(host || '').trim() || (isRemote ? '0.0.0.0' : '127.0.0.1');
320
548
  const path = resolve(input);
321
549
  if (!existsSync(path) && !/\.mdc?$/i.test(path)) mkdirSync(path, { recursive: true });
322
550
  if (statSync(path).isFile() && !/\.mdc?$/i.test(path)) throw new DocumentError('serve 文件需要 .mdc 或 .md 扩展名。');
@@ -329,11 +557,30 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
329
557
  let rootCtx = contextFor(workspace, workspace, root); initialize(rootCtx);
330
558
  if (!activeHubMode) recordRecentWorkspace(workspace);
331
559
  const runtimes = new Map();
560
+ function registerInstalledPluginConfigs(stateDir, wsSettings) {
561
+ if (!wsSettings || !stateDir) return;
562
+ const pluginsDir = join(stateDir, 'plugins');
563
+ if (!existsSync(pluginsDir)) return;
564
+ try {
565
+ for (const ent of readdirSync(pluginsDir, { withFileTypes: true })) {
566
+ if (!ent.isDirectory() || ent.name.startsWith('.')) continue;
567
+ const mPath = join(pluginsDir, ent.name, 'clado-plugin.json');
568
+ if (!existsSync(mPath)) continue;
569
+ try {
570
+ const manifest = JSON.parse(readFileSync(mPath, 'utf8'));
571
+ if (manifest?.id && manifest?.configuration?.schema) {
572
+ wsSettings.register(manifest.id, compileConfiguration(manifest.configuration));
573
+ }
574
+ } catch {}
575
+ }
576
+ } catch {}
577
+ }
332
578
  function runtimeFor(ctx) {
333
579
  const existing = runtimes.get(ctx.workspace);
334
580
  if (existing) { existing.ctx = ctx; existing.root = ctx.documents; return existing; }
335
581
  const wsPlugins = experimentalPlugins ? loadWorkspacePlugins(ctx.state) : null;
336
582
  const wsSettings = createPluginSettings(ctx, wsPlugins?.configurations);
583
+ registerInstalledPluginConfigs(ctx.state, wsSettings);
337
584
  const wsGrants = builtInGrants();
338
585
  for (const { id, permissions } of wsPlugins?.descriptor.plugins || []) wsGrants.set(id, permissions);
339
586
  const wsProviders = [...builtInCapabilities(agentName !== 'off'), ...(wsPlugins?.capabilities || [])];
@@ -391,7 +638,40 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
391
638
  return current?.expiresAt > Date.now() ? current : null;
392
639
  };
393
640
  const events = createWorkspaceEvents();
641
+ let agent = null;
394
642
  let baseService = createWorkspaceService(workspace, { documentRoot: root, readSelection });
643
+ const emitWorkspaceSystemEvents = (targetWorkspace, tool, input, result, sourceMeta = {}) => {
644
+ if (!agent?.notifySystemEvent || !result || input?.dryRun) return;
645
+ const file = String(input?.file || result?.changes?.[0]?.file || '').trim();
646
+ if (Array.isArray(result.cardChanges) && result.cardChanges.length) {
647
+ for (const ch of result.cardChanges) {
648
+ agent.notifySystemEvent(targetWorkspace, `card.${ch.action}`, {
649
+ file: ch.file,
650
+ card: ch.card,
651
+ addedTags: ch.addedTags,
652
+ removedTags: ch.removedTags,
653
+ ...sourceMeta,
654
+ });
655
+ if ((ch.addedTags?.length || 0) > 0 || (ch.removedTags?.length || 0) > 0) {
656
+ agent.notifySystemEvent(targetWorkspace, 'tag.changed', {
657
+ file: ch.file,
658
+ card: ch.card,
659
+ addedTags: ch.addedTags,
660
+ removedTags: ch.removedTags,
661
+ ...sourceMeta,
662
+ });
663
+ }
664
+ }
665
+ }
666
+ if (tool === 'clado_documents') {
667
+ const map = { create: 'doc.created', update: 'doc.updated', rename: 'doc.renamed', delete: 'doc.deleted' };
668
+ const evt = map[input?.action];
669
+ if (evt) agent.notifySystemEvent(targetWorkspace, evt, { file, ...sourceMeta });
670
+ } else if (tool === 'clado_links') {
671
+ if (input?.action === 'connect') agent.notifySystemEvent(targetWorkspace, 'link.connected', { file, card: input?.node?.[0] || '', ...sourceMeta });
672
+ if (input?.action === 'disconnect') agent.notifySystemEvent(targetWorkspace, 'link.disconnected', { file, card: input?.node?.[0] || '', ...sourceMeta });
673
+ }
674
+ };
395
675
  const mcpService = async (tool, input = {}) => {
396
676
  const result = await baseService(tool, input);
397
677
  try {
@@ -401,33 +681,105 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
401
681
  return result;
402
682
  };
403
683
  mcpService.diagnostics = (...a) => baseService.diagnostics(...a);
684
+
685
+ const externalMcpService = async (tool, input = {}) => {
686
+ const targetWorkspace = input?.workspace ? resolve(input.workspace) : workspace;
687
+ const isWrite = !input?.dryRun && (
688
+ tool === 'clado_batch'
689
+ || (tool === 'clado_documents' && ['create', 'copy', 'update', 'rename', 'delete'].includes(input?.action))
690
+ || (tool === 'clado_nodes' && ['create', 'insert', 'update', 'rename', 'move', 'delete'].includes(input?.action))
691
+ || (tool === 'clado_links' && ['connect', 'disconnect'].includes(input?.action))
692
+ );
693
+ const mcpCards = [];
694
+ if (Array.isArray(input?.node) && input.node.length) mcpCards.push(String(input.node[0]));
695
+ if (Array.isArray(input?.targetNode) && input.targetNode.length && !input.targetFile) mcpCards.push(String(input.targetNode[0]));
696
+ if (input?.title) mcpCards.push(String(input.title));
697
+ const mcpVerb = input?.action === 'delete' ? '正在删除'
698
+ : input?.action === 'create' ? '正在新建'
699
+ : input?.action === 'connect' ? '正在连线'
700
+ : input?.action === 'disconnect' ? '正在移除连线'
701
+ : '正在编辑';
702
+ const mcpSessionId = 'mcp_external';
703
+ if (isWrite && mcpCards.length) {
704
+ events.emit(targetWorkspace, 'agent.presence', {
705
+ sessionId: mcpSessionId,
706
+ roleId: 'mcp',
707
+ roleName: '外部 MCP',
708
+ tone: 'amber',
709
+ file: String(input?.file || ''),
710
+ cards: [...new Set(mcpCards)],
711
+ label: mcpVerb,
712
+ phase: 'active',
713
+ ts: Date.now(),
714
+ });
715
+ }
716
+ try {
717
+ const result = await mcpService(tool, input);
718
+ if (isWrite) {
719
+ const resultCards = Array.isArray(result?.cardChanges)
720
+ ? [...new Set(result.cardChanges.map(c => c.card).filter(Boolean))]
721
+ : [];
722
+ if (resultCards.length) {
723
+ events.emit(targetWorkspace, 'agent.presence', {
724
+ sessionId: mcpSessionId,
725
+ roleId: 'mcp',
726
+ roleName: '外部 MCP',
727
+ tone: 'amber',
728
+ file: String(result.cardChanges[0]?.file || input?.file || ''),
729
+ cards: resultCards,
730
+ label: mcpVerb,
731
+ phase: 'active',
732
+ ts: Date.now(),
733
+ });
734
+ }
735
+ events.emit(targetWorkspace, 'agent.presence', {
736
+ sessionId: mcpSessionId,
737
+ roleId: 'mcp',
738
+ roleName: '外部 MCP',
739
+ tone: 'amber',
740
+ file: String(input?.file || ''),
741
+ cards: [],
742
+ label: '刚刚编辑了',
743
+ phase: 'afterglow',
744
+ ts: Date.now(),
745
+ });
746
+ emitWorkspaceSystemEvents(targetWorkspace, tool, input, result, { originRoleId: 'mcp', originSessionId: mcpSessionId });
747
+ }
748
+ return result;
749
+ } catch (err) {
750
+ if (isWrite) {
751
+ events.emit(targetWorkspace, 'agent.presence', {
752
+ sessionId: mcpSessionId,
753
+ roleId: 'mcp',
754
+ roleName: '外部 MCP',
755
+ tone: 'amber',
756
+ file: String(input?.file || ''),
757
+ cards: [],
758
+ label: '刚刚编辑了',
759
+ phase: 'afterglow',
760
+ ts: Date.now(),
761
+ });
762
+ }
763
+ throw err;
764
+ }
765
+ };
766
+ externalMcpService.diagnostics = (...a) => baseService.diagnostics(...a);
767
+
404
768
  const liveMcpUrl = () => 'http://127.0.0.1:' + server.address().port + '/mcp';
405
- const agent = agentName !== 'off' ? (await import('./agent.js')).createAgentHandler({
769
+ agent = agentName !== 'off' ? (await import('./agent.js')).createAgentHandler({
406
770
  workspace: () => workspace,
407
771
  mcpUrl: liveMcpUrl,
408
772
  workspaceService: mcpService,
409
773
  events,
410
- resolveSettings: () => rootRuntime.settings.agentLaunch(),
411
- saveSettings: updater => {
412
- const cur = rootRuntime.settings.read('clado.agent');
413
- const next = updater(cur.value);
414
- return rootRuntime.settings.save('clado.agent', next, cur.value).value;
415
- },
774
+ remote: isRemote,
416
775
  resolveRuntimeInfo: targetWorkspace => {
417
776
  const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
418
777
  return {
419
778
  stateDir: rt.ctx.state,
420
779
  documentRoot: rt.root,
421
780
  pluginDescriptors: rt.plugins?.descriptor.plugins || [],
422
- pluginDirs: rt.plugins?.pluginDirs || [],
423
- pluginMcp: rt.plugins?.pluginMcp || [],
424
- pluginPersonas: rt.plugins?.pluginPersonas || [],
425
781
  };
426
782
  },
427
- ...(agentName === 'acp' && { resolveLaunch: () => {
428
- const { command, args, env } = rootRuntime.settings.agentLaunch();
429
- return { command, args, env };
430
- } }),
431
783
  }) : null;
432
784
  function installPlugin(targetWorkspace, files) {
433
785
  const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
@@ -484,8 +836,72 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
484
836
  rt.settings.register(installed.id, rt.plugins.configurations.get(installed.id));
485
837
  }
486
838
  }
839
+ registerInstalledPluginConfigs(rt.ctx.state, rt.settings);
487
840
  return installed;
488
841
  }
842
+ const pluginSources = {
843
+ async scan(targetWorkspace, query = '') {
844
+ const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
845
+ return await scanAllPluginSources({ workspace: rt.workspace, stateDir: rt.ctx.state, query });
846
+ },
847
+ async handleAction(targetWorkspace, body = {}) {
848
+ const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
849
+ const action = String(body?.action || '').trim();
850
+ if (action === 'add') {
851
+ const res = addPluginSource(body);
852
+ const scan = await scanAllPluginSources({ workspace: rt.workspace, stateDir: rt.ctx.state, query: body.q || '' });
853
+ return { ok: true, ...res, ...scan };
854
+ }
855
+ if (action === 'remove') {
856
+ const res = removePluginSource(body.id);
857
+ const scan = await scanAllPluginSources({ workspace: rt.workspace, stateDir: rt.ctx.state, query: body.q || '' });
858
+ return { ok: true, ...res, ...scan };
859
+ }
860
+ if (action === 'toggle') {
861
+ const res = togglePluginSource(body.id, body.enabled);
862
+ const scan = await scanAllPluginSources({ workspace: rt.workspace, stateDir: rt.ctx.state, query: body.q || '' });
863
+ return { ok: true, ...res, ...scan };
864
+ }
865
+ if (action === 'install_item') {
866
+ const item = body.item || body;
867
+ const previous = rt.plugins?.capabilities.length || 0;
868
+ const installed = await installLocalMarketItem(item, {
869
+ ctx: rt.ctx,
870
+ runtime: rt.plugins,
871
+ workspace: rt.workspace,
872
+ stateDir: rt.ctx.state,
873
+ scope: body.scope || 'user',
874
+ });
875
+ if (item.kind === 'clado-plugin') {
876
+ const pluginId = installed?.result?.id || item.id;
877
+ if (rt.plugins && pluginId) {
878
+ const descriptor = rt.plugins.descriptor.plugins.find(p => p.id === pluginId);
879
+ if (descriptor) {
880
+ rt.grants.set(pluginId, descriptor.permissions);
881
+ rt.providers.push(...rt.plugins.capabilities.slice(previous));
882
+ rt.settings.register(pluginId, rt.plugins.configurations.get(pluginId));
883
+ }
884
+ }
885
+ registerInstalledPluginConfigs(rt.ctx.state, rt.settings);
886
+ }
887
+ await agent?.reloadWorkspace?.(rt.workspace).catch(() => {});
888
+ const scan = await scanAllPluginSources({ workspace: rt.workspace, stateDir: rt.ctx.state, query: body.q || '' });
889
+ return { ok: true, installed, ...scan };
890
+ }
891
+ if (action === 'uninstall_item') {
892
+ const item = body.item || body;
893
+ const uninstalled = await uninstallLocalMarketItem(item, {
894
+ ctx: rt.ctx,
895
+ removePluginFn: id => removePlugin(rt.workspace, id),
896
+ workspace: rt.workspace,
897
+ });
898
+ await agent?.reloadWorkspace?.(rt.workspace).catch(() => {});
899
+ const scan = await scanAllPluginSources({ workspace: rt.workspace, stateDir: rt.ctx.state, query: body.q || '' });
900
+ return { ok: true, uninstalled, ...scan };
901
+ }
902
+ throw new DocumentError(`不支持的插件市场源操作:${action}`, 400);
903
+ },
904
+ };
489
905
  const canvasObjects = {
490
906
  list(targetWorkspace) {
491
907
  const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
@@ -513,6 +929,7 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
513
929
  return {
514
930
  currentWorkspace: workspace,
515
931
  currentName: basename(workspace),
932
+ currentProfile: detectWorkspaceProfile(workspace),
516
933
  hubMode: activeHubMode,
517
934
  recentWorkspaces: readRecentWorkspaces(),
518
935
  ...browseLocalFolders(dir || workspace),
@@ -564,10 +981,102 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
564
981
  return { ok: true, ...removed };
565
982
  },
566
983
  };
984
+ async function linkNode(target, body = {}) {
985
+ const file = String(body.file || '').trim();
986
+ const rawNode = Array.isArray(body.node) && body.node.length ? body.node : body.sourceNode;
987
+ const node = Array.isArray(rawNode) && rawNode.length ? rawNode.map(String) : null;
988
+ if (!file || !node) throw new DocumentError('缺少源画布文件或源节点路径。', 400);
989
+ const targetNode = Array.isArray(body.targetNode) && body.targetNode.length ? body.targetNode.map(String) : undefined;
990
+ const targetFile = body.targetFile ? String(body.targetFile).trim() : undefined;
991
+ const rawTag = body.targetTag || body.targetTagId || '';
992
+ const targetTag = rawTag ? String(rawTag).trim().replace(/^#/, '') : '';
993
+ const anchor = typeof body.anchor === 'string' && body.anchor.trim() ? body.anchor.trim() : '';
994
+ let sourcePoint = body.sourcePoint && typeof body.sourcePoint === 'object' ? { ...body.sourcePoint } : undefined;
995
+ let targetPoint = body.targetPoint && typeof body.targetPoint === 'object' ? { ...body.targetPoint } : undefined;
996
+ const rawLabel = String(body.label || anchor || targetTag || targetNode?.at(-1) || '').replace(/[\r\n\[\]]/g, '').trim();
997
+ const label = rawLabel || '关联';
998
+ const docSummary = await mcpService('clado_documents', { workspace: target.workspace, action: 'read', file, view: 'summary' });
999
+ const expectedFileVersion = docSummary?.version;
1000
+
1001
+ // 自动把前端传入的「第 N 个代码块/表格/Mermaid」映射为节点正文中的真实段落序号,并规范 Mermaid nodeId 字段
1002
+ const resolveMediaPoint = (nodePath, pt) => {
1003
+ if (!pt || !nodePath) return pt;
1004
+ const next = { ...pt };
1005
+ if (next.kind === 'mermaid' && next.node && !next.nodeId) {
1006
+ next.nodeId = next.node;
1007
+ delete next.node;
1008
+ }
1009
+ if (next.kind === 'line') return next;
1010
+ try {
1011
+ const full = workspacePath(target.root, file);
1012
+ const tree = treeOf(readFileSync(full, 'utf8'), file);
1013
+ const rec = findNode(tree, nodePath);
1014
+ if (!rec?.node?.content) return next;
1015
+ const blocks = paragraphs(rec.node.content);
1016
+ const direct = blocks[(next.paragraph || 1) - 1];
1017
+ if (direct && mediaPointFits(blockMedia(direct.text), next)) return next;
1018
+ const sameKind = blocks.filter(b => blockMedia(b.text)?.kind === next.kind);
1019
+ const byKindIdx = sameKind[(next.paragraph || 1) - 1];
1020
+ if (byKindIdx && mediaPointFits(blockMedia(byKindIdx.text), next)) {
1021
+ return { ...next, paragraph: byKindIdx.index };
1022
+ }
1023
+ const firstFit = sameKind.find(b => mediaPointFits(blockMedia(b.text), next));
1024
+ if (firstFit) return { ...next, paragraph: firstFit.index };
1025
+ } catch {}
1026
+ return next;
1027
+ };
1028
+ if (sourcePoint) sourcePoint = resolveMediaPoint(node, sourcePoint);
1029
+ if (targetPoint && targetNode) targetPoint = resolveMediaPoint(targetNode, targetPoint);
1030
+
1031
+ // Direct Tag link in prose (no media sourcePoint): write clean [label](#tagId)
1032
+ if (targetTag && !sourcePoint && !targetPoint) {
1033
+ const tagLink = `[${label}](#${targetTag})`;
1034
+ if (anchor) {
1035
+ const res = await mcpService('clado_nodes', {
1036
+ workspace: target.workspace,
1037
+ action: 'update',
1038
+ file,
1039
+ node,
1040
+ content: tagLink,
1041
+ position: { mode: 'replace', anchor },
1042
+ expectedFileVersion,
1043
+ });
1044
+ events.emit(target.workspace, 'doc.updated', { file, action: 'link', nodes: [node], label: '已连接到 #' + targetTag });
1045
+ return { ok: true, file, mode: 'tag-replace', ...res };
1046
+ }
1047
+ const res = await mcpService('clado_nodes', {
1048
+ workspace: target.workspace,
1049
+ action: 'insert',
1050
+ file,
1051
+ node,
1052
+ content: tagLink,
1053
+ expectedFileVersion,
1054
+ });
1055
+ events.emit(target.workspace, 'doc.updated', { file, action: 'link', nodes: [node], label: '已连接到 #' + targetTag });
1056
+ return { ok: true, file, mode: 'tag-append', ...res };
1057
+ }
1058
+
1059
+ if (!targetNode && !targetFile) throw new DocumentError('缺少目标卡片、小节或语义 Tag。', 400);
1060
+ const res = await mcpService('clado_links', {
1061
+ workspace: target.workspace,
1062
+ action: 'connect',
1063
+ file,
1064
+ node,
1065
+ ...(targetFile ? { targetFile } : {}),
1066
+ ...(targetNode ? { targetNode } : {}),
1067
+ label,
1068
+ ...(sourcePoint ? { sourcePoint } : (anchor ? { position: { mode: 'replace', anchor } } : {})),
1069
+ ...(targetPoint ? { targetPoint } : {}),
1070
+ ...(expectedFileVersion ? { expectedFileVersion } : {}),
1071
+ });
1072
+ events.emit(target.workspace, 'doc.updated', { file, action: 'link', nodes: [node, ...(targetNode ? [targetNode] : [])], label: '已建立新连线' });
1073
+ return { ok: true, file, mode: sourcePoint ? 'media-point' : (anchor ? 'anchor-replace' : 'card-link'), ...res };
1074
+ }
567
1075
  const handle = createWorkspaceHandler(root,{
568
- entrypoint:true,mode,theme,entry:entryFile,publishSelection,events,
1076
+ entrypoint:true,mode,theme,entry:entryFile,publishSelection,events,linkNode,
1077
+ remote:isRemote,remoteToken,
569
1078
  plugins:rootRuntime.plugins,experimentalPlugins,servePluginAsset,
570
- agent,agentProfile:agentName,capabilities,settings:rootRuntime.settings,installPlugin,removePlugin,readPluginRegistry,installCatalog,canvasObjects,workspaceHub,
1079
+ agent,agentProfile:agentName,capabilities,settings:rootRuntime.settings,installPlugin,removePlugin,readPluginRegistry,installCatalog,pluginSources,canvasObjects,workspaceHub,
571
1080
  mcpUrl:liveMcpUrl,
572
1081
  hubMode:() => activeHubMode,
573
1082
  resolveWorkspace:resolveWorkspaceParam,
@@ -575,15 +1084,21 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
575
1084
  scopeName:() => basename(workspace),
576
1085
  inactivePlugins:() => rootRuntime.inactivePlugins(),
577
1086
  });
578
- const mcp = createMcpHandler(mcpService, capabilities.invoke);
1087
+ const mcp = createMcpHandler(externalMcpService, capabilities.invoke, {
1088
+ remote: isRemote,
1089
+ remoteToken,
1090
+ invokeSession: agent ? args => agent.handleMcpSessions(args) : null,
1091
+ invokeAutomation: agent ? args => agent.handleMcpAutomations(args) : null,
1092
+ });
579
1093
  const server = createServer(async (req,res) => {
580
1094
  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'); } }
581
1095
  catch { if (!res.headersSent) res.writeHead(500);res.end('预览请求失败'); }
582
1096
  });
583
1097
  if (agent) server.on('close', agent.close);
584
1098
  server.on('close', events.close);
585
- await new Promise((resolve,reject) => { server.once('error',reject); server.listen(port,'127.0.0.1',resolve); });
1099
+ await new Promise((resolve,reject) => { server.once('error',reject); server.listen(port,listenHost,resolve); });
586
1100
  const file = entryFile ? '?file='+encodeURIComponent(entryFile) : '';
587
- const origin = 'http://127.0.0.1:'+server.address().port;
588
- return {server,url:origin+'/'+file,mcpUrl:origin+'/mcp',workspace,root,pluginWarnings:rootRuntime.plugins?.warnings || [],stopAgent:agent?.close,stopCapabilities:capabilities.close,stopEvents:events.close};
1101
+ const actualPort = server.address().port;
1102
+ const origin = 'http://127.0.0.1:'+actualPort;
1103
+ return {server,url:origin+'/'+file,mcpUrl:origin+'/mcp',workspace,root,remote:isRemote,remoteToken,listenHost,pluginWarnings:rootRuntime.plugins?.warnings || [],stopAgent:agent?.close,stopCapabilities:capabilities.close,stopEvents:events.close};
589
1104
  }