// @bun
var __create = Object.create;
var __getProtoOf = Object.getPrototypeOf;
var __defProp = Object.defineProperty;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __hasOwnProp = Object.prototype.hasOwnProperty;
function __accessProp(key) {
  return this[key];
}
var __toESMCache_node;
var __toESMCache_esm;
var __toESM = (mod, isNodeMode, target) => {
  var canCache = mod != null && typeof mod === "object";
  if (canCache) {
    var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap;
    var cached = cache.get(mod);
    if (cached)
      return cached;
  }
  target = mod != null ? __create(__getProtoOf(mod)) : {};
  const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target;
  for (let key of __getOwnPropNames(mod))
    if (!__hasOwnProp.call(to, key))
      __defProp(to, key, {
        get: __accessProp.bind(mod, key),
        enumerable: true
      });
  if (canCache)
    cache.set(mod, to);
  return to;
};
var __toCommonJS = (from) => {
  var entry = (__moduleCache ??= new WeakMap).get(from), desc;
  if (entry)
    return entry;
  entry = __defProp({}, "__esModule", { value: true });
  if (from && typeof from === "object" || typeof from === "function") {
    for (var key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(entry, key))
        __defProp(entry, key, {
          get: __accessProp.bind(from, key),
          enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
        });
  }
  __moduleCache.set(from, entry);
  return entry;
};
var __moduleCache;
var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
var __returnValue = (v) => v;
function __exportSetter(name, newValue) {
  this[name] = __returnValue.bind(null, newValue);
}
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, {
      get: all[name],
      enumerable: true,
      configurable: true,
      set: __exportSetter.bind(all, name)
    });
};
var __legacyDecorateClassTS = function(decorators, target, key, desc) {
  var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
    r = Reflect.decorate(decorators, target, key, desc);
  else
    for (var i = decorators.length - 1;i >= 0; i--)
      if (d = decorators[i])
        r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __legacyMetadataTS = (k, v) => {
  if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
    return Reflect.metadata(k, v);
};
var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
var __require = import.meta.require;

// src/ai/providers/openaiResponses.ts
var DEFAULT_BASE_URL = "https://api.openai.com";
var EVENT_PREFIX_LENGTH = 7;
var DATA_PREFIX_LENGTH = 6;
var isRecord = (value) => typeof value === "object" && value !== null;
var isRecordArray = (value) => Array.isArray(value) && value.length > 0 && isRecord(value[0]);
var mapBlockToResponsesFormat = (block) => {
  if (block.type === "text") {
    return { text: block.content, type: "input_text" };
  }
  if (block.type === "image") {
    return {
      image_url: {
        url: `data:${block.source.media_type};base64,${block.source.data}`
      },
      type: "input_image"
    };
  }
  if (block.type === "document") {
    return {
      file: {
        file_data: `data:${block.source.media_type};base64,${block.source.data}`,
        filename: block.name ?? "document.pdf"
      },
      type: "input_file"
    };
  }
  return null;
};
var mapContentToResponsesFormat = (content) => {
  if (typeof content === "string") {
    return content;
  }
  const parts = content.map(mapBlockToResponsesFormat).filter((mapped) => mapped !== null);
  return parts.length > 0 ? parts : "";
};
var hasToolBlocks = (content) => content.some((block) => block.type === "tool_use" || block.type === "tool_result");
var convertToolBlock = (block) => {
  if (block.type === "tool_use") {
    return {
      arguments: typeof block.input === "string" ? block.input : JSON.stringify(block.input),
      call_id: block.id,
      name: block.name,
      type: "function_call"
    };
  }
  if (block.type === "tool_result") {
    return {
      call_id: block.tool_use_id,
      output: typeof block.content === "string" ? block.content : "",
      type: "function_call_output"
    };
  }
  return null;
};
var convertToolBlocks = (content) => content.map(convertToolBlock).filter((converted) => converted !== null);
var convertMessage = (msg) => {
  if (typeof msg.content !== "string" && Array.isArray(msg.content) && hasToolBlocks(msg.content)) {
    return convertToolBlocks(msg.content);
  }
  const content = mapContentToResponsesFormat(msg.content);
  return [
    {
      content,
      role: msg.role === "system" ? "developer" : msg.role,
      type: "message"
    }
  ];
};
var buildInput = (messages) => {
  const input = [];
  for (const msg of messages) {
    input.push(...convertMessage(msg));
  }
  return input;
};
var mapToolDefinition = (tool) => ({
  description: tool.description,
  name: tool.name,
  parameters: tool.input_schema,
  type: "function"
});
var buildTools = (tools, isImageModel) => {
  const mapped = tools ? tools.map(mapToolDefinition) : [];
  const result = [...mapped];
  if (isImageModel) {
    result.push({ type: "image_generation" });
  }
  return result.length > 0 ? result : undefined;
};
var buildRequestBody = (params, isImageModel) => {
  const body = {
    input: buildInput(params.messages),
    model: params.model,
    stream: true
  };
  if (params.systemPrompt) {
    body.instructions = params.systemPrompt;
  }
  const tools = buildTools(params.tools, isImageModel);
  if (tools) {
    body.tools = tools;
  }
  if (params.thinking) {
    body.reasoning = {
      effort: "high",
      summary: "auto"
    };
  }
  return body;
};
var parseJSON = (data) => {
  try {
    return JSON.parse(data);
  } catch {
    return null;
  }
};
var parseToolInput = (rawArguments) => {
  try {
    return JSON.parse(rawArguments);
  } catch {
    return rawArguments;
  }
};
var extractUsage = (response) => {
  if (!isRecord(response.usage)) {
    return;
  }
  const { usage } = response;
  return {
    inputTokens: typeof usage.input_tokens === "number" ? usage.input_tokens : 0,
    outputTokens: typeof usage.output_tokens === "number" ? usage.output_tokens : 0
  };
};
var extractMimeFormat = (mimeType) => {
  if (typeof mimeType !== "string") {
    return "png";
  }
  if (mimeType.includes("jpeg"))
    return "jpeg";
  if (mimeType.includes("webp"))
    return "webp";
  return "png";
};
var processTextDelta = function* (parsed) {
  if (typeof parsed.delta === "string") {
    yield { content: parsed.delta, type: "text" };
  }
};
var processPartialImage = function* (parsed) {
  const itemId = typeof parsed.item_id === "string" ? parsed.item_id : undefined;
  const b64 = typeof parsed.partial_image_b64 === "string" ? parsed.partial_image_b64 : undefined;
  if (b64) {
    yield {
      data: b64,
      format: "png",
      imageId: itemId,
      isPartial: true,
      type: "image"
    };
  }
};
var processFunctionCallArgumentsDelta = (parsed, pendingCalls) => {
  const itemId = typeof parsed.item_id === "string" ? parsed.item_id : "";
  const callId = typeof parsed.call_id === "string" ? parsed.call_id : "";
  const delta = typeof parsed.arguments_delta === "string" ? parsed.arguments_delta : "";
  const existing = pendingCalls.get(itemId);
  if (existing) {
    existing.arguments += delta;
  } else {
    pendingCalls.set(itemId, {
      arguments: delta,
      callId,
      name: ""
    });
  }
};
var processFunctionCallArgumentsDone = function* (parsed, pendingCalls) {
  const itemId = typeof parsed.item_id === "string" ? parsed.item_id : "";
  const callId = typeof parsed.call_id === "string" ? parsed.call_id : "";
  const fullArgs = typeof parsed.arguments === "string" ? parsed.arguments : "";
  const pending = pendingCalls.get(itemId);
  const name = pending?.name ?? "";
  const args = fullArgs || pending?.arguments || "";
  pendingCalls.delete(itemId);
  yield {
    id: callId || pending?.callId || itemId,
    input: parseToolInput(args),
    name,
    type: "tool_use"
  };
};
var processOutputItemAdded = (parsed, pendingCalls) => {
  if (!isRecord(parsed.item)) {
    return;
  }
  const { item } = parsed;
  const itemId = typeof item.id === "string" ? item.id : "";
  const itemType = typeof item.type === "string" ? item.type : "";
  if (itemType !== "function_call") {
    return;
  }
  const callId = typeof item.call_id === "string" ? item.call_id : "";
  const name = typeof item.name === "string" ? item.name : "";
  pendingCalls.set(itemId, {
    arguments: "",
    callId,
    name
  });
};
var isCompletedImageGeneration = (item) => item.type === "image_generation_call" && item.status === "completed" && typeof item.result === "string" && item.result !== "";
var buildImageChunk = (item) => ({
  data: typeof item.result === "string" ? item.result : "",
  format: extractMimeFormat(item.output_format),
  imageId: typeof item.id === "string" ? item.id : undefined,
  isPartial: false,
  revisedPrompt: typeof item.revised_prompt === "string" ? item.revised_prompt : undefined,
  type: "image"
});
var extractImageFromOutput = function* (output) {
  const completedImages = output.filter(isCompletedImageGeneration);
  for (const item of completedImages) {
    yield buildImageChunk(item);
  }
};
var processCompleted = function* (parsed) {
  if (!isRecord(parsed.response)) {
    yield { type: "done", usage: undefined };
    return;
  }
  const { response } = parsed;
  const usage = extractUsage(response);
  if (isRecordArray(response.output)) {
    yield* extractImageFromOutput(response.output);
  }
  yield { type: "done", usage };
};
var processSSEEvent = function* (eventType, parsed, pendingCalls) {
  switch (eventType) {
    case "response.reasoning_summary_text.delta": {
      const delta = typeof parsed.delta === "string" ? parsed.delta : "";
      if (!delta)
        break;
      yield {
        content: delta,
        type: "thinking"
      };
      break;
    }
    case "response.output_text.delta":
      yield* processTextDelta(parsed);
      break;
    case "response.image_generation_call.partial_image":
      yield* processPartialImage(parsed);
      break;
    case "response.output_item.added":
      processOutputItemAdded(parsed, pendingCalls);
      break;
    case "response.function_call_arguments.delta":
      processFunctionCallArgumentsDelta(parsed, pendingCalls);
      break;
    case "response.function_call_arguments.done":
      yield* processFunctionCallArgumentsDone(parsed, pendingCalls);
      break;
    case "response.completed":
      yield* processCompleted(parsed);
      break;
    case "response.failed":
    case "response.incomplete": {
      const respObj = isRecord(parsed.response) ? parsed.response : parsed;
      const errMsg = isRecord(respObj.error) && typeof respObj.error.message === "string" ? respObj.error.message : `OpenAI Responses API: ${eventType}`;
      throw new Error(errMsg);
    }
  }
};
var flushSSEBuffer = function* (state) {
  if (!state.currentEvent || !state.buffer) {
    return;
  }
  const parsed = parseJSON(state.buffer);
  if (parsed) {
    yield* processSSEEvent(state.currentEvent, parsed, state.pendingCalls);
  }
  state.currentEvent = "";
  state.buffer = "";
};
var parseSSELine = (trimmed, state) => {
  if (trimmed.startsWith("event: ")) {
    state.currentEvent = trimmed.slice(EVENT_PREFIX_LENGTH);
  } else if (trimmed.startsWith("data: ")) {
    state.buffer = trimmed.slice(DATA_PREFIX_LENGTH);
  }
};
var processSSELine = function* (line, state) {
  const trimmed = line.trim();
  if (trimmed) {
    parseSSELine(trimmed, state);
    return;
  }
  yield* flushSSEBuffer(state);
};
var processSSELines = function* (lines, state) {
  for (const line of lines) {
    yield* processSSELine(line, state);
  }
};
var drainReader = async function* (reader, decoder, state, signal) {
  let textBuffer = "";
  for (let result = await reader.read();!result.done && !signal?.aborted; result = await reader.read()) {
    textBuffer += decoder.decode(result.value, { stream: true });
    const lines = textBuffer.split(`
`);
    textBuffer = lines.pop() ?? "";
    yield* processSSELines(lines, state);
  }
  if (textBuffer.trim()) {
    yield* processSSELines([textBuffer, ""], state);
  }
};
var parseSSEStream = async function* (body, signal) {
  const reader = body.getReader();
  const decoder = new TextDecoder;
  const state = {
    buffer: "",
    currentEvent: "",
    pendingCalls: new Map,
    usage: undefined
  };
  try {
    yield* drainReader(reader, decoder, state, signal);
  } finally {
    reader.releaseLock();
  }
};
var fetchResponsesStream = async function* (baseUrl, apiKey, body, signal) {
  const response = await fetch(`${baseUrl}/v1/responses`, {
    body: JSON.stringify(body),
    headers: {
      Authorization: `Bearer ${apiKey}`,
      "Content-Type": "application/json"
    },
    method: "POST",
    signal
  });
  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`OpenAI Responses API error ${response.status}: ${errorText}`);
  }
  if (!response.body) {
    throw new Error("OpenAI Responses API returned no response body");
  }
  yield* parseSSEStream(response.body, signal);
};
var resolveImageModels = (imageModels) => {
  if (!imageModels) {
    return new Set;
  }
  if (imageModels instanceof Set) {
    return imageModels;
  }
  return new Set(imageModels);
};
var openaiResponses = (config) => {
  const baseUrl = config.baseUrl ?? DEFAULT_BASE_URL;
  const imageModels = resolveImageModels(config.imageModels);
  return {
    stream: (params) => {
      const isImageModel = imageModels.has(params.model);
      const body = buildRequestBody(params, isImageModel);
      return fetchResponsesStream(baseUrl, config.apiKey, body, params.signal);
    }
  };
};
export {
  openaiResponses
};

//# debugId=65DCF5336C1A0CF064756E2164756E21
//# sourceMappingURL=openaiResponses.js.map
