cladogram 0.5.5-beta.8 → 0.6.0-beta.1
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 +102 -79
- package/bin/clado.js +1 -1
- package/docs/release.md +14 -0
- package/package.json +3 -3
- package/plugins/agent/index.js +906 -2535
- package/plugins/agent/style.css +381 -1388
- package/plugins/brand/index.js +84 -466
- package/plugins/brand/style.css +39 -172
- package/plugins/directory/index.js +33 -11
- package/plugins/directory/style.css +47 -0
- package/plugins/view-controls/index.js +17 -1
- package/plugins/view-controls/style.css +47 -29
- package/src/agent/clado-tools.js +299 -0
- package/src/agent/pi-bridge.js +487 -0
- package/src/agent/pi-config.js +630 -0
- package/src/html/plugin-ui.css +159 -134
- package/src/html/plugin-ui.js +3 -2
- package/src/server/agent.js +339 -1431
- package/src/server/assets/library.css +396 -11
- package/src/server/assets/library.html +37 -4
- package/src/server/assets/library.js +474 -203
- package/src/server/plugin-registry.js +7 -7
- package/src/server/plugins.js +62 -10
- package/src/server/workspace-hub.js +78 -1
- package/src/server/workspace.js +29 -12
- package/src/agent/context.js +0 -430
- package/src/agent/executors.js +0 -213
- package/src/agent/probe.js +0 -234
- package/src/agent/providers/anthropic.js +0 -220
- package/src/agent/providers/index.js +0 -235
- package/src/agent/providers/openai.js +0 -146
- package/src/agent/runtime.js +0 -947
- package/src/agent/sessions.js +0 -336
package/src/agent/probe.js
DELETED
|
@@ -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
|
-
|
|
@@ -1,220 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,235 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 统一模型协议路由器与多供应商注册中心(OpenAI 兼容 + Anthropic 原生 + 本地免密)。
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
import { streamOpenAI } from './openai.js';
|
|
6
|
-
import { streamAnthropic } from './anthropic.js';
|
|
7
|
-
|
|
8
|
-
export const PROVIDER_PRESETS = [
|
|
9
|
-
{
|
|
10
|
-
id: 'openai',
|
|
11
|
-
label: 'OpenAI',
|
|
12
|
-
protocol: 'openai',
|
|
13
|
-
defaultBaseUrl: 'https://api.openai.com/v1',
|
|
14
|
-
defaultModel: 'gpt-4.1',
|
|
15
|
-
models: ['gpt-4.1', 'gpt-4.1-mini', 'gpt-4o', 'o4-mini'],
|
|
16
|
-
requiresKey: true,
|
|
17
|
-
},
|
|
18
|
-
{
|
|
19
|
-
id: 'anthropic',
|
|
20
|
-
label: 'Anthropic',
|
|
21
|
-
protocol: 'anthropic',
|
|
22
|
-
defaultBaseUrl: 'https://api.anthropic.com/v1',
|
|
23
|
-
defaultModel: 'claude-sonnet-4-5',
|
|
24
|
-
models: ['claude-sonnet-4-5', 'claude-opus-4-5', 'claude-3-7-sonnet-latest'],
|
|
25
|
-
requiresKey: true,
|
|
26
|
-
},
|
|
27
|
-
{
|
|
28
|
-
id: 'deepseek',
|
|
29
|
-
label: 'DeepSeek',
|
|
30
|
-
protocol: 'openai',
|
|
31
|
-
defaultBaseUrl: 'https://api.deepseek.com/v1',
|
|
32
|
-
defaultModel: 'deepseek-chat',
|
|
33
|
-
models: ['deepseek-chat', 'deepseek-reasoner'],
|
|
34
|
-
requiresKey: true,
|
|
35
|
-
},
|
|
36
|
-
{
|
|
37
|
-
id: 'openrouter',
|
|
38
|
-
label: 'OpenRouter',
|
|
39
|
-
protocol: 'openai',
|
|
40
|
-
defaultBaseUrl: 'https://openrouter.ai/api/v1',
|
|
41
|
-
defaultModel: 'anthropic/claude-sonnet-4',
|
|
42
|
-
models: ['anthropic/claude-sonnet-4', 'openai/gpt-4.1', 'google/gemini-2.5-pro', 'deepseek/deepseek-r1'],
|
|
43
|
-
requiresKey: true,
|
|
44
|
-
},
|
|
45
|
-
{
|
|
46
|
-
id: 'siliconflow',
|
|
47
|
-
label: '硅基流动 SiliconFlow',
|
|
48
|
-
protocol: 'openai',
|
|
49
|
-
defaultBaseUrl: 'https://api.siliconflow.cn/v1',
|
|
50
|
-
defaultModel: 'deepseek-ai/DeepSeek-V3',
|
|
51
|
-
models: ['deepseek-ai/DeepSeek-V3', 'deepseek-ai/DeepSeek-R1', 'Qwen/Qwen2.5-Coder-32B-Instruct'],
|
|
52
|
-
requiresKey: true,
|
|
53
|
-
},
|
|
54
|
-
{
|
|
55
|
-
id: 'ollama',
|
|
56
|
-
label: 'Ollama 本地',
|
|
57
|
-
protocol: 'openai',
|
|
58
|
-
defaultBaseUrl: 'http://127.0.0.1:11434/v1',
|
|
59
|
-
defaultModel: 'qwen2.5-coder:14b',
|
|
60
|
-
models: ['qwen2.5-coder:14b', 'llama3.3', 'deepseek-r1:14b'],
|
|
61
|
-
requiresKey: false,
|
|
62
|
-
},
|
|
63
|
-
{
|
|
64
|
-
id: 'custom',
|
|
65
|
-
label: '自定义兼容接口',
|
|
66
|
-
protocol: 'openai',
|
|
67
|
-
defaultBaseUrl: 'https://api.openai.com/v1',
|
|
68
|
-
defaultModel: 'gpt-4.1-mini',
|
|
69
|
-
models: [],
|
|
70
|
-
requiresKey: true,
|
|
71
|
-
},
|
|
72
|
-
];
|
|
73
|
-
|
|
74
|
-
export function getProviderPreset(id) {
|
|
75
|
-
return PROVIDER_PRESETS.find(p => p.id === id) || null;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
export function maskApiKey(key = '') {
|
|
79
|
-
const clean = String(key || '').trim();
|
|
80
|
-
if (!clean) return '';
|
|
81
|
-
if (clean.length <= 8) return '••••' + clean.slice(-2);
|
|
82
|
-
return clean.slice(0, 3) + '••••' + clean.slice(-4);
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
export function resolveProvider(config = {}) {
|
|
86
|
-
const activeId = String(config.providerId || '').toLowerCase();
|
|
87
|
-
const profile = (activeId && config.providers?.[activeId]) || {};
|
|
88
|
-
const explicit = String(profile.protocol || config.provider || process.env.CLADO_LLM_PROVIDER || 'auto').toLowerCase();
|
|
89
|
-
if (explicit === 'anthropic' || explicit === 'openai') return explicit;
|
|
90
|
-
const preset = getProviderPreset(activeId);
|
|
91
|
-
if (preset?.protocol === 'anthropic') return 'anthropic';
|
|
92
|
-
const baseUrl = String(profile.baseUrl || config.baseUrl || config.apiBaseUrl || process.env.CLADO_LLM_BASE_URL || '');
|
|
93
|
-
if (/anthropic\.com/i.test(baseUrl)) return 'anthropic';
|
|
94
|
-
if (!baseUrl && process.env.ANTHROPIC_API_KEY && !process.env.OPENAI_API_KEY && !process.env.CLADO_LLM_API_KEY) {
|
|
95
|
-
return 'anthropic';
|
|
96
|
-
}
|
|
97
|
-
const model = String(profile.model || config.model || process.env.CLADO_LLM_MODEL || '');
|
|
98
|
-
if (!baseUrl && /^claude-/i.test(model)) return 'anthropic';
|
|
99
|
-
return 'openai';
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
export function resolveProviderCredentials(config = {}) {
|
|
103
|
-
const activeId = String(config.providerId || '').toLowerCase();
|
|
104
|
-
const preset = getProviderPreset(activeId);
|
|
105
|
-
const profile = (activeId && config.providers?.[activeId]) || {};
|
|
106
|
-
const provider = resolveProvider(config);
|
|
107
|
-
|
|
108
|
-
const rawKey = profile.apiKey
|
|
109
|
-
?? config.apiKey
|
|
110
|
-
?? process.env.CLADO_LLM_API_KEY
|
|
111
|
-
?? (provider === 'anthropic' ? process.env.ANTHROPIC_API_KEY : process.env.OPENAI_API_KEY)
|
|
112
|
-
?? '';
|
|
113
|
-
const hasApiKey = Boolean(String(rawKey || '').trim());
|
|
114
|
-
|
|
115
|
-
const baseUrl = String(
|
|
116
|
-
profile.baseUrl
|
|
117
|
-
|| config.baseUrl
|
|
118
|
-
|| config.apiBaseUrl
|
|
119
|
-
|| preset?.defaultBaseUrl
|
|
120
|
-
|| process.env.CLADO_LLM_BASE_URL
|
|
121
|
-
|| (provider === 'anthropic' ? 'https://api.anthropic.com/v1' : 'https://api.openai.com/v1')
|
|
122
|
-
).trim();
|
|
123
|
-
|
|
124
|
-
const isKeylessLocal = preset?.requiresKey === false || /^https?:\/\/(127\.0\.0\.1|localhost):11434(\/|$)/i.test(baseUrl);
|
|
125
|
-
const apiKey = hasApiKey ? String(rawKey).trim() : (isKeylessLocal ? 'ollama' : '');
|
|
126
|
-
const configured = hasApiKey || Boolean(activeId === 'ollama' && profile.enabled !== false && config.providers?.ollama);
|
|
127
|
-
|
|
128
|
-
const model = String(
|
|
129
|
-
profile.model
|
|
130
|
-
|| config.model
|
|
131
|
-
|| preset?.defaultModel
|
|
132
|
-
|| process.env.CLADO_LLM_MODEL
|
|
133
|
-
|| (provider === 'anthropic' ? 'claude-sonnet-4-5' : 'gpt-4.1-mini')
|
|
134
|
-
).trim();
|
|
135
|
-
|
|
136
|
-
const resolvedId = preset?.id || (provider === 'anthropic' ? 'anthropic' : 'openai');
|
|
137
|
-
const providerLabel = profile.label || preset?.label || (provider === 'anthropic' ? 'Anthropic' : 'OpenAI');
|
|
138
|
-
|
|
139
|
-
return {
|
|
140
|
-
providerId: resolvedId,
|
|
141
|
-
providerLabel,
|
|
142
|
-
provider,
|
|
143
|
-
apiKey,
|
|
144
|
-
hasApiKey,
|
|
145
|
-
configured,
|
|
146
|
-
baseUrl,
|
|
147
|
-
model,
|
|
148
|
-
};
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
export function listConfiguredModels(config = {}) {
|
|
152
|
-
const out = [];
|
|
153
|
-
const providersMap = config.providers && typeof config.providers === 'object' ? config.providers : {};
|
|
154
|
-
const seen = new Set();
|
|
155
|
-
|
|
156
|
-
for (const preset of PROVIDER_PRESETS) {
|
|
157
|
-
const prof = providersMap[preset.id];
|
|
158
|
-
if (!prof) continue;
|
|
159
|
-
const hasKey = Boolean(String(prof.apiKey || '').trim()) || preset.requiresKey === false;
|
|
160
|
-
if (!hasKey) continue;
|
|
161
|
-
const models = Array.isArray(prof.models) && prof.models.length
|
|
162
|
-
? prof.models
|
|
163
|
-
: [prof.model || preset.defaultModel, ...(preset.models || [])].filter(Boolean);
|
|
164
|
-
const uniqueModels = [...new Set(models)].slice(0, 12);
|
|
165
|
-
for (const m of uniqueModels) {
|
|
166
|
-
const k = `${preset.id}::${m}`;
|
|
167
|
-
if (seen.has(k)) continue;
|
|
168
|
-
seen.add(k);
|
|
169
|
-
out.push({
|
|
170
|
-
providerId: preset.id,
|
|
171
|
-
providerLabel: prof.label || preset.label,
|
|
172
|
-
model: m,
|
|
173
|
-
});
|
|
174
|
-
}
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
// 兼容旧版单组顶层配置
|
|
178
|
-
if (!out.length) {
|
|
179
|
-
const creds = resolveProviderCredentials(config);
|
|
180
|
-
if (creds.configured) {
|
|
181
|
-
out.push({
|
|
182
|
-
providerId: creds.providerId,
|
|
183
|
-
providerLabel: creds.providerLabel,
|
|
184
|
-
model: creds.model,
|
|
185
|
-
});
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
return out;
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
export async function fetchProviderModels({ protocol = 'openai', baseUrl = '', apiKey = '', fetchImpl = fetch } = {}) {
|
|
192
|
-
const cleanBase = String(baseUrl || '').replace(/\/+$/, '');
|
|
193
|
-
if (!cleanBase) throw new Error('请先填写 API Base URL。');
|
|
194
|
-
const headers = { accept: 'application/json' };
|
|
195
|
-
if (protocol === 'anthropic') {
|
|
196
|
-
if (apiKey) headers['x-api-key'] = apiKey;
|
|
197
|
-
headers['anthropic-version'] = '2023-06-01';
|
|
198
|
-
} else if (apiKey) {
|
|
199
|
-
headers.authorization = `Bearer ${apiKey}`;
|
|
200
|
-
}
|
|
201
|
-
const res = await fetchImpl(`${cleanBase}/models`, {
|
|
202
|
-
method: 'GET',
|
|
203
|
-
headers,
|
|
204
|
-
signal: AbortSignal.timeout(6500),
|
|
205
|
-
});
|
|
206
|
-
if (!res.ok) {
|
|
207
|
-
const txt = await res.text().catch(() => '');
|
|
208
|
-
throw new Error(`拉取模型列表失败(HTTP ${res.status})${txt ? ':' + txt.slice(0, 140) : ''}`);
|
|
209
|
-
}
|
|
210
|
-
const body = await res.json();
|
|
211
|
-
const rawList = Array.isArray(body?.data) ? body.data : (Array.isArray(body?.models) ? body.models : []);
|
|
212
|
-
const ids = rawList
|
|
213
|
-
.map(item => (typeof item === 'string' ? item : (item?.id || item?.name || '')))
|
|
214
|
-
.map(s => String(s).trim())
|
|
215
|
-
.filter(Boolean);
|
|
216
|
-
return [...new Set(ids)].slice(0, 60);
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
export async function streamModelTurn(options) {
|
|
220
|
-
const creds = resolveProviderCredentials(options.config);
|
|
221
|
-
if (!creds.apiKey) {
|
|
222
|
-
throw new Error('尚未配置供应商与模型 API Key。请点击输入框左侧模型按钮或「Agent 设置 → 供应商与模型」完成配置。');
|
|
223
|
-
}
|
|
224
|
-
const fn = creds.provider === 'anthropic' ? streamAnthropic : streamOpenAI;
|
|
225
|
-
return fn({
|
|
226
|
-
baseUrl: creds.baseUrl,
|
|
227
|
-
apiKey: creds.apiKey,
|
|
228
|
-
model: creds.model,
|
|
229
|
-
messages: options.messages,
|
|
230
|
-
tools: options.tools,
|
|
231
|
-
signal: options.signal,
|
|
232
|
-
onEvent: options.onEvent,
|
|
233
|
-
fetchImpl: options.fetchImpl,
|
|
234
|
-
});
|
|
235
|
-
}
|