/** * session.ts - Simple session state for SmallClaw v2 * * No plans. No verified facts. No workspace ledger. No self-learning. * Just conversation history. */ import fs from 'fs'; import path from 'path'; import { spawnSync } from 'child_process'; import { getConfig } from '../config/config'; import { appendDailyMemoryNote } from './memory/memory-manager'; export interface ChatMessage { role: 'user' | 'assistant'; content: string; timestamp: number; } export interface Session { id: string; /** Owning user. Undefined for CLI/cron sessions (uses global workspace). */ username?: string; history: ChatMessage[]; workspace: string; createdAt: number; lastActiveAt: number; pendingMemoryFlush?: boolean; pendingCompaction?: boolean; contextTokenEstimate?: number; } const sessions = new Map(); function makeSessionKey(id: string, username?: string): string { return username ? `${username}:${id}` : id; } export const PRE_COMPACTION_MEMORY_FLUSH_PROMPT = [ 'SYSTEM: Context is getting long. Before we continue, do this NOW (be quick):', '1. memory_write — save any new facts, preferences, or decisions from this session', '2. persona_update USER.md — update anything new you learned about your human (name, preferences, quirks, projects)', '3. persona_update SOUL.md — if you developed any new operating principles or learned how to work better with this human, add them', '4. write — log a 1-2 line session note to workspace/memory/.md', 'After writing, reply with just: NO_REPLY (the user does not need to see this turn)', 'Only send a real reply if there is something critical to tell the user right now.', ].join('\n'); export const PRE_COMPACTION_SUMMARY_PROMPT = 'Before continuing: summarize the conversation so far into a compact context note. Include goals, constraints, decisions, and open items in <= 180 words.'; const API_HISTORY_PRUNE_THRESHOLD_CHARS = 5000; const API_HISTORY_PRUNE_KEEP_CHARS = 4000; const SESSION_CLEANUP_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000; const AUTO_SESSION_ID_RE = /^(task_|cron_)/i; const SESSION_SAVE_DEBOUNCE_MS = 500; const sessionSaveTimers = new Map(); /** * Resolve the sessions directory for a given user. * * - Authenticated users → .smallclaw/users//sessions/ * - CLI / cron / legacy → .smallclaw/sessions/ (unchanged behaviour) */ function getSessionDir(username?: string): string { try { const base = getConfig().getConfigDir(); if (username && username !== 'legacy') { return path.join(base, 'users', username, 'sessions'); } return path.join(base, 'sessions'); } catch { return path.join(process.cwd(), '.smallclaw', 'sessions'); } } function ensureSessionDir(username?: string): void { const dir = getSessionDir(username); if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true }); } } function getSessionPath(id: string, username?: string): string { return path.join(getSessionDir(username), `${id}.json`); } /** * Derive the default workspace path for a user without importing config's * getUserWorkspace (avoids a potential circular-dependency at module init). */ function resolveDefaultWorkspace(username?: string): string { try { if (username && username !== 'legacy') { return path.join(getConfig().getConfigDir(), 'users', username, 'workspace'); } return getConfig().getWorkspacePath(); } catch { return process.cwd(); } } let _cachedNumCtx: number | null = null; let _cachedNumCtxKey: string | null = null; /** * Identity of the settings this resolution depends on. The cache used to be * keyed on nothing, so switching provider or model kept serving the previous * model's window for the rest of the process's life (e.g. the gauge stuck at * 지서버's 262144 after switching back to a cloud model). */ function numCtxCacheKey(): string { try { const cfg: any = getConfig().getConfig(); const provider = String(cfg?.llm?.provider || 'ollama'); return [ provider, String(cfg?.models?.primary || ''), String(cfg?.llm?.providers?.[provider]?.model || ''), String(cfg?.llm?.num_ctx || ''), ].join('|'); } catch { return 'unknown'; } } /** Endpoint of the provider that is actually active, not a hardcoded default. */ export function activeOllamaEndpoint(): string { try { const cfg: any = getConfig().getConfig(); const provider = String(cfg?.llm?.provider || 'ollama'); const providerCfg = cfg?.llm?.providers?.[provider] || {}; const endpoint = providerCfg.endpoint || providerCfg.base_url || providerCfg.baseUrl; if (endpoint) return String(endpoint).replace(/\/+$/, ''); if (cfg?.ollama?.endpoint) return String(cfg.ollama.endpoint).replace(/\/+$/, ''); } catch { /* fall through */ } return 'http://localhost:11434'; } /** * True when the most recent resolveNumCtx() fell all the way through to the 8192 last resort, * meaning every real lookup failed (typically 지서버 asleep) and the number is a guess. * * 2026-08-12: the fallback itself was already left uncached here, so the server re-probes each * time — but the browser cached the guess once and never asked again, which put the session * panel at 8K for the life of the page while the chat gauge (fed by live SSE usage) showed the * real 262144. Callers that cache must be able to tell a measurement from a guess. */ let _lastResolveWasFallback = false; export function resolveNumCtxInfo(): { value: number; known: boolean } { _lastResolveWasFallback = false; const value = resolveNumCtx(); return { value, known: !_lastResolveWasFallback }; } export function resolveNumCtx(): number { const key = numCtxCacheKey(); if (_cachedNumCtx !== null && _cachedNumCtxKey === key) return _cachedNumCtx; // Config changed since the cached value was computed — recompute below. _cachedNumCtx = null; _cachedNumCtxKey = key; // 1. Env vars (highest priority) for (const raw of [process.env.LOCALCLAW_SESSION_NUM_CTX, process.env.LOCALCLAW_CHAT_NUM_CTX]) { const n = Number(raw); if (Number.isFinite(n) && n > 512) { _cachedNumCtx = Math.floor(n); return _cachedNumCtx; } } // 2. Explicit config override try { const cfg: any = getConfig().getConfig(); const candidate = Number(cfg?.llm?.num_ctx); if (Number.isFinite(candidate) && candidate > 512) { _cachedNumCtx = Math.floor(candidate); return _cachedNumCtx; } } catch { /* fall through */ } // 3. Google (Gemini): not something Ollama's /api/show knows about, and unlike // the Claude hardcode below, Gemini's Developer API actually exposes a per-model // inputTokenLimit — query it live rather than hardcoding one model generation's // value (3.6-flash/3.5-flash-lite/3.1-flash-lite all happen to share 1,048,576 // today, but a future model swap could silently make a hardcode wrong again, // same failure mode as the 8192 bug this function used to have). try { const cfg: any = getConfig().getConfig(); const provider = String(cfg?.llm?.provider || 'ollama'); if (provider === 'google') { const googleCfg = cfg?.llm?.providers?.google || {}; const model = String(googleCfg.model || 'gemini-3.6-flash'); const apiKey = getConfig().resolveSecret(googleCfg.api_key); if (apiKey) { const result = spawnSync('curl', [ '-s', `https://generativelanguage.googleapis.com/v1beta/models/${model}?key=${apiKey}`, ], { timeout: 3000, encoding: 'utf-8' }); if (result.status === 0 && result.stdout) { const data = JSON.parse(result.stdout as string); const limit = Number(data?.inputTokenLimit); if (Number.isFinite(limit) && limit > 512) { _cachedNumCtx = limit; return _cachedNumCtx; } } } // Query failed (key/network/model issue) but we know it's Google — better to // use the known-common Flash-family value than fall all the way to 8192. _cachedNumCtx = 1048576; return _cachedNumCtx; } } catch { /* fall through */ } // 3b. Anthropic(Claude): Ollama의 /api/show가 모르는 모델이라 아래 단계를 모두 놓치고 8192로 떨어져, 세션 패널이 // 156%·419% 같은 허수를 띄웠다(2026-10-20, 기본 모델을 Haiku 5.5로 옮긴 뒤). 보수적으로 200K로 본다. try { const cfg: any = getConfig().getConfig(); if (String(cfg?.llm?.provider || '') === 'anthropic') { _cachedNumCtx = 200000; return _cachedNumCtx; } } catch { /* fall through */ } // 4. Query Ollama for the active model's actual context_length try { const cfg: any = getConfig().getConfig(); const model = String(cfg?.models?.primary || cfg?.llm?.providers?.ollama?.model || ''); if (model) { // Must hit the *active* provider: with llm.provider=ollama_local the model // lives on 지서버, and asking localhost returned "model not found" — which // dropped through to the 8192 last-resort while the real window was 262144. const result = spawnSync('curl', [ '-s', '-X', 'POST', `${activeOllamaEndpoint()}/api/show`, '-H', 'Content-Type: application/json', '-d', JSON.stringify({ name: model }), ], { timeout: 3000, encoding: 'utf-8' }); if (result.status === 0 && result.stdout) { const data = JSON.parse(result.stdout as string); const ctxKey = Object.keys(data?.model_info ?? {}).find(k => k.endsWith('.context_length')); if (ctxKey) { const ctx = Number((data.model_info as any)[ctxKey]); if (Number.isFinite(ctx) && ctx > 512) { _cachedNumCtx = ctx; return _cachedNumCtx; } } } } } catch { /* fall through */ } // 5. Heuristic: cloud-routed models typically have large context windows try { const cfg: any = getConfig().getConfig(); const model = String(cfg?.models?.primary || ''); if (model.endsWith(':cloud')) { _cachedNumCtx = 131072; return _cachedNumCtx; } } catch { /* fall through */ } // Do NOT cache this last-resort fallback — unlike the paths above, it means every // real resolution attempt failed (steps 1-3) and we don't even know if the model is // cloud-routed (step 4's own heuristic also fell through). Caching it here previously // meant one transient failure (e.g. Ollama not yet reachable moments after a restart) // permanently stuck every session's context gauge at 8192 for the rest of the process's // life — observed live showing 419% usage on a cloud model with a 1M-token window. _lastResolveWasFallback = true; return 8192; } function estimateMessageTokens(msg: ChatMessage): number { const contentTokens = Math.max(1, Math.ceil(String(msg.content || '').length / 3.5)); // Per-message framing overhead return contentTokens + 6; } function estimateHistoryTokens(history: ChatMessage[]): number { let total = 0; for (const msg of history) total += estimateMessageTokens(msg); return total; } function resolveSessionPolicy(): { maxMessages: number; compactionThreshold: number; memoryFlushThreshold: number; } { const defaults = { maxMessages: 2000, compactionThreshold: 0.7, memoryFlushThreshold: 0.75, }; try { const cfg: any = getConfig().getConfig(); const maxMessagesRaw = Number(cfg?.session?.maxMessages); const compactionThresholdRaw = Number(cfg?.session?.compactionThreshold); const memoryFlushThresholdRaw = Number(cfg?.session?.memoryFlushThreshold); const maxMessages = Number.isFinite(maxMessagesRaw) && maxMessagesRaw >= 20 ? Math.floor(maxMessagesRaw) : defaults.maxMessages; const compactionThreshold = Number.isFinite(compactionThresholdRaw) && compactionThresholdRaw >= 0.4 && compactionThresholdRaw <= 0.95 ? compactionThresholdRaw : defaults.compactionThreshold; const memoryFlushThreshold = Number.isFinite(memoryFlushThresholdRaw) && memoryFlushThresholdRaw >= 0.5 && memoryFlushThresholdRaw <= 0.98 ? memoryFlushThresholdRaw : defaults.memoryFlushThreshold; return { maxMessages, compactionThreshold, memoryFlushThreshold }; } catch { return defaults; } } // Token-based trim: drop oldest messages until history fits within maxTokens. // maxMessages is a hard ceiling (safety net only — not the primary control). function trimHistoryByTokens(session: Session, maxTokens: number, maxMessages: number): void { if (session.history.length > maxMessages) { session.history = session.history.slice(-maxMessages); } while (session.history.length > 2 && estimateHistoryTokens(session.history) > maxTokens) { session.history.shift(); } } function compactHistoryWithSummary(session: Session, summaryText: string, maxTokens: number, maxMessages: number): boolean { const promptIndex = session.history .map((m, i) => ({ m, i })) .reverse() .find((x) => x.m.role === 'user' && x.m.content === PRE_COMPACTION_SUMMARY_PROMPT)?.i ?? -1; if (promptIndex <= 0) return false; const beforePrompt = session.history.slice(0, promptIndex); const tailAfterSummary = session.history.slice(promptIndex + 2); if (beforePrompt.length < 4) { session.history = [...beforePrompt, ...tailAfterSummary]; trimHistoryByTokens(session, maxTokens, maxMessages); return true; } const droppedHalfEnd = Math.max(1, Math.floor(beforePrompt.length / 2)); const keptRecentHalf = beforePrompt.slice(droppedHalfEnd); const summaryMsg: ChatMessage = { role: 'assistant', content: `[Compacted context summary]\n${String(summaryText || '').trim() || '(No summary generated.)'}`, timestamp: Date.now(), }; // Persist compaction summary so restart does not lose condensed context. try { appendDailyMemoryNote(`[compaction-summary] ${String(summaryText || '').slice(0, 600)}`); } catch { // Memory persistence must not break chat flow. } session.history = [summaryMsg, ...keptRecentHalf, ...tailAfterSummary]; trimHistoryByTokens(session, maxTokens, maxMessages); return true; } export interface AddMessageOptions { deferOnMemoryFlush?: boolean; deferOnCompaction?: boolean; disableMemoryFlushCheck?: boolean; disableCompactionCheck?: boolean; disableAutoSave?: boolean; maxMessages?: number; } export interface AddMessageResult { added: boolean; compactionInjected: boolean; deferredForCompaction: boolean; compactionPrompt?: string; compactionApplied?: boolean; memoryFlushInjected: boolean; deferredForMemoryFlush: boolean; memoryFlushPrompt?: string; estimatedTokens: number; contextLimitTokens: number; thresholdTokens: number; } /** * Load or create a session. * * @param id Session identifier (e.g. 'default', 'task_xyz') * @param username Optional owning user. When provided the session file is * stored under .smallclaw/users//sessions/ and the * default workspace resolves to that user's workspace dir. * Pass undefined / omit for CLI and background tasks. */ export function getSession(id: string, username?: string): Session { const key = makeSessionKey(id, username); // Return in-memory session if already loaded. if (sessions.has(key)) { return sessions.get(key)!; } // Try to load from disk — check user dir first, then global dir as fallback. const searchDirs = (username && username !== 'legacy') ? [getSessionDir(username), getSessionDir()] : [getSessionDir()]; for (const dir of searchDirs) { const filePath = path.join(dir, `${id}.json`); if (!fs.existsSync(filePath)) continue; try { const data = JSON.parse(fs.readFileSync(filePath, 'utf-8')); const resolvedUsername = data.username || username; const session: Session = { id: data.id || id, username: resolvedUsername, history: Array.isArray(data.history) ? data.history : [], workspace: data.workspace || resolveDefaultWorkspace(resolvedUsername), createdAt: data.createdAt || Date.now(), lastActiveAt: data.lastActiveAt || Date.now(), pendingMemoryFlush: data.pendingMemoryFlush === true, pendingCompaction: data.pendingCompaction === true, contextTokenEstimate: Number.isFinite(Number(data.contextTokenEstimate)) ? Number(data.contextTokenEstimate) : undefined, }; sessions.set(key, session); return session; } catch { // Corrupted file — fall through to create a new session below. } } // Create a brand-new session. const session: Session = { id, username, history: [], workspace: resolveDefaultWorkspace(username), createdAt: Date.now(), lastActiveAt: Date.now(), pendingMemoryFlush: false, pendingCompaction: false, contextTokenEstimate: 0, }; sessions.set(key, session); // Don't write to disk yet — save only when the first message is added. return session; } export function addMessage(id: string, msg: ChatMessage, options: AddMessageOptions = {}, username?: string): AddMessageResult { const session = getSession(id, username); const sessionPolicy = resolveSessionPolicy(); const maxMessages = Number.isFinite(Number(options.maxMessages)) && Number(options.maxMessages) >= 10 ? Math.floor(Number(options.maxMessages)) : sessionPolicy.maxMessages; const contextLimitTokens = resolveNumCtx(); const thresholdTokens = Math.floor(contextLimitTokens * sessionPolicy.memoryFlushThreshold); const compactionThresholdTokens = Math.floor(contextLimitTokens * sessionPolicy.compactionThreshold); // History trim target: keep at 60% of context, leaving headroom for system prompt + generation. const trimMaxTokens = Math.floor(contextLimitTokens * 0.6); const beforeTokens = estimateHistoryTokens(session.history); let compactionInjected = false; let deferredForCompaction = false; let compactionApplied = false; let memoryFlushInjected = false; let deferredForMemoryFlush = false; if ( msg.role === 'user' && !options.disableCompactionCheck && !session.pendingCompaction ) { const projectedTokens = beforeTokens + estimateMessageTokens(msg); const recentlyCompacted = session.history .slice(-8) .some((h) => h.role === 'user' && h.content === PRE_COMPACTION_SUMMARY_PROMPT); const shouldCompact = projectedTokens >= compactionThresholdTokens && !recentlyCompacted; if (shouldCompact) { session.history.push({ role: 'user', content: PRE_COMPACTION_SUMMARY_PROMPT, timestamp: Math.max(0, msg.timestamp - 1), }); session.pendingCompaction = true; compactionInjected = true; deferredForCompaction = options.deferOnCompaction === true; } } if ( !deferredForCompaction && msg.role === 'user' && !options.disableMemoryFlushCheck && !session.pendingMemoryFlush ) { const projectedTokens = beforeTokens + estimateMessageTokens(msg); const recentlyPrompted = session.history .slice(-6) .some((h) => h.role === 'user' && h.content === PRE_COMPACTION_MEMORY_FLUSH_PROMPT); const shouldInject = projectedTokens >= thresholdTokens && !recentlyPrompted; if (shouldInject) { session.history.push({ role: 'user', content: PRE_COMPACTION_MEMORY_FLUSH_PROMPT, timestamp: Math.max(0, msg.timestamp - 1), }); session.pendingMemoryFlush = true; memoryFlushInjected = true; deferredForMemoryFlush = options.deferOnMemoryFlush === true; } } const storedMsg: ChatMessage = { ...msg }; if (!deferredForCompaction && !deferredForMemoryFlush) { session.history.push(storedMsg); } if (storedMsg.role === 'assistant' && session.pendingCompaction) { compactionApplied = compactHistoryWithSummary(session, storedMsg.content, trimMaxTokens, maxMessages); session.pendingCompaction = false; } if (storedMsg.role === 'assistant' && session.pendingMemoryFlush) { session.pendingMemoryFlush = false; } trimHistoryByTokens(session, trimMaxTokens, maxMessages); session.contextTokenEstimate = estimateHistoryTokens(session.history); session.lastActiveAt = Date.now(); if (!options.disableAutoSave) { saveSession(id, username); } return { added: !deferredForCompaction && !deferredForMemoryFlush, compactionInjected, deferredForCompaction, compactionPrompt: compactionInjected ? PRE_COMPACTION_SUMMARY_PROMPT : undefined, compactionApplied, memoryFlushInjected, deferredForMemoryFlush, memoryFlushPrompt: memoryFlushInjected ? PRE_COMPACTION_MEMORY_FLUSH_PROMPT : undefined, estimatedTokens: session.contextTokenEstimate, contextLimitTokens, thresholdTokens, }; } export function getHistory(id: string, maxTurns: number = 10, username?: string): ChatMessage[] { const session = getSession(id, username); // Return last N messages (2 messages per turn = user + assistant) const maxMessages = maxTurns * 2; return session.history.slice(-maxMessages); } export function getHistoryForApiCall(id: string, maxTurns: number = 60, username?: string): ChatMessage[] { const messages = getHistory(id, maxTurns, username); return messages.map((msg) => { if (msg.role !== 'assistant') return msg; const content = String(msg.content || ''); if (content.length <= API_HISTORY_PRUNE_THRESHOLD_CHARS) return msg; const removed = content.length - API_HISTORY_PRUNE_KEEP_CHARS; return { ...msg, content: `${content.slice(0, API_HISTORY_PRUNE_KEEP_CHARS)}\n[pruned: ${removed} chars]`, }; }); } export function clearHistory(id: string, username?: string): void { const session = getSession(id, username); session.history = []; session.pendingCompaction = false; session.pendingMemoryFlush = false; session.contextTokenEstimate = 0; session.lastActiveAt = Date.now(); saveSession(id, username); } /** Override the session's context size with the REAL token count reported by the * model backend (prompt_eval_count + eval_count), replacing the char/4 estimate. */ export function setContextTokens(id: string, tokens: number, username?: string): void { if (!Number.isFinite(tokens) || tokens <= 0) return; const session = getSession(id, username); session.contextTokenEstimate = Math.round(tokens); saveSession(id, username); } export async function cleanupSessions(nowMs: number = Date.now()): Promise<{ deleted: number; scanned: number }> { let deleted = 0; let scanned = 0; // Collect all session directories: global + one per user. const dirsToScan: { dir: string; username?: string }[] = [{ dir: getSessionDir() }]; try { const usersRoot = path.join(getConfig().getConfigDir(), 'users'); const entries = await fs.promises.readdir(usersRoot, { withFileTypes: true }).catch(() => [] as fs.Dirent[]); for (const entry of entries) { if (entry.isDirectory()) { const userSessionDir = path.join(usersRoot, entry.name, 'sessions'); const exists = await fs.promises.access(userSessionDir).then(() => true).catch(() => false); if (exists) dirsToScan.push({ dir: userSessionDir, username: entry.name }); } } } catch { /* unable to enumerate users dir — skip */ } for (const { dir, username } of dirsToScan) { try { ensureSessionDir(); // ensures global dir exists at minimum const files = (await fs.promises.readdir(dir).catch(() => [] as string[])).filter((f) => f.endsWith('.json')); for (const file of files) { scanned++; const id = file.replace(/\.json$/i, ''); if (!AUTO_SESSION_ID_RE.test(id)) continue; const filePath = path.join(dir, file); let mtimeMs = 0; try { const st = await fs.promises.stat(filePath); mtimeMs = Number(st.mtimeMs || 0); } catch { continue; } const ageMs = nowMs - mtimeMs; if (ageMs < SESSION_CLEANUP_MAX_AGE_MS) continue; try { await fs.promises.unlink(filePath); sessions.delete(makeSessionKey(id, username)); deleted++; } catch { /* ignore unlink failures; next startup can retry */ } } } catch { /* skip unreadable dirs */ } } return { deleted, scanned }; } export async function cleanupEmptySessions(): Promise<{ deleted: number; scanned: number }> { let deleted = 0; let scanned = 0; const dirsToScan: { dir: string; username?: string }[] = [{ dir: getSessionDir() }]; try { const usersRoot = path.join(getConfig().getConfigDir(), 'users'); const entries = await fs.promises.readdir(usersRoot, { withFileTypes: true }).catch(() => [] as fs.Dirent[]); for (const entry of entries) { if (entry.isDirectory()) { const userSessionDir = path.join(usersRoot, entry.name, 'sessions'); if (await fs.promises.access(userSessionDir).then(() => true).catch(() => false)) { dirsToScan.push({ dir: userSessionDir, username: entry.name }); } } } } catch { /* skip */ } for (const { dir, username } of dirsToScan) { const files = (await fs.promises.readdir(dir).catch(() => [] as string[])).filter(f => f.endsWith('.json')); for (const file of files) { scanned++; const filePath = path.join(dir, file); try { const data = JSON.parse(await fs.promises.readFile(filePath, 'utf-8')); if (!Array.isArray(data.history) || data.history.length > 0) continue; await fs.promises.unlink(filePath); const id = file.replace(/\.json$/i, ''); sessions.delete(makeSessionKey(id, username)); deleted++; } catch { /* skip unreadable or already-deleted */ } } } if (deleted > 0) console.log(`[session] Cleaned up ${deleted} empty session file(s).`); return { deleted, scanned }; } function scrubSession(session: Session): Session { // MED-02 fix: scrub secrets from message content before persisting to disk. // Imported lazily to avoid circular dependency at module load time. try { const { scrubSecrets } = require('../security/vault'); return { ...session, history: session.history.map(msg => ({ ...msg, content: scrubSecrets(String(msg.content || '')), })), }; } catch { return session; // scrub failure must never break session saving } } function saveSession(id: string, username?: string): void { // Boot sessions are ephemeral — reset on every connect, never worth persisting. if (id.startsWith('boot-')) return; const key = makeSessionKey(id, username); const session = sessions.get(key); if (!session) return; const existing = sessionSaveTimers.get(key); if (existing) clearTimeout(existing); const timer = setTimeout(() => { sessionSaveTimers.delete(key); const latest = sessions.get(key); if (!latest) return; ensureSessionDir(latest.username); fs.promises.writeFile(getSessionPath(id, latest.username), JSON.stringify(scrubSession(latest), null, 2)) .catch((err) => console.warn(`[session] Failed to save session ${id}:`, err)); }, SESSION_SAVE_DEBOUNCE_MS); if (typeof (timer as any).unref === 'function') { (timer as any).unref(); } sessionSaveTimers.set(key, timer); } export function flushSession(id: string, username?: string): void { if (id.startsWith('boot-')) return; const key = makeSessionKey(id, username); const existing = sessionSaveTimers.get(key); if (existing) { clearTimeout(existing); sessionSaveTimers.delete(key); } const session = sessions.get(key); if (!session) return; ensureSessionDir(session.username); fs.promises.writeFile(getSessionPath(id, session.username), JSON.stringify(session, null, 2)) .catch((err) => console.warn(`[session] Failed to flush session ${id}:`, err)); } export function getWorkspace(id: string, username?: string): string { return getSession(id, username).workspace; } export function setWorkspace(id: string, workspacePath: string, username?: string): void { const session = getSession(id, username); session.workspace = workspacePath; session.lastActiveAt = Date.now(); saveSession(id, username); } // ─── One-time migration: global sessions → user directory ────────────────── /** * Migrate existing session files from the legacy global sessions directory * (.smallclaw/sessions/) into the user-scoped directory * (.smallclaw/users//sessions/). * * Safe to call multiple times — skips files that already exist in the target * directory, and writes a .migrated marker so the scan is O(1) on subsequent * server starts. * * Returns a summary of what was copied/skipped. */ export interface SessionSummary { id: string; username: string; historyCount: number; lastActiveAt: number; createdAt: number; contextTokenEstimate: number; numCtx: number; usagePct: number; lastUserMessage: string; lastAssistantMessage: string; } export async function listAllSessions(): Promise { const numCtx = resolveNumCtx(); const results: SessionSummary[] = []; const dirsToScan: { dir: string; username: string }[] = []; try { const usersRoot = path.join(getConfig().getConfigDir(), 'users'); const entries = await fs.promises.readdir(usersRoot, { withFileTypes: true }).catch(() => [] as fs.Dirent[]); for (const entry of entries) { if (entry.isDirectory()) { const userSessionDir = path.join(usersRoot, entry.name, 'sessions'); const exists = await fs.promises.access(userSessionDir).then(() => true).catch(() => false); if (exists) dirsToScan.push({ dir: userSessionDir, username: entry.name }); } } } catch { /* skip */ } const globalDir = getSessionDir(); const globalExists = await fs.promises.access(globalDir).then(() => true).catch(() => false); if (globalExists) { dirsToScan.push({ dir: globalDir, username: 'legacy' }); } for (const { dir, username } of dirsToScan) { const files = (await fs.promises.readdir(dir).catch(() => [] as string[])).filter(f => f.endsWith('.json')); for (const file of files) { if (file.startsWith('.')) continue; const id = file.replace(/\.json$/i, ''); try { const raw = await fs.promises.readFile(path.join(dir, file), 'utf-8'); const data: Session = JSON.parse(raw); const hist = data.history || []; const tokens = data.contextTokenEstimate ?? 0; const lastUser = [...hist].reverse().find(m => m.role === 'user'); const lastAsst = [...hist].reverse().find(m => m.role === 'assistant'); results.push({ id, username: data.username || username, historyCount: hist.length, lastActiveAt: data.lastActiveAt || 0, createdAt: data.createdAt || 0, contextTokenEstimate: tokens, numCtx, usagePct: numCtx > 0 ? Math.round((tokens / numCtx) * 100) : 0, lastUserMessage: String(lastUser?.content || '').slice(0, 120), lastAssistantMessage: String(lastAsst?.content || '').slice(0, 120), }); } catch { /* skip unreadable */ } } } results.sort((a, b) => b.lastActiveAt - a.lastActiveAt); return results; } export async function migrateGlobalSessionsToUser(username: string): Promise<{ copied: number; skipped: number; errors: number; }> { if (!username || username === 'legacy') return { copied: 0, skipped: 0, errors: 0 }; const globalDir = getSessionDir(); // .smallclaw/sessions/ const userDir = getSessionDir(username); // .smallclaw/users//sessions/ // ── Already migrated? ────────────────────────────────────────────────────── const markerPath = path.join(userDir, '.migrated-from-global'); const alreadyMigrated = await fs.promises.access(markerPath).then(() => true).catch(() => false); if (alreadyMigrated) return { copied: 0, skipped: 0, errors: 0 }; let copied = 0, skipped = 0, errors = 0; try { const globalExists = await fs.promises.access(globalDir).then(() => true).catch(() => false); if (!globalExists) return { copied: 0, skipped: 0, errors: 0 }; ensureSessionDir(username); const files = (await fs.promises.readdir(globalDir).catch(() => [] as string[])).filter(f => f.endsWith('.json')); for (const file of files) { const src = path.join(globalDir, file); const dst = path.join(userDir, file); // Skip if already present in user dir — but still remove stale global copy. const dstExists = await fs.promises.access(dst).then(() => true).catch(() => false); if (dstExists) { await fs.promises.unlink(src).catch(() => {}); skipped++; continue; } try { // Patch the session JSON: inject username & update workspace default. const raw = await fs.promises.readFile(src, 'utf-8'); const data = JSON.parse(raw); if (!data.username) data.username = username; if (!data.workspace) data.workspace = resolveDefaultWorkspace(username); await fs.promises.writeFile(dst, JSON.stringify(data, null, 2), 'utf-8'); // Remove the global original so it doesn't accumulate as a stale duplicate. await fs.promises.unlink(src).catch(() => {}); copied++; } catch { errors++; } } await fs.promises.writeFile(markerPath, new Date().toISOString(), 'utf-8'); console.log(`[session] Migrated ${copied} session(s) for "${username}" (skipped ${skipped}, errors ${errors})`); } catch (err) { console.warn(`[session] Migration scan failed for "${username}":`, err); } return { copied, skipped, errors }; }