/**
 * Session lifecycle operations — extracted from AgentSession.
 *
 * Pure functions that orchestrate creating new sessions and switching between
 * existing sessions. Each function takes an explicit params object containing
 * the dependencies it needs, rather than reaching into class state.
 */
import { configureAgentTempDir } from '../../config.js';
import { DEFAULT_THINKING_LEVEL } from '../../core/index.js';
/**
 * Create a new session, optionally with initial messages and parent tracking.
 * Returns true if completed, false if cancelled by extension.
 */
export async function executeNewSession(params) {
    const { agent, sessionManager, extensionRunner, queueTracker, sessionFile: previousSessionFile, thinkingLevel, abortFn, disconnectFromAgent, reconnectToAgent, clearPendingNextTurnMessages, parentSession, setup, observability } = params;
    // Emit session_before_switch event with reason "new" (can be cancelled)
    if (extensionRunner?.hasHandlers('session_before_switch')) {
        const result = (await extensionRunner.emit({
            type: 'session_before_switch',
            reason: 'new'
        }));
        if (result?.cancel) {
            return false;
        }
    }
    disconnectFromAgent();
    await abortFn();
    agent.reset();
    sessionManager.newSession({ parentSession });
    const sessionId = sessionManager.getSessionId();
    configureAgentTempDir(sessionManager.getCwd(), sessionId);
    agent.sessionId = sessionId;
    queueTracker.clearAll();
    clearPendingNextTurnMessages();
    sessionManager.appendThinkingLevelChange(thinkingLevel);
    observability?.setSessionId?.(sessionId);
    observability?.info?.({
        module: 'session',
        event: 'session_created',
        data: {
            transition: 'new',
            has_parent_session: Boolean(parentSession)
        }
    });
    // Run setup callback if provided (e.g., to append initial messages)
    if (setup) {
        await setup(sessionManager);
        // Sync agent state with session manager after setup
        const sessionContext = sessionManager.buildSessionContext();
        agent.replaceMessages(sessionContext.messages);
    }
    reconnectToAgent();
    // Emit session_switch event with reason "new" to extensions
    if (extensionRunner) {
        await extensionRunner.emit({
            type: 'session_switch',
            reason: 'new',
            previousSessionFile
        });
    }
    // Emit session event to custom tools
    return true;
}
/**
 * Switch to an existing session by file path.
 * Returns true if switch completed, false if cancelled by extension.
 */
export async function executeSwitchSession(params) {
    const { sessionPath, agent, sessionManager, extensionRunner, models, modelRegistry, settingsManager, queueTracker, abortFn, disconnectFromAgent, reconnectToAgent, clearPendingNextTurnMessages, setThinkingLevel, observability } = params;
    const previousSessionFile = sessionManager.getSessionFile();
    // Emit session_before_switch event (can be cancelled)
    if (extensionRunner?.hasHandlers('session_before_switch')) {
        const result = (await extensionRunner.emit({
            type: 'session_before_switch',
            reason: 'resume',
            targetSessionFile: sessionPath
        }));
        if (result?.cancel) {
            return false;
        }
    }
    disconnectFromAgent();
    await abortFn();
    queueTracker.clearAll();
    clearPendingNextTurnMessages();
    // Set new session
    sessionManager.setSessionFile(sessionPath);
    const sessionId = sessionManager.getSessionId();
    configureAgentTempDir(sessionManager.getCwd(), sessionId);
    agent.sessionId = sessionId;
    observability?.setSessionId?.(sessionId);
    observability?.info?.({
        module: 'session',
        event: 'session_resumed',
        data: {
            transition: 'resume'
        }
    });
    // Reload messages
    const sessionContext = sessionManager.buildSessionContext();
    // Emit session_switch event to extensions
    if (extensionRunner) {
        await extensionRunner.emit({
            type: 'session_switch',
            reason: 'resume',
            previousSessionFile
        });
    }
    // Emit session event to custom tools
    agent.replaceMessages(sessionContext.messages);
    // Restore model if saved
    if (sessionContext.model) {
        const availableModels = await modelRegistry.getAvailable();
        const match = availableModels.find((m) => m.provider === sessionContext.model.provider && m.id === sessionContext.model.modelId);
        if (match) {
            await models.restoreModel(match);
        }
    }
    const hasThinkingEntry = sessionManager
        .getBranch()
        .some((entry) => entry.type === 'thinking_level_change');
    const defaultThinkingLevel = settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;
    if (hasThinkingEntry) {
        // Restore thinking level if saved (setThinkingLevel clamps to model capabilities)
        setThinkingLevel(sessionContext.thinkingLevel);
    }
    else {
        // Set thinking level without persisting — we're restoring, not changing
        models.setThinkingLevel(defaultThinkingLevel);
    }
    reconnectToAgent();
    return true;
}
//# sourceMappingURL=session-lifecycle.js.map