tina4-nodejs 3.13.112 → 3.13.113

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.
@@ -38805,11 +38805,100 @@ function buildMultipartBody(boundary, fieldName, filename, fileContent, contentT
38805
38805
  parts.push(Buffer.from(delimiter4 + "--" + crlf, "utf-8"));
38806
38806
  return Buffer.concat(parts);
38807
38807
  }
38808
- var RETRY_STATUSES, DOWNLOAD_CHUNK_SIZE, MAX_REDIRECTS, STRIP_ON_CROSS_ORIGIN, MIME_BY_EXT, Api;
38808
+ async function* parseLineStream(chunks) {
38809
+ const decoder = new TextDecoder("utf-8");
38810
+ let buffer = "";
38811
+ for await (const chunk of chunks) {
38812
+ buffer += decoder.decode(chunk, { stream: true });
38813
+ let idx;
38814
+ while ((idx = buffer.indexOf("\n")) >= 0) {
38815
+ let line = buffer.slice(0, idx);
38816
+ buffer = buffer.slice(idx + 1);
38817
+ if (line.endsWith("\r")) {
38818
+ line = line.slice(0, -1);
38819
+ }
38820
+ yield line;
38821
+ }
38822
+ }
38823
+ buffer += decoder.decode();
38824
+ if (buffer.length > 0) {
38825
+ if (buffer.endsWith("\r")) {
38826
+ buffer = buffer.slice(0, -1);
38827
+ }
38828
+ yield buffer;
38829
+ }
38830
+ }
38831
+ async function* parseSseStream(lines) {
38832
+ let dataParts = [];
38833
+ let event;
38834
+ let id;
38835
+ let retry;
38836
+ let has = false;
38837
+ const emit = () => {
38838
+ if (!has) return null;
38839
+ const ev = { data: dataParts.join("\n") };
38840
+ if (event !== void 0) ev.event = event;
38841
+ if (id !== void 0) ev.id = id;
38842
+ if (retry !== void 0) ev.retry = retry;
38843
+ return ev;
38844
+ };
38845
+ const reset2 = () => {
38846
+ dataParts = [];
38847
+ event = void 0;
38848
+ id = void 0;
38849
+ retry = void 0;
38850
+ has = false;
38851
+ };
38852
+ for await (const line of lines) {
38853
+ if (line === "") {
38854
+ const ev = emit();
38855
+ if (ev) yield ev;
38856
+ reset2();
38857
+ continue;
38858
+ }
38859
+ if (line.startsWith(":")) continue;
38860
+ const colon = line.indexOf(":");
38861
+ const field = colon < 0 ? line : line.slice(0, colon);
38862
+ let value = colon < 0 ? "" : line.slice(colon + 1);
38863
+ if (value.startsWith(" ")) value = value.slice(1);
38864
+ switch (field) {
38865
+ case "data":
38866
+ dataParts.push(value);
38867
+ has = true;
38868
+ break;
38869
+ case "event":
38870
+ event = value;
38871
+ has = true;
38872
+ break;
38873
+ case "id":
38874
+ id = value;
38875
+ has = true;
38876
+ break;
38877
+ case "retry": {
38878
+ const parsed = Number(value);
38879
+ if (Number.isFinite(parsed) && parsed >= 0) {
38880
+ retry = parsed;
38881
+ has = true;
38882
+ }
38883
+ break;
38884
+ }
38885
+ }
38886
+ }
38887
+ const trailing = emit();
38888
+ if (trailing) yield trailing;
38889
+ }
38890
+ var ApiStreamError, RETRY_STATUSES, DOWNLOAD_CHUNK_SIZE, MAX_REDIRECTS, STRIP_ON_CROSS_ORIGIN, MIME_BY_EXT, Api;
38809
38891
  var init_api = __esm({
38810
38892
  "../core/src/api.ts"() {
38811
38893
  "use strict";
38812
38894
  init_version();
38895
+ ApiStreamError = class extends Error {
38896
+ constructor(message, status2 = null) {
38897
+ super(message);
38898
+ this.status = status2;
38899
+ this.name = "ApiStreamError";
38900
+ }
38901
+ };
38813
38902
  RETRY_STATUSES = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
38814
38903
  DOWNLOAD_CHUNK_SIZE = 64 * 1024;
38815
38904
  MAX_REDIRECTS = 10;
@@ -39128,7 +39217,130 @@ var init_api = __esm({
39128
39217
  }
39129
39218
  return { http_code: code, headers: respHeaders, error: null, path: destPath };
39130
39219
  }
39220
+ /**
39221
+ * Stream a response body as raw bytes. Yields the chunks the transport
39222
+ * delivers, in order, never buffered whole. Ends cleanly on EOF and
39223
+ * throws on a transport failure or a non-2xx status (body drained
39224
+ * first). No JSON decoding, no line splitting, no framing —
39225
+ * {@link streamLines} and {@link streamSse} build on this primitive.
39226
+ *
39227
+ * Closing the iterator before EOF (a `break` out of a `for await`)
39228
+ * destroys the underlying socket, so a caller who takes only the
39229
+ * first few chunks never leaks the connection.
39230
+ *
39231
+ * `opts.timeout` bounds the whole stream duration (default
39232
+ * `TINA4_API_TIMEOUT` or the client `timeout`); `opts.connectTimeout`
39233
+ * bounds just the connect + headers phase (default
39234
+ * `TINA4_API_CONNECT_TIMEOUT` or 10s).
39235
+ */
39236
+ async *streamBytes(path8, opts = {}) {
39237
+ const url = this.buildUrl(path8);
39238
+ const method = (opts.method ?? "GET").toUpperCase();
39239
+ const contentType = opts.contentType ?? "application/json";
39240
+ const { headers, data } = this.buildRequest(method, contentType, opts.body, opts.headers);
39241
+ const totalSec = this.streamSeconds(opts.timeout, "TINA4_API_TIMEOUT", this.timeout);
39242
+ const connectSec = this.streamSeconds(opts.connectTimeout, "TINA4_API_CONNECT_TIMEOUT", 10);
39243
+ const opened = await this.openStreamRequest(method, url, headers, data, connectSec);
39244
+ const res = opened.res;
39245
+ const status2 = res.statusCode ?? 0;
39246
+ this.storeCookies(res.headers["set-cookie"]);
39247
+ if (status2 < 200 || status2 >= 300) {
39248
+ res.resume();
39249
+ throw new ApiStreamError(`stream failed with HTTP ${status2}`, status2);
39250
+ }
39251
+ let totalTimer = null;
39252
+ if (totalSec > 0) {
39253
+ totalTimer = setTimeout(() => {
39254
+ res.destroy(new ApiStreamError(`stream total timeout after ${totalSec}s`, null));
39255
+ }, totalSec * 1e3);
39256
+ }
39257
+ try {
39258
+ for await (const chunk of res) {
39259
+ yield chunk;
39260
+ }
39261
+ } finally {
39262
+ if (totalTimer) clearTimeout(totalTimer);
39263
+ if (!res.destroyed) res.destroy();
39264
+ }
39265
+ }
39266
+ /**
39267
+ * Stream the response body as UTF-8 lines. Splits on LF or CRLF;
39268
+ * buffers a multibyte codepoint that lands across a chunk boundary;
39269
+ * yields a trailing line without a terminator on EOF. Built on
39270
+ * {@link streamBytes} plus the shared {@link parseLineStream}.
39271
+ */
39272
+ async *streamLines(path8, opts = {}) {
39273
+ yield* parseLineStream(this.streamBytes(path8, opts));
39274
+ }
39275
+ /**
39276
+ * Stream the response as SSE (Server-Sent Events). Yields one
39277
+ * {@link SseEvent} per event boundary (blank line) or on EOF for a
39278
+ * trailing event. `data:[DONE]` is delivered as an ordinary event
39279
+ * with `data === "[DONE]"` and the iterator ends on the next EOF.
39280
+ * Built on {@link streamLines} plus the shared {@link parseSseStream}.
39281
+ */
39282
+ async *streamSse(path8, opts = {}) {
39283
+ yield* parseSseStream(this.streamLines(path8, opts));
39284
+ }
39131
39285
  // ── Internal helpers ──────────────────────────────────────────────
39286
+ /**
39287
+ * Resolve a stream duration from (in order): explicit `opts` field,
39288
+ * the named env var, then the fallback. Zero disables. A non-numeric
39289
+ * or negative env value warns via a fallback rather than throwing —
39290
+ * a bad env var must not brick every streaming call.
39291
+ */
39292
+ streamSeconds(explicit, envName, fallback) {
39293
+ if (explicit !== void 0) {
39294
+ return Number.isFinite(explicit) && explicit >= 0 ? Number(explicit) : fallback;
39295
+ }
39296
+ const raw = process.env[envName];
39297
+ if (raw === void 0) return fallback;
39298
+ const n = Number(raw);
39299
+ return Number.isFinite(n) && n >= 0 ? n : fallback;
39300
+ }
39301
+ /**
39302
+ * Open a streaming HTTP request. Returns the raw
39303
+ * {@link http.IncomingMessage} once headers arrive. Redirects are NOT
39304
+ * followed on streams (a caller who needs a redirect should do a
39305
+ * regular GET first). Connect phase is bounded by `connectSec`;
39306
+ * body-phase timeout is applied by the caller (streamBytes) via
39307
+ * `res.destroy()`.
39308
+ */
39309
+ openStreamRequest(method, url, headers, data, connectSec) {
39310
+ return new Promise((resolve30, reject) => {
39311
+ let parsed;
39312
+ try {
39313
+ parsed = new URL2(url);
39314
+ } catch (err) {
39315
+ reject(err instanceof Error ? err : new Error(String(err)));
39316
+ return;
39317
+ }
39318
+ const isHttps = parsed.protocol === "https:";
39319
+ const protocolModule = isHttps ? https : http;
39320
+ const options = {
39321
+ hostname: parsed.hostname,
39322
+ port: parsed.port || (isHttps ? 443 : 80),
39323
+ path: parsed.pathname + parsed.search,
39324
+ method,
39325
+ headers,
39326
+ timeout: connectSec > 0 ? connectSec * 1e3 : void 0
39327
+ };
39328
+ if (isHttps && this.ignoreSsl) {
39329
+ options.rejectUnauthorized = false;
39330
+ }
39331
+ const req2 = protocolModule.request(options, (res) => {
39332
+ resolve30({ res });
39333
+ });
39334
+ req2.on("timeout", () => {
39335
+ req2.destroy(new ApiStreamError(`stream connect timeout after ${connectSec}s`, null));
39336
+ });
39337
+ req2.on("error", (err) => {
39338
+ reject(err);
39339
+ });
39340
+ if (data) req2.write(data);
39341
+ req2.end();
39342
+ });
39343
+ }
39132
39344
  buildUrl(path8) {
39133
39345
  if (path8.startsWith("http://") || path8.startsWith("https://")) {
39134
39346
  return path8;
@@ -41809,10 +42021,11 @@ export default class User {
41809
42021
  // ../core/src/aiClient.ts
41810
42022
  import http2 from "node:http";
41811
42023
  import https2 from "node:https";
41812
- var AiError, AiConfigError, AiTimeoutError, AiParseError, AiHTTPError, Ai;
42024
+ var AiError, AiConfigError, AiTimeoutError, AiParseError, AiHTTPError, Ai, AggregateState;
41813
42025
  var init_aiClient = __esm({
41814
42026
  "../core/src/aiClient.ts"() {
41815
42027
  "use strict";
42028
+ init_api();
41816
42029
  AiError = class extends Error {
41817
42030
  };
41818
42031
  AiConfigError = class extends AiError {
@@ -41857,10 +42070,51 @@ var init_aiClient = __esm({
41857
42070
  throw new AiParseError("AI provider returned a malformed embedding response");
41858
42071
  }
41859
42072
  }
42073
+ /**
42074
+ * Validate role + content shape. Content may be a string OR a non-empty
42075
+ * list of {type:'text'|'image', ...} parts (ADR-0060). Malformed parts
42076
+ * fail fast with AiConfigError, never reaching the wire.
42077
+ */
41860
42078
  static validateMessages(messages) {
41861
- if (!Array.isArray(messages) || messages.length === 0 || !messages.every((message) => message && ["system", "user", "assistant"].includes(message.role) && typeof message.content === "string")) {
42079
+ if (!Array.isArray(messages) || messages.length === 0) {
41862
42080
  throw new AiConfigError("AI messages must contain supported roles and string content");
41863
42081
  }
42082
+ for (const message of messages) {
42083
+ if (!message || !["system", "user", "assistant"].includes(message.role)) {
42084
+ throw new AiConfigError("AI messages must contain supported roles and string content");
42085
+ }
42086
+ this.validateContent(message.content);
42087
+ }
42088
+ }
42089
+ static validateContent(content) {
42090
+ if (typeof content === "string") return;
42091
+ if (!Array.isArray(content) || content.length === 0) {
42092
+ throw new AiConfigError("AI message content must be a string or a non-empty list of parts");
42093
+ }
42094
+ for (const part of content) {
42095
+ if (!part || typeof part !== "object" || Array.isArray(part)) {
42096
+ throw new AiConfigError("AI content part must be an object with type and text/source");
42097
+ }
42098
+ const record = part;
42099
+ const partType = record.type;
42100
+ if (partType === "text") {
42101
+ if (typeof record.text !== "string") {
42102
+ throw new AiConfigError("AI text content part requires a string 'text' field");
42103
+ }
42104
+ } else if (partType === "image") {
42105
+ if (typeof record.source !== "string" || record.source.length === 0) {
42106
+ throw new AiConfigError("AI image content part requires a non-empty string 'source' field");
42107
+ }
42108
+ if (!record.source.startsWith("data:") && !record.source.startsWith("https://")) {
42109
+ throw new AiConfigError("AI image source must be a data: URI or an https:// URL");
42110
+ }
42111
+ if (record.source.startsWith("data:") && !/^data:[^;,\s]+;base64,[A-Za-z0-9+/=]+$/.test(record.source)) {
42112
+ throw new AiConfigError("AI image data URI must be data:<media_type>;base64,<payload>");
42113
+ }
42114
+ } else {
42115
+ throw new AiConfigError(`AI content part has unknown type '${String(partType)}'`);
42116
+ }
42117
+ }
41864
42118
  }
41865
42119
  static number(name, fallback, minimum) {
41866
42120
  const value = process.env[name] === void 0 ? fallback : Number(process.env[name]);
@@ -41908,18 +42162,57 @@ var init_aiClient = __esm({
41908
42162
  }
41909
42163
  return headers;
41910
42164
  }
42165
+ /**
42166
+ * Build the provider-specific request body from a Tina4-shaped message
42167
+ * list. Multimodal parts are translated per provider (ADR-0060):
42168
+ * - OpenAI/local: {type:'image_url', image_url:{url}}
42169
+ * - Anthropic: {type:'image', source:{type:'base64'|'url', ...}}
42170
+ * String content is preserved verbatim in the OpenAI/local shape and
42171
+ * likewise for Anthropic (both accept a bare string).
42172
+ */
41911
42173
  static chatBody(config, messages, options) {
41912
- const body = { model: config.model, messages, stream: options.stream ?? false };
42174
+ const translate = (list) => list.map((message) => ({ role: message.role, content: this.translateContent(message.content, config.provider) }));
42175
+ const body = { model: config.model, messages: translate(messages), stream: options.stream ?? false };
41913
42176
  if (options.temperature !== void 0) body.temperature = options.temperature;
41914
42177
  if (options.maxTokens !== void 0) body.max_tokens = options.maxTokens;
41915
42178
  if (config.provider === "anthropic") {
41916
- const system = messages.filter((message) => message.role === "system").map((message) => message.content);
41917
- body.messages = messages.filter((message) => message.role !== "system");
42179
+ const systemParts = messages.filter((message) => message.role === "system").map((message) => typeof message.content === "string" ? message.content : this.contentToPlainText(message.content));
42180
+ body.messages = translate(messages.filter((message) => message.role !== "system"));
41918
42181
  body.max_tokens = options.maxTokens ?? 1024;
41919
- if (system.length) body.system = system.join("\n\n");
42182
+ if (systemParts.length) body.system = systemParts.join("\n\n");
41920
42183
  }
41921
42184
  return body;
41922
42185
  }
42186
+ /**
42187
+ * Translate one message content value into the provider's on-wire shape.
42188
+ * A plain string is passed through (both providers accept a string
42189
+ * content). A parts array becomes provider-native content blocks.
42190
+ */
42191
+ static translateContent(content, provider) {
42192
+ if (typeof content === "string") return content;
42193
+ if (provider === "anthropic") {
42194
+ return content.map((part) => {
42195
+ if (part.type === "text") return { type: "text", text: part.text };
42196
+ if (part.source.startsWith("data:")) {
42197
+ const parsed = this.parseDataUri(part.source);
42198
+ return { type: "image", source: { type: "base64", media_type: parsed.mediaType, data: parsed.data } };
42199
+ }
42200
+ return { type: "image", source: { type: "url", url: part.source } };
42201
+ });
42202
+ }
42203
+ return content.map((part) => {
42204
+ if (part.type === "text") return { type: "text", text: part.text };
42205
+ return { type: "image_url", image_url: { url: part.source } };
42206
+ });
42207
+ }
42208
+ static parseDataUri(source) {
42209
+ const match = /^data:([^;,\s]+);base64,([A-Za-z0-9+/=]+)$/.exec(source);
42210
+ if (!match) throw new AiConfigError("AI image data URI must be data:<media_type>;base64,<payload>");
42211
+ return { mediaType: match[1], data: match[2] };
42212
+ }
42213
+ static contentToPlainText(parts) {
42214
+ return parts.filter((part) => part.type === "text").map((part) => part.text).join("\n\n");
42215
+ }
41923
42216
  static open(config, deadline, headers, body) {
41924
42217
  const remainingMs = deadline - performance.now();
41925
42218
  if (remainingMs <= 0) return Promise.reject(new AiTimeoutError("AI total request timeout expired"));
@@ -42019,35 +42312,12 @@ var init_aiClient = __esm({
42019
42312
  static async chatResponse(config, headers, body) {
42020
42313
  return this.normalizeChat(config.provider, await this.requestJson(config, headers, body));
42021
42314
  }
42022
- static streamDelta(provider, data) {
42023
- if (data === "[DONE]") return { completed: true };
42024
- let event;
42025
- try {
42026
- event = JSON.parse(data);
42027
- } catch {
42028
- throw new AiParseError("AI provider returned malformed stream data");
42029
- }
42030
- const text = provider === "anthropic" ? event.type === "content_block_delta" ? event.delta?.text : void 0 : event.choices?.[0]?.delta?.content;
42031
- if (text !== void 0 && text !== null && typeof text !== "string") throw new AiParseError("AI provider returned malformed stream data");
42032
- return { completed: false, text };
42033
- }
42034
- static async *streamData(response) {
42035
- let buffer = "";
42036
- for await (const chunk of response) {
42037
- buffer += Buffer.from(chunk).toString("utf8");
42038
- let newline;
42039
- while ((newline = buffer.indexOf("\n")) >= 0) {
42040
- const line = buffer.slice(0, newline).trim();
42041
- buffer = buffer.slice(newline + 1);
42042
- if (line.startsWith("data:")) yield line.slice(5).trim();
42043
- }
42044
- }
42045
- }
42046
- static streamError(error) {
42047
- if (error instanceof AiError) return error;
42048
- if (error instanceof Error && error.name === "AbortError") return new AiTimeoutError("AI total request timeout expired");
42049
- return new AiHTTPError(`AI transport failed (${error instanceof Error ? error.name : "Error"})`);
42050
- }
42315
+ /**
42316
+ * Stream the response through the shared {@link parseSseStream} framer
42317
+ * (ADR-0060 rule 5). Translates each SSE data payload into 0..N
42318
+ * {@link AiEvent}s: text_delta per chunk, tool_call aggregated per
42319
+ * index / block, exactly one done (or error) at the end.
42320
+ */
42051
42321
  static async *streamRequest(config, headers, body) {
42052
42322
  const deadline = performance.now() + config.totalTimeout * 1e3;
42053
42323
  let yielded = false;
@@ -42066,27 +42336,239 @@ var init_aiClient = __esm({
42066
42336
  }
42067
42337
  throw new AiHTTPError(`AI provider returned HTTP ${status2}`, status2);
42068
42338
  }
42069
- let completed = false;
42070
- for await (const data of this.streamData(opened.response)) {
42071
- const delta = this.streamDelta(config.provider, data);
42072
- if (delta.completed) {
42073
- completed = true;
42074
- break;
42339
+ const response = opened.response;
42340
+ const chunks = this.responseChunks(response);
42341
+ const events = parseSseStream(parseLineStream(chunks));
42342
+ const aggregator = new AggregateState(config.provider);
42343
+ let done = false;
42344
+ try {
42345
+ for await (const sseEvent of events) {
42346
+ for (const emitted of aggregator.consume(sseEvent)) {
42347
+ yielded = true;
42348
+ yield emitted;
42349
+ if (emitted.type === "done" || emitted.type === "error") {
42350
+ done = true;
42351
+ break;
42352
+ }
42353
+ }
42354
+ if (done) break;
42355
+ }
42356
+ } catch (error) {
42357
+ if (yielded) {
42358
+ yielded = true;
42359
+ yield { type: "error", message: error instanceof AiParseError ? "AI provider returned malformed stream data" : `AI transport failed (${error instanceof Error ? error.name : "Error"})` };
42360
+ opened.cleanup();
42361
+ opened = null;
42362
+ return;
42075
42363
  }
42076
- if (delta.text === void 0) continue;
42077
- yielded = true;
42078
- yield delta.text;
42364
+ throw error;
42079
42365
  }
42080
42366
  opened.cleanup();
42081
42367
  opened = null;
42082
- if (completed) return;
42083
- throw new AiParseError("AI provider stream ended before [DONE]");
42368
+ if (done) return;
42369
+ if (yielded) {
42370
+ yield { type: "error", message: "AI provider stream ended before completion" };
42371
+ return;
42372
+ }
42373
+ throw new AiParseError("AI provider stream ended before completion");
42084
42374
  } catch (error) {
42085
42375
  opened?.cleanup();
42086
42376
  const failure = this.streamError(error);
42087
- if (failure instanceof AiParseError || failure instanceof AiHTTPError && failure.status !== null || yielded || attempt >= config.maxRetries) throw failure;
42377
+ if (yielded) {
42378
+ yield { type: "error", message: failure.message };
42379
+ return;
42380
+ }
42381
+ if (failure instanceof AiParseError || failure instanceof AiHTTPError && failure.status !== null || attempt >= config.maxRetries) throw failure;
42382
+ }
42383
+ }
42384
+ }
42385
+ static async *responseChunks(response) {
42386
+ for await (const chunk of response) {
42387
+ yield chunk;
42388
+ }
42389
+ }
42390
+ static streamError(error) {
42391
+ if (error instanceof AiError) return error;
42392
+ if (error instanceof Error && error.name === "AbortError") return new AiTimeoutError("AI total request timeout expired");
42393
+ return new AiHTTPError(`AI transport failed (${error instanceof Error ? error.name : "Error"})`);
42394
+ }
42395
+ };
42396
+ AggregateState = class {
42397
+ constructor(provider) {
42398
+ this.provider = provider;
42399
+ }
42400
+ toolBuffers = /* @__PURE__ */ new Map();
42401
+ lastFinishReason = null;
42402
+ lastUsage = null;
42403
+ doneEmitted = false;
42404
+ *consume(event) {
42405
+ const data = event.data;
42406
+ if (data === "[DONE]") {
42407
+ if (this.doneEmitted) return;
42408
+ yield* this.flushRemainingToolCalls();
42409
+ this.doneEmitted = true;
42410
+ yield {
42411
+ type: "done",
42412
+ finishReason: this.lastFinishReason ?? "stop",
42413
+ ...this.lastUsage ? { usage: this.lastUsage } : {}
42414
+ };
42415
+ return;
42416
+ }
42417
+ let payload;
42418
+ try {
42419
+ payload = JSON.parse(data);
42420
+ } catch {
42421
+ throw new AiParseError("AI provider returned malformed stream data");
42422
+ }
42423
+ if (this.provider === "anthropic") {
42424
+ yield* this.consumeAnthropic(payload);
42425
+ } else {
42426
+ yield* this.consumeOpenAi(payload);
42427
+ }
42428
+ }
42429
+ *consumeOpenAi(payload) {
42430
+ const choices = payload.choices;
42431
+ if (!Array.isArray(choices) || choices.length === 0) return;
42432
+ const choice = choices[0];
42433
+ const delta = choice.delta ?? {};
42434
+ const content = delta.content;
42435
+ if (typeof content === "string" && content.length > 0) {
42436
+ yield { type: "text_delta", text: content };
42437
+ }
42438
+ const toolCalls = delta.tool_calls;
42439
+ if (Array.isArray(toolCalls)) {
42440
+ for (const call of toolCalls) {
42441
+ const index = typeof call.index === "number" ? String(call.index) : String(this.toolBuffers.size);
42442
+ const idFromCall = typeof call.id === "string" ? call.id : "";
42443
+ const fn = call.function ?? {};
42444
+ const nameFromCall = typeof fn.name === "string" ? fn.name : "";
42445
+ const argsFragment = typeof fn.arguments === "string" ? fn.arguments : "";
42446
+ const existing = this.toolBuffers.get(index) ?? { id: "", name: "", args: "" };
42447
+ if (idFromCall) existing.id = idFromCall;
42448
+ if (nameFromCall) existing.name = nameFromCall;
42449
+ existing.args += argsFragment;
42450
+ this.toolBuffers.set(index, existing);
42451
+ if (existing.name && existing.args) {
42452
+ try {
42453
+ const parsed = JSON.parse(existing.args);
42454
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
42455
+ this.toolBuffers.delete(index);
42456
+ yield { type: "tool_call", id: existing.id || `call_${index}`, name: existing.name, args: parsed };
42457
+ }
42458
+ } catch {
42459
+ }
42460
+ }
42461
+ }
42462
+ }
42463
+ if (typeof choice.finish_reason === "string" && choice.finish_reason.length > 0) {
42464
+ this.lastFinishReason = choice.finish_reason;
42465
+ }
42466
+ const usage = payload.usage;
42467
+ if (usage && typeof usage === "object") {
42468
+ const promptTokens = Number(usage.prompt_tokens ?? 0);
42469
+ const completionTokens = Number(usage.completion_tokens ?? 0);
42470
+ const totalTokens = Number(usage.total_tokens ?? promptTokens + completionTokens);
42471
+ if (Number.isFinite(promptTokens) && Number.isFinite(completionTokens)) {
42472
+ this.lastUsage = { promptTokens, completionTokens, totalTokens };
42473
+ }
42474
+ }
42475
+ }
42476
+ *consumeAnthropic(payload) {
42477
+ const type2 = payload.type;
42478
+ if (type2 === "content_block_start") {
42479
+ const block = payload.content_block ?? {};
42480
+ if (block.type === "tool_use") {
42481
+ const index = String(payload.index ?? this.toolBuffers.size);
42482
+ const id = typeof block.id === "string" ? block.id : `call_${index}`;
42483
+ const name = typeof block.name === "string" ? block.name : "";
42484
+ this.toolBuffers.set(index, { id, name, args: "" });
42485
+ }
42486
+ return;
42487
+ }
42488
+ if (type2 === "content_block_delta") {
42489
+ const index = String(payload.index ?? 0);
42490
+ const delta = payload.delta ?? {};
42491
+ if (delta.type === "text_delta" && typeof delta.text === "string" && delta.text.length > 0) {
42492
+ yield { type: "text_delta", text: delta.text };
42493
+ return;
42494
+ }
42495
+ if (delta.type === "input_json_delta" && typeof delta.partial_json === "string") {
42496
+ const existing = this.toolBuffers.get(index);
42497
+ if (existing) existing.args += delta.partial_json;
42498
+ }
42499
+ return;
42500
+ }
42501
+ if (type2 === "content_block_stop") {
42502
+ const index = String(payload.index ?? 0);
42503
+ const existing = this.toolBuffers.get(index);
42504
+ if (existing && existing.name) {
42505
+ this.toolBuffers.delete(index);
42506
+ try {
42507
+ const parsed = existing.args ? JSON.parse(existing.args) : {};
42508
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
42509
+ yield { type: "tool_call", id: existing.id, name: existing.name, args: parsed };
42510
+ return;
42511
+ }
42512
+ throw new Error();
42513
+ } catch {
42514
+ throw new AiParseError("AI provider returned malformed tool-call JSON");
42515
+ }
42516
+ }
42517
+ return;
42518
+ }
42519
+ if (type2 === "message_delta") {
42520
+ const delta = payload.delta ?? {};
42521
+ if (typeof delta.stop_reason === "string" && delta.stop_reason.length > 0) {
42522
+ this.lastFinishReason = delta.stop_reason;
42523
+ }
42524
+ const usage = payload.usage ?? {};
42525
+ if (usage.output_tokens !== void 0 || usage.input_tokens !== void 0) {
42526
+ const promptTokens = Number(usage.input_tokens ?? this.lastUsage?.promptTokens ?? 0);
42527
+ const completionTokens = Number(usage.output_tokens ?? this.lastUsage?.completionTokens ?? 0);
42528
+ this.lastUsage = { promptTokens, completionTokens, totalTokens: promptTokens + completionTokens };
42529
+ }
42530
+ return;
42531
+ }
42532
+ if (type2 === "message_stop") {
42533
+ if (this.doneEmitted) return;
42534
+ this.doneEmitted = true;
42535
+ yield {
42536
+ type: "done",
42537
+ finishReason: this.lastFinishReason ?? "end_turn",
42538
+ ...this.lastUsage ? { usage: this.lastUsage } : {}
42539
+ };
42540
+ return;
42541
+ }
42542
+ if (type2 === "message_start") {
42543
+ const message = payload.message ?? {};
42544
+ const usage = message.usage ?? {};
42545
+ if (usage.input_tokens !== void 0 || usage.output_tokens !== void 0) {
42546
+ const promptTokens = Number(usage.input_tokens ?? 0);
42547
+ const completionTokens = Number(usage.output_tokens ?? 0);
42548
+ this.lastUsage = { promptTokens, completionTokens, totalTokens: promptTokens + completionTokens };
42549
+ }
42550
+ return;
42551
+ }
42552
+ if (type2 === "error") {
42553
+ const err = payload.error ?? {};
42554
+ throw new AiParseError(typeof err.message === "string" ? err.message : "AI provider signalled a stream error");
42555
+ }
42556
+ }
42557
+ *flushRemainingToolCalls() {
42558
+ for (const [index, buffered] of this.toolBuffers) {
42559
+ if (buffered.name && buffered.args) {
42560
+ try {
42561
+ const parsed = JSON.parse(buffered.args);
42562
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
42563
+ yield { type: "tool_call", id: buffered.id || `call_${index}`, name: buffered.name, args: parsed };
42564
+ continue;
42565
+ }
42566
+ } catch {
42567
+ }
42568
+ throw new AiParseError("AI provider returned malformed tool-call JSON");
42088
42569
  }
42089
42570
  }
42571
+ this.toolBuffers.clear();
42090
42572
  }
42091
42573
  };
42092
42574
  }
@@ -43802,6 +44284,7 @@ __export(src_exports3, {
43802
44284
  AiParseError: () => AiParseError,
43803
44285
  AiTimeoutError: () => AiTimeoutError,
43804
44286
  Api: () => Api,
44287
+ ApiStreamError: () => ApiStreamError,
43805
44288
  Auth: () => Auth,
43806
44289
  CANONICAL_SESSION_BACKENDS: () => CANONICAL_SESSION_BACKENDS,
43807
44290
  CLOSE_GOING_AWAY: () => CLOSE_GOING_AWAY,
@@ -44031,7 +44514,9 @@ __export(src_exports3, {
44031
44514
  originAllowed: () => originAllowed,
44032
44515
  parseAmqpUrl: () => parseAmqpUrl,
44033
44516
  parseFrame: () => parseFrame,
44517
+ parseLineStream: () => parseLineStream,
44034
44518
  parseMultipart: () => parseMultipart,
44519
+ parseSseStream: () => parseSseStream,
44035
44520
  parseUpgradeHeaders: () => parseUpgradeHeaders,
44036
44521
  patch: () => patch,
44037
44522
  pidfilePath: () => pidfilePath,