// @bun
import {
  OpenAI,
  init_openai
} from "./chunk-cbcxbbe6.js";
import {
  addToTotalSessionCost,
  convertMessagesToLangfuse,
  convertOutputToLangfuse,
  convertToolsToLangfuse,
  createAssistantAPIErrorMessage,
  init_api,
  init_convert,
  init_cost_tracker,
  init_messages1 as init_messages,
  init_tracing,
  normalizeContentFromAPI,
  normalizeMessagesForAPI,
  recordLLMObservation,
  toolToAPISchema
} from "./chunk-421yegj3.js";
import"./chunk-aaxz8a5g.js";
import"./chunk-2kcgxnvp.js";
import"./chunk-14p6wvsq.js";
import"./chunk-6s0q1s5r.js";
import"./chunk-0cpg8qh8.js";
import {
  adaptOpenAIStreamToAnthropic,
  anthropicMessagesToOpenAI,
  anthropicToolChoiceToOpenAI,
  anthropicToolsToOpenAI,
  init_src,
  resolveGrokModel
} from "./chunk-9phn5khx.js";
import"./chunk-vk9xcryd.js";
import"./chunk-9a9g5hbj.js";
import"./chunk-ptxteaeh.js";
import"./chunk-7fcmqvbz.js";
import"./chunk-rgyzsbs3.js";
import"./chunk-q3b4n194.js";
import"./chunk-zaqfb3tz.js";
import"./chunk-6hzx0kqr.js";
import"./chunk-71sdcaq6.js";
import"./chunk-9hn8e6h1.js";
import"./chunk-dxa3y9vh.js";
import"./chunk-gjvhjywj.js";
import"./chunk-1w20m7gw.js";
import"./chunk-3gam18xn.js";
import"./chunk-rpmntgyh.js";
import"./chunk-24kv69g3.js";
import"./chunk-tzcrwnrf.js";
import"./chunk-k7xszak2.js";
import"./chunk-ztmb7geg.js";
import"./chunk-tbdkekz3.js";
import"./chunk-65zbgg1n.js";
import"./chunk-4spgkgr3.js";
import"./chunk-60fkafk2.js";
import"./chunk-h5zz0vxy.js";
import"./chunk-6hygvrhn.js";
import"./chunk-7tfdhkpy.js";
import"./chunk-8gv2pjby.js";
import"./chunk-pn23dh3d.js";
import"./chunk-rpdh02rm.js";
import"./chunk-j1wktfe2.js";
import"./chunk-fjtzfz1t.js";
import"./chunk-6hr7742d.js";
import"./chunk-xyg1sk2w.js";
import"./chunk-935nrvdb.js";
import"./chunk-8zz4z1q3.js";
import"./chunk-hem4f4gz.js";
import"./chunk-hqxp6b72.js";
import"./chunk-ccw8pse0.js";
import"./chunk-wsnxtggw.js";
import"./chunk-k8nwt8yq.js";
import"./chunk-vxbjzggp.js";
import"./chunk-d6h68rz1.js";
import"./chunk-8yvsnrkr.js";
import"./chunk-5mmhfbxb.js";
import {
  calculateUSDCost,
  init_modelCost
} from "./chunk-s2t5anwv.js";
import"./chunk-ga1jkyqy.js";
import"./chunk-9hbhydvp.js";
import {
  getProxyFetchOptions,
  init_proxy
} from "./chunk-ck9r8hpf.js";
import"./chunk-k7hexw3v.js";
import"./chunk-trqrj23e.js";
import"./chunk-za3k6h2h.js";
import"./chunk-8kf8h7xf.js";
import"./chunk-bgan4cpf.js";
import"./chunk-jmv7k0jn.js";
import"./chunk-hjxqmtg5.js";
import"./chunk-bzyzrq0k.js";
import"./chunk-vwenx8ke.js";
import"./chunk-q2h79ncs.js";
import"./chunk-v4ypszbb.js";
import"./chunk-qfsn720k.js";
import"./chunk-7qx3xhv3.js";
import"./chunk-j9475b46.js";
import"./chunk-fdwabr8p.js";
import"./chunk-e4dsy4g1.js";
import"./chunk-326zehp8.js";
import"./chunk-kc67kt75.js";
import"./chunk-40t1d75v.js";
import"./chunk-dbts5q5p.js";
import"./chunk-e3abfxpy.js";
import"./chunk-q44zc68f.js";
import"./chunk-fejeqe61.js";
import"./chunk-q1vrhh0q.js";
import"./chunk-hn4w9pkj.js";
import"./chunk-2g0ytd9d.js";
import"./chunk-de0qnnf7.js";
import"./chunk-j1mep9ck.js";
import"./chunk-6x35ffpx.js";
import"./chunk-1zbwhcbt.js";
import"./chunk-92bjkrf2.js";
import"./chunk-10k5jfc5.js";
import"./chunk-n9g24mwe.js";
import"./chunk-e3j7m7k2.js";
import"./chunk-hzmzwte2.js";
import"./chunk-pdvg91cg.js";
import"./chunk-c696122m.js";
import"./chunk-xbj5keyy.js";
import"./chunk-c1yc761e.js";
import"./chunk-c5g9shkw.js";
import"./chunk-aeysytks.js";
import {
  init_debug,
  logForDebugging
} from "./chunk-s3hafnk3.js";
import"./chunk-kb3758f7.js";
import"./chunk-9h9k5vz3.js";
import"./chunk-xmpgmeb8.js";
import"./chunk-2kz09j2s.js";
import"./chunk-c0k7b0jw.js";
import"./chunk-pecy49yr.js";
import"./chunk-azbab59e.js";
import"./chunk-3nk9q8dr.js";
import {
  __esm
} from "./chunk-hhsxm2yr.js";

// src/services/api/grok/client.ts
function getGrokClient(options) {
  if (cachedClient)
    return cachedClient;
  const apiKey = process.env.GROK_API_KEY || process.env.XAI_API_KEY || "";
  const baseURL = process.env.GROK_BASE_URL || DEFAULT_BASE_URL;
  const client = new OpenAI({
    apiKey,
    baseURL,
    maxRetries: options?.maxRetries ?? 0,
    timeout: parseInt(process.env.API_TIMEOUT_MS || String(600 * 1000), 10),
    dangerouslyAllowBrowser: true,
    fetchOptions: getProxyFetchOptions({ forAnthropicAPI: false }),
    ...options?.fetchOverride && { fetch: options.fetchOverride }
  });
  if (!options?.fetchOverride) {
    cachedClient = client;
  }
  return client;
}
var DEFAULT_BASE_URL = "https://api.x.ai/v1", cachedClient = null;
var init_client = __esm(() => {
  init_openai();
  init_proxy();
});

// src/services/api/grok/index.ts
import { randomUUID } from "crypto";
async function* queryModelGrok(messages, systemPrompt, tools, signal, options) {
  try {
    const grokModel = resolveGrokModel(options.model);
    const messagesForAPI = normalizeMessagesForAPI(messages, tools);
    const toolSchemas = await Promise.all(tools.map((tool) => toolToAPISchema(tool, {
      getToolPermissionContext: options.getToolPermissionContext,
      tools,
      agents: options.agents,
      allowedAgentTypes: options.allowedAgentTypes,
      model: options.model
    })));
    const standardTools = toolSchemas.filter((t) => {
      const anyT = t;
      return anyT.type !== "advisor_20260301" && anyT.type !== "computer_20250124";
    });
    const openaiMessages = anthropicMessagesToOpenAI(messagesForAPI, systemPrompt);
    const openaiTools = anthropicToolsToOpenAI(standardTools);
    const openaiToolChoice = anthropicToolChoiceToOpenAI(options.toolChoice);
    const client = getGrokClient({
      maxRetries: 0,
      fetchOverride: options.fetchOverride,
      source: options.querySource
    });
    logForDebugging(`[Grok] Calling model=${grokModel}, messages=${openaiMessages.length}, tools=${openaiTools.length}`);
    const stream = await client.chat.completions.create({
      model: grokModel,
      messages: openaiMessages,
      ...openaiTools.length > 0 && {
        tools: openaiTools,
        ...openaiToolChoice && { tool_choice: openaiToolChoice }
      },
      stream: true,
      stream_options: { include_usage: true },
      ...options.temperatureOverride !== undefined && {
        temperature: options.temperatureOverride
      }
    }, {
      signal
    });
    const adaptedStream = adaptOpenAIStreamToAnthropic(stream, grokModel);
    const contentBlocks = {};
    const collectedMessages = [];
    let partialMessage;
    let usage = {
      input_tokens: 0,
      output_tokens: 0,
      cache_creation_input_tokens: 0,
      cache_read_input_tokens: 0
    };
    let ttftMs = 0;
    const start = Date.now();
    for await (const event of adaptedStream) {
      switch (event.type) {
        case "message_start": {
          partialMessage = event.message;
          ttftMs = Date.now() - start;
          if (event.message?.usage) {
            usage = { ...usage, ...event.message.usage };
          }
          break;
        }
        case "content_block_start": {
          const idx = event.index;
          const cb = event.content_block;
          if (cb.type === "tool_use") {
            contentBlocks[idx] = { ...cb, input: "" };
          } else if (cb.type === "text") {
            contentBlocks[idx] = { ...cb, text: "" };
          } else if (cb.type === "thinking") {
            contentBlocks[idx] = { ...cb, thinking: "", signature: "" };
          } else {
            contentBlocks[idx] = { ...cb };
          }
          break;
        }
        case "content_block_delta": {
          const idx = event.index;
          const delta = event.delta;
          const block = contentBlocks[idx];
          if (!block)
            break;
          if (delta.type === "text_delta") {
            block.text = (block.text || "") + delta.text;
          } else if (delta.type === "input_json_delta") {
            block.input = (block.input || "") + delta.partial_json;
          } else if (delta.type === "thinking_delta") {
            block.thinking = (block.thinking || "") + delta.thinking;
          } else if (delta.type === "signature_delta") {
            block.signature = delta.signature;
          }
          break;
        }
        case "content_block_stop": {
          const idx = event.index;
          const block = contentBlocks[idx];
          if (!block || !partialMessage)
            break;
          const m = {
            message: {
              ...partialMessage,
              content: normalizeContentFromAPI([block], tools, options.agentId)
            },
            requestId: undefined,
            type: "assistant",
            uuid: randomUUID(),
            timestamp: new Date().toISOString()
          };
          collectedMessages.push(m);
          yield m;
          break;
        }
        case "message_delta": {
          const deltaUsage = event.usage;
          if (deltaUsage) {
            usage = { ...usage, ...deltaUsage };
          }
          break;
        }
        case "message_stop":
          break;
      }
      if (event.type === "message_stop" && usage.input_tokens + usage.output_tokens > 0) {
        const costUSD = calculateUSDCost(grokModel, usage);
        addToTotalSessionCost(costUSD, usage, options.model);
      }
      yield {
        type: "stream_event",
        event,
        ...event.type === "message_start" ? { ttftMs } : undefined
      };
    }
    recordLLMObservation(options.langfuseTrace ?? null, {
      model: grokModel,
      provider: "grok",
      input: convertMessagesToLangfuse(messagesForAPI, systemPrompt),
      output: convertOutputToLangfuse(collectedMessages),
      usage: {
        input_tokens: usage.input_tokens,
        output_tokens: usage.output_tokens,
        cache_creation_input_tokens: usage.cache_creation_input_tokens,
        cache_read_input_tokens: usage.cache_read_input_tokens
      },
      startTime: new Date(start),
      endTime: new Date,
      completionStartTime: ttftMs > 0 ? new Date(start + ttftMs) : undefined,
      tools: convertToolsToLangfuse(toolSchemas)
    });
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    logForDebugging(`[Grok] Error: ${errorMessage}`, { level: "error" });
    yield createAssistantAPIErrorMessage({
      content: `API Error: ${errorMessage}`,
      apiError: "api_error",
      error: error instanceof Error ? error : new Error(String(error))
    });
  }
}
var init_grok = __esm(() => {
  init_client();
  init_src();
  init_messages();
  init_api();
  init_debug();
  init_cost_tracker();
  init_modelCost();
  init_tracing();
  init_convert();
  init_messages();
});
init_grok();

export {
  queryModelGrok
};
