import { createIdGenerator as c, safeParseJSON as F, safeValidateTypes as U, convertAsyncIteratorToReadableStream as z } from "../../../../@ai-sdk_provider-utils@2.2.8_zod@3.24.4/node_modules/@ai-sdk/provider-utils/dist/index.js";
import { generateId as qe } from "../../../../@ai-sdk_provider-utils@2.2.8_zod@3.24.4/node_modules/@ai-sdk/provider-utils/dist/index.js";
import { asSchema as V, parsePartialJson as L, formatDataStreamPart as _ } from "../../../../@ai-sdk_ui-utils@1.2.11_zod@3.24.4/node_modules/@ai-sdk/ui-utils/dist/index.js";
import { jsonSchema as Ue, parseDataStreamPart as ze, processDataStream as Ve, processTextStream as Le, zodSchema as Be } from "../../../../@ai-sdk_ui-utils@1.2.11_zod@3.24.4/node_modules/@ai-sdk/ui-utils/dist/index.js";
import { AISDKError as T } from "../../../../@ai-sdk_provider@1.1.3/node_modules/@ai-sdk/provider/dist/index.js";
import { JSONParseError as He, TypeValidationError as Ge } from "../../../../@ai-sdk_provider@1.1.3/node_modules/@ai-sdk/provider/dist/index.js";
import e from "../../../../zod@3.24.4/node_modules/zod/lib/index.js";
var B = Object.defineProperty, S = (t, r) => {
  for (var o in r)
    B(t, o, { get: r[o], enumerable: !0 });
};
function O(t, {
  contentType: r,
  dataStreamVersion: o
}) {
  const a = new Headers(t ?? {});
  return a.has("Content-Type") || a.set("Content-Type", r), a.set("X-Vercel-AI-Data-Stream", o), a;
}
var C = "AI_NoObjectGeneratedError", I = `vercel.ai.error.${C}`, k = Symbol.for(I), P, w = class extends T {
  constructor({
    message: t = "No object generated.",
    cause: r,
    text: o,
    response: a,
    usage: n,
    finishReason: s
  }) {
    super({ name: C, message: t, cause: r }), this[P] = !0, this.text = o, this.response = a, this.usage = n, this.finishReason = s;
  }
  static isInstance(t) {
    return T.hasMarker(t, I);
  }
};
P = k;
var D = e.union([
  e.string(),
  e.instanceof(Uint8Array),
  e.instanceof(ArrayBuffer),
  e.custom(
    // Buffer might not be available in some environments such as CloudFlare:
    (t) => {
      var r, o;
      return (o = (r = globalThis.Buffer) == null ? void 0 : r.isBuffer(t)) != null ? o : !1;
    },
    { message: "Must be a Buffer" }
  )
]), f = e.lazy(
  () => e.union([
    e.null(),
    e.string(),
    e.number(),
    e.boolean(),
    e.record(e.string(), f),
    e.array(f)
  ])
), i = e.record(
  e.string(),
  e.record(e.string(), f)
), H = e.array(
  e.union([
    e.object({ type: e.literal("text"), text: e.string() }),
    e.object({
      type: e.literal("image"),
      data: e.string(),
      mimeType: e.string().optional()
    })
  ])
), E = e.object({
  type: e.literal("text"),
  text: e.string(),
  providerOptions: i.optional(),
  experimental_providerMetadata: i.optional()
}), G = e.object({
  type: e.literal("image"),
  image: e.union([D, e.instanceof(URL)]),
  mimeType: e.string().optional(),
  providerOptions: i.optional(),
  experimental_providerMetadata: i.optional()
}), M = e.object({
  type: e.literal("file"),
  data: e.union([D, e.instanceof(URL)]),
  filename: e.string().optional(),
  mimeType: e.string(),
  providerOptions: i.optional(),
  experimental_providerMetadata: i.optional()
}), X = e.object({
  type: e.literal("reasoning"),
  text: e.string(),
  providerOptions: i.optional(),
  experimental_providerMetadata: i.optional()
}), Y = e.object({
  type: e.literal("redacted-reasoning"),
  data: e.string(),
  providerOptions: i.optional(),
  experimental_providerMetadata: i.optional()
}), $ = e.object({
  type: e.literal("tool-call"),
  toolCallId: e.string(),
  toolName: e.string(),
  args: e.unknown(),
  providerOptions: i.optional(),
  experimental_providerMetadata: i.optional()
}), K = e.object({
  type: e.literal("tool-result"),
  toolCallId: e.string(),
  toolName: e.string(),
  result: e.unknown(),
  content: H.optional(),
  isError: e.boolean().optional(),
  providerOptions: i.optional(),
  experimental_providerMetadata: i.optional()
}), Q = e.object({
  role: e.literal("system"),
  content: e.string(),
  providerOptions: i.optional(),
  experimental_providerMetadata: i.optional()
}), W = e.object({
  role: e.literal("user"),
  content: e.union([
    e.string(),
    e.array(e.union([E, G, M]))
  ]),
  providerOptions: i.optional(),
  experimental_providerMetadata: i.optional()
}), Z = e.object({
  role: e.literal("assistant"),
  content: e.union([
    e.string(),
    e.array(
      e.union([
        E,
        M,
        X,
        Y,
        $
      ])
    )
  ]),
  providerOptions: i.optional(),
  experimental_providerMetadata: i.optional()
}), ee = e.object({
  role: e.literal("tool"),
  content: e.array(K),
  providerOptions: i.optional(),
  experimental_providerMetadata: i.optional()
});
e.union([
  Q,
  W,
  Z,
  ee
]);
var te = "JSON schema:", ae = "You MUST answer with a JSON object that matches the JSON schema above.", re = "You MUST answer with JSON.";
function oe({
  prompt: t,
  schema: r,
  schemaPrefix: o = r != null ? te : void 0,
  schemaSuffix: a = r != null ? ae : re
}) {
  return [
    t != null && t.length > 0 ? t : void 0,
    t != null && t.length > 0 ? "" : void 0,
    // add a newline if prompt is not null
    o,
    r != null ? JSON.stringify(r) : void 0,
    a
  ].filter((n) => n != null).join(`
`);
}
c({ prefix: "aiobj", size: 24 });
c({ prefix: "aiobj", size: 24 });
c({
  prefix: "aitxt",
  size: 24
});
c({
  prefix: "msg",
  size: 24
});
var ne = {};
S(ne, {
  object: () => ie,
  text: () => se
});
var se = () => ({
  type: "text",
  responseFormat: () => ({ type: "text" }),
  injectIntoSystemPrompt({ system: t }) {
    return t;
  },
  parsePartial({ text: t }) {
    return { partial: t };
  },
  parseOutput({ text: t }) {
    return t;
  }
}), ie = ({
  schema: t
}) => {
  const r = V(t);
  return {
    type: "object",
    responseFormat: ({ model: o }) => ({
      type: "json",
      schema: o.supportsStructuredOutputs ? r.jsonSchema : void 0
    }),
    injectIntoSystemPrompt({ system: o, model: a }) {
      return a.supportsStructuredOutputs ? o : oe({
        prompt: o,
        schema: r.jsonSchema
      });
    },
    parsePartial({ text: o }) {
      const a = L(o);
      switch (a.state) {
        case "failed-parse":
        case "undefined-input":
          return;
        case "repaired-parse":
        case "successful-parse":
          return {
            // Note: currently no validation of partial results:
            partial: a.value
          };
        default: {
          const n = a.state;
          throw new Error(`Unsupported parse state: ${n}`);
        }
      }
    },
    parseOutput({ text: o }, a) {
      const n = F({ text: o });
      if (!n.success)
        throw new w({
          message: "No object generated: could not parse the response.",
          cause: n.error,
          text: o,
          response: a.response,
          usage: a.usage,
          finishReason: a.finishReason
        });
      const s = U({
        value: n.value,
        schema: r
      });
      if (!s.success)
        throw new w({
          message: "No object generated: response did not match schema.",
          cause: s.error,
          text: o,
          response: a.response,
          usage: a.usage,
          finishReason: a.finishReason
        });
      return s.value;
    }
  };
};
function N(t, r) {
  const o = t.getReader(), a = r.getReader();
  let n, s, u = !1, d = !1;
  async function y(p) {
    try {
      n == null && (n = o.read());
      const l = await n;
      n = void 0, l.done ? p.close() : p.enqueue(l.value);
    } catch (l) {
      p.error(l);
    }
  }
  async function j(p) {
    try {
      s == null && (s = a.read());
      const l = await s;
      s = void 0, l.done ? p.close() : p.enqueue(l.value);
    } catch (l) {
      p.error(l);
    }
  }
  return new ReadableStream({
    async pull(p) {
      try {
        if (u) {
          await j(p);
          return;
        }
        if (d) {
          await y(p);
          return;
        }
        n == null && (n = o.read()), s == null && (s = a.read());
        const { result: l, reader: q } = await Promise.race([
          n.then((g) => ({ result: g, reader: o })),
          s.then((g) => ({ result: g, reader: a }))
        ]);
        l.done || p.enqueue(l.value), q === o ? (n = void 0, l.done && (await j(p), u = !0)) : (s = void 0, l.done && (d = !0, await y(p)));
      } catch (l) {
        p.error(l);
      }
    },
    cancel() {
      o.cancel(), a.cancel();
    }
  });
}
c({
  prefix: "aitxt",
  size: 24
});
c({
  prefix: "msg",
  size: 24
});
var le = e.object({
  name: e.string(),
  version: e.string()
}).passthrough(), v = e.object({
  _meta: e.optional(e.object({}).passthrough())
}).passthrough(), m = v, pe = e.object({
  method: e.string(),
  params: e.optional(v)
}), ue = e.object({
  experimental: e.optional(e.object({}).passthrough()),
  logging: e.optional(e.object({}).passthrough()),
  prompts: e.optional(
    e.object({
      listChanged: e.optional(e.boolean())
    }).passthrough()
  ),
  resources: e.optional(
    e.object({
      subscribe: e.optional(e.boolean()),
      listChanged: e.optional(e.boolean())
    }).passthrough()
  ),
  tools: e.optional(
    e.object({
      listChanged: e.optional(e.boolean())
    }).passthrough()
  )
}).passthrough();
m.extend({
  protocolVersion: e.string(),
  capabilities: ue,
  serverInfo: le,
  instructions: e.optional(e.string())
});
var ce = m.extend({
  nextCursor: e.optional(e.string())
}), me = e.object({
  name: e.string(),
  description: e.optional(e.string()),
  inputSchema: e.object({
    type: e.literal("object"),
    properties: e.optional(e.object({}).passthrough())
  }).passthrough()
}).passthrough();
ce.extend({
  tools: e.array(me)
});
var de = e.object({
  type: e.literal("text"),
  text: e.string()
}).passthrough(), he = e.object({
  type: e.literal("image"),
  data: e.string().base64(),
  mimeType: e.string()
}).passthrough(), A = e.object({
  /**
   * The URI of this resource.
   */
  uri: e.string(),
  /**
   * The MIME type of this resource, if known.
   */
  mimeType: e.optional(e.string())
}).passthrough(), ge = A.extend({
  text: e.string()
}), fe = A.extend({
  blob: e.string().base64()
}), Se = e.object({
  type: e.literal("resource"),
  resource: e.union([ge, fe])
}).passthrough();
m.extend({
  content: e.array(
    e.union([de, he, Se])
  ),
  isError: e.boolean().default(!1).optional()
}).or(
  m.extend({
    toolResult: e.unknown()
  })
);
var h = "2.0", ve = e.object({
  jsonrpc: e.literal(h),
  id: e.union([e.string(), e.number().int()])
}).merge(pe).strict(), be = e.object({
  jsonrpc: e.literal(h),
  id: e.union([e.string(), e.number().int()]),
  result: m
}).strict(), xe = e.object({
  jsonrpc: e.literal(h),
  id: e.union([e.string(), e.number().int()]),
  error: e.object({
    code: e.number().int(),
    message: e.string(),
    data: e.optional(e.unknown())
  })
}).strict(), ye = e.object({
  jsonrpc: e.literal(h)
}).merge(
  e.object({
    method: e.string(),
    params: e.optional(v)
  })
).strict();
e.union([
  ve,
  ye,
  be,
  xe
]);
var je = {};
S(je, {
  mergeIntoDataStream: () => Re,
  toDataStream: () => Te,
  toDataStreamResponse: () => we
});
function J(t = {}) {
  const r = new TextEncoder();
  let o = "";
  return new TransformStream({
    async start() {
      t.onStart && await t.onStart();
    },
    async transform(a, n) {
      n.enqueue(r.encode(a)), o += a, t.onToken && await t.onToken(a), t.onText && typeof a == "string" && await t.onText(a);
    },
    async flush() {
      t.onCompletion && await t.onCompletion(o), t.onFinal && await t.onFinal(o);
    }
  });
}
function b(t, r) {
  return t.pipeThrough(
    new TransformStream({
      transform: async (o, a) => {
        var n;
        if (typeof o == "string") {
          a.enqueue(o);
          return;
        }
        if ("event" in o) {
          o.event === "on_chat_model_stream" && R(
            (n = o.data) == null ? void 0 : n.chunk,
            a
          );
          return;
        }
        R(o, a);
      }
    })
  ).pipeThrough(J(r)).pipeThrough(new TextDecoderStream()).pipeThrough(
    new TransformStream({
      transform: async (o, a) => {
        a.enqueue(_("text", o));
      }
    })
  );
}
function Te(t, r) {
  return b(t, r).pipeThrough(
    new TextEncoderStream()
  );
}
function we(t, r) {
  var o;
  const a = b(
    t,
    r?.callbacks
  ).pipeThrough(new TextEncoderStream()), n = r?.data, s = r?.init, u = n ? N(n.stream, a) : a;
  return new Response(u, {
    status: (o = s?.status) != null ? o : 200,
    statusText: s?.statusText,
    headers: O(s?.headers, {
      contentType: "text/plain; charset=utf-8",
      dataStreamVersion: "v1"
    })
  });
}
function Re(t, r) {
  r.dataStream.merge(b(t, r.callbacks));
}
function R(t, r) {
  if (typeof t.content == "string")
    r.enqueue(t.content);
  else {
    const o = t.content;
    for (const a of o)
      a.type === "text" && r.enqueue(a.text);
  }
}
var _e = {};
S(_e, {
  mergeIntoDataStream: () => Ie,
  toDataStream: () => Oe,
  toDataStreamResponse: () => Ce
});
function x(t, r) {
  const o = Pe();
  return z(t[Symbol.asyncIterator]()).pipeThrough(
    new TransformStream({
      async transform(a, n) {
        n.enqueue(o(a.delta));
      }
    })
  ).pipeThrough(J(r)).pipeThrough(new TextDecoderStream()).pipeThrough(
    new TransformStream({
      transform: async (a, n) => {
        n.enqueue(_("text", a));
      }
    })
  );
}
function Oe(t, r) {
  return x(t, r).pipeThrough(
    new TextEncoderStream()
  );
}
function Ce(t, r = {}) {
  var o;
  const { init: a, data: n, callbacks: s } = r, u = x(t, s).pipeThrough(
    new TextEncoderStream()
  ), d = n ? N(n.stream, u) : u;
  return new Response(d, {
    status: (o = a?.status) != null ? o : 200,
    statusText: a?.statusText,
    headers: O(a?.headers, {
      contentType: "text/plain; charset=utf-8",
      dataStreamVersion: "v1"
    })
  });
}
function Ie(t, r) {
  r.dataStream.merge(x(t, r.callbacks));
}
function Pe() {
  let t = !0;
  return (r) => (t && (r = r.trimStart(), r && (t = !1)), r);
}
export {
  T as AISDKError,
  He as JSONParseError,
  je as LangChainAdapter,
  _e as LlamaIndexAdapter,
  w as NoObjectGeneratedError,
  ne as Output,
  Ge as TypeValidationError,
  Z as coreAssistantMessageSchema,
  Q as coreSystemMessageSchema,
  ee as coreToolMessageSchema,
  W as coreUserMessageSchema,
  c as createIdGenerator,
  _ as formatDataStreamPart,
  qe as generateId,
  Ue as jsonSchema,
  ze as parseDataStreamPart,
  Ve as processDataStream,
  Le as processTextStream,
  Be as zodSchema
};
//# sourceMappingURL=index.js.map
