tina4-nodejs 3.13.112 → 3.13.114

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 {
@@ -41830,6 +42043,8 @@ var init_aiClient = __esm({
41830
42043
  Ai = class {
41831
42044
  static chat(messages, options = {}) {
41832
42045
  this.validateMessages(messages);
42046
+ if (options.tools !== void 0) this.validateTools(options.tools);
42047
+ if (options.toolChoice !== void 0) this.validateToolChoice(options.toolChoice);
41833
42048
  const config = this.config("chat", options);
41834
42049
  const body = this.chatBody(config, messages, options);
41835
42050
  const headers = this.headers(config);
@@ -41857,10 +42072,120 @@ var init_aiClient = __esm({
41857
42072
  throw new AiParseError("AI provider returned a malformed embedding response");
41858
42073
  }
41859
42074
  }
42075
+ /**
42076
+ * Validate role + content shape. Content may be a string OR a non-empty
42077
+ * list of {type:'text'|'image'|'tool_result', ...} parts (ADR-0060 +
42078
+ * ADR-0061). The `tool` role is the OpenAI-style tool-result turn
42079
+ * (ADR-0061). Malformed parts fail fast with AiConfigError, never
42080
+ * reaching the wire.
42081
+ */
41860
42082
  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")) {
42083
+ if (!Array.isArray(messages) || messages.length === 0) {
41862
42084
  throw new AiConfigError("AI messages must contain supported roles and string content");
41863
42085
  }
42086
+ for (const raw of messages) {
42087
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
42088
+ throw new AiConfigError("AI messages must contain supported roles and string content");
42089
+ }
42090
+ const message = raw;
42091
+ const role = message.role;
42092
+ if (role === "tool") {
42093
+ if (typeof message.tool_call_id !== "string" || message.tool_call_id.length === 0) {
42094
+ throw new AiConfigError("AI tool message requires a non-empty string 'tool_call_id'");
42095
+ }
42096
+ if (typeof message.content !== "string") {
42097
+ throw new AiConfigError("AI tool message requires a string 'content'");
42098
+ }
42099
+ continue;
42100
+ }
42101
+ if (role !== "system" && role !== "user" && role !== "assistant") {
42102
+ throw new AiConfigError("AI messages must contain supported roles and string content");
42103
+ }
42104
+ this.validateContent(message.content);
42105
+ }
42106
+ }
42107
+ static validateContent(content) {
42108
+ if (typeof content === "string") return;
42109
+ if (!Array.isArray(content) || content.length === 0) {
42110
+ throw new AiConfigError("AI message content must be a string or a non-empty list of parts");
42111
+ }
42112
+ for (const part of content) {
42113
+ if (!part || typeof part !== "object" || Array.isArray(part)) {
42114
+ throw new AiConfigError("AI content part must be an object with type and text/source");
42115
+ }
42116
+ const record = part;
42117
+ const partType = record.type;
42118
+ if (partType === "text") {
42119
+ if (typeof record.text !== "string") {
42120
+ throw new AiConfigError("AI text content part requires a string 'text' field");
42121
+ }
42122
+ } else if (partType === "image") {
42123
+ if (typeof record.source !== "string" || record.source.length === 0) {
42124
+ throw new AiConfigError("AI image content part requires a non-empty string 'source' field");
42125
+ }
42126
+ if (!record.source.startsWith("data:") && !record.source.startsWith("https://")) {
42127
+ throw new AiConfigError("AI image source must be a data: URI or an https:// URL");
42128
+ }
42129
+ if (record.source.startsWith("data:") && !/^data:[^;,\s]+;base64,[A-Za-z0-9+/=]+$/.test(record.source)) {
42130
+ throw new AiConfigError("AI image data URI must be data:<media_type>;base64,<payload>");
42131
+ }
42132
+ } else if (partType === "tool_result") {
42133
+ if (typeof record.tool_use_id !== "string" || record.tool_use_id.length === 0) {
42134
+ throw new AiConfigError("AI tool_result part requires a non-empty string 'tool_use_id'");
42135
+ }
42136
+ if (typeof record.content !== "string") {
42137
+ throw new AiConfigError("AI tool_result part requires a string 'content'");
42138
+ }
42139
+ } else {
42140
+ throw new AiConfigError(`AI content part has unknown type '${String(partType)}'`);
42141
+ }
42142
+ }
42143
+ }
42144
+ /**
42145
+ * Validate the outbound tool declarations (ADR-0061). Each tool needs a
42146
+ * non-empty `name`, a string `description`, and a JSON-Schema-shaped
42147
+ * `parameters` object. Malformed tools fail fast with AiConfigError,
42148
+ * never reaching the wire.
42149
+ */
42150
+ static validateTools(tools) {
42151
+ if (!Array.isArray(tools) || tools.length === 0) {
42152
+ throw new AiConfigError("AI tools must be a non-empty list of {name, description, parameters}");
42153
+ }
42154
+ for (const tool of tools) {
42155
+ if (!tool || typeof tool !== "object" || Array.isArray(tool)) {
42156
+ throw new AiConfigError("AI tool must be an object with name, description, parameters");
42157
+ }
42158
+ const record = tool;
42159
+ if (typeof record.name !== "string" || record.name.length === 0) {
42160
+ throw new AiConfigError("AI tool requires a non-empty string 'name'");
42161
+ }
42162
+ if (typeof record.description !== "string") {
42163
+ throw new AiConfigError("AI tool requires a string 'description'");
42164
+ }
42165
+ if (!record.parameters || typeof record.parameters !== "object" || Array.isArray(record.parameters)) {
42166
+ throw new AiConfigError("AI tool requires a JSON-Schema object 'parameters'");
42167
+ }
42168
+ }
42169
+ }
42170
+ /**
42171
+ * Validate the outbound tool_choice value (ADR-0061). The four accepted
42172
+ * shapes are 'auto', 'none', 'required', and {name: 'x'}.
42173
+ */
42174
+ static validateToolChoice(choice) {
42175
+ if (typeof choice === "string") {
42176
+ if (choice !== "auto" && choice !== "none" && choice !== "required") {
42177
+ throw new AiConfigError("AI toolChoice string must be 'auto', 'none', or 'required'");
42178
+ }
42179
+ return;
42180
+ }
42181
+ if (choice && typeof choice === "object" && !Array.isArray(choice)) {
42182
+ const record = choice;
42183
+ if (typeof record.name !== "string" || record.name.length === 0) {
42184
+ throw new AiConfigError("AI toolChoice object requires a non-empty string 'name'");
42185
+ }
42186
+ return;
42187
+ }
42188
+ throw new AiConfigError("AI toolChoice must be 'auto'|'none'|'required' or {name: string}");
41864
42189
  }
41865
42190
  static number(name, fallback, minimum) {
41866
42191
  const value = process.env[name] === void 0 ? fallback : Number(process.env[name]);
@@ -41908,18 +42233,136 @@ var init_aiClient = __esm({
41908
42233
  }
41909
42234
  return headers;
41910
42235
  }
42236
+ /**
42237
+ * Build the provider-specific request body from a Tina4-shaped message
42238
+ * list plus optional tool declarations (ADR-0060 + ADR-0061).
42239
+ *
42240
+ * Content parts translate per provider:
42241
+ * - OpenAI/local: image → {type:'image_url', image_url:{url}}
42242
+ * - Anthropic: image → {type:'image', source:{type:'base64'|'url', ...}}
42243
+ * String content is preserved verbatim in the OpenAI/local shape and
42244
+ * likewise for Anthropic (both accept a bare string).
42245
+ *
42246
+ * Tool-result turns are normalised to the current provider's expected
42247
+ * shape (either the OpenAI `{role:"tool", tool_call_id, content}` turn or
42248
+ * the Anthropic `{role:"user", content:[{type:"tool_result", ...}]}`
42249
+ * turn), so an agent-loop written against Tina4 never has to fork on
42250
+ * TINA4_AI_PROVIDER (ADR-0061 wire translation).
42251
+ */
41911
42252
  static chatBody(config, messages, options) {
41912
- const body = { model: config.model, messages, stream: options.stream ?? false };
42253
+ const normalized = this.normalizeMessagesForProvider(messages, config.provider);
42254
+ const body = { model: config.model, messages: normalized, stream: options.stream ?? false };
41913
42255
  if (options.temperature !== void 0) body.temperature = options.temperature;
41914
42256
  if (options.maxTokens !== void 0) body.max_tokens = options.maxTokens;
41915
42257
  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");
42258
+ const systemParts = [];
42259
+ for (const message of messages) {
42260
+ if (message.role !== "system") continue;
42261
+ const content = message.content;
42262
+ systemParts.push(typeof content === "string" ? content : this.contentToPlainText(content));
42263
+ }
42264
+ body.messages = normalized.filter((message) => message.role !== "system");
41918
42265
  body.max_tokens = options.maxTokens ?? 1024;
41919
- if (system.length) body.system = system.join("\n\n");
42266
+ if (systemParts.length) body.system = systemParts.join("\n\n");
41920
42267
  }
42268
+ this.applyTools(body, config.provider, options);
41921
42269
  return body;
41922
42270
  }
42271
+ /**
42272
+ * Normalise the Tina4-shaped messages into the provider's on-wire shape.
42273
+ * The `tool` role and the `tool_result` content part are translated
42274
+ * between the OpenAI and Anthropic forms so either input works against
42275
+ * either provider (ADR-0061 return-path table).
42276
+ */
42277
+ static normalizeMessagesForProvider(messages, provider) {
42278
+ const out = [];
42279
+ for (const message of messages) {
42280
+ if (message.role === "tool") {
42281
+ if (provider === "anthropic") {
42282
+ out.push({
42283
+ role: "user",
42284
+ content: [{ type: "tool_result", tool_use_id: message.tool_call_id, content: message.content }]
42285
+ });
42286
+ } else {
42287
+ out.push({ role: "tool", tool_call_id: message.tool_call_id, content: message.content });
42288
+ }
42289
+ continue;
42290
+ }
42291
+ if (Array.isArray(message.content) && message.content.some((part) => part.type === "tool_result")) {
42292
+ if (provider === "anthropic") {
42293
+ out.push({ role: message.role, content: this.translateContent(message.content, provider) });
42294
+ } else {
42295
+ for (const part of message.content) {
42296
+ if (part.type === "tool_result") {
42297
+ out.push({ role: "tool", tool_call_id: part.tool_use_id, content: part.content });
42298
+ }
42299
+ }
42300
+ }
42301
+ continue;
42302
+ }
42303
+ out.push({ role: message.role, content: this.translateContent(message.content, provider) });
42304
+ }
42305
+ return out;
42306
+ }
42307
+ /**
42308
+ * Attach the outbound `tools` and `tool_choice` (ADR-0061 outbound
42309
+ * translation tables) to the body in place. When toolChoice is 'none'
42310
+ * on Anthropic (Anthropic has no "none" mode) the tools list is omitted
42311
+ * entirely — the model cannot call what it cannot see.
42312
+ */
42313
+ static applyTools(body, provider, options) {
42314
+ const choice = options.toolChoice;
42315
+ const suppressToolsForAnthropic = provider === "anthropic" && choice === "none";
42316
+ if (options.tools !== void 0 && !suppressToolsForAnthropic) {
42317
+ body.tools = options.tools.map(
42318
+ (tool) => provider === "anthropic" ? { name: tool.name, description: tool.description, input_schema: tool.parameters } : { type: "function", function: { name: tool.name, description: tool.description, parameters: tool.parameters } }
42319
+ );
42320
+ }
42321
+ if (choice === void 0) return;
42322
+ if (provider === "anthropic") {
42323
+ if (choice === "none") return;
42324
+ if (choice === "auto") body.tool_choice = { type: "auto" };
42325
+ else if (choice === "required") body.tool_choice = { type: "any" };
42326
+ else body.tool_choice = { type: "tool", name: choice.name };
42327
+ } else {
42328
+ if (typeof choice === "string") body.tool_choice = choice;
42329
+ else body.tool_choice = { type: "function", function: { name: choice.name } };
42330
+ }
42331
+ }
42332
+ /**
42333
+ * Translate one message content value into the provider's on-wire shape.
42334
+ * A plain string is passed through (both providers accept a string
42335
+ * content). A parts array becomes provider-native content blocks.
42336
+ */
42337
+ static translateContent(content, provider) {
42338
+ if (typeof content === "string") return content;
42339
+ if (provider === "anthropic") {
42340
+ return content.map((part) => {
42341
+ if (part.type === "text") return { type: "text", text: part.text };
42342
+ if (part.type === "tool_result") return { type: "tool_result", tool_use_id: part.tool_use_id, content: part.content };
42343
+ if (part.source.startsWith("data:")) {
42344
+ const parsed = this.parseDataUri(part.source);
42345
+ return { type: "image", source: { type: "base64", media_type: parsed.mediaType, data: parsed.data } };
42346
+ }
42347
+ return { type: "image", source: { type: "url", url: part.source } };
42348
+ });
42349
+ }
42350
+ return content.map((part) => {
42351
+ if (part.type === "text") return { type: "text", text: part.text };
42352
+ if (part.type === "tool_result") {
42353
+ return { type: "text", text: part.content };
42354
+ }
42355
+ return { type: "image_url", image_url: { url: part.source } };
42356
+ });
42357
+ }
42358
+ static parseDataUri(source) {
42359
+ const match = /^data:([^;,\s]+);base64,([A-Za-z0-9+/=]+)$/.exec(source);
42360
+ if (!match) throw new AiConfigError("AI image data URI must be data:<media_type>;base64,<payload>");
42361
+ return { mediaType: match[1], data: match[2] };
42362
+ }
42363
+ static contentToPlainText(parts) {
42364
+ return parts.filter((part) => part.type === "text").map((part) => part.text).join("\n\n");
42365
+ }
41923
42366
  static open(config, deadline, headers, body) {
41924
42367
  const remainingMs = deadline - performance.now();
41925
42368
  if (remainingMs <= 0) return Promise.reject(new AiTimeoutError("AI total request timeout expired"));
@@ -42019,35 +42462,12 @@ var init_aiClient = __esm({
42019
42462
  static async chatResponse(config, headers, body) {
42020
42463
  return this.normalizeChat(config.provider, await this.requestJson(config, headers, body));
42021
42464
  }
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
- }
42465
+ /**
42466
+ * Stream the response through the shared {@link parseSseStream} framer
42467
+ * (ADR-0060 rule 5). Translates each SSE data payload into 0..N
42468
+ * {@link AiEvent}s: text_delta per chunk, tool_call aggregated per
42469
+ * index / block, exactly one done (or error) at the end.
42470
+ */
42051
42471
  static async *streamRequest(config, headers, body) {
42052
42472
  const deadline = performance.now() + config.totalTimeout * 1e3;
42053
42473
  let yielded = false;
@@ -42066,27 +42486,239 @@ var init_aiClient = __esm({
42066
42486
  }
42067
42487
  throw new AiHTTPError(`AI provider returned HTTP ${status2}`, status2);
42068
42488
  }
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;
42489
+ const response = opened.response;
42490
+ const chunks = this.responseChunks(response);
42491
+ const events = parseSseStream(parseLineStream(chunks));
42492
+ const aggregator = new AggregateState(config.provider);
42493
+ let done = false;
42494
+ try {
42495
+ for await (const sseEvent of events) {
42496
+ for (const emitted of aggregator.consume(sseEvent)) {
42497
+ yielded = true;
42498
+ yield emitted;
42499
+ if (emitted.type === "done" || emitted.type === "error") {
42500
+ done = true;
42501
+ break;
42502
+ }
42503
+ }
42504
+ if (done) break;
42505
+ }
42506
+ } catch (error) {
42507
+ if (yielded) {
42508
+ yielded = true;
42509
+ yield { type: "error", message: error instanceof AiParseError ? "AI provider returned malformed stream data" : `AI transport failed (${error instanceof Error ? error.name : "Error"})` };
42510
+ opened.cleanup();
42511
+ opened = null;
42512
+ return;
42075
42513
  }
42076
- if (delta.text === void 0) continue;
42077
- yielded = true;
42078
- yield delta.text;
42514
+ throw error;
42079
42515
  }
42080
42516
  opened.cleanup();
42081
42517
  opened = null;
42082
- if (completed) return;
42083
- throw new AiParseError("AI provider stream ended before [DONE]");
42518
+ if (done) return;
42519
+ if (yielded) {
42520
+ yield { type: "error", message: "AI provider stream ended before completion" };
42521
+ return;
42522
+ }
42523
+ throw new AiParseError("AI provider stream ended before completion");
42084
42524
  } catch (error) {
42085
42525
  opened?.cleanup();
42086
42526
  const failure = this.streamError(error);
42087
- if (failure instanceof AiParseError || failure instanceof AiHTTPError && failure.status !== null || yielded || attempt >= config.maxRetries) throw failure;
42527
+ if (yielded) {
42528
+ yield { type: "error", message: failure.message };
42529
+ return;
42530
+ }
42531
+ if (failure instanceof AiParseError || failure instanceof AiHTTPError && failure.status !== null || attempt >= config.maxRetries) throw failure;
42532
+ }
42533
+ }
42534
+ }
42535
+ static async *responseChunks(response) {
42536
+ for await (const chunk of response) {
42537
+ yield chunk;
42538
+ }
42539
+ }
42540
+ static streamError(error) {
42541
+ if (error instanceof AiError) return error;
42542
+ if (error instanceof Error && error.name === "AbortError") return new AiTimeoutError("AI total request timeout expired");
42543
+ return new AiHTTPError(`AI transport failed (${error instanceof Error ? error.name : "Error"})`);
42544
+ }
42545
+ };
42546
+ AggregateState = class {
42547
+ constructor(provider) {
42548
+ this.provider = provider;
42549
+ }
42550
+ toolBuffers = /* @__PURE__ */ new Map();
42551
+ lastFinishReason = null;
42552
+ lastUsage = null;
42553
+ doneEmitted = false;
42554
+ *consume(event) {
42555
+ const data = event.data;
42556
+ if (data === "[DONE]") {
42557
+ if (this.doneEmitted) return;
42558
+ yield* this.flushRemainingToolCalls();
42559
+ this.doneEmitted = true;
42560
+ yield {
42561
+ type: "done",
42562
+ finishReason: this.lastFinishReason ?? "stop",
42563
+ ...this.lastUsage ? { usage: this.lastUsage } : {}
42564
+ };
42565
+ return;
42566
+ }
42567
+ let payload;
42568
+ try {
42569
+ payload = JSON.parse(data);
42570
+ } catch {
42571
+ throw new AiParseError("AI provider returned malformed stream data");
42572
+ }
42573
+ if (this.provider === "anthropic") {
42574
+ yield* this.consumeAnthropic(payload);
42575
+ } else {
42576
+ yield* this.consumeOpenAi(payload);
42577
+ }
42578
+ }
42579
+ *consumeOpenAi(payload) {
42580
+ const choices = payload.choices;
42581
+ if (!Array.isArray(choices) || choices.length === 0) return;
42582
+ const choice = choices[0];
42583
+ const delta = choice.delta ?? {};
42584
+ const content = delta.content;
42585
+ if (typeof content === "string" && content.length > 0) {
42586
+ yield { type: "text_delta", text: content };
42587
+ }
42588
+ const toolCalls = delta.tool_calls;
42589
+ if (Array.isArray(toolCalls)) {
42590
+ for (const call of toolCalls) {
42591
+ const index = typeof call.index === "number" ? String(call.index) : String(this.toolBuffers.size);
42592
+ const idFromCall = typeof call.id === "string" ? call.id : "";
42593
+ const fn = call.function ?? {};
42594
+ const nameFromCall = typeof fn.name === "string" ? fn.name : "";
42595
+ const argsFragment = typeof fn.arguments === "string" ? fn.arguments : "";
42596
+ const existing = this.toolBuffers.get(index) ?? { id: "", name: "", args: "" };
42597
+ if (idFromCall) existing.id = idFromCall;
42598
+ if (nameFromCall) existing.name = nameFromCall;
42599
+ existing.args += argsFragment;
42600
+ this.toolBuffers.set(index, existing);
42601
+ if (existing.name && existing.args) {
42602
+ try {
42603
+ const parsed = JSON.parse(existing.args);
42604
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
42605
+ this.toolBuffers.delete(index);
42606
+ yield { type: "tool_call", id: existing.id || `call_${index}`, name: existing.name, args: parsed };
42607
+ }
42608
+ } catch {
42609
+ }
42610
+ }
42611
+ }
42612
+ }
42613
+ if (typeof choice.finish_reason === "string" && choice.finish_reason.length > 0) {
42614
+ this.lastFinishReason = choice.finish_reason;
42615
+ }
42616
+ const usage = payload.usage;
42617
+ if (usage && typeof usage === "object") {
42618
+ const promptTokens = Number(usage.prompt_tokens ?? 0);
42619
+ const completionTokens = Number(usage.completion_tokens ?? 0);
42620
+ const totalTokens = Number(usage.total_tokens ?? promptTokens + completionTokens);
42621
+ if (Number.isFinite(promptTokens) && Number.isFinite(completionTokens)) {
42622
+ this.lastUsage = { promptTokens, completionTokens, totalTokens };
42623
+ }
42624
+ }
42625
+ }
42626
+ *consumeAnthropic(payload) {
42627
+ const type2 = payload.type;
42628
+ if (type2 === "content_block_start") {
42629
+ const block = payload.content_block ?? {};
42630
+ if (block.type === "tool_use") {
42631
+ const index = String(payload.index ?? this.toolBuffers.size);
42632
+ const id = typeof block.id === "string" ? block.id : `call_${index}`;
42633
+ const name = typeof block.name === "string" ? block.name : "";
42634
+ this.toolBuffers.set(index, { id, name, args: "" });
42635
+ }
42636
+ return;
42637
+ }
42638
+ if (type2 === "content_block_delta") {
42639
+ const index = String(payload.index ?? 0);
42640
+ const delta = payload.delta ?? {};
42641
+ if (delta.type === "text_delta" && typeof delta.text === "string" && delta.text.length > 0) {
42642
+ yield { type: "text_delta", text: delta.text };
42643
+ return;
42644
+ }
42645
+ if (delta.type === "input_json_delta" && typeof delta.partial_json === "string") {
42646
+ const existing = this.toolBuffers.get(index);
42647
+ if (existing) existing.args += delta.partial_json;
42648
+ }
42649
+ return;
42650
+ }
42651
+ if (type2 === "content_block_stop") {
42652
+ const index = String(payload.index ?? 0);
42653
+ const existing = this.toolBuffers.get(index);
42654
+ if (existing && existing.name) {
42655
+ this.toolBuffers.delete(index);
42656
+ try {
42657
+ const parsed = existing.args ? JSON.parse(existing.args) : {};
42658
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
42659
+ yield { type: "tool_call", id: existing.id, name: existing.name, args: parsed };
42660
+ return;
42661
+ }
42662
+ throw new Error();
42663
+ } catch {
42664
+ throw new AiParseError("AI provider returned malformed tool-call JSON");
42665
+ }
42666
+ }
42667
+ return;
42668
+ }
42669
+ if (type2 === "message_delta") {
42670
+ const delta = payload.delta ?? {};
42671
+ if (typeof delta.stop_reason === "string" && delta.stop_reason.length > 0) {
42672
+ this.lastFinishReason = delta.stop_reason;
42673
+ }
42674
+ const usage = payload.usage ?? {};
42675
+ if (usage.output_tokens !== void 0 || usage.input_tokens !== void 0) {
42676
+ const promptTokens = Number(usage.input_tokens ?? this.lastUsage?.promptTokens ?? 0);
42677
+ const completionTokens = Number(usage.output_tokens ?? this.lastUsage?.completionTokens ?? 0);
42678
+ this.lastUsage = { promptTokens, completionTokens, totalTokens: promptTokens + completionTokens };
42679
+ }
42680
+ return;
42681
+ }
42682
+ if (type2 === "message_stop") {
42683
+ if (this.doneEmitted) return;
42684
+ this.doneEmitted = true;
42685
+ yield {
42686
+ type: "done",
42687
+ finishReason: this.lastFinishReason ?? "end_turn",
42688
+ ...this.lastUsage ? { usage: this.lastUsage } : {}
42689
+ };
42690
+ return;
42691
+ }
42692
+ if (type2 === "message_start") {
42693
+ const message = payload.message ?? {};
42694
+ const usage = message.usage ?? {};
42695
+ if (usage.input_tokens !== void 0 || usage.output_tokens !== void 0) {
42696
+ const promptTokens = Number(usage.input_tokens ?? 0);
42697
+ const completionTokens = Number(usage.output_tokens ?? 0);
42698
+ this.lastUsage = { promptTokens, completionTokens, totalTokens: promptTokens + completionTokens };
42699
+ }
42700
+ return;
42701
+ }
42702
+ if (type2 === "error") {
42703
+ const err = payload.error ?? {};
42704
+ throw new AiParseError(typeof err.message === "string" ? err.message : "AI provider signalled a stream error");
42705
+ }
42706
+ }
42707
+ *flushRemainingToolCalls() {
42708
+ for (const [index, buffered] of this.toolBuffers) {
42709
+ if (buffered.name && buffered.args) {
42710
+ try {
42711
+ const parsed = JSON.parse(buffered.args);
42712
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
42713
+ yield { type: "tool_call", id: buffered.id || `call_${index}`, name: buffered.name, args: parsed };
42714
+ continue;
42715
+ }
42716
+ } catch {
42717
+ }
42718
+ throw new AiParseError("AI provider returned malformed tool-call JSON");
42088
42719
  }
42089
42720
  }
42721
+ this.toolBuffers.clear();
42090
42722
  }
42091
42723
  };
42092
42724
  }
@@ -43802,6 +44434,7 @@ __export(src_exports3, {
43802
44434
  AiParseError: () => AiParseError,
43803
44435
  AiTimeoutError: () => AiTimeoutError,
43804
44436
  Api: () => Api,
44437
+ ApiStreamError: () => ApiStreamError,
43805
44438
  Auth: () => Auth,
43806
44439
  CANONICAL_SESSION_BACKENDS: () => CANONICAL_SESSION_BACKENDS,
43807
44440
  CLOSE_GOING_AWAY: () => CLOSE_GOING_AWAY,
@@ -44031,7 +44664,9 @@ __export(src_exports3, {
44031
44664
  originAllowed: () => originAllowed,
44032
44665
  parseAmqpUrl: () => parseAmqpUrl,
44033
44666
  parseFrame: () => parseFrame,
44667
+ parseLineStream: () => parseLineStream,
44034
44668
  parseMultipart: () => parseMultipart,
44669
+ parseSseStream: () => parseSseStream,
44035
44670
  parseUpgradeHeaders: () => parseUpgradeHeaders,
44036
44671
  patch: () => patch,
44037
44672
  pidfilePath: () => pidfilePath,