@chatpanel/sdk 0.1.0

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/dist/index.js ADDED
@@ -0,0 +1,94 @@
1
+ // @chatpanel/sdk — a typed client for the local ChatPanel gateway.
2
+ //
3
+ // import { ChatPanel } from '@chatpanel/sdk';
4
+ // const cp = await ChatPanel.fromEnvironment(); // Node: reads ~/.chatpanel/gateway-token
5
+ // const hits = await cp.history.smartSearch({ question: 'what did we decide about the launch?' });
6
+ // for await (const delta of cp.chat.text({ model: 'claude', messages: [{ role: 'user', content: 'hi' }] })) process.stdout.write(delta);
7
+ //
8
+ // The namespaces (`history`, `memory`, `chat`, …) are GENERATED from the contract; this file
9
+ // adds the few things that need judgement: construction, discovery, pairing, and a text
10
+ // iterator over the chat stream.
11
+ import { buildApi, OPERATIONS } from './api.generated.js';
12
+ import { discoverBaseUrl, discoverToken } from './discover.js';
13
+ import { Runtime } from './runtime.js';
14
+ export * from './errors.js';
15
+ export * from './api.generated.js';
16
+ export * as types from './types.generated.js';
17
+ export { Runtime, compareVersions, normaliseBaseUrl } from './runtime.js';
18
+ export { parseFrame, readSse } from './sse.js';
19
+ export { discoverBaseUrl, discoverToken, TOKEN_ENV, TOKEN_PATH_ENV, URL_ENV } from './discover.js';
20
+ /** The text of one streamed chunk, or '' when the frame carried none (a usage frame, a tool call). */
21
+ export function deltaText(frame) {
22
+ const d = frame.data;
23
+ if (!d || typeof d !== 'object')
24
+ return '';
25
+ const delta = d.choices?.[0]?.delta;
26
+ return typeof delta?.content === 'string' ? delta.content : '';
27
+ }
28
+ export class ChatPanel {
29
+ runtime;
30
+ gateway;
31
+ models;
32
+ chat;
33
+ redaction;
34
+ history;
35
+ memory;
36
+ prefs;
37
+ teams;
38
+ projects;
39
+ agents;
40
+ engines;
41
+ skills;
42
+ constructor(options = {}) {
43
+ this.runtime = new Runtime(options);
44
+ const api = buildApi(this.runtime);
45
+ this.gateway = api.gateway;
46
+ this.models = api.models;
47
+ this.redaction = api.redaction;
48
+ this.history = api.history;
49
+ this.memory = api.memory;
50
+ this.prefs = api.prefs;
51
+ this.teams = api.teams;
52
+ this.projects = api.projects;
53
+ this.agents = api.agents;
54
+ this.engines = api.engines;
55
+ this.skills = api.skills;
56
+ const chat = api.chat;
57
+ this.chat = Object.assign(chat, {
58
+ async *text(body, opts) {
59
+ for await (const frame of chat.completionsStream(body, opts)) {
60
+ const t = deltaText(frame);
61
+ if (t)
62
+ yield t;
63
+ }
64
+ },
65
+ });
66
+ }
67
+ /**
68
+ * A client for the gateway on this machine, authenticated as the current user: the URL
69
+ * from `CHATPANEL_GATEWAY_URL` and the token from `CHATPANEL_GATEWAY_TOKEN` or the token
70
+ * file. Node only — in a browser, construct one and `pair()`.
71
+ */
72
+ static async fromEnvironment(options = {}) {
73
+ const token = await discoverToken();
74
+ return new ChatPanel({ ...options, baseUrl: options.baseUrl ?? discoverBaseUrl(), token: token || undefined });
75
+ }
76
+ /** GET /health — the version and capabilities. */
77
+ health() { return this.gateway.health(); }
78
+ /** POST /whoami — the trust class this client's credential earns. */
79
+ whoami() { return this.gateway.whoami(); }
80
+ /**
81
+ * Exchange a one-time code (from `chatpanel-gateway pair`, or the desktop app) for the
82
+ * token, and start using it. The token is RETURNED so the application can persist it —
83
+ * in the platform keychain or a 0600 file, never in a log or a URL.
84
+ */
85
+ async pair(code) {
86
+ const paired = await this.gateway.pair({ code: String(code).trim() });
87
+ this.runtime.setToken(paired.token);
88
+ return paired;
89
+ }
90
+ /** Any operation by id, for a route added to the contract before this package learnt a method for it. */
91
+ request(id, args = {}) {
92
+ return this.runtime.request(OPERATIONS[id], args);
93
+ }
94
+ }
@@ -0,0 +1,76 @@
1
+ import { type SseFrame } from './sse.js';
2
+ export type { SseFrame } from './sse.js';
3
+ /** One row of the generated route table. */
4
+ export interface Operation {
5
+ readonly id: string;
6
+ readonly method: string;
7
+ readonly path: string;
8
+ readonly auth: 'open' | 'token';
9
+ readonly since: string | null;
10
+ readonly stream: 'sse' | 'sse-when-stream' | null;
11
+ readonly pathParams: readonly string[];
12
+ readonly queryParams: readonly string[];
13
+ }
14
+ /** Per-call options every generated method accepts last. */
15
+ export interface RequestOptions {
16
+ signal?: AbortSignal;
17
+ timeoutMs?: number;
18
+ headers?: Record<string, string | undefined>;
19
+ query?: Record<string, unknown>;
20
+ }
21
+ export type TokenSource = string | undefined | (() => string | undefined | Promise<string | undefined>);
22
+ export interface RuntimeOptions {
23
+ /** Default `http://127.0.0.1:4320`. */
24
+ baseUrl?: string;
25
+ /** The gateway token, or a function that produces it (a keychain read, for instance). */
26
+ token?: TokenSource;
27
+ /** A non-loopback `baseUrl` is refused unless this is true — and then it must be https. */
28
+ allowRemote?: boolean;
29
+ /** Default 20 000 ms. Streams are not subject to it once the headers have arrived. */
30
+ timeoutMs?: number;
31
+ /** GET retries on a network error or 502/503. Default 2. Never applied to a write. */
32
+ retries?: number;
33
+ /** Check `since` against GET /health before a call. Default true. */
34
+ versionGate?: boolean;
35
+ /** Injected for tests and proxies. Default: the global fetch. */
36
+ fetch?: typeof fetch;
37
+ /** Sent as `User-Agent` where the runtime allows it. */
38
+ userAgent?: string;
39
+ }
40
+ export interface CallArgs {
41
+ path?: Record<string, string | undefined>;
42
+ query?: Record<string, unknown> | undefined;
43
+ headers?: Record<string, string | undefined>;
44
+ body?: unknown;
45
+ opts?: RequestOptions;
46
+ }
47
+ export declare function compareVersions(a: string, b: string): number;
48
+ /** Validate a base URL under the loopback rule. Returns the normalised origin (no trailing slash). */
49
+ export declare function normaliseBaseUrl(raw: string | undefined, allowRemote: boolean): string;
50
+ export declare class Runtime {
51
+ readonly baseUrl: string;
52
+ private readonly tokenSource;
53
+ private readonly timeoutMs;
54
+ private readonly retries;
55
+ private readonly versionGate;
56
+ private readonly fetchImpl;
57
+ private readonly userAgent;
58
+ private versionCache;
59
+ private tokenOverride;
60
+ constructor(options?: RuntimeOptions);
61
+ /** Nothing about the credential is ever printed. */
62
+ toString(): string;
63
+ /** Use a token obtained after construction — pairing, for instance. */
64
+ setToken(token: string | undefined): void;
65
+ token(): Promise<string>;
66
+ /** The running gateway's version — one GET /health per 30 s window. A failed probe is not cached. */
67
+ version(): Promise<string>;
68
+ /** Forget the cached version — after restarting or replacing the gateway. */
69
+ forgetVersion(): void;
70
+ /** One JSON request. Resolves to the parsed body; rejects with a ChatPanelError subclass. */
71
+ request<R = unknown>(op: Operation, args?: CallArgs): Promise<R>;
72
+ /** One SSE request. Yields frames until the server closes, `[DONE]` arrives, or the signal aborts. */
73
+ stream<F = unknown>(op: Operation, args?: CallArgs): AsyncGenerator<SseFrame<F>>;
74
+ private prepare;
75
+ private send;
76
+ }
@@ -0,0 +1,265 @@
1
+ // The transport. One place that knows how to reach the gateway, so the rules below cannot
2
+ // be forgotten at a call site — every generated method goes through `request` or `stream`.
3
+ //
4
+ // The rules, and why each exists:
5
+ // • LOOPBACK BY DEFAULT. The gateway only answers on 127.0.0.1, and the token is a bearer
6
+ // secret: a base URL on another host is refused unless the integrator opts in AND uses
7
+ // TLS, so the token can never be sent in the clear to a machine that is not this one.
8
+ // • THE TOKEN IS NEVER LOGGED. It is resolved lazily from a source function, attached as a
9
+ // header, and appears in no error, no toString, no debug output.
10
+ // • ONLY THE CONTRACT IS SENT. Path parameters are URL-encoded one segment each; query
11
+ // parameters not declared for the operation are dropped; a token-gated operation with no
12
+ // token fails HERE, with a sentence that says how to get one, instead of a bare 403.
13
+ // • THE VERSION GATE. A route the running gateway does not have does not 404 usefully — it
14
+ // falls through to the model proxy as "upstream fetch failed". So `since` is checked
15
+ // against one cached GET /health first, and refused as what it is: too old.
16
+ // • BOUNDED. Every request has a timeout; retries are for idempotent GETs only, bounded
17
+ // and jittered; a chat POST is never replayed.
18
+ import { ChatPanelError, ForbiddenError, GatewayTooOldError, GatewayUnreachableError, InvalidRequestError, errorFromResponse } from './errors.js';
19
+ import { readSse } from './sse.js';
20
+ const LOOPBACK = /^(127\.0\.0\.1|localhost|\[::1\]|::1)$/;
21
+ const VERSION_TTL_MS = 30_000;
22
+ export function compareVersions(a, b) {
23
+ const pa = a.split('.').map((n) => parseInt(n, 10) || 0);
24
+ const pb = b.split('.').map((n) => parseInt(n, 10) || 0);
25
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
26
+ const d = (pa[i] || 0) - (pb[i] || 0);
27
+ if (d)
28
+ return d;
29
+ }
30
+ return 0;
31
+ }
32
+ /** Validate a base URL under the loopback rule. Returns the normalised origin (no trailing slash). */
33
+ export function normaliseBaseUrl(raw, allowRemote) {
34
+ const text = (raw || 'http://127.0.0.1:4320').trim();
35
+ let u;
36
+ try {
37
+ u = new URL(text);
38
+ }
39
+ catch {
40
+ throw new InvalidRequestError(`baseUrl is not a URL: ${text}`);
41
+ }
42
+ if (u.username || u.password)
43
+ throw new InvalidRequestError('baseUrl must not carry credentials');
44
+ if (!/^https?:$/.test(u.protocol))
45
+ throw new InvalidRequestError(`baseUrl must be http or https (got ${u.protocol})`);
46
+ const loopback = LOOPBACK.test(u.hostname);
47
+ if (!loopback) {
48
+ if (!allowRemote)
49
+ throw new InvalidRequestError(`baseUrl ${u.origin} is not loopback — the gateway only answers on this machine; pass allowRemote: true (and https) only for a tunnel you control`);
50
+ if (u.protocol !== 'https:')
51
+ throw new InvalidRequestError(`a remote baseUrl must be https — the token would otherwise travel in the clear`);
52
+ }
53
+ return u.origin + u.pathname.replace(/\/+$/, '');
54
+ }
55
+ export class Runtime {
56
+ baseUrl;
57
+ tokenSource;
58
+ timeoutMs;
59
+ retries;
60
+ versionGate;
61
+ fetchImpl;
62
+ userAgent;
63
+ versionCache = { at: 0, version: '' };
64
+ tokenOverride;
65
+ constructor(options = {}) {
66
+ this.baseUrl = normaliseBaseUrl(options.baseUrl, !!options.allowRemote);
67
+ this.tokenSource = options.token;
68
+ this.timeoutMs = options.timeoutMs ?? 20_000;
69
+ this.retries = Math.max(0, Math.min(5, options.retries ?? 2));
70
+ this.versionGate = options.versionGate !== false;
71
+ this.fetchImpl = options.fetch ?? globalThis.fetch;
72
+ this.userAgent = options.userAgent ?? '';
73
+ if (typeof this.fetchImpl !== 'function')
74
+ throw new InvalidRequestError('no fetch available — pass options.fetch');
75
+ }
76
+ /** Nothing about the credential is ever printed. */
77
+ toString() { return `ChatPanel Runtime(${this.baseUrl})`; }
78
+ [Symbol.for('nodejs.util.inspect.custom')]() { return this.toString(); }
79
+ /** Use a token obtained after construction — pairing, for instance. */
80
+ setToken(token) { this.tokenOverride = token; }
81
+ async token() {
82
+ if (this.tokenOverride !== undefined)
83
+ return this.tokenOverride;
84
+ const s = this.tokenSource;
85
+ const v = typeof s === 'function' ? await s() : s;
86
+ return (v || '').trim();
87
+ }
88
+ /** The running gateway's version — one GET /health per 30 s window. A failed probe is not cached. */
89
+ async version() {
90
+ const now = Date.now();
91
+ if (this.versionCache.version && now - this.versionCache.at < VERSION_TTL_MS)
92
+ return this.versionCache.version;
93
+ const res = await this.send('GET', `${this.baseUrl}/health`, {}, undefined, 4000, undefined, 'gateway.health');
94
+ const text = await res.text();
95
+ let version = '';
96
+ try {
97
+ version = String(JSON.parse(text)?.version || '');
98
+ }
99
+ catch { /* not JSON */ }
100
+ if (version)
101
+ this.versionCache = { at: now, version };
102
+ return version;
103
+ }
104
+ /** Forget the cached version — after restarting or replacing the gateway. */
105
+ forgetVersion() { this.versionCache = { at: 0, version: '' }; }
106
+ /** One JSON request. Resolves to the parsed body; rejects with a ChatPanelError subclass. */
107
+ async request(op, args = {}) {
108
+ const { url, headers, timeoutMs, signal } = await this.prepare(op, args);
109
+ const body = args.body === undefined ? undefined : JSON.stringify(args.body);
110
+ if (body !== undefined)
111
+ headers['Content-Type'] = 'application/json';
112
+ headers['Accept'] = 'application/json';
113
+ const attempts = op.method === 'GET' ? this.retries + 1 : 1;
114
+ let lastErr = null;
115
+ for (let attempt = 0; attempt < attempts; attempt++) {
116
+ if (attempt)
117
+ await new Promise((r) => setTimeout(r, 150 * attempt + Math.random() * 200));
118
+ try {
119
+ const res = await this.send(op.method, url, headers, body, timeoutMs, signal, op.id);
120
+ const text = await res.text();
121
+ if (!res.ok) {
122
+ const err = errorFromResponse(res.status, text, op.id);
123
+ if ((res.status === 502 || res.status === 503) && attempt + 1 < attempts) {
124
+ lastErr = err;
125
+ continue;
126
+ }
127
+ throw err;
128
+ }
129
+ if (!text)
130
+ return undefined;
131
+ try {
132
+ return JSON.parse(text);
133
+ }
134
+ catch {
135
+ throw new ChatPanelError(`${op.id}: the gateway answered with something other than JSON`, { status: res.status, type: 'bad_response', operation: op.id });
136
+ }
137
+ }
138
+ catch (e) {
139
+ if (e instanceof GatewayUnreachableError && attempt + 1 < attempts && !signal?.aborted) {
140
+ lastErr = e;
141
+ continue;
142
+ }
143
+ throw e;
144
+ }
145
+ }
146
+ throw lastErr ?? new GatewayUnreachableError(`${op.id}: gave up`, op.id);
147
+ }
148
+ /** One SSE request. Yields frames until the server closes, `[DONE]` arrives, or the signal aborts. */
149
+ async *stream(op, args = {}) {
150
+ const { url, headers, timeoutMs, signal } = await this.prepare(op, args);
151
+ const body = args.body === undefined ? undefined : JSON.stringify(args.body);
152
+ if (body !== undefined)
153
+ headers['Content-Type'] = 'application/json';
154
+ headers['Accept'] = 'text/event-stream';
155
+ // The timeout covers the headers only: a run's tail may legitimately stay open for hours.
156
+ const headerCtl = new AbortController();
157
+ const timer = setTimeout(() => headerCtl.abort(), timeoutMs);
158
+ const combined = signal ? anySignal([signal, headerCtl.signal]) : headerCtl.signal;
159
+ let res;
160
+ try {
161
+ res = await this.fetchImpl(url, { method: op.method, headers, body, signal: combined });
162
+ }
163
+ catch (e) {
164
+ clearTimeout(timer);
165
+ if (signal?.aborted)
166
+ throw new ChatPanelError(`${op.id}: aborted`, { status: 0, type: 'aborted', operation: op.id });
167
+ throw new GatewayUnreachableError(`${op.id}: couldn't reach the gateway on ${this.baseUrl} — ${e.message}`, op.id);
168
+ }
169
+ clearTimeout(timer);
170
+ if (!res.ok)
171
+ throw errorFromResponse(res.status, await res.text().catch(() => ''), op.id);
172
+ if (!res.body)
173
+ throw new ChatPanelError(`${op.id}: no response body`, { status: res.status, type: 'bad_response', operation: op.id });
174
+ // An abort by the caller ENDS the iteration; it is not an error. Anything else that
175
+ // interrupts the body (the gateway restarting mid-stream) is reported as unreachable.
176
+ try {
177
+ for await (const frame of readSse(res.body, { stopAtDone: op.stream === 'sse-when-stream' })) {
178
+ if (signal?.aborted)
179
+ return;
180
+ yield frame;
181
+ }
182
+ }
183
+ catch (e) {
184
+ if (signal?.aborted)
185
+ return;
186
+ throw new GatewayUnreachableError(`${op.id}: the stream ended early — ${e.message}`, op.id);
187
+ }
188
+ }
189
+ async prepare(op, args) {
190
+ if (this.versionGate && op.since) {
191
+ const have = await this.version();
192
+ if (!have)
193
+ throw new GatewayUnreachableError(`${op.id}: the gateway on ${this.baseUrl} is not answering`, op.id);
194
+ if (compareVersions(op.since, have) > 0)
195
+ throw new GatewayTooOldError(op.id, have, op.since);
196
+ }
197
+ const headers = {};
198
+ if (this.userAgent)
199
+ headers['User-Agent'] = this.userAgent;
200
+ const token = await this.token();
201
+ if (token)
202
+ headers['Authorization'] = `Bearer ${token}`;
203
+ else if (op.auth === 'token') {
204
+ throw new ForbiddenError(`${op.id} needs the gateway token and this client has none — pass { token }, set CHATPANEL_GATEWAY_TOKEN, or pair with a code from \`chatpanel-gateway pair\``, op.id);
205
+ }
206
+ for (const [k, v] of Object.entries({ ...(args.headers || {}), ...(args.opts?.headers || {}) })) {
207
+ if (v === undefined || v === null)
208
+ continue;
209
+ if (/^(authorization|x-chatpanel-token|host|content-length)$/i.test(k))
210
+ throw new InvalidRequestError(`${op.id}: header ${k} is managed by the SDK`, op.id);
211
+ if (/[\r\n]/.test(v))
212
+ throw new InvalidRequestError(`${op.id}: header ${k} must be one line`, op.id);
213
+ headers[k] = String(v);
214
+ }
215
+ // Path: every declared segment present and encoded as ONE segment; the gateway's own
216
+ // regexes still apply, this is the half we own.
217
+ let path = op.path;
218
+ for (const name of op.pathParams) {
219
+ const v = args.path?.[name];
220
+ if (v === undefined || v === null || String(v) === '')
221
+ throw new InvalidRequestError(`${op.id}: path parameter ${name} is required`, op.id);
222
+ if (/[/\\]/.test(String(v)) || String(v) === '.' || String(v) === '..')
223
+ throw new InvalidRequestError(`${op.id}: path parameter ${name} must be one segment`, op.id);
224
+ path = path.replace(`{${name}}`, encodeURIComponent(String(v)));
225
+ }
226
+ const url = new URL(this.baseUrl + path);
227
+ for (const [k, v] of Object.entries({ ...(args.query || {}), ...(args.opts?.query || {}) })) {
228
+ if (!op.queryParams.includes(k) || v === undefined || v === null)
229
+ continue;
230
+ url.searchParams.set(k, typeof v === 'boolean' ? (v ? '1' : '0') : String(v));
231
+ }
232
+ return { url: url.toString(), headers, timeoutMs: args.opts?.timeoutMs ?? this.timeoutMs, signal: args.opts?.signal };
233
+ }
234
+ async send(method, url, headers, body, timeoutMs, signal, operation) {
235
+ const ctl = new AbortController();
236
+ const timer = setTimeout(() => ctl.abort(), timeoutMs);
237
+ const combined = signal ? anySignal([signal, ctl.signal]) : ctl.signal;
238
+ try {
239
+ return await this.fetchImpl(url, { method, headers, body, signal: combined });
240
+ }
241
+ catch (e) {
242
+ if (signal?.aborted)
243
+ throw new ChatPanelError(`${operation}: aborted`, { status: 0, type: 'aborted', operation });
244
+ const reason = ctl.signal.aborted ? `did not answer within ${timeoutMs} ms` : e.message;
245
+ throw new GatewayUnreachableError(`${operation}: couldn't reach the gateway on ${this.baseUrl} — ${reason}`, operation);
246
+ }
247
+ finally {
248
+ clearTimeout(timer);
249
+ }
250
+ }
251
+ }
252
+ function anySignal(signals) {
253
+ const any = AbortSignal.any;
254
+ if (typeof any === 'function')
255
+ return any(signals);
256
+ const ctl = new AbortController();
257
+ for (const s of signals) {
258
+ if (s.aborted) {
259
+ ctl.abort();
260
+ break;
261
+ }
262
+ s.addEventListener('abort', () => ctl.abort(), { once: true });
263
+ }
264
+ return ctl.signal;
265
+ }
package/dist/sse.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ export interface SseFrame<T = unknown> {
2
+ /** The `event:` name, or `message` when the frame had none. */
3
+ event: string;
4
+ /** The parsed `data:` payload — JSON when it parses, the raw string otherwise. */
5
+ data: T;
6
+ id?: string;
7
+ /** The `data:` text exactly as received. */
8
+ raw: string;
9
+ }
10
+ export declare function parseFrame(block: string): SseFrame | null;
11
+ /** Read a body stream as SSE frames. Stops at `[DONE]` (the OpenAI terminator) when `stopAtDone` is set. */
12
+ export declare function readSse<T>(body: ReadableStream<Uint8Array>, { stopAtDone }?: {
13
+ stopAtDone?: boolean;
14
+ }): AsyncGenerator<SseFrame<T>>;
package/dist/sse.js ADDED
@@ -0,0 +1,67 @@
1
+ // A text/event-stream reader. Frames are separated by a blank line; a chunk boundary can
2
+ // fall anywhere, so the tail stays in the buffer until its terminator arrives — splitting on
3
+ // '\n' alone is the classic way to lose a token every few hundred. `data:` lines of one frame
4
+ // are joined with '\n' per the spec; comment lines (`: keep-alive`) are dropped.
5
+ export function parseFrame(block) {
6
+ let event = 'message';
7
+ let id;
8
+ const data = [];
9
+ for (const line of block.split('\n')) {
10
+ if (!line || line.startsWith(':'))
11
+ continue;
12
+ const colon = line.indexOf(':');
13
+ const field = colon === -1 ? line : line.slice(0, colon);
14
+ let value = colon === -1 ? '' : line.slice(colon + 1);
15
+ if (value.startsWith(' '))
16
+ value = value.slice(1);
17
+ if (field === 'event')
18
+ event = value;
19
+ else if (field === 'data')
20
+ data.push(value);
21
+ else if (field === 'id')
22
+ id = value;
23
+ }
24
+ if (!data.length)
25
+ return null;
26
+ const raw = data.join('\n');
27
+ let parsed = raw;
28
+ try {
29
+ parsed = JSON.parse(raw);
30
+ }
31
+ catch { /* a plain string frame, e.g. [DONE] */ }
32
+ return { event, data: parsed, ...(id !== undefined ? { id } : {}), raw };
33
+ }
34
+ /** Read a body stream as SSE frames. Stops at `[DONE]` (the OpenAI terminator) when `stopAtDone` is set. */
35
+ export async function* readSse(body, { stopAtDone = false } = {}) {
36
+ const reader = body.getReader();
37
+ const decoder = new TextDecoder();
38
+ let buffer = '';
39
+ try {
40
+ for (;;) {
41
+ const { done, value } = await reader.read();
42
+ if (done)
43
+ break;
44
+ buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, '\n');
45
+ let sep;
46
+ while ((sep = buffer.indexOf('\n\n')) !== -1) {
47
+ const block = buffer.slice(0, sep);
48
+ buffer = buffer.slice(sep + 2);
49
+ const frame = parseFrame(block);
50
+ if (!frame)
51
+ continue;
52
+ if (stopAtDone && frame.raw.trim() === '[DONE]')
53
+ return;
54
+ yield frame;
55
+ }
56
+ }
57
+ const last = parseFrame(buffer);
58
+ if (last && !(stopAtDone && last.raw.trim() === '[DONE]'))
59
+ yield last;
60
+ }
61
+ finally {
62
+ try {
63
+ await reader.cancel();
64
+ }
65
+ catch { /* already closed */ }
66
+ }
67
+ }