export { createAdapter } from './chunk-627FHZZY.js';
import { createStreamSource, parseAnthropicStream, parseGeminiStream, parseOllamaStream, toProviderMessages, parseOpenAIStream, openai, readSSELines } from './chunk-4KZTWGRB.js';
export { chunkText, fetchWithRetry, openai, simulateStream } from './chunk-4KZTWGRB.js';
import { raceAbort, isAbortError, adapterErrorChunk, abortableSleep, parseCompleteToolArgs } from './chunk-6CIB2QCH.js';
import { ConfigError, ErrorCodes, AdapterError } from '@agentskit/core';

// src/generic.ts
function generic(config) {
  return {
    createSource: (request) => {
      const controller = new AbortController();
      let reader = null;
      const decoder = new TextDecoder();
      return {
        stream: async function* () {
          if (controller.signal.aborted) return;
          try {
            const stream = await raceAbort(
              config.send(request, controller.signal),
              controller.signal
            );
            if (controller.signal.aborted) {
              try {
                await stream.cancel();
              } catch {
              }
              return;
            }
            reader = stream.getReader();
            while (true) {
              if (controller.signal.aborted) {
                try {
                  await reader.cancel();
                } catch {
                }
                return;
              }
              const { done, value } = await raceAbort(reader.read(), controller.signal);
              if (done) break;
              const text = decoder.decode(value, { stream: true });
              yield { type: "text", content: text };
            }
            if (controller.signal.aborted) return;
            yield { type: "done" };
          } catch (err) {
            if (isAbortError(err) || controller.signal.aborted) return;
            yield {
              type: "error",
              content: err instanceof Error ? err.message : String(err),
              metadata: {
                error: err instanceof Error ? err : new Error(String(err))
              }
            };
          } finally {
            try {
              reader?.releaseLock();
            } catch {
            }
          }
        },
        abort: () => {
          if (!controller.signal.aborted) controller.abort();
          void reader?.cancel().catch(() => {
          });
        }
      };
    }
  };
}

// src/tool-history.ts
function toolInput(args) {
  if (args == null) return {};
  if (typeof args === "string") {
    try {
      const parsed = JSON.parse(args);
      if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
        return parsed;
      }
      return { value: parsed };
    } catch {
      return {};
    }
  }
  if (typeof args === "object" && !Array.isArray(args)) {
    return args;
  }
  return { value: args };
}
function toolResponsePayload(content) {
  try {
    const parsed = JSON.parse(content);
    if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
      return parsed;
    }
    return { result: parsed };
  } catch {
    return { result: content };
  }
}
function toAnthropicMessages(messages) {
  const knownNames = /* @__PURE__ */ new Map();
  const output = [];
  for (const message of messages) {
    if (message.role === "system") continue;
    if (message.role === "assistant" && message.toolCalls && message.toolCalls.length > 0) {
      for (const tc of message.toolCalls) knownNames.set(tc.id, tc.name);
      const blocks = [];
      if (message.content) {
        blocks.push({ type: "text", text: message.content });
      }
      for (const tc of message.toolCalls) {
        blocks.push({
          type: "tool_use",
          id: tc.id,
          name: tc.name,
          input: toolInput(tc.args)
        });
      }
      output.push({ role: "assistant", content: blocks });
      continue;
    }
    if (message.role === "tool") {
      const id = message.toolCallId;
      if (!id || !knownNames.has(id)) continue;
      const block = {
        type: "tool_result",
        tool_use_id: id,
        content: message.content
      };
      const previous2 = output[output.length - 1];
      if (previous2?.role === "user" && Array.isArray(previous2.content) && previous2.content.every((item) => item && typeof item === "object" && item.type === "tool_result")) {
        previous2.content.push(block);
      } else {
        output.push({ role: "user", content: [block] });
      }
      continue;
    }
    if (message.role === "assistant" && !message.content) continue;
    const previous = output[output.length - 1];
    if (message.role === "user" && previous?.role === "user") {
      const previousBlocks = Array.isArray(previous.content) ? previous.content : [{ type: "text", text: previous.content }];
      previous.content = [...previousBlocks, { type: "text", text: message.content }];
    } else {
      output.push({ role: message.role, content: message.content });
    }
  }
  return output;
}
function toGeminiContents(messages) {
  const knownNames = /* @__PURE__ */ new Map();
  const output = [];
  for (const message of messages) {
    if (message.role === "system") continue;
    if (message.role === "assistant" && message.toolCalls && message.toolCalls.length > 0) {
      for (const tc of message.toolCalls) knownNames.set(tc.id, tc.name);
      const parts = [];
      if (message.content) {
        parts.push({ text: message.content });
      }
      for (const tc of message.toolCalls) {
        parts.push({
          functionCall: {
            id: tc.id,
            name: tc.name,
            args: toolInput(tc.args)
          }
        });
      }
      output.push({ role: "model", parts });
      continue;
    }
    if (message.role === "tool") {
      const id = message.toolCallId;
      const name = id ? knownNames.get(id) : void 0;
      if (!name) continue;
      const part = {
        functionResponse: {
          id,
          name,
          response: toolResponsePayload(message.content)
        }
      };
      const previous2 = output[output.length - 1];
      if (previous2?.role === "user" && previous2.parts.every((item) => item.functionResponse !== void 0)) {
        previous2.parts.push(part);
      } else {
        output.push({ role: "user", parts: [part] });
      }
      continue;
    }
    if (message.role === "assistant" && !message.content) continue;
    const role = message.role === "assistant" ? "model" : "user";
    const previous = output[output.length - 1];
    if (previous?.role === role) {
      previous.parts.push({ text: message.content });
    } else {
      output.push({ role, parts: [{ text: message.content }] });
    }
  }
  return output;
}

// src/anthropic.ts
function anthropic(config) {
  const { apiKey, model, baseUrl = "https://api.anthropic.com", maxTokens = 4096, retry } = config;
  return {
    capabilities: {
      streaming: true,
      tools: true,
      reasoning: model.includes("sonnet") || model.includes("opus"),
      multiModal: true,
      usage: true
    },
    createSource: (request) => {
      const body = {
        model,
        max_tokens: request.context?.maxTokens ?? maxTokens,
        messages: toAnthropicMessages(request.messages),
        system: request.messages.find((message) => message.role === "system")?.content,
        tools: request.context?.tools?.map((tool) => ({
          name: tool.name,
          description: tool.description,
          input_schema: tool.schema
        })),
        stream: true
      };
      return createStreamSource(
        (signal) => fetch(`${baseUrl}/v1/messages`, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "x-api-key": apiKey,
            "anthropic-version": "2023-06-01"
          },
          body: JSON.stringify(body),
          signal
        }),
        parseAnthropicStream,
        "Anthropic API",
        retry
      );
    }
  };
}

// src/gemini.ts
function gemini(config) {
  const { apiKey, model, baseUrl = "https://generativelanguage.googleapis.com", retry } = config;
  return {
    capabilities: {
      streaming: true,
      tools: true,
      multiModal: true,
      usage: true
    },
    createSource: (request) => {
      const systemMessage = request.messages.find((message) => message.role === "system");
      const body = {
        contents: toGeminiContents(request.messages),
        systemInstruction: systemMessage ? { role: "system", parts: [{ text: systemMessage.content }] } : void 0,
        tools: request.context?.tools && request.context.tools.length > 0 ? [{
          functionDeclarations: request.context.tools.map((tool) => ({
            name: tool.name,
            description: tool.description,
            parameters: tool.schema
          }))
        }] : void 0
      };
      return createStreamSource(
        (signal) => fetch(
          `${baseUrl}/v1beta/models/${model}:streamGenerateContent?alt=sse`,
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              "x-goog-api-key": apiKey
            },
            body: JSON.stringify(body),
            signal
          }
        ),
        parseGeminiStream,
        "Gemini API",
        retry
      );
    }
  };
}

// src/openai-compatible.ts
function createOpenAICompatibleAdapter(defaultBaseUrl) {
  return function openAICompatibleAdapter(config) {
    return openai({
      ...config,
      baseUrl: config.baseUrl ?? defaultBaseUrl
    });
  };
}

// src/grok.ts
var grok = createOpenAICompatibleAdapter("https://api.x.ai");

// src/ollama.ts
function ollama(config) {
  const { model, baseUrl = "http://localhost:11434", retry } = config;
  return {
    capabilities: {
      streaming: true,
      tools: false,
      // varies by model; default 'false' — enable via capabilities.extensions if your model supports it
      multiModal: model.includes("llava") || model.includes("vision")
    },
    createSource: (request) => {
      const body = {
        model,
        stream: true,
        messages: request.messages.map((message) => ({
          role: message.role,
          content: message.content
        }))
      };
      return createStreamSource(
        (signal) => fetch(`${baseUrl}/api/chat`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify(body),
          signal
        }),
        parseOllamaStream,
        "Ollama API",
        retry
      );
    }
  };
}

// src/deepseek.ts
var deepseek = createOpenAICompatibleAdapter("https://api.deepseek.com");

// src/kimi.ts
var kimi = createOpenAICompatibleAdapter("https://api.moonshot.ai");

// src/langchain.ts
function asText(value) {
  if (typeof value === "string") return value;
  if (value && typeof value === "object" && "content" in value) {
    const content = value.content;
    if (typeof content === "string") return content;
  }
  return "";
}
function isToolStartEvent(eventName) {
  return eventName === "on_tool_start" || eventName.endsWith("_tool_start");
}
function langchain(config) {
  const { runnable, mode = "stream" } = config;
  return {
    createSource: (request) => {
      const controller = new AbortController();
      return {
        stream: async function* () {
          if (controller.signal.aborted) return;
          try {
            const runnableConfig = {
              version: "v2",
              signal: controller.signal
            };
            if (mode === "events" && runnable.streamEvents) {
              const events = await runnable.streamEvents(
                { messages: request.messages },
                runnableConfig
              );
              for await (const event of events) {
                if (controller.signal.aborted) return;
                const eventName = String(event.event ?? "");
                if (eventName.endsWith("_stream")) {
                  const chunk = asText(event.data);
                  if (chunk) yield { type: "text", content: chunk };
                } else if (isToolStartEvent(eventName) && event.name) {
                  yield {
                    type: "tool_call",
                    toolCall: {
                      id: String(event.run_id ?? `${event.name}-${Date.now()}`),
                      name: String(event.name),
                      args: JSON.stringify(event.data ?? {})
                    }
                  };
                }
              }
            } else if (runnable.stream) {
              const stream = await runnable.stream(
                { messages: request.messages },
                runnableConfig
              );
              for await (const value of stream) {
                if (controller.signal.aborted) return;
                const chunk = asText(value);
                if (chunk) yield { type: "text", content: chunk };
              }
            } else {
              yield adapterErrorChunk("Runnable does not implement stream() or streamEvents()");
              return;
            }
            if (controller.signal.aborted) return;
            yield { type: "done" };
          } catch (error) {
            if (isAbortError(error) || controller.signal.aborted) return;
            const message = error instanceof Error ? error.message : String(error);
            yield adapterErrorChunk(message, { cause: error });
          }
        },
        abort: () => {
          controller.abort();
        }
      };
    }
  };
}
function langgraph(config) {
  return langchain({
    runnable: config.graph,
    mode: "events"
  });
}

// src/vercel-ai.ts
var UI_STREAM_HEADER = "x-vercel-ai-ui-message-stream";
async function* parseVercelTextStream(stream) {
  const reader = stream.getReader();
  const decoder = new TextDecoder();
  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      const text = decoder.decode(value, { stream: true });
      if (text) yield { type: "text", content: text };
    }
  } finally {
    reader.releaseLock();
  }
  yield { type: "done" };
}
async function* parseVercelUiMessageStreamV1(stream) {
  for await (const data of readSSELines(stream)) {
    if (data === "[DONE]") {
      yield { type: "done" };
      return;
    }
    try {
      const part = JSON.parse(data);
      const type = part.type;
      if (type === "text-delta") {
        const delta = part.delta ?? part.textDelta;
        if (typeof delta === "string" && delta) {
          yield { type: "text", content: delta };
        }
      } else if (type === "reasoning-delta") {
        const delta = part.delta ?? part.textDelta;
        if (typeof delta === "string" && delta) {
          yield { type: "reasoning", content: delta };
        }
      } else if (type === "error") {
        const message = part.errorText ?? part.message ?? "Vercel AI UI stream error";
        yield adapterErrorChunk(String(message));
        return;
      } else if (type === "abort") {
        yield adapterErrorChunk(part.reason ?? "Vercel AI UI stream aborted by provider");
        return;
      } else if (type === "finish") {
        continue;
      }
    } catch {
    }
  }
  yield adapterErrorChunk("Vercel AI UI stream truncated before [DONE]");
}
async function* parseVercelStream(stream, response) {
  const header = response?.headers.get(UI_STREAM_HEADER) ?? response?.headers.get(UI_STREAM_HEADER.toLowerCase());
  if (header === "v1") {
    yield* parseVercelUiMessageStreamV1(stream);
    return;
  }
  yield* parseVercelTextStream(stream);
}
function vercelAI(config) {
  const { api, headers = {}, retry } = config;
  return {
    capabilities: {
      // Vercel AI routes can do any of these — whether they do depends on
      // your route handler. Omit the field instead of lying.
    },
    createSource: (request) => {
      const body = {
        messages: request.messages.map((message) => ({ role: message.role, content: message.content })),
        tools: request.context?.tools,
        systemPrompt: request.context?.systemPrompt
      };
      return createStreamSource(
        (signal) => fetch(api, {
          method: "POST",
          headers: { "Content-Type": "application/json", ...headers },
          body: JSON.stringify(body),
          signal
        }),
        parseVercelStream,
        "API",
        retry
      );
    }
  };
}

// src/mistral.ts
var mistral = createOpenAICompatibleAdapter("https://api.mistral.ai/v1");

// src/cohere.ts
var COHERE_BASE_URL = "https://api.cohere.com/compatibility/v1";
var DEFAULT_MODEL = "command-r-plus";
var baseFactory = createOpenAICompatibleAdapter(COHERE_BASE_URL);
function cohere(config) {
  const factory = baseFactory({
    model: DEFAULT_MODEL,
    ...config
  });
  return {
    ...factory,
    capabilities: {
      streaming: true,
      tools: true,
      usage: true
    }
  };
}
var cohereAdapter = cohere;

// src/together.ts
var together = createOpenAICompatibleAdapter("https://api.together.xyz/v1");

// src/groq.ts
var GROQ_BASE_URL = "https://api.groq.com/openai/v1";
var DEFAULT_MODEL2 = "llama-3.3-70b-versatile";
var baseFactory2 = createOpenAICompatibleAdapter(GROQ_BASE_URL);
function groq(config) {
  const factory = baseFactory2({
    model: DEFAULT_MODEL2,
    ...config
  });
  return {
    ...factory,
    capabilities: {
      streaming: true,
      tools: true,
      usage: true
    }
  };
}
var groqAdapter = groq;

// src/fireworks.ts
var fireworks = createOpenAICompatibleAdapter("https://api.fireworks.ai/inference/v1");

// src/openrouter.ts
var openrouter = createOpenAICompatibleAdapter("https://openrouter.ai/api/v1");

// src/huggingface.ts
var huggingface = createOpenAICompatibleAdapter("https://router.huggingface.co/v1");

// src/lmstudio.ts
var lmstudio = createOpenAICompatibleAdapter("http://localhost:1234/v1");

// src/vllm.ts
var vllm = createOpenAICompatibleAdapter("http://localhost:8000/v1");

// src/llamacpp.ts
var llamacpp = createOpenAICompatibleAdapter("http://localhost:8080/v1");

// src/cerebras.ts
var CEREBRAS_BASE_URL = "https://api.cerebras.ai/v1";
var DEFAULT_MODEL3 = "llama-3.3-70b";
var baseFactory3 = createOpenAICompatibleAdapter(CEREBRAS_BASE_URL);
function cerebras(config) {
  const factory = baseFactory3({
    model: DEFAULT_MODEL3,
    ...config
  });
  return {
    ...factory,
    capabilities: {
      streaming: true,
      tools: true,
      usage: true
    }
  };
}
var cerebrasAdapter = cerebras;

// src/azure-openai.ts
var DEFAULT_API_VERSION = "2024-10-21";
function azureOpenAI(config) {
  const { apiKey, endpoint, deployment, apiVersion = DEFAULT_API_VERSION, retry } = config;
  const includeUsage = config.includeUsage ?? true;
  const url = `${endpoint.replace(/\/$/, "")}/openai/deployments/${encodeURIComponent(deployment)}/chat/completions?api-version=${encodeURIComponent(apiVersion)}`;
  return {
    capabilities: {
      streaming: true,
      tools: true,
      usage: true
    },
    createSource: (request) => {
      const body = {
        messages: toProviderMessages(request.messages),
        tools: request.context?.tools?.map((tool) => ({
          type: "function",
          function: {
            name: tool.name,
            description: tool.description,
            parameters: tool.schema
          }
        })),
        temperature: request.context?.temperature,
        max_tokens: request.context?.maxTokens,
        stream: true
      };
      if (includeUsage) body.stream_options = { include_usage: true };
      return createStreamSource(
        (signal) => fetch(url, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "api-key": apiKey
          },
          body: JSON.stringify(body),
          signal
        }),
        parseOpenAIStream,
        "Azure OpenAI API",
        retry
      );
    }
  };
}
var azureOpenAIAdapter = azureOpenAI;

// src/replicate.ts
var DEFAULT_BASE_URL = "https://api.replicate.com";
function defaultPrompt(request) {
  return request.messages.map((m) => {
    if (m.role === "system") return `[SYSTEM] ${m.content}`;
    if (m.role === "assistant") return `[ASSISTANT] ${m.content}`;
    return `[USER] ${m.content}`;
  }).join("\n\n") + "\n\n[ASSISTANT] ";
}
async function* parseReplicateStream(stream) {
  const reader = stream.getReader();
  const decoder = new TextDecoder();
  let buffer = "";
  let currentEvent = "";
  let sawDone = false;
  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      buffer += decoder.decode(value, { stream: true });
      const lines = buffer.split("\n");
      buffer = lines.pop() ?? "";
      for (const line of lines) {
        if (line.startsWith("event: ")) {
          currentEvent = line.slice(7).trim();
          continue;
        }
        if (!line.startsWith("data: ")) continue;
        const data = line.slice(6);
        if (currentEvent === "output" && data) {
          yield { type: "text", content: data };
        } else if (currentEvent === "done") {
          sawDone = true;
          yield { type: "done" };
          return;
        } else if (currentEvent === "error") {
          yield adapterErrorChunk(data || "replicate stream error");
          return;
        }
      }
    }
  } finally {
    reader.releaseLock();
  }
  if (!sawDone) {
    yield adapterErrorChunk("Replicate stream ended without done event");
    return;
  }
  yield { type: "done" };
}
function replicate(config) {
  const { apiKey, model, version, baseUrl = DEFAULT_BASE_URL, toInput = (r) => ({ prompt: defaultPrompt(r) }) } = config;
  const predictionUrl = version ? `${baseUrl}/v1/predictions` : `${baseUrl}/v1/models/${model}/predictions`;
  return {
    capabilities: {
      streaming: true,
      tools: false
    },
    createSource: (request) => {
      const controller = new AbortController();
      let aborted = false;
      return {
        stream: async function* () {
          if (aborted) return;
          try {
            const body = {
              input: toInput(request),
              stream: true
            };
            if (version) body.version = version;
            const response = await fetch(predictionUrl, {
              method: "POST",
              headers: {
                "Content-Type": "application/json",
                "Authorization": `Bearer ${apiKey}`
              },
              body: JSON.stringify(body),
              signal: controller.signal
            });
            if (!response.ok) {
              yield adapterErrorChunk(`Replicate API error: ${response.status}`);
              return;
            }
            const prediction = await response.json();
            if (prediction.error) {
              yield adapterErrorChunk(prediction.error);
              return;
            }
            const streamUrl = prediction.urls?.stream;
            if (!streamUrl) {
              yield adapterErrorChunk("Replicate prediction has no stream URL");
              return;
            }
            const streamResponse = await fetch(streamUrl, {
              method: "GET",
              headers: { Accept: "text/event-stream" },
              signal: controller.signal
            });
            if (!streamResponse.ok || !streamResponse.body) {
              yield adapterErrorChunk(`Replicate stream error: ${streamResponse.status}`);
              return;
            }
            for await (const chunk of parseReplicateStream(streamResponse.body)) {
              if (aborted) return;
              yield chunk;
            }
          } catch (err) {
            if (isAbortError(err) || aborted) return;
            const message = err instanceof Error ? err.message : String(err);
            yield adapterErrorChunk(message, { cause: err });
          }
        },
        abort: () => {
          aborted = true;
          controller.abort();
        }
      };
    }
  };
}
var replicateAdapter = replicate;

// src/bail.ts
var BAIL_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1";
var DEFAULT_MODEL4 = "qwen-max";
var baseFactory4 = createOpenAICompatibleAdapter(BAIL_BASE_URL);
function bail(config) {
  const factory = baseFactory4({
    model: DEFAULT_MODEL4,
    ...config
  });
  return {
    ...factory,
    capabilities: {
      streaming: true,
      tools: true,
      multiModal: true,
      usage: true
    }
  };
}
var bailAdapter = bail;
var qwen = bail;

// src/vertex.ts
function vertex(config) {
  const { project, region, model, accessToken, publisher = "google", retry } = config;
  const url = `https://${region}-aiplatform.googleapis.com/v1/projects/${project}/locations/${region}/publishers/${publisher}/models/${model}:streamGenerateContent?alt=sse`;
  return {
    capabilities: {
      streaming: true,
      tools: true,
      multiModal: true,
      usage: true,
      reasoning: model.includes("pro")
    },
    createSource: (request) => {
      const systemMessage = request.messages.find((message) => message.role === "system");
      const body = {
        contents: toGeminiContents(request.messages),
        systemInstruction: systemMessage ? { role: "system", parts: [{ text: systemMessage.content }] } : void 0,
        tools: request.context?.tools && request.context.tools.length > 0 ? [{
          functionDeclarations: request.context.tools.map((tool) => ({
            name: tool.name,
            description: tool.description,
            parameters: tool.schema
          }))
        }] : void 0
      };
      return createStreamSource(
        async (signal) => {
          const token = typeof accessToken === "string" ? accessToken : await accessToken();
          return fetch(url, {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
              "Authorization": `Bearer ${token}`
            },
            body: JSON.stringify(body),
            signal
          });
        },
        parseGeminiStream,
        "Vertex AI",
        retry
      );
    }
  };
}
var vertexAdapter = vertex;
var cachedSdk = null;
async function loadSdk() {
  if (!cachedSdk) {
    cachedSdk = (async () => {
      try {
        const moduleId = "@aws-sdk/client-bedrock-runtime";
        return await import(
          /* @vite-ignore */
          moduleId
        );
      } catch {
        throw new AdapterError({
          code: ErrorCodes.AK_ADAPTER_MISSING,
          message: "Install @aws-sdk/client-bedrock-runtime to use the bedrock adapter: npm install @aws-sdk/client-bedrock-runtime",
          hint: "bedrock depends on the optional peer @aws-sdk/client-bedrock-runtime."
        });
      }
    })();
  }
  return cachedSdk;
}
function isAnthropicModel(model) {
  return model.startsWith("anthropic.");
}
function buildAnthropicBody(request, maxTokens) {
  const messages = toAnthropicMessages(request.messages);
  const system = request.messages.find((m) => m.role === "system")?.content;
  const tools = request.context?.tools?.map((tool) => ({
    name: tool.name,
    description: tool.description,
    input_schema: tool.schema
  }));
  const body = {
    anthropic_version: "bedrock-2023-05-31",
    max_tokens: request.context?.maxTokens ?? maxTokens,
    messages
  };
  if (system) body.system = system;
  if (tools && tools.length > 0) body.tools = tools;
  return JSON.stringify(body);
}
async function* parseAnthropicBedrockEvents(events) {
  const decoder = new TextDecoder();
  const pendingToolCalls = /* @__PURE__ */ new Map();
  const emitTool = function* (tc) {
    const parsed = parseCompleteToolArgs(tc.args);
    if (!parsed.ok) {
      yield {
        type: "error",
        content: parsed.error.message,
        metadata: { error: parsed.error }
      };
      return false;
    }
    yield { type: "tool_call", toolCall: { id: tc.id, name: tc.name, args: parsed.args } };
    return true;
  };
  for await (const item of events) {
    const bytes = item.chunk?.bytes;
    if (!bytes) continue;
    let event;
    try {
      event = JSON.parse(decoder.decode(bytes));
    } catch {
      continue;
    }
    const type = event.type;
    if (type === "content_block_delta") {
      const delta = event.delta;
      if (delta?.type === "text_delta" && delta.text) {
        yield { type: "text", content: delta.text };
      } else if (delta?.type === "input_json_delta") {
        const index = event.index ?? 0;
        const existing = pendingToolCalls.get(index);
        if (existing) existing.args += delta.partial_json ?? "";
      }
    } else if (type === "content_block_start") {
      const index = event.index ?? 0;
      const block = event.content_block;
      if (block?.type === "tool_use" && block.id && block.name) {
        pendingToolCalls.set(index, { id: block.id, name: block.name, args: "" });
      }
    } else if (type === "content_block_stop") {
      const index = event.index ?? 0;
      const tc = pendingToolCalls.get(index);
      if (tc) {
        if (!(yield* emitTool(tc))) {
          pendingToolCalls.clear();
          return;
        }
        pendingToolCalls.delete(index);
      }
    } else if (type === "message_delta") {
      const usage = event.usage;
      if (usage) {
        const promptTokens = usage.input_tokens ?? 0;
        const completionTokens = usage.output_tokens ?? 0;
        yield {
          type: "usage",
          usage: { promptTokens, completionTokens, totalTokens: promptTokens + completionTokens }
        };
      }
    } else if (type === "message_start") {
      const usage = event.message?.usage;
      if (usage) {
        yield {
          type: "usage",
          usage: {
            promptTokens: usage.input_tokens ?? 0,
            completionTokens: 0,
            totalTokens: usage.input_tokens ?? 0
          }
        };
      }
    } else if (type === "message_stop") {
      for (const [, tc] of pendingToolCalls) {
        if (!(yield* emitTool(tc))) {
          pendingToolCalls.clear();
          return;
        }
      }
      pendingToolCalls.clear();
      yield { type: "done" };
      return;
    }
  }
  pendingToolCalls.clear();
  yield adapterErrorChunk("Bedrock stream ended before message_stop");
}
function bedrock(config) {
  const { model, region, maxTokens = 4096 } = config;
  if (!isAnthropicModel(model)) {
    throw new ConfigError({
      code: ErrorCodes.AK_CONFIG_INVALID,
      message: `bedrock: model "${model}" is not supported in v1. Only anthropic.* models are wired up; Titan + others are tracked as a follow-up.`,
      hint: 'Pass an anthropic.* model id like "anthropic.claude-3-5-sonnet-20241022-v2:0".'
    });
  }
  let clientPromise = null;
  const getClient = async () => {
    if (config.client) return config.client;
    if (!clientPromise) {
      clientPromise = (async () => {
        const sdk = await loadSdk();
        return new sdk.BedrockRuntimeClient({ region });
      })();
    }
    return clientPromise;
  };
  return {
    capabilities: {
      streaming: true,
      tools: true,
      reasoning: model.includes("sonnet") || model.includes("opus"),
      multiModal: true,
      usage: true
    },
    createSource: (request) => {
      const controller = new AbortController();
      let aborted = false;
      return {
        stream: async function* () {
          if (aborted || controller.signal.aborted) return;
          try {
            const client = await getClient();
            if (aborted || controller.signal.aborted) return;
            const sdk = config.client ? null : await loadSdk();
            const input = {
              modelId: model,
              contentType: "application/json",
              accept: "application/json",
              body: buildAnthropicBody(request, maxTokens)
            };
            const command = sdk ? new sdk.InvokeModelWithResponseStreamCommand(input) : { input };
            const response = await client.send(command, { abortSignal: controller.signal });
            if (!response.body) {
              yield adapterErrorChunk("Bedrock: empty response body");
              return;
            }
            for await (const chunk of parseAnthropicBedrockEvents(response.body)) {
              if (aborted || controller.signal.aborted) return;
              yield chunk;
            }
          } catch (err) {
            if (isAbortError(err) || aborted) return;
            const message = err instanceof Error ? err.message : String(err);
            yield adapterErrorChunk(message, { cause: err });
          }
        },
        abort: () => {
          aborted = true;
          controller.abort();
        }
      };
    }
  };
}
var bedrockAdapter = bedrock;
var cachedSdk2 = null;
async function loadSdk2() {
  if (!cachedSdk2) {
    cachedSdk2 = (async () => {
      try {
        const moduleId = "@mlc-ai/web-llm";
        return await import(
          /* @vite-ignore */
          moduleId
        );
      } catch {
        throw new AdapterError({
          code: ErrorCodes.AK_ADAPTER_MISSING,
          message: "Install @mlc-ai/web-llm to use the webllm adapter: npm install @mlc-ai/web-llm",
          hint: "webllm is browser-only and depends on the optional peer @mlc-ai/web-llm."
        });
      }
    })();
  }
  return cachedSdk2;
}
function webllm(config) {
  let enginePromise = null;
  const getEngine = () => {
    if (config.engine) return Promise.resolve(config.engine);
    if (!enginePromise) {
      enginePromise = (async () => {
        const sdk = await loadSdk2();
        return sdk.CreateMLCEngine(config.model, { initProgressCallback: config.onProgress });
      })();
    }
    return enginePromise;
  };
  return {
    capabilities: {
      streaming: true,
      tools: false
    },
    createSource: (request) => {
      const controller = new AbortController();
      let aborted = false;
      let activeIter = null;
      const softAbort = () => {
        aborted = true;
        if (!controller.signal.aborted) controller.abort();
        if (activeIter && typeof activeIter.return === "function") {
          void activeIter.return(void 0).catch(() => {
          });
        }
      };
      return {
        stream: async function* () {
          if (aborted || controller.signal.aborted) return;
          try {
            const engine = await raceAbort(getEngine(), controller.signal);
            if (aborted || controller.signal.aborted) return;
            const messages = request.messages.map((m) => ({ role: m.role, content: m.content }));
            const completion = await raceAbort(
              Promise.resolve(
                engine.chat.completions.create({ messages, stream: true })
              ),
              controller.signal
            );
            if (aborted || controller.signal.aborted) return;
            activeIter = completion[Symbol.asyncIterator]();
            while (true) {
              if (aborted || controller.signal.aborted) {
                if (typeof activeIter.return === "function") {
                  await activeIter.return(void 0).catch(() => {
                  });
                }
                return;
              }
              const next = await raceAbort(activeIter.next(), controller.signal);
              if (next.done) break;
              if (aborted || controller.signal.aborted) {
                if (typeof activeIter.return === "function") {
                  await activeIter.return(void 0).catch(() => {
                  });
                }
                return;
              }
              const delta = next.value.choices[0]?.delta?.content;
              if (delta) yield { type: "text", content: delta };
            }
            if (aborted || controller.signal.aborted) return;
            yield { type: "done" };
          } catch (err) {
            if (isAbortError(err) || aborted || controller.signal.aborted) return;
            const message = err instanceof Error ? err.message : String(err);
            yield adapterErrorChunk(message, { cause: err });
          }
        },
        abort: () => {
          softAbort();
        }
      };
    }
  };
}
var webllmAdapter = webllm;
function requireCapabilities(request) {
  const needs = {};
  if (request.context?.tools && request.context.tools.length > 0) needs.tools = true;
  return needs;
}
function matchesCapabilities(need, have) {
  if (!have) return true;
  for (const key of Object.keys(need)) {
    if (key === "extensions") continue;
    if (need[key] && have[key] === false) return false;
  }
  return true;
}
function pickSyncPolicy(pool, policy) {
  if (policy === "cheapest") {
    const c = pool.reduce((best, x) => (x.cost ?? Infinity) < (best.cost ?? Infinity) ? x : best, pool[0]);
    return { c, reason: "cheapest" };
  }
  if (policy === "fastest") {
    const c = pool.reduce((best, x) => (x.latencyMs ?? Infinity) < (best.latencyMs ?? Infinity) ? x : best, pool[0]);
    return { c, reason: "fastest" };
  }
  if (policy === "greenest") {
    const c = pool.reduce((best, x) => (x.gCO2PerKtok ?? Infinity) < (best.gCO2PerKtok ?? Infinity) ? x : best, pool[0]);
    return { c, reason: "greenest" };
  }
  if (policy === "green-cost") {
    const carbonValues = pool.map((p) => p.gCO2PerKtok).filter((v) => v != null);
    const costValues = pool.map((p) => p.cost).filter((v) => v != null);
    const maxC = Math.max(1, ...carbonValues);
    const maxCost = Math.max(1, ...costValues);
    const score = (x) => {
      const carbon = (x.gCO2PerKtok ?? maxC / 2) / maxC;
      const cost = (x.cost ?? maxCost / 2) / maxCost;
      return carbon + cost;
    };
    const c = pool.reduce((best, x) => score(x) < score(best) ? x : best, pool[0]);
    return { c, reason: "green-cost" };
  }
  return { c: pool[0], reason: "capability-match" };
}
function matchesRegion(candidate, region) {
  return region === void 0 || candidate.region === region;
}
function createRouter(options) {
  const { candidates } = options;
  if (candidates.length === 0) {
    throw new ConfigError({
      code: ErrorCodes.AK_CONFIG_INVALID,
      message: "createRouter requires at least one candidate",
      hint: "Pass at least one candidate, e.g. createRouter({ candidates: [{ id, adapter, capabilities }] })."
    });
  }
  const policy = options.policy ?? "cheapest";
  return {
    createSource: (request) => {
      const need = requireCapabilities(request);
      const region = options.regionOf?.(request) ?? options.region;
      const capable = candidates.filter((c2) => matchesCapabilities(need, c2.capabilities ?? c2.adapter.capabilities));
      const eligible = capable.filter((c2) => matchesRegion(c2, region));
      if (capable.length > 0 && eligible.length === 0 && region !== void 0) {
        throw new ConfigError({
          code: ErrorCodes.AK_CONFIG_INVALID,
          message: `no candidate satisfies required region: ${region}`,
          hint: "Set candidate.region to the requested data-residency region, or remove the router region requirement."
        });
      }
      const classified = options.classify?.(request);
      if (typeof classified === "string") {
        const c2 = eligible.find((x) => x.id === classified);
        if (c2) {
          options.onRoute?.({ id: c2.id, reason: region ? `classify:id:${region}` : "classify:id", request });
          return c2.adapter.createSource(request);
        }
      }
      let pool = eligible;
      let pickedBy;
      if (Array.isArray(classified) && classified.length > 0) {
        const filtered = eligible.filter((c2) => c2.tags && classified.every((t) => c2.tags.includes(t)));
        if (filtered.length > 0) {
          pool = filtered;
          pickedBy = region ? `classify:tags:${region}` : "classify:tags";
        }
      }
      if (pool.length === 0) {
        throw new AdapterError({
          code: ErrorCodes.AK_ADAPTER_STREAM_FAILED,
          message: "no candidate satisfies the request",
          hint: "Ensure at least one candidate declares the required capabilities (tools, json, etc.)."
        });
      }
      if (typeof policy === "function") {
        const maybe = policy({ request, candidates: pool });
        if (typeof maybe !== "string") {
          const controller = new AbortController();
          let child;
          return {
            abort: () => {
              controller.abort();
              child?.abort();
            },
            stream: async function* () {
              let id;
              try {
                id = await raceAbort(maybe, controller.signal);
              } catch (err) {
                if (isAbortError(err)) return;
                const error = err instanceof Error ? err : new Error(String(err));
                yield {
                  type: "error",
                  content: error.message,
                  metadata: { error }
                };
                return;
              }
              const c3 = pool.find((x) => x.id === id);
              if (!c3) {
                const error = new ConfigError({
                  code: ErrorCodes.AK_CONFIG_INVALID,
                  message: `policy returned unknown id: ${id}`,
                  hint: "Custom policy functions must return one of the candidate ids."
                });
                yield {
                  type: "error",
                  content: error.message,
                  metadata: { error }
                };
                return;
              }
              try {
                options.onRoute?.({ id: c3.id, reason: pickedBy ?? "custom policy", request });
                child = c3.adapter.createSource(request);
                for await (const chunk of child.stream()) {
                  yield chunk;
                }
              } catch (err) {
                if (controller.signal.aborted || isAbortError(err)) return;
                const error = err instanceof Error ? err : new Error(String(err));
                yield {
                  type: "error",
                  content: error.message,
                  metadata: { error }
                };
              }
            }
          };
        }
        const c2 = pool.find((x) => x.id === maybe);
        if (!c2) {
          throw new ConfigError({
            code: ErrorCodes.AK_CONFIG_INVALID,
            message: `policy returned unknown id: ${maybe}`,
            hint: "Custom policy functions must return one of the candidate ids."
          });
        }
        options.onRoute?.({ id: c2.id, reason: pickedBy ?? "custom policy", request });
        return c2.adapter.createSource(request);
      }
      const { c, reason } = pickSyncPolicy(pool, policy);
      options.onRoute?.({ id: c.id, reason: pickedBy ?? reason, request });
      return c.adapter.createSource(request);
    }
  };
}

// src/carbon.ts
var DEFAULT_CARBON_TABLE = {
  // Anthropic — primarily AWS us-east-* / eu-west-* via Bedrock-style fronts.
  "anthropic:us-east-1": 0.42,
  "anthropic:us-west-2": 0.18,
  "anthropic:eu-central-1": 0.32,
  "anthropic:eu-west-1": 0.27,
  // OpenAI — Azure East US / West Europe / Sweden Central.
  "openai:eastus": 0.4,
  "openai:westus3": 0.19,
  "openai:swedencentral": 0.04,
  "openai:westeurope": 0.28,
  // Google (Vertex / Gemini) — typically reports lowest PUE.
  "google:us-central1": 0.34,
  "google:us-west1": 0.16,
  "google:europe-west1": 0.21,
  "google:europe-north1": 0.05,
  // AWS Bedrock direct.
  "aws:us-east-1": 0.42,
  "aws:us-west-2": 0.18,
  "aws:eu-west-1": 0.27,
  // Local / on-device — only the device's grid matters.
  "ollama:local": 0.3,
  "webllm:browser": 0.3,
  "lmstudio:local": 0.3,
  // Self-hosted / community.
  "groq:us-east-1": 0.4,
  "fireworks:us-west-2": 0.18,
  "together:us-east-1": 0.42,
  "cerebras:us-west-2": 0.18
};
function defaultKey(candidate) {
  if (!candidate.region) return void 0;
  const provider = candidate.id.split(/[-:]/)[0];
  return `${provider}:${candidate.region}`;
}
function applyCarbonTable(candidates, options = {}) {
  const table = options.table ?? DEFAULT_CARBON_TABLE;
  const keyFor = options.keyFor ?? defaultKey;
  return candidates.map((c) => {
    if (c.gCO2PerKtok != null) return c;
    const key = keyFor(c);
    const value = key ? table[key] : void 0;
    return { ...c, gCO2PerKtok: value ?? options.fallback };
  });
}
function estimateCO2Grams(gCO2PerKtok, tokens) {
  if (gCO2PerKtok == null) return 0;
  return tokens / 1e3 * gCO2PerKtok;
}
async function drain(source, timeoutMs) {
  const chunks = [];
  let text = "";
  let timer;
  let timedOut = false;
  let error;
  if (timeoutMs !== void 0) {
    timer = setTimeout(() => {
      timedOut = true;
      source.abort();
    }, timeoutMs);
  }
  try {
    for await (const chunk of source.stream()) {
      chunks.push(chunk);
      if (chunk.type === "text" && typeof chunk.content === "string") text += chunk.content;
      if (chunk.type === "error") {
        const metaErr = chunk.metadata?.error;
        error = metaErr instanceof Error ? metaErr : new Error(chunk.content ?? "stream error");
      }
    }
  } catch (err) {
    if (!isAbortError(err)) {
      error = err instanceof Error ? err : new Error(String(err));
    } else if (!timedOut) {
      error = err instanceof Error ? err : new Error(String(err));
    }
  } finally {
    if (timer) clearTimeout(timer);
  }
  if (timedOut) error = new Error(`timeout after ${timeoutMs}ms`);
  return { chunks, text, error };
}
function majorityVote(branches, candidates) {
  const counts = /* @__PURE__ */ new Map();
  const weightById = new Map(candidates.map((c) => [c.id, c.weight ?? 1]));
  for (const b of branches) {
    if (b.error) continue;
    counts.set(b.text, (counts.get(b.text) ?? 0) + (weightById.get(b.id) ?? 1));
  }
  let best = "";
  let bestScore = -1;
  for (const [text, score] of counts) {
    if (score > bestScore) {
      bestScore = score;
      best = text;
    }
  }
  return best;
}
function createEnsembleAdapter(options) {
  if (options.candidates.length === 0) {
    throw new ConfigError({
      code: ErrorCodes.AK_CONFIG_INVALID,
      message: "createEnsembleAdapter requires at least one candidate",
      hint: "Pass at least one candidate, e.g. createEnsembleAdapter({ candidates: [{ id, adapter }] })."
    });
  }
  const aggregate = options.aggregate ?? "majority-vote";
  return {
    createSource: (request) => {
      let aborted = false;
      const sources = [];
      const run = async () => {
        const tasks = options.candidates.map(async (c, i) => {
          try {
            const source = c.adapter.createSource(request);
            sources[i] = source;
            if (aborted) {
              source.abort();
              return { id: c.id, chunks: [], text: "", error: new Error("aborted") };
            }
            const { chunks, text, error } = await drain(source, options.timeoutMs);
            return { id: c.id, chunks, text, error };
          } catch (err) {
            const error = err instanceof Error ? err : new Error(String(err));
            return { id: c.id, chunks: [], text: "", error };
          }
        });
        return Promise.all(tasks);
      };
      const finalText = async (branches) => {
        if (typeof aggregate === "function") return aggregate(branches);
        if (aggregate === "concat") {
          return branches.filter((b) => !b.error).map((b) => b.text).join("\n---\n");
        }
        if (aggregate === "longest") {
          return branches.filter((b) => !b.error).reduce(
            (best, b) => b.text.length > best.length ? b.text : best,
            ""
          );
        }
        return majorityVote(branches, options.candidates);
      };
      return {
        abort: () => {
          aborted = true;
          for (const s of sources) s?.abort();
        },
        stream: async function* () {
          if (aborted) return;
          const branches = await run();
          options.onBranches?.(branches);
          if (aborted) {
            for (const s of sources) s?.abort();
            return;
          }
          try {
            const text = await finalText(branches);
            if (!text && branches.every((b) => b.error)) {
              const summary = branches.map((b) => `${b.id}: ${b.error?.message ?? "unknown"}`).join("; ");
              const err = new AdapterError({
                code: ErrorCodes.AK_ADAPTER_STREAM_FAILED,
                message: `all ensemble branches failed (${summary})`,
                hint: "Inspect each branch error via options.onBranches or the err.branchErrors field."
              });
              err.branchErrors = branches.map((b) => ({ id: b.id, error: b.error }));
              yield {
                type: "error",
                content: err.message,
                metadata: { error: err }
              };
              return;
            }
            yield {
              type: "text",
              content: text,
              metadata: {
                ensemble: branches.map((b) => ({
                  id: b.id,
                  bytes: b.text.length,
                  error: b.error?.message
                }))
              }
            };
            yield { type: "done" };
          } catch (err) {
            if (aborted || isAbortError(err)) return;
            const error = err instanceof Error ? err : new Error(String(err));
            yield {
              type: "error",
              content: error.message,
              metadata: { error }
            };
          }
        }
      };
    }
  };
}
function createFallbackAdapter(candidates, options = {}) {
  if (candidates.length === 0) {
    throw new ConfigError({
      code: ErrorCodes.AK_CONFIG_INVALID,
      message: "createFallbackAdapter requires at least one candidate",
      hint: 'Pass at least one candidate, e.g. createFallbackAdapter([{ id: "primary", adapter }]).'
    });
  }
  return {
    createSource: (request) => {
      let active;
      let aborted = false;
      return {
        abort: () => {
          aborted = true;
          active?.abort();
        },
        stream: async function* () {
          const errors = [];
          for (let i = 0; i < candidates.length; i++) {
            if (aborted) return;
            const candidate = candidates[i];
            let source;
            try {
              source = candidate.adapter.createSource(request);
            } catch (err2) {
              const error = err2 instanceof Error ? err2 : new Error(String(err2));
              errors.push({ id: candidate.id, error });
              options.onFallback?.({ id: candidate.id, index: i, error });
              if (options.shouldRetry && !options.shouldRetry(error, i)) {
                yield {
                  type: "error",
                  content: error.message,
                  metadata: { error }
                };
                return;
              }
              continue;
            }
            active = source;
            const iter = source.stream()[Symbol.asyncIterator]();
            let firstReal;
            let branchError;
            const leadingUsage = [];
            try {
              while (true) {
                if (aborted) {
                  source.abort();
                  return;
                }
                const r = await iter.next();
                if (r.done) {
                  branchError = new Error(`candidate ${candidate.id} emitted no chunks`);
                  break;
                }
                if (r.value.type === "error") {
                  const metaErr = r.value.metadata?.error;
                  branchError = metaErr instanceof Error ? metaErr : new Error(
                    `candidate ${candidate.id}: ${r.value.content ?? "stream error"}`
                  );
                  break;
                }
                if (r.value.type === "usage") {
                  leadingUsage.push(r.value);
                  continue;
                }
                firstReal = r.value;
                break;
              }
            } catch (err2) {
              if (isAbortError(err2) || aborted) {
                source.abort();
                return;
              }
              branchError = err2 instanceof Error ? err2 : new Error(String(err2));
            }
            if (branchError || !firstReal) {
              const error = branchError ?? new Error(`candidate ${candidate.id} emitted no chunks`);
              errors.push({ id: candidate.id, error });
              options.onFallback?.({ id: candidate.id, index: i, error });
              try {
                source.abort();
              } catch {
              }
              if (typeof iter.return === "function") {
                try {
                  await iter.return(void 0);
                } catch {
                }
              }
              if (options.shouldRetry && !options.shouldRetry(error, i)) {
                yield {
                  type: "error",
                  content: error.message,
                  metadata: { error }
                };
                return;
              }
              active = void 0;
              continue;
            }
            for (const chunk of leadingUsage) yield chunk;
            yield firstReal;
            while (true) {
              if (aborted) {
                source.abort();
                return;
              }
              try {
                const next = await iter.next();
                if (next.done) return;
                yield next.value;
              } catch (err2) {
                if (isAbortError(err2) || aborted) {
                  source.abort();
                  return;
                }
                const error = err2 instanceof Error ? err2 : new Error(String(err2));
                yield {
                  type: "error",
                  content: error.message,
                  metadata: { error }
                };
                return;
              }
            }
          }
          const summary = errors.map((e) => `${e.id}: ${e.error.message}`).join("; ");
          const err = new AdapterError({
            code: ErrorCodes.AK_ADAPTER_STREAM_FAILED,
            message: `all fallback candidates failed (${summary})`,
            hint: "Check each candidate adapter's configuration and provider keys."
          });
          yield {
            type: "error",
            content: err.message,
            metadata: { error: err }
          };
        }
      };
    }
  };
}
function mockAdapter(options) {
  const { response, delayMs = 0, history } = options;
  let callIndex = 0;
  return {
    capabilities: {
      streaming: true,
      tools: true,
      reasoning: true,
      multiModal: true,
      usage: true
    },
    createSource: (request) => {
      const controller = new AbortController();
      let myCall;
      let cancelled = false;
      return {
        stream: async function* () {
          if (cancelled || controller.signal.aborted) return;
          try {
            if (myCall === void 0) {
              myCall = callIndex++;
              history?.push(request);
            }
            const chunks = resolve(response, myCall, request);
            for (const chunk of chunks) {
              if (cancelled || controller.signal.aborted) return;
              if (delayMs > 0) {
                await abortableSleep(delayMs, controller.signal, (ms) => new Promise((resolveTimer) => setTimeout(resolveTimer, ms)));
              }
              if (cancelled || controller.signal.aborted) return;
              if (chunk.type === "error" && !(chunk.metadata?.error instanceof Error)) {
                const normalized = adapterErrorChunk(
                  chunk.content ?? "Mock adapter error",
                  { cause: chunk.metadata?.error }
                );
                yield {
                  ...chunk,
                  metadata: { ...chunk.metadata, ...normalized.metadata }
                };
                return;
              }
              yield chunk;
              if (chunk.type === "done" || chunk.type === "error") return;
            }
            yield { type: "done" };
          } catch (error) {
            if (cancelled || controller.signal.aborted || isAbortError(error)) return;
            const message = error instanceof Error ? error.message : String(error);
            yield adapterErrorChunk(message, { cause: error });
          }
        },
        abort: () => {
          cancelled = true;
          controller.abort();
        }
      };
    }
  };
}
function resolve(response, callIndex, request) {
  if (Array.isArray(response) && response.length > 0 && Array.isArray(response[0])) {
    const sequence = response;
    const item = sequence[callIndex % sequence.length];
    return item;
  }
  if (Array.isArray(response) && response.length > 0 && typeof response[0] === "function") {
    const sequence = response;
    return sequence[callIndex % sequence.length](request);
  }
  if (typeof response === "function") {
    return response(request);
  }
  return response;
}
function recordingAdapter(inner, sink) {
  return {
    capabilities: inner.capabilities,
    createSource: (request) => {
      let innerSource;
      const captured = [];
      let aborted = false;
      return {
        stream: async function* () {
          if (aborted) return;
          const recordedAt = (/* @__PURE__ */ new Date()).toISOString();
          try {
            innerSource = inner.createSource(request);
            for await (const chunk of innerSource.stream()) {
              if (aborted) return;
              captured.push(chunk);
              yield chunk;
              if (chunk.type === "done" || chunk.type === "error") return;
            }
            const errorChunk = adapterErrorChunk("Recorded adapter ended without a terminal chunk");
            captured.push(errorChunk);
            yield errorChunk;
          } catch (error) {
            if (aborted || isAbortError(error)) return;
            const message = error instanceof Error ? error.message : String(error);
            const errorChunk = adapterErrorChunk(message, { cause: error });
            captured.push(errorChunk);
            yield errorChunk;
          } finally {
            try {
              await sink.push({ recordedAt, request, chunks: captured });
            } catch {
            }
          }
        },
        abort: () => {
          aborted = true;
          innerSource?.abort();
        }
      };
    }
  };
}
function inMemorySink() {
  const fixture = [];
  return {
    fixture,
    push(turn) {
      fixture.push(turn);
    }
  };
}
function replayAdapter(fixture) {
  if (fixture.length === 0) {
    throw new ConfigError({
      code: ErrorCodes.AK_CONFIG_INVALID,
      message: "replayAdapter: fixture is empty",
      hint: "Pass a non-empty fixture; record one with recordingAdapter() first."
    });
  }
  return mockAdapter({
    response: fixture.map((turn) => turn.chunks)
  });
}
async function throwIfNotOk(response, label, _url) {
  if (response.ok) return;
  void response.body?.cancel().catch(() => {
  });
  throw embeddingError(label, `HTTP ${response.status}`);
}
function embeddingError(label, detail, cause) {
  return new AdapterError({
    code: ErrorCodes.AK_ADAPTER_STREAM_FAILED,
    message: `${label} embedding failed: ${detail}`,
    cause
  });
}
function requireEmbeddingVector(value, label) {
  if (!Array.isArray(value) || value.length === 0) {
    throw new AdapterError({
      code: ErrorCodes.AK_ADAPTER_STREAM_FAILED,
      message: `${label} returned an empty or missing embedding vector`,
      hint: "The provider responded 2xx but the embedding payload was empty or malformed."
    });
  }
  const vector = [];
  for (let i = 0; i < value.length; i++) {
    const n = value[i];
    if (typeof n !== "number" || !Number.isFinite(n)) {
      throw new AdapterError({
        code: ErrorCodes.AK_ADAPTER_STREAM_FAILED,
        message: `${label} returned a non-finite embedding value at index ${i}`,
        hint: "Embedding vectors must be finite numbers only."
      });
    }
    vector.push(n);
  }
  return vector;
}

// src/embedders/openai.ts
async function fetchAvailableModels(baseUrl, apiKey) {
  const url = `${baseUrl}/v1/models`;
  const response = await fetch(url, {
    headers: { "Authorization": `Bearer ${apiKey}` }
  });
  await throwIfNotOk(response, "openai");
  const data = await response.json();
  return data.data.map((m) => m.id).filter((id) => id.includes("embed")).sort();
}
async function buildModelError(baseUrl, apiKey, originalError) {
  try {
    const models = await fetchAvailableModels(baseUrl, apiKey);
    const list = models.length > 0 ? models.join(", ") : "none found";
    return embeddingError("OpenAI", `${originalError}. Available embedding models: ${list}`);
  } catch (fetchError) {
    return embeddingError("OpenAI", `${originalError}. Could not fetch available models`, fetchError);
  }
}
function openaiEmbedder(config) {
  const { apiKey, model = "text-embedding-3-small", baseUrl = "https://api.openai.com" } = config;
  return async (text) => {
    const response = await fetch(`${baseUrl}/v1/embeddings`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${apiKey}`
      },
      body: JSON.stringify({ model, input: text })
    });
    if (!response.ok) {
      void response.body?.cancel().catch(() => {
      });
      const message = `HTTP ${response.status}`;
      throw await buildModelError(baseUrl, apiKey, message);
    }
    const data = await response.json();
    const embedding = data.data?.[0]?.embedding;
    return requireEmbeddingVector(embedding, "OpenAI");
  };
}

// src/embedders/gemini.ts
async function fetchAvailableModels2(baseUrl, apiKey) {
  const url = `${baseUrl}/v1beta/models`;
  const response = await fetch(url, {
    headers: { "x-goog-api-key": apiKey }
  });
  await throwIfNotOk(response, "gemini");
  const data = await response.json();
  return data.models.filter((m) => m.supportedGenerationMethods.includes("embedContent")).map((m) => m.name.replace("models/", "")).sort();
}
async function buildModelError2(baseUrl, apiKey, originalError) {
  try {
    const models = await fetchAvailableModels2(baseUrl, apiKey);
    const list = models.length > 0 ? models.join(", ") : "none found";
    return embeddingError("Gemini", `${originalError}. Available embedding models: ${list}`);
  } catch (fetchError) {
    return embeddingError("Gemini", `${originalError}. Could not fetch available models`, fetchError);
  }
}
function geminiEmbedder(config) {
  const {
    apiKey,
    model = "text-embedding-004",
    baseUrl = "https://generativelanguage.googleapis.com"
  } = config;
  return async (text) => {
    const response = await fetch(
      `${baseUrl}/v1beta/models/${model}:embedContent`,
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "x-goog-api-key": apiKey
        },
        body: JSON.stringify({
          model: `models/${model}`,
          content: { parts: [{ text }] }
        })
      }
    );
    if (!response.ok) {
      void response.body?.cancel().catch(() => {
      });
      const message = `HTTP ${response.status}`;
      throw await buildModelError2(baseUrl, apiKey, message);
    }
    const data = await response.json();
    return requireEmbeddingVector(data.embedding?.values, "Gemini");
  };
}

// src/embedders/ollama.ts
async function fetchAvailableModels3(baseUrl) {
  const url = `${baseUrl}/api/tags`;
  const response = await fetch(url);
  await throwIfNotOk(response, "ollama");
  const data = await response.json();
  return data.models.map((m) => m.name).filter((name) => name.includes("embed")).sort();
}
async function buildModelError3(baseUrl, originalError) {
  try {
    const models = await fetchAvailableModels3(baseUrl);
    const list = models.length > 0 ? models.join(", ") : "none found";
    return embeddingError("Ollama", `${originalError}. Available embedding models: ${list}`);
  } catch (fetchError) {
    return embeddingError("Ollama", `${originalError}. Could not fetch available models`, fetchError);
  }
}
function ollamaEmbedder(config) {
  const { model = "nomic-embed-text", baseUrl = "http://localhost:11434" } = config;
  return async (text) => {
    const response = await fetch(`${baseUrl}/api/embed`, {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ model, input: text })
    });
    if (!response.ok) {
      void response.body?.cancel().catch(() => {
      });
      const message = `HTTP ${response.status}`;
      throw await buildModelError3(baseUrl, message);
    }
    const data = await response.json();
    const first = Array.isArray(data.embeddings) ? data.embeddings[0] : void 0;
    return requireEmbeddingVector(first, "Ollama");
  };
}
async function fetchAvailableModels4(provider, baseUrl, apiKey) {
  const url = `${baseUrl}/v1/models`;
  const response = await fetch(url, {
    headers: { "Authorization": `Bearer ${apiKey}` }
  });
  await throwIfNotOk(response, provider);
  const data = await response.json();
  return data.data.map((m) => m.id).filter((id) => id.includes("embed")).sort();
}
async function buildModelError4(provider, baseUrl, apiKey, originalError) {
  try {
    const models = await fetchAvailableModels4(provider, baseUrl, apiKey);
    const list = models.length > 0 ? models.join(", ") : "none found";
    return embeddingError(provider, `${originalError}. Available embedding models: ${list}`);
  } catch (fetchError) {
    return embeddingError(provider, `${originalError}. Could not fetch available models`, fetchError);
  }
}
function createOpenAICompatibleEmbedder(provider, defaultBaseUrl) {
  return function embedder(config) {
    if (!config.model) {
      throw new ConfigError({
        code: ErrorCodes.AK_CONFIG_INVALID,
        message: `Model is required for ${provider}. Pass { model: "<model-name>" }.`,
        hint: `${provider} does not infer a default; pick a recent embedding model and pass it explicitly.`
      });
    }
    const { apiKey, model, baseUrl = defaultBaseUrl } = config;
    return async (text) => {
      const response = await fetch(`${baseUrl}/v1/embeddings`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "Authorization": `Bearer ${apiKey}`
        },
        body: JSON.stringify({ model, input: text })
      });
      if (!response.ok) {
        void response.body?.cancel().catch(() => {
        });
        const message = `HTTP ${response.status}`;
        throw await buildModelError4(provider, baseUrl, apiKey, message);
      }
      const data = await response.json();
      const embedding = data.data?.[0]?.embedding;
      return requireEmbeddingVector(embedding, provider);
    };
  };
}

// src/embedders/deepseek.ts
var deepseekEmbedder = createOpenAICompatibleEmbedder("DeepSeek", "https://api.deepseek.com");

// src/embedders/grok.ts
var grokEmbedder = createOpenAICompatibleEmbedder("Grok", "https://api.x.ai");

// src/embedders/kimi.ts
var kimiEmbedder = createOpenAICompatibleEmbedder("Kimi", "https://api.moonshot.ai");
var DEFAULT_DEPRECATION_TABLE = [
  // OpenAI
  { provider: "openai", model: "gpt-3.5-turbo-0301", successor: "gpt-4o-mini", sunsetOn: "2024-09-13" },
  { provider: "openai", model: "gpt-3.5-turbo-0613", successor: "gpt-4o-mini", sunsetOn: "2024-09-13" },
  { provider: "openai", model: "gpt-4-0314", successor: "gpt-4o", sunsetOn: "2024-06-13" },
  { provider: "openai", model: "gpt-4-32k", successor: "gpt-4o", sunsetOn: "2024-06-06" },
  { provider: "openai", model: "text-davinci-003", successor: "gpt-4o-mini", sunsetOn: "2024-01-04" },
  // Anthropic
  { provider: "anthropic", model: "claude-2.0", successor: "claude-3-5-sonnet-latest", sunsetOn: "2025-07-21" },
  { provider: "anthropic", model: "claude-2.1", successor: "claude-3-5-sonnet-latest", sunsetOn: "2025-07-21" },
  { provider: "anthropic", model: "claude-instant-1.2", successor: "claude-3-5-haiku-latest", sunsetOn: "2024-07-22" },
  { provider: "anthropic", model: "claude-3-sonnet-20240229", successor: "claude-3-5-sonnet-latest", sunsetOn: "2025-07-21" },
  // Google
  { provider: "google", model: "gemini-1.0-pro", successor: "gemini-1.5-pro", sunsetOn: "2025-02-15" },
  { provider: "google", model: "gemini-pro-vision", successor: "gemini-1.5-pro", sunsetOn: "2024-07-12" }
];
function resolveModel(input, policy) {
  const table = policy.table ?? DEFAULT_DEPRECATION_TABLE;
  const hit = table.find((d) => d.provider === input.provider && d.model === input.model);
  if (!hit) return { model: input.model, remapped: false };
  const log = policy.logger ?? ((msg) => console.warn(msg));
  const sunset = hit.sunsetOn ? ` (sunset ${hit.sunsetOn})` : "";
  const successor = hit.successor ? ` Suggested successor: ${hit.successor}.` : "";
  const base = `[agentskit] Model "${input.provider}:${input.model}" is deprecated${sunset}.${successor}`;
  switch (policy.onDeprecation) {
    case "fail":
      throw new ConfigError({
        code: ErrorCodes.AK_CONFIG_INVALID,
        message: base,
        hint: hit.successor ? `Set model to "${hit.successor}".` : "Pick a supported model from the provider."
      });
    case "remap": {
      if (!hit.successor) {
        throw new ConfigError({
          code: ErrorCodes.AK_CONFIG_INVALID,
          message: `${base} No successor available \u2014 cannot remap.`
        });
      }
      log(`${base} Auto-remapping to "${hit.successor}".`);
      return { model: hit.successor, remapped: true, deprecation: hit };
    }
    case "warn":
    default:
      log(base);
      return { model: input.model, remapped: false, deprecation: hit };
  }
}
function withDeprecationPolicy(factory, options) {
  resolveModel({ provider: options.provider, model: options.model }, options);
  return factory;
}

// src/credential-rotation.ts
function createRotatingCredentials(initial, options) {
  let value = initial;
  const handlers = /* @__PURE__ */ new Set();
  return {
    current: () => value,
    rotate: async (next) => {
      value = next;
      const event = {
        rotatedAt: (/* @__PURE__ */ new Date()).toISOString(),
        id: options.id,
        fingerprint: next.slice(-4)
      };
      for (const h of handlers) h(event);
      return next;
    },
    onRotate: (handler) => {
      handlers.add(handler);
      return () => handlers.delete(handler);
    }
  };
}
async function refreshCredentials(adapter, next, options) {
  const log = options?.logger ?? ((msg) => console.log(msg));
  if (adapter && typeof adapter === "object" && "refreshCredentials" in adapter && typeof adapter.refreshCredentials === "function") {
    await adapter.refreshCredentials(next);
    log(`[agentskit] credentials refreshed${options?.id ? ` (${options.id})` : ""}`);
    return true;
  }
  log(`[agentskit] adapter does not support credential rotation; restart required${options?.id ? ` (${options.id})` : ""}`);
  return false;
}

export { DEFAULT_CARBON_TABLE, DEFAULT_DEPRECATION_TABLE, anthropic, applyCarbonTable, azureOpenAI, azureOpenAIAdapter, bail, bailAdapter, bedrock, bedrockAdapter, cerebras, cerebrasAdapter, cohere, cohereAdapter, createEnsembleAdapter, createFallbackAdapter, createOpenAICompatibleEmbedder, createRotatingCredentials, createRouter, deepseek, deepseekEmbedder, estimateCO2Grams, fireworks, gemini, geminiEmbedder, generic, grok, grokEmbedder, groq, groqAdapter, huggingface, inMemorySink, kimi, kimiEmbedder, langchain, langgraph, llamacpp, lmstudio, mistral, mockAdapter, ollama, ollamaEmbedder, openaiEmbedder, openrouter, qwen, recordingAdapter, refreshCredentials, replayAdapter, replicate, replicateAdapter, resolveModel, together, vercelAI, vertex, vertexAdapter, vllm, webllm, webllmAdapter, withDeprecationPolicy };
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map