import {
  getAvailableAgentsQuery,
  loadAgentStateQuery
} from "./chunk-3ETRQN2E.mjs";
import {
  generateCopilotResponseMutation
} from "./chunk-KTA7QTTU.mjs";

// src/client/CopilotRuntimeClient.ts
import { Client, cacheExchange, fetchExchange } from "@urql/core";

// package.json
var version = "1.51.3-next.3";

// src/client/CopilotRuntimeClient.ts
import {
  ResolvedCopilotKitError,
  CopilotKitLowLevelError,
  CopilotKitError,
  CopilotKitVersionMismatchError,
  getPossibleVersionMismatch
} from "@copilotkit/shared";
var createFetchFn = (signal, handleGQLWarning) => async (...args) => {
  var _a, _b;
  const publicApiKey = (_b = (_a = args[1]) == null ? void 0 : _a.headers) == null ? void 0 : _b["x-copilotcloud-public-api-key"];
  try {
    const result = await fetch(args[0], { ...args[1] ?? {}, signal });
    const mismatch = publicApiKey ? null : await getPossibleVersionMismatch({
      runtimeVersion: result.headers.get("X-CopilotKit-Runtime-Version"),
      runtimeClientGqlVersion: version
    });
    if (result.status !== 200) {
      if (result.status >= 400 && result.status <= 500) {
        if (mismatch) {
          throw new CopilotKitVersionMismatchError(mismatch);
        }
        throw new ResolvedCopilotKitError({ status: result.status });
      }
    }
    if (mismatch && handleGQLWarning) {
      handleGQLWarning(mismatch.message);
    }
    return result;
  } catch (error) {
    if (error.message.includes("BodyStreamBuffer was aborted") || error.message.includes("signal is aborted without reason")) {
      throw error;
    }
    if (error instanceof CopilotKitError) {
      throw error;
    }
    throw new CopilotKitLowLevelError({ error, url: args[0] });
  }
};
var CopilotRuntimeClient = class {
  constructor(options) {
    const headers = {};
    this.handleGQLErrors = options.handleGQLErrors;
    this.handleGQLWarning = options.handleGQLWarning;
    if (options.headers) {
      Object.assign(headers, options.headers);
    }
    if (options.publicApiKey) {
      headers["x-copilotcloud-public-api-key"] = options.publicApiKey;
    }
    this.client = new Client({
      url: options.url,
      exchanges: [cacheExchange, fetchExchange],
      fetchOptions: {
        headers: {
          ...headers,
          "X-CopilotKit-Runtime-Client-GQL-Version": version
        },
        ...options.credentials ? { credentials: options.credentials } : {}
      }
    });
  }
  generateCopilotResponse({
    data,
    properties,
    signal
  }) {
    const fetchFn = createFetchFn(signal, this.handleGQLWarning);
    const result = this.client.mutation(generateCopilotResponseMutation, { data, properties }, { fetch: fetchFn });
    return result;
  }
  asStream(source) {
    const handleGQLErrors = this.handleGQLErrors;
    return new ReadableStream({
      start(controller) {
        source.subscribe(({ data, hasNext, error }) => {
          var _a;
          if (error) {
            if (error.message.includes("BodyStreamBuffer was aborted") || error.message.includes("signal is aborted without reason")) {
              if (!hasNext)
                controller.close();
              console.warn("Abort error suppressed");
              return;
            }
            if ((_a = error.extensions) == null ? void 0 : _a.visibility) {
              const syntheticError = {
                ...error,
                graphQLErrors: [
                  {
                    message: error.message,
                    extensions: error.extensions
                  }
                ]
              };
              if (handleGQLErrors) {
                handleGQLErrors(syntheticError);
              }
              return;
            }
            controller.error(error);
            if (handleGQLErrors) {
              handleGQLErrors(error);
            }
          } else {
            controller.enqueue(data);
            if (!hasNext) {
              controller.close();
            }
          }
        });
      }
    });
  }
  availableAgents() {
    const fetchFn = createFetchFn();
    return this.client.query(getAvailableAgentsQuery, {}, { fetch: fetchFn });
  }
  loadAgentState(data) {
    const fetchFn = createFetchFn();
    const result = this.client.query(
      loadAgentStateQuery,
      { data },
      { fetch: fetchFn }
    );
    result.toPromise().then(({ error }) => {
      if (error && this.handleGQLErrors) {
        this.handleGQLErrors(error);
      }
    }).catch(() => {
    });
    return result;
  }
  static removeGraphQLTypename(data) {
    if (Array.isArray(data)) {
      data.forEach((item) => CopilotRuntimeClient.removeGraphQLTypename(item));
    } else if (typeof data === "object" && data !== null) {
      delete data.__typename;
      Object.keys(data).forEach((key) => {
        if (typeof data[key] === "object" && data[key] !== null) {
          CopilotRuntimeClient.removeGraphQLTypename(data[key]);
        }
      });
    }
    return data;
  }
};

export {
  CopilotRuntimeClient
};
//# sourceMappingURL=chunk-FG6RU64Q.mjs.map