Skip to content

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

10.1 KB
Raw Blame
import type { Message } from "@vetta/ai";
import type {
	ConversationDocument,
	RuntimeDocumentParticipant,
	RuntimeDocumentParticipantContext,
} from "@vetta/runtime-core";
import type {
	AgentFeature,
	AgentFeatureDefinition,
	RuntimeToolDefinition,
	StoredSessionEvent,
} from "@vetta/runtime-core/kernel";
import {
	isValidTaskName,
	type SubagentChildHandle,
	SubagentCoordinator,
	type SubagentLifecycle,
	type SubagentSnapshot,
	type SubagentSpawnRequest,
	type SubagentTypeDefinition,
	type SubagentTypeRegistryLike,
	taskPath,
} from "@vetta/runtime-subagents";
import type { CodingAgentSubagentWorkRuntime } from "../../execution/background/work-controller.js";
import type {
	CodingAgentSubagentSnapshot,
	CodingAgentWorkflowDispatcherPort,
	CodingAgentWorkflowDispatchRequest,
} from "../../runtime-contracts/index.js";
import type { CodingAgentSubagentProfile } from "../contracts/index.js";
import { CODING_AGENT_SUBAGENT_TYPE_WORKFLOW, createDefaultCodingAgentSubagentTypeRegistry } from "./profiles.js";
import { CodingAgentSubagentStatePersistence } from "./state-persistence.js";
import { CodingAgentSubagentTodoProjection, toSubagentSnapshot } from "./todo-progress-projection.js";
import { createCodingAgentSubagentRuntimeToolRegistrations } from "./tool-registrations.js";

export type { CodingAgentSubagentProfile } from "../contracts/index.js";
export {
	CODING_AGENT_SUBAGENT_TYPE_EXPLORER,
	CODING_AGENT_SUBAGENT_TYPE_GENERAL,
	CODING_AGENT_SUBAGENT_TYPE_WORKFLOW,
	createDefaultCodingAgentSubagentTypeRegistry,
} from "./profiles.js";

export interface CodingAgentSubagentRuntimeOptions {
	readonly parentSessionId: string;
	readonly maxConcurrent?: number;
	readonly createEntryId?: () => string;
	readonly lifecycle?: SubagentLifecycle;
	readonly typeRegistry?: SubagentTypeRegistryLike<CodingAgentSubagentProfile>;
	readonly readParentMessages: () => Promise<readonly Message[]>;
	readonly createChild: (
		request: SubagentSpawnRequest,
		type: SubagentTypeDefinition<CodingAgentSubagentProfile>,
		forkContext: readonly Message[] | undefined,
		todo: CodingAgentSubagentChildTodoBinding,
		signal?: AbortSignal,
	) => Promise<SubagentChildHandle>;
	readonly reopenChild?: (
		snapshot: SubagentSnapshot,
		type: SubagentTypeDefinition<CodingAgentSubagentProfile>,
		forkContext: readonly Message[] | undefined,
		todo: CodingAgentSubagentChildTodoBinding,
		signal?: AbortSignal,
	) => Promise<SubagentChildHandle>;
	readonly onNotify?: (agents: readonly CodingAgentSubagentSnapshot[]) => void;
	readonly onUpdate?: (agents: readonly CodingAgentSubagentSnapshot[]) => void;
	readonly formatInitialMessage?: (snapshot: SubagentSnapshot, message: string) => string;
	readonly validateRecoveredChild?: (snapshot: SubagentSnapshot) => Promise<string | undefined>;
	readonly onRecoveryIssue?: (message: string) => void;
	readonly onError?: (error: unknown, operation: string) => void;
}

export interface CodingAgentSubagentChildTodoBinding {
	readonly initialItems?: readonly string[];
	onItemsChanged(items: readonly { readonly status: string }[]): void;
}

/**
 * Coding Agent Session-local 子代理能力。
 *
 * 调度器只认识 Child Handle;具体 Session、模型、工具、存储和 MCP 继承由
 * Composition Root 注入的 Child Factory 决定。
 */
export class CodingAgentSubagentRuntime
	implements CodingAgentSubagentWorkRuntime, CodingAgentWorkflowDispatcherPort, RuntimeDocumentParticipant
{
	readonly feature: AgentFeatureDefinition;
	private readonly coordinator: SubagentCoordinator<CodingAgentSubagentProfile>;
	private readonly persistence: CodingAgentSubagentStatePersistence;
	private readonly todoProjection = new CodingAgentSubagentTodoProjection();
	private readonly tools: readonly RuntimeToolDefinition[];
	private disposed = false;

	constructor(options: CodingAgentSubagentRuntimeOptions) {
		const reopenChild = options.reopenChild;
		const registry = options.typeRegistry ?? createDefaultCodingAgentSubagentTypeRegistry();
		this.coordinator = new SubagentCoordinator({
			parentSessionId: options.parentSessionId,
			typeRegistry: registry,
			maxConcurrent: options.maxConcurrent,
			lifecycle: options.lifecycle,
			formatInitialMessage: options.formatInitialMessage,
			onError: options.onError,
			onNotify: (agents) => options.onNotify?.(this.todoProjection.projectAll(agents)),
			onUpdate: (agents) => {
				this.publishSnapshots(agents, options.onUpdate);
			},
			onDeliveryClaimed: (marker) => this.persistence.recordDelivery(marker),
			factory: {
				create: async (request, type, signal) =>
					options.createChild(
						request,
						type,
						shouldForkParentContext(type.profile) ? [...(await options.readParentMessages())] : undefined,
						this.createTodoBinding(request.taskName, options.onUpdate, true),
						signal,
					),
				reopen: reopenChild
					? async (snapshot, type, signal) =>
							reopenChild(
								snapshot,
								type,
								undefined,
								this.createTodoBinding(snapshot.taskName, options.onUpdate, false),
								signal,
							)
					: undefined,
			},
		});
		this.persistence = new CodingAgentSubagentStatePersistence({
			restore: async (state) => {
				const agents = await prepareRecoveredAgents(state.agents, registry, options);
				for (const snapshot of agents) this.todoProjection.restore(snapshot);
				try {
					this.coordinator.restore({
						agents: agents.map(toSubagentSnapshot),
						delivered: state.delivered,
					});
				} catch (error) {
					options.onRecoveryIssue?.(error instanceof Error ? error.message : String(error));
					this.coordinator.restore({ agents: [], delivered: [] });
				}
			},
			onRecoveryIssue: options.onRecoveryIssue,
			createEntryId: options.createEntryId,
		});
		this.tools = createCodingAgentSubagentRuntimeToolRegistrations(
			() => this.coordinator,
			() => this,
			CODING_AGENT_SUBAGENT_TYPE_WORKFLOW,
		).map(({ tool }) => tool);
		this.feature = {
			id: "coding-agent-subagents",
			prepare: async (): Promise<AgentFeature> => ({
				contribute: async () => ({ tools: this.tools }),
				dispose: async () => {},
			}),
		};
	}

	readTools(): readonly RuntimeToolDefinition[] {
		return this.tools;
	}

	clearFinished(): number {
		const cleared = this.coordinator.clearFinished();
		this.todoProjection.prune(this.coordinator.list());
		return cleared;
	}

	list(): readonly CodingAgentSubagentSnapshot[] {
		return this.todoProjection.projectAll(this.coordinator.list());
	}

	interrupt(target: string): CodingAgentSubagentSnapshot | undefined {
		if (!this.coordinator.get(target)) return undefined;
		return this.todoProjection.project(this.coordinator.interrupt(target));
	}

	interruptAll(): readonly CodingAgentSubagentSnapshot[] {
		return this.todoProjection.projectAll(this.coordinator.interruptAll());
	}

	dispatchWorkflows(requests: readonly CodingAgentWorkflowDispatchRequest[]): readonly CodingAgentSubagentSnapshot[] {
		const seed = this.todoProjection.seed(requests);
		try {
			const snapshots = this.coordinator.spawnMany(requests.map(({ todos: _todos, ...request }) => request));
			return this.todoProjection.projectAll(snapshots);
		} catch (error) {
			this.todoProjection.rollback(seed);
			throw error;
		}
	}

	initialize(document: ConversationDocument, context: RuntimeDocumentParticipantContext): Promise<void> {
		return this.persistence.initialize(document, context);
	}

	onDocumentChanged(document: ConversationDocument): Promise<void> {
		return this.persistence.onDocumentChanged(document);
	}

	onSessionEvent(event: StoredSessionEvent): Promise<void> {
		return this.persistence.onSessionEvent(event);
	}

	async dispose(): Promise<void> {
		if (this.disposed) return;
		this.disposed = true;
		await this.coordinator.dispose();
		await this.persistence.dispose();
	}

	private publishSnapshots(
		agents: readonly SubagentSnapshot[],
		onUpdate: CodingAgentSubagentRuntimeOptions["onUpdate"],
	): void {
		const snapshots = this.todoProjection.projectAll(agents);
		this.persistence.recordSnapshots(snapshots);
		onUpdate?.(snapshots);
	}

	private createTodoBinding(
		taskName: string,
		onUpdate: CodingAgentSubagentRuntimeOptions["onUpdate"],
		includeInitialItems: boolean,
	): CodingAgentSubagentChildTodoBinding {
		return {
			...(includeInitialItems ? { initialItems: this.todoProjection.readInitialItems(taskName) } : {}),
			onItemsChanged: (items) => {
				if (this.todoProjection.update(taskName, items)) {
					this.publishSnapshots(this.coordinator.list(), onUpdate);
				}
			},
		};
	}
}

function shouldForkParentContext(profile: CodingAgentSubagentProfile): boolean {
	return profile.contextPolicy ? profile.contextPolicy.mode === "full" : profile.forkParentContext !== false;
}

async function prepareRecoveredAgents(
	agents: readonly CodingAgentSubagentSnapshot[],
	registry: SubagentTypeRegistryLike<CodingAgentSubagentProfile>,
	options: CodingAgentSubagentRuntimeOptions,
): Promise<CodingAgentSubagentSnapshot[]> {
	const recovered: CodingAgentSubagentSnapshot[] = [];
	for (const snapshot of agents) {
		if (
			snapshot.parentSessionId !== options.parentSessionId ||
			!isValidTaskName(snapshot.taskName) ||
			snapshot.path !== taskPath(snapshot.taskName)
		) {
			options.onRecoveryIssue?.(`Ignoring recovered subagent "${snapshot.id}" with invalid ownership`);
			continue;
		}
		if (!registry.get(snapshot.agentType)) {
			recovered.push(recoveryFailure(snapshot, `Subagent type "${snapshot.agentType}" is no longer registered`));
			continue;
		}
		if (!snapshot.sessionFile && (snapshot.status === "completed" || snapshot.status === "interrupted")) {
			recovered.push(recoveryFailure(snapshot, "Recovered subagent has no child session transcript"));
			continue;
		}
		const validationIssue = snapshot.sessionFile ? await options.validateRecoveredChild?.(snapshot) : undefined;
		recovered.push(validationIssue ? recoveryFailure(snapshot, validationIssue) : snapshot);
	}
	return recovered;
}

function recoveryFailure(snapshot: CodingAgentSubagentSnapshot, errorMessage: string): CodingAgentSubagentSnapshot {
	return {
		...snapshot,
		status: "failed",
		endedAt: Date.now(),
		errorMessage,
		generation: snapshot.generation + 1,
		usage: { ...snapshot.usage },
		todoProgress: snapshot.todoProgress ? { ...snapshot.todoProgress } : undefined,
	};
}