Skip to content

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

38.6 KB
Raw Blame
import type { Message } from "@vetta/ai";
import type { HistoryEntry, PromptRequest, RuntimeQueuePromptIfRunningOutcome, SessionEvent } from "../contracts.js";
import {
	type ConversationDocument,
	type ConversationDocumentCommand,
	type ConversationDocumentCommandResult,
	type ConversationDocumentStore,
	type ConversationMessageRecord,
	conversationDocumentEntry,
	extractConversationEntryText,
	isConversationDocumentEntryEvent,
} from "../conversation/index.js";
import { createRuntimeId } from "../id-generator.js";
import type { AgentSession } from "../kernel/agent-session.js";
import type {
	AgentSessionState,
	ConversationRepository,
	EventSink,
	KernelEvent,
	QueuedSessionInput,
	RuntimeInputRequestPreparer,
	SessionInput,
	SessionInputQueueMode,
	SessionInputRequest,
	SessionSendResult,
	StoredSessionEvent,
	TurnResult,
} from "../kernel/contracts.js";
import { sessionBusyError, sessionClosedError } from "../kernel/errors.js";
import type { SessionInputQueueEntry, SessionInputQueueSnapshot } from "../kernel/session-input-queue.js";
import type { SessionContextState } from "../session-context-state.js";
import type { SessionExtensionEndpointToken } from "../session-extensions/contracts.js";
import { ConversationDocumentMutationCoordinator } from "./conversation-document-mutation-coordinator.js";
import { mapKernelEventToSessionEvents } from "./kernel-session-events.js";
import { RetryableCleanup } from "./retryable-cleanup.js";
import type { RuntimeDocumentParticipant, RuntimeDocumentParticipantContext } from "./runtime-document-participant.js";
import type { RuntimeModelRuntime } from "./runtime-model.js";
import {
	type RuntimeSessionIdentity,
	RuntimeSessionProjection,
	type RuntimeStateSource,
} from "./runtime-session-projection.js";
import type {
	RuntimeHostSessionAssembly,
	RuntimeHostSessionAssemblyCandidate,
	RuntimeSessionBackend,
} from "./session-backend.js";
import { SessionContextStateProjection } from "./session-context-state-projection.js";
import { baseSessionEvent } from "./session-events.js";
import type {
	RuntimeSessionConfigurationController,
	RuntimeSessionContextController,
	RuntimeSessionContextDeliveryController,
	RuntimeSessionContextUsageView,
	RuntimeSessionConversationController,
	RuntimeSessionConversationView,
	RuntimeSessionExecutionController,
	RuntimeSessionExecutionObservation,
	RuntimeSessionExecutionObservationStream,
	RuntimeSessionExtensionHost,
	RuntimeSessionMetadataController,
	RuntimeSessionQueueController,
	RuntimeSessionQueueView,
	RuntimeSessionState,
	RuntimeSessionToolController,
} from "./session-ports.js";

export type RuntimePromptResult = SessionSendResult;

/** 把公开 PromptRequest 封装为等待 Turn admission 的 Kernel 请求。 */
export interface RuntimePromptAdapter extends RuntimeInputRequestPreparer {
	createRequest(request: PromptRequest): SessionInputRequest;
}

export interface KernelRuntimeAssembly {
	readonly session: AgentSession;
	readonly repository: ConversationRepository;
	readonly conversationDocumentStore: ConversationDocumentStore;
	readonly promptAdapter: RuntimePromptAdapter;
	readonly modelRuntime: RuntimeModelRuntime;
	readonly identity: RuntimeSessionIdentity;
	readonly stateSource: RuntimeStateSource;
	readonly documentParticipants?: readonly RuntimeDocumentParticipant[];
	readonly extensionHost?: RuntimeSessionExtensionHost;
	readonly contextController?: RuntimeSessionContextController;
	readonly contextDeliveryController?: RuntimeSessionContextDeliveryController;
	readonly executionController?: RuntimeSessionExecutionController;
	readonly configurationController?: RuntimeSessionConfigurationController;
	readonly toolController?: RuntimeSessionToolController;
	/** 由组合根释放 Session 之外的独占资源;共享 Repository 不应在这里关闭。 */
	dispose?(): Promise<void>;
}

export interface KernelRuntimeFactory<TCreateOptions> {
	create(options: TCreateOptions, eventSink: EventSink): Promise<KernelRuntimeAssembly>;
	resume(options: TCreateOptions, eventSink: EventSink): Promise<KernelRuntimeAssembly>;
}

export interface KernelRuntimeSessionBackendOptions<TCreateOptions> {
	readonly runtimeFactory: KernelRuntimeFactory<TCreateOptions>;
}

export interface RuntimeSessionStatus {
	readonly sessionId: string;
	readonly state: AgentSessionState;
	readonly pendingMessageCount: number;
	readonly steeringMode: SessionInputQueueMode;
	readonly followUpMode: SessionInputQueueMode;
	readonly messageCount: number;
	readonly contextState?: SessionContextState;
}

/** Kernel Runtime 当前真实具备的 RuntimeHost 核心能力。 */
export type RuntimeSessionCoreAssembly = Pick<
	RuntimeHostSessionAssembly,
	"lifecycle" | "historyReader" | "historyController" | "modelController" | "modelView" | "workspaceView" | "corePorts"
> & {
	readonly conversationView: RuntimeSessionConversationView;
	readonly conversationController: RuntimeSessionConversationController;
	readonly queueView: RuntimeSessionQueueView;
	readonly queueController: RuntimeSessionQueueController;
	readonly contextUsageView: RuntimeSessionContextUsageView;
	readonly executionObservationStream: RuntimeSessionExecutionObservationStream;
	readonly extensionHost?: RuntimeSessionExtensionHost;
	readonly contextController?: RuntimeSessionContextController;
	readonly contextDeliveryController: RuntimeSessionContextDeliveryController;
	readonly metadataController: RuntimeSessionMetadataController;
	readonly toolController?: RuntimeSessionToolController;
};

/**
 * How long a stop waits for the turn to unwind before returning anyway. Long enough for
 * a tool that honours its AbortSignal to settle, short enough that one that ignores it
 * cannot hold the stop open.
 */
const ABORT_UNWIND_TIMEOUT_MS = 2_000;

export class RuntimeSession {
	private readonly session: AgentSession;
	private readonly promptAdapter: RuntimePromptAdapter;
	private readonly eventSink: RuntimeSessionEventSink;
	private readonly modelRuntime: RuntimeModelRuntime;
	private readonly stateSource: RuntimeStateSource;
	private readonly conversationDocumentStore: ConversationDocumentStore;
	private readonly projection: RuntimeSessionProjection;
	private readonly documentMutations: ConversationDocumentMutationCoordinator;
	private readonly documentParticipants: readonly RuntimeDocumentParticipant[];
	private readonly extensionHost: RuntimeSessionExtensionHost | undefined;
	private readonly contextController: RuntimeSessionContextController | undefined;
	private readonly contextDeliveryController: RuntimeSessionContextDeliveryController;
	private readonly executionController: RuntimeSessionExecutionController | undefined;
	private readonly configurationController: RuntimeSessionConfigurationController | undefined;
	private readonly toolController: RuntimeSessionToolController | undefined;
	private readonly disposeRuntime: (() => Promise<void>) | undefined;
	private readonly cleanup = new RetryableCleanup();
	private disposed = false;
	private historyMutation = false;

	constructor(
		assembly: KernelRuntimeAssembly,
		eventSink: RuntimeSessionEventSink,
		projection: RuntimeSessionProjection,
	) {
		this.session = assembly.session;
		this.promptAdapter = assembly.promptAdapter;
		this.eventSink = eventSink;
		this.modelRuntime = assembly.modelRuntime;
		this.stateSource = assembly.stateSource;
		this.conversationDocumentStore = assembly.conversationDocumentStore;
		this.projection = projection;
		this.documentMutations = new ConversationDocumentMutationCoordinator({
			readSessionId: () => this.session.id,
			store: this.conversationDocumentStore,
			readProjectedDocument: () => this.projection.readDocument(),
			replaceProjectedDocument: (document) => this.projection.replaceDocument(document),
		});
		this.eventSink.bindDocumentMutationCoordinator(this.documentMutations);
		this.documentParticipants = assembly.documentParticipants ?? [];
		this.extensionHost = assembly.extensionHost;
		this.contextController = assembly.contextController;
		this.contextDeliveryController =
			assembly.contextDeliveryController ?? createContextDeliveryController(assembly.session);
		this.executionController = assembly.executionController;
		this.configurationController = assembly.configurationController;
		this.toolController = assembly.toolController;
		const dispose = assembly.dispose;
		this.disposeRuntime = dispose ? () => dispose.call(assembly) : undefined;
		this.cleanup.add({
			id: "context-compaction",
			phase: 0,
			cleanup: () => this.contextController?.abortCompaction(),
		});
		for (const [index, participant] of this.documentParticipants.entries()) {
			if (participant.dispose) {
				this.cleanup.add({
					id: `document-participant:${index}`,
					phase: 1,
					cleanup: () => participant.dispose?.(),
				});
			}
		}
		this.cleanup.add({ id: "event-sink", phase: 2, cleanup: () => this.eventSink.clear() });
		this.cleanup.add({ id: "kernel-session", phase: 3, cleanup: () => this.session.close() });
		if (this.disposeRuntime) {
			this.cleanup.add({ id: "runtime-assembly", phase: 4, cleanup: this.disposeRuntime });
		}
	}

	get sessionId(): string {
		return this.session.id;
	}

	hasExtension<Input, Output>(token: SessionExtensionEndpointToken<Input, Output>): boolean {
		return this.extensionHost?.hasEndpoint(token) === true;
	}

	invokeExtension<Input, Output>(
		token: SessionExtensionEndpointToken<Input, Output>,
		input: Input,
		signal?: AbortSignal,
	): Promise<Output> {
		if (!this.extensionHost) throw new Error(`Runtime Session extension endpoint is unavailable: ${token.id}`);
		return this.extensionHost.invoke(token, input, signal);
	}

	invokeExtensionSync<Input, Output>(token: SessionExtensionEndpointToken<Input, Output>, input: Input): Output {
		if (!this.extensionHost) throw new Error(`Runtime Session extension endpoint is unavailable: ${token.id}`);
		return this.extensionHost.invokeSync(token, input);
	}

	get sessionPath(): string | undefined {
		return this.eventSink.readIdentity().sessionPath;
	}

	async prompt(request: PromptRequest): Promise<RuntimePromptResult> {
		this.assertOpen();
		const compacting = this.contextController?.readState().isCompacting ?? false;
		if (
			this.historyMutation ||
			(compacting && (this.session.state !== "running" || request.streamingBehavior === undefined))
		) {
			throw sessionBusyError();
		}
		if ((this.session.state === "running" || this.session.state === "cancelling") && !request.streamingBehavior) {
			throw sessionBusyError();
		}
		try {
			const inputRequest = this.promptAdapter.createRequest(request);
			this.assertOpen();
			return await this.session.sendRequest(
				inputRequest,
				{
					...(request.streamingBehavior ? { streamingBehavior: request.streamingBehavior } : {}),
				},
				this.promptAdapter,
			);
		} catch (error) {
			// prompt 在进入 turn 之前失败(模型选择或扩展预处理等)时,
			// 用户消息不会经 TurnPipeline 落盘。补一条 custom entry 保住事实,
			// 历史可查(ADR-0060)。仅空闲态写入,避免与进行中 turn 的追加冲突。
			if (this.session.state === "idle") {
				try {
					await this.appendEntry("prompt_rejected", {
						text: request.text,
						error: error instanceof Error ? error.message : String(error),
					});
				} catch (persistError) {
					console.warn("[runtime-core] failed to persist prompt_rejected entry", persistError);
				}
			}
			throw error;
		}
	}

	async promptWhenAvailable(request: PromptRequest, signal?: AbortSignal): Promise<RuntimePromptResult> {
		this.assertOpen();
		if (this.historyMutation) throw sessionBusyError();
		try {
			const inputRequest = this.promptAdapter.createRequest(request);
			this.assertOpen();
			return await this.session.sendRequestWhenAvailable(inputRequest, this.promptAdapter, signal);
		} catch (error) {
			if (this.session.state === "idle") {
				try {
					await this.appendEntry("prompt_rejected", {
						text: request.text,
						error: error instanceof Error ? error.message : String(error),
					});
				} catch (persistError) {
					console.warn("[runtime-core] failed to persist prompt_rejected entry", persistError);
				}
			}
			throw error;
		}
	}

	async queuePromptIfRunning(request: PromptRequest): Promise<RuntimeQueuePromptIfRunningOutcome> {
		this.assertOpen();
		const compacting = this.contextController?.readState().isCompacting ?? false;
		if (this.historyMutation || (compacting && this.session.state !== "running")) throw sessionBusyError();
		const inputRequest = this.promptAdapter.createRequest(request);
		const result = await this.session.queueRequestIfRunning(
			inputRequest,
			request.streamingBehavior ?? "followUp",
			this.promptAdapter,
		);
		return result.status === "idle"
			? result
			: { status: "queued", behavior: result.behavior, pendingCount: result.pendingCount, id: result.id };
	}

	async continue(): Promise<TurnResult> {
		this.assertOpen();
		if (this.historyMutation || this.contextController?.readState().isCompacting) throw sessionBusyError();
		return this.session.continue();
	}

	async retry(): Promise<TurnResult> {
		this.assertOpen();
		if (this.historyMutation || this.contextController?.readState().isCompacting) throw sessionBusyError();
		return this.session.retry();
	}

	async abort(reason?: string): Promise<void> {
		this.assertOpen();
		await this.session.cancel(reason, { waitMs: ABORT_UNWIND_TIMEOUT_MS });
	}

	subscribe(handler: (event: SessionEvent) => void): () => void {
		this.assertOpen();
		return this.eventSink.subscribe(handler);
	}

	subscribeExecutionObservations(
		handler: (observation: RuntimeSessionExecutionObservation) => Promise<void> | void,
	): () => void {
		this.assertOpen();
		return this.eventSink.subscribeExecutionObservation(handler);
	}

	async getState(): Promise<RuntimeSessionStatus> {
		this.assertOpen();
		return {
			sessionId: this.sessionId,
			state: this.session.state,
			pendingMessageCount: this.session.pendingMessageCount,
			steeringMode: this.session.steeringMode,
			followUpMode: this.session.followUpMode,
			messageCount: this.projection.readMessageCount(),
			contextState: this.eventSink.readContextState(),
		};
	}

	async getMessages(): Promise<readonly Message[]> {
		this.assertOpen();
		return this.projection.readMessages();
	}

	readState(): RuntimeSessionState {
		this.assertOpen();
		const dynamic = this.stateSource.read();
		const identity = this.eventSink.readIdentity();
		return {
			model: this.modelRuntime.readCurrentModel(),
			thinkingLevel: this.modelRuntime.readThinkingLevel(),
			...dynamic,
			contextState: this.eventSink.readContextState(),
			activeToolNames: [...dynamic.activeToolNames],
			isStreaming: this.session.state === "running" || this.session.state === "cancelling",
			messageCount: this.projection.readMessageCount(),
			parentSessionPath: identity.parentSessionPath,
			parentEntryId: identity.parentEntryId,
		};
	}

	readMessages(): readonly Message[] {
		this.assertOpen();
		return this.projection.readMessages();
	}

	readHistory(): readonly HistoryEntry[] {
		this.assertOpen();
		return this.projection.readHistory();
	}

	async navigateForEdit(entryId: string): Promise<{ text: string; cancelled: boolean }> {
		return this.withHistoryMutation("Cannot edit message while the session is streaming", async () => {
			const entry = conversationDocumentEntry(this.projection.readDocument(), entryId);
			const text = extractConversationEntryText(entry);
			const editable =
				entry.type === "custom_message" ||
				(entry.type === "message" && isRecord(entry.message) && entry.message.role === "user");
			await this.executeDocumentCommand({
				type: "active_leaf.set",
				entryId: editable ? entry.parentId : entry.id,
			});
			return { text, cancelled: false };
		});
	}

	async switchBranch(entryId: string): Promise<{ leafId: string }> {
		return this.withHistoryMutation("Cannot switch branch while the session is streaming", async () => {
			const result = await this.executeDocumentCommand({ type: "branch.select", entryId });
			if (!result.leafId) throw new Error(`Entry ${entryId} has no branch leaf`);
			return { leafId: result.leafId };
		});
	}

	async appendBranchSummary(
		parentId: string | null,
		summary: string,
		details?: unknown,
		fromHook?: boolean,
	): Promise<{ entryId: string }> {
		return this.withHistoryMutation("Cannot summarize branch while the session is streaming", async () => {
			const entryId = `branch-summary-${createRuntimeId()}`;
			await this.executeDocumentCommand({
				type: "branch_summary.append",
				entryId,
				parentId,
				summary,
				details,
				fromHook,
				timestamp: new Date().toISOString(),
			});
			return { entryId };
		});
	}

	async deleteMessage(entryId: string): Promise<{ leafId: string | null }> {
		return this.withHistoryMutation("Cannot delete a message while the session is streaming", async () => {
			const result = await this.executeDocumentCommand({ type: "message.delete", entryId });
			return { leafId: result.leafId };
		});
	}

	async replaceLastUserMessage(entryId: string): Promise<{ leafId: string | null }> {
		return this.withHistoryMutation("Cannot replace a message while the session is streaming", async () => {
			const result = await this.executeDocumentCommand({ type: "user_turn.replace", entryId });
			return { leafId: result.leafId };
		});
	}

	async forkSession(entryId: string): Promise<{ path: string; text: string }> {
		return this.withHistoryMutation("Cannot fork while the session is streaming", async () => {
			const result = await this.conversationDocumentStore.fork(this.sessionId, entryId);
			return { path: result.path, text: result.text };
		});
	}

	async setName(name: string): Promise<void> {
		this.assertOpen();
		if (this.historyMutation || this.contextController?.readState().isCompacting) {
			throw new Error("Cannot rename while another session mutation is active");
		}
		this.historyMutation = true;
		try {
			await this.executeDocumentCommand({
				type: "session.name.set",
				name,
			});
		} finally {
			this.historyMutation = false;
		}
	}

	async appendEntry(customType: string, data?: unknown): Promise<void> {
		this.assertOpen();
		await this.executeDocumentCommand({
			type: "custom.append",
			entryId: `entry-${createRuntimeId()}`,
			customType,
			data,
			timestamp: new Date().toISOString(),
		});
	}

	async appendConversationMessage(record: ConversationMessageRecord): Promise<{ readonly entryId: string }> {
		this.assertOpen();
		await this.executeDocumentCommand({ type: "message.append", record });
		return { entryId: record.id };
	}

	async setLabel(entryId: string, label: string | undefined): Promise<void> {
		this.assertOpen();
		await this.executeDocumentCommand({
			type: "entry.label.set",
			entryId: `label-${createRuntimeId()}`,
			targetId: entryId,
			label,
			timestamp: new Date().toISOString(),
		});
	}

	createCoreAssembly(): RuntimeSessionCoreAssembly {
		this.assertOpen();
		const runtimeSession = this;
		const queueController: RuntimeSessionQueueController = {
			readPendingMessageCount: () => this.session.pendingMessageCount,
			readSteeringMode: () => this.session.steeringMode,
			readFollowUpMode: () => this.session.followUpMode,
			readSteeringMessages: () => this.readQueuedTexts("steer"),
			readFollowUpMessages: () => this.readQueuedTexts("followUp"),
			clear: () => {
				const cleared = this.session.clearQueue();
				return {
					steering: cleared.steering.map(readQueuedInputText),
					followUp: cleared.followUps.map(readQueuedInputText),
				};
			},
			readQueueState: () => {
				const snapshot = this.session.listQueue();
				return {
					paused: snapshot.paused,
					// 与 queue.changed 镜像同一口径:内部控制信号不进用户可见队列。
					entries: snapshot.entries
						.filter((entry) => !entry.internal)
						.map((entry) => ({
							id: entry.id,
							behavior: entry.behavior,
							kind: entry.input.operation?.type === "context.compact" ? "context_compaction" : "message",
							displayText: readQueuedInputText(entry.input),
						})),
				};
			},
			readQueueSnapshot: () => this.session.listQueue(),
			restoreQueue: (snapshot) => {
				const parsed = parseQueueSnapshot(snapshot);
				if (parsed) this.session.restoreQueue(parsed);
			},
			removeQueued: (id) => this.session.removeQueued(id),
			reorderQueuedFollowUps: (ids) => this.session.reorderQueuedFollowUps(ids),
			enqueueContextCompaction: (request = {}) =>
				this.session.queueOperation({
					type: "context.compact",
					...(request.customInstructions === undefined ? {} : { customInstructions: request.customInstructions }),
				}),
			sendQueuedNow: async (id) => {
				const result = await this.session.sendQueuedNow(id);
				if (result.status === "started") {
					// turn 结果经事件流回放(turn.completed/failed 自带落盘与广播),这里不阻塞。
					void result.turn.catch((error) => {
						console.warn("[runtime-core] sendQueuedNow turn crashed", error);
					});
					return "started";
				}
				return result.status;
			},
			resumeQueue: async () => {
				void this.session.resumeQueue().catch((error) => {
					console.warn("[runtime-core] resumeQueue turn crashed", error);
				});
			},
		};
		return {
			lifecycle: {
				get sessionId() {
					return runtimeSession.sessionId;
				},
				get agentId() {
					return runtimeSession.eventSink.readIdentity().agentId;
				},
				get sessionPath() {
					return runtimeSession.eventSink.readIdentity().sessionPath;
				},
				get sessionDirectory() {
					return runtimeSession.eventSink.readIdentity().sessionDirectory;
				},
				dispose: () => this.dispose(),
			},
			historyReader: {
				readHistory: () => this.readHistory(),
			},
			historyController: {
				navigateForEdit: (entryId) => this.navigateForEdit(entryId),
				switchBranch: (entryId) => this.switchBranch(entryId),
				appendBranchSummary: (parentId, summary, details, fromHook) =>
					this.appendBranchSummary(parentId, summary, details, fromHook),
				deleteMessage: (entryId) => this.deleteMessage(entryId),
				replaceLastUserMessage: (entryId) => this.replaceLastUserMessage(entryId),
				forkSession: (entryId) => this.forkSession(entryId),
				setName: (name) => this.setName(name),
			},
			modelController: this.modelRuntime,
			modelView: this.modelRuntime,
			workspaceView: {
				readWorkingDirectory: () => this.eventSink.readIdentity().cwd,
			},
			conversationView: {
				readDocument: () => this.projection.readDocument(),
			},
			conversationController: {
				appendMessage: (record) => this.appendConversationMessage(record),
			},
			queueView: queueController,
			queueController,
			contextUsageView: {
				readContextUsage: () => {
					const state = this.stateSource.read();
					return {
						tokens: state.contextTokens ?? null,
						contextWindow: state.contextWindow,
						percent: state.contextPercent,
						...(state.contextComposition ? { composition: state.contextComposition } : {}),
					};
				},
			},
			executionObservationStream: {
				subscribe: (handler) => this.eventSink.subscribeExecutionObservation(handler),
			},
			extensionHost: this.extensionHost,
			contextController: this.contextController,
			contextDeliveryController: this.contextDeliveryController,
			metadataController: {
				appendEntry: (customType, data) => this.appendEntry(customType, data),
				readName: () => this.projection.readDocument().name,
				setName: (name) => this.setName(name),
				setLabel: (entryId, label) => this.setLabel(entryId, label),
			},
			toolController: this.toolController,
			corePorts: {
				turnControl: {
					prompt: async (request) => {
						const result = await this.prompt(request);
						if (result.status === "handled") return { status: "handled" as const };
						if (result.status === "queued") {
							return { status: "queued" as const, pendingCount: result.pendingCount, queueItemId: result.id };
						}
						return {
							status: result.status,
							...(result.status === "failed" ? { error: result.error, turnId: result.turnId } : {}),
							...(result.status === "completed" ? { turnId: result.turnId } : {}),
						};
					},
					promptWhenAvailable: async (request, signal) => {
						const result = await this.promptWhenAvailable(request, signal);
						if (result.status === "handled") return { status: "handled" as const };
						if (result.status === "queued") {
							return { status: "queued" as const, pendingCount: result.pendingCount, queueItemId: result.id };
						}
						return {
							status: result.status,
							...(result.status === "failed" ? { error: result.error, turnId: result.turnId } : {}),
							...(result.status === "completed" ? { turnId: result.turnId } : {}),
						};
					},
					queuePromptIfRunning: async (request) => this.queuePromptIfRunning(request),
					continue: async () => {
						await this.continue();
					},
					retry: async () => {
						await this.retry();
					},
					abort: () => this.abort(),
				},
				eventStream: {
					subscribe: (handler) => this.subscribe(handler),
				},
				stateReader: {
					readState: () => this.readState(),
					readMessages: () => this.readMessages(),
				},
			},
		};
	}

	private readQueuedTexts(behavior: "steer" | "followUp"): readonly string[] {
		const snapshot = this.session.listQueue();
		return snapshot.entries
			.filter((entry) => entry.behavior === behavior)
			.map(({ input }) => readQueuedInputText(input));
	}

	/**
	 * 暴露给宿主组合根的候选 Assembly。缺失能力保持缺失,由上层完整性门禁决定
	 * 是否允许接入 RuntimeHost;这里不使用 no-op 伪造功能。
	 */
	createRuntimeHostAssemblyCandidate(): RuntimeHostSessionAssemblyCandidate {
		const coreAssembly = this.createCoreAssembly();
		return {
			...coreAssembly,
			executionController: this.executionController,
			configurationController: this.configurationController,
		};
	}

	async dispose(): Promise<void> {
		this.disposed = true;
		await this.cleanup.run("Failed to dispose Runtime session");
	}

	async initializeDocumentParticipants(document: ConversationDocument): Promise<void> {
		const context: RuntimeDocumentParticipantContext = {
			appendCustomEntry: async (entry) => {
				await this.executeDocumentCommand({
					type: "custom.append",
					...entry,
				});
			},
		};
		for (const participant of this.documentParticipants) {
			await participant.initialize(document, context);
		}
	}

	private assertOpen(): void {
		if (this.disposed) throw sessionClosedError();
	}

	private async executeDocumentCommand(
		command: ConversationDocumentCommand,
	): Promise<ConversationDocumentCommandResult> {
		const result = await this.documentMutations.execute(command);
		for (const participant of this.documentParticipants) {
			await participant.onDocumentChanged(result.document);
		}
		this.eventSink.refreshContextState();
		return result;
	}

	private async withHistoryMutation<T>(message: string, operation: () => Promise<T>): Promise<T> {
		this.assertOpen();
		if (
			this.historyMutation ||
			this.contextController?.readState().isCompacting ||
			this.session.state === "running" ||
			this.session.state === "cancelling" ||
			this.session.state === "recovery_required"
		) {
			throw new Error(message);
		}
		this.historyMutation = true;
		try {
			return await operation();
		} finally {
			this.historyMutation = false;
		}
	}
}

/**
 * Kernel 驱动的 Runtime Session 后端。
 *
 * 它将 Kernel Session、Conversation Store 与宿主端口组合为稳定的 RuntimeSession。
 */
export class KernelRuntimeSessionBackend<TCreateOptions>
	implements RuntimeSessionBackend<TCreateOptions, RuntimeSession>
{
	private readonly options: KernelRuntimeSessionBackendOptions<TCreateOptions>;

	constructor(options: KernelRuntimeSessionBackendOptions<TCreateOptions>) {
		this.options = options;
	}

	async create(options: TCreateOptions): Promise<RuntimeSession> {
		return this.assemble("create", options);
	}

	async resume(options: TCreateOptions): Promise<RuntimeSession> {
		return this.assemble("resume", options);
	}

	private async assemble(operation: "create" | "resume", options: TCreateOptions): Promise<RuntimeSession> {
		const eventSink = new RuntimeSessionEventSink();
		const assembly = await this.options.runtimeFactory[operation](options, eventSink);
		try {
			const [conversation, document] = await Promise.all([
				assembly.repository.load(assembly.session.id),
				assembly.conversationDocumentStore.readDocument(assembly.session.id),
			]);
			const projection = new RuntimeSessionProjection(conversation, document);
			eventSink.bindProjection(projection);
			eventSink.bindIdentity(assembly.identity);
			eventSink.bindStateSource(assembly.stateSource);
			eventSink.bindDocumentParticipants(assembly.documentParticipants ?? []);
			const runtimeSession = new RuntimeSession(assembly, eventSink, projection);
			await runtimeSession.initializeDocumentParticipants(document);
			eventSink.finishInitialization();
			return runtimeSession;
		} catch (error) {
			try {
				await assembly.session.close();
			} finally {
				await assembly.dispose?.();
			}
			throw error;
		}
	}
}

class RuntimeSessionEventSink implements EventSink {
	private readonly contextState = new SessionContextStateProjection();
	private readonly listeners = new Set<(event: SessionEvent) => void>();
	private readonly executionObservationListeners = new Set<
		(observation: RuntimeSessionExecutionObservation) => Promise<void> | void
	>();
	private readonly initializationEvents: SessionEvent[] = [];
	private documentParticipants: readonly RuntimeDocumentParticipant[] = [];
	private documentMutationCoordinator: ConversationDocumentMutationCoordinator | undefined;
	private identity: RuntimeSessionIdentity = {};
	private projection: RuntimeSessionProjection | undefined;
	private stateSource: RuntimeStateSource | undefined;
	private initializing = true;

	async publish(event: KernelEvent): Promise<void> {
		if (event.type === "execution.observation") {
			await this.notifyExecutionObservationListeners({
				turnId: event.turnId,
				event: event.observation,
				timestamp: event.timestamp,
			});
		}
		if (event.type === "conversation.continued") {
			await this.applyProjectionChange(() =>
				this.projection?.replaceConversation(event.conversation, event.document),
			);
			this.identity = {
				agentId: event.document.identity.agentId ?? this.identity.agentId,
				cwd: event.document.identity.cwd,
				sessionDirectory: event.sessionDirectory ?? this.identity.sessionDirectory,
				sessionPath: event.sessionPath,
				parentSessionPath: event.document.identity.parentSessionPath,
				parentEntryId: event.document.identity.parentEntryId,
			};
			for (const participant of this.documentParticipants) {
				await participant.onDocumentChanged(event.document);
			}
		}
		if (isStoredSessionEvent(event)) {
			if (this.documentMutationCoordinator) {
				await this.documentMutationCoordinator.synchronizeProjection();
			} else {
				this.projection?.apply(event);
			}
			if (isConversationDocumentEntryEvent(event)) {
				const document = this.projection?.readDocument();
				if (document) {
					for (const participant of this.documentParticipants) {
						await participant.onDocumentChanged(document);
					}
				}
			}
			for (const participant of this.documentParticipants) {
				await participant.onSessionEvent?.(event);
			}
		}
		for (const mappedEvent of mapKernelEventToSessionEvents(event)) {
			const mapped = this.withDynamicState(mappedEvent);
			if (this.initializing) {
				this.initializationEvents.push(mapped);
				continue;
			}
			this.notifyListeners(mapped);
			if (mapped.channel !== "assistant") this.refreshContextState(mapped);
		}
		if (isStoredSessionEvent(event) || event.type === "conversation.continued") this.refreshContextState();
	}

	subscribe(handler: (event: SessionEvent) => void): () => void {
		this.refreshContextState();
		this.listeners.add(handler);
		for (const event of this.initializationEvents.splice(0)) {
			try {
				handler(event);
			} catch {
				// Session observers are isolated from initialization recovery events.
			}
		}
		const state = this.contextState.read();
		if (state) {
			try {
				handler({ ...baseSessionEvent(state.sessionId, "runtime-core"), type: "session.context.state", state });
			} catch {
				// An observer must not prevent subscription cleanup or affect the Session.
			}
		}
		return () => this.listeners.delete(handler);
	}

	readContextState(): SessionContextState | undefined {
		return this.contextState.read();
	}

	refreshContextState(event?: SessionEvent): void {
		if (this.initializing || !this.projection || !this.stateSource) return;
		const document = this.projection.readDocument();
		const state = this.contextState.update(
			document.identity.sessionId,
			this.stateSource.read(),
			this.stateSource.readCompactionEligibility?.(document) ?? { status: "unknown" },
			event,
		);
		if (state)
			this.notifyListeners({
				...baseSessionEvent(state.sessionId, "runtime-core"),
				type: "session.context.state",
				state,
			});
	}

	subscribeExecutionObservation(
		handler: (observation: RuntimeSessionExecutionObservation) => Promise<void> | void,
	): () => void {
		this.executionObservationListeners.add(handler);
		return () => this.executionObservationListeners.delete(handler);
	}

	finishInitialization(): void {
		this.initializing = false;
		this.refreshContextState();
	}

	bindProjection(projection: RuntimeSessionProjection): void {
		this.projection = projection;
	}

	bindIdentity(identity: RuntimeSessionIdentity): void {
		this.identity = { ...identity };
	}

	readIdentity(): RuntimeSessionIdentity {
		return this.identity;
	}

	bindStateSource(stateSource: RuntimeStateSource): void {
		this.stateSource = stateSource;
	}

	bindDocumentParticipants(participants: readonly RuntimeDocumentParticipant[]): void {
		this.documentParticipants = participants;
	}

	bindDocumentMutationCoordinator(coordinator: ConversationDocumentMutationCoordinator): void {
		this.documentMutationCoordinator = coordinator;
	}

	clear(): void {
		this.listeners.clear();
		this.executionObservationListeners.clear();
		this.initializationEvents.length = 0;
		this.stateSource = undefined;
		this.documentMutationCoordinator = undefined;
	}

	private async applyProjectionChange(change: () => void): Promise<void> {
		if (this.documentMutationCoordinator) {
			await this.documentMutationCoordinator.applyProjectionChange(change);
			return;
		}
		change();
	}

	private withDynamicState(event: SessionEvent): SessionEvent {
		if (!this.stateSource) return event;
		const state = this.stateSource.read();
		if (event.type === "compaction.end" && event.success) {
			return {
				...event,
				contextPercent: state.contextPercent,
				contextWindow: state.contextWindow,
				...(state.contextTokens !== undefined ? { contextTokens: state.contextTokens } : {}),
			};
		}
		if (event.type !== "usage.update") return event;
		const contextTokens = state.contextTokens ?? event.input + event.output + event.cacheRead + event.cacheWrite;
		return {
			...event,
			contextTokens,
			contextPercent: state.contextWindow > 0 ? (contextTokens / state.contextWindow) * 100 : null,
			contextWindow: state.contextWindow,
			...(state.contextComposition ? { contextComposition: state.contextComposition } : {}),
		};
	}

	private notifyListeners(event: SessionEvent): void {
		for (const listener of this.listeners) {
			try {
				listener(event);
			} catch {
				// Session observers are isolated from turn execution and from each other.
			}
		}
	}

	private async notifyExecutionObservationListeners(observation: RuntimeSessionExecutionObservation): Promise<void> {
		for (const listener of this.executionObservationListeners) {
			try {
				await listener(observation);
			} catch {
				// Execution observers are ordered but cannot change Turn semantics.
			}
		}
	}
}

function isStoredSessionEvent(event: KernelEvent): event is StoredSessionEvent {
	return (
		event.type === "turn.started" ||
		event.type === "turn.continued" ||
		event.type === "message.appended" ||
		event.type === "context.appended" ||
		event.type === "context.recorded" ||
		event.type === "context.compacted" ||
		event.type === "turn.completed" ||
		event.type === "turn.cancelled" ||
		event.type === "turn.failed" ||
		event.type === "turn.transferred"
	);
}

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

/** sidecar 快照来自磁盘,属不可信边界:结构不符则整体丢弃,不让坏数据进 kernel。 */
function parseQueueSnapshot(snapshot: unknown): SessionInputQueueSnapshot | undefined {
	if (typeof snapshot !== "object" || snapshot === null) return undefined;
	const candidate = snapshot as { paused?: unknown; entries?: unknown };
	if (typeof candidate.paused !== "boolean" || !Array.isArray(candidate.entries)) return undefined;
	const entries: SessionInputQueueEntry[] = [];
	for (const entry of candidate.entries) {
		if (typeof entry !== "object" || entry === null) return undefined;
		const { id, behavior, input, internal } = entry as {
			id?: unknown;
			behavior?: unknown;
			input?: unknown;
			internal?: unknown;
		};
		if (typeof id !== "string" || id.length === 0) return undefined;
		if (behavior !== "steer" && behavior !== "followUp") return undefined;
		if (typeof input !== "object" || input === null) return undefined;
		if (internal !== undefined && typeof internal !== "boolean") return undefined;
		const queuedInput = input as Record<string, unknown>;
		if (queuedInput.operation !== undefined) {
			if (behavior !== "followUp" || !isRecord(queuedInput.operation)) return undefined;
			const operation = queuedInput.operation;
			if (operation.type !== "context.compact") return undefined;
			if (operation.customInstructions !== undefined && typeof operation.customInstructions !== "string") {
				return undefined;
			}
			if (
				queuedInput.message !== undefined ||
				queuedInput.request !== undefined ||
				queuedInput.context !== undefined
			) {
				return undefined;
			}
		}
		entries.push({
			id,
			behavior,
			input: input as SessionInputQueueEntry["input"],
			...(internal ? { internal: true } : {}),
		});
	}
	return { paused: candidate.paused, entries };
}

function readQueuedMessageText(message: SessionInput["message"]): string {
	if (typeof message.content === "string") return message.content;
	return message.content
		.filter(
			(part): part is Extract<(typeof message.content)[number], { readonly type: "text" }> => part.type === "text",
		)
		.map((part) => part.text)
		.join("");
}

function readQueuedInputText(input: QueuedSessionInput): string {
	return input.message
		? readQueuedMessageText(input.message)
		: (input.request?.displayText ?? (input.operation?.type === "context.compact" ? "context.compact" : ""));
}

function createContextDeliveryController(session: AgentSession): RuntimeSessionContextDeliveryController {
	return {
		deliver: async (records, mode) => {
			if (mode === "record") {
				await session.recordContext(records);
				return;
			}
			if (mode === "nextTurn") {
				session.queueNextTurnContext(records);
				return;
			}
			if (mode === "triggerTurn") {
				await session.requestContinuation(records);
				return;
			}
			session.queueContext(mode, records);
		},
	};
}