// @bun
import {
  OpenAI,
  init_openai,
  init_openaiShared,
  updateOpenAIUsage
} from "./chunk-wn7mwjvq.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-e91vvygt.js";
import"./chunk-k60b56gr.js";
import"./chunk-14p6wvsq.js";
import"./chunk-n66h7gtd.js";
import"./chunk-28jd8qjx.js";
import"./chunk-djt39ze3.js";
import"./chunk-9a9g5hbj.js";
import"./chunk-ptxteaeh.js";
import"./chunk-ftrj0crk.js";
import"./chunk-yrpthe2x.js";
import"./chunk-10fpzkhd.js";
import"./chunk-awz3dq2e.js";
import {
  adaptOpenAIStreamToAnthropic,
  anthropicMessagesToOpenAI,
  anthropicToolChoiceToOpenAI,
  anthropicToolsToOpenAI,
  init_src,
  resolveGrokModel
} from "./chunk-2tabctw9.js";
import"./chunk-z21x0z3h.js";
import"./chunk-9hn8e6h1.js";
import"./chunk-rgyzsbs3.js";
import"./chunk-qn6me9n1.js";
import"./chunk-9rwstxn3.js";
import"./chunk-td4ter5p.js";
import"./chunk-71sdcaq6.js";
import"./chunk-cb6yemrf.js";
import"./chunk-tj8te4np.js";
import"./chunk-jjh8y2m7.js";
import"./chunk-dr2x4ze7.js";
import"./chunk-8ad8jmrf.js";
import"./chunk-24kv69g3.js";
import"./chunk-68n1gfc7.js";
import"./chunk-1w7c5hws.js";
import"./chunk-4gyjc4jm.js";
import"./chunk-4spgkgr3.js";
import"./chunk-e8dhxycp.js";
import"./chunk-hf0jvnz1.js";
import"./chunk-9pygs2bc.js";
import"./chunk-60fkafk2.js";
import"./chunk-gaazk5m4.js";
import"./chunk-vgmsapsy.js";
import"./chunk-093ej2sf.js";
import"./chunk-7tfdhkpy.js";
import"./chunk-nde5ym6a.js";
import"./chunk-zypcr179.js";
import"./chunk-etcs82b2.js";
import"./chunk-7wy0nfkf.js";
import"./chunk-1emjj9xz.js";
import"./chunk-m1hz377a.js";
import"./chunk-4nctdw69.js";
import"./chunk-vhghhw4q.js";
import"./chunk-935nrvdb.js";
import"./chunk-8zz4z1q3.js";
import"./chunk-hdwp8fte.js";
import"./chunk-hqxp6b72.js";
import"./chunk-3cwfww0q.js";
import"./chunk-xqc9bbe3.js";
import"./chunk-w5hnghah.js";
import"./chunk-qm7pdcft.js";
import"./chunk-x59e8cv0.js";
import"./chunk-s76nvx50.js";
import"./chunk-7jyr5758.js";
import {
  calculateUSDCost,
  init_modelCost
} from "./chunk-zrpa39fh.js";
import"./chunk-nkg1b3qw.js";
import"./chunk-c1kx8bry.js";
import"./chunk-epvbnq43.js";
import {
  getProxyFetchOptions,
  init_proxy
} from "./chunk-swgt1px0.js";
import"./chunk-8kf8h7xf.js";
import"./chunk-swz6krys.js";
import"./chunk-7eywm3ed.js";
import"./chunk-bgan4cpf.js";
import"./chunk-jmv7k0jn.js";
import"./chunk-25w7rxtr.js";
import"./chunk-5xfj4jkd.js";
import"./chunk-c1t99xmt.js";
import"./chunk-vwenx8ke.js";
import"./chunk-8thwr7p8.js";
import"./chunk-v4ypszbb.js";
import"./chunk-bk6ck5c2.js";
import"./chunk-ym6j0wv1.js";
import"./chunk-hjmatcgt.js";
import"./chunk-6mdh70q0.js";
import"./chunk-ch92ycde.js";
import"./chunk-e4dsy4g1.js";
import"./chunk-326zehp8.js";
import"./chunk-kc67kt75.js";
import"./chunk-40t1d75v.js";
import"./chunk-rt34thxn.js";
import"./chunk-e3abfxpy.js";
import"./chunk-q44zc68f.js";
import"./chunk-fejeqe61.js";
import"./chunk-kgkdmr0x.js";
import"./chunk-hn4w9pkj.js";
import"./chunk-cswpvb8x.js";
import"./chunk-gxyx8b8w.js";
import"./chunk-j1mep9ck.js";
import"./chunk-6x35ffpx.js";
import"./chunk-1zbwhcbt.js";
import"./chunk-ddaxg4xh.js";
import"./chunk-vvh31np8.js";
import"./chunk-tywrrc1m.js";
import"./chunk-e3j7m7k2.js";
import"./chunk-4p0hxk2c.js";
import"./chunk-c4dyxsat.js";
import"./chunk-34rn09za.js";
import"./chunk-m28vg9w4.js";
import"./chunk-rk9fgqmg.js";
import"./chunk-nw4zt0y4.js";
import"./chunk-c1yc761e.js";
import"./chunk-c5g9shkw.js";
import {
  init_debug,
  logForDebugging
} from "./chunk-k9jzhhww.js";
import"./chunk-kb3758f7.js";
import"./chunk-xqs9r7pg.js";
import"./chunk-tj0dzck2.js";
import"./chunk-aeysytks.js";
import"./chunk-ns1htxgd.js";
import"./chunk-ztqzmfx1.js";
import"./chunk-6k1rsk85.js";
import"./chunk-nxzx0ey9.js";
import"./chunk-yes1my80.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 = updateOpenAIUsage(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 = updateOpenAIUsage(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_openaiShared();
  init_src();
  init_messages();
  init_api();
  init_debug();
  init_cost_tracker();
  init_modelCost();
  init_tracing();
  init_convert();
  init_messages();
});
init_grok();

export {
  queryModelGrok
};

//# debugId=54810FEE4A5CE2E864756E2164756E21
//# sourceMappingURL=chunk-xz0kg1rk.js.map
