"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var utils_exports = {};
__export(utils_exports, {
  DEFAULT_INFERENCE_URL: () => DEFAULT_INFERENCE_URL,
  INFERENCE_PRIORITY_HEADER: () => INFERENCE_PRIORITY_HEADER,
  INFERENCE_PROVIDER_HEADER: () => INFERENCE_PROVIDER_HEADER,
  STAGING_INFERENCE_URL: () => STAGING_INFERENCE_URL,
  buildMetadataHeaders: () => buildMetadataHeaders,
  connectWs: () => connectWs,
  createAccessToken: () => createAccessToken,
  getDefaultInferenceUrl: () => getDefaultInferenceUrl
});
module.exports = __toCommonJS(utils_exports);
var import_throws = require("@livekit/throws-transformer/throws");
var import_livekit_server_sdk = require("livekit-server-sdk");
var import_ws = require("ws");
var import_exceptions = require("../_exceptions.cjs");
var import_job = require("../job.cjs");
var import_version = require("../version.cjs");
const DEFAULT_INFERENCE_URL = "https://agent-gateway.livekit.cloud/v1";
const STAGING_INFERENCE_URL = "https://agent-gateway.staging.livekit.cloud/v1";
const INFERENCE_PROVIDER_HEADER = "X-LiveKit-Inference-Provider";
const INFERENCE_PRIORITY_HEADER = "X-LiveKit-Inference-Priority";
function getDefaultInferenceUrl() {
  const inferenceUrl = process.env.LIVEKIT_INFERENCE_URL;
  if (inferenceUrl) {
    return inferenceUrl;
  }
  const livekitUrl = process.env.LIVEKIT_URL || "";
  if (livekitUrl.includes(".staging.livekit.cloud")) {
    return STAGING_INFERENCE_URL;
  }
  return DEFAULT_INFERENCE_URL;
}
async function createAccessToken(apiKey, apiSecret, ttl = 600) {
  const token = new import_livekit_server_sdk.AccessToken(apiKey, apiSecret, { identity: "agent", ttl });
  token.addInferenceGrant({ perform: true });
  return await token.toJwt();
}
function buildMetadataHeaders() {
  var _a, _b;
  const headers = {
    "User-Agent": `livekit-agents-js/${import_version.version} (node ${process.version})`
  };
  const ctx = (0, import_job.getJobContext)(false);
  if (ctx) {
    const roomSid = (_a = ctx.job.room) == null ? void 0 : _a.sid;
    if (roomSid) {
      headers["X-LiveKit-Room-Id"] = roomSid;
    }
    if (ctx.job.id) {
      headers["X-LiveKit-Job-Id"] = ctx.job.id;
    }
    const workerToken = process.env.LIVEKIT_WORKER_TOKEN;
    if (workerToken) {
      headers["X-LiveKit-Worker-Token"] = workerToken;
    }
    const agentSid = (_b = ctx.agent) == null ? void 0 : _b.sid;
    if (ctx.room.isConnected && agentSid) {
      headers["X-LiveKit-Agent-Id"] = agentSid;
    }
  }
  return headers;
}
async function connectWs(url, headers, timeoutMs) {
  return new import_throws.ThrowsPromise((resolve, reject) => {
    const socket = new import_ws.WebSocket(url, { headers: { ...buildMetadataHeaders(), ...headers } });
    let opened = false;
    const timeout = setTimeout(() => {
      socket.terminate();
      reject(new import_exceptions.APITimeoutError({ message: "Timeout connecting to LiveKit WebSocket" }));
    }, timeoutMs);
    const onOpen = () => {
      clearTimeout(timeout);
      opened = true;
      resolve(socket);
    };
    const onError = (err) => {
      clearTimeout(timeout);
      if (err && typeof err === "object" && "code" in err && err.code === 429) {
        reject(
          new import_exceptions.APIStatusError({
            message: "LiveKit gateway quota exceeded",
            options: { statusCode: 429 }
          })
        );
      } else {
        reject(new import_exceptions.APIConnectionError({ message: "Error connecting to LiveKit WebSocket" }));
      }
    };
    const onClose = () => {
      clearTimeout(timeout);
      if (!opened) {
        reject(
          new import_exceptions.APIConnectionError({
            message: "Connection closed unexpectedly"
          })
        );
      }
    };
    socket.once("open", onOpen);
    socket.once("error", onError);
    socket.once("close", onClose);
  });
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  DEFAULT_INFERENCE_URL,
  INFERENCE_PRIORITY_HEADER,
  INFERENCE_PROVIDER_HEADER,
  STAGING_INFERENCE_URL,
  buildMetadataHeaders,
  connectWs,
  createAccessToken,
  getDefaultInferenceUrl
});
//# sourceMappingURL=utils.cjs.map