import {
  getEventStore,
  updateSessionMetadata
} from "./chunk-XKR3HCAL.js";
import {
  buildMessagesFromStoredEvents,
  foldPendingConfirmations
} from "./chunk-NONI4CRP.js";
import {
  createContextStateMessage,
  createSessionStateMessage
} from "./chunk-CEZNMLOO.js";
import {
  logger
} from "./chunk-K44MW7JJ.js";

// src/server/utils/session-utils.ts
function getSessionMessageCount(sessionId) {
  const eventStore = getEventStore();
  const events = eventStore.getEvents(sessionId);
  let count = 0;
  for (const event of events) {
    if (event.type === "message.start") {
      const data = event.data;
      if (data.role === "user") {
        count++;
      }
    }
  }
  return count;
}
function finalizeTurnCompletion(sessionId, sessionManager, broadcastForSession) {
  sessionManager.setRunning(sessionId, false);
  const contextState = sessionManager.getContextState(sessionId);
  broadcastForSession(sessionId, createContextStateMessage(contextState));
}
function buildRunChatTurnParams(params) {
  return {
    sessionManager: params.sessionManager,
    sessionId: params.sessionId,
    llmClient: params.llmClient,
    signal: params.signal,
    onMessage: params.onMessage,
    ...params.statsIdentity ? { statsIdentity: params.statsIdentity } : {}
  };
}

// src/server/session/name-generator.ts
var SESSION_NAME_PROMPT = `Generate a concise, descriptive session name (max 50 characters) based on the user's message.
Return ONLY the name, nothing else.

Example inputs and outputs:
- "How do I set up React?" \u2192 "React setup"
- "Fix the authentication bug" \u2192 "Fix authentication bug"
- "Add unit tests for the API" \u2192 "Add API unit tests"

User message: {message}`;
async function generateSessionName(options) {
  const { userMessage, llmClient, signal } = options;
  try {
    logger.debug("Generating session name", { messagePreview: userMessage.slice(0, 50) });
    const prompt = SESSION_NAME_PROMPT.replace("{message}", userMessage);
    const messages = [
      {
        role: "user",
        content: prompt
      }
    ];
    const timeoutSignal = AbortSignal.timeout(6e4);
    const composedSignal = signal ? AbortSignal.any([timeoutSignal, signal]) : timeoutSignal;
    const response = await llmClient.complete({
      messages,
      tools: [],
      signal: composedSignal,
      disableThinking: true
    });
    let name = response.content.trim();
    if (name.length > 50) {
      name = name.substring(0, 47) + "...";
    }
    if (!name || name.length < 3) {
      return {
        success: false,
        error: "Generated name is too short or empty"
      };
    }
    logger.debug("Session name generated successfully", { name });
    return {
      success: true,
      name
    };
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : "Unknown error generating session name";
    logger.debug("Session name generation error", { error: errorMessage });
    return {
      success: false,
      error: errorMessage
    };
  }
}
function needsNameGeneration(sessionTitle, messageCount) {
  if (messageCount > 1) {
    return false;
  }
  if (!sessionTitle || sessionTitle.trim() === "") {
    return true;
  }
  if (/^Session \d+$/.test(sessionTitle)) {
    return true;
  }
  return false;
}
function needsNameGenerationCheck(sessionId, sessionTitle, messageCount) {
  const needsGeneration = needsNameGeneration(sessionTitle, messageCount);
  logger.debug("Session name generation check", {
    sessionId,
    title: sessionTitle,
    messageCount,
    needsGeneration
  });
  return needsGeneration;
}
function applyGeneratedSessionName(sessionId, name, deps) {
  updateSessionMetadata(sessionId, { title: name });
  deps.eventStore.append(sessionId, {
    type: "session.name_generated",
    data: { name }
  });
  const updatedSession = deps.sessionManager.getSession(sessionId);
  if (updatedSession) {
    const events = deps.eventStore.getEvents(sessionId);
    const messages = buildMessagesFromStoredEvents(events);
    const pendingConfirmations = foldPendingConfirmations(events);
    deps.broadcastForSession(sessionId, createSessionStateMessage(updatedSession, messages, pendingConfirmations));
  }
}

export {
  getSessionMessageCount,
  finalizeTurnCompletion,
  buildRunChatTurnParams,
  generateSessionName,
  needsNameGenerationCheck,
  applyGeneratedSessionName
};
//# sourceMappingURL=chunk-QFSSKIQ3.js.map