import { t as openNodeSqliteDatabase } from "../../node-sqlite-GN5_mcoB.js";
import { t as loadSqliteVecExtension } from "../../sqlite-vec-7qoh8Zei.js";
import "../../sqlite-runtime-CRyA-CYA.js";
import "../../memory-core-host-engine-schema-ArbJPD3C.js";
import { n as runVectorKnnQuery } from "../../manager-search-knn-Du9AM2HM.js";
//#region extensions/memory-core/src/memory/manager-search-knn.child.ts
const MAX_STDIN_BYTES = 1024 * 1024;
const MAX_STDOUT_BYTES = 2 * 1024 * 1024;
function isChildInput(value) {
	if (!value || typeof value !== "object") return false;
	const input = value;
	return typeof input.databasePath === "string" && input.databasePath.length > 0 && Boolean(input.request) && typeof input.request === "object";
}
async function run(input) {
	if (!isChildInput(input)) return {
		status: "failed",
		error: "invalid memory vector KNN child input"
	};
	const db = openNodeSqliteDatabase(input.databasePath, {
		allowExtension: true,
		readOnly: true
	});
	try {
		db.exec("PRAGMA query_only = ON; PRAGMA busy_timeout = 5000");
		const loaded = await loadSqliteVecExtension({
			db,
			extensionPath: input.extensionPath
		});
		if (!loaded.ok) throw new Error(loaded.error ?? "sqlite-vec unavailable in memory search child");
		return {
			status: "ok",
			value: runVectorKnnQuery(db, input.request)
		};
	} catch (error) {
		return {
			status: "failed",
			error: error instanceof Error ? error.message : String(error)
		};
	} finally {
		db.close();
	}
}
function writeResult(result) {
	let payload = Buffer.from(JSON.stringify(result), "utf8");
	if (payload.byteLength > MAX_STDOUT_BYTES) payload = Buffer.from(JSON.stringify({
		status: "failed",
		error: "memory vector KNN child result is too large"
	}), "utf8");
	process.stdout.write(payload);
}
const chunks = [];
let inputBytes = 0;
let inputTooLarge = false;
process.stdin.on("data", (chunk) => {
	inputBytes += chunk.byteLength;
	if (inputBytes > MAX_STDIN_BYTES) {
		inputTooLarge = true;
		chunks.length = 0;
		return;
	}
	chunks.push(chunk);
});
process.stdin.once("end", () => {
	if (inputTooLarge) {
		writeResult({
			status: "failed",
			error: "memory vector KNN child input is too large"
		});
		return;
	}
	let input;
	try {
		input = JSON.parse(Buffer.concat(chunks).toString("utf8"));
	} catch {
		writeResult({
			status: "failed",
			error: "invalid memory vector KNN child JSON"
		});
		return;
	}
	run(input).then(writeResult, (error) => {
		writeResult({
			status: "failed",
			error: error instanceof Error ? error.message : String(error)
		});
	});
});
process.stdin.resume();
//#endregion
export {};
