import { AdapterError, ErrorCodes } from '@agentskit/core';

// src/stream-errors.ts
function isAbortError(err) {
  if (err instanceof DOMException && err.name === "AbortError") return true;
  if (err instanceof Error && err.name === "AbortError") return true;
  return false;
}
function adapterErrorChunk(message, options) {
  const error = new AdapterError({
    code: options?.code ?? ErrorCodes.AK_ADAPTER_STREAM_FAILED,
    message,
    cause: options?.cause
  });
  return {
    type: "error",
    content: message,
    metadata: { error }
  };
}
function parseCompleteToolArgs(args) {
  const raw = args.length > 0 ? args : "{}";
  try {
    JSON.parse(raw);
    return { ok: true, args: raw };
  } catch (cause) {
    return {
      ok: false,
      error: new AdapterError({
        code: ErrorCodes.AK_ADAPTER_STREAM_FAILED,
        message: "Incomplete or malformed tool-call arguments JSON",
        cause
      })
    };
  }
}
function raceAbort(promise, signal) {
  if (signal.aborted) {
    return Promise.reject(new DOMException("Aborted", "AbortError"));
  }
  return new Promise((resolve, reject) => {
    let settled = false;
    const onAbort = () => {
      if (settled) return;
      settled = true;
      signal.removeEventListener("abort", onAbort);
      reject(new DOMException("Aborted", "AbortError"));
    };
    signal.addEventListener("abort", onAbort);
    promise.then(
      (value) => {
        if (settled) return;
        settled = true;
        signal.removeEventListener("abort", onAbort);
        resolve(value);
      },
      (err) => {
        if (settled) return;
        settled = true;
        signal.removeEventListener("abort", onAbort);
        reject(err);
      }
    );
  });
}
async function abortableSleep(ms, signal, sleep) {
  if (signal.aborted) throw new DOMException("Aborted", "AbortError");
  await raceAbort(sleep(ms), signal);
  if (signal.aborted) throw new DOMException("Aborted", "AbortError");
}
async function cancelBody(body) {
  if (!body) return;
  try {
    await body.cancel();
  } catch {
  }
}

export { abortableSleep, adapterErrorChunk, cancelBody, isAbortError, parseCompleteToolArgs, raceAbort };
//# sourceMappingURL=chunk-6CIB2QCH.js.map
//# sourceMappingURL=chunk-6CIB2QCH.js.map