/**
 * URL branch of the `read` tool: routes plain URL reads through the
 * cache/artifact/llms.txt fetch pipeline ({@link executeReadUrl}); explicit
 * URL line selectors reuse the same safe rendering path before slicing lines.
 */
import { resolve as resolvePath } from "node:path";
import { applyReadLineSelection, decodeReadableUrl } from "./read-document-extract.js";
import { executeReadUrl, loadPage } from "./fetch-url.js";
export async function readUrlBranch(args) {
    const { effectivePath, rawOutput, effectiveRanges, effectiveOffset, effectiveLimit, cwd, ctx, signal, maxChars, maxBytes, oversized, sourceMeta } = args;
    const session = ctx?.sessionManager;
    const sessionDir = session?.getSessionDir?.();
    const scope = session?.getSessionId?.() ?? cwd;
    const artifactsDir = sessionDir ? resolvePath(sessionDir, "artifacts") : undefined;
    if (!effectiveRanges && !effectiveOffset && effectiveLimit === undefined) {
        const result = await executeReadUrl(scope, { path: effectivePath, raw: rawOutput }, artifactsDir, signal);
        const artifactId = result.artifactId ?? result.details.meta?.artifactId;
        const truncation = result.details.meta?.truncation;
        return {
            content: [{ type: "text", text: result.content }],
            details: {
                ...(truncation ? { truncation } : {}),
                meta: { ...(result.details.meta ?? {}), source: effectivePath, sourcePath: effectivePath, ...(artifactId ? { artifactId } : {}) },
            },
        };
    }
    const page = await loadPage(effectivePath, 10_000, signal);
    const textContent = rawOutput ? page.content : await decodeReadableUrl(new Response(page.content, { headers: { "content-type": page.contentType } }), page.finalUrl || effectivePath);
    const selection = applyReadLineSelection(textContent.split("\n"), effectiveRanges, effectiveOffset, effectiveLimit, rawOutput), selectedText = selection.lines.join("\n");
    if ((effectiveRanges || effectiveOffset) && selection.lines.length === 0) {
        const requested = effectiveRanges?.[0]?.start ?? effectiveOffset ?? 1;
        return { content: [{ type: "text", text: `Requested line ${requested} is beyond end of resource (${textContent.split("\n").length} lines total).` }], details: undefined };
    }
    if (selectedText.length > maxChars || Buffer.byteLength(selectedText, "utf8") > maxBytes) {
        return oversized({ blocked: true, path: effectivePath, chars: selectedText.length, maxChars, startLine: selection.firstLine, totalFileLines: textContent.split("\n").length, firstLineBytes: Buffer.byteLength(selection.lines[0] ?? "", "utf8"), byteGuidance: false });
    }
    return { content: [{ type: "text", text: rawOutput ? selectedText : `URL: ${effectivePath}\nStatus: ${page.status}\nContent-Type: ${page.contentType || "unknown"}\n\n${selectedText}` }], details: sourceMeta(effectivePath) };
}
//# sourceMappingURL=read-url.js.map