import { basename, extname } from 'node:path'; import type { DeferredLoadContext } from './load-startup-context.js'; import { accountRequiredMessage } from './desktop-mode.js'; import { existsSync, readFileSync, writeFileSync } from 'fs'; import { AuthStore } from './auth.js'; import { getProfileMemoryFile } from './init-command.js'; import { resolveActivePersonaFile, readPersonaFile } from './persona.js'; export interface LoadedFileSnapshot { path: string | null; exists: boolean; content: string; source?: 'local' | 'hub' | 'none'; id?: string; resource_id?: string; } export interface LoadedMemorySnapshot extends LoadedFileSnapshot { line_limit: number; total_lines: number; truncated: boolean; } export interface LoadContextSnapshot { persona: LoadedFileSnapshot; memory: LoadedMemorySnapshot; } export const AGENT_MEMORY_LINE_LIMIT = 200; function ensureMemoryFile(path: string): void { if (!existsSync(path)) writeFileSync(path, ''); } export function loadPersonaSnapshot(authStore = new AuthStore(), includeContent = true): LoadedFileSnapshot { const resolved = resolveActivePersonaFile(authStore); const exists = resolved.path !== null && existsSync(resolved.path); return { path: resolved.path, exists, content: includeContent && resolved.path ? readPersonaFile(resolved.path) : '', source: resolved.source, ...(resolved.id ? { id: resolved.id } : {}), ...(resolved.resourceId ? { resource_id: resolved.resourceId } : {}), }; } export function loadMemorySnapshot(authStore = new AuthStore(), includeContent = true): LoadedFileSnapshot { const profile = authStore.getActive(); if (!profile) throw new Error(accountRequiredMessage('Not logged in.')); const path = getProfileMemoryFile(profile); ensureMemoryFile(path); const exists = existsSync(path); return { path, exists, content: includeContent && exists ? readFileSync(path, 'utf8') : '', }; } export function limitMemoryForAgent( snapshot: LoadedFileSnapshot, lineLimit = AGENT_MEMORY_LINE_LIMIT, ): LoadedMemorySnapshot { const lineEndPattern = /\r\n|\r|\n/g; const lineEndOffsets: number[] = []; let match: RegExpExecArray | null; while ((match = lineEndPattern.exec(snapshot.content)) !== null) { lineEndOffsets.push(match.index + match[0].length); } const endsWithLineBreak = lineEndOffsets.at(-1) === snapshot.content.length; const totalLines = snapshot.content.length === 0 ? 0 : lineEndOffsets.length + (endsWithLineBreak ? 0 : 1); const truncated = totalLines > lineLimit; const cutoff = truncated ? lineEndOffsets[lineLimit - 1] : snapshot.content.length; return { ...snapshot, content: snapshot.content.slice(0, cutoff), line_limit: lineLimit, total_lines: totalLines, truncated, }; } export function loadContext( authStore = new AuthStore(), options: { includeContent?: boolean } = {}, ): LoadContextSnapshot { const includeContent = options.includeContent !== false; return { persona: loadPersonaSnapshot(authStore, includeContent), memory: limitMemoryForAgent(loadMemorySnapshot(authStore, includeContent)), }; } /** Assemble the same complete report for load and prepare --full. */ export function formatLoadReport( context: LoadContextSnapshot, saved?: DeferredLoadContext & { prepared_at: string }, ) { const persona = context.persona; const configurationWarnings: Record[] = [...(saved?.configuration_warnings ?? [])]; if (!saved) configurationWarnings.push({ code: 'PREPARED_CONTEXT_UNAVAILABLE', message: 'Prepared resource results are unavailable. Local persona and memory are still returned; do not repeat start/join.', }); if (context.memory.truncated) configurationWarnings.push({ code: 'MEMORY_LENGTH_EXCEEDED', line_limit: context.memory.line_limit, total_lines: context.memory.total_lines, message: `Memory exceeds ${context.memory.line_limit} lines; only the first ${context.memory.line_limit} lines are included. Organize it during the post-game debrief.`, }); return { prepared_at: saved?.prepared_at ?? null, context: { persona: saved?.persona_available !== false && persona.exists ? { name: persona.id ?? (persona.path ? basename(persona.path, extname(persona.path)) : 'persona'), content: persona.content, source: persona.source ?? 'none', } : null, memory: context.memory.content, }, sync: saved?.sync ?? { status: 'unavailable' }, ...(saved?.changes ? { changes: saved.changes } : {}), capabilities: saved?.capabilities ?? null, configuration_warnings: configurationWarnings, }; }