/** * ============================================================ * src/context/sessionRegistry.ts —— 同 cwd 多 session 注册表 * ------------------------------------------------------------ * 做的事: * 一个工作目录下可以有多个并行 session(id = 任意字符串), * 每次只激活一个。active 信息存 ~/.minimal-agent/active-sessions.json, * 键是 cwd 的 sha1[:12],值是当前激活的 session id 字符串。 * * 文件路径: * /.minimal-agent/active-sessions.json * /.minimal-agent/sessions/--.json * (新格式;旧格式 .json 视作 id='default' 兼容) * * 抉择: * - active 文件 atomic write(写 .tmp + rename)—— 防止跨进程并发写时部分写入 * - sessionId 为字符串,'default' 是约定的默认值(无 active 时返回它) * - listSessions 同时扫新旧格式,保证迁移期不丢 * ============================================================ */ import { createHash, randomUUID } from 'node:crypto'; import { basename } from 'node:path'; import { copyFile, mkdir, readFile, readdir, rename, rm, stat, unlink, writeFile } from 'node:fs/promises'; import { homedir } from 'node:os'; import { join } from 'node:path'; import { resolveSessionFile, sessionFileFor, validateSessionId } from './sessionPath.js'; import { workspaceIndexService } from './workspaceIndex.js'; import type { ModelFallbackReason, ModelRef } from '../modelRef.js'; export { validateSessionId } from './sessionPath.js'; /** 解析根目录,支持 MINIMAL_AGENT_HOME 测试覆盖 */ function agentHome(): string { return process.env.MINIMAL_AGENT_HOME ?? homedir(); } function agentDir(): string { return join(agentHome(), '.minimal-agent'); } function activeFilePath(): string { return join(agentDir(), 'active-sessions.json'); } function sessionsDirPath(): string { return join(agentDir(), 'sessions'); } function cwdHash(cwd: string): string { return createHash('sha1').update(cwd).digest('hex').slice(0, 12); } interface ActiveMap { [cwdHash: string]: string; } export interface SessionSummary { id: string; title: string; createdAt: number; updatedAt: number; lastMessagePreview?: string; /** Session 级模型绑定;缺省时回退到全局基座模型。 */ modelId?: string; preferredModel?: ModelRef; effectiveModel?: ModelRef; fallbackReason?: ModelFallbackReason; restoreWhenAvailable?: boolean; onlineToolCategories?: string[]; } interface SessionMetadataFile { [cwdHash: string]: Record; } function metadataFilePath(): string { return join(agentDir(), 'session-metadata.json'); } async function loadMetadata(): Promise { try { const value = JSON.parse(await readFile(metadataFilePath(), 'utf8')) as unknown; return value && typeof value === 'object' && !Array.isArray(value) ? value as SessionMetadataFile : {}; } catch { return {}; } } async function saveMetadata(value: SessionMetadataFile): Promise { await mkdir(agentDir(), { recursive: true }); const target = metadataFilePath(); const tmp = `${target}.${process.pid}.${randomUUID()}.tmp`; try { await writeFile(tmp, JSON.stringify(value, null, 2), { encoding: 'utf8', mode: 0o600 }); await rename(tmp, target); } finally { await unlink(tmp).catch(() => {}); } } async function loadActiveMap(): Promise { try { const raw = await readFile(activeFilePath(), 'utf8'); const data = JSON.parse(raw); if (data && typeof data === 'object' && !Array.isArray(data)) { return data as ActiveMap; } return {}; } catch { return {}; } } async function saveActiveMap(map: ActiveMap): Promise { await mkdir(agentDir(), { recursive: true }); const target = activeFilePath(); const tmp = `${target}.${process.pid}.${randomUUID()}.tmp`; try { await writeFile(tmp, JSON.stringify(map), { encoding: 'utf8', mode: 0o600 }); await rename(tmp, target); } finally { await unlink(tmp).catch(() => {}); } } /** * 同进程内的串行互斥队列(`session-metadata.json` / `active-sessions.json` 都是全局 * 单文件,按 cwdHash 分组——两个并发调用方 load→改→save 会互相覆盖丢更新)。 * 照抄 `plugins/cron-runner/src/store.ts` 的 `enqueueMutation` 模式。 * * 同进程先排队,队首操作再取得跨进程目录锁。CLI、Desktop Runtime 与 Cron 可以同时 * 使用同一个 MINIMAL_AGENT_HOME;仅靠 rename 只能避免半写文件,不能避免两个进程 * load→改→save 时后写覆盖先写。目录创建在各平台都是原子的,适合做短临界区互斥。 * * 下面所有导出的可变函数(setActiveSession/createSession/updateSessionMetadata/ * copySession/deleteSession)都必须整体包一层 enqueueMutation;内部若需要调用 * 另一个可变操作的逻辑,必须调用其 *Unlocked 版本而不是导出版本——否则内层调用会 * 排到同一队列的外层调用之后,外层等内层、内层等外层排到自己,死锁。 */ let mutationQueue: Promise = Promise.resolve(); const LOCK_STALE_MS = 120_000; const LOCK_WAIT_MS = 15_000; function lockDirPath(): string { return join(agentDir(), 'session-registry.lock'); } function processIsAlive(pid: number): boolean { if (!Number.isInteger(pid) || pid <= 0) return false; try { process.kill(pid, 0); return true; } catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM'; } } async function acquireRegistryLock(): Promise<() => Promise> { const lockDir = lockDirPath(); const ownerFile = join(lockDir, 'owner.json'); const startedAt = Date.now(); await mkdir(agentDir(), { recursive: true, mode: 0o700 }); while (true) { try { await mkdir(lockDir, { mode: 0o700 }); await writeFile(ownerFile, JSON.stringify({ pid: process.pid, createdAt: Date.now() }), { encoding: 'utf8', mode: 0o600, }); return async () => { await rm(lockDir, { recursive: true, force: true }); }; } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; let stale = false; try { const [ownerRaw, info] = await Promise.all([readFile(ownerFile, 'utf8'), stat(lockDir)]); const owner = JSON.parse(ownerRaw) as { pid?: number; createdAt?: number }; stale = typeof owner.pid === 'number' ? !processIsAlive(owner.pid) : Date.now() - info.mtimeMs > LOCK_STALE_MS; } catch { try { stale = Date.now() - (await stat(lockDir)).mtimeMs > LOCK_STALE_MS; } catch { continue; } } if (stale) { await rm(lockDir, { recursive: true, force: true }); continue; } if (Date.now() - startedAt > LOCK_WAIT_MS) { throw new Error('等待 Session 注册表锁超时,请确认没有异常残留的 minimal-agent 进程'); } await new Promise((resolve) => setTimeout(resolve, 25)); } } } function enqueueMutation(mutate: () => Promise): Promise { const run = async (): Promise => { const release = await acquireRegistryLock(); try { return await mutate(); } finally { await release(); } }; const operation = mutationQueue.then(run, run); mutationQueue = operation.then(() => undefined, () => undefined); return operation; } /** * 获取当前 cwd 的激活 session id。 * 无记录 → 返回 'default'。 */ export async function getActiveSession(cwd: string): Promise { const workspace = await workspaceIndexService.findByPath(cwd).catch(() => null); if (workspace?.activeSessionId) { try { return validateSessionId(workspace.activeSessionId); } catch { /* fall through */ } } const map = await loadActiveMap(); try { return validateSessionId(map[cwdHash(cwd)] ?? 'default'); } catch { return 'default'; } } async function setActiveSessionUnlocked(cwd: string, sessionId: string): Promise { const id = validateSessionId(sessionId); const map = await loadActiveMap(); map[cwdHash(cwd)] = id; await saveActiveMap(map); // 索引是自愈便利层:权威存储(active-sessions.json)已落盘,索引写失败 // (锁超时/磁盘错误)绝不能反过来打断会话切换——尽力而为,下次 reconcile 自愈。 await workspaceIndexService.setActive(cwd, id).catch(async () => { await workspaceIndexService.recordPendingMutation({ type: 'active', path: cwd, sessionId: id }).catch(() => {}); }); } /** * 设置当前 cwd 的激活 session id。 * * 写入策略:先写 .tmp,再原子 rename 到 target; * 即使被中断也只会留临时文件,不破坏 target。 */ export async function setActiveSession( cwd: string, sessionId: string, ): Promise { return enqueueMutation(() => setActiveSessionUnlocked(cwd, sessionId)); } /** * 列出当前 cwd 下所有真实存在的 session id。 * * 扫描规则: * - 新格式 `--.json` → 提取 id * - 旧格式 `.json` → 视作 'default' * - default 只有存在历史文件或元数据时才返回;CLI 的隐式 default 写入兼容不变 */ export async function listSessions(cwd: string): Promise { const dir = sessionsDirPath(); const defaultName = basename(sessionFileFor(cwd, 'default')); const prefix = defaultName.slice(0, -'default.json'.length); let names: string[] = []; try { names = await readdir(dir); } catch { /* a new workspace has no files yet */ } const ids = names .filter((name) => name.startsWith(prefix) && name.endsWith('.json') && !name.endsWith('.tmp.json')) .map((name) => name.slice(prefix.length, -'.json'.length)) .filter((id) => { try { validateSessionId(id); return true; } catch { return false; } }); const metadata = await loadMetadata(); ids.push(...Object.keys(metadata[cwdHash(cwd)] ?? {}).filter((id) => !ids.includes(id))); if (!ids.includes('default')) { try { await stat(await resolveSessionFile(cwd, 'default')); ids.push('default'); } catch { // A missing implicit default is not a visible conversation. } } const unique = [...new Set(ids.filter((id) => id !== 'default'))].sort(); return ids.includes('default') ? ['default', ...unique] : unique; } export async function listSessionSummaries(cwd: string): Promise { const ids = await listSessions(cwd); const metadata = await loadMetadata(); const group = metadata[cwdHash(cwd)] ?? {}; const indexed = await workspaceIndexService.findByPath(cwd).catch(() => null); const indexedById = new Map((indexed?.sessions ?? []).map((session) => [session.id, session])); for (const session of indexed?.sessions ?? []) { if (!ids.includes(session.id)) ids.push(session.id); } return (await Promise.all(ids.map(async (id) => { const existing = group[id] ?? indexedById.get(id); let modified = existing?.updatedAt ?? Date.now(); try { modified = (await stat(await resolveSessionFile(cwd, id))).mtimeMs; } catch { /* metadata-only draft */ } return existing ? { ...existing, updatedAt: Math.max(existing.updatedAt, modified) } : { id, title: id === 'default' ? '默认会话' : id, createdAt: modified, updatedAt: modified, }; }))).sort((a, b) => { if (a.id === 'default') return -1; if (b.id === 'default') return 1; return b.updatedAt - a.updatedAt; }); } async function createSessionUnlocked( cwd: string, options: { id?: string; title?: string; modelId?: string; preferredModel?: ModelRef; onlineToolCategories?: string[] }, ): Promise { const id = validateSessionId(options.id ?? randomUUID()); const metadata = await loadMetadata(); const hash = cwdHash(cwd); const group = metadata[hash] ?? {}; if (group[id] || (await listSessions(cwd)).includes(id)) throw new Error(`session 已存在: ${id}`); const now = Date.now(); const summary = { id, title: options.title?.trim() || '新会话', createdAt: now, updatedAt: now, ...(options.modelId?.trim() ? { modelId: options.modelId.trim() } : {}), ...(options.preferredModel ? { preferredModel: options.preferredModel, restoreWhenAvailable: true } : {}), ...(options.onlineToolCategories ? { onlineToolCategories: [...options.onlineToolCategories] } : {}), }; metadata[hash] = { ...group, [id]: summary }; await saveMetadata(metadata); // 权威元数据已落盘;索引只是便利层,失败不阻断建会话(见 setActiveSessionUnlocked)。 await workspaceIndexService.touchSession(cwd, summary).catch(async () => { await workspaceIndexService.recordPendingMutation({ type: 'touch', path: cwd, session: summary }).catch(() => {}); }); return summary; } export async function createSession( cwd: string, options: { id?: string; title?: string; modelId?: string; preferredModel?: ModelRef; onlineToolCategories?: string[] } = {}, ): Promise { return enqueueMutation(() => createSessionUnlocked(cwd, options)); } async function updateSessionMetadataUnlocked( cwd: string, sessionId: string, patch: { title?: string; lastMessagePreview?: string; modelId?: string | null; preferredModel?: ModelRef | null; effectiveModel?: ModelRef | null; fallbackReason?: ModelFallbackReason; restoreWhenAvailable?: boolean; onlineToolCategories?: string[] }, ): Promise { const id = validateSessionId(sessionId); const metadata = await loadMetadata(); const hash = cwdHash(cwd); const group = metadata[hash] ?? {}; const now = Date.now(); const previous = group[id] ?? { id, title: id === 'default' ? '默认会话' : id, createdAt: now, updatedAt: now }; const next = { ...previous, ...(patch.title !== undefined ? { title: patch.title.trim() || previous.title } : {}), ...(patch.lastMessagePreview !== undefined ? { lastMessagePreview: patch.lastMessagePreview.slice(0, 240) } : {}), ...(patch.modelId === null ? { modelId: undefined } : patch.modelId !== undefined ? { modelId: patch.modelId.trim() } : {}), ...(patch.preferredModel === null ? { preferredModel: undefined } : patch.preferredModel !== undefined ? { preferredModel: patch.preferredModel } : {}), ...(patch.effectiveModel === null ? { effectiveModel: undefined } : patch.effectiveModel !== undefined ? { effectiveModel: patch.effectiveModel } : {}), ...(patch.fallbackReason !== undefined ? { fallbackReason: patch.fallbackReason } : {}), ...(patch.restoreWhenAvailable !== undefined ? { restoreWhenAvailable: patch.restoreWhenAvailable } : {}), ...(patch.onlineToolCategories !== undefined ? { onlineToolCategories: [...patch.onlineToolCategories] } : {}), updatedAt: now, }; metadata[hash] = { ...group, [id]: next }; await saveMetadata(metadata); // 权威元数据已落盘;索引只是便利层,失败不阻断元数据更新。 await workspaceIndexService.touchSession(cwd, next).catch(async () => { await workspaceIndexService.recordPendingMutation({ type: 'touch', path: cwd, session: next }).catch(() => {}); }); return next; } export async function updateSessionMetadata( cwd: string, sessionId: string, patch: { title?: string; lastMessagePreview?: string; modelId?: string | null; preferredModel?: ModelRef | null; effectiveModel?: ModelRef | null; fallbackReason?: ModelFallbackReason; restoreWhenAvailable?: boolean; onlineToolCategories?: string[] }, ): Promise { return enqueueMutation(() => updateSessionMetadataUnlocked(cwd, sessionId, patch)); } export async function copySession(cwd: string, sourceSessionId: string, title?: string): Promise { return enqueueMutation(async () => { const sourceId = validateSessionId(sourceSessionId); const source = (await listSessionSummaries(cwd)).find((session) => session.id === sourceId); const target = await createSessionUnlocked(cwd, { title: title ?? '会话副本', ...(source?.modelId ? { modelId: source.modelId } : {}), ...(source?.preferredModel ? { preferredModel: source.preferredModel } : {}), ...(source?.onlineToolCategories ? { onlineToolCategories: source.onlineToolCategories } : {}) }); try { await mkdir(sessionsDirPath(), { recursive: true }); await copyFile(await resolveSessionFile(cwd, sourceId), sessionFileFor(cwd, target.id)); } catch { // An empty source session is still valid; its metadata is the useful clone. } return target; }); } export async function deleteSession(cwd: string, sessionId: string): Promise { return enqueueMutation(async () => { const id = validateSessionId(sessionId); if (id === 'default') throw new Error('默认会话不能删除,可以归档后清空'); await unlink(await resolveSessionFile(cwd, id)).catch(() => {}); const metadata = await loadMetadata(); const hash = cwdHash(cwd); if (metadata[hash]) { delete metadata[hash][id]; await saveMetadata(metadata); } // 权威元数据已删除;索引只是便利层,失败不阻断删会话。 await workspaceIndexService.removeSession(cwd, id).catch(async () => { await workspaceIndexService.recordPendingMutation({ type: 'remove-session', path: cwd, sessionId: id }).catch(() => {}); }); // 注意:这里故意直接读 loadActiveMap + 调 *Unlocked,不调导出的 // getActiveSession/setActiveSession——同一个已在队列里的 mutation // 不能再排一次同一队列,否则自己等自己,死锁。 const activeMap = await loadActiveMap(); if ((activeMap[cwdHash(cwd)] ?? 'default') === id) { await setActiveSessionUnlocked(cwd, 'default'); } }); }