repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/klaus/src/coordinator.ts

Raw
File outline
import { join } from "node:path";
import {
	type Api,
	type AssistantMessage,
	type AssistantMessageEventStream,
	type Context,
	calculateCost,
	createAssistantMessageEventStream,
	type Model,
	type SimpleStreamOptions,
} from "@earendil-works/pi-ai";
import { type KlausQueryHandle, startSdkQuery } from "./agent-sdk.js";
import {
	FileSessionStore,
	type KlausSessionStore,
	loadCheckpoints,
	MemorySessionStore,
	StagingSessionStore,
	saveCheckpoint,
} from "./cache.js";
import { dbg } from "./debug.js";
import {
	contextFingerprint,
	createAssistant,
	isKlausModelId,
	type KlausContentEvent,
	type KlausQueryCallbacks,
	type KlausRequest,
	MODEL_SELECTORS,
	modelFacingContent,
	requiredConstrainedTool,
	toKlausTools,
} from "./protocol.js";
import { replayImages, replayPrompt } from "./replay.js";
import { rewriteSubscriptionPrompt } from "./subscription-prompt.js";
import type { PiToolResult } from "./tool-bridge.js";

interface ActiveQuery {
	id: symbol;
	sessionId?: string;
	handle?: KlausQueryHandle;
	sink?: PiSink;
	toolCallIds: Set<string>;
	tools: KlausRequest["tools"];
	closed: boolean;
	closePromise?: Promise<void>;
	timer?: ReturnType<typeof setTimeout>;
	idleLease?: ReturnType<typeof setTimeout>;
	abort?: () => void;
	signal?: AbortSignal;
	secondary: boolean;
	committable: boolean;
	modelId: string;
	cwd: string;
	thinking: SimpleStreamOptions["reasoning"];
	headers: SimpleStreamOptions["headers"];
	metadata?: Record<string, string>;
	emittedContent: boolean;
	context: Context;
	store: KlausSessionStore;
	staging: StagingSessionStore;
}

interface CompletedQuery {
	sdkSessionId: string;
	fingerprint: string;
	position?: string;
	piLeafId?: string;
	messageCount: number;
	protocol: 1;
	store: KlausSessionStore;
}

interface SessionScope {
	id: string;
	persisted: boolean;
	dir: string;
}

type ResolveOAuth = (modelId: string) => Promise<string>;
type CurrentCwd = () => string;
type CurrentSession = () => SessionScope | undefined;
type Warn = (message: string) => void;

class PiSink {
	readonly stream = createAssistantMessageEventStream();
	readonly output: AssistantMessage;
	private indices = new Map<number, number>();
	private toolJson = new Map<number, string>();
	private finished = false;

	constructor(private readonly model: Model<Api>) {
		dbg?.("coordinator.sink.create", {
			provider: model.provider,
			api: model.api,
			modelId: model.id,
		});
		this.output = createAssistant(model);
		this.stream.push({ type: "start", partial: this.output });
	}

	content(event: KlausContentEvent): void {
		dbg?.("coordinator.sink.content", {
			type: event.type,
			index: event.index,
			length:
				"delta" in event
					? event.delta.length
					: "text" in event
						? event.text.length
						: "thinking" in event
							? event.thinking.length
							: undefined,
			name: "name" in event ? event.name : undefined,
		});
		if (this.finished) return;
		switch (event.type) {
			case "text-start": {
				const index = this.output.content.length;
				this.indices.set(event.index, index);
				this.output.content.push({ type: "text", text: "" });
				this.stream.push({
					type: "text_start",
					contentIndex: index,
					partial: this.output,
				});
				break;
			}
			case "text-delta": {
				const index = this.indices.get(event.index);
				const block =
					index === undefined ? undefined : this.output.content[index];
				if (index === undefined || block?.type !== "text") return;
				block.text += event.delta;
				this.stream.push({
					type: "text_delta",
					contentIndex: index,
					delta: event.delta,
					partial: this.output,
				});
				break;
			}
			case "text-end": {
				const index = this.indices.get(event.index);
				if (index === undefined) return;
				this.stream.push({
					type: "text_end",
					contentIndex: index,
					content: event.text,
					partial: this.output,
				});
				break;
			}
			case "thinking-start": {
				const index = this.output.content.length;
				this.indices.set(event.index, index);
				this.output.content.push({ type: "thinking", thinking: "" });
				this.stream.push({
					type: "thinking_start",
					contentIndex: index,
					partial: this.output,
				});
				break;
			}
			case "thinking-delta": {
				const index = this.indices.get(event.index);
				const block =
					index === undefined ? undefined : this.output.content[index];
				if (index === undefined || block?.type !== "thinking") return;
				block.thinking += event.delta;
				this.stream.push({
					type: "thinking_delta",
					contentIndex: index,
					delta: event.delta,
					partial: this.output,
				});
				break;
			}
			case "thinking-end": {
				const index = this.indices.get(event.index);
				const block =
					index === undefined ? undefined : this.output.content[index];
				if (index === undefined || block?.type !== "thinking") return;
				block.thinkingSignature = event.signature;
				block.redacted = event.redacted;
				this.stream.push({
					type: "thinking_end",
					contentIndex: index,
					content: event.thinking,
					partial: this.output,
				});
				break;
			}
			case "tool-start": {
				const index = this.output.content.length;
				this.indices.set(event.index, index);
				this.toolJson.set(event.index, "");
				this.output.content.push({
					type: "toolCall",
					id: event.id,
					name: event.name,
					arguments: {},
				});
				this.stream.push({
					type: "toolcall_start",
					contentIndex: index,
					partial: this.output,
				});
				break;
			}
			case "tool-delta": {
				const index = this.indices.get(event.index);
				if (index === undefined) return;
				this.toolJson.set(
					event.index,
					`${this.toolJson.get(event.index) ?? ""}${event.delta}`,
				);
				this.stream.push({
					type: "toolcall_delta",
					contentIndex: index,
					delta: event.delta,
					partial: this.output,
				});
				break;
			}
			case "tool-end": {
				const index = this.indices.get(event.index);
				const block =
					index === undefined ? undefined : this.output.content[index];
				if (index === undefined || block?.type !== "toolCall") return;
				block.arguments = event.arguments;
				this.stream.push({
					type: "toolcall_end",
					contentIndex: index,
					toolCall: block,
					partial: this.output,
				});
				break;
			}
		}
	}

	toolUse(): void {
		dbg?.("coordinator.sink.toolUse", { finished: this.finished });
		if (this.finished) return;
		this.finished = true;
		this.output.stopReason = "toolUse";
		this.stream.push({ type: "done", reason: "toolUse", message: this.output });
		this.stream.end();
	}

	done(
		usage: {
			input: number;
			output: number;
			cacheRead: number;
			cacheWrite: number;
		},
		responseId?: string,
		responseModel?: string,
		stopReason: "stop" | "length" = "stop",
	): void {
		dbg?.("coordinator.sink.done", {
			finished: this.finished,
			usage,
			responseId,
			responseModel,
			stopReason,
		});
		if (this.finished) return;
		this.finished = true;
		Object.assign(this.output.usage, usage);
		this.output.usage.totalTokens =
			usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
		const fallbackCost =
			this.model.compat &&
			"allowedFallbackModels" in this.model.compat &&
			responseModel !== this.model.id
				? this.model.compat.allowedFallbackModels?.find(
						(fallback) =>
							fallback.provider === "anthropic" &&
							fallback.model === responseModel,
					)?.cost
				: undefined;
		calculateCost(
			fallbackCost && responseModel
				? { ...this.model, id: responseModel, cost: fallbackCost }
				: this.model,
			this.output.usage,
		);
		this.output.responseId = responseId;
		this.output.responseModel = responseModel;
		this.output.stopReason = stopReason;
		this.stream.push({
			type: "done",
			reason: stopReason,
			message: this.output,
		});
		this.stream.end();
	}

	error(error: unknown, aborted = false): void {
		dbg?.("coordinator.sink.error", {
			finished: this.finished,
			aborted,
			error: error instanceof Error ? error.message : String(error),
		});
		if (this.finished) return;
		this.finished = true;
		this.output.stopReason = aborted ? "aborted" : "error";
		this.output.errorMessage =
			error instanceof Error ? error.message : String(error);
		this.stream.push({
			type: "error",
			reason: this.output.stopReason,
			error: this.output,
		});
		this.stream.end();
	}
}

export class QueryCoordinator {
	private readonly bySession = new Map<string, Set<ActiveQuery>>();
	private readonly anonymous = new Set<ActiveQuery>();
	private readonly completed = new Map<string, CompletedQuery>();
	private readonly memoryStores = new Map<string, MemorySessionStore>();
	private readonly diskStores = new Map<string, FileSessionStore>();
	private readonly pendingCheckpoints = new Map<string, CompletedQuery>();
	private cacheReady: Promise<void> = Promise.resolve();

	constructor(
		private readonly resolveOAuth: ResolveOAuth,
		private readonly currentCwd: CurrentCwd,
		private readonly currentSession: CurrentSession = () => undefined,
		private readonly warn: Warn = () => undefined,
	) {
		dbg?.("coordinator.create");
	}

	stream(
		model: Model<Api>,
		context: Context,
		options: SimpleStreamOptions = {},
	): AssistantMessageEventStream {
		dbg?.("coordinator.stream", {
			modelId: model.id,
			messageCount: context.messages.length,
			toolCount: context.tools?.length ?? 0,
			sessionId: options.sessionId,
			reasoning: options.reasoning,
		});
		const sink = new PiSink(model);
		void this.invoke(sink, model, context, options);
		return sink.stream;
	}

	preparePrimaryCache(scope: SessionScope): Promise<void> {
		dbg?.("coordinator.preparePrimaryCache", {
			id: scope.id,
			persisted: scope.persisted,
			dir: scope.dir,
		});
		if (!scope.persisted) {
			this.cacheReady = Promise.resolve();
			return this.cacheReady;
		}
		const store = new FileSessionStore(join(scope.dir, ".klaus", "sessions"));
		this.diskStores.set(scope.id, store);
		this.cacheReady = store.prepare();
		return this.cacheReady;
	}

	async persistCheckpoint(sessionId: string, piLeafId: string): Promise<void> {
		dbg?.("coordinator.persistCheckpoint.start", { sessionId, piLeafId });
		const checkpoint = this.pendingCheckpoints.get(sessionId);
		const root = this.checkpointRoot(sessionId);
		if (!checkpoint || !root) {
			dbg?.("coordinator.persistCheckpoint.skip", {
				sessionId,
				hasCheckpoint: Boolean(checkpoint),
				hasRoot: Boolean(root),
			});
			return;
		}
		checkpoint.piLeafId = piLeafId;
		await saveCheckpoint(root, sessionId, checkpoint);
		this.pendingCheckpoints.delete(sessionId);
		dbg?.("coordinator.persistCheckpoint.end", { sessionId, piLeafId });
	}

	async closeAll(reason: string): Promise<void> {
		dbg?.("coordinator.closeAll.start", { reason });
		const states = [
			...this.anonymous,
			...[...this.bySession.values()].flatMap((states) => [...states]),
		];
		await Promise.all(states.map((state) => this.closeState(state, reason)));
		this.completed.clear();
		this.memoryStores.clear();
		this.diskStores.clear();
		this.pendingCheckpoints.clear();
		dbg?.("coordinator.closeAll.end", { reason, stateCount: states.length });
	}

	private async invoke(
		sink: PiSink,
		model: Model<Api>,
		context: Context,
		options: SimpleStreamOptions,
	): Promise<void> {
		dbg?.("coordinator.invoke.start", {
			modelId: model.id,
			sessionId: options.sessionId,
			messageCount: context.messages.length,
		});
		try {
			if (!isKlausModelId(model.id))
				throw new Error(`Unsupported Klaus model ${model.id}.`);
			const required = requiredConstrainedTool(context.tools);
			if (required)
				throw new Error(
					`Tool ${required} requires constrained sampling, which Klaus cannot provide.`,
				);

			const batch = recentToolResults(context);
			dbg?.("coordinator.invoke.batch", {
				resultCount: batch.results.length,
				userAfter: batch.userAfter,
			});
			const continuation = this.findContinuation(
				options.sessionId,
				batch.results,
			);
			const tools = toKlausTools(context.tools);
			dbg?.("coordinator.invoke.continuation", {
				found: Boolean(continuation),
				hasHandle: Boolean(continuation?.handle),
			});
			if (continuation?.handle) {
				const incompatible =
					batch.userAfter ||
					continuation.handle.bridge.hasSchemaChange(tools) ||
					continuation.modelId !== model.id ||
					continuation.thinking !== options.reasoning ||
					JSON.stringify(continuation.headers ?? {}) !==
						JSON.stringify(options.headers ?? {}) ||
					options.onPayload !== undefined;
				dbg?.("coordinator.invoke.compatibility", { incompatible });
				if (incompatible) {
					await this.closeState(
						continuation,
						"Pi request changed across a tool boundary; replaying canonically.",
					);
				} else {
					continuation.sink = sink;
					continuation.context = context;
					if (continuation.idleLease) clearTimeout(continuation.idleLease);
					continuation.idleLease = undefined;
					this.replaceAbort(continuation, options.signal);
					this.armTimeout(continuation, options.timeoutMs);
					if (options.onResponse && continuation.metadata) {
						await options.onResponse(
							{ status: 200, headers: continuation.metadata },
							model,
						);
					}
					for (const result of batch.results) {
						await continuation.handle.bridge.waitForPending(
							[result.id],
							options.signal,
						);
						if (!continuation.handle.bridge.settle(result)) {
							throw new Error(`Unknown Klaus tool result ${result.id}.`);
						}
					}
					return;
				}
			}
			await this.start(sink, model, context, options, tools);
		} catch (error) {
			dbg?.("coordinator.invoke.error", {
				error: error instanceof Error ? error.message : String(error),
			});
			sink.error(error, options.signal?.aborted);
		}
	}

	private async start(
		sink: PiSink,
		model: Model<Api>,
		context: Context,
		options: SimpleStreamOptions,
		tools: KlausRequest["tools"],
		forceCold = false,
	): Promise<void> {
		dbg?.("coordinator.start.begin", {
			modelId: model.id,
			sessionId: options.sessionId,
			forceCold,
			messageCount: context.messages.length,
			toolNames: tools.map((tool) => tool.name),
		});
		await this.cacheReady;
		dbg?.("coordinator.start.cacheReady");
		const store = this.storeFor(options.sessionId);
		const cwd = this.currentCwd();
		const identity = `${model.id}\0${cwd}`;
		const candidates: CompletedQuery[] = [];
		const memory =
			!forceCold && options.sessionId
				? this.completed.get(options.sessionId)
				: undefined;
		if (memory) candidates.push(memory);
		dbg?.("coordinator.start.memoryCandidate", { found: Boolean(memory) });
		const checkpointRoot = this.checkpointRoot(options.sessionId);
		if (!forceCold && options.sessionId && checkpointRoot) {
			try {
				for (const checkpoint of await loadCheckpoints(
					checkpointRoot,
					options.sessionId,
				)) {
					if (
						!candidates.some(
							(item) => item.fingerprint === checkpoint.fingerprint,
						)
					) {
						candidates.push({ ...checkpoint, store });
					}
				}
			} catch (error) {
				dbg?.("coordinator.start.checkpointLoadError", {
					error: error instanceof Error ? error.message : String(error),
				});
				candidates.length = memory ? 1 : 0;
			}
		}
		dbg?.("coordinator.start.candidates", { count: candidates.length });
		const completed = candidates.toReversed().find(
			(checkpoint) =>
				checkpoint.messageCount < context.messages.length &&
				checkpoint.fingerprint ===
					contextFingerprint(
						{
							systemPrompt: context.systemPrompt,
							messages: context.messages.slice(0, checkpoint.messageCount),
							tools: context.tools,
						},
						identity,
					),
		);
		dbg?.("coordinator.start.completed", {
			found: Boolean(completed),
			messageCount: completed?.messageCount,
		});
		const deltaContext: Context = {
			systemPrompt: context.systemPrompt,
			messages: completed
				? context.messages.slice(completed.messageCount)
				: context.messages,
			tools: context.tools,
		};
		const linearResume =
			completed !== undefined &&
			deltaContext.messages.length === 1 &&
			isTextUser(deltaContext.messages[0]);
		const canResume = completed !== undefined;
		dbg?.("coordinator.start.resumePlan", {
			linearResume,
			canResume,
			deltaMessageCount: deltaContext.messages.length,
		});
		const staging = new StagingSessionStore(completed?.store ?? store);
		const request: KlausRequest = {
			modelId: model.id as keyof typeof MODEL_SELECTORS,
			selector: MODEL_SELECTORS[model.id as keyof typeof MODEL_SELECTORS],
			systemPrompt: context.systemPrompt ?? "",
			prompt: linearResume
				? finalUserPrompt(deltaContext)
				: replayPrompt(deltaContext),
			images: replayImages(deltaContext),
			tools,
			thinking: options.reasoning,
			thinkingBudget: thinkingBudget(options),
			cwd,
			sessionId: options.sessionId,
			headers: options.headers ?? {},
			env: options.env ?? {},
			timeoutMs: options.timeoutMs,
			sessionStore: staging,
			resume: canResume ? completed?.sdkSessionId : undefined,
			resumeAt: canResume && !linearResume ? completed?.position : undefined,
			forkSession: canResume && !linearResume,
		};
		dbg?.("coordinator.start.request", {
			modelId: request.modelId,
			selector: request.selector,
			promptLength: request.prompt.length,
			systemPromptLength: request.systemPrompt.length,
			imageCount: request.images?.length ?? 0,
			toolNames: request.tools.map((tool) => tool.name),
			thinking: request.thinking,
			thinkingBudget: request.thinkingBudget,
			cwd: request.cwd,
			resume: Boolean(request.resume),
			resumeAt: Boolean(request.resumeAt),
			forkSession: request.forkSession,
		});
		const payloadRequest: KlausRequest = { ...request };
		delete payloadRequest.sessionStore;
		delete payloadRequest.resume;
		delete payloadRequest.resumeAt;
		delete payloadRequest.forkSession;
		dbg?.("coordinator.start.payloadHook", {
			enabled: options.onPayload !== undefined,
		});
		const hookPayload = options.onPayload
			? await options.onPayload(payloadRequest, model)
			: undefined;
		const transformedPayload =
			hookPayload === undefined ? payloadRequest : hookPayload;
		const transformed = isRequest(transformedPayload)
			? {
					...transformedPayload,
					sessionStore: request.sessionStore,
					resume: request.resume,
					resumeAt: request.resumeAt,
					forkSession: request.forkSession,
				}
			: transformedPayload;
		dbg?.("coordinator.start.payloadTransformed", {
			transformed: hookPayload !== undefined,
			valid: isRequest(transformed),
		});
		if (!isRequest(transformed))
			throw new Error("Klaus onPayload returned an invalid request.");
		if (
			transformed.resume &&
			(transformed.modelId !== request.modelId ||
				transformed.selector !== request.selector ||
				transformed.systemPrompt !== request.systemPrompt ||
				transformed.cwd !== request.cwd ||
				JSON.stringify(transformed.tools) !== JSON.stringify(request.tools))
		) {
			transformed.resume = undefined;
			transformed.resumeAt = undefined;
			transformed.forkSession = undefined;
			transformed.prompt = replayPrompt(context);
			transformed.images = replayImages(context);
		}
		const scope = this.currentSession();
		dbg?.("coordinator.start.scope", {
			sessionId: scope?.id,
			persisted: scope?.persisted,
			dir: scope?.dir,
		});
		const state: ActiveQuery = {
			id: Symbol("klaus-query"),
			sessionId: options.sessionId,
			sink,
			toolCallIds: new Set(),
			tools: transformed.tools,
			closed: false,
			secondary: Boolean(options.sessionId && options.sessionId !== scope?.id),
			committable: true,
			modelId: model.id,
			cwd,
			thinking: options.reasoning,
			headers: options.headers,
			emittedContent: false,
			context,
			store: completed?.store ?? store,
			staging,
		};
		this.addState(state);
		dbg?.("coordinator.start.stateAdded", {
			sessionId: state.sessionId,
			secondary: state.secondary,
			committable: state.committable,
		});
		this.armTimeout(state, transformed.timeoutMs);
		this.replaceAbort(state, options.signal);
		if (options.signal?.aborted) {
			await this.closeState(state, "Pi aborted the Klaus query.", true);
			return;
		}
		const callbacks: KlausQueryCallbacks = {
			onReady: async (metadata) => {
				dbg?.("coordinator.callback.ready", metadata);
				if (state.closed) return;
				state.metadata = metadata;
				await options.onResponse?.({ status: 200, headers: metadata }, model);
			},
			onActivity: () => {
				dbg?.("coordinator.callback.activity", { closed: state.closed });
				this.touchState(state, transformed.timeoutMs);
			},
			onContent: (event) => {
				dbg?.("coordinator.callback.content", {
					type: event.type,
					index: event.index,
					name: "name" in event ? event.name : undefined,
				});
				if (state.closed) return;
				state.emittedContent = true;
				if (event.type === "tool-start") state.toolCallIds.add(event.id);
				state.sink?.content(event);
			},
			onToolBoundary: () => {
				dbg?.("coordinator.callback.toolBoundary", {
					closed: state.closed,
					sessionId: state.sessionId,
					secondary: state.secondary,
				});
				if (state.closed) return;
				if (!state.sessionId) {
					state.sink?.error(
						new Error("Klaus cannot continue a sessionless tool call."),
					);
					void this.closeState(
						state,
						"Sessionless tool continuation is unsupported.",
					);
					return;
				}
				if (state.timer) clearTimeout(state.timer);
				state.timer = undefined;
				state.sink?.toolUse();
				state.sink = undefined;
				if (state.secondary) {
					state.idleLease = setTimeout(
						() =>
							void this.closeState(
								state,
								"Klaus secondary query idle lease expired.",
							),
						15 * 60_000,
					);
				}
			},
			onResult: (result) => {
				dbg?.("coordinator.callback.result", {
					...result,
					closed: state.closed,
				});
				if (state.closed) return;
				state.sink?.done(
					result.usage,
					result.responseId,
					result.responseModel,
					result.stopReason,
				);
				void (async () => {
					if (
						state.committable &&
						state.sessionId &&
						result.sdkSessionId &&
						state.sink
					) {
						await state.staging.commit();
						const completed: CompletedQuery = {
							sdkSessionId: result.sdkSessionId,
							position: result.position,
							messageCount: state.context.messages.length + 1,
							protocol: 1,
							fingerprint: contextFingerprint(
								{
									systemPrompt: state.context.systemPrompt,
									messages: [...state.context.messages, state.sink.output],
									tools: state.context.tools,
								},
								`${state.modelId}\0${state.cwd}`,
							),
							store: state.store,
						};
						this.completed.set(state.sessionId, completed);
						if (this.checkpointRoot(state.sessionId)) {
							this.pendingCheckpoints.set(state.sessionId, completed);
						}
					}
					await this.closeState(state, "Klaus query completed.");
				})().catch((error) => {
					state.sink?.error(error);
					void this.closeState(state, "Klaus checkpoint failed.");
				});
			},
			onError: (error) => {
				dbg?.("coordinator.callback.error", {
					error: error.message,
					closed: state.closed,
					resume: Boolean(transformed.resume),
					emittedContent: state.emittedContent,
				});
				if (state.closed) return;
				if (transformed.resume && !state.emittedContent && state.sink) {
					const retrySink = state.sink;
					state.sink = undefined;
					if (state.sessionId) {
						this.completed.delete(state.sessionId);
						this.pendingCheckpoints.delete(state.sessionId);
					}
					void (async () => {
						await this.closeState(
							state,
							"Klaus resume failed; replaying canonically.",
						);
						await this.start(retrySink, model, context, options, tools, true);
					})().catch((retryError) => retrySink.error(retryError));
					return;
				}
				state.sink?.error(error);
				void this.closeState(state, error.message);
			},
		};
		try {
			dbg?.("coordinator.oauth.resolve.start", { modelId: model.id });
			const oauth = await this.resolveOAuth(model.id);
			dbg?.("coordinator.oauth.resolve.end", {
				modelId: model.id,
				tokenLength: oauth.length,
			});
			if (state.closed) return;
			dbg?.("coordinator.sdk.start");
			const outgoing = rewriteSubscriptionPrompt(transformed, this.warn);
			const handle = await startSdkQuery(outgoing, oauth, callbacks);
			dbg?.("coordinator.sdk.started");
			if (state.closed) {
				await handle.close("Klaus query closed during startup.");
				return;
			}
			state.handle = handle;
			dbg?.("coordinator.handle.attached");
		} catch (error) {
			dbg?.("coordinator.start.error", {
				error: error instanceof Error ? error.message : String(error),
			});
			state.sink?.error(error, options.signal?.aborted);
			await this.closeState(state, "Klaus query startup failed.");
		}
	}

	private findContinuation(
		sessionId: string | undefined,
		results: PiToolResult[],
	): ActiveQuery | undefined {
		dbg?.("coordinator.findContinuation", {
			sessionId,
			resultIds: results.map((result) => result.id),
		});
		if (!sessionId || results.length === 0) return undefined;
		return [...(this.bySession.get(sessionId) ?? [])].find(
			(state) =>
				!state.closed &&
				results.every((result) => state.toolCallIds.has(result.id)),
		);
	}

	private addState(state: ActiveQuery): void {
		dbg?.("coordinator.addState", { sessionId: state.sessionId });
		if (!state.sessionId) {
			this.anonymous.add(state);
			return;
		}
		const states = this.bySession.get(state.sessionId) ?? new Set();
		if ([...states].some((existing) => !existing.closed)) {
			state.committable = false;
			for (const existing of states) existing.committable = false;
		}
		states.add(state);
		this.bySession.set(state.sessionId, states);
	}

	private replaceAbort(
		state: ActiveQuery,
		signal: AbortSignal | undefined,
	): void {
		dbg?.("coordinator.replaceAbort", {
			hadSignal: Boolean(state.signal),
			hasSignal: Boolean(signal),
			aborted: signal?.aborted,
		});
		if (state.signal && state.abort) {
			state.signal.removeEventListener("abort", state.abort);
		}
		state.signal = signal;
		state.abort = signal
			? () => void this.closeState(state, "Pi aborted the Klaus query.", true)
			: undefined;
		if (signal && state.abort) {
			signal.addEventListener("abort", state.abort, { once: true });
		}
	}

	private touchState(state: ActiveQuery, timeoutMs: number | undefined): void {
		dbg?.("coordinator.touchState", {
			sessionId: state.sessionId,
			timeoutMs,
			hasIdleLease: Boolean(state.idleLease),
		});
		this.armTimeout(state, timeoutMs);
		if (!state.idleLease) return;
		clearTimeout(state.idleLease);
		state.idleLease = setTimeout(
			() =>
				void this.closeState(
					state,
					"Klaus secondary query idle lease expired.",
				),
			15 * 60_000,
		);
	}

	private checkpointRoot(sessionId: string | undefined): string | undefined {
		const scope = this.currentSession();
		dbg?.("coordinator.checkpointRoot", {
			sessionId,
			scopeId: scope?.id,
			persisted: scope?.persisted,
		});
		return sessionId && scope?.id === sessionId && scope.persisted
			? join(scope.dir, ".klaus", "checkpoints")
			: undefined;
	}

	private storeFor(sessionId: string | undefined): KlausSessionStore {
		dbg?.("coordinator.storeFor", { sessionId });
		if (!sessionId) return new MemorySessionStore();
		const scope = this.currentSession();
		if (scope?.id === sessionId && scope.persisted) {
			const existing = this.diskStores.get(sessionId);
			if (existing) return existing;
			const store = new FileSessionStore(join(scope.dir, ".klaus", "sessions"));
			this.diskStores.set(sessionId, store);
			return store;
		}
		const existing = this.memoryStores.get(sessionId);
		if (existing) return existing;
		const store = new MemorySessionStore();
		this.memoryStores.set(sessionId, store);
		return store;
	}

	private armTimeout(state: ActiveQuery, timeoutMs: number | undefined): void {
		dbg?.("coordinator.armTimeout", {
			sessionId: state.sessionId,
			timeoutMs,
			closed: state.closed,
			hasSink: Boolean(state.sink),
		});
		if (state.timer) clearTimeout(state.timer);
		if (!timeoutMs || state.closed || !state.sink) return;
		state.timer = setTimeout(() => {
			state.sink?.error(
				new Error("Klaus timed out waiting for Claude activity."),
			);
			void this.closeState(state, "Klaus activity timeout.");
		}, timeoutMs);
	}

	private async closeState(
		state: ActiveQuery,
		reason: string,
		aborted = false,
	): Promise<void> {
		dbg?.("coordinator.closeState.start", {
			sessionId: state.sessionId,
			reason,
			aborted,
			alreadyClosed: state.closed,
			hasHandle: Boolean(state.handle),
		});
		if (state.closePromise) return state.closePromise;
		state.closed = true;
		state.closePromise = (async () => {
			if (state.timer) clearTimeout(state.timer);
			if (state.idleLease) clearTimeout(state.idleLease);
			if (state.signal && state.abort) {
				state.signal.removeEventListener("abort", state.abort);
			}
			state.sink?.error(new Error(reason), aborted);
			if (state.handle) await state.handle.close(reason);
			if (state.sessionId) {
				const states = this.bySession.get(state.sessionId);
				states?.delete(state);
				if (states?.size === 0) this.bySession.delete(state.sessionId);
			} else {
				this.anonymous.delete(state);
			}
			dbg?.("coordinator.closeState.end", {
				sessionId: state.sessionId,
				reason,
			});
		})();
		return state.closePromise;
	}
}

function thinkingBudget(options: SimpleStreamOptions): number | undefined {
	dbg?.("coordinator.thinkingBudget", { reasoning: options.reasoning });
	switch (options.reasoning) {
		case "minimal":
			return options.thinkingBudgets?.minimal;
		case "low":
			return options.thinkingBudgets?.low;
		case "medium":
			return options.thinkingBudgets?.medium;
		case "high":
		case "xhigh":
		case "max":
			return options.thinkingBudgets?.high;
		default:
			return undefined;
	}
}

function isTextUser(message: Context["messages"][number] | undefined): boolean {
	return (
		message?.role === "user" &&
		(typeof message.content === "string" ||
			message.content.every((item) => item.type === "text"))
	);
}

function finalUserPrompt(context: Context): string {
	dbg?.("coordinator.finalUserPrompt", {
		messageCount: context.messages.length,
	});
	const message = context.messages.at(-1);
	if (message?.role !== "user") return replayPrompt(context);
	return typeof message.content === "string"
		? message.content
		: message.content
				.filter((item) => item.type === "text")
				.map((item) => item.text)
				.join("\n");
}

function recentToolResults(context: Context): {
	results: PiToolResult[];
	userAfter: boolean;
} {
	dbg?.("coordinator.recentToolResults.start", {
		messageCount: context.messages.length,
	});
	const results: PiToolResult[] = [];
	let userAfter = false;
	for (let index = context.messages.length - 1; index >= 0; index -= 1) {
		const message = context.messages[index];
		if (message.role === "assistant") break;
		if (message.role === "user") {
			userAfter = true;
			continue;
		}
		results.unshift({
			id: message.toolCallId,
			content: modelFacingContent(message.content),
			isError: message.isError,
		});
	}
	dbg?.("coordinator.recentToolResults.end", {
		resultIds: results.map((result) => result.id),
		userAfter,
	});
	return { results, userAfter };
}

function isRequest(value: unknown): value is KlausRequest {
	dbg?.("coordinator.isRequest", {
		type: typeof value,
		isArray: Array.isArray(value),
	});
	if (typeof value !== "object" || value === null || Array.isArray(value))
		return false;
	const request = value as Partial<KlausRequest>;
	return (
		typeof request.modelId === "string" &&
		isKlausModelId(request.modelId) &&
		typeof request.selector === "string" &&
		typeof request.systemPrompt === "string" &&
		typeof request.prompt === "string" &&
		(request.images === undefined ||
			(Array.isArray(request.images) &&
				request.images.every(
					(image) =>
						typeof image === "object" &&
						image !== null &&
						typeof image.data === "string" &&
						typeof image.mimeType === "string",
				))) &&
		(request.thinking === undefined ||
			["minimal", "low", "medium", "high", "xhigh", "max"].includes(
				request.thinking,
			)) &&
		(request.thinkingBudget === undefined ||
			(Number.isInteger(request.thinkingBudget) &&
				request.thinkingBudget > 0)) &&
		(request.timeoutMs === undefined ||
			(Number.isFinite(request.timeoutMs) && request.timeoutMs >= 0)) &&
		(request.sessionId === undefined ||
			typeof request.sessionId === "string") &&
		Array.isArray(request.tools) &&
		request.tools.every(
			(tool) =>
				typeof tool === "object" &&
				tool !== null &&
				typeof tool.name === "string" &&
				typeof tool.description === "string" &&
				typeof tool.inputSchema === "object" &&
				tool.inputSchema !== null &&
				!Array.isArray(tool.inputSchema),
		) &&
		typeof request.cwd === "string" &&
		typeof request.headers === "object" &&
		request.headers !== null &&
		Object.values(request.headers).every(
			(value) => typeof value === "string" || value === null,
		) &&
		(request.env === undefined ||
			(typeof request.env === "object" &&
				request.env !== null &&
				Object.values(request.env).every((value) => typeof value === "string")))
	);
}