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

// types/typeGuards.ts
var isValidAIClientMessage = (data) => {
  if (!data || typeof data !== "object") {
    return false;
  }
  if (!("type" in data) || typeof data.type !== "string") {
    return false;
  }
  switch (data.type) {
    case "message":
      return "content" in data && typeof data.content === "string";
    case "cancel":
      return "conversationId" in data && typeof data.conversationId === "string";
    case "branch":
      return "messageId" in data && typeof data.messageId === "string" && "content" in data && typeof data.content === "string" && "conversationId" in data && typeof data.conversationId === "string";
    default:
      return false;
  }
}, isValidAIServerMessage = (data) => {
  if (!data || typeof data !== "object") {
    return false;
  }
  if (!("type" in data) || typeof data.type !== "string") {
    return false;
  }
  switch (data.type) {
    case "chunk":
      return "content" in data && typeof data.content === "string" && "messageId" in data && "conversationId" in data;
    case "thinking":
      return "content" in data && typeof data.content === "string" && "messageId" in data && "conversationId" in data;
    case "tool_status":
      return "name" in data && "status" in data && "messageId" in data && "conversationId" in data;
    case "image":
      return "data" in data && typeof data.data === "string" && "format" in data && typeof data.format === "string" && "isPartial" in data && typeof data.isPartial === "boolean" && "messageId" in data && "conversationId" in data;
    case "complete":
      return "messageId" in data && "conversationId" in data;
    case "rag_retrieved":
      return "conversationId" in data && "messageId" in data && "sources" in data && Array.isArray(data.sources);
    case "error":
      return "message" in data && typeof data.message === "string";
    default:
      return false;
  }
}, isValidHMRClientMessage = (data) => {
  if (!data || typeof data !== "object") {
    return false;
  }
  if (!("type" in data) || typeof data.type !== "string") {
    return false;
  }
  switch (data.type) {
    case "ping":
      return true;
    case "ready":
      return true;
    case "request-rebuild":
      return true;
    case "hydration-error":
      return true;
    case "hmr-timing":
      return true;
    default:
      return false;
  }
};

// src/ai/client/actions.ts
var serverMessageToAction = (msg) => {
  switch (msg.type) {
    case "chunk":
      return {
        content: msg.content,
        conversationId: msg.conversationId,
        messageId: msg.messageId,
        type: "chunk"
      };
    case "thinking":
      return {
        content: msg.content,
        conversationId: msg.conversationId,
        messageId: msg.messageId,
        type: "thinking"
      };
    case "tool_status":
      return {
        conversationId: msg.conversationId,
        input: msg.input,
        messageId: msg.messageId,
        name: msg.name,
        result: msg.result,
        status: msg.status,
        type: "tool_status"
      };
    case "image":
      return {
        conversationId: msg.conversationId,
        data: msg.data,
        format: msg.format,
        imageId: msg.imageId,
        isPartial: msg.isPartial,
        messageId: msg.messageId,
        revisedPrompt: msg.revisedPrompt,
        type: "image"
      };
    case "complete":
      return {
        conversationId: msg.conversationId,
        durationMs: msg.durationMs,
        messageId: msg.messageId,
        model: msg.model,
        sources: msg.sources,
        type: "complete",
        usage: msg.usage
      };
    case "rag_retrieved":
      return {
        conversationId: msg.conversationId,
        messageId: msg.messageId,
        sources: msg.sources,
        type: "rag_retrieved"
      };
    case "error":
      return { message: msg.message, type: "error" };
    default:
      return null;
  }
};

// src/ai/client/connection.ts
var WS_OPEN = 1;
var WS_NORMAL_CLOSURE = 1000;
var WS_CLOSED = 3;
var DEFAULT_PING_INTERVAL = 30000;
var RECONNECT_INITIAL_DELAY = 500;
var RECONNECT_POLL_INTERVAL = 300;
var DEFAULT_MAX_RECONNECT_ATTEMPTS = 60;
var noop = () => {};
var noopUnsubscribe = () => noop;
var NOOP_CONNECTION = {
  close: noop,
  send: noop,
  subscribe: noopUnsubscribe,
  getReadyState: () => WS_CLOSED
};
var buildWsUrl = (path) => {
  const { hostname, port, protocol } = window.location;
  const wsProtocol = protocol === "https:" ? "wss:" : "ws:";
  const portSuffix = port ? `:${port}` : "";
  return `${wsProtocol}//${hostname}${portSuffix}${path}`;
};
var parseServerMessage = (event) => {
  let data;
  try {
    data = JSON.parse(String(event.data));
  } catch {
    return null;
  }
  if (data && typeof data === "object" && "type" in data && data.type === "pong") {
    return null;
  }
  if (!isValidAIServerMessage(data)) {
    return null;
  }
  return data;
};
var createAIConnection = (path, options = {}) => {
  if (typeof window === "undefined") {
    return NOOP_CONNECTION;
  }
  const shouldReconnect = options.reconnect !== false;
  const pingInterval = options.pingInterval ?? DEFAULT_PING_INTERVAL;
  const maxReconnectAttempts = options.maxReconnectAttempts ?? DEFAULT_MAX_RECONNECT_ATTEMPTS;
  const listeners = new Set;
  const connState = {
    isConnected: false,
    pingInterval: null,
    reconnectAttempts: 0,
    reconnectTimeout: null,
    ws: null
  };
  const clearTimers = () => {
    if (connState.pingInterval) {
      clearInterval(connState.pingInterval);
      connState.pingInterval = null;
    }
    if (connState.reconnectTimeout) {
      clearTimeout(connState.reconnectTimeout);
      connState.reconnectTimeout = null;
    }
  };
  const scheduleReconnect = () => {
    connState.reconnectAttempts++;
    const delay = connState.reconnectAttempts === 1 ? RECONNECT_INITIAL_DELAY : RECONNECT_POLL_INTERVAL;
    connState.reconnectTimeout = setTimeout(() => {
      if (connState.reconnectAttempts > maxReconnectAttempts) {
        return;
      }
      connect();
    }, delay);
  };
  const connect = () => {
    const url = buildWsUrl(path);
    const wsInstance = new WebSocket(url, options.protocols);
    wsInstance.onopen = () => {
      connState.isConnected = true;
      connState.reconnectAttempts = 0;
      connState.pingInterval = setInterval(() => {
        if (wsInstance.readyState === WS_OPEN && connState.isConnected) {
          wsInstance.send(JSON.stringify({ type: "ping" }));
        }
      }, pingInterval);
    };
    wsInstance.onmessage = (event) => {
      const message = parseServerMessage(event);
      if (!message) {
        return;
      }
      listeners.forEach((listener) => listener(message));
    };
    wsInstance.onclose = (event) => {
      connState.isConnected = false;
      clearTimers();
      const shouldAttemptReconnect = shouldReconnect && event.code !== WS_NORMAL_CLOSURE && connState.reconnectAttempts < maxReconnectAttempts;
      if (shouldAttemptReconnect) {
        scheduleReconnect();
      }
    };
    wsInstance.onerror = () => {};
    connState.ws = wsInstance;
  };
  const send = (msg) => {
    if (connState.ws?.readyState === WS_OPEN) {
      connState.ws.send(JSON.stringify(msg));
    }
  };
  const subscribe = (callback) => {
    listeners.add(callback);
    return () => {
      listeners.delete(callback);
    };
  };
  const close = () => {
    clearTimers();
    if (connState.ws) {
      connState.ws.close(WS_NORMAL_CLOSURE);
      connState.ws = null;
    }
    connState.isConnected = false;
    listeners.clear();
  };
  const getReadyState = () => connState.ws?.readyState ?? WS_CLOSED;
  connect();
  return { close, getReadyState, send, subscribe };
};

// src/ai/client/messageStore.ts
var EMPTY_STATE = {
  activeConversationId: null,
  conversations: new Map,
  error: null,
  isStreaming: false
};
var initialActiveConversationId = null;
var initialError = null;
var freshState = () => ({
  activeConversationId: initialActiveConversationId,
  conversations: new Map,
  error: initialError,
  isStreaming: false
});
var findAssistantMessage = (conversation, messageId) => conversation.messages.find((msg) => msg.id === messageId && msg.role === "assistant");
var getOrCreate = (state, conversationId) => {
  let conversation = state.conversations.get(conversationId);
  if (!conversation) {
    conversation = {
      createdAt: Date.now(),
      id: conversationId,
      messages: []
    };
    state.conversations.set(conversationId, conversation);
  }
  return conversation;
};
var handleSend = (state, action) => {
  const conversation = getOrCreate(state, action.conversationId);
  const message = {
    attachments: action.attachments,
    content: action.content,
    conversationId: action.conversationId,
    id: action.messageId,
    role: "user",
    timestamp: Date.now()
  };
  conversation.messages = [...conversation.messages, message];
  state.activeConversationId = action.conversationId;
  state.error = null;
  state.isStreaming = true;
};
var handleChunk = (state, action) => {
  const conversation = getOrCreate(state, action.conversationId);
  const existingIdx = conversation.messages.findIndex((msg) => msg.id === action.messageId && msg.role === "assistant");
  if (existingIdx >= 0) {
    const prevContent = conversation.messages[existingIdx]?.content ?? "";
    conversation.messages = conversation.messages.map((msg, idx) => idx === existingIdx ? { ...msg, content: prevContent + action.content } : msg);
    return;
  }
  const message = {
    content: action.content,
    conversationId: action.conversationId,
    id: action.messageId,
    isStreaming: true,
    role: "assistant",
    timestamp: Date.now()
  };
  conversation.messages = [...conversation.messages, message];
};
var handleThinking = (state, action) => {
  const conversation = getOrCreate(state, action.conversationId);
  const existingIdx = conversation.messages.findIndex((msg) => msg.id === action.messageId && msg.role === "assistant");
  if (existingIdx >= 0) {
    const prevThinking = conversation.messages[existingIdx]?.thinking ?? "";
    conversation.messages = conversation.messages.map((msg, idx) => idx === existingIdx ? { ...msg, thinking: prevThinking + action.content } : msg);
    return;
  }
  const message = {
    content: "",
    conversationId: action.conversationId,
    id: action.messageId,
    isStreaming: true,
    role: "assistant",
    thinking: action.content,
    timestamp: Date.now()
  };
  conversation.messages = [...conversation.messages, message];
};
var upsertToolCall = (message, toolCall) => {
  if (!message.toolCalls) {
    message.toolCalls = [toolCall];
    return;
  }
  const existingIdx = message.toolCalls.findIndex((existing) => existing.name === toolCall.name);
  if (existingIdx >= 0) {
    message.toolCalls[existingIdx] = toolCall;
  } else {
    message.toolCalls = [...message.toolCalls, toolCall];
  }
};
var getOrCreateAssistantMessage = (conversation, messageId, conversationId) => {
  const existing = findAssistantMessage(conversation, messageId);
  if (existing) {
    return existing;
  }
  const message = {
    content: "",
    conversationId,
    id: messageId,
    isStreaming: true,
    role: "assistant",
    timestamp: Date.now()
  };
  conversation.messages = [...conversation.messages, message];
  return message;
};
var handleRAGRetrieved = (state, action) => {
  const conversation = getOrCreate(state, action.conversationId);
  const message = getOrCreateAssistantMessage(conversation, action.messageId, action.conversationId);
  message.sources = action.sources;
  message.retrievedAt = Date.now();
  conversation.messages = [...conversation.messages];
};
var handleToolStatus = (state, action) => {
  const conversation = getOrCreate(state, action.conversationId);
  const message = getOrCreateAssistantMessage(conversation, action.messageId, action.conversationId);
  const toolCall = {
    id: action.messageId,
    input: action.input,
    name: action.name,
    result: action.status === "complete" ? action.result ?? "" : undefined
  };
  upsertToolCall(message, toolCall);
  conversation.messages = [...conversation.messages];
};
var markMessageComplete = (conversation, messageId, usage, durationMs, model, sources) => {
  conversation.messages = conversation.messages.map((msg) => msg.id === messageId && msg.role === "assistant" ? {
    ...msg,
    durationMs,
    isStreaming: false,
    model,
    sources: sources ?? msg.sources,
    usage
  } : msg);
};
var NOT_FOUND = -1;
var findExistingImageById = (images, imageId) => {
  if (!imageId)
    return NOT_FOUND;
  return images.findIndex((img) => img.imageId === imageId);
};
var findReplaceablePartialIndex = (images) => {
  const lastIdx = images.length - 1;
  if (lastIdx >= 0 && images[lastIdx]?.isPartial) {
    return lastIdx;
  }
  return NOT_FOUND;
};
var upsertImage = (message, imageData) => {
  if (!message.images) {
    message.images = [imageData];
    return;
  }
  const existingIdx = findExistingImageById(message.images, imageData.imageId);
  if (existingIdx >= 0) {
    message.images[existingIdx] = imageData;
    return;
  }
  const replaceableIdx = findReplaceablePartialIndex(message.images);
  if (replaceableIdx >= 0) {
    message.images[replaceableIdx] = imageData;
    return;
  }
  message.images = [...message.images, imageData];
};
var handleImage = (state, action) => {
  const conversation = getOrCreate(state, action.conversationId);
  const message = getOrCreateAssistantMessage(conversation, action.messageId, action.conversationId);
  upsertImage(message, {
    data: action.data,
    format: action.format,
    imageId: action.imageId,
    isPartial: action.isPartial,
    revisedPrompt: action.revisedPrompt
  });
  conversation.messages = [...conversation.messages];
};
var handleComplete = (state, action) => {
  const conversation = state.conversations.get(action.conversationId);
  if (conversation) {
    markMessageComplete(conversation, action.messageId, action.usage, action.durationMs, action.model, action.sources);
  }
  state.isStreaming = false;
};
var markConversationStreamsComplete = (conversation) => {
  const streamingMessages = conversation.messages.filter((msg) => msg.isStreaming);
  if (streamingMessages.length === 0) {
    return;
  }
  for (const msg of streamingMessages) {
    msg.isStreaming = false;
  }
  conversation.messages = [...conversation.messages];
};
var markAllStreamsComplete = (state) => {
  for (const [, conversation] of state.conversations) {
    markConversationStreamsComplete(conversation);
  }
};
var handleBranch = (state, action) => {
  const source = state.conversations.get(action.oldConversationId);
  if (!source) {
    return;
  }
  const cutoffIndex = source.messages.findIndex((msg) => msg.id === action.fromMessageId);
  if (cutoffIndex < 0) {
    return;
  }
  const branchedMessages = source.messages.slice(0, cutoffIndex + 1).map((msg) => ({ ...msg, conversationId: action.newConversationId }));
  const newConversation = {
    createdAt: Date.now(),
    id: action.newConversationId,
    messages: branchedMessages
  };
  state.conversations.set(action.newConversationId, newConversation);
  state.activeConversationId = action.newConversationId;
};
var applyAction = (state, action) => {
  switch (action.type) {
    case "send":
      handleSend(state, action);
      break;
    case "chunk":
      handleChunk(state, action);
      break;
    case "thinking":
      handleThinking(state, action);
      break;
    case "tool_status":
      handleToolStatus(state, action);
      break;
    case "image":
      handleImage(state, action);
      break;
    case "complete":
      handleComplete(state, action);
      break;
    case "error":
      state.error = action.message;
      state.isStreaming = false;
      break;
    case "rag_retrieved":
      handleRAGRetrieved(state, action);
      break;
    case "cancel":
      state.isStreaming = false;
      markAllStreamsComplete(state);
      break;
    case "branch":
      handleBranch(state, action);
      break;
    case "set_conversation":
      state.activeConversationId = action.conversationId;
      break;
  }
};
var createAIMessageStore = () => {
  let state = freshState();
  const subscribers = new Set;
  return {
    dispatch: (action) => {
      applyAction(state, action);
      state = { ...state, conversations: new Map(state.conversations) };
      subscribers.forEach((callback) => callback());
    },
    getServerSnapshot: () => EMPTY_STATE,
    getSnapshot: () => state,
    subscribe: (callback) => {
      subscribers.add(callback);
      return () => {
        subscribers.delete(callback);
      };
    }
  };
};

// src/ai/protocol.ts
var generateId = () => crypto.randomUUID();
var parseAIMessage = (raw) => {
  if (raw === null || raw === undefined) {
    return null;
  }
  let text;
  if (typeof raw === "string") {
    text = raw;
  } else if (raw instanceof ArrayBuffer) {
    text = new TextDecoder().decode(raw);
  } else if (ArrayBuffer.isView(raw)) {
    text = new TextDecoder().decode(raw);
  } else if (typeof raw === "object") {
    if (isValidAIClientMessage(raw)) {
      return raw;
    }
    return null;
  } else {
    return null;
  }
  try {
    const parsed = JSON.parse(text);
    if (isValidAIClientMessage(parsed)) {
      return parsed;
    }
    return null;
  } catch {
    return null;
  }
};
var serializeAIMessage = (msg) => JSON.stringify(msg);

// src/ai/client/createAIStream.ts
var createAIStream = (path, conversationId) => {
  const connection = createAIConnection(path);
  const store = createAIMessageStore();
  const listeners = new Set;
  let currentError = null;
  let currentIsStreaming = false;
  let currentMessages = [];
  let activeConversationId = conversationId ?? null;
  const syncState = () => {
    const snapshot = store.getSnapshot();
    const convId = activeConversationId ?? snapshot.activeConversationId;
    const conversation = convId ? snapshot.conversations.get(convId) : undefined;
    activeConversationId = convId ?? snapshot.activeConversationId;
    currentError = snapshot.error;
    currentIsStreaming = snapshot.isStreaming;
    currentMessages = conversation?.messages ?? [];
    listeners.forEach((listener) => listener());
  };
  const unsubscribeStore = store.subscribe(syncState);
  const unsubscribeConnection = connection.subscribe((msg) => {
    const action = serverMessageToAction(msg);
    if (action) {
      store.dispatch(action);
    }
  });
  const branch = (messageId, content) => {
    if (activeConversationId) {
      connection.send({
        content,
        conversationId: activeConversationId,
        messageId,
        type: "branch"
      });
    }
  };
  const cancel = () => {
    if (activeConversationId) {
      store.dispatch({ type: "cancel" });
      connection.send({
        conversationId: activeConversationId,
        type: "cancel"
      });
    }
  };
  const destroy = () => {
    unsubscribeStore();
    unsubscribeConnection();
    connection.close();
    listeners.clear();
  };
  const send = (content, attachments) => {
    const convId = activeConversationId ?? generateId();
    const msgId = generateId();
    store.dispatch({
      attachments,
      content,
      conversationId: convId,
      messageId: msgId,
      type: "send"
    });
    connection.send({
      attachments,
      content,
      conversationId: convId,
      type: "message"
    });
  };
  const subscribe = (callback) => {
    listeners.add(callback);
    return () => {
      listeners.delete(callback);
    };
  };
  return {
    branch,
    cancel,
    destroy,
    send,
    subscribe,
    get error() {
      return currentError;
    },
    get isStreaming() {
      return currentIsStreaming;
    },
    get messages() {
      return currentMessages;
    }
  };
};
// src/ai/client/ragClient.ts
var jsonHeaders = {
  "Content-Type": "application/json"
};
var normalizeBasePath = (path) => path.endsWith("/") ? path.slice(0, -1) : path;
var parseJson = async (response) => {
  const payload = await response.json();
  return payload;
};
var toErrorMessage = async (response) => {
  try {
    const payload = await response.json();
    if (typeof payload.error === "string" && payload.error) {
      return payload.error;
    }
  } catch {}
  return `Request failed with status ${response.status}`;
};
var createRAGClient = (options) => {
  const basePath = normalizeBasePath(options.path);
  const fetchImpl = options.fetch ?? fetch;
  return {
    async ingest(chunks) {
      const response = await fetchImpl(`${basePath}/ingest`, {
        body: JSON.stringify({ chunks }),
        headers: jsonHeaders,
        method: "POST"
      });
      if (!response.ok) {
        return {
          ok: false,
          error: await toErrorMessage(response)
        };
      }
      return parseJson(response);
    },
    async ingestDocuments(input) {
      const response = await fetchImpl(`${basePath}/ingest`, {
        body: JSON.stringify(input),
        headers: jsonHeaders,
        method: "POST"
      });
      if (!response.ok) {
        return {
          ok: false,
          error: await toErrorMessage(response)
        };
      }
      return parseJson(response);
    },
    async search(input) {
      const response = await fetchImpl(`${basePath}/search`, {
        body: JSON.stringify(input),
        headers: jsonHeaders,
        method: "POST"
      });
      if (!response.ok) {
        throw new Error(await toErrorMessage(response));
      }
      const payload = await parseJson(response);
      if (!payload.ok) {
        throw new Error(payload.error ?? "RAG search failed");
      }
      return payload.results ?? [];
    },
    async status() {
      const response = await fetchImpl(`${basePath}/status`);
      if (!response.ok) {
        throw new Error(await toErrorMessage(response));
      }
      return parseJson(response);
    },
    async documents(kind) {
      const query = kind ? `?kind=${encodeURIComponent(kind)}` : "";
      const response = await fetchImpl(`${basePath}/documents${query}`);
      if (!response.ok) {
        throw new Error(await toErrorMessage(response));
      }
      return parseJson(response);
    },
    async createDocument(input) {
      const response = await fetchImpl(`${basePath}/documents`, {
        body: JSON.stringify(input),
        headers: jsonHeaders,
        method: "POST"
      });
      if (!response.ok) {
        return {
          ok: false,
          error: await toErrorMessage(response)
        };
      }
      return parseJson(response);
    },
    async documentChunks(id) {
      const response = await fetchImpl(`${basePath}/documents/${encodeURIComponent(id)}/chunks`);
      if (!response.ok) {
        const error = await toErrorMessage(response);
        return { ok: false, error };
      }
      return parseJson(response);
    },
    async deleteDocument(id) {
      const response = await fetchImpl(`${basePath}/documents/${encodeURIComponent(id)}`, {
        method: "DELETE"
      });
      if (!response.ok) {
        return {
          ok: false,
          error: await toErrorMessage(response)
        };
      }
      return parseJson(response);
    },
    async reseed() {
      const response = await fetchImpl(`${basePath}/reseed`, {
        method: "POST"
      });
      if (!response.ok) {
        return {
          ok: false,
          error: await toErrorMessage(response)
        };
      }
      return parseJson(response);
    },
    async reset() {
      const response = await fetchImpl(`${basePath}/reset`, {
        method: "POST"
      });
      if (!response.ok) {
        return {
          ok: false,
          error: await toErrorMessage(response)
        };
      }
      return parseJson(response);
    },
    async backends() {
      const response = await fetchImpl(`${basePath}/backends`);
      if (!response.ok) {
        throw new Error(await toErrorMessage(response));
      }
      return parseJson(response);
    },
    async clearIndex() {
      const response = await fetchImpl(`${basePath}/index`, {
        method: "DELETE"
      });
      if (!response.ok) {
        throw new Error(await toErrorMessage(response));
      }
      return parseJson(response);
    }
  };
};
export {
  createRAGClient,
  createAIStream
};

//# debugId=253EC4A33623255164756E2164756E21
//# sourceMappingURL=index.js.map
