// Where sessions live, and which session a message belongs to. // // Layout under the data folder: // sessions/index.json session key -> current session id (and earlier ones) // sessions/.jsonl one event log per session // // A session KEY names a conversation slot ("steward:main"). A session ID names one concrete // log. `/new` keeps the key and starts a fresh log; the old log stays on disk untouched. import { randomBytes } from 'node:crypto'; import { readFile } from 'node:fs/promises'; import path from 'node:path'; import { Mutex, writeFileAtomic } from '../runtime/atomic.ts'; import { Session, type RecoveryReport } from './session.ts'; /** * How messages map to sessions. With "main", every direct message from the owner shares one * conversation, whatever the channel. With "per-channel", each channel gets its own. Scheduled * jobs (lab 09) and sub-agents (lab 10) always get their own keys. */ export type SessionScope = 'main' | 'per-channel'; export function sessionKey(agent: string, scope: SessionScope, channel: string): string { return scope === 'main' ? `${agent}:main` : `${agent}:channel:${channel}`; } interface IndexEntry { current: string; previous: string[]; } interface IndexFile { version: 1; keys: Record; } export interface SessionSummary { key: string; current: string; previous: number; } export class SessionStore { readonly dir: string; private readonly clock: () => Date; /** Index updates run one at a time: parallel helpers (lab 10) open sessions concurrently. */ private readonly indexLock = new Mutex(); constructor(dataDir: string, clock: () => Date = () => new Date()) { this.dir = path.join(dataDir, 'sessions'); this.clock = clock; } /** Opens the current session for a key, creating it on first use. */ async open(key: string): Promise<{ session: Session; recovery: RecoveryReport }> { const entry = await this.indexLock.run(async () => { const index = await this.readIndex(); let found = index.keys[key]; if (!found) { found = { current: this.newId(), previous: [] }; index.keys[key] = found; await this.writeIndex(index); } return found; }); return Session.open(key, entry.current, this.fileFor(entry.current), this.clock); } /** Reads the current session for a key without changing anything (see Session.peek). */ async peek(key: string): Promise { const entry = (await this.readIndex()).keys[key]; if (!entry) return undefined; return Session.peek(key, entry.current, this.fileFor(entry.current), this.clock); } /** Starts a new session for the key. The previous log is kept as it is. */ async rotate(key: string): Promise { const entry = await this.indexLock.run(async () => { const index = await this.readIndex(); const old = index.keys[key]; const next: IndexEntry = { current: this.newId(), previous: old ? [...old.previous, old.current] : [], }; index.keys[key] = next; await this.writeIndex(index); return next; }); const { session } = await Session.open( key, entry.current, this.fileFor(entry.current), this.clock, ); return session; } async list(): Promise { const index = await this.readIndex(); return Object.entries(index.keys) .map(([key, entry]) => ({ key, current: entry.current, previous: entry.previous.length })) .sort((a, b) => a.key.localeCompare(b.key)); } fileFor(sessionId: string): string { return path.join(this.dir, `${sessionId}.jsonl`); } private newId(): string { const stamp = this.clock().toISOString().replace(/[-:]/g, '').replace('T', '-').slice(0, 15); return `${stamp}-${randomBytes(2).toString('hex')}`; } private async readIndex(): Promise { try { return JSON.parse(await readFile(path.join(this.dir, 'index.json'), 'utf8')) as IndexFile; } catch (err) { if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { version: 1, keys: {} }; throw err; } } /** Write to a temp file, then rename: a crash leaves either the old or the new index. */ private async writeIndex(index: IndexFile): Promise { await writeFileAtomic(path.join(this.dir, 'index.json'), JSON.stringify(index, null, 2) + '\n'); } }