import { checkFileSafety } from "../prompt/safety.js";
import { DEFAULT_MAX_BYTES, formatSize, truncateHead } from "./truncate.js";
import { isBareProfileMarkdownFileName, resolvePathUnderWorkspace, resolveProfileMarkdownPathIfBareName } from "./tool-paths.js";
import { readFile, stat } from "fs/promises";
import { Type } from "@sinclair/typebox";
//#region src/agent/tools/read.ts
const MAX_FILE_SIZE = 10 * 1024 * 1024;
const DEFAULT_MAX_LINES = 500;
const ReadFileSchema = Type.Object({
	path: Type.String({ description: "File path to read" }),
	limit: Type.Optional(Type.Number({ description: "Max lines (default: 500)" }))
});
function createReadFileTool(workspace, options) {
	return {
		name: "read_file",
		description: "Read file contents. Relative paths are from the current agent workspace; profile Markdown (SOUL.md, etc.) is found automatically when given by filename.",
		parameters: ReadFileSchema,
		label: "📄 Read",
		async execute(_toolCallId, params, _signal) {
			return executeReadFile(workspace, options?.profileMarkdownRoot, params);
		}
	};
}
async function executeReadFile(workspace, profileMarkdownRoot, params) {
	try {
		const safety = checkFileSafety("read", params.path);
		if (!safety.allowed) return {
			content: [{
				type: "text",
				text: `🚫 ${safety.message}`
			}],
			details: {}
		};
		let normalized = resolvePathUnderWorkspace(params.path, workspace);
		let stats;
		try {
			stats = await stat(normalized);
		} catch (e) {
			if (e?.code === "ENOENT" && profileMarkdownRoot && isBareProfileMarkdownFileName(params.path)) {
				const alt = resolveProfileMarkdownPathIfBareName(params.path, profileMarkdownRoot);
				try {
					stats = await stat(alt);
					normalized = alt;
				} catch {
					throw e;
				}
			} else throw e;
		}
		if (stats.size > MAX_FILE_SIZE) return {
			content: [{
				type: "text",
				text: `🚫 File too large: ${formatSize(stats.size)}`
			}],
			details: {}
		};
		const truncation = truncateHead(await readFile(normalized, "utf-8"), {
			maxLines: params.limit || DEFAULT_MAX_LINES,
			maxBytes: DEFAULT_MAX_BYTES
		});
		let outputText = truncation.content;
		if (truncation.truncated) if (truncation.firstLineExceedsLimit) outputText = `(Line exceeds ${formatSize(DEFAULT_MAX_BYTES)})`;
		else outputText += `\n\n[${truncation.outputLines}/${truncation.totalLines} lines]`;
		return {
			content: [{
				type: "text",
				text: outputText
			}],
			details: {}
		};
	} catch (error) {
		return {
			content: [{
				type: "text",
				text: `Error: ${error instanceof Error ? error.message : String(error)}`
			}],
			details: {}
		};
	}
}
//#endregion
export { createReadFileTool };

//# sourceMappingURL=read.js.map