cladogram 0.6.0-beta.1 → 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 (39) hide show
  1. package/README.md +50 -47
  2. package/bin/clado.js +34 -2
  3. package/docs/agent-context.md +63 -0
  4. package/docs/agent-reference.md +219 -0
  5. package/docs/release.md +116 -0
  6. package/package.json +3 -1
  7. package/plugins/agent/index.js +2429 -723
  8. package/plugins/agent/settings.js +3592 -0
  9. package/plugins/agent/style.css +1327 -94
  10. package/plugins/view-controls/index.js +0 -11
  11. package/plugins/view-controls/style.css +7 -14
  12. package/skills/clado/SKILL.md +4 -2
  13. package/src/agent/automations.js +454 -0
  14. package/src/agent/clado-tools.js +597 -104
  15. package/src/agent/pi-bridge.js +2184 -112
  16. package/src/agent/pi-config.js +1889 -108
  17. package/src/agent/pi-hooks-perms.js +621 -0
  18. package/src/html/app-css.js +69 -1
  19. package/src/html/canvas-chain.js +32 -6
  20. package/src/html/canvas-focus.js +19 -13
  21. package/src/html/canvas-live-diff.js +1373 -0
  22. package/src/html/canvas-ui.css +503 -2
  23. package/src/html/canvas-wires.js +5 -1
  24. package/src/html/page.js +4 -2
  25. package/src/html/plugin-assets.js +5 -1
  26. package/src/html/plugin-ui.css +1 -1
  27. package/src/html/runtime-api.js +152 -10
  28. package/src/html/runtime.js +546 -37
  29. package/src/server/agent.js +594 -37
  30. package/src/server/assets/library-canvas.js +256 -9
  31. package/src/server/assets/library.css +567 -12
  32. package/src/server/assets/library.html +2 -0
  33. package/src/server/assets/library.js +1028 -32
  34. package/src/server/code-inspect.js +183 -0
  35. package/src/server/mcp.js +90 -22
  36. package/src/server/plugin-registry.js +664 -2
  37. package/src/server/workspace.js +551 -25
  38. package/src/workspace/graph-snapshot.js +695 -0
  39. package/src/workspace/service.js +201 -9
@@ -1,19 +1,34 @@
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,
@@ -25,10 +40,81 @@ import {
25
40
  renameCanvasDocument,
26
41
  resolveWorkspaceSelection,
27
42
  } from './workspace-hub.js';
43
+ import { readFileGitState, readWorkspaceCodeFile, resolveSymbolInWorkspace } from './code-inspect.js';
28
44
  import { z } from 'zod/v4';
29
45
  const assets = join(dirname(fileURLToPath(import.meta.url)), 'assets');
30
- 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
+ };
31
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
+
32
118
  const viewSelection = z.object({
33
119
  tab: z.uuid(), file: z.string().min(1), version: z.string().regex(/^[a-f0-9]{64}$/),
34
120
  nodes: z.array(z.array(z.string().min(1)).min(1).max(6)).max(200),
@@ -36,6 +122,8 @@ const viewSelection = z.object({
36
122
  }).strict();
37
123
  export function createWorkspaceHandler(directory, options = {}) {
38
124
  const root = resolve(directory);
125
+ const remote = Boolean(options.remote);
126
+ const remoteToken = remote && options.remoteToken ? String(options.remoteToken) : '';
39
127
  const assetNames = new Set(['library.html','library.css','library.js','library-canvas.js']);
40
128
  if (options.capabilities) assetNames.add('library-plugin-bridge.js');
41
129
  if (options.plugins || options.experimentalPlugins) for (const name of ['library-plugins.js', 'library-plugins.css', 'clado-plugin-sdk.js']) assetNames.add(name);
@@ -50,13 +138,43 @@ export function createWorkspaceHandler(directory, options = {}) {
50
138
  const pluginFile = workspacePluginAssets.get(url.pathname);
51
139
  if (!url.pathname.startsWith('/library/') && !assetNames.has(route) && !pluginFile && !(options.entrypoint && route === '')) return false;
52
140
  try {
53
- const host = req.headers.host;
54
- 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
+ }
55
173
  const pluginsEnabled = !!(options.plugins || options.experimentalPlugins);
56
174
  const pluginAsset = pluginsEnabled && url.pathname.startsWith('/library/plugin-assets/');
57
- 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);
58
176
  if (url.pathname === '/library/selection' && options.publishSelection && req.method === 'POST') {
59
- 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);
60
178
  const target = resolveTarget(url);
61
179
  const chunks = []; let size = 0;
62
180
  for await (const chunk of req) {
@@ -88,6 +206,10 @@ export function createWorkspaceHandler(directory, options = {}) {
88
206
  const target = resolveTarget(url);
89
207
  await options.agent.handleConfig(req, res, target.workspace); return true;
90
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
+ }
91
213
  if (options.agent && url.pathname === '/library/agent') {
92
214
  const target = resolveTarget(url);
93
215
  await options.agent.handle(req, res, target.workspace); return true;
@@ -97,7 +219,7 @@ export function createWorkspaceHandler(directory, options = {}) {
97
219
  if (!target.settings) throw new DocumentError('没有这个预览入口;文档操作请使用 /mcp。',404);
98
220
  const id = url.searchParams.get('id');
99
221
  if (req.method === 'GET') { json(res, 200, target.settings.read(id)); return true; }
100
- 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') {
101
223
  throw new DocumentError('插件设置只接受同源页面写入。', 403);
102
224
  }
103
225
  const chunks = []; let size = 0;
@@ -112,12 +234,12 @@ export function createWorkspaceHandler(directory, options = {}) {
112
234
  }
113
235
  if (options.installPlugin && url.pathname === '/library/install-plugin') {
114
236
  if (req.method === 'DELETE' && options.removePlugin) {
115
- if (req.headers.origin !== 'http://' + host) throw new DocumentError('卸载插件需要在工作区页面操作。', 403);
237
+ if (!hasTrustedSameOrigin(req, remote)) throw new DocumentError('卸载插件需要在工作区页面操作。', 403);
116
238
  const target = resolveTarget(url);
117
239
  json(res, 200, options.removePlugin(target.workspace, url.searchParams.get('id')));
118
240
  return true;
119
241
  }
120
- 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') {
121
243
  throw new DocumentError('插件安装需要在工作区页面操作。', 403);
122
244
  }
123
245
  const target = resolveTarget(url);
@@ -137,7 +259,7 @@ export function createWorkspaceHandler(directory, options = {}) {
137
259
  return true;
138
260
  }
139
261
  if (req.method === 'POST' && options.installCatalog) {
140
- 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') {
141
263
  throw new DocumentError('插件市场安装只接受同源页面请求。', 403);
142
264
  }
143
265
  const chunks = []; let size = 0;
@@ -153,6 +275,28 @@ export function createWorkspaceHandler(directory, options = {}) {
153
275
  }
154
276
  throw new DocumentError('插件市场索引仅支持 GET 或 POST。', 405);
155
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
+ }
156
300
  if (url.pathname === '/library/objects' && options.canvasObjects) {
157
301
  const target = resolveTarget(url);
158
302
  if (req.method === 'GET') {
@@ -167,7 +311,7 @@ export function createWorkspaceHandler(directory, options = {}) {
167
311
  return true;
168
312
  }
169
313
  if (req.method === 'POST') {
170
- 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') {
171
315
  throw new DocumentError('画布组件操作只接受同源页面请求。', 403);
172
316
  }
173
317
  const chunks = []; let size = 0;
@@ -194,7 +338,7 @@ export function createWorkspaceHandler(directory, options = {}) {
194
338
  return true;
195
339
  }
196
340
  if (req.method === 'POST') {
197
- 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') {
198
342
  throw new DocumentError('工作区切换只接受同源页面请求。', 403);
199
343
  }
200
344
  const chunks = []; let size = 0;
@@ -232,7 +376,7 @@ export function createWorkspaceHandler(directory, options = {}) {
232
376
  const target = resolveTarget(url);
233
377
  options.capabilities.connect(view.data, res, target.workspace, target.workspaceId); return true;
234
378
  }
235
- 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') {
236
380
  throw new DocumentError('插件通信只接受同源页面请求。', 403);
237
381
  }
238
382
  const captureId = url.searchParams.get('captureId');
@@ -251,6 +395,21 @@ export function createWorkspaceHandler(directory, options = {}) {
251
395
  json(res, 200, await options.capabilities.receive(view.data, message));
252
396
  return true;
253
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
+ }
254
413
  if (req.method !== 'GET' && req.method !== 'HEAD') throw new DocumentError('不支持这个请求方法。',405);
255
414
  if (url.pathname === '/library/workspaces.json') {
256
415
  const workspaces = options.listWorkspaces
@@ -258,6 +417,65 @@ export function createWorkspaceHandler(directory, options = {}) {
258
417
  : [{ id: '', name: basename(root), workspace: root, documentRoot: root, documents: scanDirectory(root).documents.length }];
259
418
  json(res, 200, { scope: options.scopeName ? (typeof options.scopeName === 'function' ? options.scopeName() : options.scopeName) : basename(root), workspaces }); return true;
260
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
+ }
261
479
  if (pluginsEnabled && url.pathname === '/library/plugins.json') {
262
480
  const target = resolveTarget(url);
263
481
  const values = target.settings?.values() || {};
@@ -302,11 +520,15 @@ export function createWorkspaceHandler(directory, options = {}) {
302
520
  const path=workspacePath(target.root,name,false,true);
303
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;
304
522
  }
305
- 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);
306
524
  const target = resolveTarget(url);
307
525
  const file = workspacePath(target.root,name), item = readDocument(file);
308
526
  if (url.pathname === '/library/source.mdc') { send(res,200,types.md,item.source); return true; }
309
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
+ }
310
532
  const mode = ['cards','mindmap','doc'].includes(url.searchParams.get('mode')) ? url.searchParams.get('mode') : (options.mode || 'cards');
311
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'});
312
534
  const bodyEnd = html.lastIndexOf('</body>');
@@ -317,7 +539,12 @@ export function createWorkspaceHandler(directory, options = {}) {
317
539
  }
318
540
  };
319
541
  }
320
- export async function startWorkspace(input, { port = 4317, mode = 'cards', theme = 'light', entry, project = false, hubMode = false, experimentalPlugins = false, agent: agentName = 'pi' } = {}) {
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');
321
548
  const path = resolve(input);
322
549
  if (!existsSync(path) && !/\.mdc?$/i.test(path)) mkdirSync(path, { recursive: true });
323
550
  if (statSync(path).isFile() && !/\.mdc?$/i.test(path)) throw new DocumentError('serve 文件需要 .mdc 或 .md 扩展名。');
@@ -330,11 +557,30 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
330
557
  let rootCtx = contextFor(workspace, workspace, root); initialize(rootCtx);
331
558
  if (!activeHubMode) recordRecentWorkspace(workspace);
332
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
+ }
333
578
  function runtimeFor(ctx) {
334
579
  const existing = runtimes.get(ctx.workspace);
335
580
  if (existing) { existing.ctx = ctx; existing.root = ctx.documents; return existing; }
336
581
  const wsPlugins = experimentalPlugins ? loadWorkspacePlugins(ctx.state) : null;
337
582
  const wsSettings = createPluginSettings(ctx, wsPlugins?.configurations);
583
+ registerInstalledPluginConfigs(ctx.state, wsSettings);
338
584
  const wsGrants = builtInGrants();
339
585
  for (const { id, permissions } of wsPlugins?.descriptor.plugins || []) wsGrants.set(id, permissions);
340
586
  const wsProviders = [...builtInCapabilities(agentName !== 'off'), ...(wsPlugins?.capabilities || [])];
@@ -392,7 +638,40 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
392
638
  return current?.expiresAt > Date.now() ? current : null;
393
639
  };
394
640
  const events = createWorkspaceEvents();
641
+ let agent = null;
395
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
+ };
396
675
  const mcpService = async (tool, input = {}) => {
397
676
  const result = await baseService(tool, input);
398
677
  try {
@@ -402,12 +681,97 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
402
681
  return result;
403
682
  };
404
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
+
405
768
  const liveMcpUrl = () => 'http://127.0.0.1:' + server.address().port + '/mcp';
406
- const agent = agentName !== 'off' ? (await import('./agent.js')).createAgentHandler({
769
+ agent = agentName !== 'off' ? (await import('./agent.js')).createAgentHandler({
407
770
  workspace: () => workspace,
408
771
  mcpUrl: liveMcpUrl,
409
772
  workspaceService: mcpService,
410
773
  events,
774
+ remote: isRemote,
411
775
  resolveRuntimeInfo: targetWorkspace => {
412
776
  const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
413
777
  return {
@@ -472,8 +836,72 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
472
836
  rt.settings.register(installed.id, rt.plugins.configurations.get(installed.id));
473
837
  }
474
838
  }
839
+ registerInstalledPluginConfigs(rt.ctx.state, rt.settings);
475
840
  return installed;
476
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
+ };
477
905
  const canvasObjects = {
478
906
  list(targetWorkspace) {
479
907
  const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
@@ -553,10 +981,102 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
553
981
  return { ok: true, ...removed };
554
982
  },
555
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
+ }
556
1075
  const handle = createWorkspaceHandler(root,{
557
- entrypoint:true,mode,theme,entry:entryFile,publishSelection,events,
1076
+ entrypoint:true,mode,theme,entry:entryFile,publishSelection,events,linkNode,
1077
+ remote:isRemote,remoteToken,
558
1078
  plugins:rootRuntime.plugins,experimentalPlugins,servePluginAsset,
559
- 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,
560
1080
  mcpUrl:liveMcpUrl,
561
1081
  hubMode:() => activeHubMode,
562
1082
  resolveWorkspace:resolveWorkspaceParam,
@@ -564,15 +1084,21 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
564
1084
  scopeName:() => basename(workspace),
565
1085
  inactivePlugins:() => rootRuntime.inactivePlugins(),
566
1086
  });
567
- 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
+ });
568
1093
  const server = createServer(async (req,res) => {
569
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'); } }
570
1095
  catch { if (!res.headersSent) res.writeHead(500);res.end('预览请求失败'); }
571
1096
  });
572
1097
  if (agent) server.on('close', agent.close);
573
1098
  server.on('close', events.close);
574
- 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); });
575
1100
  const file = entryFile ? '?file='+encodeURIComponent(entryFile) : '';
576
- const origin = 'http://127.0.0.1:'+server.address().port;
577
- 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};
578
1104
  }