'use strict';

var chunk6VROHRAR_cjs = require('./chunk-6VROHRAR.cjs');
var chunkC73WLCY3_cjs = require('./chunk-C73WLCY3.cjs');
var chunkKXCUCBEI_cjs = require('./chunk-KXCUCBEI.cjs');
var schemaCompat = require('@mastra/schema-compat');
var ai = require('ai');
var zod = require('zod');
var zodToJsonSchema = require('zod-to-json-schema');

var MastraLLMV1 = class extends chunkKXCUCBEI_cjs.MastraBase {
  #model;
  #mastra;
  constructor({ model, mastra }) {
    super({ name: "aisdk" });
    this.#model = model;
    if (mastra) {
      this.#mastra = mastra;
      if (mastra.getLogger()) {
        this.__setLogger(this.#mastra.getLogger());
      }
    }
  }
  __registerPrimitives(p) {
    if (p.telemetry) {
      this.__setTelemetry(p.telemetry);
    }
    if (p.logger) {
      this.__setLogger(p.logger);
    }
  }
  __registerMastra(p) {
    this.#mastra = p;
  }
  getProvider() {
    return this.#model.provider;
  }
  getModelId() {
    return this.#model.modelId;
  }
  getModel() {
    return this.#model;
  }
  _applySchemaCompat(schema) {
    const model = this.#model;
    const schemaCompatLayers = [];
    if (model) {
      const modelInfo = {
        modelId: model.modelId,
        supportsStructuredOutputs: model.supportsStructuredOutputs ?? false,
        provider: model.provider
      };
      schemaCompatLayers.push(
        new schemaCompat.OpenAIReasoningSchemaCompatLayer(modelInfo),
        new schemaCompat.OpenAISchemaCompatLayer(modelInfo),
        new schemaCompat.GoogleSchemaCompatLayer(modelInfo),
        new schemaCompat.AnthropicSchemaCompatLayer(modelInfo),
        new schemaCompat.DeepSeekSchemaCompatLayer(modelInfo),
        new schemaCompat.MetaSchemaCompatLayer(modelInfo)
      );
    }
    return schemaCompat.applyCompatLayer({
      schema,
      compatLayers: schemaCompatLayers,
      mode: "aiSdkSchema"
    });
  }
  _startAISpan(model, agentAISpan, name, streaming, options) {
    return agentAISpan?.createChildSpan({
      name,
      type: "llm_generation" /* LLM_GENERATION */,
      input: options.prompt,
      attributes: {
        model: model.modelId,
        provider: model.provider,
        parameters: {
          temperature: options.temperature,
          maxTokens: options.maxTokens,
          topP: options.topP,
          frequencyPenalty: options.frequencyPenalty,
          presencePenalty: options.presencePenalty,
          stop: options.stop
        },
        streaming
      }
    });
  }
  _wrapModel(model, agentAISpan) {
    if (!agentAISpan) {
      return model;
    }
    const wrappedDoGenerate = async (options) => {
      const llmSpan = this._startAISpan(model, agentAISpan, `llm generate: '${model.modelId}'`, false, options);
      try {
        const result = await model.doGenerate(options);
        llmSpan.end({
          output: result.text,
          attributes: {
            usage: result.usage ? {
              promptTokens: result.usage.promptTokens,
              completionTokens: result.usage.completionTokens
            } : void 0
          }
        });
        return result;
      } catch (error) {
        llmSpan.error({ error });
        throw error;
      }
    };
    const wrappedDoStream = async (options) => {
      const llmSpan = this._startAISpan(model, agentAISpan, `llm stream: '${model.modelId}'`, true, options);
      try {
        const result = await model.doStream(options);
        const originalStream = result.stream;
        let finishReason;
        let finalUsage = null;
        const wrappedStream = originalStream.pipeThrough(
          new TransformStream({
            // this gets called on each chunk output
            transform(chunk, controller) {
              if (chunk.type === "finish") {
                finishReason = chunk.finishReason;
                finalUsage = chunk.usage;
              }
              controller.enqueue(chunk);
            },
            // this gets called at the end of the stream
            flush() {
              llmSpan.end({
                attributes: {
                  usage: finalUsage ? {
                    promptTokens: finalUsage.promptTokens,
                    completionTokens: finalUsage.completionTokens,
                    totalTokens: finalUsage.totalTokens
                  } : void 0
                },
                metadata: {
                  finishReason
                }
              });
            }
          })
        );
        return {
          ...result,
          stream: wrappedStream
        };
      } catch (error) {
        llmSpan.error({ error });
        throw error;
      }
    };
    return {
      ...model,
      doGenerate: wrappedDoGenerate,
      doStream: wrappedDoStream
    };
  }
  async __text({
    runId,
    messages,
    maxSteps = 5,
    tools = {},
    temperature,
    toolChoice = "auto",
    onStepFinish,
    experimental_output,
    telemetry,
    threadId,
    resourceId,
    runtimeContext,
    agentAISpan,
    ...rest
  }) {
    const model = this.#model;
    this.logger.debug(`[LLM] - Generating text`, {
      runId,
      messages,
      maxSteps,
      threadId,
      resourceId,
      tools: Object.keys(tools)
    });
    let schema = void 0;
    if (experimental_output) {
      this.logger.debug("[LLM] - Using experimental output", {
        runId
      });
      if (chunk6VROHRAR_cjs.isZodType(experimental_output)) {
        schema = experimental_output;
        if (schema instanceof zod.z.ZodArray) {
          schema = schema._def.type;
        }
        let jsonSchemaToUse;
        if ("toJSONSchema" in zod.z) {
          jsonSchemaToUse = zod.z["toJSONSchema"](schema);
        } else {
          jsonSchemaToUse = zodToJsonSchema.zodToJsonSchema(schema, {
            $refStrategy: "none",
            target: "jsonSchema7"
          });
        }
        schema = ai.jsonSchema(jsonSchemaToUse);
      } else {
        schema = ai.jsonSchema(experimental_output);
      }
    }
    const argsForExecute = {
      ...rest,
      messages,
      model: this._wrapModel(model, agentAISpan),
      temperature,
      tools: {
        ...tools
      },
      toolChoice,
      maxSteps,
      onStepFinish: async (props) => {
        try {
          await onStepFinish?.({ ...props, runId });
        } catch (e) {
          const mastraError = new chunkC73WLCY3_cjs.MastraError(
            {
              id: "LLM_TEXT_ON_STEP_FINISH_CALLBACK_EXECUTION_FAILED",
              domain: "LLM" /* LLM */,
              category: "USER" /* USER */,
              details: {
                modelId: model.modelId,
                modelProvider: model.provider,
                runId: runId ?? "unknown",
                threadId: threadId ?? "unknown",
                resourceId: resourceId ?? "unknown",
                finishReason: props?.finishReason,
                toolCalls: props?.toolCalls ? JSON.stringify(props.toolCalls) : "",
                toolResults: props?.toolResults ? JSON.stringify(props.toolResults) : "",
                usage: props?.usage ? JSON.stringify(props.usage) : ""
              }
            },
            e
          );
          throw mastraError;
        }
        this.logger.debug("[LLM] - Text Step Change:", {
          text: props?.text,
          toolCalls: props?.toolCalls,
          toolResults: props?.toolResults,
          finishReason: props?.finishReason,
          usage: props?.usage,
          runId
        });
        if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
          this.logger.warn("Rate limit approaching, waiting 10 seconds", { runId });
          await chunk6VROHRAR_cjs.delay(10 * 1e3);
        }
      },
      experimental_telemetry: {
        ...this.experimental_telemetry,
        ...telemetry
      },
      experimental_output: schema ? ai.Output.object({
        schema
      }) : void 0
    };
    try {
      const result = await ai.generateText(argsForExecute);
      if (schema && result.finishReason === "stop") {
        result.object = result.experimental_output;
      }
      return result;
    } catch (e) {
      const mastraError = new chunkC73WLCY3_cjs.MastraError(
        {
          id: "LLM_GENERATE_TEXT_AI_SDK_EXECUTION_FAILED",
          domain: "LLM" /* LLM */,
          category: "THIRD_PARTY" /* THIRD_PARTY */,
          details: {
            modelId: model.modelId,
            modelProvider: model.provider,
            runId: runId ?? "unknown",
            threadId: threadId ?? "unknown",
            resourceId: resourceId ?? "unknown"
          }
        },
        e
      );
      throw mastraError;
    }
  }
  async __textObject({
    messages,
    structuredOutput,
    runId,
    telemetry,
    threadId,
    resourceId,
    runtimeContext,
    agentAISpan,
    ...rest
  }) {
    const model = this.#model;
    this.logger.debug(`[LLM] - Generating a text object`, { runId });
    try {
      let output = "object";
      if (structuredOutput instanceof zod.z.ZodArray) {
        output = "array";
        structuredOutput = structuredOutput._def.type;
      }
      const processedSchema = this._applySchemaCompat(structuredOutput);
      const argsForExecute = {
        ...rest,
        messages,
        model: this._wrapModel(model, agentAISpan),
        // @ts-expect-error - output in our implementation can only be object or array
        output,
        schema: processedSchema,
        experimental_telemetry: {
          ...this.experimental_telemetry,
          ...telemetry
        }
      };
      try {
        return await ai.generateObject(argsForExecute);
      } catch (e) {
        const mastraError = new chunkC73WLCY3_cjs.MastraError(
          {
            id: "LLM_GENERATE_OBJECT_AI_SDK_EXECUTION_FAILED",
            domain: "LLM" /* LLM */,
            category: "THIRD_PARTY" /* THIRD_PARTY */,
            details: {
              modelId: model.modelId,
              modelProvider: model.provider,
              runId: runId ?? "unknown",
              threadId: threadId ?? "unknown",
              resourceId: resourceId ?? "unknown"
            }
          },
          e
        );
        throw mastraError;
      }
    } catch (e) {
      if (e instanceof chunkC73WLCY3_cjs.MastraError) {
        throw e;
      }
      const mastraError = new chunkC73WLCY3_cjs.MastraError(
        {
          id: "LLM_GENERATE_OBJECT_AI_SDK_SCHEMA_CONVERSION_FAILED",
          domain: "LLM" /* LLM */,
          category: "USER" /* USER */,
          details: {
            modelId: model.modelId,
            modelProvider: model.provider,
            runId: runId ?? "unknown",
            threadId: threadId ?? "unknown",
            resourceId: resourceId ?? "unknown"
          }
        },
        e
      );
      throw mastraError;
    }
  }
  __stream({
    messages,
    onStepFinish,
    onFinish,
    maxSteps = 5,
    tools = {},
    runId,
    temperature,
    toolChoice = "auto",
    experimental_output,
    telemetry,
    threadId,
    resourceId,
    runtimeContext,
    agentAISpan,
    ...rest
  }) {
    const model = this.#model;
    this.logger.debug(`[LLM] - Streaming text`, {
      runId,
      threadId,
      resourceId,
      messages,
      maxSteps,
      tools: Object.keys(tools || {})
    });
    let schema;
    if (experimental_output) {
      this.logger.debug("[LLM] - Using experimental output", {
        runId
      });
      if (typeof experimental_output.parse === "function") {
        schema = experimental_output;
        if (schema instanceof zod.z.ZodArray) {
          schema = schema._def.type;
        }
      } else {
        schema = ai.jsonSchema(experimental_output);
      }
    }
    const argsForExecute = {
      model: this._wrapModel(model, agentAISpan),
      temperature,
      tools: {
        ...tools
      },
      maxSteps,
      toolChoice,
      onStepFinish: async (props) => {
        try {
          await onStepFinish?.({ ...props, runId });
        } catch (e) {
          const mastraError = new chunkC73WLCY3_cjs.MastraError(
            {
              id: "LLM_STREAM_ON_STEP_FINISH_CALLBACK_EXECUTION_FAILED",
              domain: "LLM" /* LLM */,
              category: "USER" /* USER */,
              details: {
                modelId: model.modelId,
                modelProvider: model.provider,
                runId: runId ?? "unknown",
                threadId: threadId ?? "unknown",
                resourceId: resourceId ?? "unknown",
                finishReason: props?.finishReason,
                toolCalls: props?.toolCalls ? JSON.stringify(props.toolCalls) : "",
                toolResults: props?.toolResults ? JSON.stringify(props.toolResults) : "",
                usage: props?.usage ? JSON.stringify(props.usage) : ""
              }
            },
            e
          );
          this.logger.trackException(mastraError);
          throw mastraError;
        }
        this.logger.debug("[LLM] - Stream Step Change:", {
          text: props?.text,
          toolCalls: props?.toolCalls,
          toolResults: props?.toolResults,
          finishReason: props?.finishReason,
          usage: props?.usage,
          runId
        });
        if (props?.response?.headers?.["x-ratelimit-remaining-tokens"] && parseInt(props?.response?.headers?.["x-ratelimit-remaining-tokens"], 10) < 2e3) {
          this.logger.warn("Rate limit approaching, waiting 10 seconds", { runId });
          await chunk6VROHRAR_cjs.delay(10 * 1e3);
        }
      },
      onFinish: async (props) => {
        try {
          await onFinish?.({ ...props, runId });
        } catch (e) {
          const mastraError = new chunkC73WLCY3_cjs.MastraError(
            {
              id: "LLM_STREAM_ON_FINISH_CALLBACK_EXECUTION_FAILED",
              domain: "LLM" /* LLM */,
              category: "USER" /* USER */,
              details: {
                modelId: model.modelId,
                modelProvider: model.provider,
                runId: runId ?? "unknown",
                threadId: threadId ?? "unknown",
                resourceId: resourceId ?? "unknown",
                finishReason: props?.finishReason,
                toolCalls: props?.toolCalls ? JSON.stringify(props.toolCalls) : "",
                toolResults: props?.toolResults ? JSON.stringify(props.toolResults) : "",
                usage: props?.usage ? JSON.stringify(props.usage) : ""
              }
            },
            e
          );
          this.logger.trackException(mastraError);
          throw mastraError;
        }
        this.logger.debug("[LLM] - Stream Finished:", {
          text: props?.text,
          toolCalls: props?.toolCalls,
          toolResults: props?.toolResults,
          finishReason: props?.finishReason,
          usage: props?.usage,
          runId,
          threadId,
          resourceId
        });
      },
      ...rest,
      messages,
      experimental_telemetry: {
        ...this.experimental_telemetry,
        ...telemetry
      },
      experimental_output: schema ? ai.Output.object({
        schema
      }) : void 0
    };
    try {
      return ai.streamText(argsForExecute);
    } catch (e) {
      const mastraError = new chunkC73WLCY3_cjs.MastraError(
        {
          id: "LLM_STREAM_TEXT_AI_SDK_EXECUTION_FAILED",
          domain: "LLM" /* LLM */,
          category: "THIRD_PARTY" /* THIRD_PARTY */,
          details: {
            modelId: model.modelId,
            modelProvider: model.provider,
            runId: runId ?? "unknown",
            threadId: threadId ?? "unknown",
            resourceId: resourceId ?? "unknown"
          }
        },
        e
      );
      throw mastraError;
    }
  }
  __streamObject({
    messages,
    runId,
    runtimeContext,
    threadId,
    resourceId,
    onFinish,
    structuredOutput,
    telemetry,
    agentAISpan,
    ...rest
  }) {
    const model = this.#model;
    this.logger.debug(`[LLM] - Streaming structured output`, {
      runId,
      messages
    });
    try {
      let output = "object";
      if (structuredOutput instanceof zod.z.ZodArray) {
        output = "array";
        structuredOutput = structuredOutput._def.type;
      }
      const processedSchema = this._applySchemaCompat(structuredOutput);
      const argsForExecute = {
        ...rest,
        model: this._wrapModel(model, agentAISpan),
        onFinish: async (props) => {
          try {
            await onFinish?.({ ...props, runId });
          } catch (e) {
            const mastraError = new chunkC73WLCY3_cjs.MastraError(
              {
                id: "LLM_STREAM_OBJECT_ON_FINISH_CALLBACK_EXECUTION_FAILED",
                domain: "LLM" /* LLM */,
                category: "USER" /* USER */,
                details: {
                  modelId: model.modelId,
                  modelProvider: model.provider,
                  runId: runId ?? "unknown",
                  threadId: threadId ?? "unknown",
                  resourceId: resourceId ?? "unknown",
                  toolCalls: "",
                  toolResults: "",
                  finishReason: "",
                  usage: props?.usage ? JSON.stringify(props.usage) : ""
                }
              },
              e
            );
            this.logger.trackException(mastraError);
            throw mastraError;
          }
          this.logger.debug("[LLM] - Object Stream Finished:", {
            usage: props?.usage,
            runId,
            threadId,
            resourceId
          });
        },
        messages,
        // @ts-expect-error - output in our implementation can only be object or array
        output,
        experimental_telemetry: {
          ...this.experimental_telemetry,
          ...telemetry
        },
        schema: processedSchema
      };
      try {
        return ai.streamObject(argsForExecute);
      } catch (e) {
        const mastraError = new chunkC73WLCY3_cjs.MastraError(
          {
            id: "LLM_STREAM_OBJECT_AI_SDK_EXECUTION_FAILED",
            domain: "LLM" /* LLM */,
            category: "THIRD_PARTY" /* THIRD_PARTY */,
            details: {
              modelId: model.modelId,
              modelProvider: model.provider,
              runId: runId ?? "unknown",
              threadId: threadId ?? "unknown",
              resourceId: resourceId ?? "unknown"
            }
          },
          e
        );
        throw mastraError;
      }
    } catch (e) {
      if (e instanceof chunkC73WLCY3_cjs.MastraError) {
        throw e;
      }
      const mastraError = new chunkC73WLCY3_cjs.MastraError(
        {
          id: "LLM_STREAM_OBJECT_AI_SDK_SCHEMA_CONVERSION_FAILED",
          domain: "LLM" /* LLM */,
          category: "USER" /* USER */,
          details: {
            modelId: model.modelId,
            modelProvider: model.provider,
            runId: runId ?? "unknown",
            threadId: threadId ?? "unknown",
            resourceId: resourceId ?? "unknown"
          }
        },
        e
      );
      throw mastraError;
    }
  }
  convertToMessages(messages) {
    if (Array.isArray(messages)) {
      return messages.map((m) => {
        if (typeof m === "string") {
          return {
            role: "user",
            content: m
          };
        }
        return m;
      });
    }
    return [
      {
        role: "user",
        content: messages
      }
    ];
  }
  async generate(messages, {
    output,
    ...rest
  }) {
    const msgs = this.convertToMessages(messages);
    if (!output) {
      const { maxSteps, onStepFinish, ...textOptions } = rest;
      return await this.__text({
        messages: msgs,
        maxSteps,
        onStepFinish,
        ...textOptions
      });
    }
    return await this.__textObject({
      messages: msgs,
      structuredOutput: output,
      ...rest
    });
  }
  stream(messages, {
    maxSteps = 5,
    output,
    onFinish,
    ...rest
  }) {
    const msgs = this.convertToMessages(messages);
    if (!output) {
      return this.__stream({
        messages: msgs,
        maxSteps,
        onFinish,
        ...rest
      });
    }
    return this.__streamObject({
      messages: msgs,
      structuredOutput: output,
      onFinish,
      ...rest
    });
  }
};

exports.MastraLLMV1 = MastraLLMV1;
//# sourceMappingURL=chunk-VBAWR62U.cjs.map
//# sourceMappingURL=chunk-VBAWR62U.cjs.map