Skip to content

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

2.8 KB
Raw Blame
export interface BackgroundCommandProcess {
	stop(): void;
}

export interface DetachedProcessGroupListener {
	onOutput(text: string): void;
	/** Every process of the group has exited (or the group was stopped). */
	onExit(): void;
}

/**
 * Processes a command left running in its process group after the command shell exited.
 *
 * The host keeps watching the group until it empties; `stop` terminates the whole group,
 * `release` only stops watching and leaves the processes running.
 */
export interface DetachedProcessGroup extends BackgroundCommandProcess {
	readonly processGroupId: number;
	/** Epoch ms at which the host confirmed the group outlived its shell. */
	readonly adoptedAt: number;
	/** Starts delivering output and exit; output produced before attaching is buffered. */
	attach(listener: DetachedProcessGroupListener): void;
	release(): void;
}

export interface SpawnBackgroundCommandProcessOptions {
	readonly command: string;
	readonly cwd: string;
	readonly env: NodeJS.ProcessEnv;
	readonly onOutput: (text: string) => void;
	readonly onExit: (exitCode: number | undefined) => void;
	readonly onError: (error: Error) => void;
	/** Called right before `onExit` when processes of the command outlived the shell. */
	readonly onDetached?: (group: DetachedProcessGroup) => void;
}

export interface BackgroundCommandProcessOperations {
	spawn(options: SpawnBackgroundCommandProcessOptions): BackgroundCommandProcess;
	/**
	 * Resumes watching a group adopted by an earlier host process. Resolves `undefined` when the
	 * group is gone or its id now belongs to processes started after the adoption.
	 */
	reattach?(
		record: Pick<DetachedProcessRecord, "processGroupId" | "adoptedAt">,
	): Promise<DetachedProcessGroup | undefined>;
}

export interface BackgroundCommandOutput {
	readonly path: string;
	append(text: string): void;
	read(offset: number): string;
	close(): void;
}

export interface BackgroundCommandOutputStore {
	create(taskId: string): BackgroundCommandOutput;
	/** Reopens the output of a task from an earlier host process for reading. */
	open?(path: string): BackgroundCommandOutput;
}

/** What survives a host restart about one adopted process group. */
export interface DetachedProcessRecord {
	readonly processGroupId: number;
	readonly adoptedAt: number;
	readonly command: string;
	readonly cwd: string;
	readonly outputFile: string;
	readonly toolCallId?: string;
}

/** Durable list of the adopted process groups that belong to one session. */
export interface DetachedProcessRegistry {
	list(): readonly DetachedProcessRecord[];
	record(entry: DetachedProcessRecord): void;
	remove(processGroupId: number): void;
}

export interface BackgroundCommandHost {
	readonly processOperations: BackgroundCommandProcessOperations;
	readonly outputStore: BackgroundCommandOutputStore;
	readonly detachedProcessRegistry?: DetachedProcessRegistry;
}