cladogram 0.5.5-beta.9 → 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 +7 -0
- package/package.json +3 -3
- package/plugins/agent/index.js +928 -3131
- package/plugins/agent/style.css +404 -1511
- package/plugins/brand/index.js +84 -466
- package/plugins/brand/style.css +39 -172
- package/plugins/directory/index.js +10 -10
- 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 +329 -1590
- package/src/server/assets/library.css +396 -11
- package/src/server/assets/library.html +37 -4
- package/src/server/assets/library.js +428 -203
- package/src/server/plugin-registry.js +7 -7
- package/src/server/plugins.js +1 -1
- package/src/server/workspace-hub.js +50 -0
- package/src/server/workspace.js +4 -15
- package/src/agent/commands.js +0 -204
- package/src/agent/context.js +0 -445
- package/src/agent/executors.js +0 -213
- package/src/agent/mcp-client.js +0 -308
- 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 -995
- package/src/agent/sessions.js +0 -336
- package/src/agent/skills.js +0 -190
|
@@ -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
|
-
}
|
|
@@ -1,146 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* OpenAI 兼容协议流式适配器(支持 OpenAI / DeepSeek / 通义 / Kimi / OpenRouter / Ollama)。
|
|
3
|
-
*
|
|
4
|
-
* 解析 SSE `data: {...}` 增量帧,输出 Clado 统一事件:
|
|
5
|
-
* - thinking_delta(兼容 reasoning_content / reasoning)
|
|
6
|
-
* - text_delta
|
|
7
|
-
* - tool_call_start
|
|
8
|
-
* 返回完整的 assistant message(供多轮上下文拼接)与 stopReason。
|
|
9
|
-
*/
|
|
10
|
-
|
|
11
|
-
function finalizeToolCalls(byIndex) {
|
|
12
|
-
return [...byIndex.entries()]
|
|
13
|
-
.sort((a, b) => a[0] - b[0])
|
|
14
|
-
.map(([, call]) => ({
|
|
15
|
-
id: call.id || ('call_' + Math.random().toString(36).slice(2, 10)),
|
|
16
|
-
type: 'function',
|
|
17
|
-
function: { name: call.name || 'unknown', arguments: call.arguments || '{}' },
|
|
18
|
-
}));
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export async function streamOpenAI({
|
|
22
|
-
baseUrl,
|
|
23
|
-
apiKey,
|
|
24
|
-
model,
|
|
25
|
-
messages,
|
|
26
|
-
tools,
|
|
27
|
-
signal,
|
|
28
|
-
onEvent = () => {},
|
|
29
|
-
fetchImpl = fetch,
|
|
30
|
-
}) {
|
|
31
|
-
const url = String(baseUrl || 'https://api.openai.com/v1').replace(/\/+$/, '') + '/chat/completions';
|
|
32
|
-
const response = await fetchImpl(url, {
|
|
33
|
-
method: 'POST',
|
|
34
|
-
headers: {
|
|
35
|
-
'content-type': 'application/json',
|
|
36
|
-
authorization: `Bearer ${apiKey}`,
|
|
37
|
-
},
|
|
38
|
-
body: JSON.stringify({
|
|
39
|
-
model,
|
|
40
|
-
messages,
|
|
41
|
-
...(tools?.length ? { tools, tool_choice: 'auto' } : {}),
|
|
42
|
-
stream: true,
|
|
43
|
-
}),
|
|
44
|
-
signal,
|
|
45
|
-
});
|
|
46
|
-
|
|
47
|
-
if (!response.ok) {
|
|
48
|
-
const body = await response.text().catch(() => '');
|
|
49
|
-
throw new Error(`OpenAI 兼容接口失败(HTTP ${response.status})${body ? ':' + body.slice(0, 240) : ''}`);
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
const contentType = response.headers?.get?.('content-type') || '';
|
|
53
|
-
if (!contentType.includes('text/event-stream') || !response.body) {
|
|
54
|
-
// 兼容不返回 SSE 的代理或测试 mock
|
|
55
|
-
const data = await response.json();
|
|
56
|
-
const choice = data?.choices?.[0];
|
|
57
|
-
const msg = choice?.message;
|
|
58
|
-
if (!msg) throw new Error('LLM 未返回有效消息。');
|
|
59
|
-
const thinking = msg.reasoning_content || msg.reasoning || '';
|
|
60
|
-
if (thinking) onEvent({ type: 'thinking_delta', text: thinking });
|
|
61
|
-
if (msg.content) onEvent({ type: 'text_delta', text: msg.content });
|
|
62
|
-
for (const tc of msg.tool_calls || []) {
|
|
63
|
-
onEvent({ type: 'tool_call_start', id: tc.id, name: tc.function?.name });
|
|
64
|
-
}
|
|
65
|
-
return {
|
|
66
|
-
message: {
|
|
67
|
-
role: 'assistant',
|
|
68
|
-
content: msg.content ?? null,
|
|
69
|
-
...(msg.tool_calls?.length ? { tool_calls: msg.tool_calls } : {}),
|
|
70
|
-
},
|
|
71
|
-
thinking,
|
|
72
|
-
stopReason: choice?.finish_reason || 'stop',
|
|
73
|
-
};
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
const reader = response.body.getReader();
|
|
77
|
-
const decoder = new TextDecoder();
|
|
78
|
-
let buffer = '';
|
|
79
|
-
let content = '';
|
|
80
|
-
let thinking = '';
|
|
81
|
-
let finishReason = 'stop';
|
|
82
|
-
const toolCalls = new Map();
|
|
83
|
-
const announced = new Set();
|
|
84
|
-
|
|
85
|
-
function processLine(line) {
|
|
86
|
-
const trimmed = line.trim();
|
|
87
|
-
if (!trimmed || !trimmed.startsWith('data:')) return;
|
|
88
|
-
const raw = trimmed.slice(5).trim();
|
|
89
|
-
if (!raw || raw === '[DONE]') return;
|
|
90
|
-
let chunk;
|
|
91
|
-
try { chunk = JSON.parse(raw); } catch { return; }
|
|
92
|
-
const choice = chunk?.choices?.[0];
|
|
93
|
-
if (!choice) return;
|
|
94
|
-
if (choice.finish_reason) finishReason = choice.finish_reason;
|
|
95
|
-
const delta = choice.delta || {};
|
|
96
|
-
const thought = delta.reasoning_content || delta.reasoning || '';
|
|
97
|
-
if (thought) {
|
|
98
|
-
thinking += thought;
|
|
99
|
-
onEvent({ type: 'thinking_delta', text: thought });
|
|
100
|
-
}
|
|
101
|
-
if (delta.content) {
|
|
102
|
-
content += delta.content;
|
|
103
|
-
onEvent({ type: 'text_delta', text: delta.content });
|
|
104
|
-
}
|
|
105
|
-
if (Array.isArray(delta.tool_calls)) {
|
|
106
|
-
for (const part of delta.tool_calls) {
|
|
107
|
-
const idx = typeof part.index === 'number' ? part.index : 0;
|
|
108
|
-
const entry = toolCalls.get(idx) || { id: '', name: '', arguments: '' };
|
|
109
|
-
if (part.id) entry.id = part.id;
|
|
110
|
-
if (part.function?.name) entry.name += part.function.name;
|
|
111
|
-
if (part.function?.arguments) entry.arguments += part.function.arguments;
|
|
112
|
-
toolCalls.set(idx, entry);
|
|
113
|
-
if (entry.name && !announced.has(idx)) {
|
|
114
|
-
announced.add(idx);
|
|
115
|
-
onEvent({ type: 'tool_call_start', id: entry.id || `call_${idx}`, name: entry.name });
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
try {
|
|
122
|
-
while (true) {
|
|
123
|
-
const { value, done } = await reader.read();
|
|
124
|
-
if (done) break;
|
|
125
|
-
buffer += decoder.decode(value, { stream: true });
|
|
126
|
-
const lines = buffer.split(/\r?\n/);
|
|
127
|
-
buffer = lines.pop() || '';
|
|
128
|
-
for (const line of lines) processLine(line);
|
|
129
|
-
}
|
|
130
|
-
buffer += decoder.decode();
|
|
131
|
-
if (buffer.trim()) processLine(buffer);
|
|
132
|
-
} finally {
|
|
133
|
-
reader.releaseLock();
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
const finalCalls = finalizeToolCalls(toolCalls);
|
|
137
|
-
return {
|
|
138
|
-
message: {
|
|
139
|
-
role: 'assistant',
|
|
140
|
-
content: content || null,
|
|
141
|
-
...(finalCalls.length ? { tool_calls: finalCalls } : {}),
|
|
142
|
-
},
|
|
143
|
-
thinking,
|
|
144
|
-
stopReason: finishReason,
|
|
145
|
-
};
|
|
146
|
-
}
|