// Turns the stored conversation into what is sent to the API, and decides when // old messages should be folded into a summary. Pure functions (unit-tested in Node). // // A stored message looks like: // { id, role: 'user' | 'assistant' | 'event', text, ts, // stamp?: 'Tue 17 Nov 2026, 21:04', user messages: local send time // images?: [{ id, mediaType }], user messages: attached photos // excluded?: true, never sent to the API (failed or refused turns) // ... display-only fields (mood, cost, error, local) } // // For assistant messages `text` is the raw reply including its tags, so the model // always sees its own output exactly as it wrote it. The history is append-only: // nothing before the newest message is ever rewritten, which keeps the prompt // cache valid from one request to the next. import { CONTEXT } from './config.js'; const IMAGE_TOKENS = 1600; /** Rough token estimate for one stored message (about 3.2 characters per token). */ export function estimateTokens(msg) { const chars = (msg.text || '').length + (msg.stamp ? msg.stamp.length + 3 : 0); return Math.ceil(chars / 3.2) + 6 + (msg.images?.length || 0) * IMAGE_TOKENS; } /** Messages that belong to the API context: from `contextStart`, without excluded ones. */ export function contextMessages(conv) { return conv.messages.slice(conv.contextStart || 0).filter((m) => !m.excluded && (m.text || m.images?.length)); } /** * Builds the `messages` parameter. * @param conv the stored conversation * @param loadImage async (id) => { mediaType, data } | null (base64 without prefix) */ export async function buildMessages(conv, loadImage = async () => null) { const out = []; for (const m of contextMessages(conv)) { if (m.role === 'assistant') { if (!out.length) continue; // the API needs the first message to come from the user out.push({ role: 'assistant', content: m.text }); } else if (m.role === 'event') { out.push({ role: 'user', content: m.text }); } else { const blocks = []; for (const ref of m.images || []) { const img = await loadImage(ref.id); if (img?.data) { blocks.push({ type: 'image', source: { type: 'base64', media_type: img.mediaType, data: img.data } }); } else { blocks.push({ type: 'text', text: '(a photo that is no longer stored on this device)' }); } } const body = m.text || '(sent a photo)'; blocks.push({ type: 'text', text: m.stamp ? `[${m.stamp}]\n${body}` : body }); out.push({ role: 'user', content: blocks }); } } return out; } /** * Decides whether old messages should be folded into the summary. * @returns null, or { newStart } where messages [contextStart, newStart) are to be summarised and dropped. */ export function planCompaction(conv, limits = CONTEXT) { const start = conv.contextStart || 0; const msgs = conv.messages; const live = (m) => !m.excluded && (m.text || m.images?.length); let estimated = 0; let count = 0; for (let i = start; i < msgs.length; i += 1) { if (live(msgs[i])) { estimated += estimateTokens(msgs[i]); count += 1; } } // The API reports the true size of the last request; trust the larger number, // and if our own estimate was too low, scale every message up to match. const size = Math.max(estimated, conv.lastPromptTokens || 0); if (size <= limits.maxTokens || count <= limits.minKeep) return null; const scale = estimated > 0 ? size / estimated : 1; // Walk back from the newest message until the tail we keep is big enough. let kept = 0; let keptCount = 0; let i = msgs.length; while (i > start && (kept < limits.keepTokens || keptCount < limits.minKeep)) { i -= 1; if (live(msgs[i])) { const t = estimateTokens(msgs[i]) * scale; if (keptCount >= limits.minKeep && kept + t > limits.keepTokens) { i += 1; break; } kept += t; keptCount += 1; } } // The kept tail has to begin with something in the user role. while (i < msgs.length && !(live(msgs[i]) && msgs[i].role !== 'assistant')) i += 1; if (i <= start || i >= msgs.length) return null; const dropped = msgs.slice(start, i).filter(live); const force = size > limits.hardLimit; // Not worth a summary request for one exchange: wait until there is more to fold away. if (!dropped.length || (dropped.length < 4 && !force)) return null; return { newStart: i, force }; } /** A conversation as stored for a fresh start. */ export function newConversation(now = Date.now()) { return { id: `c${now.toString(36)}`, startedAt: now, messages: [], contextStart: 0, summary: '', lastPromptTokens: 0, snapshot: null }; } let counter = 0; export function makeId(prefix = 'm') { counter += 1; return `${prefix}${Date.now().toString(36)}${counter.toString(36)}${Math.random().toString(36).slice(2, 6)}`; } /** "Tue 17 Nov 2026, 21:04" in the user's local time zone. */ export function formatStamp(date = new Date()) { const days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']; const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; const p = (n) => String(n).padStart(2, '0'); return `${days[date.getDay()]} ${date.getDate()} ${months[date.getMonth()]} ${date.getFullYear()}, ${p(date.getHours())}:${p(date.getMinutes())}`; }