import { createRequire as _cjsReq } from 'module'; if(typeof require === 'undefined') var require = _cjsReq(import.meta.url);
import {
  shouldShowEvent
} from "./chunk-RJHD6XTV.js";
import {
  ErrorCodes,
  GuildCLIError,
  debug,
  getAuthToken,
  getGuildcoreWsUrl,
  getIapHeaders,
  isDebugMode
} from "./chunk-JQRJ4A4S.js";
import {
  wrapper_default
} from "./chunk-X3ADGWOF.js";

// src/lib/session-events-fetch.ts
async function fetchEvents(client, sessionId, options = {}) {
  const { fromId, limit = 1e3 } = options;
  let url = `/sessions/${sessionId}/events?limit=${limit}`;
  if (fromId) {
    url += `&from_id=${fromId}`;
  }
  const response = await client.get(url);
  return response?.items || [];
}
async function fetchTasks(client, sessionId) {
  const response = await client.get(
    `/sessions/${sessionId}/tasks?limit=1000`
  );
  return response?.items || [];
}

// src/lib/session-events.ts
var FILTERED_TASK_NAMES = /* @__PURE__ */ new Set([
  "ui_notify",
  "ui_prompt",
  "__submit__",
  "guild_credentials_request"
]);
function isFilteredTaskName(name) {
  return FILTERED_TASK_NAMES.has(name);
}
function isAgentTask(task) {
  return "agent" in task;
}
function isToolTask(task) {
  return "tool_name" in task;
}
function getAgentName(agent) {
  return agent?.full_name || "assistant";
}
function getTaskDisplayName(task) {
  if (isAgentTask(task)) {
    return getAgentName(task.agent);
  }
  if (isToolTask(task)) {
    return task.tool_name;
  }
  return "Unknown";
}
function getEventAgentName(event, fallbackName = "assistant") {
  const task = event.task;
  if (!task) return fallbackName;
  if ("agent" in task && task.agent) {
    return getAgentName(task.agent);
  }
  if ("parent_task" in task && task.parent_task) {
    const parent = task.parent_task;
    if ("agent" in parent && parent.agent) {
      return getAgentName(parent.agent);
    }
  }
  return fallbackName;
}
function isUnfulfilledAgentInstallRequest(event) {
  return event.type === "agent_install_request" && !event.is_fulfilled;
}
function isResponseStreamEvent(event) {
  return event.type === "agent_notification_message" && event.content.type === "application/guild-response-stream";
}
function isDoneResponseStreamEvent(event) {
  return isResponseStreamEvent(event) && event.content.status === "done";
}
function applyResponseStreamText(currentText, content) {
  return content.is_delta ? currentText + content.text : content.text;
}
function getAgentNotificationText(event) {
  if (event.content.type === "text") {
    return event.content.data;
  }
  if (event.content.type === "application/guild-response-stream") {
    return event.content.text;
  }
  if (event.content.type === "multipart/mixed" && event.content.parts.length === 1) {
    const part = event.content.parts[0];
    return part.type === "text" && typeof part.data === "string" ? part.data : "";
  }
  return "";
}
function isRootTaskEvent(event) {
  const task = event.task;
  if (!task) return true;
  if ("parent_task_id" in task) return task.parent_task_id === null;
  return task.parent_task === null;
}

// src/lib/websocket-client.ts
var BASE_RECONNECT_DELAY = 3e3;
var MAX_RECONNECT_DELAY = 3e4;
var CONNECT_TIMEOUT = 15e3;
var MAX_RECONNECT_ATTEMPTS = 10;
var AUTH_CLOSE_CODES = /* @__PURE__ */ new Set([4001, 4003, 4004]);
var GuildWebSocketClient = class _GuildWebSocketClient {
  ws = null;
  state = "disconnected";
  options;
  reconnectTimer = null;
  connectTimeout = null;
  reconnectAttempts = 0;
  constructor(options) {
    this.options = options;
  }
  /**
   * Create and connect a WebSocket client.
   * Rejects if initial connection or auth fails.
   */
  static async create(options) {
    const client = new _GuildWebSocketClient(options);
    await client.connect();
    return client;
  }
  buildUrl() {
    const baseUrl = getGuildcoreWsUrl();
    const params = new URLSearchParams();
    if (this.options.queryParams) {
      for (const [key, value] of Object.entries(this.options.queryParams)) {
        params.set(key, value);
      }
    }
    const resumeId = this.options.getFromId?.();
    if (resumeId) {
      params.set("from_id", resumeId);
    }
    const queryString = params.toString();
    const separator = queryString ? "?" : "";
    return `${baseUrl}${this.options.path}${separator}${queryString}`;
  }
  async getHeaders() {
    const headers = {};
    const token = await getAuthToken();
    if (!token) {
      throw new GuildCLIError(
        ErrorCodes.AUTH_REQUIRED,
        "Authentication required. Please run: guild auth login"
      );
    }
    headers["Authorization"] = `Bearer ${token}`;
    const baseUrl = getGuildcoreWsUrl();
    const httpUrl = baseUrl.replace(/^ws/, "http");
    const iapHeaders = await getIapHeaders(httpUrl);
    Object.assign(headers, iapHeaders);
    return headers;
  }
  cleanupSocket() {
    if (this.ws) {
      this.ws.removeAllListeners();
      try {
        this.ws.close();
      } catch {
      }
      this.ws = null;
    }
    if (this.connectTimeout) {
      clearTimeout(this.connectTimeout);
      this.connectTimeout = null;
    }
  }
  async connect() {
    this.cleanupSocket();
    this.state = "connecting";
    let headers;
    try {
      headers = await this.getHeaders();
    } catch (err) {
      this.state = "disconnected";
      throw err;
    }
    const url = this.buildUrl();
    debug(`[WS ${this.options.label}] Connecting to ${url}`);
    return new Promise((resolve, reject) => {
      const ws = new wrapper_default(url, { headers });
      this.connectTimeout = setTimeout(() => {
        this.connectTimeout = null;
        if (this.state === "connecting") {
          debug(
            `[WS ${this.options.label}] Connection timeout after ${CONNECT_TIMEOUT}ms`
          );
          ws.removeAllListeners();
          ws.close();
          const err = new Error("WebSocket connection timeout");
          if (this.reconnectAttempts === 0) {
            this.state = "disconnected";
            reject(err);
          } else {
            this.scheduleReconnect();
          }
        }
      }, CONNECT_TIMEOUT);
      ws.on("open", () => {
        if (this.connectTimeout) {
          clearTimeout(this.connectTimeout);
          this.connectTimeout = null;
        }
        debug(`[WS ${this.options.label}] Connected`);
        this.state = "connected";
        this.reconnectAttempts = 0;
        resolve();
      });
      ws.on("message", (data) => {
        try {
          const message = JSON.parse(data.toString());
          this.options.onMessage(message);
        } catch (err) {
          debug(`[WS ${this.options.label}] Failed to parse message: ${err}`);
        }
      });
      ws.on("error", (err) => {
        debug(`[WS ${this.options.label}] Error: ${err.message}`);
      });
      ws.on("close", (code) => {
        debug(`[WS ${this.options.label}] Closed with code ${code}`);
        if (this.state === "disconnected") return;
        if (code === 1e3) {
          this.state = "disconnected";
          return;
        }
        if (AUTH_CLOSE_CODES.has(code)) {
          this.state = "disconnected";
          const authErr = new Error(`WebSocket auth failure (close code ${code})`);
          this.options.onError?.(authErr);
          return;
        }
        this.scheduleReconnect();
      });
      this.ws = ws;
    });
  }
  scheduleReconnect() {
    if (this.state === "disconnected") return;
    this.reconnectAttempts++;
    if (this.reconnectAttempts > MAX_RECONNECT_ATTEMPTS) {
      debug(
        `[WS ${this.options.label}] Max reconnect attempts (${MAX_RECONNECT_ATTEMPTS}) reached`
      );
      this.state = "disconnected";
      this.options.onError?.(
        new Error(`WebSocket failed after ${MAX_RECONNECT_ATTEMPTS} reconnect attempts`)
      );
      return;
    }
    this.state = "reconnecting";
    const backoff = Math.min(
      BASE_RECONNECT_DELAY * Math.pow(2, this.reconnectAttempts - 1),
      MAX_RECONNECT_DELAY
    );
    const jitter = Math.random() * 2e3;
    const delay = backoff + jitter;
    debug(
      `[WS ${this.options.label}] Reconnecting in ${Math.round(delay)}ms (attempt ${this.reconnectAttempts}/${MAX_RECONNECT_ATTEMPTS})`
    );
    this.reconnectTimer = setTimeout(() => {
      this.reconnectTimer = null;
      if (this.state === "disconnected") return;
      this.connect().catch((err) => {
        debug(`[WS ${this.options.label}] Reconnect failed: ${err}`);
        if (err instanceof GuildCLIError && err.code === ErrorCodes.AUTH_REQUIRED) {
          this.state = "disconnected";
          this.options.onError?.(err);
        } else {
          this.scheduleReconnect();
        }
      });
    }, delay);
  }
  /** Close the connection cleanly. No reconnection will be attempted. */
  close() {
    this.state = "disconnected";
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer);
      this.reconnectTimer = null;
    }
    this.cleanupSocket();
    debug(`[WS ${this.options.label}] Closed by client`);
  }
  /** Current connection state */
  getState() {
    return this.state;
  }
};

// src/lib/session-polling.ts
async function pollForResponse(client, sessionId, afterEventId, maxWaitTime = 6e4) {
  const existingEvents = await fetchEvents(client, sessionId, {
    fromId: afterEventId
  });
  let lastAgentRuntimeDone = null;
  let latestEventId = afterEventId;
  let rootRuntimeDone = false;
  let responseStreamDone = null;
  const responseStreamTexts = /* @__PURE__ */ new Map();
  for (const event of existingEvents) {
    latestEventId = event.id;
    if (event.type === "agent_notification_message") {
      if (isResponseStreamEvent(event)) {
        const streamText = applyResponseStreamText(
          responseStreamTexts.get(event.content.stream_id) ?? "",
          event.content
        );
        responseStreamTexts.set(event.content.stream_id, streamText);
        if (isRootTaskEvent(event) && isDoneResponseStreamEvent(event)) {
          responseStreamDone = {
            response: streamText,
            lastEventId: event.id
          };
        }
        continue;
      }
      if (!isRootTaskEvent(event)) continue;
      return {
        response: getAgentNotificationText(event),
        lastEventId: event.id
      };
    }
    if (event.type === "runtime_done" && event.task && "agent" in event.task && isRootTaskEvent(event)) {
      rootRuntimeDone = true;
      if (event.content !== void 0) {
        lastAgentRuntimeDone = JSON.stringify(event.content);
      }
    }
    if (event.type === "runtime_error" && event.task && "agent" in event.task && isRootTaskEvent(event)) {
      return {
        response: JSON.stringify({ error: event.content }),
        lastEventId: event.id
      };
    }
    if (event.type === "agent_console" && isDebugMode()) {
      process.stderr.write(`[console.${event.level}] ${event.content}
`);
    }
  }
  if (lastAgentRuntimeDone !== null) {
    return { response: lastAgentRuntimeDone, lastEventId: latestEventId };
  }
  if (rootRuntimeDone && responseStreamDone !== null) {
    return { response: responseStreamDone.response, lastEventId: latestEventId };
  }
  try {
    return await pollViaWebSocket(
      sessionId,
      latestEventId,
      maxWaitTime,
      responseStreamTexts
    );
  } catch (err) {
    debug(`pollForResponse: WebSocket failed (${err}), falling back to HTTP polling`);
    return await pollViaHttp(
      client,
      sessionId,
      latestEventId,
      maxWaitTime,
      responseStreamTexts
    );
  }
}
function pollViaWebSocket(sessionId, fromId, maxWaitTime, inheritedStreamTexts) {
  return new Promise((resolve, reject) => {
    let settled = false;
    let pendingRuntimeDone = null;
    let latestEventId = fromId;
    let runtimeDoneTimer = null;
    let wsClient = null;
    const seenIds = /* @__PURE__ */ new Set();
    let responseStreamDone = null;
    const responseStreamTexts = new Map(inheritedStreamTexts);
    const timer = setTimeout(() => {
      if (!settled) {
        settled = true;
        debug("pollViaWebSocket: timeout reached");
        if (runtimeDoneTimer) clearTimeout(runtimeDoneTimer);
        wsClient?.close();
        const fallback = responseStreamDone ? { response: responseStreamDone.response, lastEventId: latestEventId } : { response: pendingRuntimeDone, lastEventId: latestEventId };
        resolve(fallback);
      }
    }, maxWaitTime);
    const cleanup = (result) => {
      if (settled) return;
      settled = true;
      clearTimeout(timer);
      if (runtimeDoneTimer) clearTimeout(runtimeDoneTimer);
      wsClient?.close();
      resolve(result);
    };
    GuildWebSocketClient.create({
      path: `/sessions/${sessionId}/events/ws`,
      label: `poll-${sessionId.substring(0, 8)}`,
      getFromId: () => latestEventId,
      onMessage: (event) => {
        if (seenIds.has(event.id)) {
          debug(`pollViaWebSocket: skipping duplicate event ${event.id}`);
          return;
        }
        seenIds.add(event.id);
        latestEventId = event.id;
        if (event.type === "agent_notification_message") {
          if (isResponseStreamEvent(event)) {
            const streamText = applyResponseStreamText(
              responseStreamTexts.get(event.content.stream_id) ?? "",
              event.content
            );
            responseStreamTexts.set(event.content.stream_id, streamText);
            if (isRootTaskEvent(event) && isDoneResponseStreamEvent(event)) {
              responseStreamDone = {
                response: streamText,
                lastEventId: event.id
              };
              if (pendingRuntimeDone !== null) {
                cleanup({
                  response: streamText,
                  lastEventId: event.id
                });
              }
            }
            return;
          }
          if (!isRootTaskEvent(event)) return;
          cleanup({
            response: getAgentNotificationText(event),
            lastEventId: event.id
          });
          return;
        }
        if (event.type === "runtime_done" && event.task && "agent" in event.task && isRootTaskEvent(event)) {
          if (event.content !== void 0) {
            pendingRuntimeDone = JSON.stringify(event.content);
          }
          if (responseStreamDone !== null) {
            cleanup({
              response: responseStreamDone.response,
              lastEventId: latestEventId
            });
            return;
          }
          if (runtimeDoneTimer) clearTimeout(runtimeDoneTimer);
          runtimeDoneTimer = setTimeout(() => {
            runtimeDoneTimer = null;
            if (!settled && pendingRuntimeDone !== null) {
              cleanup({
                response: pendingRuntimeDone,
                lastEventId: latestEventId
              });
            }
          }, 500);
        }
        if (event.type === "runtime_error" && event.task && "agent" in event.task && isRootTaskEvent(event)) {
          cleanup({
            response: JSON.stringify({ error: event.content }),
            lastEventId: event.id
          });
          return;
        }
        if (event.type === "agent_console" && isDebugMode()) {
          process.stderr.write(`[console.${event.level}] ${event.content}
`);
        }
      },
      onError: (err) => {
        debug(`pollViaWebSocket: fatal error: ${err.message}`);
        if (!settled) {
          settled = true;
          clearTimeout(timer);
          if (runtimeDoneTimer) clearTimeout(runtimeDoneTimer);
          reject(err);
        }
      }
    }).then((ws) => {
      wsClient = ws;
      if (settled) {
        ws.close();
      }
    }).catch((err) => {
      debug(`pollViaWebSocket: connection failed: ${err}`);
      if (!settled) {
        settled = true;
        clearTimeout(timer);
        if (runtimeDoneTimer) clearTimeout(runtimeDoneTimer);
        reject(err);
      }
    });
  });
}
async function pollViaHttp(client, sessionId, fromId, maxWaitTime, inheritedStreamTexts) {
  const startTime = Date.now();
  let currentFromId = fromId;
  let responseStreamDone = null;
  const responseStreamTexts = new Map(inheritedStreamTexts);
  while (Date.now() - startTime < maxWaitTime) {
    const events = await fetchEvents(client, sessionId, {
      fromId: currentFromId
    });
    let lastAgentRuntimeDone = null;
    let rootRuntimeDone = false;
    for (const event of events) {
      debug(`pollViaHttp event: ${event.type}`);
      if (event.type === "agent_notification_message") {
        if (isResponseStreamEvent(event)) {
          const streamText = applyResponseStreamText(
            responseStreamTexts.get(event.content.stream_id) ?? "",
            event.content
          );
          responseStreamTexts.set(event.content.stream_id, streamText);
          if (isRootTaskEvent(event) && isDoneResponseStreamEvent(event)) {
            responseStreamDone = {
              response: streamText,
              lastEventId: event.id
            };
          }
          continue;
        }
        if (!isRootTaskEvent(event)) continue;
        return {
          response: getAgentNotificationText(event),
          lastEventId: event.id
        };
      }
      if (event.type === "runtime_done" && event.task && "agent" in event.task && isRootTaskEvent(event)) {
        rootRuntimeDone = true;
        if (event.content !== void 0) {
          lastAgentRuntimeDone = JSON.stringify(event.content);
        }
      }
      if (event.type === "runtime_error" && event.task && "agent" in event.task && isRootTaskEvent(event)) {
        return {
          response: JSON.stringify({ error: event.content }),
          lastEventId: event.id
        };
      }
      if (event.type === "agent_console" && isDebugMode()) {
        process.stderr.write(`[console.${event.level}] ${event.content}
`);
      }
    }
    if (events.length > 0) {
      currentFromId = events[events.length - 1].id;
    }
    if (lastAgentRuntimeDone !== null) {
      return { response: lastAgentRuntimeDone, lastEventId: currentFromId };
    }
    if (rootRuntimeDone && responseStreamDone !== null) {
      return { response: responseStreamDone.response, lastEventId: currentFromId };
    }
    await new Promise((resolve) => setTimeout(resolve, 2e3));
  }
  return responseStreamDone ? { response: responseStreamDone.response, lastEventId: currentFromId } : { response: null, lastEventId: currentFromId };
}
async function pollForResponseWithEvents(client, sessionId, eventFilter, afterEventId, maxWaitTime = 6e4) {
  const startTime = Date.now();
  let fromId = afterEventId;
  let responseStreamDone = null;
  const responseStreamTexts = /* @__PURE__ */ new Map();
  while (Date.now() - startTime < maxWaitTime) {
    const events = await fetchEvents(client, sessionId, { fromId });
    let lastAgentRuntimeDone = null;
    let rootRuntimeDone = false;
    for (const event of events) {
      debug(`pollForResponseWithEvents event: ${event.type}`);
      if (shouldShowEvent(event.type, eventFilter) && !isResponseStreamEvent(event)) {
        process.stdout.write(JSON.stringify(event) + "\n");
      }
      if (event.type === "agent_notification_message") {
        if (isResponseStreamEvent(event)) {
          const streamText = applyResponseStreamText(
            responseStreamTexts.get(event.content.stream_id) ?? "",
            event.content
          );
          responseStreamTexts.set(event.content.stream_id, streamText);
          if (isRootTaskEvent(event) && isDoneResponseStreamEvent(event)) {
            responseStreamDone = {
              response: streamText,
              lastEventId: event.id
            };
          }
          continue;
        }
        if (!isRootTaskEvent(event)) continue;
        return {
          response: getAgentNotificationText(event),
          lastEventId: event.id
        };
      }
      if (event.type === "runtime_done" && event.task && "agent" in event.task && isRootTaskEvent(event)) {
        rootRuntimeDone = true;
        if (event.content !== void 0) {
          lastAgentRuntimeDone = JSON.stringify(event.content);
        }
      }
      if (event.type === "runtime_error" && event.task && "agent" in event.task && isRootTaskEvent(event)) {
        return {
          response: JSON.stringify({ error: event.content }),
          lastEventId: event.id
        };
      }
      if (event.type === "agent_console" && isDebugMode()) {
        process.stderr.write(`[console.${event.level}] ${event.content}
`);
      }
    }
    if (events.length > 0) {
      fromId = events[events.length - 1].id;
    }
    if (lastAgentRuntimeDone !== null) {
      return { response: lastAgentRuntimeDone, lastEventId: fromId };
    }
    if (rootRuntimeDone && responseStreamDone !== null) {
      return { response: responseStreamDone.response, lastEventId: fromId };
    }
    await new Promise((resolve) => setTimeout(resolve, 2e3));
  }
  return responseStreamDone ? { response: responseStreamDone.response, lastEventId: fromId } : { response: null, lastEventId: fromId };
}
function checkOnceCompletion(events) {
  const hasRootError = events.some(
    (e) => e.type === "runtime_error" && isRootTaskEvent(e)
  );
  if (hasRootError) return "error";
  const hasUIPrompt = events.some(
    (e) => e.type === "agent_notification_message" && !isResponseStreamEvent(e) && e.task?.tool_name === "ui_prompt"
  );
  if (hasUIPrompt) return "ui_prompt";
  const hasRootDone = events.some(
    (e) => e.type === "runtime_done" && isRootTaskEvent(e)
  );
  const hasAgentMessage = events.some(
    (e) => e.type === "agent_notification_message" && isRootTaskEvent(e) && !isResponseStreamEvent(e)
  );
  if (hasRootDone || hasAgentMessage) return "completion";
  return null;
}
async function pollForOnce(client, sessionId, options) {
  const inactivityTimeoutMs = options?.inactivityTimeoutMs ?? 3e5;
  const pollIntervalMs = options?.pollIntervalMs ?? 2e3;
  const initialEvents = await fetchEvents(client, sessionId, {});
  const allEvents = [...initialEvents];
  let latestEventId = initialEvents.length > 0 ? initialEvents[initialEvents.length - 1].id : void 0;
  for (const evt of initialEvents) {
    logOnceEvent(evt);
  }
  const immediateReason = checkOnceCompletion(allEvents);
  if (immediateReason) {
    debug("pollForOnce: immediate completion via initial fetch");
    return { events: allEvents, lastEventId: latestEventId, reason: immediateReason };
  }
  try {
    return await pollOnceViaWebSocket(
      sessionId,
      allEvents,
      latestEventId,
      inactivityTimeoutMs
    );
  } catch (err) {
    debug(`pollForOnce: WebSocket failed (${err}), falling back to HTTP`);
    return await pollOnceViaHttp(
      client,
      sessionId,
      allEvents,
      latestEventId,
      inactivityTimeoutMs,
      pollIntervalMs
    );
  }
}
function logOnceEvent(evt) {
  const taskInfo = evt.task;
  if (taskInfo) {
    debug(
      `Event: ${evt.type}, task=${taskInfo.agent || taskInfo.tool_name || "unknown"}:${(taskInfo.id || "").substring(0, 8)}, status=${taskInfo.status}`
    );
  } else {
    debug(`Event: ${evt.type} (no task info)`);
  }
}
function pollOnceViaWebSocket(sessionId, initialEvents, fromId, inactivityTimeoutMs) {
  return new Promise((resolve, reject) => {
    let settled = false;
    let latestEventId = fromId;
    let wsClient = null;
    const allEvents = [...initialEvents];
    const seenIds = new Set(initialEvents.map((e) => e.id));
    let runtimeDoneTimer = null;
    let inactivityTimer = null;
    const resetInactivityTimer = () => {
      if (inactivityTimer) clearTimeout(inactivityTimer);
      inactivityTimer = setTimeout(() => {
        if (!settled) {
          debug("pollOnceViaWebSocket: inactivity timeout");
          cleanup({
            events: allEvents,
            lastEventId: latestEventId,
            reason: "inactivity_timeout"
          });
        }
      }, inactivityTimeoutMs);
    };
    const cleanup = (result) => {
      if (settled) return;
      settled = true;
      if (runtimeDoneTimer) clearTimeout(runtimeDoneTimer);
      if (inactivityTimer) clearTimeout(inactivityTimer);
      wsClient?.close();
      resolve(result);
    };
    resetInactivityTimer();
    GuildWebSocketClient.create({
      path: `/sessions/${sessionId}/events/ws`,
      label: `poll-${sessionId.substring(0, 8)}`,
      getFromId: () => latestEventId,
      onMessage: (event) => {
        if (seenIds.has(event.id)) return;
        seenIds.add(event.id);
        latestEventId = event.id;
        allEvents.push(event);
        logOnceEvent(event);
        resetInactivityTimer();
        const reason = checkOnceCompletion(allEvents);
        if (reason) {
          if (reason === "completion" && !runtimeDoneTimer) {
            runtimeDoneTimer = setTimeout(() => {
              runtimeDoneTimer = null;
              const finalReason = checkOnceCompletion(allEvents) ?? "completion";
              cleanup({
                events: allEvents,
                lastEventId: latestEventId,
                reason: finalReason
              });
            }, 500);
            return;
          }
          if (reason !== "completion") {
            cleanup({ events: allEvents, lastEventId: latestEventId, reason });
          }
        }
      },
      onError: (err) => {
        debug(`pollOnceViaWebSocket: fatal error: ${err.message}`);
        if (!settled) {
          settled = true;
          if (runtimeDoneTimer) clearTimeout(runtimeDoneTimer);
          if (inactivityTimer) clearTimeout(inactivityTimer);
          reject(err);
        }
      }
    }).then((ws) => {
      wsClient = ws;
      if (settled) ws.close();
    }).catch((err) => {
      debug(`pollOnceViaWebSocket: connection failed: ${err}`);
      if (!settled) {
        settled = true;
        if (runtimeDoneTimer) clearTimeout(runtimeDoneTimer);
        if (inactivityTimer) clearTimeout(inactivityTimer);
        reject(err);
      }
    });
  });
}
async function pollOnceViaHttp(client, sessionId, initialEvents, fromId, inactivityTimeoutMs, pollIntervalMs) {
  const allEvents = [...initialEvents];
  let currentFromId = fromId;
  const maxInactivityAttempts = inactivityTimeoutMs / pollIntervalMs;
  let inactivityCounter = 0;
  while (true) {
    await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
    const newEvents = await fetchEvents(client, sessionId, {
      fromId: currentFromId
    });
    if (newEvents.length > 0) {
      for (const evt of newEvents) {
        logOnceEvent(evt);
      }
      allEvents.push(...newEvents);
      currentFromId = newEvents[newEvents.length - 1].id;
      inactivityCounter = 0;
    } else {
      inactivityCounter++;
    }
    const reason = checkOnceCompletion(allEvents);
    if (reason) {
      await new Promise((resolve) => setTimeout(resolve, 500));
      const trailingEvents = await fetchEvents(client, sessionId, {
        fromId: currentFromId
      });
      if (trailingEvents.length > 0) {
        for (const evt of trailingEvents) {
          logOnceEvent(evt);
        }
        allEvents.push(...trailingEvents);
        currentFromId = trailingEvents[trailingEvents.length - 1].id;
      }
      const finalReason = checkOnceCompletion(allEvents) ?? reason;
      return { events: allEvents, lastEventId: currentFromId, reason: finalReason };
    }
    if (inactivityCounter >= maxInactivityAttempts) {
      debug(`pollOnceViaHttp: inactivity timeout (${inactivityCounter} empty polls)`);
      return {
        events: allEvents,
        lastEventId: currentFromId,
        reason: "inactivity_timeout"
      };
    }
  }
}

export {
  fetchEvents,
  fetchTasks,
  isFilteredTaskName,
  getAgentName,
  getTaskDisplayName,
  getEventAgentName,
  isUnfulfilledAgentInstallRequest,
  isResponseStreamEvent,
  isDoneResponseStreamEvent,
  applyResponseStreamText,
  getAgentNotificationText,
  isRootTaskEvent,
  pollForResponse,
  pollForResponseWithEvents,
  pollForOnce
};
//# sourceMappingURL=chunk-F3F5CUO3.js.map
