import {
  applyGeneratedSessionName,
  buildRunChatTurnParams,
  finalizeTurnCompletion,
  generateSessionName,
  getSessionMessageCount,
  needsNameGenerationCheck
} from "./chunk-QFSSKIQ3.js";
import {
  runChatTurn
} from "./chunk-UFY4I643.js";
import "./chunk-ALH4KM2Y.js";
import "./chunk-PSJIT5LZ.js";
import "./chunk-XAMAYRDA.js";
import "./chunk-DL6ZILAF.js";
import "./chunk-PBGOZMVY.js";
import "./chunk-VRGRAQDG.js";
import "./chunk-HGAMIPFO.js";
import {
  getEventStore
} from "./chunk-XKR3HCAL.js";
import "./chunk-FBGWG4N6.js";
import "./chunk-NONI4CRP.js";
import {
  createChatMessageMessage,
  createPhaseChangedMessage,
  createSessionRunningMessage
} from "./chunk-CEZNMLOO.js";
import "./chunk-BJYPTN5S.js";
import "./chunk-FQLK5GL5.js";
import "./chunk-CQGTEGKL.js";
import "./chunk-CGZHLM3K.js";
import "./chunk-SZKEGZIB.js";
import {
  logger
} from "./chunk-K44MW7JJ.js";

// src/server/session/chat-handler.ts
var activeAgents = /* @__PURE__ */ new Map();
async function startChatSession(sessionId, content, deps, options) {
  const { sessionManager, llmClient, statsIdentity, broadcastForSession } = deps;
  const session = sessionManager.getSession(sessionId);
  if (!session) {
    throw new Error("Session not found");
  }
  const eventStore = getEventStore();
  if (session.isRunning) {
    throw new Error("Session is already running");
  }
  if (session.phase === "blocked") {
    sessionManager.setPhase(sessionId, "build");
    broadcastForSession(sessionId, createPhaseChangedMessage("build"));
  }
  const controller = new AbortController();
  const existingController = activeAgents.get(sessionId);
  if (existingController) {
    existingController.abort();
  }
  activeAgents.set(sessionId, controller);
  sessionManager.setRunning(sessionId, true);
  broadcastForSession(sessionId, createSessionRunningMessage(true));
  try {
    const { maybeAutoCompactContext } = await import("./auto-compaction-UIWTO3H5.js");
    await maybeAutoCompactContext({
      sessionManager,
      sessionId,
      llmClient,
      statsIdentity,
      signal: controller.signal
    });
    if (controller.signal.aborted) {
      return;
    }
    const userMessage = sessionManager.addMessage(sessionId, {
      role: "user",
      content,
      ...options?.attachments && { attachments: options.attachments },
      ...options?.messageKind && { messageKind: options.messageKind },
      ...options?.isSystemGenerated && { isSystemGenerated: options.isSystemGenerated }
    });
    broadcastForSession(sessionId, createChatMessageMessage(userMessage));
    const messageCount = getSessionMessageCount(sessionId);
    const currentSession = sessionManager.getSession(sessionId);
    if (currentSession && needsNameGenerationCheck(sessionId, currentSession.metadata.title, messageCount)) {
      generateSessionName({
        userMessage: content,
        llmClient,
        signal: controller.signal
      }).then((result) => {
        logger.debug("Session name generation result", {
          sessionId,
          success: result.success,
          name: result.name,
          error: result.error
        });
        if (result.success && result.name) {
          applyGeneratedSessionName(sessionId, result.name, {
            sessionManager,
            eventStore,
            broadcastForSession
          });
        }
      }).catch((error) => {
        logger.error("Session name generation failed", {
          sessionId,
          error: error instanceof Error ? error.message : String(error)
        });
      });
    }
    startTurnWithCompletionChain(sessionId, controller, deps);
  } catch (error) {
    if (activeAgents.get(sessionId) === controller) {
      activeAgents.delete(sessionId);
    }
    try {
      sessionManager.setRunning(sessionId, false);
      broadcastForSession(sessionId, createSessionRunningMessage(false));
    } catch {
    }
    finalizeTurnCompletion(sessionId, sessionManager, broadcastForSession);
    throw error;
  }
}
function startTurnWithCompletionChain(sessionId, controller, deps) {
  const { sessionManager, llmClient, statsIdentity, broadcastForSession } = deps;
  runChatTurn(
    buildRunChatTurnParams({
      sessionManager,
      sessionId,
      llmClient,
      statsIdentity,
      signal: controller.signal,
      onMessage: (msg) => broadcastForSession(sessionId, msg)
    })
  ).catch((error) => {
    if (error instanceof Error && error.message === "Aborted") {
      return;
    }
  }).finally(() => {
    if (activeAgents.get(sessionId) !== controller) {
      return;
    }
    activeAgents.delete(sessionId);
    const completionMsgs = sessionManager.drainCompletionMessages(sessionId);
    const next = completionMsgs[0];
    if (next) {
      for (const remaining of completionMsgs.slice(1)) {
        sessionManager.queueMessage(sessionId, "completion", remaining.content, remaining.attachments);
      }
      const userMessage = sessionManager.addMessage(sessionId, {
        role: "user",
        content: next.content,
        ...next.attachments ? { attachments: next.attachments } : {}
      });
      broadcastForSession(sessionId, createChatMessageMessage(userMessage));
      const newController = new AbortController();
      activeAgents.set(sessionId, newController);
      startTurnWithCompletionChain(sessionId, newController, deps);
      return;
    }
    sessionManager.clearMessageQueue(sessionId);
    finalizeTurnCompletion(sessionId, sessionManager, broadcastForSession);
  });
}
function stopSessionExecution(sessionId, sessionManager) {
  const controller = activeAgents.get(sessionId);
  if (controller) {
    activeAgents.delete(sessionId);
    controller.abort();
  }
  sessionManager.setRunning(sessionId, false);
}
export {
  startChatSession,
  stopSessionExecution
};
//# sourceMappingURL=chat-handler-IVIWOR3D.js.map