cladogram 0.6.0-beta.2 → 0.6.0-beta.3

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.
@@ -0,0 +1,183 @@
1
+ /**
2
+ * Safe workspace source code reader, symbol resolver & Git diff inspector
3
+ * for Clado's Right-Side Live Code & Git Diff Drawer.
4
+ */
5
+
6
+ import { execFileSync } from 'node:child_process';
7
+ import { existsSync, lstatSync, readdirSync, readFileSync } from 'node:fs';
8
+ import { extname, join, relative, resolve, sep } from 'node:path';
9
+ import { DocumentError } from '../workspace/documents.js';
10
+
11
+ const MAX_CODE_BYTES = 256 * 1024;
12
+ const SKIP_DIRS = new Set(['node_modules', '.git', '.clado', 'dist', 'build', '.next', 'coverage', '.cache', 'target', 'vendor']);
13
+ const LANG_BY_EXT = {
14
+ '.js': 'javascript', '.mjs': 'javascript', '.cjs': 'javascript', '.jsx': 'jsx',
15
+ '.ts': 'typescript', '.tsx': 'tsx', '.py': 'python', '.go': 'go', '.rs': 'rust',
16
+ '.java': 'java', '.kt': 'kotlin', '.rb': 'ruby', '.php': 'php', '.cs': 'csharp',
17
+ '.c': 'c', '.cpp': 'cpp', '.h': 'c', '.hpp': 'cpp', '.css': 'css', '.scss': 'scss',
18
+ '.html': 'html', '.json': 'json', '.yaml': 'yaml', '.yml': 'yaml', '.xml': 'xml',
19
+ '.sql': 'sql', '.sh': 'bash', '.md': 'markdown', '.mdc': 'markdown', '.vue': 'vue',
20
+ };
21
+
22
+ export function safeWorkspaceSourcePath(workspaceRoot, relPath) {
23
+ const clean = String(relPath || '').trim().replace(/^\/+/, '');
24
+ if (!clean || clean.includes('\0') || clean.includes('..') || clean.startsWith('.git/') || clean === '.git') {
25
+ throw new DocumentError('文件路径超出工作区安全范围。', 403);
26
+ }
27
+ const base = resolve(workspaceRoot);
28
+ const full = resolve(base, clean);
29
+ if (full !== base && !full.startsWith(base + sep)) {
30
+ throw new DocumentError('文件路径超出工作区安全范围。', 403);
31
+ }
32
+ return { full, rel: relative(base, full).split('\\').join('/') };
33
+ }
34
+
35
+ function isLikelyBinary(buf) {
36
+ const sample = buf.subarray(0, Math.min(buf.length, 4096));
37
+ for (let i = 0; i < sample.length; i++) {
38
+ if (sample[i] === 0) return true;
39
+ }
40
+ return false;
41
+ }
42
+
43
+ export function readWorkspaceCodeFile(workspaceRoot, relPath) {
44
+ const { full, rel } = safeWorkspaceSourcePath(workspaceRoot, relPath);
45
+ if (!existsSync(full)) throw new DocumentError('找不到文件:' + rel, 404);
46
+ const stat = lstatSync(full);
47
+ if (!stat.isFile()) throw new DocumentError('目标不是普通文件:' + rel, 400);
48
+ if (stat.size > MAX_CODE_BYTES) throw new DocumentError('源码文件超过 256 KB 预览限制。', 413);
49
+ const buf = readFileSync(full);
50
+ if (isLikelyBinary(buf)) throw new DocumentError('不支持预览二进制文件。', 415);
51
+ const content = buf.toString('utf8');
52
+ const lines = content.split(/\r?\n/);
53
+ const ext = extname(rel).toLowerCase();
54
+ return {
55
+ path: rel,
56
+ content,
57
+ totalLines: lines.length,
58
+ language: LANG_BY_EXT[ext] || ext.replace(/^\./, '') || 'text',
59
+ };
60
+ }
61
+
62
+ export function readFileGitState(workspaceRoot, relPath) {
63
+ const { full, rel } = safeWorkspaceSourcePath(workspaceRoot, relPath);
64
+ let headContent = null;
65
+ let gitDiff = '';
66
+ let tracked = false;
67
+ try {
68
+ headContent = execFileSync('git', ['show', `HEAD:${rel}`], {
69
+ cwd: workspaceRoot,
70
+ encoding: 'utf8',
71
+ maxBuffer: MAX_CODE_BYTES * 2,
72
+ stdio: ['ignore', 'pipe', 'ignore'],
73
+ });
74
+ tracked = true;
75
+ } catch {
76
+ headContent = null;
77
+ }
78
+ try {
79
+ gitDiff = execFileSync('git', ['diff', 'HEAD', '--', rel], {
80
+ cwd: workspaceRoot,
81
+ encoding: 'utf8',
82
+ maxBuffer: MAX_CODE_BYTES * 2,
83
+ stdio: ['ignore', 'pipe', 'ignore'],
84
+ });
85
+ } catch {
86
+ gitDiff = '';
87
+ }
88
+ const currentContent = existsSync(full) && lstatSync(full).isFile() && lstatSync(full).size <= MAX_CODE_BYTES
89
+ ? readFileSync(full, 'utf8')
90
+ : null;
91
+ return {
92
+ path: rel,
93
+ tracked,
94
+ headContent,
95
+ currentContent,
96
+ gitDiff,
97
+ changed: headContent !== null && currentContent !== null ? headContent !== currentContent : (!tracked && currentContent !== null),
98
+ };
99
+ }
100
+
101
+ export function resolveSymbolInWorkspace(workspaceRoot, symbolQuery) {
102
+ const raw = String(symbolQuery || '').trim();
103
+ if (!raw) throw new DocumentError('缺少符号或文件路径参数。', 400);
104
+
105
+ // Direct relative path check first
106
+ const strippedLine = raw.replace(/:(\d+)$/, '');
107
+ const explicitLine = Number(raw.match(/:(\d+)$/)?.[1] || 0);
108
+ try {
109
+ const { full, rel } = safeWorkspaceSourcePath(workspaceRoot, strippedLine);
110
+ if (existsSync(full) && lstatSync(full).isFile()) {
111
+ const fileData = readWorkspaceCodeFile(workspaceRoot, rel);
112
+ return { ...fileData, matchedLine: explicitLine || 1 };
113
+ }
114
+ } catch {}
115
+
116
+ // Parse ClassName#methodName or ClassName.methodName or filename
117
+ const [rawClass, rawMethod] = raw.split(/[#.]/);
118
+ const className = String(rawClass || '').replace(/\(.*\)$/, '').trim();
119
+ const methodName = String(rawMethod || '').replace(/\(.*\)$/, '').trim();
120
+ if (!className) throw new DocumentError('无法解析符号:' + raw, 404);
121
+
122
+ const candidates = [];
123
+ const walk = (dir, depth = 0) => {
124
+ if (depth > 6 || candidates.length >= 250) return;
125
+ let entries;
126
+ try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
127
+ for (const ent of entries) {
128
+ if (ent.name.startsWith('.') && ent.name !== '.env.example') continue;
129
+ if (ent.isDirectory()) {
130
+ if (!SKIP_DIRS.has(ent.name)) walk(join(dir, ent.name), depth + 1);
131
+ } else if (ent.isFile()) {
132
+ const ext = extname(ent.name).toLowerCase();
133
+ if (!(ext in LANG_BY_EXT) || ext === '.md' || ext === '.mdc') continue;
134
+ const full = join(dir, ent.name);
135
+ const rel = relative(workspaceRoot, full).split('\\').join('/');
136
+ const stem = ent.name.slice(0, ent.name.length - ext.length);
137
+ const exactFile = stem.toLowerCase() === className.toLowerCase()
138
+ || ent.name.toLowerCase() === raw.toLowerCase()
139
+ || stem.replace(/[-_]/g, '').toLowerCase() === className.replace(/[-_]/g, '').toLowerCase();
140
+ candidates.push({ full, rel, score: exactFile ? 10 : (rel.toLowerCase().includes(className.toLowerCase()) ? 5 : 1) });
141
+ }
142
+ }
143
+ };
144
+ walk(workspaceRoot);
145
+ candidates.sort((a, b) => b.score - a.score);
146
+
147
+ const classRegex = new RegExp(`\\b${className.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`);
148
+ const methodRegex = methodName
149
+ ? new RegExp(`\\b${methodName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`)
150
+ : null;
151
+
152
+ for (const cand of candidates.slice(0, 80)) {
153
+ try {
154
+ const stat = lstatSync(cand.full);
155
+ if (stat.size > MAX_CODE_BYTES) continue;
156
+ const text = readFileSync(cand.full, 'utf8');
157
+ if (cand.score < 10 && !classRegex.test(text)) continue;
158
+ const lines = text.split(/\r?\n/);
159
+ let matchedLine = 1;
160
+ if (methodRegex) {
161
+ const mIdx = lines.findIndex(l => methodRegex.test(l));
162
+ if (mIdx >= 0) matchedLine = mIdx + 1;
163
+ else {
164
+ const cIdx = lines.findIndex(l => classRegex.test(l));
165
+ if (cIdx >= 0) matchedLine = cIdx + 1;
166
+ }
167
+ } else {
168
+ const cIdx = lines.findIndex(l => classRegex.test(l));
169
+ if (cIdx >= 0) matchedLine = cIdx + 1;
170
+ }
171
+ const ext = extname(cand.rel).toLowerCase();
172
+ return {
173
+ path: cand.rel,
174
+ content: text,
175
+ totalLines: lines.length,
176
+ language: LANG_BY_EXT[ext] || ext.replace(/^\./, '') || 'text',
177
+ matchedLine,
178
+ };
179
+ } catch {}
180
+ }
181
+
182
+ throw new DocumentError(`在工作区源码中未找到匹配「${raw}」的文件。`, 404);
183
+ }
package/src/server/mcp.js CHANGED
@@ -65,8 +65,8 @@ function createServer(invoke, invokeCapability) {
65
65
  catch (error) { return await failure(error, args); }
66
66
  });
67
67
  };
68
- register('clado_workspace', '初始化、查看工作区、列出子工作区、搜索或校验。用户说“我选的卡片”时用selection,按点选顺序读取标题路径、正文、后代和版本。selectionStatus为empty或stale时请用户选中或重新选择。inspect返回工作区版本和目录;workspaces列出当前服务范围内的子工作区;init准备工作区。', {
69
- 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()
68
+ register('clado_workspace', '初始化、查看工作区、列出子工作区、读取画布拓扑树(graph)、搜索或校验。用户说“我选的卡片”时用selection,按点选顺序读取标题路径、正文、后代和版本。selectionStatus为empty或stale时请用户选中或重新选择。graph返回类似DOM树的卡片列布局、跨卡连线、语义Tag、孤立卡与断链快照。inspect返回工作区版本和目录;workspaces列出当前服务范围内的子工作区;init准备工作区。', {
69
+ action: z.enum(['init','inspect','search','validate','selection','workspaces','graph']), file: z.string().optional(), query: z.string().optional(), includeContent: z.boolean().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(100).optional()
70
70
  });
71
71
  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。修改模板不影响已有文档头部。', {
72
72
  action: z.enum(['list','read','create','update','delete','pull','push']), scope: z.enum(['project','user']).optional(),
@@ -75,8 +75,8 @@ function createServer(invoke, invokeCapability) {
75
75
  view: z.enum(['prompt','source','full']).optional().describe('read默认prompt,编辑规则用source,只有需要全部字段时才用full。'),
76
76
  expectedWorkspaceVersion: version, expectedUserTemplateVersion: z.string().optional().describe('读取返回的userTemplateVersion;用户库写入及push必填。'), dryRun: z.boolean().optional()
77
77
  });
78
- register('clado_documents', '文档list/read/create/copy/update/rename/delete。read默认full,按需view:nodes/source/summary。create用file(.md或.mdc)/title/templateId,source只传正文。copy用file/newFile保留规则头和正文并重定位副本引用。create/copy检查目标尚不存在,可省略版本。update传完整source,可用metadata替换头;rename用newFile维护引用;delete被引用默认拒绝,unlink才断开。update/rename/delete使用expectedFileVersion或expectedWorkspaceVersion;results返回最终位置。', {
79
- action: z.enum(['list','read','create','copy','update','rename','delete']), view: z.enum(['full','nodes','source','summary']).optional(), file: z.string().optional(), query: z.string().optional(), title: z.string().optional(), templateId: z.string().optional(), source: text().optional(), metadata: z.record(z.string(), z.unknown()).optional(), newFile: z.string().optional(), unlink: z.boolean().optional(), expectedFileVersion, expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
78
+ register('clado_documents', '文档list/read/create/copy/update/rename/delete。read默认full,按需view:nodes/source/summary/graph(graph返回卡片列布局、跨卡连线、语义Tag、孤立卡与断链拓扑树)。create用file(.md或.mdc)/title/templateId,source只传正文。copy用file/newFile保留规则头和正文并重定位副本引用。create/copy检查目标尚不存在,可省略版本。update传完整source,可用metadata替换头;rename用newFile维护引用;delete被引用默认拒绝,unlink才断开。update/rename/delete使用expectedFileVersion或expectedWorkspaceVersion;results返回最终位置。', {
79
+ action: z.enum(['list','read','create','copy','update','rename','delete']), view: z.enum(['full','nodes','source','summary','graph']).optional(), file: z.string().optional(), query: z.string().optional(), title: z.string().optional(), templateId: z.string().optional(), source: text().optional(), metadata: z.record(z.string(), z.unknown()).optional(), newFile: z.string().optional(), unlink: z.boolean().optional(), expectedFileVersion, expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
80
80
  });
81
81
  register('clado_nodes', '节点read/query/create/insert/update/rename/move/delete。file必填,node用标题数组。read返回nodeVersion、行号、同级index和段落编号。create在同级末尾新增可省略版本;指定index需文件版本。insert追加/置顶或按唯一anchor插入、update用position:{mode:replace,anchor:原文}时可省略版本。按段落编号或整段覆盖用expectedNodeVersion、expectedFileVersion或expectedWorkspaceVersion,均保留孩子。rename/move维护引用;delete有孩子需recursive。results返回最终位置。', {
82
82
  action: z.enum(['read','query','create','insert','update','rename','move','delete']), ...Object.fromEntries(['file','node','parent','title','content','index','position','recursive','unlink','targetFile'].map(key => [key, nodeFields[key]])), relation: z.enum(['parent','children','ancestors','descendants','siblings','upstream','downstream']).optional(), depth: z.number().int().min(1).max(100).optional(), includeContent: z.boolean().optional(), offset: z.number().int().nonnegative().optional(), limit: z.number().int().min(1).max(100).optional(), expectedFileVersion, expectedNodeVersion, expectedWorkspaceVersion: version, dryRun: z.boolean().optional()
@@ -1,11 +1,14 @@
1
1
  import { createServer } from 'node:http';
2
- import { createHash, randomUUID } from 'node:crypto';
2
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
3
3
  import { readFileSync, 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';
@@ -25,10 +28,75 @@ import {
25
28
  renameCanvasDocument,
26
29
  resolveWorkspaceSelection,
27
30
  } from './workspace-hub.js';
31
+ import { readFileGitState, readWorkspaceCodeFile, resolveSymbolInWorkspace } from './code-inspect.js';
28
32
  import { z } from 'zod/v4';
29
33
  const assets = join(dirname(fileURLToPath(import.meta.url)), 'assets');
30
34
  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'};
31
35
  const types = { html: 'text/html', css: 'text/css', js: 'text/javascript', json: 'application/json', md: 'text/markdown' };
36
+ const REMOTE_COOKIE = 'clado_remote_token';
37
+
38
+ function isTrustedOrigin(req, remote = false) {
39
+ const origin = req.headers.origin;
40
+ if (!origin) return true;
41
+ const host = String(req.headers.host || '').trim();
42
+ if (!host) return false;
43
+ if (origin === 'http://' + host) return true;
44
+ if (!remote) return false;
45
+ const forwardedHost = String(req.headers['x-forwarded-host'] || '').split(',')[0].trim();
46
+ const allowed = new Set([host]);
47
+ if (forwardedHost) allowed.add(forwardedHost);
48
+ for (const h of allowed) {
49
+ if (h && (origin === 'http://' + h || origin === 'https://' + h)) return true;
50
+ }
51
+ return false;
52
+ }
53
+
54
+ function hasTrustedSameOrigin(req, remote = false) {
55
+ return Boolean(req.headers.origin) && isTrustedOrigin(req, remote);
56
+ }
57
+
58
+ function readCookie(req, name) {
59
+ const raw = String(req.headers.cookie || '');
60
+ if (!raw) return '';
61
+ for (const part of raw.split(';')) {
62
+ const idx = part.indexOf('=');
63
+ if (idx < 0) continue;
64
+ if (part.slice(0, idx).trim() === name) {
65
+ try { return decodeURIComponent(part.slice(idx + 1).trim()); } catch { return part.slice(idx + 1).trim(); }
66
+ }
67
+ }
68
+ return '';
69
+ }
70
+
71
+ function safeTokenMatch(candidate, expected) {
72
+ if (!candidate || !expected) return false;
73
+ const a = Buffer.from(String(candidate));
74
+ const b = Buffer.from(String(expected));
75
+ return a.length === b.length && timingSafeEqual(a, b);
76
+ }
77
+
78
+ function renderRemoteUnlockPage(errorMsg = '') {
79
+ const errHtml = errorMsg ? `<p class="err">${String(errorMsg).replace(/[<>&"]/g, '')}</p>` : '';
80
+ return `<!doctype html>
81
+ <html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
82
+ <title>Clado 远程调试验证</title>
83
+ <style>
84
+ *{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}
85
+ .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)}
86
+ 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}
87
+ .err{color:#be123c;background:rgba(244,63,94,.1);padding:8px 10px;border-radius:10px;margin-bottom:12px}
88
+ 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}
89
+ 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}
90
+ </style></head><body>
91
+ <form class="card" method="GET" action="/">
92
+ <h1>Clado 远程调试验证</h1>
93
+ <p>当前工作台运行在安全远程模式,请输入终端打印的访问口令(Token)继续。</p>
94
+ ${errHtml}
95
+ <input name="token" type="password" placeholder="粘贴访问口令…" autocomplete="off" required autofocus>
96
+ <button type="submit">进入空间画布</button>
97
+ </form></body></html>`;
98
+ }
99
+
32
100
  const viewSelection = z.object({
33
101
  tab: z.uuid(), file: z.string().min(1), version: z.string().regex(/^[a-f0-9]{64}$/),
34
102
  nodes: z.array(z.array(z.string().min(1)).min(1).max(6)).max(200),
@@ -36,6 +104,8 @@ const viewSelection = z.object({
36
104
  }).strict();
37
105
  export function createWorkspaceHandler(directory, options = {}) {
38
106
  const root = resolve(directory);
107
+ const remote = Boolean(options.remote);
108
+ const remoteToken = remote && options.remoteToken ? String(options.remoteToken) : '';
39
109
  const assetNames = new Set(['library.html','library.css','library.js','library-canvas.js']);
40
110
  if (options.capabilities) assetNames.add('library-plugin-bridge.js');
41
111
  if (options.plugins || options.experimentalPlugins) for (const name of ['library-plugins.js', 'library-plugins.css', 'clado-plugin-sdk.js']) assetNames.add(name);
@@ -50,13 +120,43 @@ export function createWorkspaceHandler(directory, options = {}) {
50
120
  const pluginFile = workspacePluginAssets.get(url.pathname);
51
121
  if (!url.pathname.startsWith('/library/') && !assetNames.has(route) && !pluginFile && !(options.entrypoint && route === '')) return false;
52
122
  try {
53
- const host = req.headers.host;
54
- if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host || '')) throw new DocumentError('只接受本机预览请求。',403);
123
+ const host = String(req.headers.host || '').trim();
124
+ if (remote) {
125
+ if (!host || /[\s/@]/.test(host)) throw new DocumentError('请求主机头不合法。', 403);
126
+ } else if (!/^(127\.0\.0\.1|localhost)(:\d+)?$/.test(host)) {
127
+ throw new DocumentError('只接受本机预览请求。', 403);
128
+ }
129
+ if (remoteToken) {
130
+ const queryToken = url.searchParams.get('token') || '';
131
+ const authHeader = String(req.headers.authorization || '');
132
+ const bearerToken = authHeader.startsWith('Bearer ') ? authHeader.slice(7).trim() : '';
133
+ const cookieToken = readCookie(req, REMOTE_COOKIE);
134
+ if (queryToken && safeTokenMatch(queryToken, remoteToken) && req.method === 'GET') {
135
+ const isHttps = String(req.headers['x-forwarded-proto'] || '').split(',')[0].trim() === 'https';
136
+ const cleanUrl = new URL(url.pathname + url.search, 'http://clado.local');
137
+ cleanUrl.searchParams.delete('token');
138
+ const dest = cleanUrl.pathname + (cleanUrl.search || '');
139
+ const cookie = `${REMOTE_COOKIE}=${encodeURIComponent(remoteToken)}; Path=/; HttpOnly; SameSite=Lax${isHttps ? '; Secure' : ''}`;
140
+ res.writeHead(302, { 'set-cookie': cookie, location: dest, 'cache-control': 'no-store' });
141
+ res.end();
142
+ return true;
143
+ }
144
+ const authed = safeTokenMatch(cookieToken, remoteToken)
145
+ || safeTokenMatch(bearerToken, remoteToken)
146
+ || safeTokenMatch(queryToken, remoteToken);
147
+ if (!authed) {
148
+ if (req.method === 'GET' && String(req.headers.accept || '').includes('text/html')) {
149
+ send(res, 401, types.html, renderRemoteUnlockPage(queryToken ? '口令不正确,请重新输入。' : ''));
150
+ return true;
151
+ }
152
+ throw new DocumentError('需要远程访问口令(token)。', 401);
153
+ }
154
+ }
55
155
  const pluginsEnabled = !!(options.plugins || options.experimentalPlugins);
56
156
  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);
157
+ if (req.headers.origin && !isTrustedOrigin(req, remote) && !(pluginAsset && req.headers.origin === 'null')) throw new DocumentError('来源不匹配。',403);
58
158
  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);
159
+ if (!hasTrustedSameOrigin(req, remote) || req.headers['content-type'] !== 'application/json') throw new DocumentError('选区只接受同源页面请求。', 403);
60
160
  const target = resolveTarget(url);
61
161
  const chunks = []; let size = 0;
62
162
  for await (const chunk of req) {
@@ -97,7 +197,7 @@ export function createWorkspaceHandler(directory, options = {}) {
97
197
  if (!target.settings) throw new DocumentError('没有这个预览入口;文档操作请使用 /mcp。',404);
98
198
  const id = url.searchParams.get('id');
99
199
  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') {
200
+ if (req.method !== 'POST' || !hasTrustedSameOrigin(req, remote) || req.headers['content-type'] !== 'application/json') {
101
201
  throw new DocumentError('插件设置只接受同源页面写入。', 403);
102
202
  }
103
203
  const chunks = []; let size = 0;
@@ -112,12 +212,12 @@ export function createWorkspaceHandler(directory, options = {}) {
112
212
  }
113
213
  if (options.installPlugin && url.pathname === '/library/install-plugin') {
114
214
  if (req.method === 'DELETE' && options.removePlugin) {
115
- if (req.headers.origin !== 'http://' + host) throw new DocumentError('卸载插件需要在工作区页面操作。', 403);
215
+ if (!hasTrustedSameOrigin(req, remote)) throw new DocumentError('卸载插件需要在工作区页面操作。', 403);
116
216
  const target = resolveTarget(url);
117
217
  json(res, 200, options.removePlugin(target.workspace, url.searchParams.get('id')));
118
218
  return true;
119
219
  }
120
- if (req.method !== 'POST' || req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') {
220
+ if (req.method !== 'POST' || !hasTrustedSameOrigin(req, remote) || req.headers['content-type'] !== 'application/json') {
121
221
  throw new DocumentError('插件安装需要在工作区页面操作。', 403);
122
222
  }
123
223
  const target = resolveTarget(url);
@@ -137,7 +237,7 @@ export function createWorkspaceHandler(directory, options = {}) {
137
237
  return true;
138
238
  }
139
239
  if (req.method === 'POST' && options.installCatalog) {
140
- if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
240
+ if (!hasTrustedSameOrigin(req, remote) || req.headers['content-type']?.split(';')[0] !== 'application/json') {
141
241
  throw new DocumentError('插件市场安装只接受同源页面请求。', 403);
142
242
  }
143
243
  const chunks = []; let size = 0;
@@ -167,7 +267,7 @@ export function createWorkspaceHandler(directory, options = {}) {
167
267
  return true;
168
268
  }
169
269
  if (req.method === 'POST') {
170
- if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
270
+ if (!hasTrustedSameOrigin(req, remote) || req.headers['content-type']?.split(';')[0] !== 'application/json') {
171
271
  throw new DocumentError('画布组件操作只接受同源页面请求。', 403);
172
272
  }
173
273
  const chunks = []; let size = 0;
@@ -194,7 +294,7 @@ export function createWorkspaceHandler(directory, options = {}) {
194
294
  return true;
195
295
  }
196
296
  if (req.method === 'POST') {
197
- if (req.headers.origin !== 'http://' + host || req.headers['content-type']?.split(';')[0] !== 'application/json') {
297
+ if (!hasTrustedSameOrigin(req, remote) || req.headers['content-type']?.split(';')[0] !== 'application/json') {
198
298
  throw new DocumentError('工作区切换只接受同源页面请求。', 403);
199
299
  }
200
300
  const chunks = []; let size = 0;
@@ -232,7 +332,7 @@ export function createWorkspaceHandler(directory, options = {}) {
232
332
  const target = resolveTarget(url);
233
333
  options.capabilities.connect(view.data, res, target.workspace, target.workspaceId); return true;
234
334
  }
235
- if (req.method !== 'POST' || req.headers.origin !== 'http://' + host || req.headers['content-type'] !== 'application/json') {
335
+ if (req.method !== 'POST' || !hasTrustedSameOrigin(req, remote) || req.headers['content-type'] !== 'application/json') {
236
336
  throw new DocumentError('插件通信只接受同源页面请求。', 403);
237
337
  }
238
338
  const captureId = url.searchParams.get('captureId');
@@ -251,6 +351,21 @@ export function createWorkspaceHandler(directory, options = {}) {
251
351
  json(res, 200, await options.capabilities.receive(view.data, message));
252
352
  return true;
253
353
  }
354
+ if (options.linkNode && url.pathname === '/library/link') {
355
+ if (req.method !== 'POST' || !hasTrustedSameOrigin(req, remote) || req.headers['content-type']?.split(';')[0] !== 'application/json') {
356
+ throw new DocumentError('画布连线只接受同源页面 POST 请求。', 403);
357
+ }
358
+ const chunks = []; let size = 0;
359
+ for await (const chunk of req) {
360
+ size += chunk.length;
361
+ if (size > 65536) throw new DocumentError('连线参数过大。', 413);
362
+ chunks.push(chunk);
363
+ }
364
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
365
+ const target = resolveTarget(url);
366
+ json(res, 200, await options.linkNode(target, body));
367
+ return true;
368
+ }
254
369
  if (req.method !== 'GET' && req.method !== 'HEAD') throw new DocumentError('不支持这个请求方法。',405);
255
370
  if (url.pathname === '/library/workspaces.json') {
256
371
  const workspaces = options.listWorkspaces
@@ -258,6 +373,30 @@ export function createWorkspaceHandler(directory, options = {}) {
258
373
  : [{ id: '', name: basename(root), workspace: root, documentRoot: root, documents: scanDirectory(root).documents.length }];
259
374
  json(res, 200, { scope: options.scopeName ? (typeof options.scopeName === 'function' ? options.scopeName() : options.scopeName) : basename(root), workspaces }); return true;
260
375
  }
376
+ if (url.pathname === '/library/code-file') {
377
+ const target = resolveTarget(url);
378
+ const relPath = url.searchParams.get('path');
379
+ const symbol = url.searchParams.get('symbol');
380
+ const data = relPath
381
+ ? readWorkspaceCodeFile(target.workspace, relPath)
382
+ : resolveSymbolInWorkspace(target.workspace, symbol);
383
+ let git = null;
384
+ try { git = readFileGitState(target.workspace, data.path); } catch {}
385
+ json(res, 200, {
386
+ ...data,
387
+ gitDiff: git?.gitDiff || '',
388
+ headContent: git?.headContent ?? null,
389
+ changed: Boolean(git?.changed),
390
+ });
391
+ return true;
392
+ }
393
+ if (url.pathname === '/library/git-diff') {
394
+ const target = resolveTarget(url);
395
+ const relPath = url.searchParams.get('path');
396
+ if (!relPath) throw new DocumentError('缺少 path 参数。', 400);
397
+ json(res, 200, readFileGitState(target.workspace, relPath));
398
+ return true;
399
+ }
261
400
  if (pluginsEnabled && url.pathname === '/library/plugins.json') {
262
401
  const target = resolveTarget(url);
263
402
  const values = target.settings?.values() || {};
@@ -302,11 +441,15 @@ export function createWorkspaceHandler(directory, options = {}) {
302
441
  const path=workspacePath(target.root,name,false,true);
303
442
  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
443
  }
305
- if (!['/library/source.mdc','/library/canvas'].includes(url.pathname)) throw new DocumentError('没有这个预览入口;文档操作请使用 /mcp。',404);
444
+ if (!['/library/source.mdc','/library/canvas','/library/doc.json'].includes(url.pathname)) throw new DocumentError('没有这个预览入口;文档操作请使用 /mcp。',404);
306
445
  const target = resolveTarget(url);
307
446
  const file = workspacePath(target.root,name), item = readDocument(file);
308
447
  if (url.pathname === '/library/source.mdc') { send(res,200,types.md,item.source); return true; }
309
448
  if (item.diagnostics.some(d=>d.severity==='error')) throw new DocumentError('文档暂时无法解析。',422,item.diagnostics);
449
+ if (url.pathname === '/library/doc.json') {
450
+ json(res, 200, { file: name, version: item.version, doc: item.doc, diagnostics: item.diagnostics });
451
+ return true;
452
+ }
310
453
  const mode = ['cards','mindmap','doc'].includes(url.searchParams.get('mode')) ? url.searchParams.get('mode') : (options.mode || 'cards');
311
454
  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
455
  const bodyEnd = html.lastIndexOf('</body>');
@@ -317,7 +460,12 @@ export function createWorkspaceHandler(directory, options = {}) {
317
460
  }
318
461
  };
319
462
  }
320
- export async function startWorkspace(input, { port = 4317, mode = 'cards', theme = 'light', entry, project = false, hubMode = false, experimentalPlugins = false, agent: agentName = 'pi' } = {}) {
463
+ 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' } = {}) {
464
+ const isRemote = Boolean(remote);
465
+ const remoteToken = isRemote && !noToken
466
+ ? (String(token || '').trim() || randomBytes(12).toString('hex'))
467
+ : '';
468
+ const listenHost = String(host || '').trim() || (isRemote ? '0.0.0.0' : '127.0.0.1');
321
469
  const path = resolve(input);
322
470
  if (!existsSync(path) && !/\.mdc?$/i.test(path)) mkdirSync(path, { recursive: true });
323
471
  if (statSync(path).isFile() && !/\.mdc?$/i.test(path)) throw new DocumentError('serve 文件需要 .mdc 或 .md 扩展名。');
@@ -408,6 +556,7 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
408
556
  mcpUrl: liveMcpUrl,
409
557
  workspaceService: mcpService,
410
558
  events,
559
+ remote: isRemote,
411
560
  resolveRuntimeInfo: targetWorkspace => {
412
561
  const rt = runtimeFor(contextFor(workspace, targetWorkspace, root));
413
562
  return {
@@ -553,8 +702,100 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
553
702
  return { ok: true, ...removed };
554
703
  },
555
704
  };
705
+ async function linkNode(target, body = {}) {
706
+ const file = String(body.file || '').trim();
707
+ const rawNode = Array.isArray(body.node) && body.node.length ? body.node : body.sourceNode;
708
+ const node = Array.isArray(rawNode) && rawNode.length ? rawNode.map(String) : null;
709
+ if (!file || !node) throw new DocumentError('缺少源画布文件或源节点路径。', 400);
710
+ const targetNode = Array.isArray(body.targetNode) && body.targetNode.length ? body.targetNode.map(String) : undefined;
711
+ const targetFile = body.targetFile ? String(body.targetFile).trim() : undefined;
712
+ const rawTag = body.targetTag || body.targetTagId || '';
713
+ const targetTag = rawTag ? String(rawTag).trim().replace(/^#/, '') : '';
714
+ const anchor = typeof body.anchor === 'string' && body.anchor.trim() ? body.anchor.trim() : '';
715
+ let sourcePoint = body.sourcePoint && typeof body.sourcePoint === 'object' ? { ...body.sourcePoint } : undefined;
716
+ let targetPoint = body.targetPoint && typeof body.targetPoint === 'object' ? { ...body.targetPoint } : undefined;
717
+ const rawLabel = String(body.label || anchor || targetTag || targetNode?.at(-1) || '').replace(/[\r\n\[\]]/g, '').trim();
718
+ const label = rawLabel || '关联';
719
+ const docSummary = await mcpService('clado_documents', { workspace: target.workspace, action: 'read', file, view: 'summary' });
720
+ const expectedFileVersion = docSummary?.version;
721
+
722
+ // 自动把前端传入的「第 N 个代码块/表格/Mermaid」映射为节点正文中的真实段落序号,并规范 Mermaid nodeId 字段
723
+ const resolveMediaPoint = (nodePath, pt) => {
724
+ if (!pt || !nodePath) return pt;
725
+ const next = { ...pt };
726
+ if (next.kind === 'mermaid' && next.node && !next.nodeId) {
727
+ next.nodeId = next.node;
728
+ delete next.node;
729
+ }
730
+ if (next.kind === 'line') return next;
731
+ try {
732
+ const full = workspacePath(target.root, file);
733
+ const tree = treeOf(readFileSync(full, 'utf8'), file);
734
+ const rec = findNode(tree, nodePath);
735
+ if (!rec?.node?.content) return next;
736
+ const blocks = paragraphs(rec.node.content);
737
+ const direct = blocks[(next.paragraph || 1) - 1];
738
+ if (direct && mediaPointFits(blockMedia(direct.text), next)) return next;
739
+ const sameKind = blocks.filter(b => blockMedia(b.text)?.kind === next.kind);
740
+ const byKindIdx = sameKind[(next.paragraph || 1) - 1];
741
+ if (byKindIdx && mediaPointFits(blockMedia(byKindIdx.text), next)) {
742
+ return { ...next, paragraph: byKindIdx.index };
743
+ }
744
+ const firstFit = sameKind.find(b => mediaPointFits(blockMedia(b.text), next));
745
+ if (firstFit) return { ...next, paragraph: firstFit.index };
746
+ } catch {}
747
+ return next;
748
+ };
749
+ if (sourcePoint) sourcePoint = resolveMediaPoint(node, sourcePoint);
750
+ if (targetPoint && targetNode) targetPoint = resolveMediaPoint(targetNode, targetPoint);
751
+
752
+ // Direct Tag link in prose (no media sourcePoint): write clean [label](#tagId)
753
+ if (targetTag && !sourcePoint && !targetPoint) {
754
+ const tagLink = `[${label}](#${targetTag})`;
755
+ if (anchor) {
756
+ const res = await mcpService('clado_nodes', {
757
+ workspace: target.workspace,
758
+ action: 'update',
759
+ file,
760
+ node,
761
+ content: tagLink,
762
+ position: { mode: 'replace', anchor },
763
+ expectedFileVersion,
764
+ });
765
+ events.emit(target.workspace, 'doc.updated', { file, action: 'link', nodes: [node], label: '已连接到 #' + targetTag });
766
+ return { ok: true, file, mode: 'tag-replace', ...res };
767
+ }
768
+ const res = await mcpService('clado_nodes', {
769
+ workspace: target.workspace,
770
+ action: 'insert',
771
+ file,
772
+ node,
773
+ content: tagLink,
774
+ expectedFileVersion,
775
+ });
776
+ events.emit(target.workspace, 'doc.updated', { file, action: 'link', nodes: [node], label: '已连接到 #' + targetTag });
777
+ return { ok: true, file, mode: 'tag-append', ...res };
778
+ }
779
+
780
+ if (!targetNode && !targetFile) throw new DocumentError('缺少目标卡片、小节或语义 Tag。', 400);
781
+ const res = await mcpService('clado_links', {
782
+ workspace: target.workspace,
783
+ action: 'connect',
784
+ file,
785
+ node,
786
+ ...(targetFile ? { targetFile } : {}),
787
+ ...(targetNode ? { targetNode } : {}),
788
+ label,
789
+ ...(sourcePoint ? { sourcePoint } : (anchor ? { position: { mode: 'replace', anchor } } : {})),
790
+ ...(targetPoint ? { targetPoint } : {}),
791
+ ...(expectedFileVersion ? { expectedFileVersion } : {}),
792
+ });
793
+ events.emit(target.workspace, 'doc.updated', { file, action: 'link', nodes: [node, ...(targetNode ? [targetNode] : [])], label: '已建立新连线' });
794
+ return { ok: true, file, mode: sourcePoint ? 'media-point' : (anchor ? 'anchor-replace' : 'card-link'), ...res };
795
+ }
556
796
  const handle = createWorkspaceHandler(root,{
557
- entrypoint:true,mode,theme,entry:entryFile,publishSelection,events,
797
+ entrypoint:true,mode,theme,entry:entryFile,publishSelection,events,linkNode,
798
+ remote:isRemote,remoteToken,
558
799
  plugins:rootRuntime.plugins,experimentalPlugins,servePluginAsset,
559
800
  agent,agentProfile:agentName,capabilities,settings:rootRuntime.settings,installPlugin,removePlugin,readPluginRegistry,installCatalog,canvasObjects,workspaceHub,
560
801
  mcpUrl:liveMcpUrl,
@@ -571,8 +812,9 @@ export async function startWorkspace(input, { port = 4317, mode = 'cards', theme
571
812
  });
572
813
  if (agent) server.on('close', agent.close);
573
814
  server.on('close', events.close);
574
- await new Promise((resolve,reject) => { server.once('error',reject); server.listen(port,'127.0.0.1',resolve); });
815
+ await new Promise((resolve,reject) => { server.once('error',reject); server.listen(port,listenHost,resolve); });
575
816
  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};
817
+ const actualPort = server.address().port;
818
+ const origin = 'http://127.0.0.1:'+actualPort;
819
+ 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
820
  }