import { parseJsonEventStream as ce, resolve as U, generateId as me, validateTypes as X, safeParseJSON as G, createIdGenerator as W, asSchema as ve, safeValidateTypes as he } from "../../../../@ai-sdk_provider-utils@3.0.8_zod@4.1.5/node_modules/@ai-sdk/provider-utils/dist/index.js";
import { jsonSchema as bt, zodSchema as Tt } from "../../../../@ai-sdk_provider-utils@3.0.8_zod@4.1.5/node_modules/@ai-sdk/provider-utils/dist/index.js";
import { AISDKError as Z } from "../../../../@ai-sdk_provider@2.0.0/node_modules/@ai-sdk/provider/dist/index.js";
import { JSONParseError as _t, TypeValidationError as xt } from "../../../../@ai-sdk_provider@2.0.0/node_modules/@ai-sdk/provider/dist/index.js";
import { union as N, string as a, instanceof as Y, custom as ge, lazy as Ie, record as K, object as u, literal as i, boolean as S, unknown as b, discriminatedUnion as ye, array as D, strictObject as f, looseObject as F, optional as M, base64 as te, number as B, enum as H, never as O, null as fe } from "../../../../zod@4.1.5/node_modules/zod/v4/classic/schemas.js";
var Ee = Object.defineProperty, be = (s, e) => {
  for (var l in e)
    Ee(s, l, { get: e[l], enumerable: !0 });
}, ae = "AI_NoObjectGeneratedError", se = `vercel.ai.error.${ae}`, Te = Symbol.for(se), re, k = class extends Z {
  constructor({
    message: s = "No object generated.",
    cause: e,
    text: l,
    response: d,
    usage: m,
    finishReason: v
  }) {
    super({ name: ae, message: s, cause: e }), this[re] = !0, this.text = l, this.response = d, this.usage = m, this.finishReason = v;
  }
  static isInstance(s) {
    return Z.hasMarker(s, se);
  }
};
re = Te;
var oe = N([
  a(),
  Y(Uint8Array),
  Y(ArrayBuffer),
  ge(
    // Buffer might not be available in some environments such as CloudFlare:
    (s) => {
      var e, l;
      return (l = (e = globalThis.Buffer) == null ? void 0 : e.isBuffer(s)) != null ? l : !1;
    },
    { message: "Must be a Buffer" }
  )
]), J = Ie(
  () => N([
    fe(),
    a(),
    B(),
    S(),
    K(a(), J),
    D(J)
  ])
), g = K(
  a(),
  K(a(), J)
), ie = u({
  type: i("text"),
  text: a(),
  providerOptions: g.optional()
}), Se = u({
  type: i("image"),
  image: N([oe, Y(URL)]),
  mediaType: a().optional(),
  providerOptions: g.optional()
}), le = u({
  type: i("file"),
  data: N([oe, Y(URL)]),
  filename: a().optional(),
  mediaType: a(),
  providerOptions: g.optional()
}), _e = u({
  type: i("reasoning"),
  text: a(),
  providerOptions: g.optional()
}), xe = u({
  type: i("tool-call"),
  toolCallId: a(),
  toolName: a(),
  input: b(),
  providerOptions: g.optional(),
  providerExecuted: S().optional()
}), Re = ye("type", [
  u({
    type: i("text"),
    value: a()
  }),
  u({
    type: i("json"),
    value: J
  }),
  u({
    type: i("error-text"),
    value: a()
  }),
  u({
    type: i("error-json"),
    value: J
  }),
  u({
    type: i("content"),
    value: D(
      N([
        u({
          type: i("text"),
          text: a()
        }),
        u({
          type: i("media"),
          data: a(),
          mediaType: a()
        })
      ])
    )
  })
]), ne = u({
  type: i("tool-result"),
  toolCallId: a(),
  toolName: a(),
  output: Re,
  providerOptions: g.optional()
}), Ce = u(
  {
    role: i("system"),
    content: a(),
    providerOptions: g.optional()
  }
), Me = u({
  role: i("user"),
  content: N([
    a(),
    D(N([ie, Se, le]))
  ]),
  providerOptions: g.optional()
}), Ne = u({
  role: i("assistant"),
  content: N([
    a(),
    D(
      N([
        ie,
        le,
        _e,
        xe,
        ne
      ])
    )
  ]),
  providerOptions: g.optional()
}), Ae = u({
  role: i("tool"),
  content: D(ne),
  providerOptions: g.optional()
});
N([
  Ce,
  Me,
  Ne,
  Ae
]);
W({
  prefix: "aitxt",
  size: 24
});
(class extends TransformStream {
  constructor() {
    super({
      transform(s, e) {
        e.enqueue(`data: ${JSON.stringify(s)}

`);
      },
      flush(s) {
        s.enqueue(`data: [DONE]

`);
      }
    });
  }
});
var we = N([
  f({
    type: i("text-start"),
    id: a(),
    providerMetadata: g.optional()
  }),
  f({
    type: i("text-delta"),
    id: a(),
    delta: a(),
    providerMetadata: g.optional()
  }),
  f({
    type: i("text-end"),
    id: a(),
    providerMetadata: g.optional()
  }),
  f({
    type: i("error"),
    errorText: a()
  }),
  f({
    type: i("tool-input-start"),
    toolCallId: a(),
    toolName: a(),
    providerExecuted: S().optional(),
    dynamic: S().optional()
  }),
  f({
    type: i("tool-input-delta"),
    toolCallId: a(),
    inputTextDelta: a()
  }),
  f({
    type: i("tool-input-available"),
    toolCallId: a(),
    toolName: a(),
    input: b(),
    providerExecuted: S().optional(),
    providerMetadata: g.optional(),
    dynamic: S().optional()
  }),
  f({
    type: i("tool-input-error"),
    toolCallId: a(),
    toolName: a(),
    input: b(),
    providerExecuted: S().optional(),
    providerMetadata: g.optional(),
    dynamic: S().optional(),
    errorText: a()
  }),
  f({
    type: i("tool-output-available"),
    toolCallId: a(),
    output: b(),
    providerExecuted: S().optional(),
    dynamic: S().optional(),
    preliminary: S().optional()
  }),
  f({
    type: i("tool-output-error"),
    toolCallId: a(),
    errorText: a(),
    providerExecuted: S().optional(),
    dynamic: S().optional()
  }),
  f({
    type: i("reasoning"),
    text: a(),
    providerMetadata: g.optional()
  }),
  f({
    type: i("reasoning-start"),
    id: a(),
    providerMetadata: g.optional()
  }),
  f({
    type: i("reasoning-delta"),
    id: a(),
    delta: a(),
    providerMetadata: g.optional()
  }),
  f({
    type: i("reasoning-end"),
    id: a(),
    providerMetadata: g.optional()
  }),
  f({
    type: i("reasoning-part-finish")
  }),
  f({
    type: i("source-url"),
    sourceId: a(),
    url: a(),
    title: a().optional(),
    providerMetadata: g.optional()
  }),
  f({
    type: i("source-document"),
    sourceId: a(),
    mediaType: a(),
    title: a(),
    filename: a().optional(),
    providerMetadata: g.optional()
  }),
  f({
    type: i("file"),
    url: a(),
    mediaType: a(),
    providerMetadata: g.optional()
  }),
  f({
    type: a().startsWith("data-"),
    id: a().optional(),
    data: b(),
    transient: S().optional()
  }),
  f({
    type: i("start-step")
  }),
  f({
    type: i("finish-step")
  }),
  f({
    type: i("start"),
    messageId: a().optional(),
    messageMetadata: b().optional()
  }),
  f({
    type: i("finish"),
    messageMetadata: b().optional()
  }),
  f({
    type: i("abort")
  }),
  f({
    type: i("message-metadata"),
    messageMetadata: b()
  })
]);
function Pe(s) {
  return s.type.startsWith("data-");
}
function pe(s, e) {
  if (s === void 0 && e === void 0)
    return;
  if (s === void 0)
    return e;
  if (e === void 0)
    return s;
  const l = { ...s };
  for (const d in e)
    if (Object.prototype.hasOwnProperty.call(e, d)) {
      const m = e[d];
      if (m === void 0)
        continue;
      const v = d in s ? s[d] : void 0, y = m !== null && typeof m == "object" && !Array.isArray(m) && !(m instanceof Date) && !(m instanceof RegExp), t = v != null && typeof v == "object" && !Array.isArray(v) && !(v instanceof Date) && !(v instanceof RegExp);
      y && t ? l[d] = pe(
        v,
        m
      ) : l[d] = m;
    }
  return l;
}
function Oe(s) {
  const e = ["ROOT"];
  let l = -1, d = null;
  function m(p, r, n) {
    switch (p) {
      case '"': {
        l = r, e.pop(), e.push(n), e.push("INSIDE_STRING");
        break;
      }
      case "f":
      case "t":
      case "n": {
        l = r, d = r, e.pop(), e.push(n), e.push("INSIDE_LITERAL");
        break;
      }
      case "-": {
        e.pop(), e.push(n), e.push("INSIDE_NUMBER");
        break;
      }
      case "0":
      case "1":
      case "2":
      case "3":
      case "4":
      case "5":
      case "6":
      case "7":
      case "8":
      case "9": {
        l = r, e.pop(), e.push(n), e.push("INSIDE_NUMBER");
        break;
      }
      case "{": {
        l = r, e.pop(), e.push(n), e.push("INSIDE_OBJECT_START");
        break;
      }
      case "[": {
        l = r, e.pop(), e.push(n), e.push("INSIDE_ARRAY_START");
        break;
      }
    }
  }
  function v(p, r) {
    switch (p) {
      case ",": {
        e.pop(), e.push("INSIDE_OBJECT_AFTER_COMMA");
        break;
      }
      case "}": {
        l = r, e.pop();
        break;
      }
    }
  }
  function y(p, r) {
    switch (p) {
      case ",": {
        e.pop(), e.push("INSIDE_ARRAY_AFTER_COMMA");
        break;
      }
      case "]": {
        l = r, e.pop();
        break;
      }
    }
  }
  for (let p = 0; p < s.length; p++) {
    const r = s[p];
    switch (e[e.length - 1]) {
      case "ROOT":
        m(r, p, "FINISH");
        break;
      case "INSIDE_OBJECT_START": {
        switch (r) {
          case '"': {
            e.pop(), e.push("INSIDE_OBJECT_KEY");
            break;
          }
          case "}": {
            l = p, e.pop();
            break;
          }
        }
        break;
      }
      case "INSIDE_OBJECT_AFTER_COMMA": {
        switch (r) {
          case '"': {
            e.pop(), e.push("INSIDE_OBJECT_KEY");
            break;
          }
        }
        break;
      }
      case "INSIDE_OBJECT_KEY": {
        switch (r) {
          case '"': {
            e.pop(), e.push("INSIDE_OBJECT_AFTER_KEY");
            break;
          }
        }
        break;
      }
      case "INSIDE_OBJECT_AFTER_KEY": {
        switch (r) {
          case ":": {
            e.pop(), e.push("INSIDE_OBJECT_BEFORE_VALUE");
            break;
          }
        }
        break;
      }
      case "INSIDE_OBJECT_BEFORE_VALUE": {
        m(r, p, "INSIDE_OBJECT_AFTER_VALUE");
        break;
      }
      case "INSIDE_OBJECT_AFTER_VALUE": {
        v(r, p);
        break;
      }
      case "INSIDE_STRING": {
        switch (r) {
          case '"': {
            e.pop(), l = p;
            break;
          }
          case "\\": {
            e.push("INSIDE_STRING_ESCAPE");
            break;
          }
          default:
            l = p;
        }
        break;
      }
      case "INSIDE_ARRAY_START": {
        switch (r) {
          case "]": {
            l = p, e.pop();
            break;
          }
          default: {
            l = p, m(r, p, "INSIDE_ARRAY_AFTER_VALUE");
            break;
          }
        }
        break;
      }
      case "INSIDE_ARRAY_AFTER_VALUE": {
        switch (r) {
          case ",": {
            e.pop(), e.push("INSIDE_ARRAY_AFTER_COMMA");
            break;
          }
          case "]": {
            l = p, e.pop();
            break;
          }
          default: {
            l = p;
            break;
          }
        }
        break;
      }
      case "INSIDE_ARRAY_AFTER_COMMA": {
        m(r, p, "INSIDE_ARRAY_AFTER_VALUE");
        break;
      }
      case "INSIDE_STRING_ESCAPE": {
        e.pop(), l = p;
        break;
      }
      case "INSIDE_NUMBER": {
        switch (r) {
          case "0":
          case "1":
          case "2":
          case "3":
          case "4":
          case "5":
          case "6":
          case "7":
          case "8":
          case "9": {
            l = p;
            break;
          }
          case "e":
          case "E":
          case "-":
          case ".":
            break;
          case ",": {
            e.pop(), e[e.length - 1] === "INSIDE_ARRAY_AFTER_VALUE" && y(r, p), e[e.length - 1] === "INSIDE_OBJECT_AFTER_VALUE" && v(r, p);
            break;
          }
          case "}": {
            e.pop(), e[e.length - 1] === "INSIDE_OBJECT_AFTER_VALUE" && v(r, p);
            break;
          }
          case "]": {
            e.pop(), e[e.length - 1] === "INSIDE_ARRAY_AFTER_VALUE" && y(r, p);
            break;
          }
          default: {
            e.pop();
            break;
          }
        }
        break;
      }
      case "INSIDE_LITERAL": {
        const c = s.substring(d, p + 1);
        !"false".startsWith(c) && !"true".startsWith(c) && !"null".startsWith(c) ? (e.pop(), e[e.length - 1] === "INSIDE_OBJECT_AFTER_VALUE" ? v(r, p) : e[e.length - 1] === "INSIDE_ARRAY_AFTER_VALUE" && y(r, p)) : l = p;
        break;
      }
    }
  }
  let t = s.slice(0, l + 1);
  for (let p = e.length - 1; p >= 0; p--)
    switch (e[p]) {
      case "INSIDE_STRING": {
        t += '"';
        break;
      }
      case "INSIDE_OBJECT_KEY":
      case "INSIDE_OBJECT_AFTER_KEY":
      case "INSIDE_OBJECT_AFTER_COMMA":
      case "INSIDE_OBJECT_START":
      case "INSIDE_OBJECT_BEFORE_VALUE":
      case "INSIDE_OBJECT_AFTER_VALUE": {
        t += "}";
        break;
      }
      case "INSIDE_ARRAY_START":
      case "INSIDE_ARRAY_AFTER_COMMA":
      case "INSIDE_ARRAY_AFTER_VALUE": {
        t += "]";
        break;
      }
      case "INSIDE_LITERAL": {
        const n = s.substring(d, s.length);
        "true".startsWith(n) ? t += "true".slice(n.length) : "false".startsWith(n) ? t += "false".slice(n.length) : "null".startsWith(n) && (t += "null".slice(n.length));
      }
    }
  return t;
}
async function de(s) {
  if (s === void 0)
    return { value: void 0, state: "undefined-input" };
  let e = await G({ text: s });
  return e.success ? { value: e.value, state: "successful-parse" } : (e = await G({ text: Oe(s) }), e.success ? { value: e.value, state: "repaired-parse" } : { value: void 0, state: "failed-parse" });
}
function q(s) {
  return s.type.startsWith("tool-");
}
function De(s) {
  return s.type === "dynamic-tool";
}
function z(s) {
  return q(s) || De(s);
}
function ee(s) {
  return s.type.split("-").slice(1).join("-");
}
function Ue({
  lastMessage: s,
  messageId: e
}) {
  return {
    message: s?.role === "assistant" ? s : {
      id: e,
      metadata: void 0,
      role: "assistant",
      parts: []
    },
    activeTextParts: {},
    activeReasoningParts: {},
    partialToolCalls: {}
  };
}
function Fe({
  stream: s,
  messageMetadataSchema: e,
  dataPartSchemas: l,
  runUpdateMessageJob: d,
  onError: m,
  onToolCall: v,
  onData: y
}) {
  return s.pipeThrough(
    new TransformStream({
      async transform(t, p) {
        await d(async ({ state: r, write: n }) => {
          var c, I, _, x;
          function R(o) {
            const T = r.message.parts.filter(q).find(
              (h) => h.toolCallId === o
            );
            if (T == null)
              throw new Error(
                "tool-output-error must be preceded by a tool-input-available"
              );
            return T;
          }
          function A(o) {
            const T = r.message.parts.filter(
              (h) => h.type === "dynamic-tool"
            ).find(
              (h) => h.toolCallId === o
            );
            if (T == null)
              throw new Error(
                "tool-output-error must be preceded by a tool-input-available"
              );
            return T;
          }
          function C(o) {
            var w;
            const T = r.message.parts.find(
              (j) => q(j) && j.toolCallId === o.toolCallId
            ), h = o, P = T;
            T != null ? (T.state = o.state, P.input = h.input, P.output = h.output, P.errorText = h.errorText, P.rawInput = h.rawInput, P.preliminary = h.preliminary, P.providerExecuted = (w = h.providerExecuted) != null ? w : T.providerExecuted, h.providerMetadata != null && T.state === "input-available" && (T.callProviderMetadata = h.providerMetadata)) : r.message.parts.push({
              type: `tool-${o.toolName}`,
              toolCallId: o.toolCallId,
              state: o.state,
              input: h.input,
              output: h.output,
              rawInput: h.rawInput,
              errorText: h.errorText,
              providerExecuted: h.providerExecuted,
              preliminary: h.preliminary,
              ...h.providerMetadata != null ? { callProviderMetadata: h.providerMetadata } : {}
            });
          }
          function E(o) {
            var w;
            const T = r.message.parts.find(
              (j) => j.type === "dynamic-tool" && j.toolCallId === o.toolCallId
            ), h = o, P = T;
            T != null ? (T.state = o.state, P.toolName = o.toolName, P.input = h.input, P.output = h.output, P.errorText = h.errorText, P.rawInput = (w = h.rawInput) != null ? w : P.rawInput, P.preliminary = h.preliminary, h.providerMetadata != null && T.state === "input-available" && (T.callProviderMetadata = h.providerMetadata)) : r.message.parts.push({
              type: "dynamic-tool",
              toolName: o.toolName,
              toolCallId: o.toolCallId,
              state: o.state,
              input: h.input,
              output: h.output,
              errorText: h.errorText,
              preliminary: h.preliminary,
              ...h.providerMetadata != null ? { callProviderMetadata: h.providerMetadata } : {}
            });
          }
          async function L(o) {
            if (o != null) {
              const w = r.message.metadata != null ? pe(r.message.metadata, o) : o;
              e != null && await X({
                value: w,
                schema: e
              }), r.message.metadata = w;
            }
          }
          switch (t.type) {
            case "text-start": {
              const o = {
                type: "text",
                text: "",
                providerMetadata: t.providerMetadata,
                state: "streaming"
              };
              r.activeTextParts[t.id] = o, r.message.parts.push(o), n();
              break;
            }
            case "text-delta": {
              const o = r.activeTextParts[t.id];
              o.text += t.delta, o.providerMetadata = (c = t.providerMetadata) != null ? c : o.providerMetadata, n();
              break;
            }
            case "text-end": {
              const o = r.activeTextParts[t.id];
              o.state = "done", o.providerMetadata = (I = t.providerMetadata) != null ? I : o.providerMetadata, delete r.activeTextParts[t.id], n();
              break;
            }
            case "reasoning-start": {
              const o = {
                type: "reasoning",
                text: "",
                providerMetadata: t.providerMetadata,
                state: "streaming"
              };
              r.activeReasoningParts[t.id] = o, r.message.parts.push(o), n();
              break;
            }
            case "reasoning-delta": {
              const o = r.activeReasoningParts[t.id];
              o.text += t.delta, o.providerMetadata = (_ = t.providerMetadata) != null ? _ : o.providerMetadata, n();
              break;
            }
            case "reasoning-end": {
              const o = r.activeReasoningParts[t.id];
              o.providerMetadata = (x = t.providerMetadata) != null ? x : o.providerMetadata, o.state = "done", delete r.activeReasoningParts[t.id], n();
              break;
            }
            case "file": {
              r.message.parts.push({
                type: "file",
                mediaType: t.mediaType,
                url: t.url
              }), n();
              break;
            }
            case "source-url": {
              r.message.parts.push({
                type: "source-url",
                sourceId: t.sourceId,
                url: t.url,
                title: t.title,
                providerMetadata: t.providerMetadata
              }), n();
              break;
            }
            case "source-document": {
              r.message.parts.push({
                type: "source-document",
                sourceId: t.sourceId,
                mediaType: t.mediaType,
                title: t.title,
                filename: t.filename,
                providerMetadata: t.providerMetadata
              }), n();
              break;
            }
            case "tool-input-start": {
              const o = r.message.parts.filter(q);
              r.partialToolCalls[t.toolCallId] = {
                text: "",
                toolName: t.toolName,
                index: o.length,
                dynamic: t.dynamic
              }, t.dynamic ? E({
                toolCallId: t.toolCallId,
                toolName: t.toolName,
                state: "input-streaming",
                input: void 0
              }) : C({
                toolCallId: t.toolCallId,
                toolName: t.toolName,
                state: "input-streaming",
                input: void 0,
                providerExecuted: t.providerExecuted
              }), n();
              break;
            }
            case "tool-input-delta": {
              const o = r.partialToolCalls[t.toolCallId];
              o.text += t.inputTextDelta;
              const { value: w } = await de(
                o.text
              );
              o.dynamic ? E({
                toolCallId: t.toolCallId,
                toolName: o.toolName,
                state: "input-streaming",
                input: w
              }) : C({
                toolCallId: t.toolCallId,
                toolName: o.toolName,
                state: "input-streaming",
                input: w
              }), n();
              break;
            }
            case "tool-input-available": {
              t.dynamic ? E({
                toolCallId: t.toolCallId,
                toolName: t.toolName,
                state: "input-available",
                input: t.input,
                providerMetadata: t.providerMetadata
              }) : C({
                toolCallId: t.toolCallId,
                toolName: t.toolName,
                state: "input-available",
                input: t.input,
                providerExecuted: t.providerExecuted,
                providerMetadata: t.providerMetadata
              }), n(), v && !t.providerExecuted && await v({
                toolCall: t
              });
              break;
            }
            case "tool-input-error": {
              t.dynamic ? E({
                toolCallId: t.toolCallId,
                toolName: t.toolName,
                state: "output-error",
                input: t.input,
                errorText: t.errorText,
                providerMetadata: t.providerMetadata
              }) : C({
                toolCallId: t.toolCallId,
                toolName: t.toolName,
                state: "output-error",
                input: void 0,
                rawInput: t.input,
                errorText: t.errorText,
                providerExecuted: t.providerExecuted,
                providerMetadata: t.providerMetadata
              }), n();
              break;
            }
            case "tool-output-available": {
              if (t.dynamic) {
                const o = A(
                  t.toolCallId
                );
                E({
                  toolCallId: t.toolCallId,
                  toolName: o.toolName,
                  state: "output-available",
                  input: o.input,
                  output: t.output,
                  preliminary: t.preliminary
                });
              } else {
                const o = R(t.toolCallId);
                C({
                  toolCallId: t.toolCallId,
                  toolName: ee(o),
                  state: "output-available",
                  input: o.input,
                  output: t.output,
                  providerExecuted: t.providerExecuted,
                  preliminary: t.preliminary
                });
              }
              n();
              break;
            }
            case "tool-output-error": {
              if (t.dynamic) {
                const o = A(
                  t.toolCallId
                );
                E({
                  toolCallId: t.toolCallId,
                  toolName: o.toolName,
                  state: "output-error",
                  input: o.input,
                  errorText: t.errorText
                });
              } else {
                const o = R(t.toolCallId);
                C({
                  toolCallId: t.toolCallId,
                  toolName: ee(o),
                  state: "output-error",
                  input: o.input,
                  rawInput: o.rawInput,
                  errorText: t.errorText
                });
              }
              n();
              break;
            }
            case "start-step": {
              r.message.parts.push({ type: "step-start" });
              break;
            }
            case "finish-step": {
              r.activeTextParts = {}, r.activeReasoningParts = {};
              break;
            }
            case "start": {
              t.messageId != null && (r.message.id = t.messageId), await L(t.messageMetadata), (t.messageId != null || t.messageMetadata != null) && n();
              break;
            }
            case "finish": {
              await L(t.messageMetadata), t.messageMetadata != null && n();
              break;
            }
            case "message-metadata": {
              await L(t.messageMetadata), t.messageMetadata != null && n();
              break;
            }
            case "error": {
              m?.(new Error(t.errorText));
              break;
            }
            default:
              if (Pe(t)) {
                l?.[t.type] != null && await X({
                  value: t.data,
                  schema: l[t.type]
                });
                const o = t;
                if (o.transient) {
                  y?.(o);
                  break;
                }
                const w = o.id != null ? r.message.parts.find(
                  (T) => o.type === T.type && o.id === T.id
                ) : void 0;
                w != null ? w.data = o.data : r.message.parts.push(o), y?.(o), n();
              }
          }
          p.enqueue(t);
        });
      }
    })
  );
}
async function Le({
  stream: s,
  onError: e
}) {
  const l = s.getReader();
  try {
    for (; ; ) {
      const { done: d } = await l.read();
      if (d)
        break;
    }
  } catch (d) {
    e?.(d);
  } finally {
    l.releaseLock();
  }
}
W({
  prefix: "aitxt",
  size: 24
});
W({ prefix: "aiobj", size: 24 });
var je = class {
  constructor() {
    this.queue = [], this.isProcessing = !1;
  }
  async processQueue() {
    if (!this.isProcessing) {
      for (this.isProcessing = !0; this.queue.length > 0; )
        await this.queue[0](), this.queue.shift();
      this.isProcessing = !1;
    }
  }
  async run(s) {
    return new Promise((e, l) => {
      this.queue.push(async () => {
        try {
          await s(), e();
        } catch (d) {
          l(d);
        }
      }), this.processQueue();
    });
  }
};
W({ prefix: "aiobj", size: 24 });
var Be = {};
be(Be, {
  object: () => Ve,
  text: () => Je
});
var Je = () => ({
  type: "text",
  responseFormat: { type: "text" },
  async parsePartial({ text: s }) {
    return { partial: s };
  },
  async parseOutput({ text: s }) {
    return s;
  }
}), Ve = ({
  schema: s
}) => {
  const e = ve(s);
  return {
    type: "object",
    responseFormat: {
      type: "json",
      schema: e.jsonSchema
    },
    async parsePartial({ text: l }) {
      const d = await de(l);
      switch (d.state) {
        case "failed-parse":
        case "undefined-input":
          return;
        case "repaired-parse":
        case "successful-parse":
          return {
            // Note: currently no validation of partial results:
            partial: d.value
          };
        default: {
          const m = d.state;
          throw new Error(`Unsupported parse state: ${m}`);
        }
      }
    },
    async parseOutput({ text: l }, d) {
      const m = await G({ text: l });
      if (!m.success)
        throw new k({
          message: "No object generated: could not parse the response.",
          cause: m.error,
          text: l,
          response: d.response,
          usage: d.usage,
          finishReason: d.finishReason
        });
      const v = await he({
        value: m.value,
        schema: e
      });
      if (!v.success)
        throw new k({
          message: "No object generated: response did not match schema.",
          cause: v.error,
          text: l,
          response: d.response,
          usage: d.usage,
          finishReason: d.finishReason
        });
      return v.value;
    }
  };
}, qe = F({
  name: a(),
  version: a()
}), Q = F({
  _meta: M(u({}).loose())
}), V = Q, Ye = u({
  method: a(),
  params: M(Q)
}), We = F({
  experimental: M(u({}).loose()),
  logging: M(u({}).loose()),
  prompts: M(
    F({
      listChanged: M(S())
    })
  ),
  resources: M(
    F({
      subscribe: M(S()),
      listChanged: M(S())
    })
  ),
  tools: M(
    F({
      listChanged: M(S())
    })
  )
});
V.extend({
  protocolVersion: a(),
  capabilities: We,
  serverInfo: qe,
  instructions: M(a())
});
var $e = V.extend({
  nextCursor: M(a())
}), Ge = u({
  name: a(),
  description: M(a()),
  inputSchema: u({
    type: i("object"),
    properties: M(u({}).loose())
  }).loose()
}).loose();
$e.extend({
  tools: D(Ge)
});
var Ke = u({
  type: i("text"),
  text: a()
}).loose(), ze = u({
  type: i("image"),
  data: te(),
  mimeType: a()
}).loose(), ue = u({
  /**
   * The URI of this resource.
   */
  uri: a(),
  /**
   * The MIME type of this resource, if known.
   */
  mimeType: M(a())
}).loose(), He = ue.extend({
  text: a()
}), Qe = ue.extend({
  blob: te()
}), Xe = u({
  type: i("resource"),
  resource: N([He, Qe])
}).loose();
V.extend({
  content: D(
    N([Ke, ze, Xe])
  ),
  isError: S().default(!1).optional()
}).or(
  V.extend({
    toolResult: b()
  })
);
var $ = "2.0", Ze = u({
  jsonrpc: i($),
  id: N([a(), B().int()])
}).merge(Ye).strict(), ke = u({
  jsonrpc: i($),
  id: N([a(), B().int()]),
  result: V
}).strict(), et = u({
  jsonrpc: i($),
  id: N([a(), B().int()]),
  error: u({
    code: B().int(),
    message: a(),
    data: M(b())
  })
}).strict(), tt = u({
  jsonrpc: i($)
}).merge(
  u({
    method: a(),
    params: M(Q)
  })
).strict();
N([
  Ze,
  tt,
  ke,
  et
]);
async function at(s) {
  if (s == null)
    return [];
  if (!globalThis.FileList || !(s instanceof globalThis.FileList))
    throw new Error("FileList is not supported in the current environment");
  return Promise.all(
    Array.from(s).map(async (e) => {
      const { name: l, type: d } = e, m = await new Promise((v, y) => {
        const t = new FileReader();
        t.onload = (p) => {
          var r;
          v((r = p.target) == null ? void 0 : r.result);
        }, t.onerror = (p) => y(p), t.readAsDataURL(e);
      });
      return {
        type: "file",
        mediaType: d,
        filename: l,
        url: m
      };
    })
  );
}
var st = class {
  constructor({
    api: s = "/api/chat",
    credentials: e,
    headers: l,
    body: d,
    fetch: m,
    prepareSendMessagesRequest: v,
    prepareReconnectToStreamRequest: y
  }) {
    this.api = s, this.credentials = e, this.headers = l, this.body = d, this.fetch = m, this.prepareSendMessagesRequest = v, this.prepareReconnectToStreamRequest = y;
  }
  async sendMessages({
    abortSignal: s,
    ...e
  }) {
    var l, d, m, v, y;
    const t = await U(this.body), p = await U(this.headers), r = await U(this.credentials), n = await ((l = this.prepareSendMessagesRequest) == null ? void 0 : l.call(this, {
      api: this.api,
      id: e.chatId,
      messages: e.messages,
      body: { ...t, ...e.body },
      headers: { ...p, ...e.headers },
      credentials: r,
      requestMetadata: e.metadata,
      trigger: e.trigger,
      messageId: e.messageId
    })), c = (d = n?.api) != null ? d : this.api, I = n?.headers !== void 0 ? n.headers : { ...p, ...e.headers }, _ = n?.body !== void 0 ? n.body : {
      ...t,
      ...e.body,
      id: e.chatId,
      messages: e.messages,
      trigger: e.trigger,
      messageId: e.messageId
    }, x = (m = n?.credentials) != null ? m : r, A = await ((v = this.fetch) != null ? v : globalThis.fetch)(c, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        ...I
      },
      body: JSON.stringify(_),
      credentials: x,
      signal: s
    });
    if (!A.ok)
      throw new Error(
        (y = await A.text()) != null ? y : "Failed to fetch the chat response."
      );
    if (!A.body)
      throw new Error("The response body is empty.");
    return this.processResponseStream(A.body);
  }
  async reconnectToStream(s) {
    var e, l, d, m, v;
    const y = await U(this.body), t = await U(this.headers), p = await U(this.credentials), r = await ((e = this.prepareReconnectToStreamRequest) == null ? void 0 : e.call(this, {
      api: this.api,
      id: s.chatId,
      body: { ...y, ...s.body },
      headers: { ...t, ...s.headers },
      credentials: p,
      requestMetadata: s.metadata
    })), n = (l = r?.api) != null ? l : `${this.api}/${s.chatId}/stream`, c = r?.headers !== void 0 ? r.headers : { ...t, ...s.headers }, I = (d = r?.credentials) != null ? d : p, x = await ((m = this.fetch) != null ? m : globalThis.fetch)(n, {
      method: "GET",
      headers: c,
      credentials: I
    });
    if (x.status === 204)
      return null;
    if (!x.ok)
      throw new Error(
        (v = await x.text()) != null ? v : "Failed to fetch the chat response."
      );
    if (!x.body)
      throw new Error("The response body is empty.");
    return this.processResponseStream(x.body);
  }
}, rt = class extends st {
  constructor(s = {}) {
    super(s);
  }
  processResponseStream(s) {
    return ce({
      stream: s,
      schema: we
    }).pipeThrough(
      new TransformStream({
        async transform(e, l) {
          if (!e.success)
            throw e.error;
          l.enqueue(e.value);
        }
      })
    );
  }
}, It = class {
  constructor({
    generateId: s = me,
    id: e = s(),
    transport: l = new rt(),
    messageMetadataSchema: d,
    dataPartSchemas: m,
    state: v,
    onError: y,
    onToolCall: t,
    onFinish: p,
    onData: r,
    sendAutomaticallyWhen: n
  }) {
    this.activeResponse = void 0, this.jobExecutor = new je(), this.sendMessage = async (c, I) => {
      var _, x, R, A;
      if (c == null) {
        await this.makeRequest({
          trigger: "submit-message",
          messageId: (_ = this.lastMessage) == null ? void 0 : _.id,
          ...I
        });
        return;
      }
      let C;
      if ("text" in c || "files" in c ? C = {
        parts: [
          ...Array.isArray(c.files) ? c.files : await at(c.files),
          ..."text" in c && c.text != null ? [{ type: "text", text: c.text }] : []
        ]
      } : C = c, c.messageId != null) {
        const E = this.state.messages.findIndex(
          (L) => L.id === c.messageId
        );
        if (E === -1)
          throw new Error(`message with id ${c.messageId} not found`);
        if (this.state.messages[E].role !== "user")
          throw new Error(
            `message with id ${c.messageId} is not a user message`
          );
        this.state.messages = this.state.messages.slice(0, E + 1), this.state.replaceMessage(E, {
          ...C,
          id: c.messageId,
          role: (x = C.role) != null ? x : "user",
          metadata: c.metadata
        });
      } else
        this.state.pushMessage({
          ...C,
          id: (R = C.id) != null ? R : this.generateId(),
          role: (A = C.role) != null ? A : "user",
          metadata: c.metadata
        });
      await this.makeRequest({
        trigger: "submit-message",
        messageId: c.messageId,
        ...I
      });
    }, this.regenerate = async ({
      messageId: c,
      ...I
    } = {}) => {
      const _ = c == null ? this.state.messages.length - 1 : this.state.messages.findIndex((x) => x.id === c);
      if (_ === -1)
        throw new Error(`message ${c} not found`);
      this.state.messages = this.state.messages.slice(
        0,
        // if the message is a user message, we need to include it in the request:
        this.messages[_].role === "assistant" ? _ : _ + 1
      ), await this.makeRequest({
        trigger: "regenerate-message",
        messageId: c,
        ...I
      });
    }, this.resumeStream = async (c = {}) => {
      await this.makeRequest({ trigger: "resume-stream", ...c });
    }, this.clearError = () => {
      this.status === "error" && (this.state.error = void 0, this.setStatus({ status: "ready" }));
    }, this.addToolResult = async ({
      tool: c,
      toolCallId: I,
      output: _
    }) => this.jobExecutor.run(async () => {
      var x, R;
      const A = this.state.messages, C = A[A.length - 1];
      this.state.replaceMessage(A.length - 1, {
        ...C,
        parts: C.parts.map(
          (E) => z(E) && E.toolCallId === I ? { ...E, state: "output-available", output: _ } : E
        )
      }), this.activeResponse && (this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(
        (E) => z(E) && E.toolCallId === I ? {
          ...E,
          state: "output-available",
          output: _,
          errorText: void 0
        } : E
      )), this.status !== "streaming" && this.status !== "submitted" && ((x = this.sendAutomaticallyWhen) != null && x.call(this, { messages: this.state.messages })) && this.makeRequest({
        trigger: "submit-message",
        messageId: (R = this.lastMessage) == null ? void 0 : R.id
      });
    }), this.stop = async () => {
      var c;
      this.status !== "streaming" && this.status !== "submitted" || (c = this.activeResponse) != null && c.abortController && this.activeResponse.abortController.abort();
    }, this.id = e, this.transport = l, this.generateId = s, this.messageMetadataSchema = d, this.dataPartSchemas = m, this.state = v, this.onError = y, this.onToolCall = t, this.onFinish = p, this.onData = r, this.sendAutomaticallyWhen = n;
  }
  /**
   * Hook status:
   *
   * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.
   * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.
   * - `ready`: The full response has been received and processed; a new user message can be submitted.
   * - `error`: An error occurred during the API request, preventing successful completion.
   */
  get status() {
    return this.state.status;
  }
  setStatus({
    status: s,
    error: e
  }) {
    this.status !== s && (this.state.status = s, this.state.error = e);
  }
  get error() {
    return this.state.error;
  }
  get messages() {
    return this.state.messages;
  }
  get lastMessage() {
    return this.state.messages[this.state.messages.length - 1];
  }
  set messages(s) {
    this.state.messages = s;
  }
  async makeRequest({
    trigger: s,
    metadata: e,
    headers: l,
    body: d,
    messageId: m
  }) {
    var v, y, t;
    this.setStatus({ status: "submitted", error: void 0 });
    const p = this.lastMessage;
    let r = !1, n = !1, c = !1;
    try {
      const I = {
        state: Ue({
          lastMessage: this.state.snapshot(p),
          messageId: this.generateId()
        }),
        abortController: new AbortController()
      };
      I.abortController.signal.addEventListener("abort", () => {
        r = !0;
      }), this.activeResponse = I;
      let _;
      if (s === "resume-stream") {
        const R = await this.transport.reconnectToStream({
          chatId: this.id,
          metadata: e,
          headers: l,
          body: d
        });
        if (R == null) {
          this.setStatus({ status: "ready" });
          return;
        }
        _ = R;
      } else
        _ = await this.transport.sendMessages({
          chatId: this.id,
          messages: this.state.messages,
          abortSignal: I.abortController.signal,
          metadata: e,
          headers: l,
          body: d,
          trigger: s,
          messageId: m
        });
      const x = (R) => (
        // serialize the job execution to avoid race conditions:
        this.jobExecutor.run(
          () => R({
            state: I.state,
            write: () => {
              var A;
              this.setStatus({ status: "streaming" }), I.state.message.id === ((A = this.lastMessage) == null ? void 0 : A.id) ? this.state.replaceMessage(
                this.state.messages.length - 1,
                I.state.message
              ) : this.state.pushMessage(I.state.message);
            }
          })
        )
      );
      await Le({
        stream: Fe({
          stream: _,
          onToolCall: this.onToolCall,
          onData: this.onData,
          messageMetadataSchema: this.messageMetadataSchema,
          dataPartSchemas: this.dataPartSchemas,
          runUpdateMessageJob: x,
          onError: (R) => {
            throw R;
          }
        }),
        onError: (R) => {
          throw R;
        }
      }), this.setStatus({ status: "ready" });
    } catch (I) {
      if (r || I.name === "AbortError")
        return r = !0, this.setStatus({ status: "ready" }), null;
      c = !0, I instanceof TypeError && (I.message.toLowerCase().includes("fetch") || I.message.toLowerCase().includes("network")) && (n = !0), this.onError && I instanceof Error && this.onError(I), this.setStatus({ status: "error", error: I });
    } finally {
      try {
        (v = this.onFinish) == null || v.call(this, {
          message: this.activeResponse.state.message,
          messages: this.state.messages,
          isAbort: r,
          isDisconnect: n,
          isError: c
        });
      } catch (I) {
        console.error(I);
      }
      this.activeResponse = void 0;
    }
    (y = this.sendAutomaticallyWhen) != null && y.call(this, { messages: this.state.messages }) && await this.makeRequest({
      trigger: "submit-message",
      messageId: (t = this.lastMessage) == null ? void 0 : t.id,
      metadata: e,
      headers: l,
      body: d
    });
  }
};
function yt({
  messages: s
}) {
  const e = s[s.length - 1];
  if (!e || e.role !== "assistant")
    return !1;
  const l = e.parts.reduce((m, v, y) => v.type === "step-start" ? y : m, -1), d = e.parts.slice(l + 1).filter(z);
  return d.length > 0 && d.every((m) => m.state === "output-available");
}
var ot = u({
  type: i("text"),
  text: a(),
  state: H(["streaming", "done"]).optional(),
  providerMetadata: g.optional()
}), it = u({
  type: i("reasoning"),
  text: a(),
  state: H(["streaming", "done"]).optional(),
  providerMetadata: g.optional()
}), lt = u({
  type: i("source-url"),
  sourceId: a(),
  url: a(),
  title: a().optional(),
  providerMetadata: g.optional()
}), nt = u({
  type: i("source-document"),
  sourceId: a(),
  mediaType: a(),
  title: a(),
  filename: a().optional(),
  providerMetadata: g.optional()
}), pt = u({
  type: i("file"),
  mediaType: a(),
  filename: a().optional(),
  url: a(),
  providerMetadata: g.optional()
}), dt = u({
  type: i("step-start")
}), ut = u({
  type: a().startsWith("data-"),
  id: a().optional(),
  data: b()
}), ct = [
  u({
    type: i("dynamic-tool"),
    toolName: a(),
    toolCallId: a(),
    state: i("input-streaming"),
    input: b().optional(),
    output: O().optional(),
    errorText: O().optional()
  }),
  u({
    type: i("dynamic-tool"),
    toolName: a(),
    toolCallId: a(),
    state: i("input-available"),
    input: b(),
    output: O().optional(),
    errorText: O().optional(),
    callProviderMetadata: g.optional()
  }),
  u({
    type: i("dynamic-tool"),
    toolName: a(),
    toolCallId: a(),
    state: i("output-available"),
    input: b(),
    output: b(),
    errorText: O().optional(),
    callProviderMetadata: g.optional(),
    preliminary: S().optional()
  }),
  u({
    type: i("dynamic-tool"),
    toolName: a(),
    toolCallId: a(),
    state: i("output-error"),
    input: b(),
    output: O().optional(),
    errorText: a(),
    callProviderMetadata: g.optional()
  })
], mt = [
  u({
    type: a().startsWith("tool-"),
    toolCallId: a(),
    state: i("input-streaming"),
    input: b().optional(),
    output: O().optional(),
    errorText: O().optional()
  }),
  u({
    type: a().startsWith("tool-"),
    toolCallId: a(),
    state: i("input-available"),
    input: b(),
    output: O().optional(),
    errorText: O().optional(),
    callProviderMetadata: g.optional()
  }),
  u({
    type: a().startsWith("tool-"),
    toolCallId: a(),
    state: i("output-available"),
    input: b(),
    output: b(),
    errorText: O().optional(),
    callProviderMetadata: g.optional(),
    preliminary: S().optional()
  }),
  u({
    type: a().startsWith("tool-"),
    toolCallId: a(),
    state: i("output-error"),
    input: b(),
    output: O().optional(),
    errorText: a(),
    callProviderMetadata: g.optional()
  })
];
u({
  id: a(),
  role: H(["system", "user", "assistant"]),
  metadata: b().optional(),
  parts: D(
    N([
      ot,
      it,
      lt,
      nt,
      pt,
      dt,
      ut,
      ...ct,
      ...mt
    ])
  )
});
export {
  Z as AISDKError,
  It as AbstractChat,
  rt as DefaultChatTransport,
  st as HttpChatTransport,
  _t as JSONParseError,
  k as NoObjectGeneratedError,
  Be as Output,
  je as SerialJobExecutor,
  xt as TypeValidationError,
  ve as asSchema,
  Ne as assistantModelMessageSchema,
  Le as consumeStream,
  at as convertFileListToFileUIParts,
  W as createIdGenerator,
  me as generateId,
  ee as getToolName,
  z as isToolOrDynamicToolUIPart,
  q as isToolUIPart,
  bt as jsonSchema,
  yt as lastAssistantMessageIsCompleteWithToolCalls,
  de as parsePartialJson,
  Ce as systemModelMessageSchema,
  Ae as toolModelMessageSchema,
  Me as userModelMessageSchema,
  Tt as zodSchema
};
//# sourceMappingURL=index.js.map
