import { isValidAgentProvider } from "./agent/provider-manifest.js";
function getLogger(logger) {
    return logger.child({ module: "persistence" });
}
/**
 * Attach AgentStorage persistence to an AgentManager instance so every
 * agent_state snapshot is flushed to disk.
 */
export function attachAgentStoragePersistence(logger, agentManager, storage) {
    const log = getLogger(logger);
    const unsubscribe = agentManager.subscribe((event) => {
        if (event.type !== "agent_state") {
            return;
        }
        void storage.applySnapshot(event.agent).catch((error) => {
            log.error({ err: error, agentId: event.agent.id }, "Failed to persist agent snapshot");
        });
    });
    return unsubscribe;
}
export function buildConfigOverrides(record) {
    return {
        cwd: record.cwd,
        modeId: record.lastModeId ?? record.config?.modeId ?? undefined,
        model: record.config?.model ?? undefined,
        thinkingOptionId: record.config?.thinkingOptionId ?? undefined,
        featureValues: record.config?.featureValues ?? undefined,
        title: record.config?.title ?? undefined,
        extra: record.config?.extra ?? undefined,
        systemPrompt: record.config?.systemPrompt ?? undefined,
        mcpServers: record.config?.mcpServers ?? undefined,
    };
}
export function buildSessionConfig(record) {
    if (!isValidAgentProvider(record.provider)) {
        throw new Error(`Unknown provider '${record.provider}'`);
    }
    const overrides = buildConfigOverrides(record);
    return {
        provider: record.provider,
        cwd: record.cwd,
        modeId: overrides.modeId,
        model: overrides.model,
        thinkingOptionId: overrides.thinkingOptionId,
        featureValues: overrides.featureValues,
        title: overrides.title,
        extra: overrides.extra,
        systemPrompt: overrides.systemPrompt,
        mcpServers: overrides.mcpServers,
    };
}
export function extractTimestamps(record) {
    return {
        createdAt: new Date(record.createdAt),
        updatedAt: new Date(record.lastActivityAt ?? record.updatedAt),
        lastUserMessageAt: record.lastUserMessageAt ? new Date(record.lastUserMessageAt) : null,
        labels: record.labels,
    };
}
//# sourceMappingURL=persistence-hooks.js.map