Skip to content

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

11.7 KB
Raw Blame
import type {
	RuntimeExecutionModeUpdate,
	RuntimeResourceContext,
	RuntimeSessionExecutionController,
	SessionExecutionMode,
} from "@vetta/runtime-core";
import type { AgentFeatureDefinition, AgentSession, CapabilityBinding } from "@vetta/runtime-core/kernel";
import { sessionExtensionObservation } from "@vetta/runtime-core/session-extensions";
import {
	type BackgroundCommandService,
	CODING_TOOL_AVAILABILITY_ERROR_CODES,
	type CodingToolAvailabilityErrorCode,
	type CodingToolCatalogEntry,
	type CodingToolRegistration,
	createCodingToolsFeature,
	GenerationalCodingToolCatalog,
	guardCodingToolRegistration,
	InMemoryCodingToolRegistry,
} from "@vetta/runtime-tools";
import type { CodingAgentSessionExecutionEnvironment } from "../../composition/contracts/session-execution-environment.js";
import {
	createTaskOutputToolRegistration,
	createTaskStopToolRegistration,
} from "../../features/background-tasks/index.js";
import {
	type CodingAgentRuntimeToolRegistration,
	type CodingAgentToolActivation,
	selectCodingAgentToolRegistrations,
} from "../../runtime-contracts/index.js";
import { declareCodingAgentPlatformTools } from "../../tool-policy/platform-tool-declarations.js";
import { CODING_AGENT_BACKGROUND_TASKS_OBSERVATION } from "../background/background-work-session-extension-contract.js";
import { buildCodingAgentBackgroundCommandNotification } from "../background/notification.js";
import type { CodingAgentSandboxAuthorizationPort } from "../sandbox/authorization-contract.js";
import { createCodingAgentSandboxToolRegistrations } from "../sandbox/tool-registrations.js";

const SESSION_EXECUTION_FEATURE_ID = "coding-session-execution-tools";

export interface CodingAgentSessionExecutionRuntimeOptions {
	readonly cwd: string;
	readonly activation: CodingAgentToolActivation;
	readonly environment: CodingAgentSessionExecutionEnvironment;
	readonly enableBackgroundTasks?: boolean;
	readonly initialMode?: SessionExecutionMode;
	readonly sandboxHostPath?: string;
	readonly linuxBubblewrapPath?: string;
	readonly macosSandboxExecPath?: string;
	readonly readSessionId: () => string;
	readonly resolveToolEntry?: (toolName: string) => CodingToolCatalogEntry | undefined;
	readonly resourceContext: RuntimeResourceContext;
	readonly sandboxAuthorization: CodingAgentSandboxAuthorizationPort;
}

/** Session-local 的命令、后台任务与 sandbox 执行组合。 */
export class CodingAgentSessionExecutionRuntime {
	readonly backgroundService: BackgroundCommandService;
	readonly feature: AgentFeatureDefinition;
	private readonly catalog: GenerationalCodingToolCatalog;
	private disposeTaskEvents: (() => void) | undefined;
	private disposeTaskNotifications: (() => void) | undefined;
	private readonly fullAccessRegistrations: readonly CodingAgentRuntimeToolRegistration[];
	private readonly sourceBindings = new Map<string, CapabilityBinding | undefined>();
	private mode: SessionExecutionMode;
	private nextCatalogGeneration = 0;

	constructor(private readonly options: CodingAgentSessionExecutionRuntimeOptions) {
		this.mode = options.initialMode ?? "full-access";
		this.backgroundService = options.environment.backgroundService;
		this.fullAccessRegistrations = [
			...declareCodingAgentPlatformTools(
				options.environment.registrations.filter(({ tool }) => !BACKGROUND_TASK_TOOL_NAMES.has(tool.name)),
			),
			createTaskOutputToolRegistration({ backgroundService: this.backgroundService }),
			createTaskStopToolRegistration({ backgroundService: this.backgroundService }),
		].map((registration) => inheritModelOrder(registration, options.resolveToolEntry?.(registration.tool.name)));
		for (const toolName of SESSION_EXECUTION_TOOL_NAMES) {
			this.sourceBindings.set(toolName, options.resolveToolEntry?.(toolName)?.binding);
		}
		const initialRegistry = this.createModeRegistry(
			this.buildModeRegistrations(this.mode, this.fullAccessRegistrations, {
				mode: this.mode,
				sessionId: options.readSessionId(),
				sandboxHostPath: options.sandboxHostPath,
				linuxBubblewrapPath: options.linuxBubblewrapPath,
				macosSandboxExecPath: options.macosSandboxExecPath,
			}),
		);
		this.catalog = new GenerationalCodingToolCatalog(initialRegistry, {
			resolveAvailabilityErrorCode: (toolName) => this.resolveAvailabilityErrorCode(toolName),
		});
		this.feature = createCodingToolsFeature({
			id: SESSION_EXECUTION_FEATURE_ID,
			catalog: this.catalog,
			selectRegistrations: (registrations) => {
				const selectedNames = new Set(
					selectCodingAgentToolRegistrations(
						this.fullAccessRegistrations,
						withBackgroundTaskCapability(options.activation, options.enableBackgroundTasks !== false),
					).map(({ tool }) => tool.name),
				);
				return registrations.filter(({ tool }) => selectedNames.has(tool.name));
			},
			filterRegistration: (registration) =>
				this.isEnabled(registration.tool.name) &&
				this.resolveAvailabilityErrorCode(registration.tool.name) === undefined,
		});
		this.bindBackgroundTaskObservers();
	}

	createExecutionController(session: AgentSession): RuntimeSessionExecutionController {
		return {
			isBusy: () =>
				session.state === "running" || session.state === "cancelling" || session.state === "recovery_required",
			reconfigure: async (update) => {
				const registrations = this.buildModeRegistrations(update.mode, this.fullAccessRegistrations, update);
				const next = this.createModeRegistry(registrations);
				this.catalog.publish(next);
				this.mode = update.mode;
			},
		};
	}

	async quiesceBackgroundCommands(): Promise<void> {
		this.unbindBackgroundTaskObservers();
		try {
			await this.backgroundService.shutdown();
		} finally {
			this.bindBackgroundTaskObservers();
		}
	}

	private bindBackgroundTaskObservers(): void {
		this.disposeTaskEvents = this.backgroundService.subscribe(() => {
			void this.options.resourceContext
				.reportObservation({
					...sessionExtensionObservation(CODING_AGENT_BACKGROUND_TASKS_OBSERVATION, this.backgroundService.list()),
					source: "tool",
				})
				.catch((error: unknown) => {
					console.warn("[coding-agent-runtime] failed to publish background task observation", error);
				});
		});
		this.disposeTaskNotifications = this.backgroundService.subscribeNotifications((task) => {
			void this.options.resourceContext
				.deliverAsyncContext([
					{
						type: "task-notification",
						content: [{ type: "text", text: buildCodingAgentBackgroundCommandNotification(task) }],
						modelVisible: true,
						display: true,
					},
				])
				.catch((error: unknown) => {
					console.warn("[coding-agent-runtime] failed to deliver background task notification", error);
				});
		});
	}

	private unbindBackgroundTaskObservers(): void {
		this.disposeTaskNotifications?.();
		this.disposeTaskNotifications = undefined;
		this.disposeTaskEvents?.();
		this.disposeTaskEvents = undefined;
	}

	readMode(): SessionExecutionMode {
		return this.mode;
	}

	readRegistrations(): readonly CodingToolRegistration[] {
		return this.catalog.snapshot().registrations;
	}

	readAvailableTools(): ReadonlyMap<string, CodingToolRegistration["tool"]> {
		return new Map(
			this.catalog
				.snapshot()
				.entries.map(
					(entry) => [entry.registration.tool.name, guardCodingToolRegistration(this.catalog, entry)] as const,
				)
				.filter(
					([toolName]) => this.isEnabled(toolName) && this.resolveAvailabilityErrorCode(toolName) === undefined,
				),
		);
	}

	ownsTool(toolName: string): boolean {
		if (!this.catalog.resolve(toolName)) return false;
		if (!this.options.resolveToolEntry) return true;
		const sourceBinding = this.sourceBindings.get(toolName);
		if (!sourceBinding) return false;
		const current = this.options.resolveToolEntry(toolName);
		return current === undefined || sameBinding(sourceBinding, current.binding);
	}

	async dispose(): Promise<void> {
		this.unbindBackgroundTaskObservers();
		try {
			await this.backgroundService.shutdown();
		} finally {
			await this.options.environment.dispose();
		}
	}

	private resolveAvailabilityErrorCode(toolName: string): CodingToolAvailabilityErrorCode | undefined {
		const resolveToolEntry = this.options.resolveToolEntry;
		if (!resolveToolEntry) return undefined;
		const sourceBinding = this.sourceBindings.get(toolName);
		const current = resolveToolEntry(toolName);
		if (!sourceBinding || !current) return CODING_TOOL_AVAILABILITY_ERROR_CODES.UNAVAILABLE;
		if (current.state === "revoked") return CODING_TOOL_AVAILABILITY_ERROR_CODES.REVOKED;
		if (!sameBinding(sourceBinding, current.binding)) {
			return CODING_TOOL_AVAILABILITY_ERROR_CODES.DEFINITION_CHANGED;
		}
		if (current.state === "deactivated") return CODING_TOOL_AVAILABILITY_ERROR_CODES.DEACTIVATED;
		return undefined;
	}

	private isEnabled(toolName: string): boolean {
		return this.options.enableBackgroundTasks !== false || !BACKGROUND_TASK_TOOL_NAMES.has(toolName);
	}

	private buildModeRegistrations(
		mode: SessionExecutionMode,
		fullAccessRegistrations: readonly CodingAgentRuntimeToolRegistration[],
		update: RuntimeExecutionModeUpdate,
	): readonly CodingAgentRuntimeToolRegistration[] {
		const taskRegistrations = fullAccessRegistrations.filter(
			({ tool }) => tool.name === "task_output" || tool.name === "task_stop",
		);
		if (mode === "full-access") return fullAccessRegistrations;
		return [
			...declareCodingAgentPlatformTools(
				createCodingAgentSandboxToolRegistrations({
					cwd: this.options.cwd,
					authorization: this.options.sandboxAuthorization,
					environment: this.options.environment.sandbox,
					windowsSandboxHostPath: update.sandboxHostPath,
					linuxBubblewrapPath: update.linuxBubblewrapPath,
					macosSandboxExecPath: update.macosSandboxExecPath,
					getSessionId: this.options.readSessionId,
				}),
			).map((registration) =>
				inheritModelOrder(registration, this.options.resolveToolEntry?.(registration.tool.name)),
			),
			...taskRegistrations,
		];
	}

	private createModeRegistry(
		registrations: readonly CodingAgentRuntimeToolRegistration[],
	): InMemoryCodingToolRegistry {
		this.nextCatalogGeneration += 1;
		return new InMemoryCodingToolRegistry(registrations.map(toRuntimeExecutionRegistration), {
			sourceId: `coding-session-execution-tools:${this.nextCatalogGeneration}`,
		});
	}
}

const SESSION_EXECUTION_TOOL_NAMES = ["bash", "shell", "read", "write", "edit", "task_output", "task_stop"] as const;
const BACKGROUND_TASK_TOOL_NAMES = new Set<string>(["task_output", "task_stop"]);

/** Session execution owns these base tool names whenever its runtime is active. */
export function isCodingAgentSessionExecutionToolName(toolName: string): boolean {
	return (SESSION_EXECUTION_TOOL_NAMES as readonly string[]).includes(toolName);
}

function inheritModelOrder(
	registration: CodingAgentRuntimeToolRegistration,
	source: CodingToolCatalogEntry | undefined,
): CodingAgentRuntimeToolRegistration {
	const modelOrder = source?.registration.modelOrder;
	const resultPolicy = source?.registration.resultPolicy;
	return {
		...registration,
		...(modelOrder === undefined ? {} : { modelOrder, tool: { ...registration.tool, modelOrder } }),
		...(resultPolicy ? { resultPolicy } : {}),
	};
}

function toRuntimeExecutionRegistration(registration: CodingAgentRuntimeToolRegistration): CodingToolRegistration {
	const { scopeUse: _scopeUse, requires: _requires, category: _category, ...runtimeRegistration } = registration;
	return runtimeRegistration;
}

function withBackgroundTaskCapability(
	activation: CodingAgentToolActivation,
	enabled: boolean,
): CodingAgentToolActivation {
	if (!enabled || activation.mode === "explicit") return activation;
	return {
		...activation,
		capabilities: new Set([...(activation.capabilities ?? []), "bg-tasks"]),
	};
}

function sameBinding(left: CapabilityBinding, right: CapabilityBinding): boolean {
	return (
		left.sourceId === right.sourceId && left.capabilityId === right.capabilityId && left.revision === right.revision
	);
}