import { OpenAICompatibleImageModel } from "./index-BUBTSVFi.js";
import { a as createProviderToolFactoryWithOutputSchema, w as withoutTrailingSlash, N as NoSuchModelError, b as lazySchema, g as generateId, k as withUserAgentSuffix, z as zodSchema, p as parseProviderOptions, f as postJsonToApi, e as combineHeaders, h as createJsonResponseHandler, A as APICallError, J as extractResponseHeaders, K as safeParseJSON, i as createEventSourceResponseHandler, j as loadApiKey, n as convertToBase64, U as UnsupportedFunctionalityError, o as createJsonErrorResponseHandler, v as validateTypes } from "./index-BNPaYB6_.js";
import { aB as object, aM as unknown, aD as string, aC as array, aE as number, aK as union, aO as any, aJ as boolean, aF as _enum, aI as literal, aG as discriminatedUnion, aN as record } from "./index-P1RimRZR.js";
function convertToXaiChatMessages(prompt) {
  var _a;
  const messages = [];
  const warnings = [];
  for (const { role, content } of prompt) {
    switch (role) {
      case "system": {
        messages.push({ role: "system", content });
        break;
      }
      case "user": {
        if (content.length === 1 && content[0].type === "text") {
          messages.push({ role: "user", content: content[0].text });
          break;
        }
        messages.push({
          role: "user",
          content: content.map((part) => {
            switch (part.type) {
              case "text": {
                return { type: "text", text: part.text };
              }
              case "file": {
                if (part.mediaType.startsWith("image/")) {
                  const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
                  return {
                    type: "image_url",
                    image_url: {
                      url: part.data instanceof URL ? part.data.toString() : `data:${mediaType};base64,${convertToBase64(part.data)}`
                    }
                  };
                } else {
                  throw new UnsupportedFunctionalityError({
                    functionality: `file part media type ${part.mediaType}`
                  });
                }
              }
            }
          })
        });
        break;
      }
      case "assistant": {
        let text = "";
        const toolCalls = [];
        for (const part of content) {
          switch (part.type) {
            case "text": {
              text += part.text;
              break;
            }
            case "tool-call": {
              toolCalls.push({
                id: part.toolCallId,
                type: "function",
                function: {
                  name: part.toolName,
                  arguments: JSON.stringify(part.input)
                }
              });
              break;
            }
          }
        }
        messages.push({
          role: "assistant",
          content: text,
          tool_calls: toolCalls.length > 0 ? toolCalls : void 0
        });
        break;
      }
      case "tool": {
        for (const toolResponse of content) {
          if (toolResponse.type === "tool-approval-response") {
            continue;
          }
          const output = toolResponse.output;
          let contentValue;
          switch (output.type) {
            case "text":
            case "error-text":
              contentValue = output.value;
              break;
            case "execution-denied":
              contentValue = (_a = output.reason) != null ? _a : "Tool execution denied.";
              break;
            case "content":
            case "json":
            case "error-json":
              contentValue = JSON.stringify(output.value);
              break;
          }
          messages.push({
            role: "tool",
            tool_call_id: toolResponse.toolCallId,
            content: contentValue
          });
        }
        break;
      }
      default: {
        const _exhaustiveCheck = role;
        throw new Error(`Unsupported role: ${_exhaustiveCheck}`);
      }
    }
  }
  return { messages, warnings };
}
function convertXaiChatUsage(usage) {
  var _a, _b, _c, _d;
  const cacheReadTokens = (_b = (_a = usage.prompt_tokens_details) == null ? void 0 : _a.cached_tokens) != null ? _b : 0;
  const reasoningTokens = (_d = (_c = usage.completion_tokens_details) == null ? void 0 : _c.reasoning_tokens) != null ? _d : 0;
  return {
    inputTokens: {
      total: usage.prompt_tokens,
      noCache: usage.prompt_tokens - cacheReadTokens,
      cacheRead: cacheReadTokens,
      cacheWrite: void 0
    },
    outputTokens: {
      total: usage.completion_tokens,
      text: usage.completion_tokens - reasoningTokens,
      reasoning: reasoningTokens
    },
    raw: usage
  };
}
function getResponseMetadata({
  id,
  model,
  created,
  created_at
}) {
  const unixTime = created != null ? created : created_at;
  return {
    id: id != null ? id : void 0,
    modelId: model != null ? model : void 0,
    timestamp: unixTime != null ? new Date(unixTime * 1e3) : void 0
  };
}
function mapXaiFinishReason(finishReason) {
  switch (finishReason) {
    case "stop":
      return "stop";
    case "length":
      return "length";
    case "tool_calls":
    case "function_call":
      return "tool-calls";
    case "content_filter":
      return "content-filter";
    default:
      return "other";
  }
}
var webSourceSchema = object({
  type: literal("web"),
  country: string().length(2).optional(),
  excludedWebsites: array(string()).max(5).optional(),
  allowedWebsites: array(string()).max(5).optional(),
  safeSearch: boolean().optional()
});
var xSourceSchema = object({
  type: literal("x"),
  excludedXHandles: array(string()).optional(),
  includedXHandles: array(string()).optional(),
  postFavoriteCount: number().int().optional(),
  postViewCount: number().int().optional(),
  /**
   * @deprecated use `includedXHandles` instead
   */
  xHandles: array(string()).optional()
});
var newsSourceSchema = object({
  type: literal("news"),
  country: string().length(2).optional(),
  excludedWebsites: array(string()).max(5).optional(),
  safeSearch: boolean().optional()
});
var rssSourceSchema = object({
  type: literal("rss"),
  links: array(string().url()).max(1)
  // currently only supports one RSS link
});
var searchSourceSchema = discriminatedUnion("type", [
  webSourceSchema,
  xSourceSchema,
  newsSourceSchema,
  rssSourceSchema
]);
var xaiProviderOptions = object({
  reasoningEffort: _enum(["low", "high"]).optional(),
  /**
   * Whether to enable parallel function calling during tool use.
   * When true, the model can call multiple functions in parallel.
   * When false, the model will call functions sequentially.
   * Defaults to true.
   */
  parallel_function_calling: boolean().optional(),
  searchParameters: object({
    /**
     * search mode preference
     * - "off": disables search completely
     * - "auto": model decides whether to search (default)
     * - "on": always enables search
     */
    mode: _enum(["off", "auto", "on"]),
    /**
     * whether to return citations in the response
     * defaults to true
     */
    returnCitations: boolean().optional(),
    /**
     * start date for search data (ISO8601 format: YYYY-MM-DD)
     */
    fromDate: string().optional(),
    /**
     * end date for search data (ISO8601 format: YYYY-MM-DD)
     */
    toDate: string().optional(),
    /**
     * maximum number of search results to consider
     * defaults to 20
     */
    maxSearchResults: number().min(1).max(50).optional(),
    /**
     * data sources to search from.
     * defaults to [{ type: 'web' }, { type: 'x' }] if not specified.
     *
     * @example
     * sources: [{ type: 'web', country: 'US' }, { type: 'x' }]
     */
    sources: array(searchSourceSchema).optional()
  }).optional()
});
var xaiErrorDataSchema = object({
  error: object({
    message: string(),
    type: string().nullish(),
    param: any().nullish(),
    code: union([string(), number()]).nullish()
  })
});
var xaiFailedResponseHandler = createJsonErrorResponseHandler({
  errorSchema: xaiErrorDataSchema,
  errorToMessage: (data) => data.error.message
});
function prepareTools({
  tools,
  toolChoice
}) {
  tools = (tools == null ? void 0 : tools.length) ? tools : void 0;
  const toolWarnings = [];
  if (tools == null) {
    return { tools: void 0, toolChoice: void 0, toolWarnings };
  }
  const xaiTools2 = [];
  for (const tool of tools) {
    if (tool.type === "provider") {
      toolWarnings.push({
        type: "unsupported",
        feature: `provider-defined tool ${tool.name}`
      });
    } else {
      xaiTools2.push({
        type: "function",
        function: {
          name: tool.name,
          description: tool.description,
          parameters: tool.inputSchema
        }
      });
    }
  }
  if (toolChoice == null) {
    return { tools: xaiTools2, toolChoice: void 0, toolWarnings };
  }
  const type = toolChoice.type;
  switch (type) {
    case "auto":
    case "none":
      return { tools: xaiTools2, toolChoice: type, toolWarnings };
    case "required":
      return { tools: xaiTools2, toolChoice: "required", toolWarnings };
    case "tool":
      return {
        tools: xaiTools2,
        toolChoice: {
          type: "function",
          function: { name: toolChoice.toolName }
        },
        toolWarnings
      };
    default: {
      const _exhaustiveCheck = type;
      throw new UnsupportedFunctionalityError({
        functionality: `tool choice type: ${_exhaustiveCheck}`
      });
    }
  }
}
var XaiChatLanguageModel = class {
  constructor(modelId, config) {
    this.specificationVersion = "v3";
    this.supportedUrls = {
      "image/*": [/^https?:\/\/.*$/]
    };
    this.modelId = modelId;
    this.config = config;
  }
  get provider() {
    return this.config.provider;
  }
  async getArgs({
    prompt,
    maxOutputTokens,
    temperature,
    topP,
    topK,
    frequencyPenalty,
    presencePenalty,
    stopSequences,
    seed,
    responseFormat,
    providerOptions,
    tools,
    toolChoice
  }) {
    var _a, _b, _c;
    const warnings = [];
    const options = (_a = await parseProviderOptions({
      provider: "xai",
      providerOptions,
      schema: xaiProviderOptions
    })) != null ? _a : {};
    if (topK != null) {
      warnings.push({ type: "unsupported", feature: "topK" });
    }
    if (frequencyPenalty != null) {
      warnings.push({ type: "unsupported", feature: "frequencyPenalty" });
    }
    if (presencePenalty != null) {
      warnings.push({ type: "unsupported", feature: "presencePenalty" });
    }
    if (stopSequences != null) {
      warnings.push({ type: "unsupported", feature: "stopSequences" });
    }
    const { messages, warnings: messageWarnings } = convertToXaiChatMessages(prompt);
    warnings.push(...messageWarnings);
    const {
      tools: xaiTools2,
      toolChoice: xaiToolChoice,
      toolWarnings
    } = prepareTools({
      tools,
      toolChoice
    });
    warnings.push(...toolWarnings);
    const baseArgs = {
      // model id
      model: this.modelId,
      // standard generation settings
      max_completion_tokens: maxOutputTokens,
      temperature,
      top_p: topP,
      seed,
      reasoning_effort: options.reasoningEffort,
      // parallel function calling
      parallel_function_calling: options.parallel_function_calling,
      // response format
      response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? responseFormat.schema != null ? {
        type: "json_schema",
        json_schema: {
          name: (_b = responseFormat.name) != null ? _b : "response",
          schema: responseFormat.schema,
          strict: true
        }
      } : { type: "json_object" } : void 0,
      // search parameters
      search_parameters: options.searchParameters ? {
        mode: options.searchParameters.mode,
        return_citations: options.searchParameters.returnCitations,
        from_date: options.searchParameters.fromDate,
        to_date: options.searchParameters.toDate,
        max_search_results: options.searchParameters.maxSearchResults,
        sources: (_c = options.searchParameters.sources) == null ? void 0 : _c.map((source) => {
          var _a2;
          return {
            type: source.type,
            ...source.type === "web" && {
              country: source.country,
              excluded_websites: source.excludedWebsites,
              allowed_websites: source.allowedWebsites,
              safe_search: source.safeSearch
            },
            ...source.type === "x" && {
              excluded_x_handles: source.excludedXHandles,
              included_x_handles: (_a2 = source.includedXHandles) != null ? _a2 : source.xHandles,
              post_favorite_count: source.postFavoriteCount,
              post_view_count: source.postViewCount
            },
            ...source.type === "news" && {
              country: source.country,
              excluded_websites: source.excludedWebsites,
              safe_search: source.safeSearch
            },
            ...source.type === "rss" && {
              links: source.links
            }
          };
        })
      } : void 0,
      // messages in xai format
      messages,
      // tools in xai format
      tools: xaiTools2,
      tool_choice: xaiToolChoice
    };
    return {
      args: baseArgs,
      warnings
    };
  }
  async doGenerate(options) {
    var _a, _b;
    const { args: body, warnings } = await this.getArgs(options);
    const url = `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`;
    const {
      responseHeaders,
      value: response,
      rawValue: rawResponse
    } = await postJsonToApi({
      url,
      headers: combineHeaders(this.config.headers(), options.headers),
      body,
      failedResponseHandler: xaiFailedResponseHandler,
      successfulResponseHandler: createJsonResponseHandler(
        xaiChatResponseSchema
      ),
      abortSignal: options.abortSignal,
      fetch: this.config.fetch
    });
    if (response.error != null) {
      throw new APICallError({
        message: response.error,
        url,
        requestBodyValues: body,
        statusCode: 200,
        responseHeaders,
        responseBody: JSON.stringify(rawResponse),
        isRetryable: response.code === "The service is currently unavailable"
      });
    }
    const choice = response.choices[0];
    const content = [];
    if (choice.message.content != null && choice.message.content.length > 0) {
      let text = choice.message.content;
      const lastMessage = body.messages[body.messages.length - 1];
      if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant" && text === lastMessage.content) {
        text = "";
      }
      if (text.length > 0) {
        content.push({ type: "text", text });
      }
    }
    if (choice.message.reasoning_content != null && choice.message.reasoning_content.length > 0) {
      content.push({
        type: "reasoning",
        text: choice.message.reasoning_content
      });
    }
    if (choice.message.tool_calls != null) {
      for (const toolCall of choice.message.tool_calls) {
        content.push({
          type: "tool-call",
          toolCallId: toolCall.id,
          toolName: toolCall.function.name,
          input: toolCall.function.arguments
        });
      }
    }
    if (response.citations != null) {
      for (const url2 of response.citations) {
        content.push({
          type: "source",
          sourceType: "url",
          id: this.config.generateId(),
          url: url2
        });
      }
    }
    return {
      content,
      finishReason: {
        unified: mapXaiFinishReason(choice.finish_reason),
        raw: (_b = choice.finish_reason) != null ? _b : void 0
      },
      usage: convertXaiChatUsage(response.usage),
      // defined when there is no error
      request: { body },
      response: {
        ...getResponseMetadata(response),
        headers: responseHeaders,
        body: rawResponse
      },
      warnings
    };
  }
  async doStream(options) {
    var _a;
    const { args, warnings } = await this.getArgs(options);
    const body = {
      ...args,
      stream: true,
      stream_options: {
        include_usage: true
      }
    };
    const url = `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/chat/completions`;
    const { responseHeaders, value: response } = await postJsonToApi({
      url,
      headers: combineHeaders(this.config.headers(), options.headers),
      body,
      failedResponseHandler: xaiFailedResponseHandler,
      successfulResponseHandler: async ({ response: response2 }) => {
        const responseHeaders2 = extractResponseHeaders(response2);
        const contentType = response2.headers.get("content-type");
        if (contentType == null ? void 0 : contentType.includes("application/json")) {
          const responseBody = await response2.text();
          const parsedError = await safeParseJSON({
            text: responseBody,
            schema: xaiStreamErrorSchema
          });
          if (parsedError.success) {
            throw new APICallError({
              message: parsedError.value.error,
              url,
              requestBodyValues: body,
              statusCode: 200,
              responseHeaders: responseHeaders2,
              responseBody,
              isRetryable: parsedError.value.code === "The service is currently unavailable"
            });
          }
          throw new APICallError({
            message: "Invalid JSON response",
            url,
            requestBodyValues: body,
            statusCode: 200,
            responseHeaders: responseHeaders2,
            responseBody
          });
        }
        return createEventSourceResponseHandler(xaiChatChunkSchema)({
          response: response2,
          url,
          requestBodyValues: body
        });
      },
      abortSignal: options.abortSignal,
      fetch: this.config.fetch
    });
    let finishReason = {
      unified: "other",
      raw: void 0
    };
    let usage = void 0;
    let isFirstChunk = true;
    const contentBlocks = {};
    const lastReasoningDeltas = {};
    let activeReasoningBlockId = void 0;
    const self = this;
    return {
      stream: response.pipeThrough(
        new TransformStream({
          start(controller) {
            controller.enqueue({ type: "stream-start", warnings });
          },
          transform(chunk, controller) {
            if (options.includeRawChunks) {
              controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
            }
            if (!chunk.success) {
              controller.enqueue({ type: "error", error: chunk.error });
              return;
            }
            const value = chunk.value;
            if (isFirstChunk) {
              controller.enqueue({
                type: "response-metadata",
                ...getResponseMetadata(value)
              });
              isFirstChunk = false;
            }
            if (value.citations != null) {
              for (const url2 of value.citations) {
                controller.enqueue({
                  type: "source",
                  sourceType: "url",
                  id: self.config.generateId(),
                  url: url2
                });
              }
            }
            if (value.usage != null) {
              usage = convertXaiChatUsage(value.usage);
            }
            const choice = value.choices[0];
            if ((choice == null ? void 0 : choice.finish_reason) != null) {
              finishReason = {
                unified: mapXaiFinishReason(choice.finish_reason),
                raw: choice.finish_reason
              };
            }
            if ((choice == null ? void 0 : choice.delta) == null) {
              return;
            }
            const delta = choice.delta;
            const choiceIndex = choice.index;
            if (delta.content != null && delta.content.length > 0) {
              const textContent = delta.content;
              if (activeReasoningBlockId != null && !contentBlocks[activeReasoningBlockId].ended) {
                controller.enqueue({
                  type: "reasoning-end",
                  id: activeReasoningBlockId
                });
                contentBlocks[activeReasoningBlockId].ended = true;
                activeReasoningBlockId = void 0;
              }
              const lastMessage = body.messages[body.messages.length - 1];
              if ((lastMessage == null ? void 0 : lastMessage.role) === "assistant" && textContent === lastMessage.content) {
                return;
              }
              const blockId = `text-${value.id || choiceIndex}`;
              if (contentBlocks[blockId] == null) {
                contentBlocks[blockId] = { type: "text", ended: false };
                controller.enqueue({
                  type: "text-start",
                  id: blockId
                });
              }
              controller.enqueue({
                type: "text-delta",
                id: blockId,
                delta: textContent
              });
            }
            if (delta.reasoning_content != null && delta.reasoning_content.length > 0) {
              const blockId = `reasoning-${value.id || choiceIndex}`;
              if (lastReasoningDeltas[blockId] === delta.reasoning_content) {
                return;
              }
              lastReasoningDeltas[blockId] = delta.reasoning_content;
              if (contentBlocks[blockId] == null) {
                contentBlocks[blockId] = { type: "reasoning", ended: false };
                activeReasoningBlockId = blockId;
                controller.enqueue({
                  type: "reasoning-start",
                  id: blockId
                });
              }
              controller.enqueue({
                type: "reasoning-delta",
                id: blockId,
                delta: delta.reasoning_content
              });
            }
            if (delta.tool_calls != null) {
              if (activeReasoningBlockId != null && !contentBlocks[activeReasoningBlockId].ended) {
                controller.enqueue({
                  type: "reasoning-end",
                  id: activeReasoningBlockId
                });
                contentBlocks[activeReasoningBlockId].ended = true;
                activeReasoningBlockId = void 0;
              }
              for (const toolCall of delta.tool_calls) {
                const toolCallId = toolCall.id;
                controller.enqueue({
                  type: "tool-input-start",
                  id: toolCallId,
                  toolName: toolCall.function.name
                });
                controller.enqueue({
                  type: "tool-input-delta",
                  id: toolCallId,
                  delta: toolCall.function.arguments
                });
                controller.enqueue({
                  type: "tool-input-end",
                  id: toolCallId
                });
                controller.enqueue({
                  type: "tool-call",
                  toolCallId,
                  toolName: toolCall.function.name,
                  input: toolCall.function.arguments
                });
              }
            }
          },
          flush(controller) {
            for (const [blockId, block] of Object.entries(contentBlocks)) {
              if (!block.ended) {
                controller.enqueue({
                  type: block.type === "text" ? "text-end" : "reasoning-end",
                  id: blockId
                });
              }
            }
            controller.enqueue({ type: "finish", finishReason, usage });
          }
        })
      ),
      request: { body },
      response: { headers: responseHeaders }
    };
  }
};
var xaiUsageSchema = object({
  prompt_tokens: number(),
  completion_tokens: number(),
  total_tokens: number(),
  prompt_tokens_details: object({
    text_tokens: number().nullish(),
    audio_tokens: number().nullish(),
    image_tokens: number().nullish(),
    cached_tokens: number().nullish()
  }).nullish(),
  completion_tokens_details: object({
    reasoning_tokens: number().nullish(),
    audio_tokens: number().nullish(),
    accepted_prediction_tokens: number().nullish(),
    rejected_prediction_tokens: number().nullish()
  }).nullish()
});
var xaiChatResponseSchema = object({
  id: string().nullish(),
  created: number().nullish(),
  model: string().nullish(),
  choices: array(
    object({
      message: object({
        role: literal("assistant"),
        content: string().nullish(),
        reasoning_content: string().nullish(),
        tool_calls: array(
          object({
            id: string(),
            type: literal("function"),
            function: object({
              name: string(),
              arguments: string()
            })
          })
        ).nullish()
      }),
      index: number(),
      finish_reason: string().nullish()
    })
  ).nullish(),
  object: literal("chat.completion").nullish(),
  usage: xaiUsageSchema.nullish(),
  citations: array(string().url()).nullish(),
  code: string().nullish(),
  error: string().nullish()
});
var xaiChatChunkSchema = object({
  id: string().nullish(),
  created: number().nullish(),
  model: string().nullish(),
  choices: array(
    object({
      delta: object({
        role: _enum(["assistant"]).optional(),
        content: string().nullish(),
        reasoning_content: string().nullish(),
        tool_calls: array(
          object({
            id: string(),
            type: literal("function"),
            function: object({
              name: string(),
              arguments: string()
            })
          })
        ).nullish()
      }),
      finish_reason: string().nullish(),
      index: number()
    })
  ),
  usage: xaiUsageSchema.nullish(),
  citations: array(string().url()).nullish()
});
var xaiStreamErrorSchema = object({
  code: string(),
  error: string()
});
async function convertToXaiResponsesInput({
  prompt
}) {
  var _a, _b, _c, _d, _e;
  const input = [];
  const inputWarnings = [];
  for (const message of prompt) {
    switch (message.role) {
      case "system": {
        input.push({
          role: "system",
          content: message.content
        });
        break;
      }
      case "user": {
        const contentParts = [];
        for (const block of message.content) {
          switch (block.type) {
            case "text": {
              contentParts.push({ type: "input_text", text: block.text });
              break;
            }
            case "file": {
              if (block.mediaType.startsWith("image/")) {
                const mediaType = block.mediaType === "image/*" ? "image/jpeg" : block.mediaType;
                const imageUrl = block.data instanceof URL ? block.data.toString() : `data:${mediaType};base64,${convertToBase64(block.data)}`;
                contentParts.push({ type: "input_image", image_url: imageUrl });
              } else {
                throw new UnsupportedFunctionalityError({
                  functionality: `file part media type ${block.mediaType}`
                });
              }
              break;
            }
            default: {
              inputWarnings.push({
                type: "other",
                message: "xAI Responses API does not support this content type in user messages"
              });
            }
          }
        }
        input.push({
          role: "user",
          content: contentParts
        });
        break;
      }
      case "assistant": {
        for (const part of message.content) {
          switch (part.type) {
            case "text": {
              const id = typeof ((_b = (_a = part.providerOptions) == null ? void 0 : _a.xai) == null ? void 0 : _b.itemId) === "string" ? part.providerOptions.xai.itemId : void 0;
              input.push({
                role: "assistant",
                content: part.text,
                id
              });
              break;
            }
            case "tool-call": {
              if (part.providerExecuted) {
                break;
              }
              const id = typeof ((_d = (_c = part.providerOptions) == null ? void 0 : _c.xai) == null ? void 0 : _d.itemId) === "string" ? part.providerOptions.xai.itemId : void 0;
              input.push({
                type: "function_call",
                id: id != null ? id : part.toolCallId,
                call_id: part.toolCallId,
                name: part.toolName,
                arguments: JSON.stringify(part.input),
                status: "completed"
              });
              break;
            }
            case "tool-result": {
              break;
            }
            case "reasoning":
            case "file": {
              inputWarnings.push({
                type: "other",
                message: `xAI Responses API does not support ${part.type} in assistant messages`
              });
              break;
            }
            default: {
              inputWarnings.push({
                type: "other",
                message: "xAI Responses API does not support this content type in assistant messages"
              });
            }
          }
        }
        break;
      }
      case "tool": {
        for (const part of message.content) {
          if (part.type === "tool-approval-response") {
            continue;
          }
          const output = part.output;
          let outputValue;
          switch (output.type) {
            case "text":
            case "error-text":
              outputValue = output.value;
              break;
            case "execution-denied":
              outputValue = (_e = output.reason) != null ? _e : "tool execution denied";
              break;
            case "json":
            case "error-json":
              outputValue = JSON.stringify(output.value);
              break;
            case "content":
              outputValue = output.value.map((item) => {
                if (item.type === "text") {
                  return item.text;
                }
                return "";
              }).join("");
              break;
            default: {
              outputValue = "";
            }
          }
          input.push({
            type: "function_call_output",
            call_id: part.toolCallId,
            output: outputValue
          });
        }
        break;
      }
      default: {
        inputWarnings.push({
          type: "other",
          message: "unsupported message role"
        });
      }
    }
  }
  return { input, inputWarnings };
}
function convertXaiResponsesUsage(usage) {
  var _a, _b, _c, _d;
  const cacheReadTokens = (_b = (_a = usage.input_tokens_details) == null ? void 0 : _a.cached_tokens) != null ? _b : 0;
  const reasoningTokens = (_d = (_c = usage.output_tokens_details) == null ? void 0 : _c.reasoning_tokens) != null ? _d : 0;
  return {
    inputTokens: {
      total: usage.input_tokens,
      noCache: usage.input_tokens - cacheReadTokens,
      cacheRead: cacheReadTokens,
      cacheWrite: void 0
    },
    outputTokens: {
      total: usage.output_tokens,
      text: usage.output_tokens - reasoningTokens,
      reasoning: reasoningTokens
    },
    raw: usage
  };
}
function mapXaiResponsesFinishReason(finishReason) {
  switch (finishReason) {
    case "stop":
    case "completed":
      return "stop";
    case "length":
      return "length";
    case "tool_calls":
    case "function_call":
      return "tool-calls";
    case "content_filter":
      return "content-filter";
    default:
      return "other";
  }
}
var annotationSchema = union([
  object({
    type: literal("url_citation"),
    url: string(),
    title: string().optional()
  }),
  object({
    type: string()
  })
]);
var messageContentPartSchema = object({
  type: string(),
  text: string().optional(),
  logprobs: array(any()).optional(),
  annotations: array(annotationSchema).optional()
});
var reasoningSummaryPartSchema = object({
  type: string(),
  text: string()
});
var toolCallSchema = object({
  name: string().optional(),
  arguments: string().optional(),
  input: string().optional(),
  call_id: string().optional(),
  id: string(),
  status: string(),
  action: any().optional()
});
var mcpCallSchema = object({
  name: string().optional(),
  arguments: string().optional(),
  output: string().optional(),
  error: string().optional(),
  id: string(),
  status: string(),
  server_label: string().optional()
});
var outputItemSchema = discriminatedUnion("type", [
  object({
    type: literal("web_search_call"),
    ...toolCallSchema.shape
  }),
  object({
    type: literal("x_search_call"),
    ...toolCallSchema.shape
  }),
  object({
    type: literal("code_interpreter_call"),
    ...toolCallSchema.shape
  }),
  object({
    type: literal("code_execution_call"),
    ...toolCallSchema.shape
  }),
  object({
    type: literal("view_image_call"),
    ...toolCallSchema.shape
  }),
  object({
    type: literal("view_x_video_call"),
    ...toolCallSchema.shape
  }),
  object({
    type: literal("file_search_call"),
    id: string(),
    status: string(),
    queries: array(string()).optional(),
    results: array(
      object({
        file_id: string(),
        filename: string(),
        score: number(),
        text: string()
      })
    ).nullish()
  }),
  object({
    type: literal("custom_tool_call"),
    ...toolCallSchema.shape
  }),
  object({
    type: literal("mcp_call"),
    ...mcpCallSchema.shape
  }),
  object({
    type: literal("message"),
    role: string(),
    content: array(messageContentPartSchema),
    id: string(),
    status: string()
  }),
  object({
    type: literal("function_call"),
    name: string(),
    arguments: string(),
    call_id: string(),
    id: string()
  }),
  object({
    type: literal("reasoning"),
    id: string(),
    summary: array(reasoningSummaryPartSchema),
    status: string(),
    encrypted_content: string().nullish()
  })
]);
var xaiResponsesUsageSchema = object({
  input_tokens: number(),
  output_tokens: number(),
  total_tokens: number().optional(),
  input_tokens_details: object({
    cached_tokens: number().optional()
  }).optional(),
  output_tokens_details: object({
    reasoning_tokens: number().optional()
  }).optional(),
  num_sources_used: number().optional(),
  num_server_side_tools_used: number().optional()
});
var xaiResponsesResponseSchema = object({
  id: string().nullish(),
  created_at: number().nullish(),
  model: string().nullish(),
  object: literal("response"),
  output: array(outputItemSchema),
  usage: xaiResponsesUsageSchema.nullish(),
  status: string()
});
var xaiResponsesChunkSchema = union([
  object({
    type: literal("response.created"),
    response: xaiResponsesResponseSchema.partial({ usage: true, status: true })
  }),
  object({
    type: literal("response.in_progress"),
    response: xaiResponsesResponseSchema.partial({ usage: true, status: true })
  }),
  object({
    type: literal("response.output_item.added"),
    item: outputItemSchema,
    output_index: number()
  }),
  object({
    type: literal("response.output_item.done"),
    item: outputItemSchema,
    output_index: number()
  }),
  object({
    type: literal("response.content_part.added"),
    item_id: string(),
    output_index: number(),
    content_index: number(),
    part: messageContentPartSchema
  }),
  object({
    type: literal("response.content_part.done"),
    item_id: string(),
    output_index: number(),
    content_index: number(),
    part: messageContentPartSchema
  }),
  object({
    type: literal("response.output_text.delta"),
    item_id: string(),
    output_index: number(),
    content_index: number(),
    delta: string(),
    logprobs: array(any()).optional()
  }),
  object({
    type: literal("response.output_text.done"),
    item_id: string(),
    output_index: number(),
    content_index: number(),
    text: string(),
    logprobs: array(any()).optional(),
    annotations: array(annotationSchema).optional()
  }),
  object({
    type: literal("response.output_text.annotation.added"),
    item_id: string(),
    output_index: number(),
    content_index: number(),
    annotation_index: number(),
    annotation: annotationSchema
  }),
  object({
    type: literal("response.reasoning_summary_part.added"),
    item_id: string(),
    output_index: number(),
    summary_index: number(),
    part: reasoningSummaryPartSchema
  }),
  object({
    type: literal("response.reasoning_summary_part.done"),
    item_id: string(),
    output_index: number(),
    summary_index: number(),
    part: reasoningSummaryPartSchema
  }),
  object({
    type: literal("response.reasoning_summary_text.delta"),
    item_id: string(),
    output_index: number(),
    summary_index: number(),
    delta: string()
  }),
  object({
    type: literal("response.reasoning_summary_text.done"),
    item_id: string(),
    output_index: number(),
    summary_index: number(),
    text: string()
  }),
  object({
    type: literal("response.web_search_call.in_progress"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.web_search_call.searching"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.web_search_call.completed"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.x_search_call.in_progress"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.x_search_call.searching"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.x_search_call.completed"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.file_search_call.in_progress"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.file_search_call.searching"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.file_search_call.completed"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.code_execution_call.in_progress"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.code_execution_call.executing"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.code_execution_call.completed"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.code_interpreter_call.in_progress"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.code_interpreter_call.executing"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.code_interpreter_call.interpreting"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.code_interpreter_call.completed"),
    item_id: string(),
    output_index: number()
  }),
  // Code interpreter code streaming events
  object({
    type: literal("response.code_interpreter_call_code.delta"),
    item_id: string(),
    output_index: number(),
    delta: string()
  }),
  object({
    type: literal("response.code_interpreter_call_code.done"),
    item_id: string(),
    output_index: number(),
    code: string()
  }),
  object({
    type: literal("response.custom_tool_call_input.delta"),
    item_id: string(),
    output_index: number(),
    delta: string()
  }),
  object({
    type: literal("response.custom_tool_call_input.done"),
    item_id: string(),
    output_index: number(),
    input: string()
  }),
  object({
    type: literal("response.mcp_call.in_progress"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.mcp_call.executing"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.mcp_call.completed"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.mcp_call.failed"),
    item_id: string(),
    output_index: number()
  }),
  object({
    type: literal("response.mcp_call_arguments.delta"),
    item_id: string(),
    output_index: number(),
    delta: string()
  }),
  object({
    type: literal("response.mcp_call_arguments.done"),
    item_id: string(),
    output_index: number(),
    arguments: string().optional()
  }),
  object({
    type: literal("response.mcp_call_output.delta"),
    item_id: string(),
    output_index: number(),
    delta: string()
  }),
  object({
    type: literal("response.mcp_call_output.done"),
    item_id: string(),
    output_index: number(),
    output: string().optional()
  }),
  object({
    type: literal("response.done"),
    response: xaiResponsesResponseSchema
  }),
  object({
    type: literal("response.completed"),
    response: xaiResponsesResponseSchema
  })
]);
var xaiResponsesProviderOptions = object({
  /**
   * Constrains how hard a reasoning model thinks before responding.
   * Possible values are `low` (uses fewer reasoning tokens), `medium` and `high` (uses more reasoning tokens).
   */
  reasoningEffort: _enum(["low", "medium", "high"]).optional(),
  /**
   * Whether to store the input message(s) and model response for later retrieval.
   * @default true
   */
  store: boolean().optional(),
  /**
   * The ID of the previous response from the model.
   */
  previousResponseId: string().optional(),
  /**
   * Specify additional output data to include in the model response.
   * Example values: 'file_search_call.results'.
   */
  include: array(_enum(["file_search_call.results"])).nullish()
});
var fileSearchArgsSchema = lazySchema(
  () => zodSchema(
    object({
      vectorStoreIds: array(string()),
      maxNumResults: number().optional()
    })
  )
);
var fileSearchOutputSchema = lazySchema(
  () => zodSchema(
    object({
      queries: array(string()),
      results: array(
        object({
          fileId: string(),
          filename: string(),
          score: number().min(0).max(1),
          text: string()
        })
      ).nullable()
    })
  )
);
var fileSearchToolFactory = createProviderToolFactoryWithOutputSchema({
  id: "xai.file_search",
  inputSchema: lazySchema(() => zodSchema(object({}))),
  outputSchema: fileSearchOutputSchema
});
var fileSearch = (args) => fileSearchToolFactory(args);
var mcpServerArgsSchema = lazySchema(
  () => zodSchema(
    object({
      serverUrl: string().describe("The URL of the MCP server"),
      serverLabel: string().optional().describe("A label for the MCP server"),
      serverDescription: string().optional().describe("Description of the MCP server"),
      allowedTools: array(string()).optional().describe("List of allowed tool names"),
      headers: record(string(), string()).optional().describe("Custom headers to send"),
      authorization: string().optional().describe("Authorization header value")
    })
  )
);
var mcpServerOutputSchema = lazySchema(
  () => zodSchema(
    object({
      name: string(),
      arguments: string(),
      result: unknown()
    })
  )
);
var mcpServerToolFactory = createProviderToolFactoryWithOutputSchema({
  id: "xai.mcp",
  inputSchema: lazySchema(() => zodSchema(object({}))),
  outputSchema: mcpServerOutputSchema
});
var mcpServer = (args) => mcpServerToolFactory(args);
var webSearchArgsSchema = lazySchema(
  () => zodSchema(
    object({
      allowedDomains: array(string()).max(5).optional(),
      excludedDomains: array(string()).max(5).optional(),
      enableImageUnderstanding: boolean().optional()
    })
  )
);
var webSearchOutputSchema = lazySchema(
  () => zodSchema(
    object({
      query: string(),
      sources: array(
        object({
          title: string(),
          url: string(),
          snippet: string()
        })
      )
    })
  )
);
var webSearchToolFactory = createProviderToolFactoryWithOutputSchema({
  id: "xai.web_search",
  inputSchema: lazySchema(() => zodSchema(object({}))),
  outputSchema: webSearchOutputSchema
});
var webSearch = (args = {}) => webSearchToolFactory(args);
var xSearchArgsSchema = lazySchema(
  () => zodSchema(
    object({
      allowedXHandles: array(string()).max(10).optional(),
      excludedXHandles: array(string()).max(10).optional(),
      fromDate: string().optional(),
      toDate: string().optional(),
      enableImageUnderstanding: boolean().optional(),
      enableVideoUnderstanding: boolean().optional()
    })
  )
);
var xSearchOutputSchema = lazySchema(
  () => zodSchema(
    object({
      query: string(),
      posts: array(
        object({
          author: string(),
          text: string(),
          url: string(),
          likes: number()
        })
      )
    })
  )
);
var xSearchToolFactory = createProviderToolFactoryWithOutputSchema({
  id: "xai.x_search",
  inputSchema: lazySchema(() => zodSchema(object({}))),
  outputSchema: xSearchOutputSchema
});
var xSearch = (args = {}) => xSearchToolFactory(args);
async function prepareResponsesTools({
  tools,
  toolChoice
}) {
  const normalizedTools = (tools == null ? void 0 : tools.length) ? tools : void 0;
  const toolWarnings = [];
  if (normalizedTools == null) {
    return { tools: void 0, toolChoice: void 0, toolWarnings };
  }
  const xaiTools2 = [];
  const toolByName = /* @__PURE__ */ new Map();
  for (const tool of normalizedTools) {
    toolByName.set(tool.name, tool);
    if (tool.type === "provider") {
      switch (tool.id) {
        case "xai.web_search": {
          const args = await validateTypes({
            value: tool.args,
            schema: webSearchArgsSchema
          });
          xaiTools2.push({
            type: "web_search",
            allowed_domains: args.allowedDomains,
            excluded_domains: args.excludedDomains,
            enable_image_understanding: args.enableImageUnderstanding
          });
          break;
        }
        case "xai.x_search": {
          const args = await validateTypes({
            value: tool.args,
            schema: xSearchArgsSchema
          });
          xaiTools2.push({
            type: "x_search",
            allowed_x_handles: args.allowedXHandles,
            excluded_x_handles: args.excludedXHandles,
            from_date: args.fromDate,
            to_date: args.toDate,
            enable_image_understanding: args.enableImageUnderstanding,
            enable_video_understanding: args.enableVideoUnderstanding
          });
          break;
        }
        case "xai.code_execution": {
          xaiTools2.push({
            type: "code_interpreter"
          });
          break;
        }
        case "xai.view_image": {
          xaiTools2.push({
            type: "view_image"
          });
          break;
        }
        case "xai.view_x_video": {
          xaiTools2.push({
            type: "view_x_video"
          });
          break;
        }
        case "xai.file_search": {
          const args = await validateTypes({
            value: tool.args,
            schema: fileSearchArgsSchema
          });
          xaiTools2.push({
            type: "file_search",
            vector_store_ids: args.vectorStoreIds,
            max_num_results: args.maxNumResults
          });
          break;
        }
        case "xai.mcp": {
          const args = await validateTypes({
            value: tool.args,
            schema: mcpServerArgsSchema
          });
          xaiTools2.push({
            type: "mcp",
            server_url: args.serverUrl,
            server_label: args.serverLabel,
            server_description: args.serverDescription,
            allowed_tools: args.allowedTools,
            headers: args.headers,
            authorization: args.authorization
          });
          break;
        }
        default: {
          toolWarnings.push({
            type: "unsupported",
            feature: `provider-defined tool ${tool.name}`
          });
          break;
        }
      }
    } else {
      xaiTools2.push({
        type: "function",
        name: tool.name,
        description: tool.description,
        parameters: tool.inputSchema
      });
    }
  }
  if (toolChoice == null) {
    return { tools: xaiTools2, toolChoice: void 0, toolWarnings };
  }
  const type = toolChoice.type;
  switch (type) {
    case "auto":
    case "none":
      return { tools: xaiTools2, toolChoice: type, toolWarnings };
    case "required":
      return { tools: xaiTools2, toolChoice: "required", toolWarnings };
    case "tool": {
      const selectedTool = toolByName.get(toolChoice.toolName);
      if (selectedTool == null) {
        return {
          tools: xaiTools2,
          toolChoice: void 0,
          toolWarnings
        };
      }
      if (selectedTool.type === "provider") {
        toolWarnings.push({
          type: "unsupported",
          feature: `toolChoice for server-side tool "${selectedTool.name}"`
        });
        return { tools: xaiTools2, toolChoice: void 0, toolWarnings };
      }
      return {
        tools: xaiTools2,
        toolChoice: { type: "function", name: selectedTool.name },
        toolWarnings
      };
    }
    default: {
      const _exhaustiveCheck = type;
      throw new UnsupportedFunctionalityError({
        functionality: `tool choice type: ${_exhaustiveCheck}`
      });
    }
  }
}
var XaiResponsesLanguageModel = class {
  constructor(modelId, config) {
    this.specificationVersion = "v3";
    this.supportedUrls = {
      "image/*": [/^https?:\/\/.*$/]
    };
    this.modelId = modelId;
    this.config = config;
  }
  get provider() {
    return this.config.provider;
  }
  async getArgs({
    prompt,
    maxOutputTokens,
    temperature,
    topP,
    stopSequences,
    seed,
    responseFormat,
    providerOptions,
    tools,
    toolChoice
  }) {
    var _a, _b, _c, _d, _e, _f, _g;
    const warnings = [];
    const options = (_a = await parseProviderOptions({
      provider: "xai",
      providerOptions,
      schema: xaiResponsesProviderOptions
    })) != null ? _a : {};
    if (stopSequences != null) {
      warnings.push({ type: "unsupported", feature: "stopSequences" });
    }
    const webSearchToolName = (_b = tools == null ? void 0 : tools.find(
      (tool) => tool.type === "provider" && tool.id === "xai.web_search"
    )) == null ? void 0 : _b.name;
    const xSearchToolName = (_c = tools == null ? void 0 : tools.find(
      (tool) => tool.type === "provider" && tool.id === "xai.x_search"
    )) == null ? void 0 : _c.name;
    const codeExecutionToolName = (_d = tools == null ? void 0 : tools.find(
      (tool) => tool.type === "provider" && tool.id === "xai.code_execution"
    )) == null ? void 0 : _d.name;
    const mcpToolName = (_e = tools == null ? void 0 : tools.find(
      (tool) => tool.type === "provider" && tool.id === "xai.mcp"
    )) == null ? void 0 : _e.name;
    const fileSearchToolName = (_f = tools == null ? void 0 : tools.find(
      (tool) => tool.type === "provider" && tool.id === "xai.file_search"
    )) == null ? void 0 : _f.name;
    const { input, inputWarnings } = await convertToXaiResponsesInput({
      prompt
    });
    warnings.push(...inputWarnings);
    const {
      tools: xaiTools2,
      toolChoice: xaiToolChoice,
      toolWarnings
    } = await prepareResponsesTools({
      tools,
      toolChoice
    });
    warnings.push(...toolWarnings);
    let include = options.include ? [...options.include] : void 0;
    if (options.store === false) {
      if (include == null) {
        include = ["reasoning.encrypted_content"];
      } else {
        include = [...include, "reasoning.encrypted_content"];
      }
    }
    const baseArgs = {
      model: this.modelId,
      input,
      max_output_tokens: maxOutputTokens,
      temperature,
      top_p: topP,
      seed,
      ...(responseFormat == null ? void 0 : responseFormat.type) === "json" && {
        text: {
          format: responseFormat.schema != null ? {
            type: "json_schema",
            strict: true,
            name: (_g = responseFormat.name) != null ? _g : "response",
            description: responseFormat.description,
            schema: responseFormat.schema
          } : { type: "json_object" }
        }
      },
      ...options.reasoningEffort != null && {
        reasoning: { effort: options.reasoningEffort }
      },
      ...options.store === false && {
        store: options.store
      },
      ...include != null && {
        include
      },
      ...options.previousResponseId != null && {
        previous_response_id: options.previousResponseId
      }
    };
    if (xaiTools2 && xaiTools2.length > 0) {
      baseArgs.tools = xaiTools2;
    }
    if (xaiToolChoice != null) {
      baseArgs.tool_choice = xaiToolChoice;
    }
    return {
      args: baseArgs,
      warnings,
      webSearchToolName,
      xSearchToolName,
      codeExecutionToolName,
      mcpToolName,
      fileSearchToolName
    };
  }
  async doGenerate(options) {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
    const {
      args: body,
      warnings,
      webSearchToolName,
      xSearchToolName,
      codeExecutionToolName,
      mcpToolName,
      fileSearchToolName
    } = await this.getArgs(options);
    const {
      responseHeaders,
      value: response,
      rawValue: rawResponse
    } = await postJsonToApi({
      url: `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/responses`,
      headers: combineHeaders(this.config.headers(), options.headers),
      body,
      failedResponseHandler: xaiFailedResponseHandler,
      successfulResponseHandler: createJsonResponseHandler(
        xaiResponsesResponseSchema
      ),
      abortSignal: options.abortSignal,
      fetch: this.config.fetch
    });
    const content = [];
    const webSearchSubTools = [
      "web_search",
      "web_search_with_snippets",
      "browse_page"
    ];
    const xSearchSubTools = [
      "x_user_search",
      "x_keyword_search",
      "x_semantic_search",
      "x_thread_fetch"
    ];
    for (const part of response.output) {
      if (part.type === "file_search_call") {
        const toolName = fileSearchToolName != null ? fileSearchToolName : "file_search";
        content.push({
          type: "tool-call",
          toolCallId: part.id,
          toolName,
          input: "",
          providerExecuted: true
        });
        content.push({
          type: "tool-result",
          toolCallId: part.id,
          toolName,
          result: {
            queries: (_b = part.queries) != null ? _b : [],
            results: (_d = (_c = part.results) == null ? void 0 : _c.map((result) => ({
              fileId: result.file_id,
              filename: result.filename,
              score: result.score,
              text: result.text
            }))) != null ? _d : null
          }
        });
        continue;
      }
      if (part.type === "web_search_call" || part.type === "x_search_call" || part.type === "code_interpreter_call" || part.type === "code_execution_call" || part.type === "view_image_call" || part.type === "view_x_video_call" || part.type === "custom_tool_call" || part.type === "mcp_call") {
        let toolName = (_e = part.name) != null ? _e : "";
        if (webSearchSubTools.includes((_f = part.name) != null ? _f : "") || part.type === "web_search_call") {
          toolName = webSearchToolName != null ? webSearchToolName : "web_search";
        } else if (xSearchSubTools.includes((_g = part.name) != null ? _g : "") || part.type === "x_search_call") {
          toolName = xSearchToolName != null ? xSearchToolName : "x_search";
        } else if (part.name === "code_execution" || part.type === "code_interpreter_call" || part.type === "code_execution_call") {
          toolName = codeExecutionToolName != null ? codeExecutionToolName : "code_execution";
        } else if (part.type === "mcp_call") {
          toolName = (_h = mcpToolName != null ? mcpToolName : part.name) != null ? _h : "mcp";
        }
        const toolInput = part.type === "custom_tool_call" ? (_i = part.input) != null ? _i : "" : part.type === "mcp_call" ? (_j = part.arguments) != null ? _j : "" : (_k = part.arguments) != null ? _k : "";
        content.push({
          type: "tool-call",
          toolCallId: part.id,
          toolName,
          input: toolInput,
          providerExecuted: true
        });
        continue;
      }
      switch (part.type) {
        case "message": {
          for (const contentPart of part.content) {
            if (contentPart.text) {
              content.push({
                type: "text",
                text: contentPart.text
              });
            }
            if (contentPart.annotations) {
              for (const annotation of contentPart.annotations) {
                if (annotation.type === "url_citation" && "url" in annotation) {
                  content.push({
                    type: "source",
                    sourceType: "url",
                    id: this.config.generateId(),
                    url: annotation.url,
                    title: (_l = annotation.title) != null ? _l : annotation.url
                  });
                }
              }
            }
          }
          break;
        }
        case "function_call": {
          content.push({
            type: "tool-call",
            toolCallId: part.call_id,
            toolName: part.name,
            input: part.arguments
          });
          break;
        }
        case "reasoning": {
          const summaryTexts = part.summary.map((s) => s.text).filter((text) => text && text.length > 0);
          if (summaryTexts.length > 0) {
            const reasoningText = summaryTexts.join("");
            if (part.encrypted_content || part.id) {
              content.push({
                type: "reasoning",
                text: reasoningText,
                providerMetadata: {
                  xai: {
                    ...part.encrypted_content && {
                      reasoningEncryptedContent: part.encrypted_content
                    },
                    ...part.id && { itemId: part.id }
                  }
                }
              });
            } else {
              content.push({
                type: "reasoning",
                text: reasoningText
              });
            }
          }
          break;
        }
      }
    }
    return {
      content,
      finishReason: {
        unified: mapXaiResponsesFinishReason(response.status),
        raw: (_m = response.status) != null ? _m : void 0
      },
      usage: response.usage ? convertXaiResponsesUsage(response.usage) : {
        inputTokens: { total: 0, noCache: 0, cacheRead: 0, cacheWrite: 0 },
        outputTokens: { total: 0, text: 0, reasoning: 0 }
      },
      request: { body },
      response: {
        ...getResponseMetadata(response),
        headers: responseHeaders,
        body: rawResponse
      },
      warnings
    };
  }
  async doStream(options) {
    var _a;
    const {
      args,
      warnings,
      webSearchToolName,
      xSearchToolName,
      codeExecutionToolName,
      mcpToolName,
      fileSearchToolName
    } = await this.getArgs(options);
    const body = {
      ...args,
      stream: true
    };
    const { responseHeaders, value: response } = await postJsonToApi({
      url: `${(_a = this.config.baseURL) != null ? _a : "https://api.x.ai/v1"}/responses`,
      headers: combineHeaders(this.config.headers(), options.headers),
      body,
      failedResponseHandler: xaiFailedResponseHandler,
      successfulResponseHandler: createEventSourceResponseHandler(
        xaiResponsesChunkSchema
      ),
      abortSignal: options.abortSignal,
      fetch: this.config.fetch
    });
    let finishReason = {
      unified: "other",
      raw: void 0
    };
    let usage = void 0;
    let isFirstChunk = true;
    const contentBlocks = {};
    const seenToolCalls = /* @__PURE__ */ new Set();
    const activeReasoning = {};
    const self = this;
    return {
      stream: response.pipeThrough(
        new TransformStream({
          start(controller) {
            controller.enqueue({ type: "stream-start", warnings });
          },
          transform(chunk, controller) {
            var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m;
            if (options.includeRawChunks) {
              controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
            }
            if (!chunk.success) {
              controller.enqueue({ type: "error", error: chunk.error });
              return;
            }
            const event = chunk.value;
            if (event.type === "response.created" || event.type === "response.in_progress") {
              if (isFirstChunk) {
                controller.enqueue({
                  type: "response-metadata",
                  ...getResponseMetadata(event.response)
                });
                isFirstChunk = false;
              }
              return;
            }
            if (event.type === "response.reasoning_summary_part.added") {
              const blockId = `reasoning-${event.item_id}`;
              activeReasoning[event.item_id] = {};
              controller.enqueue({
                type: "reasoning-start",
                id: blockId,
                providerMetadata: {
                  xai: {
                    itemId: event.item_id
                  }
                }
              });
            }
            if (event.type === "response.reasoning_summary_text.delta") {
              const blockId = `reasoning-${event.item_id}`;
              controller.enqueue({
                type: "reasoning-delta",
                id: blockId,
                delta: event.delta,
                providerMetadata: {
                  xai: {
                    itemId: event.item_id
                  }
                }
              });
              return;
            }
            if (event.type === "response.reasoning_summary_text.done") {
              return;
            }
            if (event.type === "response.output_text.delta") {
              const blockId = `text-${event.item_id}`;
              if (contentBlocks[blockId] == null) {
                contentBlocks[blockId] = { type: "text" };
                controller.enqueue({
                  type: "text-start",
                  id: blockId
                });
              }
              controller.enqueue({
                type: "text-delta",
                id: blockId,
                delta: event.delta
              });
              return;
            }
            if (event.type === "response.output_text.done") {
              if (event.annotations) {
                for (const annotation of event.annotations) {
                  if (annotation.type === "url_citation" && "url" in annotation) {
                    controller.enqueue({
                      type: "source",
                      sourceType: "url",
                      id: self.config.generateId(),
                      url: annotation.url,
                      title: (_a2 = annotation.title) != null ? _a2 : annotation.url
                    });
                  }
                }
              }
              return;
            }
            if (event.type === "response.output_text.annotation.added") {
              const annotation = event.annotation;
              if (annotation.type === "url_citation" && "url" in annotation) {
                controller.enqueue({
                  type: "source",
                  sourceType: "url",
                  id: self.config.generateId(),
                  url: annotation.url,
                  title: (_b = annotation.title) != null ? _b : annotation.url
                });
              }
              return;
            }
            if (event.type === "response.done" || event.type === "response.completed") {
              const response2 = event.response;
              if (response2.usage) {
                usage = convertXaiResponsesUsage(response2.usage);
              }
              if (response2.status) {
                finishReason = {
                  unified: mapXaiResponsesFinishReason(response2.status),
                  raw: response2.status
                };
              }
              return;
            }
            if (event.type === "response.custom_tool_call_input.delta" || event.type === "response.custom_tool_call_input.done") {
              return;
            }
            if (event.type === "response.output_item.added" || event.type === "response.output_item.done") {
              const part = event.item;
              if (part.type === "reasoning") {
                if (event.type === "response.output_item.done") {
                  const blockId = `reasoning-${part.id}`;
                  if (!(part.id in activeReasoning)) {
                    activeReasoning[part.id] = {};
                    controller.enqueue({
                      type: "reasoning-start",
                      id: blockId,
                      providerMetadata: {
                        xai: {
                          ...part.id && { itemId: part.id }
                        }
                      }
                    });
                  }
                  controller.enqueue({
                    type: "reasoning-end",
                    id: blockId,
                    providerMetadata: {
                      xai: {
                        ...part.encrypted_content && {
                          reasoningEncryptedContent: part.encrypted_content
                        },
                        ...part.id && { itemId: part.id }
                      }
                    }
                  });
                  delete activeReasoning[part.id];
                }
                return;
              }
              if (part.type === "file_search_call") {
                const toolName = fileSearchToolName != null ? fileSearchToolName : "file_search";
                if (!seenToolCalls.has(part.id)) {
                  seenToolCalls.add(part.id);
                  controller.enqueue({
                    type: "tool-input-start",
                    id: part.id,
                    toolName
                  });
                  controller.enqueue({
                    type: "tool-input-delta",
                    id: part.id,
                    delta: ""
                  });
                  controller.enqueue({
                    type: "tool-input-end",
                    id: part.id
                  });
                  controller.enqueue({
                    type: "tool-call",
                    toolCallId: part.id,
                    toolName,
                    input: "",
                    providerExecuted: true
                  });
                }
                if (event.type === "response.output_item.done") {
                  controller.enqueue({
                    type: "tool-result",
                    toolCallId: part.id,
                    toolName,
                    result: {
                      queries: (_c = part.queries) != null ? _c : [],
                      results: (_e = (_d = part.results) == null ? void 0 : _d.map((result) => ({
                        fileId: result.file_id,
                        filename: result.filename,
                        score: result.score,
                        text: result.text
                      }))) != null ? _e : null
                    }
                  });
                }
                return;
              }
              if (part.type === "web_search_call" || part.type === "x_search_call" || part.type === "code_interpreter_call" || part.type === "code_execution_call" || part.type === "view_image_call" || part.type === "view_x_video_call" || part.type === "custom_tool_call" || part.type === "mcp_call") {
                const webSearchSubTools = [
                  "web_search",
                  "web_search_with_snippets",
                  "browse_page"
                ];
                const xSearchSubTools = [
                  "x_user_search",
                  "x_keyword_search",
                  "x_semantic_search",
                  "x_thread_fetch"
                ];
                let toolName = (_f = part.name) != null ? _f : "";
                if (webSearchSubTools.includes((_g = part.name) != null ? _g : "") || part.type === "web_search_call") {
                  toolName = webSearchToolName != null ? webSearchToolName : "web_search";
                } else if (xSearchSubTools.includes((_h = part.name) != null ? _h : "") || part.type === "x_search_call") {
                  toolName = xSearchToolName != null ? xSearchToolName : "x_search";
                } else if (part.name === "code_execution" || part.type === "code_interpreter_call" || part.type === "code_execution_call") {
                  toolName = codeExecutionToolName != null ? codeExecutionToolName : "code_execution";
                } else if (part.type === "mcp_call") {
                  toolName = (_i = mcpToolName != null ? mcpToolName : part.name) != null ? _i : "mcp";
                }
                const toolInput = part.type === "custom_tool_call" ? (_j = part.input) != null ? _j : "" : part.type === "mcp_call" ? (_k = part.arguments) != null ? _k : "" : (_l = part.arguments) != null ? _l : "";
                const shouldEmit = part.type === "custom_tool_call" ? event.type === "response.output_item.done" : !seenToolCalls.has(part.id);
                if (shouldEmit && !seenToolCalls.has(part.id)) {
                  seenToolCalls.add(part.id);
                  controller.enqueue({
                    type: "tool-input-start",
                    id: part.id,
                    toolName
                  });
                  controller.enqueue({
                    type: "tool-input-delta",
                    id: part.id,
                    delta: toolInput
                  });
                  controller.enqueue({
                    type: "tool-input-end",
                    id: part.id
                  });
                  controller.enqueue({
                    type: "tool-call",
                    toolCallId: part.id,
                    toolName,
                    input: toolInput,
                    providerExecuted: true
                  });
                }
                return;
              }
              if (part.type === "message") {
                for (const contentPart of part.content) {
                  if (contentPart.text && contentPart.text.length > 0) {
                    const blockId = `text-${part.id}`;
                    if (contentBlocks[blockId] == null) {
                      contentBlocks[blockId] = { type: "text" };
                      controller.enqueue({
                        type: "text-start",
                        id: blockId
                      });
                      controller.enqueue({
                        type: "text-delta",
                        id: blockId,
                        delta: contentPart.text
                      });
                    }
                  }
                  if (contentPart.annotations) {
                    for (const annotation of contentPart.annotations) {
                      if (annotation.type === "url_citation" && "url" in annotation) {
                        controller.enqueue({
                          type: "source",
                          sourceType: "url",
                          id: self.config.generateId(),
                          url: annotation.url,
                          title: (_m = annotation.title) != null ? _m : annotation.url
                        });
                      }
                    }
                  }
                }
              } else if (part.type === "function_call") {
                if (!seenToolCalls.has(part.call_id)) {
                  seenToolCalls.add(part.call_id);
                  controller.enqueue({
                    type: "tool-input-start",
                    id: part.call_id,
                    toolName: part.name
                  });
                  controller.enqueue({
                    type: "tool-input-delta",
                    id: part.call_id,
                    delta: part.arguments
                  });
                  controller.enqueue({
                    type: "tool-input-end",
                    id: part.call_id
                  });
                  controller.enqueue({
                    type: "tool-call",
                    toolCallId: part.call_id,
                    toolName: part.name,
                    input: part.arguments
                  });
                }
              }
            }
          },
          flush(controller) {
            for (const [blockId, block] of Object.entries(contentBlocks)) {
              if (block.type === "text") {
                controller.enqueue({
                  type: "text-end",
                  id: blockId
                });
              }
            }
            controller.enqueue({ type: "finish", finishReason, usage });
          }
        })
      ),
      request: { body },
      response: { headers: responseHeaders }
    };
  }
};
var codeExecutionOutputSchema = object({
  output: string().describe("the output of the code execution"),
  error: string().optional().describe("any error that occurred")
});
var codeExecutionToolFactory = createProviderToolFactoryWithOutputSchema({
  id: "xai.code_execution",
  inputSchema: object({}).describe("no input parameters"),
  outputSchema: codeExecutionOutputSchema
});
var codeExecution = (args = {}) => codeExecutionToolFactory(args);
var viewImageOutputSchema = object({
  description: string().describe("description of the image"),
  objects: array(string()).optional().describe("objects detected in the image")
});
var viewImageToolFactory = createProviderToolFactoryWithOutputSchema({
  id: "xai.view_image",
  inputSchema: object({}).describe("no input parameters"),
  outputSchema: viewImageOutputSchema
});
var viewImage = (args = {}) => viewImageToolFactory(args);
var viewXVideoOutputSchema = object({
  transcript: string().optional().describe("transcript of the video"),
  description: string().describe("description of the video content"),
  duration: number().optional().describe("duration in seconds")
});
var viewXVideoToolFactory = createProviderToolFactoryWithOutputSchema({
  id: "xai.view_x_video",
  inputSchema: object({}).describe("no input parameters"),
  outputSchema: viewXVideoOutputSchema
});
var viewXVideo = (args = {}) => viewXVideoToolFactory(args);
var xaiTools = {
  codeExecution,
  fileSearch,
  mcpServer,
  viewImage,
  viewXVideo,
  webSearch,
  xSearch
};
var VERSION = "3.0.47";
var xaiErrorStructure = {
  errorSchema: xaiErrorDataSchema,
  errorToMessage: (data) => data.error.message
};
function createXai(options = {}) {
  var _a;
  const baseURL = withoutTrailingSlash(
    (_a = options.baseURL) != null ? _a : "https://api.x.ai/v1"
  );
  const getHeaders = () => withUserAgentSuffix(
    {
      Authorization: `Bearer ${loadApiKey({
        apiKey: options.apiKey,
        environmentVariableName: "XAI_API_KEY",
        description: "xAI API key"
      })}`,
      ...options.headers
    },
    `ai-sdk/xai/${VERSION}`
  );
  const createChatLanguageModel = (modelId) => {
    return new XaiChatLanguageModel(modelId, {
      provider: "xai.chat",
      baseURL,
      headers: getHeaders,
      generateId,
      fetch: options.fetch
    });
  };
  const createResponsesLanguageModel = (modelId) => {
    return new XaiResponsesLanguageModel(modelId, {
      provider: "xai.responses",
      baseURL,
      headers: getHeaders,
      generateId,
      fetch: options.fetch
    });
  };
  const createImageModel = (modelId) => {
    return new OpenAICompatibleImageModel(modelId, {
      provider: "xai.image",
      url: ({ path }) => `${baseURL}${path}`,
      headers: getHeaders,
      fetch: options.fetch,
      errorStructure: xaiErrorStructure
    });
  };
  const provider = (modelId) => createChatLanguageModel(modelId);
  provider.specificationVersion = "v3";
  provider.languageModel = createChatLanguageModel;
  provider.chat = createChatLanguageModel;
  provider.responses = createResponsesLanguageModel;
  provider.embeddingModel = (modelId) => {
    throw new NoSuchModelError({ modelId, modelType: "embeddingModel" });
  };
  provider.textEmbeddingModel = provider.embeddingModel;
  provider.imageModel = createImageModel;
  provider.image = createImageModel;
  provider.tools = xaiTools;
  return provider;
}
var xai = createXai();
export {
  VERSION,
  codeExecution,
  createXai,
  mcpServer,
  viewImage,
  viewXVideo,
  webSearch,
  xSearch,
  xai,
  xaiTools
};
//# sourceMappingURL=index-xBnDpGPH.js.map
