cladogram 0.5.4 → 0.5.5-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -6
- package/bin/clado.js +5 -5
- package/docs/release.md +13 -0
- package/package.json +1 -1
- package/plugins/agent/index.js +458 -25
- package/plugins/agent/style.css +299 -8
- package/plugins/directory/capabilities.json +1 -1
- package/plugins/directory/index.js +57 -2
- package/plugins/directory/style.css +11 -0
- package/plugins/view-controls/index.js +1 -1
- package/plugins/view-controls/style.css +30 -10
- package/skills/clado/SKILL.md +17 -16
- package/src/agent/executors.js +213 -0
- package/src/agent/probe.js +176 -0
- package/src/agent/providers/anthropic.js +220 -0
- package/src/agent/providers/index.js +52 -0
- package/src/agent/providers/openai.js +146 -0
- package/src/agent/runtime.js +557 -0
- package/src/agent/sessions.js +129 -0
- package/src/html/app-css.js +62 -9
- package/src/html/canvas-chain.js +2 -1
- package/src/html/canvas-ui.css +63 -0
- package/src/html/page.js +4 -0
- package/src/html/plugin-ui.css +12 -0
- package/src/html/plugin-ui.js +8 -2
- package/src/html/runtime-api.js +136 -5
- package/src/html/runtime.js +160 -290
- package/src/html/view-registry.js +95 -0
- package/src/html/views/view-cards.js +28 -0
- package/src/html/views/view-doc.js +51 -0
- package/src/html/views/view-mindmap.js +173 -0
- package/src/server/agent.js +335 -17
- package/src/server/assets/library-canvas.js +13 -3
- package/src/server/assets/library-plugin-bridge.js +2 -2
- package/src/server/assets/library-plugins.js +2 -2
- package/src/server/assets/library.css +5 -0
- package/src/server/assets/library.html +1 -1
- package/src/server/assets/library.js +157 -20
- package/src/server/events.js +189 -0
- package/src/server/export.js +1 -1
- package/src/server/mcp.js +16 -16
- package/src/server/plugin-capabilities.js +38 -22
- package/src/server/plugin-settings.js +27 -1
- package/src/server/plugins.js +17 -4
- package/src/server/workspace.js +171 -56
- package/src/skill/install.js +1 -1
- package/src/skill/targets.js +3 -3
- package/src/util/update.js +3 -2
- package/src/workspace/service.js +23 -15
- package/src/workspace/storage.js +88 -20
- package/templates/business-flow.mdc +1 -1
- package/templates/call-chain.mdc +1 -1
- package/templates/data-design.mdc +1 -1
- package/templates/test-cases.mdc +47 -0
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ACP 执行器插件注册、任务包组装与运行记录(.clado/runs/)。
|
|
3
|
+
*
|
|
4
|
+
* 将外部 Coding Agent(ZCode / Claude Code / Codex / 自定义插件执行器)统一建模为
|
|
5
|
+
* 可发现、可派单的 ACP Executor,用户在 Clado 面板内一键外包开发并实时等待结果。
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { randomUUID } from 'node:crypto';
|
|
9
|
+
import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
10
|
+
import { join } from 'node:path';
|
|
11
|
+
import { z } from 'zod/v4';
|
|
12
|
+
import { readDocument, scanDirectory, workspacePath } from '../workspace/documents.js';
|
|
13
|
+
|
|
14
|
+
export const executorSchema = z.strictObject({
|
|
15
|
+
id: z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,63}$/),
|
|
16
|
+
name: z.string().trim().min(1).max(80),
|
|
17
|
+
protocol: z.literal('acp').default('acp'),
|
|
18
|
+
command: z.string().trim().min(1).max(2048),
|
|
19
|
+
args: z.array(z.string().max(2048)).max(32).default([]),
|
|
20
|
+
env: z.record(z.string(), z.string().max(2048)).default({}),
|
|
21
|
+
capabilities: z.array(z.string().min(1).max(64)).max(16).default(['code.write', 'test.run']),
|
|
22
|
+
description: z.string().max(400).optional(),
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 发现工作区可用的全部 ACP 执行器(内置/用户配置 + 插件包声明的 contributes.executors)。
|
|
27
|
+
*/
|
|
28
|
+
export function discoverExecutors({ stateDir, settings = {}, pluginDescriptors = [] } = {}) {
|
|
29
|
+
const result = [];
|
|
30
|
+
const seen = new Set();
|
|
31
|
+
const push = item => {
|
|
32
|
+
if (!item || seen.has(item.id)) return;
|
|
33
|
+
seen.add(item.id);
|
|
34
|
+
result.push(item);
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
if (settings.command) {
|
|
38
|
+
push({
|
|
39
|
+
id: 'acp.default',
|
|
40
|
+
name: settings.name || '默认 ACP 执行器',
|
|
41
|
+
protocol: 'acp',
|
|
42
|
+
command: settings.command,
|
|
43
|
+
args: Array.isArray(settings.args) ? settings.args : [],
|
|
44
|
+
env: settings.env && typeof settings.env === 'object' ? settings.env : {},
|
|
45
|
+
capabilities: ['code.write', 'test.run'],
|
|
46
|
+
description: '来自「灵感」设置的默认外部 ACP Coding Agent',
|
|
47
|
+
source: 'settings',
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
for (const raw of Array.isArray(settings.executors) ? settings.executors : []) {
|
|
52
|
+
const parsed = executorSchema.safeParse(raw);
|
|
53
|
+
if (!parsed.success) continue;
|
|
54
|
+
push({ ...parsed.data, source: 'settings' });
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// 从已加载插件或 .clado/plugins/*/clado-plugin.json 发现声明式执行器
|
|
58
|
+
for (const plugin of pluginDescriptors) {
|
|
59
|
+
for (const raw of Array.isArray(plugin?.executors) ? plugin.executors : []) {
|
|
60
|
+
const parsed = executorSchema.safeParse(raw);
|
|
61
|
+
if (!parsed.success) continue;
|
|
62
|
+
push({ ...parsed.data, id: plugin.id + '/' + parsed.data.id, pluginId: plugin.id, source: 'plugin' });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (stateDir) {
|
|
67
|
+
const dir = join(stateDir, 'plugins');
|
|
68
|
+
if (existsSync(dir) && lstatSync(dir).isDirectory()) {
|
|
69
|
+
for (const entry of readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
70
|
+
if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
|
|
71
|
+
const manifestPath = join(dir, entry.name, 'clado-plugin.json');
|
|
72
|
+
if (!existsSync(manifestPath)) continue;
|
|
73
|
+
try {
|
|
74
|
+
const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
|
|
75
|
+
const declared = manifest?.contributes?.executors;
|
|
76
|
+
if (!Array.isArray(declared) || !manifest?.id) continue;
|
|
77
|
+
for (const raw of declared) {
|
|
78
|
+
const parsed = executorSchema.safeParse(raw);
|
|
79
|
+
if (!parsed.success) continue;
|
|
80
|
+
push({
|
|
81
|
+
...parsed.data,
|
|
82
|
+
id: manifest.id + '/' + parsed.data.id,
|
|
83
|
+
pluginId: manifest.id,
|
|
84
|
+
source: 'plugin',
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
} catch {}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
return result;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* 面向前端的安全摘要(不向浏览器泄露 command/env 敏感细节)。
|
|
97
|
+
*/
|
|
98
|
+
export function publicExecutorList(executors) {
|
|
99
|
+
return executors.map(({ id, name, protocol, capabilities, description, source, pluginId }) => ({
|
|
100
|
+
id, name, protocol, capabilities, description: description || '', source, ...(pluginId ? { pluginId } : {}),
|
|
101
|
+
}));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* 基于当前画布文档与选区,组装发给外部 ACP Coding Agent 的 Executable Spec 任务包。
|
|
106
|
+
*/
|
|
107
|
+
export function buildDispatchPrompt({ workspace, documentRoot, file, selection = [], instruction = '', mcpName = '' }) {
|
|
108
|
+
const blocks = [];
|
|
109
|
+
let specExcerpt = '';
|
|
110
|
+
let relatedTests = [];
|
|
111
|
+
|
|
112
|
+
if (documentRoot && file) {
|
|
113
|
+
try {
|
|
114
|
+
const fullPath = workspacePath(documentRoot, file);
|
|
115
|
+
const item = readDocument(fullPath);
|
|
116
|
+
specExcerpt = item.source.length > 24000
|
|
117
|
+
? item.source.slice(0, 24000) + '\n\n<!-- spec truncated; use Clado MCP to read full document -->'
|
|
118
|
+
: item.source;
|
|
119
|
+
} catch {}
|
|
120
|
+
try {
|
|
121
|
+
const { documents } = scanDirectory(documentRoot);
|
|
122
|
+
relatedTests = documents
|
|
123
|
+
.filter(d => d.file !== file && /test|用例|qa/i.test(d.file + ' ' + d.title))
|
|
124
|
+
.slice(0, 5)
|
|
125
|
+
.map(d => `${d.file}(${d.title})`);
|
|
126
|
+
} catch {}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
blocks.push({
|
|
130
|
+
type: 'text',
|
|
131
|
+
text: [
|
|
132
|
+
'你是通过 Clado ACP 执行器插件被派发的外部开发执行器(Coding Agent)。',
|
|
133
|
+
'你的任务是严格依据 Clado 画布中已拍板的设计规格与测试用例在本地仓库完成代码实现与测试验证。',
|
|
134
|
+
mcpName ? `执行期间可通过已连接的 ${mcpName} MCP 读取更多画布文档或更新实现备注(workspace: ${workspace})。` : '',
|
|
135
|
+
'完成后请给出简明实现总结:改了哪些文件、跑了哪些测试、是否有偏离设计之处。',
|
|
136
|
+
].filter(Boolean).join('\n'),
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
blocks.push({
|
|
140
|
+
type: 'text',
|
|
141
|
+
text: JSON.stringify({
|
|
142
|
+
workspace,
|
|
143
|
+
specFile: file || '',
|
|
144
|
+
selection,
|
|
145
|
+
relatedTestDocs: relatedTests,
|
|
146
|
+
}),
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
if (specExcerpt) {
|
|
150
|
+
blocks.push({
|
|
151
|
+
type: 'text',
|
|
152
|
+
text: `以下为当前画布规格全文(${file}):\n\n${specExcerpt}`,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
blocks.push({
|
|
157
|
+
type: 'text',
|
|
158
|
+
text: '用户派发指令:\n' + (instruction.trim() || '请严格按上述 Clado 设计规格完成代码实现与测试验证。'),
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
return blocks;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/* ── 轻量运行记录(.clado/runs/<runId>.json) ─────────────────── */
|
|
165
|
+
|
|
166
|
+
function runsDir(stateDir) {
|
|
167
|
+
const dir = join(stateDir, 'runs');
|
|
168
|
+
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
|
|
169
|
+
return dir;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function createRunRecord(stateDir, record) {
|
|
173
|
+
if (!stateDir) return { id: randomUUID(), ...record, createdAt: new Date().toISOString() };
|
|
174
|
+
const id = record.id || randomUUID();
|
|
175
|
+
const payload = {
|
|
176
|
+
id,
|
|
177
|
+
kind: record.kind || 'builtin',
|
|
178
|
+
mode: record.mode || 'design',
|
|
179
|
+
executorId: record.executorId || null,
|
|
180
|
+
file: record.file || '',
|
|
181
|
+
instruction: String(record.instruction || '').slice(0, 400),
|
|
182
|
+
status: 'running',
|
|
183
|
+
createdAt: new Date().toISOString(),
|
|
184
|
+
updatedAt: new Date().toISOString(),
|
|
185
|
+
summary: '',
|
|
186
|
+
touchedFiles: [],
|
|
187
|
+
};
|
|
188
|
+
try { writeFileSync(join(runsDir(stateDir), id + '.json'), JSON.stringify(payload, null, 2) + '\n'); } catch {}
|
|
189
|
+
return payload;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
export function updateRunRecord(stateDir, run, patch = {}) {
|
|
193
|
+
if (!run) return null;
|
|
194
|
+
const next = { ...run, ...patch, updatedAt: new Date().toISOString() };
|
|
195
|
+
if (stateDir && next.id) {
|
|
196
|
+
try { writeFileSync(join(runsDir(stateDir), next.id + '.json'), JSON.stringify(next, null, 2) + '\n'); } catch {}
|
|
197
|
+
}
|
|
198
|
+
return next;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function listRunRecords(stateDir, limit = 12) {
|
|
202
|
+
if (!stateDir) return [];
|
|
203
|
+
const dir = join(stateDir, 'runs');
|
|
204
|
+
if (!existsSync(dir) || !lstatSync(dir).isDirectory()) return [];
|
|
205
|
+
const items = [];
|
|
206
|
+
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
|
207
|
+
if (!entry.isFile() || !entry.name.endsWith('.json')) continue;
|
|
208
|
+
try { items.push(JSON.parse(readFileSync(join(dir, entry.name), 'utf8'))); } catch {}
|
|
209
|
+
}
|
|
210
|
+
return items
|
|
211
|
+
.sort((a, b) => String(b.createdAt || '').localeCompare(String(a.createdAt || '')))
|
|
212
|
+
.slice(0, limit);
|
|
213
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Anthropic 原生 Messages API 流式适配器(/v1/messages)。
|
|
3
|
+
*
|
|
4
|
+
* 原生支持:
|
|
5
|
+
* - Prompt Caching(对 system prompt 与最后一个工具定义自动附加 ephemeral cache_control)
|
|
6
|
+
* - thinking_delta / text_delta / tool_use input_json_delta 实时流解析
|
|
7
|
+
* - 将统一内部消息格式无损映射为 Anthropic blocks,并回产出统一内部 assistant message。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
function toAnthropicTools(tools = []) {
|
|
11
|
+
const mapped = tools.map(tool => ({
|
|
12
|
+
name: tool.function.name,
|
|
13
|
+
description: tool.function.description || '',
|
|
14
|
+
input_schema: tool.function.parameters || { type: 'object', properties: {} },
|
|
15
|
+
}));
|
|
16
|
+
if (mapped.length) {
|
|
17
|
+
mapped[mapped.length - 1] = { ...mapped[mapped.length - 1], cache_control: { type: 'ephemeral' } };
|
|
18
|
+
}
|
|
19
|
+
return mapped;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function toAnthropicPayload(messages = []) {
|
|
23
|
+
const systemBlocks = [];
|
|
24
|
+
const out = [];
|
|
25
|
+
|
|
26
|
+
const pushMessage = (role, block) => {
|
|
27
|
+
const prev = out[out.length - 1];
|
|
28
|
+
if (prev && prev.role === role) prev.content.push(block);
|
|
29
|
+
else out.push({ role, content: [block] });
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
for (const msg of messages) {
|
|
33
|
+
if (!msg) continue;
|
|
34
|
+
if (msg.role === 'system') {
|
|
35
|
+
if (msg.content) {
|
|
36
|
+
systemBlocks.push({
|
|
37
|
+
type: 'text',
|
|
38
|
+
text: String(msg.content),
|
|
39
|
+
cache_control: { type: 'ephemeral' },
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (msg.role === 'user') {
|
|
45
|
+
pushMessage('user', { type: 'text', text: String(msg.content || '') });
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (msg.role === 'assistant') {
|
|
49
|
+
const blocks = [];
|
|
50
|
+
if (msg.content) blocks.push({ type: 'text', text: String(msg.content) });
|
|
51
|
+
for (const call of msg.tool_calls || []) {
|
|
52
|
+
let input = {};
|
|
53
|
+
try { input = JSON.parse(call.function?.arguments || '{}'); } catch {}
|
|
54
|
+
blocks.push({
|
|
55
|
+
type: 'tool_use',
|
|
56
|
+
id: call.id,
|
|
57
|
+
name: call.function?.name || 'unknown',
|
|
58
|
+
input,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
if (blocks.length) out.push({ role: 'assistant', content: blocks });
|
|
62
|
+
continue;
|
|
63
|
+
}
|
|
64
|
+
if (msg.role === 'tool') {
|
|
65
|
+
pushMessage('user', {
|
|
66
|
+
type: 'tool_result',
|
|
67
|
+
tool_use_id: msg.tool_call_id,
|
|
68
|
+
content: String(msg.content || ''),
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return { system: systemBlocks, messages: out };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function streamAnthropic({
|
|
76
|
+
baseUrl,
|
|
77
|
+
apiKey,
|
|
78
|
+
model,
|
|
79
|
+
messages,
|
|
80
|
+
tools,
|
|
81
|
+
maxTokens = 4096,
|
|
82
|
+
signal,
|
|
83
|
+
onEvent = () => {},
|
|
84
|
+
fetchImpl = fetch,
|
|
85
|
+
}) {
|
|
86
|
+
const cleanBase = String(baseUrl || 'https://api.anthropic.com/v1').replace(/\/+$/, '');
|
|
87
|
+
const url = cleanBase.endsWith('/messages') ? cleanBase : cleanBase + '/messages';
|
|
88
|
+
const converted = toAnthropicPayload(messages);
|
|
89
|
+
const anthropicTools = toAnthropicTools(tools);
|
|
90
|
+
|
|
91
|
+
const response = await fetchImpl(url, {
|
|
92
|
+
method: 'POST',
|
|
93
|
+
headers: {
|
|
94
|
+
'content-type': 'application/json',
|
|
95
|
+
'x-api-key': apiKey,
|
|
96
|
+
'anthropic-version': '2023-06-01',
|
|
97
|
+
},
|
|
98
|
+
body: JSON.stringify({
|
|
99
|
+
model,
|
|
100
|
+
max_tokens: maxTokens,
|
|
101
|
+
...(converted.system.length ? { system: converted.system } : {}),
|
|
102
|
+
messages: converted.messages,
|
|
103
|
+
...(anthropicTools.length ? { tools: anthropicTools } : {}),
|
|
104
|
+
stream: true,
|
|
105
|
+
}),
|
|
106
|
+
signal,
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
if (!response.ok) {
|
|
110
|
+
const body = await response.text().catch(() => '');
|
|
111
|
+
throw new Error(`Anthropic 接口失败(HTTP ${response.status})${body ? ':' + body.slice(0, 240) : ''}`);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const contentType = response.headers?.get?.('content-type') || '';
|
|
115
|
+
if (!contentType.includes('text/event-stream') || !response.body) {
|
|
116
|
+
const data = await response.json();
|
|
117
|
+
let text = '', thinking = '';
|
|
118
|
+
const calls = [];
|
|
119
|
+
for (const block of data?.content || []) {
|
|
120
|
+
if (block.type === 'thinking' && block.thinking) {
|
|
121
|
+
thinking += block.thinking;
|
|
122
|
+
onEvent({ type: 'thinking_delta', text: block.thinking });
|
|
123
|
+
} else if (block.type === 'text' && block.text) {
|
|
124
|
+
text += block.text;
|
|
125
|
+
onEvent({ type: 'text_delta', text: block.text });
|
|
126
|
+
} else if (block.type === 'tool_use') {
|
|
127
|
+
onEvent({ type: 'tool_call_start', id: block.id, name: block.name });
|
|
128
|
+
calls.push({
|
|
129
|
+
id: block.id,
|
|
130
|
+
type: 'function',
|
|
131
|
+
function: { name: block.name, arguments: JSON.stringify(block.input || {}) },
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
return {
|
|
136
|
+
message: { role: 'assistant', content: text || null, ...(calls.length ? { tool_calls: calls } : {}) },
|
|
137
|
+
thinking,
|
|
138
|
+
stopReason: data?.stop_reason || 'end_turn',
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const reader = response.body.getReader();
|
|
143
|
+
const decoder = new TextDecoder();
|
|
144
|
+
let buffer = '';
|
|
145
|
+
let content = '';
|
|
146
|
+
let thinking = '';
|
|
147
|
+
let stopReason = 'end_turn';
|
|
148
|
+
const blocks = new Map();
|
|
149
|
+
|
|
150
|
+
function processEvent(rawData) {
|
|
151
|
+
if (!rawData || rawData === '[DONE]') return;
|
|
152
|
+
let ev;
|
|
153
|
+
try { ev = JSON.parse(rawData); } catch { return; }
|
|
154
|
+
if (ev.type === 'content_block_start') {
|
|
155
|
+
const idx = ev.index ?? 0;
|
|
156
|
+
const b = ev.content_block || {};
|
|
157
|
+
if (b.type === 'tool_use') {
|
|
158
|
+
blocks.set(idx, { type: 'tool_use', id: b.id, name: b.name, json: '' });
|
|
159
|
+
onEvent({ type: 'tool_call_start', id: b.id, name: b.name });
|
|
160
|
+
} else {
|
|
161
|
+
blocks.set(idx, { type: b.type || 'text' });
|
|
162
|
+
}
|
|
163
|
+
} else if (ev.type === 'content_block_delta') {
|
|
164
|
+
const idx = ev.index ?? 0;
|
|
165
|
+
const delta = ev.delta || {};
|
|
166
|
+
if (delta.type === 'thinking_delta' && delta.thinking) {
|
|
167
|
+
thinking += delta.thinking;
|
|
168
|
+
onEvent({ type: 'thinking_delta', text: delta.thinking });
|
|
169
|
+
} else if (delta.type === 'text_delta' && delta.text) {
|
|
170
|
+
content += delta.text;
|
|
171
|
+
onEvent({ type: 'text_delta', text: delta.text });
|
|
172
|
+
} else if (delta.type === 'input_json_delta' && delta.partial_json) {
|
|
173
|
+
const entry = blocks.get(idx);
|
|
174
|
+
if (entry && entry.type === 'tool_use') entry.json += delta.partial_json;
|
|
175
|
+
}
|
|
176
|
+
} else if (ev.type === 'message_delta' && ev.delta?.stop_reason) {
|
|
177
|
+
stopReason = ev.delta.stop_reason;
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
try {
|
|
182
|
+
while (true) {
|
|
183
|
+
const { value, done } = await reader.read();
|
|
184
|
+
if (done) break;
|
|
185
|
+
buffer += decoder.decode(value, { stream: true });
|
|
186
|
+
const lines = buffer.split(/\r?\n/);
|
|
187
|
+
buffer = lines.pop() || '';
|
|
188
|
+
for (const line of lines) {
|
|
189
|
+
const trimmed = line.trim();
|
|
190
|
+
if (trimmed.startsWith('data:')) processEvent(trimmed.slice(5).trim());
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
buffer += decoder.decode();
|
|
194
|
+
for (const line of buffer.split(/\r?\n/)) {
|
|
195
|
+
const trimmed = line.trim();
|
|
196
|
+
if (trimmed.startsWith('data:')) processEvent(trimmed.slice(5).trim());
|
|
197
|
+
}
|
|
198
|
+
} finally {
|
|
199
|
+
reader.releaseLock();
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
const toolCalls = [...blocks.entries()]
|
|
203
|
+
.sort((a, b) => a[0] - b[0])
|
|
204
|
+
.filter(([, b]) => b.type === 'tool_use')
|
|
205
|
+
.map(([, b]) => ({
|
|
206
|
+
id: b.id || ('toolu_' + Math.random().toString(36).slice(2, 10)),
|
|
207
|
+
type: 'function',
|
|
208
|
+
function: { name: b.name, arguments: b.json || '{}' },
|
|
209
|
+
}));
|
|
210
|
+
|
|
211
|
+
return {
|
|
212
|
+
message: {
|
|
213
|
+
role: 'assistant',
|
|
214
|
+
content: content || null,
|
|
215
|
+
...(toolCalls.length ? { tool_calls: toolCalls } : {}),
|
|
216
|
+
},
|
|
217
|
+
thinking,
|
|
218
|
+
stopReason,
|
|
219
|
+
};
|
|
220
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 统一模型协议路由器(OpenAI 兼容 + Anthropic 原生)。
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { streamOpenAI } from './openai.js';
|
|
6
|
+
import { streamAnthropic } from './anthropic.js';
|
|
7
|
+
|
|
8
|
+
export function resolveProvider(config = {}) {
|
|
9
|
+
const explicit = String(config.provider || process.env.CLADO_LLM_PROVIDER || 'auto').toLowerCase();
|
|
10
|
+
if (explicit === 'anthropic' || explicit === 'openai') return explicit;
|
|
11
|
+
const baseUrl = String(config.baseUrl || process.env.CLADO_LLM_BASE_URL || '');
|
|
12
|
+
if (/anthropic\.com/i.test(baseUrl)) return 'anthropic';
|
|
13
|
+
if (!baseUrl && process.env.ANTHROPIC_API_KEY && !process.env.OPENAI_API_KEY && !process.env.CLADO_LLM_API_KEY) {
|
|
14
|
+
return 'anthropic';
|
|
15
|
+
}
|
|
16
|
+
const model = String(config.model || process.env.CLADO_LLM_MODEL || '');
|
|
17
|
+
if (!baseUrl && /^claude-/i.test(model)) return 'anthropic';
|
|
18
|
+
return 'openai';
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function resolveProviderCredentials(config = {}) {
|
|
22
|
+
const provider = resolveProvider(config);
|
|
23
|
+
const apiKey = config.apiKey
|
|
24
|
+
|| process.env.CLADO_LLM_API_KEY
|
|
25
|
+
|| (provider === 'anthropic' ? process.env.ANTHROPIC_API_KEY : process.env.OPENAI_API_KEY)
|
|
26
|
+
|| '';
|
|
27
|
+
const baseUrl = config.baseUrl
|
|
28
|
+
|| process.env.CLADO_LLM_BASE_URL
|
|
29
|
+
|| (provider === 'anthropic' ? 'https://api.anthropic.com/v1' : 'https://api.openai.com/v1');
|
|
30
|
+
const model = config.model
|
|
31
|
+
|| process.env.CLADO_LLM_MODEL
|
|
32
|
+
|| (provider === 'anthropic' ? 'claude-sonnet-4-5' : 'gpt-4.1-mini');
|
|
33
|
+
return { provider, apiKey, baseUrl, model };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function streamModelTurn(options) {
|
|
37
|
+
const creds = resolveProviderCredentials(options.config);
|
|
38
|
+
if (!creds.apiKey) {
|
|
39
|
+
throw new Error('未配置内置 Agent 的 API Key。请在「灵感」设置中填写 apiKey / provider / baseUrl / model,或改用外部 ACP 执行器。');
|
|
40
|
+
}
|
|
41
|
+
const fn = creds.provider === 'anthropic' ? streamAnthropic : streamOpenAI;
|
|
42
|
+
return fn({
|
|
43
|
+
baseUrl: creds.baseUrl,
|
|
44
|
+
apiKey: creds.apiKey,
|
|
45
|
+
model: creds.model,
|
|
46
|
+
messages: options.messages,
|
|
47
|
+
tools: options.tools,
|
|
48
|
+
signal: options.signal,
|
|
49
|
+
onEvent: options.onEvent,
|
|
50
|
+
fetchImpl: options.fetchImpl,
|
|
51
|
+
});
|
|
52
|
+
}
|