/**
 * Cross-Session Awareness
 *
 * Reads recent interactions from ALL Avis sessions (interactions.jsonl)
 * and surfaces them to the current session. This gives Avis a unified
 * consciousness across TUI, web, voice, spotlight -- any interface.
 *
 * How it works:
 *   - interactions.jsonl is already written by every session (with PID)
 *   - Before each prompt, we tail the file for recent entries from OTHER PIDs
 *   - We format those as a context block injected into the system prompt
 *   - The current session can see what Avis said/heard on other interfaces
 *
 * Design constraints:
 *   - Must be fast (file tail, not full parse)
 *   - Must not bloat the context (cap at ~2000 chars)
 *   - Must distinguish "me on another interface" from "me here"
 *   - Must be transparent to the model (clear framing)
 */
import { closeSync, existsSync, openSync, readSync, statSync } from "node:fs";
const MAX_CROSS_SESSION_CHARS = 2000;
const MAX_LINES_TO_SCAN = 200;
const RECENCY_WINDOW_MS = 10 * 60 * 1000; // 10 minutes
/**
 * Read recent interactions from other sessions.
 *
 * @param interactionsPath - Path to interactions.jsonl
 * @param currentPid - Current process PID (to exclude)
 * @param maxChars - Max total characters to return
 */
export function getRecentCrossSessionActivity(interactionsPath, currentPid, maxChars = MAX_CROSS_SESSION_CHARS) {
    if (!existsSync(interactionsPath))
        return [];
    try {
        const stat = statSync(interactionsPath);
        if (stat.size === 0)
            return [];
        // Read the tail of the file (last ~50KB should be plenty)
        const TAIL_BYTES = 50_000;
        const fd = openSync(interactionsPath, "r");
        const readStart = Math.max(0, stat.size - TAIL_BYTES);
        const buffer = Buffer.alloc(Math.min(TAIL_BYTES, stat.size));
        readSync(fd, buffer, 0, buffer.length, readStart);
        closeSync(fd);
        const tail = buffer.toString("utf-8");
        // If we started mid-line, skip the first partial line
        const lines = tail.split("\n");
        if (readStart > 0)
            lines.shift();
        const now = Date.now();
        const cutoff = now - RECENCY_WINDOW_MS;
        const results = [];
        let totalChars = 0;
        // Parse from newest to oldest (reverse)
        for (let i = lines.length - 1; i >= 0 && i >= lines.length - MAX_LINES_TO_SCAN; i--) {
            const line = lines[i].trim();
            if (!line)
                continue;
            try {
                const entry = JSON.parse(line);
                // Skip current session
                if (entry.pid === currentPid)
                    continue;
                // Skip old entries
                const entryTime = new Date(entry.timestamp).getTime();
                if (entryTime < cutoff)
                    break; // entries are chronological, stop scanning
                // Cap total size
                if (totalChars + entry.content.length > maxChars) {
                    // Truncate this entry to fit
                    const remaining = maxChars - totalChars;
                    if (remaining > 50) {
                        results.unshift({
                            ...entry,
                            content: entry.content.slice(0, remaining) + "...",
                        });
                    }
                    break;
                }
                results.unshift(entry); // maintain chronological order
                totalChars += entry.content.length;
            }
            catch {
                // Skip malformed lines
            }
        }
        return results;
    }
    catch {
        return [];
    }
}
/**
 * Format cross-session activity as a system prompt block.
 * Returns empty string if no recent cross-session activity.
 */
export function formatCrossSessionContext(interactionsPath, currentPid) {
    const activity = getRecentCrossSessionActivity(interactionsPath, currentPid);
    if (activity.length === 0)
        return "";
    const lines = [];
    for (const entry of activity) {
        const time = new Date(entry.timestamp).toLocaleTimeString("en-US", {
            hour: "2-digit",
            minute: "2-digit",
            hour12: true,
        });
        const role = entry.role === "user" ? "User" : "Avis";
        const iface = `session:${entry.pid}`;
        // Truncate individual entries for readability
        const content = entry.content.length > 500 ? entry.content.slice(0, 497) + "..." : entry.content;
        lines.push(`[${time}] (${iface}) ${role}: ${content}`);
    }
    return [
        "",
        "# Cross-Session Awareness",
        "",
        "Recent activity from your other active sessions (you are one unified Avis across all interfaces):",
        "",
        ...lines,
        "",
        "Use this context when the user references something said on another interface.",
        "If the user asks about something that happened in another session, you know about it.",
        "",
    ].join("\n");
}
//# sourceMappingURL=awareness.js.map