"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebFetchTool = void 0;
const fs = __importStar(require("fs/promises"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const pdfTool_1 = require("./pdfTool");
const MAX_RESPONSE_SIZE = 50_000;
const MAX_PDF_BYTES = 50_000_000;
const PDF_EXTRACT_TIMEOUT_MS = 60_000;
function withTimeout(promise, ms, label) {
    return new Promise((resolve, reject) => {
        const timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
        promise.then((value) => { clearTimeout(timer); resolve(value); }, (err) => { clearTimeout(timer); reject(err); });
    });
}
exports.WebFetchTool = {
    name: 'web_fetch',
    description: 'Fetch the content of a URL and return the response body as text. PDF responses are passed through pdf_read text extraction automatically.',
    parameters: {
        type: 'object',
        properties: {
            url: { type: 'string', description: 'URL to fetch' },
            method: { type: 'string', description: 'HTTP method (default: GET)' },
        },
        required: ['url'],
    },
    isReadOnly: true,
    async execute(input) {
        const url = input.url;
        const method = input.method ?? 'GET';
        try {
            const response = await fetch(url, { method, signal: AbortSignal.timeout(30_000) });
            const contentType = (response.headers.get('content-type') ?? '').toLowerCase();
            const looksLikePdf = contentType.includes('application/pdf') || url.toLowerCase().split('?')[0].endsWith('.pdf');
            if (response.ok && looksLikePdf) {
                const buffer = Buffer.from(await response.arrayBuffer());
                if (buffer.length > MAX_PDF_BYTES) {
                    return { success: false, output: `PDF response exceeds ${MAX_PDF_BYTES} bytes (${buffer.length}).`, error: 'pdf too large' };
                }
                const tmpPath = path.join(os.tmpdir(), `harness-webfetch-${Date.now()}.pdf`);
                try {
                    await fs.writeFile(tmpPath, buffer);
                    const result = await withTimeout((0, pdfTool_1.extractPdfText)(buffer, { maxChars: MAX_RESPONSE_SIZE }, tmpPath), PDF_EXTRACT_TIMEOUT_MS, 'PDF extraction');
                    const header = `[PDF fetched from ${url}; pages ${result.startPage}-${result.endPage} of ${result.pageCount}]\n\n`;
                    return { success: true, output: header + result.text };
                }
                finally {
                    await fs.rm(tmpPath, { force: true });
                }
            }
            const body = await response.text();
            const truncated = body.length > MAX_RESPONSE_SIZE
                ? body.slice(0, MAX_RESPONSE_SIZE) + '\n...(truncated)'
                : body;
            if (!response.ok) {
                return {
                    success: false,
                    output: `HTTP ${response.status} ${response.statusText}\n${truncated}`,
                    error: `HTTP ${response.status}`,
                };
            }
            return { success: true, output: truncated };
        }
        catch (error) {
            const msg = error instanceof Error ? error.message : String(error);
            return { success: false, output: `Fetch failed: ${msg}`, error: msg };
        }
    },
};
//# sourceMappingURL=webFetchTool.js.map