import { ToolCallAssembler, shouldIgnoreScopedTaskToolEvent } from "../../client/stream/handles/tools.js";
import { isRootNamespace, namespaceKey } from "../namespace.js";
import { upsertToolCall } from "../tool-calls.js";
import { openProjectionSubscription } from "./runtime.js";
//#region src/stream/projections/tool-calls.ts
function toolCallsProjection(namespace) {
	const ns = [...namespace];
	return {
		key: `toolCalls|${namespaceKey(ns)}`,
		namespace: ns,
		initial: [],
		open({ thread, store, rootBus }) {
			const assembler = new ToolCallAssembler();
			const applyToolsEvent = (event) => {
				if (shouldIgnoreScopedTaskToolEvent(ns, event)) return;
				const tc = assembler.consume(event);
				if (tc == null) return;
				const next = upsertToolCall(store.getSnapshot(), tc);
				store.setValue(next);
			};
			if (isRootNamespace(ns) && rootBus.channels.includes("tools")) {
				const unsubscribe = rootBus.subscribe((event) => {
					if (event.method !== "tools") return;
					if (!isRootNamespace(event.params.namespace)) return;
					applyToolsEvent(event);
				});
				return { dispose() {
					unsubscribe();
				} };
			}
			let runtime;
			const openSubscription = () => {
				runtime = openProjectionSubscription({
					thread,
					channels: ["tools"],
					namespace: ns,
					onEvent(event) {
						if (event.method !== "tools") return;
						applyToolsEvent(event);
					}
				});
			};
			let disposed = false;
			(async () => {
				if (!(await rootBus.trySeedFromHistory?.({
					kind: "toolCalls",
					namespace: ns,
					store
				}) === true) && !disposed) openSubscription();
			})();
			return { async dispose() {
				disposed = true;
				await runtime?.dispose();
			} };
		}
	};
}
//#endregion
export { toolCallsProjection };

//# sourceMappingURL=tool-calls.js.map