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.
@@ -27611,11 +27611,100 @@ function buildMultipartBody(boundary, fieldName, filename, fileContent, contentT
27611
27611
  parts.push(Buffer.from(delimiter2 + "--" + crlf, "utf-8"));
27612
27612
  return Buffer.concat(parts);
27613
27613
  }
27614
- var RETRY_STATUSES, DOWNLOAD_CHUNK_SIZE, MAX_REDIRECTS, STRIP_ON_CROSS_ORIGIN, MIME_BY_EXT, Api;
27614
+ async function* parseLineStream(chunks) {
27615
+ const decoder = new TextDecoder("utf-8");
27616
+ let buffer = "";
27617
+ for await (const chunk of chunks) {
27618
+ buffer += decoder.decode(chunk, { stream: true });
27619
+ let idx;
27620
+ while ((idx = buffer.indexOf("\n")) >= 0) {
27621
+ let line = buffer.slice(0, idx);
27622
+ buffer = buffer.slice(idx + 1);
27623
+ if (line.endsWith("\r")) {
27624
+ line = line.slice(0, -1);
27625
+ }
27626
+ yield line;
27627
+ }
27628
+ }
27629
+ buffer += decoder.decode();
27630
+ if (buffer.length > 0) {
27631
+ if (buffer.endsWith("\r")) {
27632
+ buffer = buffer.slice(0, -1);
27633
+ }
27634
+ yield buffer;
27635
+ }
27636
+ }
27637
+ async function* parseSseStream(lines) {
27638
+ let dataParts = [];
27639
+ let event;
27640
+ let id;
27641
+ let retry;
27642
+ let has = false;
27643
+ const emit = () => {
27644
+ if (!has) return null;
27645
+ const ev = { data: dataParts.join("\n") };
27646
+ if (event !== void 0) ev.event = event;
27647
+ if (id !== void 0) ev.id = id;
27648
+ if (retry !== void 0) ev.retry = retry;
27649
+ return ev;
27650
+ };
27651
+ const reset2 = () => {
27652
+ dataParts = [];
27653
+ event = void 0;
27654
+ id = void 0;
27655
+ retry = void 0;
27656
+ has = false;
27657
+ };
27658
+ for await (const line of lines) {
27659
+ if (line === "") {
27660
+ const ev = emit();
27661
+ if (ev) yield ev;
27662
+ reset2();
27663
+ continue;
27664
+ }
27665
+ if (line.startsWith(":")) continue;
27666
+ const colon = line.indexOf(":");
27667
+ const field = colon < 0 ? line : line.slice(0, colon);
27668
+ let value = colon < 0 ? "" : line.slice(colon + 1);
27669
+ if (value.startsWith(" ")) value = value.slice(1);
27670
+ switch (field) {
27671
+ case "data":
27672
+ dataParts.push(value);
27673
+ has = true;
27674
+ break;
27675
+ case "event":
27676
+ event = value;
27677
+ has = true;
27678
+ break;
27679
+ case "id":
27680
+ id = value;
27681
+ has = true;
27682
+ break;
27683
+ case "retry": {
27684
+ const parsed = Number(value);
27685
+ if (Number.isFinite(parsed) && parsed >= 0) {
27686
+ retry = parsed;
27687
+ has = true;
27688
+ }
27689
+ break;
27690
+ }
27691
+ }
27692
+ }
27693
+ const trailing = emit();
27694
+ if (trailing) yield trailing;
27695
+ }
27696
+ var ApiStreamError, RETRY_STATUSES, DOWNLOAD_CHUNK_SIZE, MAX_REDIRECTS, STRIP_ON_CROSS_ORIGIN, MIME_BY_EXT, Api;
27615
27697
  var init_api = __esm({
27616
27698
  "../core/src/api.ts"() {
27617
27699
  "use strict";
27618
27700
  init_version();
27701
+ ApiStreamError = class extends Error {
27702
+ constructor(message, status2 = null) {
27703
+ super(message);
27704
+ this.status = status2;
27705
+ this.name = "ApiStreamError";
27706
+ }
27707
+ };
27619
27708
  RETRY_STATUSES = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
27620
27709
  DOWNLOAD_CHUNK_SIZE = 64 * 1024;
27621
27710
  MAX_REDIRECTS = 10;
@@ -27934,7 +28023,130 @@ var init_api = __esm({
27934
28023
  }
27935
28024
  return { http_code: code, headers: respHeaders, error: null, path: destPath };
27936
28025
  }
28026
+ /**
28027
+ * Stream a response body as raw bytes. Yields the chunks the transport
28028
+ * delivers, in order, never buffered whole. Ends cleanly on EOF and
28029
+ * throws on a transport failure or a non-2xx status (body drained
28030
+ * first). No JSON decoding, no line splitting, no framing —
28031
+ * {@link streamLines} and {@link streamSse} build on this primitive.
28032
+ *
28033
+ * Closing the iterator before EOF (a `break` out of a `for await`)
28034
+ * destroys the underlying socket, so a caller who takes only the
28035
+ * first few chunks never leaks the connection.
28036
+ *
28037
+ * `opts.timeout` bounds the whole stream duration (default
28038
+ * `TINA4_API_TIMEOUT` or the client `timeout`); `opts.connectTimeout`
28039
+ * bounds just the connect + headers phase (default
28040
+ * `TINA4_API_CONNECT_TIMEOUT` or 10s).
28041
+ */
28042
+ async *streamBytes(path8, opts = {}) {
28043
+ const url = this.buildUrl(path8);
28044
+ const method = (opts.method ?? "GET").toUpperCase();
28045
+ const contentType = opts.contentType ?? "application/json";
28046
+ const { headers, data } = this.buildRequest(method, contentType, opts.body, opts.headers);
28047
+ const totalSec = this.streamSeconds(opts.timeout, "TINA4_API_TIMEOUT", this.timeout);
28048
+ const connectSec = this.streamSeconds(opts.connectTimeout, "TINA4_API_CONNECT_TIMEOUT", 10);
28049
+ const opened = await this.openStreamRequest(method, url, headers, data, connectSec);
28050
+ const res = opened.res;
28051
+ const status2 = res.statusCode ?? 0;
28052
+ this.storeCookies(res.headers["set-cookie"]);
28053
+ if (status2 < 200 || status2 >= 300) {
28054
+ res.resume();
28055
+ throw new ApiStreamError(`stream failed with HTTP ${status2}`, status2);
28056
+ }
28057
+ let totalTimer = null;
28058
+ if (totalSec > 0) {
28059
+ totalTimer = setTimeout(() => {
28060
+ res.destroy(new ApiStreamError(`stream total timeout after ${totalSec}s`, null));
28061
+ }, totalSec * 1e3);
28062
+ }
28063
+ try {
28064
+ for await (const chunk of res) {
28065
+ yield chunk;
28066
+ }
28067
+ } finally {
28068
+ if (totalTimer) clearTimeout(totalTimer);
28069
+ if (!res.destroyed) res.destroy();
28070
+ }
28071
+ }
28072
+ /**
28073
+ * Stream the response body as UTF-8 lines. Splits on LF or CRLF;
28074
+ * buffers a multibyte codepoint that lands across a chunk boundary;
28075
+ * yields a trailing line without a terminator on EOF. Built on
28076
+ * {@link streamBytes} plus the shared {@link parseLineStream}.
28077
+ */
28078
+ async *streamLines(path8, opts = {}) {
28079
+ yield* parseLineStream(this.streamBytes(path8, opts));
28080
+ }
28081
+ /**
28082
+ * Stream the response as SSE (Server-Sent Events). Yields one
28083
+ * {@link SseEvent} per event boundary (blank line) or on EOF for a
28084
+ * trailing event. `data:[DONE]` is delivered as an ordinary event
28085
+ * with `data === "[DONE]"` and the iterator ends on the next EOF.
28086
+ * Built on {@link streamLines} plus the shared {@link parseSseStream}.
28087
+ */
28088
+ async *streamSse(path8, opts = {}) {
28089
+ yield* parseSseStream(this.streamLines(path8, opts));
28090
+ }
27937
28091
  // ── Internal helpers ──────────────────────────────────────────────
28092
+ /**
28093
+ * Resolve a stream duration from (in order): explicit `opts` field,
28094
+ * the named env var, then the fallback. Zero disables. A non-numeric
28095
+ * or negative env value warns via a fallback rather than throwing —
28096
+ * a bad env var must not brick every streaming call.
28097
+ */
28098
+ streamSeconds(explicit, envName, fallback) {
28099
+ if (explicit !== void 0) {
28100
+ return Number.isFinite(explicit) && explicit >= 0 ? Number(explicit) : fallback;
28101
+ }
28102
+ const raw = process.env[envName];
28103
+ if (raw === void 0) return fallback;
28104
+ const n = Number(raw);
28105
+ return Number.isFinite(n) && n >= 0 ? n : fallback;
28106
+ }
28107
+ /**
28108
+ * Open a streaming HTTP request. Returns the raw
28109
+ * {@link http.IncomingMessage} once headers arrive. Redirects are NOT
28110
+ * followed on streams (a caller who needs a redirect should do a
28111
+ * regular GET first). Connect phase is bounded by `connectSec`;
28112
+ * body-phase timeout is applied by the caller (streamBytes) via
28113
+ * `res.destroy()`.
28114
+ */
28115
+ openStreamRequest(method, url, headers, data, connectSec) {
28116
+ return new Promise((resolve20, reject) => {
28117
+ let parsed;
28118
+ try {
28119
+ parsed = new URL2(url);
28120
+ } catch (err) {
28121
+ reject(err instanceof Error ? err : new Error(String(err)));
28122
+ return;
28123
+ }
28124
+ const isHttps = parsed.protocol === "https:";
28125
+ const protocolModule = isHttps ? https : http;
28126
+ const options = {
28127
+ hostname: parsed.hostname,
28128
+ port: parsed.port || (isHttps ? 443 : 80),
28129
+ path: parsed.pathname + parsed.search,
28130
+ method,
28131
+ headers,
28132
+ timeout: connectSec > 0 ? connectSec * 1e3 : void 0
28133
+ };
28134
+ if (isHttps && this.ignoreSsl) {
28135
+ options.rejectUnauthorized = false;
28136
+ }
28137
+ const req2 = protocolModule.request(options, (res) => {
28138
+ resolve20({ res });
28139
+ });
28140
+ req2.on("timeout", () => {
28141
+ req2.destroy(new ApiStreamError(`stream connect timeout after ${connectSec}s`, null));
28142
+ });
28143
+ req2.on("error", (err) => {
28144
+ reject(err);
28145
+ });
28146
+ if (data) req2.write(data);
28147
+ req2.end();
28148
+ });
28149
+ }
27938
28150
  buildUrl(path8) {
27939
28151
  if (path8.startsWith("http://") || path8.startsWith("https://")) {
27940
28152
  return path8;
@@ -30597,10 +30809,11 @@ export default class User {
30597
30809
  // ../core/src/aiClient.ts
30598
30810
  import http2 from "node:http";
30599
30811
  import https2 from "node:https";
30600
- var AiError, AiConfigError, AiTimeoutError, AiParseError, AiHTTPError, Ai;
30812
+ var AiError, AiConfigError, AiTimeoutError, AiParseError, AiHTTPError, Ai, AggregateState;
30601
30813
  var init_aiClient = __esm({
30602
30814
  "../core/src/aiClient.ts"() {
30603
30815
  "use strict";
30816
+ init_api();
30604
30817
  AiError = class extends Error {
30605
30818
  };
30606
30819
  AiConfigError = class extends AiError {
@@ -30645,10 +30858,51 @@ var init_aiClient = __esm({
30645
30858
  throw new AiParseError("AI provider returned a malformed embedding response");
30646
30859
  }
30647
30860
  }
30861
+ /**
30862
+ * Validate role + content shape. Content may be a string OR a non-empty
30863
+ * list of {type:'text'|'image', ...} parts (ADR-0060). Malformed parts
30864
+ * fail fast with AiConfigError, never reaching the wire.
30865
+ */
30648
30866
  static validateMessages(messages) {
30649
- if (!Array.isArray(messages) || messages.length === 0 || !messages.every((message) => message && ["system", "user", "assistant"].includes(message.role) && typeof message.content === "string")) {
30867
+ if (!Array.isArray(messages) || messages.length === 0) {
30650
30868
  throw new AiConfigError("AI messages must contain supported roles and string content");
30651
30869
  }
30870
+ for (const message of messages) {
30871
+ if (!message || !["system", "user", "assistant"].includes(message.role)) {
30872
+ throw new AiConfigError("AI messages must contain supported roles and string content");
30873
+ }
30874
+ this.validateContent(message.content);
30875
+ }
30876
+ }
30877
+ static validateContent(content) {
30878
+ if (typeof content === "string") return;
30879
+ if (!Array.isArray(content) || content.length === 0) {
30880
+ throw new AiConfigError("AI message content must be a string or a non-empty list of parts");
30881
+ }
30882
+ for (const part of content) {
30883
+ if (!part || typeof part !== "object" || Array.isArray(part)) {
30884
+ throw new AiConfigError("AI content part must be an object with type and text/source");
30885
+ }
30886
+ const record = part;
30887
+ const partType = record.type;
30888
+ if (partType === "text") {
30889
+ if (typeof record.text !== "string") {
30890
+ throw new AiConfigError("AI text content part requires a string 'text' field");
30891
+ }
30892
+ } else if (partType === "image") {
30893
+ if (typeof record.source !== "string" || record.source.length === 0) {
30894
+ throw new AiConfigError("AI image content part requires a non-empty string 'source' field");
30895
+ }
30896
+ if (!record.source.startsWith("data:") && !record.source.startsWith("https://")) {
30897
+ throw new AiConfigError("AI image source must be a data: URI or an https:// URL");
30898
+ }
30899
+ if (record.source.startsWith("data:") && !/^data:[^;,\s]+;base64,[A-Za-z0-9+/=]+$/.test(record.source)) {
30900
+ throw new AiConfigError("AI image data URI must be data:<media_type>;base64,<payload>");
30901
+ }
30902
+ } else {
30903
+ throw new AiConfigError(`AI content part has unknown type '${String(partType)}'`);
30904
+ }
30905
+ }
30652
30906
  }
30653
30907
  static number(name, fallback, minimum) {
30654
30908
  const value = process.env[name] === void 0 ? fallback : Number(process.env[name]);
@@ -30696,18 +30950,57 @@ var init_aiClient = __esm({
30696
30950
  }
30697
30951
  return headers;
30698
30952
  }
30953
+ /**
30954
+ * Build the provider-specific request body from a Tina4-shaped message
30955
+ * list. Multimodal parts are translated per provider (ADR-0060):
30956
+ * - OpenAI/local: {type:'image_url', image_url:{url}}
30957
+ * - Anthropic: {type:'image', source:{type:'base64'|'url', ...}}
30958
+ * String content is preserved verbatim in the OpenAI/local shape and
30959
+ * likewise for Anthropic (both accept a bare string).
30960
+ */
30699
30961
  static chatBody(config, messages, options) {
30700
- const body = { model: config.model, messages, stream: options.stream ?? false };
30962
+ const translate = (list) => list.map((message) => ({ role: message.role, content: this.translateContent(message.content, config.provider) }));
30963
+ const body = { model: config.model, messages: translate(messages), stream: options.stream ?? false };
30701
30964
  if (options.temperature !== void 0) body.temperature = options.temperature;
30702
30965
  if (options.maxTokens !== void 0) body.max_tokens = options.maxTokens;
30703
30966
  if (config.provider === "anthropic") {
30704
- const system = messages.filter((message) => message.role === "system").map((message) => message.content);
30705
- body.messages = messages.filter((message) => message.role !== "system");
30967
+ const systemParts = messages.filter((message) => message.role === "system").map((message) => typeof message.content === "string" ? message.content : this.contentToPlainText(message.content));
30968
+ body.messages = translate(messages.filter((message) => message.role !== "system"));
30706
30969
  body.max_tokens = options.maxTokens ?? 1024;
30707
- if (system.length) body.system = system.join("\n\n");
30970
+ if (systemParts.length) body.system = systemParts.join("\n\n");
30708
30971
  }
30709
30972
  return body;
30710
30973
  }
30974
+ /**
30975
+ * Translate one message content value into the provider's on-wire shape.
30976
+ * A plain string is passed through (both providers accept a string
30977
+ * content). A parts array becomes provider-native content blocks.
30978
+ */
30979
+ static translateContent(content, provider) {
30980
+ if (typeof content === "string") return content;
30981
+ if (provider === "anthropic") {
30982
+ return content.map((part) => {
30983
+ if (part.type === "text") return { type: "text", text: part.text };
30984
+ if (part.source.startsWith("data:")) {
30985
+ const parsed = this.parseDataUri(part.source);
30986
+ return { type: "image", source: { type: "base64", media_type: parsed.mediaType, data: parsed.data } };
30987
+ }
30988
+ return { type: "image", source: { type: "url", url: part.source } };
30989
+ });
30990
+ }
30991
+ return content.map((part) => {
30992
+ if (part.type === "text") return { type: "text", text: part.text };
30993
+ return { type: "image_url", image_url: { url: part.source } };
30994
+ });
30995
+ }
30996
+ static parseDataUri(source) {
30997
+ const match = /^data:([^;,\s]+);base64,([A-Za-z0-9+/=]+)$/.exec(source);
30998
+ if (!match) throw new AiConfigError("AI image data URI must be data:<media_type>;base64,<payload>");
30999
+ return { mediaType: match[1], data: match[2] };
31000
+ }
31001
+ static contentToPlainText(parts) {
31002
+ return parts.filter((part) => part.type === "text").map((part) => part.text).join("\n\n");
31003
+ }
30711
31004
  static open(config, deadline, headers, body) {
30712
31005
  const remainingMs = deadline - performance.now();
30713
31006
  if (remainingMs <= 0) return Promise.reject(new AiTimeoutError("AI total request timeout expired"));
@@ -30807,35 +31100,12 @@ var init_aiClient = __esm({
30807
31100
  static async chatResponse(config, headers, body) {
30808
31101
  return this.normalizeChat(config.provider, await this.requestJson(config, headers, body));
30809
31102
  }
30810
- static streamDelta(provider, data) {
30811
- if (data === "[DONE]") return { completed: true };
30812
- let event;
30813
- try {
30814
- event = JSON.parse(data);
30815
- } catch {
30816
- throw new AiParseError("AI provider returned malformed stream data");
30817
- }
30818
- const text = provider === "anthropic" ? event.type === "content_block_delta" ? event.delta?.text : void 0 : event.choices?.[0]?.delta?.content;
30819
- if (text !== void 0 && text !== null && typeof text !== "string") throw new AiParseError("AI provider returned malformed stream data");
30820
- return { completed: false, text };
30821
- }
30822
- static async *streamData(response) {
30823
- let buffer = "";
30824
- for await (const chunk of response) {
30825
- buffer += Buffer.from(chunk).toString("utf8");
30826
- let newline;
30827
- while ((newline = buffer.indexOf("\n")) >= 0) {
30828
- const line = buffer.slice(0, newline).trim();
30829
- buffer = buffer.slice(newline + 1);
30830
- if (line.startsWith("data:")) yield line.slice(5).trim();
30831
- }
30832
- }
30833
- }
30834
- static streamError(error) {
30835
- if (error instanceof AiError) return error;
30836
- if (error instanceof Error && error.name === "AbortError") return new AiTimeoutError("AI total request timeout expired");
30837
- return new AiHTTPError(`AI transport failed (${error instanceof Error ? error.name : "Error"})`);
30838
- }
31103
+ /**
31104
+ * Stream the response through the shared {@link parseSseStream} framer
31105
+ * (ADR-0060 rule 5). Translates each SSE data payload into 0..N
31106
+ * {@link AiEvent}s: text_delta per chunk, tool_call aggregated per
31107
+ * index / block, exactly one done (or error) at the end.
31108
+ */
30839
31109
  static async *streamRequest(config, headers, body) {
30840
31110
  const deadline = performance.now() + config.totalTimeout * 1e3;
30841
31111
  let yielded = false;
@@ -30854,27 +31124,239 @@ var init_aiClient = __esm({
30854
31124
  }
30855
31125
  throw new AiHTTPError(`AI provider returned HTTP ${status2}`, status2);
30856
31126
  }
30857
- let completed = false;
30858
- for await (const data of this.streamData(opened.response)) {
30859
- const delta = this.streamDelta(config.provider, data);
30860
- if (delta.completed) {
30861
- completed = true;
30862
- break;
31127
+ const response = opened.response;
31128
+ const chunks = this.responseChunks(response);
31129
+ const events = parseSseStream(parseLineStream(chunks));
31130
+ const aggregator = new AggregateState(config.provider);
31131
+ let done = false;
31132
+ try {
31133
+ for await (const sseEvent of events) {
31134
+ for (const emitted of aggregator.consume(sseEvent)) {
31135
+ yielded = true;
31136
+ yield emitted;
31137
+ if (emitted.type === "done" || emitted.type === "error") {
31138
+ done = true;
31139
+ break;
31140
+ }
31141
+ }
31142
+ if (done) break;
31143
+ }
31144
+ } catch (error) {
31145
+ if (yielded) {
31146
+ yielded = true;
31147
+ yield { type: "error", message: error instanceof AiParseError ? "AI provider returned malformed stream data" : `AI transport failed (${error instanceof Error ? error.name : "Error"})` };
31148
+ opened.cleanup();
31149
+ opened = null;
31150
+ return;
30863
31151
  }
30864
- if (delta.text === void 0) continue;
30865
- yielded = true;
30866
- yield delta.text;
31152
+ throw error;
30867
31153
  }
30868
31154
  opened.cleanup();
30869
31155
  opened = null;
30870
- if (completed) return;
30871
- throw new AiParseError("AI provider stream ended before [DONE]");
31156
+ if (done) return;
31157
+ if (yielded) {
31158
+ yield { type: "error", message: "AI provider stream ended before completion" };
31159
+ return;
31160
+ }
31161
+ throw new AiParseError("AI provider stream ended before completion");
30872
31162
  } catch (error) {
30873
31163
  opened?.cleanup();
30874
31164
  const failure = this.streamError(error);
30875
- if (failure instanceof AiParseError || failure instanceof AiHTTPError && failure.status !== null || yielded || attempt >= config.maxRetries) throw failure;
31165
+ if (yielded) {
31166
+ yield { type: "error", message: failure.message };
31167
+ return;
31168
+ }
31169
+ if (failure instanceof AiParseError || failure instanceof AiHTTPError && failure.status !== null || attempt >= config.maxRetries) throw failure;
31170
+ }
31171
+ }
31172
+ }
31173
+ static async *responseChunks(response) {
31174
+ for await (const chunk of response) {
31175
+ yield chunk;
31176
+ }
31177
+ }
31178
+ static streamError(error) {
31179
+ if (error instanceof AiError) return error;
31180
+ if (error instanceof Error && error.name === "AbortError") return new AiTimeoutError("AI total request timeout expired");
31181
+ return new AiHTTPError(`AI transport failed (${error instanceof Error ? error.name : "Error"})`);
31182
+ }
31183
+ };
31184
+ AggregateState = class {
31185
+ constructor(provider) {
31186
+ this.provider = provider;
31187
+ }
31188
+ toolBuffers = /* @__PURE__ */ new Map();
31189
+ lastFinishReason = null;
31190
+ lastUsage = null;
31191
+ doneEmitted = false;
31192
+ *consume(event) {
31193
+ const data = event.data;
31194
+ if (data === "[DONE]") {
31195
+ if (this.doneEmitted) return;
31196
+ yield* this.flushRemainingToolCalls();
31197
+ this.doneEmitted = true;
31198
+ yield {
31199
+ type: "done",
31200
+ finishReason: this.lastFinishReason ?? "stop",
31201
+ ...this.lastUsage ? { usage: this.lastUsage } : {}
31202
+ };
31203
+ return;
31204
+ }
31205
+ let payload;
31206
+ try {
31207
+ payload = JSON.parse(data);
31208
+ } catch {
31209
+ throw new AiParseError("AI provider returned malformed stream data");
31210
+ }
31211
+ if (this.provider === "anthropic") {
31212
+ yield* this.consumeAnthropic(payload);
31213
+ } else {
31214
+ yield* this.consumeOpenAi(payload);
31215
+ }
31216
+ }
31217
+ *consumeOpenAi(payload) {
31218
+ const choices = payload.choices;
31219
+ if (!Array.isArray(choices) || choices.length === 0) return;
31220
+ const choice = choices[0];
31221
+ const delta = choice.delta ?? {};
31222
+ const content = delta.content;
31223
+ if (typeof content === "string" && content.length > 0) {
31224
+ yield { type: "text_delta", text: content };
31225
+ }
31226
+ const toolCalls = delta.tool_calls;
31227
+ if (Array.isArray(toolCalls)) {
31228
+ for (const call of toolCalls) {
31229
+ const index = typeof call.index === "number" ? String(call.index) : String(this.toolBuffers.size);
31230
+ const idFromCall = typeof call.id === "string" ? call.id : "";
31231
+ const fn = call.function ?? {};
31232
+ const nameFromCall = typeof fn.name === "string" ? fn.name : "";
31233
+ const argsFragment = typeof fn.arguments === "string" ? fn.arguments : "";
31234
+ const existing = this.toolBuffers.get(index) ?? { id: "", name: "", args: "" };
31235
+ if (idFromCall) existing.id = idFromCall;
31236
+ if (nameFromCall) existing.name = nameFromCall;
31237
+ existing.args += argsFragment;
31238
+ this.toolBuffers.set(index, existing);
31239
+ if (existing.name && existing.args) {
31240
+ try {
31241
+ const parsed = JSON.parse(existing.args);
31242
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
31243
+ this.toolBuffers.delete(index);
31244
+ yield { type: "tool_call", id: existing.id || `call_${index}`, name: existing.name, args: parsed };
31245
+ }
31246
+ } catch {
31247
+ }
31248
+ }
31249
+ }
31250
+ }
31251
+ if (typeof choice.finish_reason === "string" && choice.finish_reason.length > 0) {
31252
+ this.lastFinishReason = choice.finish_reason;
31253
+ }
31254
+ const usage = payload.usage;
31255
+ if (usage && typeof usage === "object") {
31256
+ const promptTokens = Number(usage.prompt_tokens ?? 0);
31257
+ const completionTokens = Number(usage.completion_tokens ?? 0);
31258
+ const totalTokens = Number(usage.total_tokens ?? promptTokens + completionTokens);
31259
+ if (Number.isFinite(promptTokens) && Number.isFinite(completionTokens)) {
31260
+ this.lastUsage = { promptTokens, completionTokens, totalTokens };
31261
+ }
31262
+ }
31263
+ }
31264
+ *consumeAnthropic(payload) {
31265
+ const type2 = payload.type;
31266
+ if (type2 === "content_block_start") {
31267
+ const block = payload.content_block ?? {};
31268
+ if (block.type === "tool_use") {
31269
+ const index = String(payload.index ?? this.toolBuffers.size);
31270
+ const id = typeof block.id === "string" ? block.id : `call_${index}`;
31271
+ const name = typeof block.name === "string" ? block.name : "";
31272
+ this.toolBuffers.set(index, { id, name, args: "" });
31273
+ }
31274
+ return;
31275
+ }
31276
+ if (type2 === "content_block_delta") {
31277
+ const index = String(payload.index ?? 0);
31278
+ const delta = payload.delta ?? {};
31279
+ if (delta.type === "text_delta" && typeof delta.text === "string" && delta.text.length > 0) {
31280
+ yield { type: "text_delta", text: delta.text };
31281
+ return;
31282
+ }
31283
+ if (delta.type === "input_json_delta" && typeof delta.partial_json === "string") {
31284
+ const existing = this.toolBuffers.get(index);
31285
+ if (existing) existing.args += delta.partial_json;
31286
+ }
31287
+ return;
31288
+ }
31289
+ if (type2 === "content_block_stop") {
31290
+ const index = String(payload.index ?? 0);
31291
+ const existing = this.toolBuffers.get(index);
31292
+ if (existing && existing.name) {
31293
+ this.toolBuffers.delete(index);
31294
+ try {
31295
+ const parsed = existing.args ? JSON.parse(existing.args) : {};
31296
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
31297
+ yield { type: "tool_call", id: existing.id, name: existing.name, args: parsed };
31298
+ return;
31299
+ }
31300
+ throw new Error();
31301
+ } catch {
31302
+ throw new AiParseError("AI provider returned malformed tool-call JSON");
31303
+ }
31304
+ }
31305
+ return;
31306
+ }
31307
+ if (type2 === "message_delta") {
31308
+ const delta = payload.delta ?? {};
31309
+ if (typeof delta.stop_reason === "string" && delta.stop_reason.length > 0) {
31310
+ this.lastFinishReason = delta.stop_reason;
31311
+ }
31312
+ const usage = payload.usage ?? {};
31313
+ if (usage.output_tokens !== void 0 || usage.input_tokens !== void 0) {
31314
+ const promptTokens = Number(usage.input_tokens ?? this.lastUsage?.promptTokens ?? 0);
31315
+ const completionTokens = Number(usage.output_tokens ?? this.lastUsage?.completionTokens ?? 0);
31316
+ this.lastUsage = { promptTokens, completionTokens, totalTokens: promptTokens + completionTokens };
31317
+ }
31318
+ return;
31319
+ }
31320
+ if (type2 === "message_stop") {
31321
+ if (this.doneEmitted) return;
31322
+ this.doneEmitted = true;
31323
+ yield {
31324
+ type: "done",
31325
+ finishReason: this.lastFinishReason ?? "end_turn",
31326
+ ...this.lastUsage ? { usage: this.lastUsage } : {}
31327
+ };
31328
+ return;
31329
+ }
31330
+ if (type2 === "message_start") {
31331
+ const message = payload.message ?? {};
31332
+ const usage = message.usage ?? {};
31333
+ if (usage.input_tokens !== void 0 || usage.output_tokens !== void 0) {
31334
+ const promptTokens = Number(usage.input_tokens ?? 0);
31335
+ const completionTokens = Number(usage.output_tokens ?? 0);
31336
+ this.lastUsage = { promptTokens, completionTokens, totalTokens: promptTokens + completionTokens };
31337
+ }
31338
+ return;
31339
+ }
31340
+ if (type2 === "error") {
31341
+ const err = payload.error ?? {};
31342
+ throw new AiParseError(typeof err.message === "string" ? err.message : "AI provider signalled a stream error");
31343
+ }
31344
+ }
31345
+ *flushRemainingToolCalls() {
31346
+ for (const [index, buffered] of this.toolBuffers) {
31347
+ if (buffered.name && buffered.args) {
31348
+ try {
31349
+ const parsed = JSON.parse(buffered.args);
31350
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
31351
+ yield { type: "tool_call", id: buffered.id || `call_${index}`, name: buffered.name, args: parsed };
31352
+ continue;
31353
+ }
31354
+ } catch {
31355
+ }
31356
+ throw new AiParseError("AI provider returned malformed tool-call JSON");
30876
31357
  }
30877
31358
  }
31359
+ this.toolBuffers.clear();
30878
31360
  }
30879
31361
  };
30880
31362
  }
@@ -32590,6 +33072,7 @@ __export(src_exports2, {
32590
33072
  AiParseError: () => AiParseError,
32591
33073
  AiTimeoutError: () => AiTimeoutError,
32592
33074
  Api: () => Api,
33075
+ ApiStreamError: () => ApiStreamError,
32593
33076
  Auth: () => Auth,
32594
33077
  CANONICAL_SESSION_BACKENDS: () => CANONICAL_SESSION_BACKENDS,
32595
33078
  CLOSE_GOING_AWAY: () => CLOSE_GOING_AWAY,
@@ -32819,7 +33302,9 @@ __export(src_exports2, {
32819
33302
  originAllowed: () => originAllowed,
32820
33303
  parseAmqpUrl: () => parseAmqpUrl,
32821
33304
  parseFrame: () => parseFrame,
33305
+ parseLineStream: () => parseLineStream,
32822
33306
  parseMultipart: () => parseMultipart,
33307
+ parseSseStream: () => parseSseStream,
32823
33308
  parseUpgradeHeaders: () => parseUpgradeHeaders,
32824
33309
  patch: () => patch,
32825
33310
  pidfilePath: () => pidfilePath,