interplane.Get Omega
Read in your language

omega-harness

Agent skills for operating, encoding and communicating in Omega (.om) and the AIEN repositories

Brought by drakestapleton

branch main Branches Tags History

omega-harness / cli / src / inkling.ts

751 lines · 24132 bytes Raw Blame History
1import net from 'node:net';
2import type { FunctionDeclaration } from '@google/genai';
3
4interface SimpleHttpResponse {
5 status: number;
6 headers: Record<string, string>;
7 body: string;
8}
9
10/**
11 * Raw HTTP/1.1 request over TCP that accepts both CRLF (\r\n) and bare LF (\n)
12 * header endings (needed for pure-Omega `inkling2-serve` which emits LF headers,
13 * whereas Node's undici fetch() strictly rejects non-CRLF headers).
14 */
15function rawHttpRequest(
16 urlStr: string,
17 opts: {
18 method: 'GET' | 'POST';
19 headers?: Record<string, string>;
20 body?: string;
21 timeoutMs?: number;
22 signal?: AbortSignal;
23 }
24): Promise<SimpleHttpResponse> {
25 return new Promise((resolve, reject) => {
26 const u = new URL(urlStr);
27 if (u.protocol !== 'http:') {
28 reject(new Error(`rawHttpRequest only supports http://, got ${u.protocol}`));
29 return;
30 }
31 const port = u.port ? Number(u.port) : 80;
32 const host = u.hostname;
33 const pathAndQuery = (u.pathname || '/') + (u.search || '');
34 const bodyBuf = opts.body ? Buffer.from(opts.body, 'utf8') : Buffer.alloc(0);
35
36 const reqHeaders: Record<string, string> = {
37 Host: u.host,
38 Connection: 'close',
39 ...(opts.headers || {}),
40 };
41 if (opts.method === 'POST') {
42 reqHeaders['Content-Length'] = String(bodyBuf.length);
43 }
44
45 const headLines = [
46 `${opts.method} ${pathAndQuery} HTTP/1.1`,
47 ...Object.entries(reqHeaders).map(([k, v]) => `${k}: ${v}`),
48 '',
49 '',
50 ].join('\r\n');
51
52 const socket = net.createConnection({ host, port });
53 const chunks: Buffer[] = [];
54 let settled = false;
55
56 const finishErr = (err: Error) => {
57 if (settled) return;
58 settled = true;
59 socket.destroy();
60 reject(err);
61 };
62
63 if (opts.timeoutMs) {
64 socket.setTimeout(opts.timeoutMs, () => {
65 finishErr(new Error(`HTTP timeout after ${opts.timeoutMs}ms`));
66 });
67 }
68
69 if (opts.signal) {
70 if (opts.signal.aborted) {
71 finishErr(new Error('Cancelled by user'));
72 return;
73 }
74 opts.signal.addEventListener(
75 'abort',
76 () => finishErr(new Error('Cancelled by user')),
77 { once: true }
78 );
79 }
80
81 socket.on('connect', () => {
82 socket.write(headLines);
83 if (bodyBuf.length > 0) socket.write(bodyBuf);
84 });
85 socket.on('data', (chunk) => chunks.push(chunk));
86 socket.on('error', (err) => finishErr(err));
87 socket.on('end', () => {
88 if (settled) return;
89 settled = true;
90 const raw = Buffer.concat(chunks).toString('utf8');
91 let sepIdx = raw.indexOf('\r\n\r\n');
92 let sepLen = 4;
93 if (sepIdx < 0) {
94 sepIdx = raw.indexOf('\n\n');
95 sepLen = 2;
96 }
97 if (sepIdx < 0) {
98 reject(new Error(`Malformed HTTP response from ${urlStr}`));
99 return;
100 }
101 const headerPart = raw.slice(0, sepIdx);
102 const bodyPart = raw.slice(sepIdx + sepLen);
103 const lines = headerPart.split(/\r?\n/);
104 const statusMatch = lines[0]?.match(/^HTTP\/\d\.\d\s+(\d+)/);
105 const status = statusMatch ? Number(statusMatch[1]) : 0;
106 const headers: Record<string, string> = {};
107 for (const l of lines.slice(1)) {
108 const colon = l.indexOf(':');
109 if (colon > 0) {
110 headers[l.slice(0, colon).trim().toLowerCase()] = l.slice(colon + 1).trim();
111 }
112 }
113 resolve({ status, headers, body: bodyPart });
114 });
115 });
116}
117
118async function flexibleRequest(
119 urlStr: string,
120 opts: {
121 method: 'GET' | 'POST';
122 headers?: Record<string, string>;
123 body?: string;
124 timeoutMs?: number;
125 signal?: AbortSignal;
126 }
127): Promise<SimpleHttpResponse> {
128 try {
129 const res = await fetch(urlStr, {
130 method: opts.method,
131 headers: opts.headers,
132 body: opts.body,
133 signal: opts.signal || (opts.timeoutMs ? AbortSignal.timeout(opts.timeoutMs) : undefined),
134 });
135 const headers: Record<string, string> = {};
136 res.headers.forEach((v, k) => {
137 headers[k.toLowerCase()] = v;
138 });
139 const body = await res.text();
140 return { status: res.status, headers, body };
141 } catch (err: unknown) {
142 const causeCode = (err as { cause?: { code?: string } })?.cause?.code || '';
143 if (
144 urlStr.startsWith('http://') &&
145 (causeCode.startsWith('HPE_') || String(err).includes('fetch failed'))
146 ) {
147 return rawHttpRequest(urlStr, opts);
148 }
149 throw err;
150 }
151}
152
153export interface InklingHealth {
154 online: boolean;
155 endpoint: string;
156 model?: string;
157 contextWindow?: number;
158 kvPrefixHits?: number;
159 slotsActive?: number;
160 slotsMax?: number;
161 arborisTransitions?: number;
162 arborisTop8Hits?: number;
163 arborisTop16Hits?: number;
164 engine: 'inkling2-serve' | 'openai-compat' | 'offline';
165 error?: string;
166}
167
168export interface InklingMessage {
169 role: 'system' | 'user' | 'assistant' | 'tool';
170 content: string;
171 rawAssistantOutput?: string;
172 name?: string;
173 tool_call_id?: string;
174 tool_calls?: Array<{
175 id: string;
176 type: 'function';
177 function: { name: string; arguments: string };
178 }>;
179}
180
181export interface ParsedInklingOutput {
182 text: string;
183 thinking?: string;
184 toolCalls: Array<{ id: string; name: string; args: Record<string, unknown> }>;
185}
186
187/**
188 * Probe an Inkling HTTP endpoint (GET /health, falling back to GET /v1/models).
189 * Detects Omega's pure seeded-Omega `inkling2-serve` (which reports slots_max / slots_active)
190 * versus a general OpenAI-compatible Inkling server.
191 */
192export async function probeInkling(endpoint: string, apiKey?: string): Promise<InklingHealth> {
193 const base = endpoint.replace(/\/+$/, '');
194 const headers: Record<string, string> = {};
195 if (apiKey) headers['Authorization'] = `Bearer ${apiKey}`;
196
197 try {
198 const res = await flexibleRequest(`${base}/health`, {
199 method: 'GET',
200 headers,
201 timeoutMs: 2500,
202 });
203 if (res.status >= 200 && res.status < 300) {
204 let data: Record<string, unknown> = {};
205 try {
206 data = JSON.parse(res.body) as Record<string, unknown>;
207 } catch {
208 data = {};
209 }
210 const slotsMax =
211 typeof data.slots_max === 'number'
212 ? data.slots_max
213 : typeof data.max_slots === 'number'
214 ? data.max_slots
215 : undefined;
216 const slotsActive =
217 typeof data.slots_active === 'number'
218 ? data.slots_active
219 : typeof data.active_slots === 'number'
220 ? data.active_slots
221 : undefined;
222 const model = typeof data.model === 'string' ? data.model : 'inkling-2-mini';
223 const isNativeServe = slotsMax !== undefined;
224 return {
225 online: true,
226 endpoint: base,
227 model,
228 contextWindow: typeof data.context_window === 'number' ? data.context_window : undefined,
229 kvPrefixHits: typeof data.kv_prefix_hits === 'number' ? data.kv_prefix_hits : undefined,
230 slotsActive,
231 slotsMax,
232 arborisTransitions: typeof data.arboris_transitions === 'number' ? data.arboris_transitions : undefined,
233 arborisTop8Hits: typeof data.arboris_top8_hits === 'number' ? data.arboris_top8_hits : undefined,
234 arborisTop16Hits: typeof data.arboris_top16_hits === 'number' ? data.arboris_top16_hits : undefined,
235 engine: isNativeServe ? 'inkling2-serve' : 'openai-compat',
236 };
237 }
238 } catch {
239 // Fall through to /v1/models check
240 }
241
242 try {
243 const res = await flexibleRequest(`${base}/v1/models`, {
244 method: 'GET',
245 headers,
246 timeoutMs: 2500,
247 });
248 if (res.status >= 200 && res.status < 300) {
249 let data: { data?: Array<{ id?: string; slots_max?: number }> } = {};
250 try {
251 data = JSON.parse(res.body) as { data?: Array<{ id?: string; slots_max?: number }> };
252 } catch {
253 data = {};
254 }
255 const first = data.data?.[0];
256 return {
257 online: true,
258 endpoint: base,
259 model: first?.id || 'inkling-2-mini',
260 slotsMax: first?.slots_max,
261 engine: first?.slots_max !== undefined ? 'inkling2-serve' : 'openai-compat',
262 };
263 }
264 return {
265 online: false,
266 endpoint: base,
267 engine: 'offline',
268 error: `HTTP ${res.status}`,
269 };
270 } catch (err: unknown) {
271 return {
272 online: false,
273 endpoint: base,
274 engine: 'offline',
275 error: err instanceof Error ? err.message : String(err),
276 };
277 }
278}
279
280/**
281 * Parse Inkling-2-Mini tool calls and control tokens:
282 * - <|content_thinking|>...<|end_message|>
283 * - <|message_model|>NAME<|content_invoke_tool_json|>{"name":...,"args":...}<|end_message|>
284 * - <tool>{"name":"...","args":{...}}</tool>
285 * - Standalone JSON tool call block: {"tool":"...","args":{...}} or {"name":"...","args":{...}}
286 */
287export function parseInklingTokens(raw: string): ParsedInklingOutput {
288 const toolCalls: Array<{ id: string; name: string; args: Record<string, unknown> }> = [];
289 let thinking = '';
290 let text = raw;
291
292 const pushCall = (jsonStr: string): boolean => {
293 const candidates = [jsonStr.trim(), jsonStr.trim().replace(/'/g, '"')];
294 for (const cand of candidates) {
295 try {
296 const parsed = JSON.parse(cand) as {
297 name?: string;
298 tool?: string;
299 args?: Record<string, unknown>;
300 arguments?: Record<string, unknown>;
301 };
302 const fnName = parsed.name || parsed.tool;
303 if (fnName && typeof fnName === 'string') {
304 toolCalls.push({
305 id: `ik-tc-${Date.now()}-${toolCalls.length}`,
306 name: fnName,
307 args: parsed.args || parsed.arguments || {},
308 });
309 return true;
310 }
311 } catch {
312 // try next candidate
313 }
314 }
315 return false;
316 };
317
318 // Extract thinking blocks
319 text = text.replace(/<\|content_thinking\|>([\s\S]*?)(?:<\|end_message\|>|$)/g, (_, inner: string) => {
320 thinking += (thinking ? '\n' : '') + inner.trim();
321 return '';
322 });
323
324 // Extract native Inkling tool invocations
325 text = text.replace(
326 /(?:<\|message_model\|>[^<]*)?<\|content_invoke_tool_json\|>([\s\S]*?)(?:<\|end_message\|>|$)/g,
327 (full, jsonStr: string) => (pushCall(jsonStr) ? '' : full)
328 );
329
330 // Extract <tool>{...}</tool> tags
331 text = text.replace(/<tool>\s*([\s\S]*?)\s*<\/tool>/gi, (full, jsonStr: string) =>
332 pushCall(jsonStr) ? '' : full
333 );
334
335 // Extract fenced ```json {"tool":...}``` or inline {"tool":"...", "args":{...}} when no other call matched
336 if (toolCalls.length === 0) {
337 text = text.replace(/```(?:json)?\s*(\{[\s\S]*?"(?:tool|name)"[\s\S]*?\})\s*```/g, (full, jsonStr: string) =>
338 pushCall(jsonStr) ? '' : full
339 );
340 }
341 if (toolCalls.length === 0) {
342 const inlineMatch = text.match(/(\{"(?:tool|name)"\s*:\s*"[a-z0-9_]+"(?:\s*,\s*"(?:args|arguments)"\s*:\s*\{[^{}]*\})?\s*\})/);
343 if (inlineMatch && pushCall(inlineMatch[1])) {
344 text = text.replace(inlineMatch[1], '');
345 }
346 }
347
348 // Strip remaining Inkling framing tokens
349 text = text
350 .replace(/<\|content_text\|>/g, '')
351 .replace(/<\|end_message\|>/g, '')
352 .replace(/<\|content_model_end_sampling\|>/g, '')
353 .replace(/<\|message_model\|>/g, '')
354 .trim();
355
356 return {
357 text,
358 thinking: thinking || undefined,
359 toolCalls,
360 };
361}
362
363function toOpenAITools(decls: FunctionDeclaration[]) {
364 return decls.map((d) => ({
365 type: 'function' as const,
366 function: {
367 name: d.name,
368 description: d.description || '',
369 parameters: d.parameters || { type: 'object', properties: {} },
370 },
371 }));
372}
373
374const SHORT_TOOL_DESC: Record<string, string> = {
375 read_file: 'Read file lines',
376 write_file: 'Write file',
377 edit_file: 'Edit text in file',
378 delete_file: 'Delete file',
379 list_dir: 'List directory',
380 glob_files: 'Find files by glob',
381 grep_search: 'Search text in files',
382 run_shell: 'Run shell command',
383 git_status: 'Git status',
384 git_diff: 'Git diff',
385 git_log: 'Git log',
386 git_commit: 'Git commit',
387 web_fetch: 'Fetch URL text',
388 web_search: 'Search the web',
389 todo_write: 'Update task list',
390 todo_read: 'Read task list',
391 memory_save: 'Save memory',
392 memory_read: 'Read memory',
393 spawn_subagent: 'Run subagent on subtask',
394 spawn_parallel_subagents: 'Run parallel subagents',
395 list_subagents: 'List subagents',
396 message_subagent: 'Message subagent',
397 list_skills: 'List Omega skills',
398 load_skill: 'Load Omega skill',
399 omc_compile: 'Compile .om with omc',
400 omc_run: 'Compile and run .om',
401 omega_pin: 'Show PIN and omc hash',
402};
403
404function normalizeSchema(obj: unknown): unknown {
405 if (Array.isArray(obj)) return obj.map(normalizeSchema);
406 if (!obj || typeof obj !== 'object') return obj;
407 const rec = obj as Record<string, unknown>;
408 const out: Record<string, unknown> = {};
409 for (const k of Object.keys(rec).sort()) {
410 if (k === 'description') continue;
411 if (k === 'type' && typeof rec[k] === 'string') {
412 out[k] = rec[k].toLowerCase();
413 } else {
414 out[k] = normalizeSchema(rec[k]);
415 }
416 }
417 return out;
418}
419
420/**
421 * Render the EXACT Inkling-2-Mini native chat_template.jinja wire format
422 * for `inkling2-serve` (32,768-tok KV + exact KV/sconv prefix caching + native tool calling).
423 */
424export function renderInklingChatTemplate(
425 messages: InklingMessage[],
426 tools: FunctionDeclaration[],
427 thinkingEffort = 0
428): string {
429 const parts: string[] = [];
430
431 if (tools.length > 0) {
432 const specs = tools.map((d) => ({
433 description: SHORT_TOOL_DESC[d.name || ''] || (d.description || '').slice(0, 32),
434 name: d.name || '',
435 parameters: normalizeSchema(d.parameters || { type: 'object', properties: {} }),
436 type: 'function',
437 }));
438 parts.push(`<|message_system|>tool_declare<|content_xml|>${JSON.stringify(specs)}<|end_message|>`);
439 }
440
441 let effortEmitted = false;
442 for (const m of messages) {
443 if (!effortEmitted && m.role !== 'system') {
444 parts.push(`<|message_system|><|content_text|>Thinking effort level: ${thinkingEffort}<|end_message|>`);
445 effortEmitted = true;
446 }
447 if (m.role === 'system') {
448 parts.push(`<|message_system|><|content_text|>${m.content}<|end_message|>`);
449 } else if (m.role === 'user') {
450 parts.push(`<|message_user|><|content_text|>${m.content}<|end_message|>`);
451 } else if (m.role === 'assistant') {
452 if (m.rawAssistantOutput !== undefined) {
453 parts.push(`<|message_model|>${m.rawAssistantOutput}<|content_model_end_sampling|>`);
454 } else {
455 if (m.content) {
456 parts.push(`<|message_model|><|content_text|>${m.content}<|end_message|>`);
457 }
458 if (m.tool_calls && m.tool_calls.length > 0) {
459 for (const tc of m.tool_calls) {
460 let parsedArgs: Record<string, unknown> = {};
461 try {
462 parsedArgs = tc.function.arguments ? JSON.parse(tc.function.arguments) : {};
463 } catch {
464 parsedArgs = {};
465 }
466 const callJson = JSON.stringify({ name: tc.function.name, args: parsedArgs });
467 parts.push(`<|message_model|>${tc.function.name}<|content_invoke_tool_json|>${callJson}<|end_message|>`);
468 }
469 }
470 parts.push('<|content_model_end_sampling|>');
471 }
472 } else if (m.role === 'tool') {
473 const tname = m.name || 'tool';
474 parts.push(`<|message_tool|>${tname}<|content_text|>${m.content}<|end_message|>`);
475 }
476 }
477
478 if (!effortEmitted) {
479 parts.push(`<|message_system|><|content_text|>Thinking effort level: ${thinkingEffort}<|end_message|>`);
480 }
481 parts.push('<|message_model|>');
482 return parts.join('');
483}
484
485/**
486 * Formats a request for Omega's native `inkling2-serve` (32K context, 128 KiB request buffer,
487 * full JSON unescaping, native special-token encoding).
488 */
489export function buildNativeServePayload(
490 model: string,
491 userPrompt: string,
492 messages?: InklingMessage[],
493 tools?: FunctionDeclaration[]
494): string {
495 if (messages && messages.length > 0) {
496 const rendered = renderInklingChatTemplate(messages, tools || [], 0);
497 // Stay cleanly inside 120 KiB budget
498 const bounded = rendered.length > 120_000 ? rendered.slice(rendered.length - 120_000) : rendered;
499 return JSON.stringify({
500 model,
501 messages: [{ role: 'user', content: bounded }],
502 });
503 }
504 const sanitized = userPrompt
505 .replace(/"/g, "'")
506 .replace(/\r?\n+/g, ' ')
507 .trim()
508 .slice(0, 120_000);
509 return JSON.stringify({
510 model,
511 messages: [{ role: 'user', content: sanitized }],
512 });
513}
514
515export async function callInklingChat(opts: {
516 endpoint: string;
517 model: string;
518 messages: InklingMessage[];
519 tools: FunctionDeclaration[];
520 apiKey?: string;
521 engine: 'inkling2-serve' | 'openai-compat';
522 signal?: AbortSignal;
523 onTextDelta: (chunk: string) => void;
524}): Promise<{
525 parsed: ParsedInklingOutput;
526 rawContent: string;
527 usage?: { promptTokens: number; outputTokens: number; totalTokens: number };
528}> {
529 const base = opts.endpoint.replace(/\/+$/, '');
530 const url = `${base}/v1/chat/completions`;
531 const headers: Record<string, string> = {
532 'Content-Type': 'application/json',
533 };
534 if (opts.apiKey) {
535 headers['Authorization'] = `Bearer ${opts.apiKey}`;
536 }
537
538 // Native pure-Omega `inkling2-serve` path (with automatic 503 server_busy retry)
539 if (opts.engine === 'inkling2-serve') {
540 const lastUser = [...opts.messages].reverse().find((m) => m.role === 'user');
541 const body = buildNativeServePayload(opts.model, lastUser?.content || '', opts.messages, opts.tools);
542
543 let lastStatus = 0;
544 for (let attempt = 0; attempt < 5; attempt++) {
545 const res = await flexibleRequest(url, {
546 method: 'POST',
547 headers,
548 body,
549 timeoutMs: 300_000,
550 signal: opts.signal,
551 });
552 lastStatus = res.status;
553
554 if (res.status === 503 && attempt < 4) {
555 const retryAfter = Number(res.headers['retry-after'] || '1');
556 const delayMs = Math.min(5000, Math.max(250, retryAfter * 1000));
557 await new Promise((r) => setTimeout(r, delayMs));
558 continue;
559 }
560
561 if (res.status < 200 || res.status >= 300) {
562 throw new Error(`Inkling server HTTP ${res.status}: ${res.body.slice(0, 200)}`);
563 }
564
565 const data = JSON.parse(res.body) as {
566 choices?: Array<{ message?: { content?: string } }>;
567 usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number };
568 };
569 const rawContent = data.choices?.[0]?.message?.content || '';
570 const parsed = parseInklingTokens(rawContent);
571 if (parsed.text) {
572 opts.onTextDelta(parsed.text);
573 }
574 const usage = data.usage
575 ? {
576 promptTokens: data.usage.prompt_tokens || 0,
577 outputTokens: data.usage.completion_tokens || 0,
578 totalTokens: data.usage.total_tokens || 0,
579 }
580 : undefined;
581 return { parsed, rawContent, usage };
582 }
583 throw new Error(`Inkling server busy (HTTP ${lastStatus}) after 5 retries — all 8 KV slots occupied.`);
584 }
585
586 // Full OpenAI-compatible Inkling server path (SSE streaming + native tool_calls)
587 const payload = {
588 model: opts.model,
589 messages: opts.messages,
590 tools: toOpenAITools(opts.tools),
591 stream: true,
592 };
593
594 const res = await fetch(url, {
595 method: 'POST',
596 headers,
597 body: JSON.stringify(payload),
598 signal: opts.signal,
599 });
600
601 if (!res.ok) {
602 const errText = await res.text().catch(() => '');
603 throw new Error(`Inkling server HTTP ${res.status}: ${errText.slice(0, 240)}`);
604 }
605
606 const contentType = res.headers.get('content-type') || '';
607
608 // Non-streaming JSON fallback if server ignored stream: true
609 if (!contentType.includes('text/event-stream') || !res.body) {
610 const data = (await res.json()) as {
611 choices?: Array<{
612 message?: {
613 content?: string;
614 reasoning_content?: string;
615 tool_calls?: Array<{
616 id?: string;
617 function?: { name?: string; arguments?: string };
618 }>;
619 };
620 }>;
621 usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number };
622 };
623 const msg = data.choices?.[0]?.message;
624 const parsed = parseInklingTokens(msg?.content || '');
625 if (msg?.reasoning_content) {
626 parsed.thinking = msg.reasoning_content;
627 }
628 if (msg?.tool_calls) {
629 for (const tc of msg.tool_calls) {
630 const fn = tc.function;
631 if (!fn?.name) continue;
632 let args: Record<string, unknown> = {};
633 try {
634 args = fn.arguments ? JSON.parse(fn.arguments) : {};
635 } catch {
636 args = {};
637 }
638 parsed.toolCalls.push({
639 id: tc.id || `ik-tc-${Date.now()}-${parsed.toolCalls.length}`,
640 name: fn.name,
641 args,
642 });
643 }
644 }
645 if (parsed.text) opts.onTextDelta(parsed.text);
646 const usage = data.usage
647 ? {
648 promptTokens: data.usage.prompt_tokens || 0,
649 outputTokens: data.usage.completion_tokens || 0,
650 totalTokens: data.usage.total_tokens || 0,
651 }
652 : undefined;
653 return { parsed, rawContent: msg?.content || '', usage };
654 }
655
656 // SSE streaming parser
657 const reader = res.body.getReader();
658 const decoder = new TextDecoder();
659 let buf = '';
660 let rawText = '';
661 let reasoningText = '';
662 const tcAccum = new Map<number, { id: string; name: string; argsJson: string }>();
663 let usage: { promptTokens: number; outputTokens: number; totalTokens: number } | undefined;
664
665 while (true) {
666 const { done, value } = await reader.read();
667 if (done) break;
668 buf += decoder.decode(value, { stream: true });
669
670 let nl: number;
671 while ((nl = buf.indexOf('\n')) >= 0) {
672 const line = buf.slice(0, nl).trim();
673 buf = buf.slice(nl + 1);
674 if (!line.startsWith('data:')) continue;
675 const payloadStr = line.slice(5).trim();
676 if (!payloadStr || payloadStr === '[DONE]') continue;
677
678 try {
679 const chunk = JSON.parse(payloadStr) as {
680 choices?: Array<{
681 delta?: {
682 content?: string;
683 reasoning_content?: string;
684 tool_calls?: Array<{
685 index?: number;
686 id?: string;
687 function?: { name?: string; arguments?: string };
688 }>;
689 };
690 }>;
691 usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number };
692 };
693
694 if (chunk.usage) {
695 usage = {
696 promptTokens: chunk.usage.prompt_tokens || 0,
697 outputTokens: chunk.usage.completion_tokens || 0,
698 totalTokens: chunk.usage.total_tokens || 0,
699 };
700 }
701
702 const delta = chunk.choices?.[0]?.delta;
703 if (!delta) continue;
704
705 if (delta.reasoning_content) {
706 reasoningText += delta.reasoning_content;
707 }
708 if (delta.content) {
709 rawText += delta.content;
710 // Stream clean text when not inside a raw control tag
711 if (!delta.content.includes('<|')) {
712 opts.onTextDelta(delta.content);
713 }
714 }
715 if (delta.tool_calls) {
716 for (const tc of delta.tool_calls) {
717 const idx = tc.index ?? 0;
718 const entry = tcAccum.get(idx) || {
719 id: tc.id || `ik-tc-${Date.now()}-${idx}`,
720 name: '',
721 argsJson: '',
722 };
723 if (tc.id) entry.id = tc.id;
724 if (tc.function?.name) entry.name += tc.function.name;
725 if (tc.function?.arguments) entry.argsJson += tc.function.arguments;
726 tcAccum.set(idx, entry);
727 }
728 }
729 } catch {
730 // ignore malformed SSE frame
731 }
732 }
733 }
734
735 const parsed = parseInklingTokens(rawText);
736 if (reasoningText && !parsed.thinking) {
737 parsed.thinking = reasoningText;
738 }
739 for (const entry of tcAccum.values()) {
740 if (!entry.name) continue;
741 let args: Record<string, unknown> = {};
742 try {
743 args = entry.argsJson ? JSON.parse(entry.argsJson) : {};
744 } catch {
745 args = {};
746 }
747 parsed.toolCalls.push({ id: entry.id, name: entry.name, args });
748 }
749
750 return { parsed, rawContent: rawText, usage };
751}