cladogram 0.5.5-beta.1 → 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.
@@ -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
+ }
@@ -0,0 +1,146 @@
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
+ }