Something went wrong. Try again.
A monorepo for writing specs and other serious text on the AT Protocol.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102// Reading an answer as it comes: lines of JSON (Claude Code's stream, the// sidecar's), or server-sent events (an OpenAI-compatible server with// `stream: true`). Each reader takes a Response, calls back per unit, and// stops when the signal aborts.import type { AssistantEvent } from './types.ts';
/** Read a body line by line, calling `onLine` for each non-empty one; the whole text is returned too. */export async function readLines(res: Response, onLine: (line: string) => void, signal?: AbortSignal): Promise<string> { const body = res.body; if (!body) { const text = await res.text(); for (const line of text.split('\n')) if (line.trim()) onLine(line); return text; } const reader = body.getReader(); const decoder = new TextDecoder(); let buf = ''; let all = ''; const stop = () => void reader.cancel().catch(() => {}); signal?.addEventListener('abort', stop, { once: true }); try { for (;;) { const { value, done } = await reader.read(); if (done) break; const chunk = decoder.decode(value, { stream: true }); all += chunk; buf += chunk; let at: number; while ((at = buf.indexOf('\n')) >= 0) { const line = buf.slice(0, at).replace(/\r$/, ''); buf = buf.slice(at + 1); if (line.trim()) onLine(line); } } if (buf.trim()) onLine(buf); } finally { signal?.removeEventListener('abort', stop); } return all;}
/** Read server-sent events, calling `onData` with each event's data (the text after `data:`, lines joined); `[DONE]` ends it. */export async function readSSE(res: Response, onData: (data: string) => void, signal?: AbortSignal): Promise<void> { let data: string[] = []; const flush = () => { if (!data.length) return; const d = data.join('\n'); data = []; if (d.trim() !== '[DONE]') onData(d); }; await readLinesRaw(res, (line) => { if (line === '') flush(); else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, '')); // comments (": keep-alive") and other fields are not ours }, signal); flush();}
/** Like readLines, but every line is reported, empty ones included (an event stream's blank lines end an event). */async function readLinesRaw(res: Response, onLine: (line: string) => void, signal?: AbortSignal): Promise<void> { const body = res.body; if (!body) { for (const line of (await res.text()).split('\n')) onLine(line.replace(/\r$/, '')); return; } const reader = body.getReader(); const decoder = new TextDecoder(); let buf = ''; const stop = () => void reader.cancel().catch(() => {}); signal?.addEventListener('abort', stop, { once: true }); try { for (;;) { const { value, done } = await reader.read(); if (done) break; buf += decoder.decode(value, { stream: true }); let at: number; while ((at = buf.indexOf('\n')) >= 0) { onLine(buf.slice(0, at).replace(/\r$/, '')); buf = buf.slice(at + 1); } } if (buf) onLine(buf); } finally { signal?.removeEventListener('abort', stop); }}
/** A number of characters or tokens, for a status line: "1,200 characters". */export const countOf = (n: number, unit: string): string => `${n.toLocaleString()} ${unit}${n === 1 ? '' : 's'}`;
/** Seconds since `since`, for a status line: "12 s", "1 min 30 s". */export function elapsed(since: number, now = Date.now()): string { const s = Math.max(0, Math.round((now - since) / 1000)); return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min ${s % 60} s`;}
/** An error that means the writer stopped the request. */export const isAbort = (err: unknown): boolean => err instanceof Error && (err.name === 'AbortError' || /aborted/i.test(err.message));
/** A reporter that does nothing, for assistants asked without one. */export const noEvents = (_e: AssistantEvent): void => {};