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,308 +0,0 @@
1
- /**
2
- * Clado 原生 Agent 外部 MCP Client 运行时与配置管理:
3
- * - 支持全球配置(~/.clado/mcp.json)、工作区配置(.clado/mcp.json)与插件声明(pluginMcp)三层合并;
4
- * - 兼容标准 mcpServers JSON 格式(Claude Code / Cursor 直接粘贴即用);
5
- * - 支持 Stdio(本地命令)与 Streamable HTTP(远程/本机 HTTP MCP)双传输协议;
6
- * - 提供连通性测试、工具发现缓存、与原生 Agent 工具调用桥接(mcp__<server>__<tool>)。
7
- */
8
-
9
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
10
- import { dirname, join } from 'node:path';
11
- import { Client } from '@modelcontextprotocol/sdk/client/index.js';
12
- import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
13
- import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
14
- import { userTemplatePaths } from '../skill/templates.js';
15
- import { VERSION } from '../util/version.js';
16
-
17
- const NAME_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,47}$/;
18
- const DEFAULT_TIMEOUT_MS = 12000;
19
-
20
- function globalMcpPath() {
21
- return join(userTemplatePaths().state, 'mcp.json');
22
- }
23
-
24
- function workspaceMcpPath(workspace) {
25
- return workspace ? join(workspace, '.clado', 'mcp.json') : '';
26
- }
27
-
28
- function readMcpFile(filePath) {
29
- if (!filePath || !existsSync(filePath)) return {};
30
- try {
31
- const raw = JSON.parse(readFileSync(filePath, 'utf8'));
32
- if (!raw || typeof raw !== 'object') return {};
33
- const servers = raw.mcpServers && typeof raw.mcpServers === 'object' ? raw.mcpServers : raw;
34
- return servers && typeof servers === 'object' && !Array.isArray(servers) ? servers : {};
35
- } catch {
36
- return {};
37
- }
38
- }
39
-
40
- function writeMcpFile(filePath, servers) {
41
- const dir = dirname(filePath);
42
- if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
43
- writeFileSync(filePath, JSON.stringify({ mcpServers: servers }, null, 2) + '\n', { mode: 0o600 });
44
- }
45
-
46
- export function normalizeServerConfig(raw = {}) {
47
- if (!raw || typeof raw !== 'object') throw new Error('MCP 服务配置必须是 JSON 对象。');
48
- const url = typeof raw.url === 'string' ? raw.url.trim() : '';
49
- const command = typeof raw.command === 'string' ? raw.command.trim() : '';
50
- const type = raw.type === 'http' || raw.type === 'streamable-http' || (!command && url) ? 'http' : 'stdio';
51
- const enabled = raw.enabled !== false;
52
-
53
- if (type === 'http') {
54
- if (!/^https?:\/\//i.test(url)) throw new Error('HTTP MCP 服务需要有效的 http(s):// 地址。');
55
- const headers = raw.headers && typeof raw.headers === 'object' && !Array.isArray(raw.headers)
56
- ? Object.fromEntries(Object.entries(raw.headers).map(([k, v]) => [String(k), String(v)]))
57
- : {};
58
- return { type: 'http', url, headers, enabled };
59
- }
60
-
61
- if (!command) throw new Error('Stdio MCP 服务需要填写启动命令(command)。');
62
- const args = Array.isArray(raw.args)
63
- ? raw.args.map(a => String(a))
64
- : (typeof raw.args === 'string' && raw.args.trim() ? raw.args.trim().split(/\s+/) : []);
65
- const env = raw.env && typeof raw.env === 'object' && !Array.isArray(raw.env)
66
- ? Object.fromEntries(Object.entries(raw.env).map(([k, v]) => [String(k), String(v)]))
67
- : {};
68
- const cwd = typeof raw.cwd === 'string' && raw.cwd.trim() ? raw.cwd.trim() : undefined;
69
- return { type: 'stdio', command, args, env, ...(cwd ? { cwd } : {}), enabled };
70
- }
71
-
72
- function sanitizeServerForUi(name, cfg, scope, pluginId = '') {
73
- const envKeys = cfg.env ? Object.keys(cfg.env) : [];
74
- const headerKeys = cfg.headers ? Object.keys(cfg.headers) : [];
75
- return {
76
- name,
77
- scope,
78
- ...(pluginId ? { pluginId } : {}),
79
- type: cfg.type || (cfg.url ? 'http' : 'stdio'),
80
- enabled: cfg.enabled !== false,
81
- command: cfg.command || '',
82
- args: Array.isArray(cfg.args) ? cfg.args : [],
83
- url: cfg.url || '',
84
- envKeys,
85
- headerKeys,
86
- };
87
- }
88
-
89
- export function listMcpServers(workspace, { pluginMcp = [], includeSecrets = false } = {}) {
90
- const merged = new Map();
91
-
92
- for (const item of pluginMcp || []) {
93
- if (!item?.name || !NAME_RE.test(item.name)) continue;
94
- try {
95
- const cfg = normalizeServerConfig(item);
96
- merged.set(item.name, { name: item.name, scope: 'plugin', pluginId: item.pluginId || '', config: cfg });
97
- } catch {}
98
- }
99
-
100
- const globalMap = readMcpFile(globalMcpPath());
101
- for (const [name, raw] of Object.entries(globalMap)) {
102
- if (!NAME_RE.test(name)) continue;
103
- try {
104
- merged.set(name, { name, scope: 'global', config: normalizeServerConfig(raw) });
105
- } catch {}
106
- }
107
-
108
- const wsMap = readMcpFile(workspaceMcpPath(workspace));
109
- for (const [name, raw] of Object.entries(wsMap)) {
110
- if (!NAME_RE.test(name)) continue;
111
- try {
112
- merged.set(name, { name, scope: 'workspace', config: normalizeServerConfig(raw) });
113
- } catch {}
114
- }
115
-
116
- return [...merged.values()].map(entry => (
117
- includeSecrets
118
- ? entry
119
- : sanitizeServerForUi(entry.name, entry.config, entry.scope, entry.pluginId)
120
- ));
121
- }
122
-
123
- export function saveMcpServer(workspace, { name, scope = 'workspace', config } = {}) {
124
- const cleanName = String(name || '').trim();
125
- if (!NAME_RE.test(cleanName)) {
126
- throw new Error('MCP 服务名称仅支持字母、数字、下划线和连字符(1-48 字符)。');
127
- }
128
- const normalized = normalizeServerConfig(config);
129
- const filePath = scope === 'global' || !workspace ? globalMcpPath() : workspaceMcpPath(workspace);
130
- const current = readMcpFile(filePath);
131
- current[cleanName] = normalized;
132
- writeMcpFile(filePath, current);
133
- return sanitizeServerForUi(cleanName, normalized, scope === 'global' || !workspace ? 'global' : 'workspace');
134
- }
135
-
136
- export function toggleMcpServer(workspace, { name, scope = 'workspace', enabled = true } = {}) {
137
- const cleanName = String(name || '').trim();
138
- const filePath = scope === 'global' || !workspace ? globalMcpPath() : workspaceMcpPath(workspace);
139
- const current = readMcpFile(filePath);
140
- if (!current[cleanName]) throw new Error(`未找到 MCP 服务:${cleanName}`);
141
- current[cleanName] = { ...current[cleanName], enabled: Boolean(enabled) };
142
- writeMcpFile(filePath, current);
143
- return sanitizeServerForUi(cleanName, normalizeServerConfig(current[cleanName]), scope === 'global' || !workspace ? 'global' : 'workspace');
144
- }
145
-
146
- export function deleteMcpServer(workspace, { name, scope = 'workspace' } = {}) {
147
- const cleanName = String(name || '').trim();
148
- const filePath = scope === 'global' || !workspace ? globalMcpPath() : workspaceMcpPath(workspace);
149
- const current = readMcpFile(filePath);
150
- if (!current[cleanName]) return false;
151
- delete current[cleanName];
152
- writeMcpFile(filePath, current);
153
- return true;
154
- }
155
-
156
- export function importMcpJson(workspace, { scope = 'workspace', jsonText = '' } = {}) {
157
- let parsed;
158
- try {
159
- parsed = typeof jsonText === 'string' ? JSON.parse(jsonText) : jsonText;
160
- } catch {
161
- throw new Error('粘贴的内容不是合法 JSON。');
162
- }
163
- const map = parsed?.mcpServers && typeof parsed.mcpServers === 'object' ? parsed.mcpServers : parsed;
164
- if (!map || typeof map !== 'object' || Array.isArray(map)) {
165
- throw new Error('JSON 需要包含 mcpServers 对象或直接为服务名称映射。');
166
- }
167
- const entries = Object.entries(map);
168
- if (!entries.length) throw new Error('JSON 中没有可导入的 MCP 服务。');
169
-
170
- const filePath = scope === 'global' || !workspace ? globalMcpPath() : workspaceMcpPath(workspace);
171
- const current = readMcpFile(filePath);
172
- const imported = [];
173
- for (const [name, raw] of entries) {
174
- if (!NAME_RE.test(name)) throw new Error(`服务名称无效:${name}`);
175
- current[name] = normalizeServerConfig(raw);
176
- imported.push(name);
177
- }
178
- writeMcpFile(filePath, current);
179
- return imported;
180
- }
181
-
182
- async function withMcpClient(serverConfig, workspace, fn, { timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
183
- const client = new Client({ name: 'clado-native-agent', version: VERSION });
184
- let transport;
185
- if (serverConfig.type === 'http') {
186
- transport = new StreamableHTTPClientTransport(new URL(serverConfig.url), {
187
- requestInit: serverConfig.headers && Object.keys(serverConfig.headers).length
188
- ? { headers: serverConfig.headers }
189
- : undefined,
190
- });
191
- } else {
192
- transport = new StdioClientTransport({
193
- command: serverConfig.command,
194
- args: serverConfig.args || [],
195
- env: { ...process.env, ...(serverConfig.env || {}) },
196
- cwd: serverConfig.cwd || workspace || process.cwd(),
197
- stderr: 'pipe',
198
- });
199
- }
200
-
201
- let timer;
202
- const timeoutPromise = new Promise((_, reject) => {
203
- timer = setTimeout(() => reject(new Error(`连接 MCP 服务超时(>${Math.round(timeoutMs / 1000)}s)`)), timeoutMs);
204
- });
205
-
206
- try {
207
- await Promise.race([client.connect(transport), timeoutPromise]);
208
- return await Promise.race([fn(client), timeoutPromise]);
209
- } finally {
210
- clearTimeout(timer);
211
- await client.close().catch(() => {});
212
- }
213
- }
214
-
215
- export async function testMcpServer(workspace, serverConfig, { timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {
216
- const started = Date.now();
217
- try {
218
- const normalized = normalizeServerConfig(serverConfig);
219
- const tools = await withMcpClient(normalized, workspace, async client => {
220
- const res = await client.listTools();
221
- return Array.isArray(res?.tools) ? res.tools : [];
222
- }, { timeoutMs });
223
- return {
224
- ok: true,
225
- latencyMs: Date.now() - started,
226
- toolCount: tools.length,
227
- tools: tools.map(t => ({ name: t.name, description: t.description || '' })),
228
- };
229
- } catch (error) {
230
- return {
231
- ok: false,
232
- latencyMs: Date.now() - started,
233
- toolCount: 0,
234
- tools: [],
235
- error: error?.message || String(error),
236
- };
237
- }
238
- }
239
-
240
- export function encodeMcpToolName(serverName, toolName) {
241
- const safeTool = String(toolName || '').replace(/[^a-zA-Z0-9_-]/g, '_');
242
- return `mcp__${serverName}__${safeTool}`;
243
- }
244
-
245
- export async function discoverExternalMcpTools(workspace, { pluginMcp = [], timeoutMs = 6000 } = {}) {
246
- const servers = listMcpServers(workspace, { pluginMcp, includeSecrets: true }).filter(s => s.config.enabled !== false);
247
- if (!servers.length) return { definitions: [], registry: new Map(), errors: [] };
248
-
249
- const definitions = [];
250
- const registry = new Map();
251
- const errors = [];
252
-
253
- await Promise.all(servers.map(async entry => {
254
- try {
255
- const tools = await withMcpClient(entry.config, workspace, async client => {
256
- const res = await client.listTools();
257
- return Array.isArray(res?.tools) ? res.tools : [];
258
- }, { timeoutMs });
259
-
260
- for (const tool of tools) {
261
- const fnName = encodeMcpToolName(entry.name, tool.name);
262
- registry.set(fnName, {
263
- serverName: entry.name,
264
- toolName: tool.name,
265
- config: entry.config,
266
- });
267
- definitions.push({
268
- type: 'function',
269
- function: {
270
- name: fnName,
271
- description: `[MCP:${entry.name}] ${tool.description || tool.name}`,
272
- parameters: tool.inputSchema && typeof tool.inputSchema === 'object'
273
- ? tool.inputSchema
274
- : { type: 'object', properties: {} },
275
- },
276
- });
277
- }
278
- } catch (error) {
279
- errors.push({ server: entry.name, error: error?.message || String(error) });
280
- }
281
- }));
282
-
283
- return { definitions, registry, errors };
284
- }
285
-
286
- export async function callExternalMcpTool(entry, args = {}, workspace, { timeoutMs = 20000 } = {}) {
287
- return withMcpClient(entry.config, workspace, async client => {
288
- const result = await client.callTool({
289
- name: entry.toolName,
290
- arguments: args && typeof args === 'object' ? args : {},
291
- });
292
- const content = Array.isArray(result?.content) ? result.content : [];
293
- const textParts = content
294
- .map(part => {
295
- if (part?.type === 'text') return part.text || '';
296
- if (part?.type === 'resource' && part.resource?.text) return part.resource.text;
297
- return JSON.stringify(part);
298
- })
299
- .filter(Boolean);
300
- return {
301
- ok: !result?.isError,
302
- server: entry.serverName,
303
- tool: entry.toolName,
304
- text: textParts.join('\n') || (result?.structuredContent ? JSON.stringify(result.structuredContent) : ''),
305
- ...(result?.structuredContent ? { structuredContent: result.structuredContent } : {}),
306
- };
307
- }, { timeoutMs });
308
- }
@@ -1,234 +0,0 @@
1
- /**
2
- * 本地存量代码只读分析探针(Local Codebase Probe)。
3
- *
4
- * 严格限定在工作区目录内,屏蔽 .git / node_modules / .clado / 符号链接逃逸,
5
- * 为独立垂直 Agent 提供只读的目录树、符号检索、精准行区间读取与 Git Diff 证据。
6
- */
7
-
8
- import { execFile } from 'node:child_process';
9
- import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
10
- import { extname, join, relative, resolve, sep } from 'node:path';
11
- import { promisify } from 'node:util';
12
-
13
- const execFileAsync = promisify(execFile);
14
- const IGNORED_DIRS = new Set(['.git', '.clado', 'node_modules', 'dist', 'build', 'coverage', '.next', '.nuxt', 'target', '__pycache__', '.venv']);
15
- const BINARY_EXTS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.webp', '.ico', '.pdf', '.zip', '.gz', '.tgz', '.woff', '.woff2', '.ttf', '.eot', '.mp4', '.mp3', '.exe', '.dll', '.so', '.dylib', '.class', '.jar']);
16
-
17
- function assertInsideWorkspace(workspace, targetPath = '.') {
18
- const root = realpathSync(resolve(workspace));
19
- const candidate = resolve(root, String(targetPath || '.'));
20
- if (candidate !== root && !candidate.startsWith(root + sep)) {
21
- throw new Error('路径超出当前工作区范围。');
22
- }
23
- if (!existsSync(candidate)) throw new Error('目标路径不存在:' + targetPath);
24
- const actual = realpathSync(candidate);
25
- if (actual !== root && !actual.startsWith(root + sep)) {
26
- throw new Error('符号链接指向工作区之外,已拒绝访问。');
27
- }
28
- return { root, actual };
29
- }
30
-
31
- /**
32
- * 列出本地仓库目录树与文件列表(跳过隐藏目录、依赖目录与符号链接)。
33
- */
34
- export function probeTree(workspace, { path = '.', maxDepth = 4, maxFiles = 200 } = {}) {
35
- const { root, actual } = assertInsideWorkspace(workspace, path);
36
- const limitDepth = Math.min(8, Math.max(1, Number(maxDepth) || 4));
37
- const limitFiles = Math.min(500, Math.max(1, Number(maxFiles) || 200));
38
- const files = [];
39
- let truncated = false;
40
-
41
- function walk(dir, depth) {
42
- if (files.length >= limitFiles) { truncated = true; return; }
43
- let entries;
44
- try { entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name)); }
45
- catch { return; }
46
- for (const entry of entries) {
47
- if (files.length >= limitFiles) { truncated = true; return; }
48
- if (entry.isSymbolicLink()) continue;
49
- if (entry.isDirectory()) {
50
- if (IGNORED_DIRS.has(entry.name) || entry.name.startsWith('.')) continue;
51
- if (depth < limitDepth) walk(join(dir, entry.name), depth + 1);
52
- } else if (entry.isFile()) {
53
- if (entry.name.startsWith('.') && entry.name !== '.env.example') continue;
54
- const full = join(dir, entry.name);
55
- files.push(relative(root, full).split(sep).join('/'));
56
- }
57
- }
58
- }
59
-
60
- if (lstatSync(actual).isFile()) {
61
- files.push(relative(root, actual).split(sep).join('/'));
62
- } else {
63
- walk(actual, 1);
64
- }
65
- return { root: relative(root, actual).split(sep).join('/') || '.', count: files.length, truncated, files };
66
- }
67
-
68
- /**
69
- * 在本地代码中检索关键字或符号定义(优先使用 rg,不可用时回退纯 JS 扫描)。
70
- */
71
- export async function probeSearch(workspace, { query, path = '.', glob, maxResults = 40 } = {}) {
72
- const q = String(query || '').trim();
73
- if (!q) throw new Error('query 不能为空。');
74
- const { root, actual } = assertInsideWorkspace(workspace, path);
75
- const limit = Math.min(100, Math.max(1, Number(maxResults) || 40));
76
-
77
- try {
78
- const args = ['--json', '--fixed-strings', '--no-heading', '--max-count', '10', '--glob', '!.git', '--glob', '!node_modules', '--glob', '!.clado'];
79
- if (glob && typeof glob === 'string') args.push('--glob', glob);
80
- args.push('--', q, actual);
81
- const { stdout } = await execFileAsync('rg', args, { cwd: root, maxBuffer: 4 * 1024 * 1024, timeout: 8000 });
82
- const matches = [];
83
- for (const line of stdout.split('\n')) {
84
- if (!line) continue;
85
- const item = JSON.parse(line);
86
- if (item.type !== 'match') continue;
87
- const file = relative(root, resolve(root, item.data.path.text)).split(sep).join('/');
88
- matches.push({
89
- file,
90
- line: item.data.line_number,
91
- text: String(item.data.lines?.text || '').replace(/\r?\n$/, '').slice(0, 240),
92
- });
93
- if (matches.length >= limit) break;
94
- }
95
- return { query: q, count: matches.length, truncated: matches.length >= limit, matches };
96
- } catch (error) {
97
- // rg exit code 1 means zero matches (not an error)
98
- if (error?.code === 1 && !error.stderr) {
99
- return { query: q, count: 0, truncated: false, matches: [] };
100
- }
101
- // Fallback pure-JS search when rg is unavailable
102
- const { files } = probeTree(workspace, { path, maxDepth: 6, maxFiles: 300 });
103
- const matches = [];
104
- for (const file of files) {
105
- if (BINARY_EXTS.has(extname(file).toLowerCase())) continue;
106
- let content;
107
- try {
108
- const full = join(root, file);
109
- if (lstatSync(full).size > 512 * 1024) continue;
110
- content = readFileSync(full, 'utf8');
111
- } catch { continue; }
112
- const lines = content.split(/\r?\n/);
113
- for (let i = 0; i < lines.length; i++) {
114
- if (lines[i].includes(q)) {
115
- matches.push({ file, line: i + 1, text: lines[i].slice(0, 240) });
116
- if (matches.length >= limit) return { query: q, count: matches.length, truncated: true, matches };
117
- }
118
- }
119
- }
120
- return { query: q, count: matches.length, truncated: false, matches };
121
- }
122
- }
123
-
124
- /**
125
- * 读取指定本地源码文件的有界行区间(1-indexed,单次最多 400 行)。
126
- */
127
- export function probeRead(workspace, { file, startLine = 1, endLine } = {}) {
128
- if (!file || typeof file !== 'string') throw new Error('file 必填。');
129
- const { root, actual } = assertInsideWorkspace(workspace, file);
130
- const stat = lstatSync(actual);
131
- if (!stat.isFile()) throw new Error('目标不是普通文件:' + file);
132
- if (BINARY_EXTS.has(extname(actual).toLowerCase())) throw new Error('不支持读取二进制文件:' + file);
133
- if (stat.size > 2 * 1024 * 1024) throw new Error('文件超过 2 MB 读取限制。');
134
-
135
- const lines = readFileSync(actual, 'utf8').split(/\r?\n/);
136
- const start = Math.max(1, Math.min(lines.length || 1, Number(startLine) || 1));
137
- const requestedEnd = endLine ? Number(endLine) : start + 199;
138
- const end = Math.max(start, Math.min(lines.length, start + 399, requestedEnd));
139
- const slice = lines.slice(start - 1, end).map((text, idx) => `${start + idx}: ${text}`).join('\n');
140
- return {
141
- file: relative(root, actual).split(sep).join('/'),
142
- totalLines: lines.length,
143
- startLine: start,
144
- endLine: end,
145
- truncated: end < lines.length,
146
- content: slice,
147
- };
148
- }
149
-
150
- /**
151
- * 读取本地 Git 仓库状态与 Diff(用于存量改造分析及外包开发后的验收核对)。
152
- */
153
- export async function probeGitDiff(workspace, { ref = '', statOnly = false, maxChars = 16000 } = {}) {
154
- const { root } = assertInsideWorkspace(workspace, '.');
155
- const runGit = async args => {
156
- const { stdout } = await execFileAsync('git', args, { cwd: root, maxBuffer: 4 * 1024 * 1024, timeout: 8000 });
157
- return stdout;
158
- };
159
- try {
160
- const branch = (await runGit(['rev-parse', '--abbrev-ref', 'HEAD'])).trim();
161
- const status = (await runGit(['status', '--short'])).trim();
162
- const diffArgs = ref && /^[a-zA-Z0-9._/~^-]+$/.test(ref) ? ['diff', ref] : ['diff'];
163
- const stat = (await runGit([...diffArgs, '--stat'])).trim();
164
- let diff = '';
165
- let truncated = false;
166
- if (!statOnly) {
167
- const fullDiff = await runGit(diffArgs);
168
- const limit = Math.min(32000, Math.max(1000, Number(maxChars) || 16000));
169
- truncated = fullDiff.length > limit;
170
- diff = truncated ? fullDiff.slice(0, limit) + '\n... (diff truncated)' : fullDiff;
171
- }
172
- return { isGitRepo: true, branch, status, stat, diff, truncated };
173
- } catch (error) {
174
- return { isGitRepo: false, branch: '', status: '', stat: '', diff: '', truncated: false, message: '当前目录不是 Git 仓库或无法读取 git 状态。' };
175
- }
176
- }
177
-
178
- const READONLY_CMD_RE = /^(git\s+(status|diff|log|show|branch|rev-parse)\b|ls\b|pwd\b|rg\b|grep\b|cat\b|head\b|tail\b|wc\b|which\b|node\s+(-v|--version)\b|npm\s+(-v|--version)\b|pnpm\s+(-v|--version)\b)/i;
179
- const BLOCKED_CMD_RE = /(\brm\s+-[a-z]*r[a-z]*f?\s+\/(\s|$)|:\(\)\s*\{|\bmkfs\b|\bshutdown\b|\breboot\b|\bdd\s+if=)/i;
180
- const SHELL_CHAIN_RE = /[;&|`$<>]|\r|\n/;
181
-
182
- /**
183
- * 对命令行调用进行安全分级:blocked(高危拦截)| readonly(只读免审)| write_or_exec(需按策略审批)。
184
- */
185
- export function classifyShellCommand(command) {
186
- const clean = String(command || '').trim();
187
- if (!clean) return 'blocked';
188
- if (BLOCKED_CMD_RE.test(clean)) return 'blocked';
189
- if (!SHELL_CHAIN_RE.test(clean) && READONLY_CMD_RE.test(clean)) return 'readonly';
190
- return 'write_or_exec';
191
- }
192
-
193
- /**
194
- * 在当前工作区根目录受控执行单条命令(带超时与输出截断保护)。
195
- */
196
- export async function executeWorkspaceCommand(workspace, { command, timeoutMs = 20000, maxChars = 16000 } = {}) {
197
- const clean = String(command || '').trim();
198
- if (!clean) throw new Error('command 不能为空。');
199
- if (classifyShellCommand(clean) === 'blocked') {
200
- throw new Error('该命令命中高危安全规则,已被系统拦截。');
201
- }
202
- const { root } = assertInsideWorkspace(workspace, '.');
203
- const timeout = Math.min(60000, Math.max(2000, Number(timeoutMs) || 20000));
204
- const limit = Math.min(32000, Math.max(1000, Number(maxChars) || 16000));
205
-
206
- try {
207
- const { stdout = '', stderr = '' } = await execFileAsync('bash', ['-lc', clean], {
208
- cwd: root,
209
- timeout,
210
- maxBuffer: 4 * 1024 * 1024,
211
- env: { ...process.env, PAGER: 'cat', GIT_TERMINAL_PROMPT: '0' },
212
- });
213
- const combined = [stdout, stderr].filter(Boolean).join('\n');
214
- const truncated = combined.length > limit;
215
- return {
216
- ok: true,
217
- exitCode: 0,
218
- command: clean,
219
- output: truncated ? combined.slice(0, limit) + '\n... (output truncated)' : combined,
220
- truncated,
221
- };
222
- } catch (error) {
223
- const out = [error?.stdout || '', error?.stderr || '', error?.message || ''].filter(Boolean).join('\n');
224
- const truncated = out.length > limit;
225
- return {
226
- ok: false,
227
- exitCode: typeof error?.code === 'number' ? error.code : 1,
228
- command: clean,
229
- output: truncated ? out.slice(0, limit) + '\n... (output truncated)' : out,
230
- truncated,
231
- };
232
- }
233
- }
234
-