import { acquireContextLock } from './contextLock.js'; import { loadContext, saveContext } from './persistContext.js'; import { manualCompact } from './compact.js'; import type { Message, Provider, PromptCacheContext } from '../types.js'; /** Shared TUI/Desktop/headless transaction. Reload under the cross-process * session lock; a failed/cancelled summary or save never replaces live history. */ export async function compactSession(input: { sessionFile: string; history?: Message[]; provider: Provider; signal?: AbortSignal; promptCache?: PromptCacheContext; customInstructions?: string; compact?: typeof manualCompact; lockWait?: Parameters[2]; }) { const release = await acquireContextLock(input.sessionFile, input.signal, input.lockWait); try { const disk = await loadContext(input.sessionFile); const history = disk ? [...disk, ...(input.history ?? []).filter(message => message.role === 'system' && message._ephemeral && !message._uiProgress)] : [...(input.history ?? [])]; const result = await (input.compact ?? manualCompact)(history, input.provider, input.signal, undefined, input.promptCache, { customInstructions: input.customInstructions }); input.signal?.throwIfAborted(); if (!result.unchangedReason) await saveContext(result.messages, input.sessionFile, { strict: true }); return result; } finally { await release(); } }