import { generateId as M, safeParseJSON as L, validatorSymbol as v } from "../../../../../@ai-sdk_provider-utils@2.2.8_zod@3.24.4/node_modules/@ai-sdk/provider-utils/dist/index.js";
import "../../../../../zod-to-json-schema@3.24.5_zod@3.24.4/node_modules/zod-to-json-schema/dist/esm/parsers/string.js";
import { zodToJsonSchema as F } from "../../../../../zod-to-json-schema@3.24.5_zod@3.24.4/node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js";
var k = {
  code: "0",
  name: "text",
  parse: (t) => {
    if (typeof t != "string")
      throw new Error('"text" parts expect a string value.');
    return { type: "text", value: t };
  }
}, R = {
  code: "3",
  name: "error",
  parse: (t) => {
    if (typeof t != "string")
      throw new Error('"error" parts expect a string value.');
    return { type: "error", value: t };
  }
}, N = {
  code: "4",
  name: "assistant_message",
  parse: (t) => {
    if (t == null || typeof t != "object" || !("id" in t) || !("role" in t) || !("content" in t) || typeof t.id != "string" || typeof t.role != "string" || t.role !== "assistant" || !Array.isArray(t.content) || !t.content.every(
      (e) => e != null && typeof e == "object" && "type" in e && e.type === "text" && "text" in e && e.text != null && typeof e.text == "object" && "value" in e.text && typeof e.text.value == "string"
    ))
      throw new Error(
        '"assistant_message" parts expect an object with an "id", "role", and "content" property.'
      );
    return {
      type: "assistant_message",
      value: t
    };
  }
}, C = {
  code: "5",
  name: "assistant_control_data",
  parse: (t) => {
    if (t == null || typeof t != "object" || !("threadId" in t) || !("messageId" in t) || typeof t.threadId != "string" || typeof t.messageId != "string")
      throw new Error(
        '"assistant_control_data" parts expect an object with a "threadId" and "messageId" property.'
      );
    return {
      type: "assistant_control_data",
      value: {
        threadId: t.threadId,
        messageId: t.messageId
      }
    };
  }
}, x = {
  code: "6",
  name: "data_message",
  parse: (t) => {
    if (t == null || typeof t != "object" || !("role" in t) || !("data" in t) || typeof t.role != "string" || t.role !== "data")
      throw new Error(
        '"data_message" parts expect an object with a "role" and "data" property.'
      );
    return {
      type: "data_message",
      value: t
    };
  }
}, j = [
  k,
  R,
  N,
  C,
  x
];
k.code + "", R.code + "", N.code + "", C.code + "", x.code + "";
k.name + "", k.code, R.name + "", R.code, N.name + "", N.code, C.name + "", C.code, x.name + "", x.code;
j.map((t) => t.code);
function U({
  promptTokens: t,
  completionTokens: e
}) {
  return {
    promptTokens: t,
    completionTokens: e,
    totalTokens: t + e
  };
}
function V(t) {
  const e = ["ROOT"];
  let r = -1, s = null;
  function i(o, n, h) {
    switch (o) {
      case '"': {
        r = n, e.pop(), e.push(h), e.push("INSIDE_STRING");
        break;
      }
      case "f":
      case "t":
      case "n": {
        r = n, s = n, e.pop(), e.push(h), e.push("INSIDE_LITERAL");
        break;
      }
      case "-": {
        e.pop(), e.push(h), 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": {
        r = n, e.pop(), e.push(h), e.push("INSIDE_NUMBER");
        break;
      }
      case "{": {
        r = n, e.pop(), e.push(h), e.push("INSIDE_OBJECT_START");
        break;
      }
      case "[": {
        r = n, e.pop(), e.push(h), e.push("INSIDE_ARRAY_START");
        break;
      }
    }
  }
  function l(o, n) {
    switch (o) {
      case ",": {
        e.pop(), e.push("INSIDE_OBJECT_AFTER_COMMA");
        break;
      }
      case "}": {
        r = n, e.pop();
        break;
      }
    }
  }
  function u(o, n) {
    switch (o) {
      case ",": {
        e.pop(), e.push("INSIDE_ARRAY_AFTER_COMMA");
        break;
      }
      case "]": {
        r = n, e.pop();
        break;
      }
    }
  }
  for (let o = 0; o < t.length; o++) {
    const n = t[o];
    switch (e[e.length - 1]) {
      case "ROOT":
        i(n, o, "FINISH");
        break;
      case "INSIDE_OBJECT_START": {
        switch (n) {
          case '"': {
            e.pop(), e.push("INSIDE_OBJECT_KEY");
            break;
          }
          case "}": {
            r = o, e.pop();
            break;
          }
        }
        break;
      }
      case "INSIDE_OBJECT_AFTER_COMMA": {
        switch (n) {
          case '"': {
            e.pop(), e.push("INSIDE_OBJECT_KEY");
            break;
          }
        }
        break;
      }
      case "INSIDE_OBJECT_KEY": {
        switch (n) {
          case '"': {
            e.pop(), e.push("INSIDE_OBJECT_AFTER_KEY");
            break;
          }
        }
        break;
      }
      case "INSIDE_OBJECT_AFTER_KEY": {
        switch (n) {
          case ":": {
            e.pop(), e.push("INSIDE_OBJECT_BEFORE_VALUE");
            break;
          }
        }
        break;
      }
      case "INSIDE_OBJECT_BEFORE_VALUE": {
        i(n, o, "INSIDE_OBJECT_AFTER_VALUE");
        break;
      }
      case "INSIDE_OBJECT_AFTER_VALUE": {
        l(n, o);
        break;
      }
      case "INSIDE_STRING": {
        switch (n) {
          case '"': {
            e.pop(), r = o;
            break;
          }
          case "\\": {
            e.push("INSIDE_STRING_ESCAPE");
            break;
          }
          default:
            r = o;
        }
        break;
      }
      case "INSIDE_ARRAY_START": {
        switch (n) {
          case "]": {
            r = o, e.pop();
            break;
          }
          default: {
            r = o, i(n, o, "INSIDE_ARRAY_AFTER_VALUE");
            break;
          }
        }
        break;
      }
      case "INSIDE_ARRAY_AFTER_VALUE": {
        switch (n) {
          case ",": {
            e.pop(), e.push("INSIDE_ARRAY_AFTER_COMMA");
            break;
          }
          case "]": {
            r = o, e.pop();
            break;
          }
          default: {
            r = o;
            break;
          }
        }
        break;
      }
      case "INSIDE_ARRAY_AFTER_COMMA": {
        i(n, o, "INSIDE_ARRAY_AFTER_VALUE");
        break;
      }
      case "INSIDE_STRING_ESCAPE": {
        e.pop(), r = o;
        break;
      }
      case "INSIDE_NUMBER": {
        switch (n) {
          case "0":
          case "1":
          case "2":
          case "3":
          case "4":
          case "5":
          case "6":
          case "7":
          case "8":
          case "9": {
            r = o;
            break;
          }
          case "e":
          case "E":
          case "-":
          case ".":
            break;
          case ",": {
            e.pop(), e[e.length - 1] === "INSIDE_ARRAY_AFTER_VALUE" && u(n, o), e[e.length - 1] === "INSIDE_OBJECT_AFTER_VALUE" && l(n, o);
            break;
          }
          case "}": {
            e.pop(), e[e.length - 1] === "INSIDE_OBJECT_AFTER_VALUE" && l(n, o);
            break;
          }
          case "]": {
            e.pop(), e[e.length - 1] === "INSIDE_ARRAY_AFTER_VALUE" && u(n, o);
            break;
          }
          default: {
            e.pop();
            break;
          }
        }
        break;
      }
      case "INSIDE_LITERAL": {
        const c = t.substring(s, o + 1);
        !"false".startsWith(c) && !"true".startsWith(c) && !"null".startsWith(c) ? (e.pop(), e[e.length - 1] === "INSIDE_OBJECT_AFTER_VALUE" ? l(n, o) : e[e.length - 1] === "INSIDE_ARRAY_AFTER_VALUE" && u(n, o)) : r = o;
        break;
      }
    }
  }
  let p = t.slice(0, r + 1);
  for (let o = e.length - 1; o >= 0; o--)
    switch (e[o]) {
      case "INSIDE_STRING": {
        p += '"';
        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": {
        p += "}";
        break;
      }
      case "INSIDE_ARRAY_START":
      case "INSIDE_ARRAY_AFTER_COMMA":
      case "INSIDE_ARRAY_AFTER_VALUE": {
        p += "]";
        break;
      }
      case "INSIDE_LITERAL": {
        const h = t.substring(s, t.length);
        "true".startsWith(h) ? p += "true".slice(h.length) : "false".startsWith(h) ? p += "false".slice(h.length) : "null".startsWith(h) && (p += "null".slice(h.length));
      }
    }
  return p;
}
function Y(t) {
  if (t === void 0)
    return { value: void 0, state: "undefined-input" };
  let e = L({ text: t });
  return e.success ? { value: e.value, state: "successful-parse" } : (e = L({ text: V(t) }), e.success ? { value: e.value, state: "repaired-parse" } : { value: void 0, state: "failed-parse" });
}
var $ = {
  code: "0",
  name: "text",
  parse: (t) => {
    if (typeof t != "string")
      throw new Error('"text" parts expect a string value.');
    return { type: "text", value: t };
  }
}, W = {
  code: "2",
  name: "data",
  parse: (t) => {
    if (!Array.isArray(t))
      throw new Error('"data" parts expect an array value.');
    return { type: "data", value: t };
  }
}, K = {
  code: "3",
  name: "error",
  parse: (t) => {
    if (typeof t != "string")
      throw new Error('"error" parts expect a string value.');
    return { type: "error", value: t };
  }
}, G = {
  code: "8",
  name: "message_annotations",
  parse: (t) => {
    if (!Array.isArray(t))
      throw new Error('"message_annotations" parts expect an array value.');
    return { type: "message_annotations", value: t };
  }
}, q = {
  code: "9",
  name: "tool_call",
  parse: (t) => {
    if (t == null || typeof t != "object" || !("toolCallId" in t) || typeof t.toolCallId != "string" || !("toolName" in t) || typeof t.toolName != "string" || !("args" in t) || typeof t.args != "object")
      throw new Error(
        '"tool_call" parts expect an object with a "toolCallId", "toolName", and "args" property.'
      );
    return {
      type: "tool_call",
      value: t
    };
  }
}, z = {
  code: "a",
  name: "tool_result",
  parse: (t) => {
    if (t == null || typeof t != "object" || !("toolCallId" in t) || typeof t.toolCallId != "string" || !("result" in t))
      throw new Error(
        '"tool_result" parts expect an object with a "toolCallId" and a "result" property.'
      );
    return {
      type: "tool_result",
      value: t
    };
  }
}, H = {
  code: "b",
  name: "tool_call_streaming_start",
  parse: (t) => {
    if (t == null || typeof t != "object" || !("toolCallId" in t) || typeof t.toolCallId != "string" || !("toolName" in t) || typeof t.toolName != "string")
      throw new Error(
        '"tool_call_streaming_start" parts expect an object with a "toolCallId" and "toolName" property.'
      );
    return {
      type: "tool_call_streaming_start",
      value: t
    };
  }
}, Q = {
  code: "c",
  name: "tool_call_delta",
  parse: (t) => {
    if (t == null || typeof t != "object" || !("toolCallId" in t) || typeof t.toolCallId != "string" || !("argsTextDelta" in t) || typeof t.argsTextDelta != "string")
      throw new Error(
        '"tool_call_delta" parts expect an object with a "toolCallId" and "argsTextDelta" property.'
      );
    return {
      type: "tool_call_delta",
      value: t
    };
  }
}, X = {
  code: "d",
  name: "finish_message",
  parse: (t) => {
    if (t == null || typeof t != "object" || !("finishReason" in t) || typeof t.finishReason != "string")
      throw new Error(
        '"finish_message" parts expect an object with a "finishReason" property.'
      );
    const e = {
      finishReason: t.finishReason
    };
    return "usage" in t && t.usage != null && typeof t.usage == "object" && "promptTokens" in t.usage && "completionTokens" in t.usage && (e.usage = {
      promptTokens: typeof t.usage.promptTokens == "number" ? t.usage.promptTokens : Number.NaN,
      completionTokens: typeof t.usage.completionTokens == "number" ? t.usage.completionTokens : Number.NaN
    }), {
      type: "finish_message",
      value: e
    };
  }
}, Z = {
  code: "e",
  name: "finish_step",
  parse: (t) => {
    if (t == null || typeof t != "object" || !("finishReason" in t) || typeof t.finishReason != "string")
      throw new Error(
        '"finish_step" parts expect an object with a "finishReason" property.'
      );
    const e = {
      finishReason: t.finishReason,
      isContinued: !1
    };
    return "usage" in t && t.usage != null && typeof t.usage == "object" && "promptTokens" in t.usage && "completionTokens" in t.usage && (e.usage = {
      promptTokens: typeof t.usage.promptTokens == "number" ? t.usage.promptTokens : Number.NaN,
      completionTokens: typeof t.usage.completionTokens == "number" ? t.usage.completionTokens : Number.NaN
    }), "isContinued" in t && typeof t.isContinued == "boolean" && (e.isContinued = t.isContinued), {
      type: "finish_step",
      value: e
    };
  }
}, tt = {
  code: "f",
  name: "start_step",
  parse: (t) => {
    if (t == null || typeof t != "object" || !("messageId" in t) || typeof t.messageId != "string")
      throw new Error(
        '"start_step" parts expect an object with an "id" property.'
      );
    return {
      type: "start_step",
      value: {
        messageId: t.messageId
      }
    };
  }
}, et = {
  code: "g",
  name: "reasoning",
  parse: (t) => {
    if (typeof t != "string")
      throw new Error('"reasoning" parts expect a string value.');
    return { type: "reasoning", value: t };
  }
}, at = {
  code: "h",
  name: "source",
  parse: (t) => {
    if (t == null || typeof t != "object")
      throw new Error('"source" parts expect a Source object.');
    return {
      type: "source",
      value: t
    };
  }
}, rt = {
  code: "i",
  name: "redacted_reasoning",
  parse: (t) => {
    if (t == null || typeof t != "object" || !("data" in t) || typeof t.data != "string")
      throw new Error(
        '"redacted_reasoning" parts expect an object with a "data" property.'
      );
    return { type: "redacted_reasoning", value: { data: t.data } };
  }
}, ot = {
  code: "j",
  name: "reasoning_signature",
  parse: (t) => {
    if (t == null || typeof t != "object" || !("signature" in t) || typeof t.signature != "string")
      throw new Error(
        '"reasoning_signature" parts expect an object with a "signature" property.'
      );
    return {
      type: "reasoning_signature",
      value: { signature: t.signature }
    };
  }
}, nt = {
  code: "k",
  name: "file",
  parse: (t) => {
    if (t == null || typeof t != "object" || !("data" in t) || typeof t.data != "string" || !("mimeType" in t) || typeof t.mimeType != "string")
      throw new Error(
        '"file" parts expect an object with a "data" and "mimeType" property.'
      );
    return { type: "file", value: t };
  }
}, D = [
  $,
  W,
  K,
  G,
  q,
  z,
  H,
  Q,
  X,
  Z,
  tt,
  et,
  at,
  rt,
  ot,
  nt
], st = Object.fromEntries(
  D.map((t) => [t.code, t])
);
Object.fromEntries(
  D.map((t) => [t.name, t.code])
);
var it = D.map((t) => t.code), ct = (t) => {
  const e = t.indexOf(":");
  if (e === -1)
    throw new Error("Failed to parse stream string. No separator found.");
  const r = t.slice(0, e);
  if (!it.includes(r))
    throw new Error(`Failed to parse stream string. Invalid code ${r}.`);
  const s = r, i = t.slice(e + 1), l = JSON.parse(i);
  return st[s].parse(l);
};
function At(t, e) {
  const r = D.find((s) => s.name === t);
  if (!r)
    throw new Error(`Invalid stream part type: ${t}`);
  return `${r.code}:${JSON.stringify(e)}
`;
}
var lt = 10;
function pt(t, e) {
  const r = new Uint8Array(e);
  let s = 0;
  for (const i of t)
    r.set(i, s), s += i.length;
  return t.length = 0, r;
}
async function dt({
  stream: t,
  onTextPart: e,
  onReasoningPart: r,
  onReasoningSignaturePart: s,
  onRedactedReasoningPart: i,
  onSourcePart: l,
  onFilePart: u,
  onDataPart: p,
  onErrorPart: o,
  onToolCallStreamingStartPart: n,
  onToolCallDeltaPart: h,
  onToolCallPart: c,
  onToolResultPart: w,
  onMessageAnnotationsPart: _,
  onFinishMessagePart: y,
  onFinishStepPart: T,
  onStartStepPart: A
}) {
  const S = t.getReader(), b = new TextDecoder(), m = [];
  let E = 0;
  for (; ; ) {
    const { value: g } = await S.read();
    if (g && (m.push(g), E += g.length, g[g.length - 1] !== lt))
      continue;
    if (m.length === 0)
      break;
    const a = pt(m, E);
    E = 0;
    const d = b.decode(a, { stream: !0 }).split(`
`).filter((I) => I !== "").map(ct);
    for (const { type: I, value: f } of d)
      switch (I) {
        case "text":
          await e?.(f);
          break;
        case "reasoning":
          await r?.(f);
          break;
        case "reasoning_signature":
          await s?.(f);
          break;
        case "redacted_reasoning":
          await i?.(f);
          break;
        case "file":
          await u?.(f);
          break;
        case "source":
          await l?.(f);
          break;
        case "data":
          await p?.(f);
          break;
        case "error":
          await o?.(f);
          break;
        case "message_annotations":
          await _?.(f);
          break;
        case "tool_call_streaming_start":
          await n?.(f);
          break;
        case "tool_call_delta":
          await h?.(f);
          break;
        case "tool_call":
          await c?.(f);
          break;
        case "tool_result":
          await w?.(f);
          break;
        case "finish_message":
          await y?.(f);
          break;
        case "finish_step":
          await T?.(f);
          break;
        case "start_step":
          await A?.(f);
          break;
        default: {
          const O = I;
          throw new Error(`Unknown stream part type: ${O}`);
        }
      }
  }
}
async function ft({
  stream: t,
  update: e,
  onToolCall: r,
  onFinish: s,
  generateId: i = M,
  getCurrentDate: l = () => /* @__PURE__ */ new Date(),
  lastMessage: u
}) {
  var p, o;
  const n = u?.role === "assistant";
  let h = n ? 1 + // find max step in existing tool invocations:
  ((o = (p = u.toolInvocations) == null ? void 0 : p.reduce((a, d) => {
    var I;
    return Math.max(a, (I = d.step) != null ? I : 0);
  }, 0)) != null ? o : 0) : 0;
  const c = n ? structuredClone(u) : {
    id: i(),
    createdAt: l(),
    role: "assistant",
    content: "",
    parts: []
  };
  let w, _, y;
  function T(a, d) {
    const I = c.parts.find(
      (f) => f.type === "tool-invocation" && f.toolInvocation.toolCallId === a
    );
    I != null ? I.toolInvocation = d : c.parts.push({
      type: "tool-invocation",
      toolInvocation: d
    });
  }
  const A = [];
  let S = n ? u?.annotations : void 0;
  const b = {};
  let m = {
    completionTokens: NaN,
    promptTokens: NaN,
    totalTokens: NaN
  }, E = "unknown";
  function g() {
    const a = [...A];
    S?.length && (c.annotations = S);
    const d = {
      // deep copy the message to ensure that deep changes (msg attachments) are updated
      // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
      ...structuredClone(c),
      // add a revision id to ensure that the message is updated with SWR. SWR uses a
      // hashing approach by default to detect changes, but it only works for shallow
      // changes. This is why we need to add a revision id to ensure that the message
      // is updated with SWR (without it, the changes get stuck in SWR and are not
      // forwarded to rendering):
      revisionId: i()
    };
    e({
      message: d,
      data: a,
      replaceLastMessage: n
    });
  }
  await dt({
    stream: t,
    onTextPart(a) {
      w == null ? (w = {
        type: "text",
        text: a
      }, c.parts.push(w)) : w.text += a, c.content += a, g();
    },
    onReasoningPart(a) {
      var d;
      y == null ? (y = { type: "text", text: a }, _?.details.push(y)) : y.text += a, _ == null ? (_ = {
        type: "reasoning",
        reasoning: a,
        details: [y]
      }, c.parts.push(_)) : _.reasoning += a, c.reasoning = ((d = c.reasoning) != null ? d : "") + a, g();
    },
    onReasoningSignaturePart(a) {
      y != null && (y.signature = a.signature);
    },
    onRedactedReasoningPart(a) {
      _ == null && (_ = {
        type: "reasoning",
        reasoning: "",
        details: []
      }, c.parts.push(_)), _.details.push({
        type: "redacted",
        data: a.data
      }), y = void 0, g();
    },
    onFilePart(a) {
      c.parts.push({
        type: "file",
        mimeType: a.mimeType,
        data: a.data
      }), g();
    },
    onSourcePart(a) {
      c.parts.push({
        type: "source",
        source: a
      }), g();
    },
    onToolCallStreamingStartPart(a) {
      c.toolInvocations == null && (c.toolInvocations = []), b[a.toolCallId] = {
        text: "",
        step: h,
        toolName: a.toolName,
        index: c.toolInvocations.length
      };
      const d = {
        state: "partial-call",
        step: h,
        toolCallId: a.toolCallId,
        toolName: a.toolName,
        args: void 0
      };
      c.toolInvocations.push(d), T(a.toolCallId, d), g();
    },
    onToolCallDeltaPart(a) {
      const d = b[a.toolCallId];
      d.text += a.argsTextDelta;
      const { value: I } = Y(d.text), f = {
        state: "partial-call",
        step: d.step,
        toolCallId: a.toolCallId,
        toolName: d.toolName,
        args: I
      };
      c.toolInvocations[d.index] = f, T(a.toolCallId, f), g();
    },
    async onToolCallPart(a) {
      const d = {
        state: "call",
        step: h,
        ...a
      };
      if (b[a.toolCallId] != null ? c.toolInvocations[b[a.toolCallId].index] = d : (c.toolInvocations == null && (c.toolInvocations = []), c.toolInvocations.push(d)), T(a.toolCallId, d), g(), r) {
        const I = await r({ toolCall: a });
        if (I != null) {
          const f = {
            state: "result",
            step: h,
            ...a,
            result: I
          };
          c.toolInvocations[c.toolInvocations.length - 1] = f, T(a.toolCallId, f), g();
        }
      }
    },
    onToolResultPart(a) {
      const d = c.toolInvocations;
      if (d == null)
        throw new Error("tool_result must be preceded by a tool_call");
      const I = d.findIndex(
        (O) => O.toolCallId === a.toolCallId
      );
      if (I === -1)
        throw new Error(
          "tool_result must be preceded by a tool_call with the same toolCallId"
        );
      const f = {
        ...d[I],
        state: "result",
        ...a
      };
      d[I] = f, T(a.toolCallId, f), g();
    },
    onDataPart(a) {
      A.push(...a), g();
    },
    onMessageAnnotationsPart(a) {
      S == null ? S = [...a] : S.push(...a), g();
    },
    onFinishStepPart(a) {
      h += 1, w = a.isContinued ? w : void 0, _ = void 0, y = void 0;
    },
    onStartStepPart(a) {
      n || (c.id = a.messageId), c.parts.push({ type: "step-start" }), g();
    },
    onFinishMessagePart(a) {
      E = a.finishReason, a.usage != null && (m = U(a.usage));
    },
    onErrorPart(a) {
      throw new Error(a);
    }
  }), s?.({ message: c, finishReason: E, usage: m });
}
async function ut({
  stream: t,
  onTextPart: e
}) {
  const r = t.pipeThrough(new TextDecoderStream()).getReader();
  for (; ; ) {
    const { done: s, value: i } = await r.read();
    if (s)
      break;
    await e(i);
  }
}
async function ht({
  stream: t,
  update: e,
  onFinish: r,
  getCurrentDate: s = () => /* @__PURE__ */ new Date(),
  generateId: i = M
}) {
  const l = { type: "text", text: "" }, u = {
    id: i(),
    createdAt: s(),
    role: "assistant",
    content: "",
    parts: [l]
  };
  await ut({
    stream: t,
    onTextPart: (p) => {
      u.content += p, l.text += p, e({
        message: { ...u },
        data: [],
        replaceLastMessage: !1
      });
    }
  }), r?.(u, {
    usage: { completionTokens: NaN, promptTokens: NaN, totalTokens: NaN },
    finishReason: "unknown"
  });
}
var gt = () => fetch;
async function bt({
  api: t,
  body: e,
  streamProtocol: r = "data",
  credentials: s,
  headers: i,
  abortController: l,
  restoreMessagesOnFailure: u,
  onResponse: p,
  onUpdate: o,
  onFinish: n,
  onToolCall: h,
  generateId: c,
  fetch: w = gt(),
  lastMessage: _,
  requestType: y = "generate"
}) {
  var T, A, S;
  const m = await (y === "resume" ? w(`${t}?chatId=${e.id}`, {
    method: "GET",
    headers: {
      "Content-Type": "application/json",
      ...i
    },
    signal: (T = l?.()) == null ? void 0 : T.signal,
    credentials: s
  }) : w(t, {
    method: "POST",
    body: JSON.stringify(e),
    headers: {
      "Content-Type": "application/json",
      ...i
    },
    signal: (A = l?.()) == null ? void 0 : A.signal,
    credentials: s
  })).catch((E) => {
    throw u(), E;
  });
  if (p)
    try {
      await p(m);
    } catch (E) {
      throw E;
    }
  if (!m.ok)
    throw u(), new Error(
      (S = await m.text()) != null ? S : "Failed to fetch the chat response."
    );
  if (!m.body)
    throw new Error("The response body is empty.");
  switch (r) {
    case "text": {
      await ht({
        stream: m.body,
        update: o,
        onFinish: n,
        generateId: c
      });
      return;
    }
    case "data": {
      await ft({
        stream: m.body,
        update: o,
        lastMessage: _,
        onToolCall: h,
        onFinish({ message: E, finishReason: g, usage: a }) {
          n && E != null && n(E, { usage: a, finishReason: g });
        },
        generateId: c
      });
      return;
    }
    default: {
      const E = r;
      throw new Error(`Unknown stream protocol: ${E}`);
    }
  }
}
function B(t) {
  return t?.reduce((e, r) => {
    var s;
    return Math.max(e, (s = r.step) != null ? s : 0);
  }, 0);
}
function It(t) {
  var e;
  return (e = t.parts) != null ? e : [
    ...t.toolInvocations ? t.toolInvocations.map((r) => ({
      type: "tool-invocation",
      toolInvocation: r
    })) : [],
    ...t.reasoning ? [
      {
        type: "reasoning",
        reasoning: t.reasoning,
        details: [{ type: "text", text: t.reasoning }]
      }
    ] : [],
    ...t.content ? [{ type: "text", text: t.content }] : []
  ];
}
function kt(t) {
  return t.map((e) => ({
    ...e,
    parts: It(e)
  }));
}
function J(t, e) {
  if (t === e)
    return !0;
  if (t == null || e == null)
    return !1;
  if (typeof t != "object" && typeof e != "object")
    return t === e;
  if (t.constructor !== e.constructor)
    return !1;
  if (t instanceof Date && e instanceof Date)
    return t.getTime() === e.getTime();
  if (Array.isArray(t)) {
    if (t.length !== e.length)
      return !1;
    for (let i = 0; i < t.length; i++)
      if (!J(t[i], e[i]))
        return !1;
    return !0;
  }
  const r = Object.keys(t), s = Object.keys(e);
  if (r.length !== s.length)
    return !1;
  for (const i of r)
    if (!s.includes(i) || !J(t[i], e[i]))
      return !1;
  return !0;
}
async function Rt(t) {
  if (!t)
    return [];
  if (globalThis.FileList && t instanceof globalThis.FileList)
    return Promise.all(
      Array.from(t).map(async (e) => {
        const { name: r, type: s } = e, i = await new Promise((l, u) => {
          const p = new FileReader();
          p.onload = (o) => {
            var n;
            l((n = o.target) == null ? void 0 : n.result);
          }, p.onerror = (o) => u(o), p.readAsDataURL(e);
        });
        return {
          name: r,
          contentType: s,
          url: i
        };
      })
    );
  if (Array.isArray(t))
    return t;
  throw new Error("Invalid attachments type");
}
function _t(t, e) {
  var r;
  const s = (r = void 0) != null ? r : !1;
  return Et(
    F(t, {
      $refStrategy: s ? "root" : "none",
      target: "jsonSchema7"
      // note: openai mode breaks various gemini conversions
    }),
    {
      validate: (i) => {
        const l = t.safeParse(i);
        return l.success ? { success: !0, value: l.data } : { success: !1, error: l.error };
      }
    }
  );
}
var P = Symbol.for("vercel.ai.schema");
function Et(t, {
  validate: e
} = {}) {
  return {
    [P]: !0,
    _type: void 0,
    // should never be used directly
    [v]: !0,
    jsonSchema: t,
    validate: e
  };
}
function yt(t) {
  return typeof t == "object" && t !== null && P in t && t[P] === !0 && "jsonSchema" in t && "validate" in t;
}
function Nt(t) {
  return yt(t) ? t : _t(t);
}
function Ct({
  originalMaxToolInvocationStep: t,
  originalMessageCount: e,
  maxSteps: r,
  messages: s
}) {
  var i;
  const l = s[s.length - 1];
  return (
    // check if the feature is enabled:
    r > 1 && // ensure there is a last message:
    l != null && // ensure we actually have new steps (to prevent infinite loops in case of errors):
    (s.length > e || B(l.toolInvocations) !== t) && // check that next step is possible:
    mt(l) && // limit the number of automatic steps:
    ((i = B(l.toolInvocations)) != null ? i : 0) < r
  );
}
function mt(t) {
  if (t.role !== "assistant")
    return !1;
  const e = t.parts.reduce((s, i, l) => i.type === "step-start" ? l : s, -1), r = t.parts.slice(e + 1).filter((s) => s.type === "tool-invocation");
  return r.length > 0 && r.every((s) => "result" in s.toolInvocation);
}
function xt({
  messages: t,
  toolCallId: e,
  toolResult: r
}) {
  var s;
  const i = t[t.length - 1], l = i.parts.find(
    (p) => p.type === "tool-invocation" && p.toolInvocation.toolCallId === e
  );
  if (l == null)
    return;
  const u = {
    ...l.toolInvocation,
    state: "result",
    result: r
  };
  l.toolInvocation = u, i.toolInvocations = (s = i.toolInvocations) == null ? void 0 : s.map(
    (p) => p.toolCallId === e ? u : p
  );
}
export {
  Nt as asSchema,
  bt as callChatApi,
  B as extractMaxToolInvocationStep,
  kt as fillMessageParts,
  At as formatDataStreamPart,
  M as generateId,
  It as getMessageParts,
  mt as isAssistantMessageWithCompletedToolCalls,
  J as isDeepEqualData,
  Et as jsonSchema,
  ct as parseDataStreamPart,
  Y as parsePartialJson,
  Rt as prepareAttachmentsForRequest,
  dt as processDataStream,
  ut as processTextStream,
  Ct as shouldResubmitMessages,
  xt as updateToolCallResult,
  _t as zodSchema
};
//# sourceMappingURL=index.js.map
