Skip to content

Open-source, local-first AI agent for real work.

2.8 KB
Raw Blame
import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
import { dirname } from "node:path";
import type { DetachedProcessRecord, DetachedProcessRegistry } from "../shared/background-command-host.js";

const FILE_VERSION = 1;

interface StoredDetachedProcess extends DetachedProcessRecord {
	readonly sessionId: string;
}

export interface NodeDetachedProcessRegistryOptions {
	/** Shared by every session of the host; entries carry their session id. */
	readonly filePath: string;
	readonly sessionId: string;
}

/**
 * File-backed registry of adopted process groups.
 *
 * Every write re-reads the file, so sessions of one host process never lose each other's
 * entries; synchronous I/O keeps each read-modify-write uninterrupted.
 */
export function createNodeDetachedProcessRegistry(
	options: NodeDetachedProcessRegistryOptions,
): DetachedProcessRegistry {
	const update = (change: (entries: StoredDetachedProcess[]) => StoredDetachedProcess[]): void => {
		writeEntries(options.filePath, change(readEntries(options.filePath)));
	};
	return {
		list() {
			return readEntries(options.filePath)
				.filter((entry) => entry.sessionId === options.sessionId)
				.map(({ sessionId: _sessionId, ...record }) => record);
		},
		record(entry) {
			update((entries) => [
				...entries.filter((existing) => existing.processGroupId !== entry.processGroupId),
				{ ...entry, sessionId: options.sessionId },
			]);
		},
		remove(processGroupId) {
			update((entries) =>
				entries.filter(
					(entry) => !(entry.sessionId === options.sessionId && entry.processGroupId === processGroupId),
				),
			);
		},
	};
}

function readEntries(filePath: string): StoredDetachedProcess[] {
	let parsed: unknown;
	try {
		parsed = JSON.parse(readFileSync(filePath, "utf8"));
	} catch {
		return [];
	}
	if (!isRecord(parsed) || parsed.version !== FILE_VERSION || !Array.isArray(parsed.entries)) return [];
	return parsed.entries.filter(isStoredDetachedProcess);
}

function writeEntries(filePath: string, entries: readonly StoredDetachedProcess[]): void {
	mkdirSync(dirname(filePath), { recursive: true });
	const temporaryPath = `${filePath}.${process.pid}.tmp`;
	writeFileSync(temporaryPath, `${JSON.stringify({ version: FILE_VERSION, entries }, null, 2)}\n`);
	renameSync(temporaryPath, filePath);
}

function isStoredDetachedProcess(value: unknown): value is StoredDetachedProcess {
	return (
		isRecord(value) &&
		typeof value.sessionId === "string" &&
		Number.isInteger(value.processGroupId) &&
		typeof value.adoptedAt === "number" &&
		typeof value.command === "string" &&
		typeof value.cwd === "string" &&
		typeof value.outputFile === "string" &&
		(value.toolCallId === undefined || typeof value.toolCallId === "string")
	);
}

function isRecord(value: unknown): value is Record<string, unknown> {
	return typeof value === "object" && value !== null;
}