dist / runtime / webTurn.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.webOperation = webOperation;
exports.webCapabilities = webCapabilities;
exports.httpUrl = httpUrl;
exports.userRequestText = userRequestText;
exports.urlsIn = urlsIn;
exports.inspectWebTurn = inspectWebTurn;
exports.planWebTurn = planWebTurn;
const jsonschema_1 = require("jsonschema");
const toolBridge_1 = require("../toolBridge");
const names = { fetch_page: ["Visit Website Advanced", "Visit Website"], read_saved_page: ["Read Saved Website"], search_saved_page: ["Search Saved Website"], read_saved_json_ld: ["Read Saved JSON-LD"] };
function webOperation(name) {
    for (const [operation, spellings] of Object.entries(names))
        for (const spelling of spellings) {
            for (const variant of [spelling, spelling.replace(/ /g, "_")])
                if (name === variant || ["/", "__", "."].some(separator => name.endsWith(separator + variant)))
                    return operation;
        }
}
function webCapabilities(definitions) {
    return definitions.flatMap(definition => {
        const operation = webOperation(definition.function.name), schema = definition.function.parameters;
        if (!operation)
            return [];
        const key = operation === "fetch_page" ? "url" : "pageId";
        if (schema?.properties?.[key]?.type !== "string" || !schema.required?.includes(key))
            return [];
        return [{ id: operation, name: definition.function.name, definition }];
    });
}
function httpUrl(value) {
    if (typeof value !== "string")
        return;
    try {
        const url = new URL(value);
        if (["http:", "https:"].includes(url.protocol) && !url.username && !url.password)
            return url.href;
    }
    catch { }
}
// Analyze Images appends these inventories to the user message after preparing
// attachments. Their source URLs identify images, not additional page requests.
// Only classify intent from the request; keep the complete message for the model.
function userRequestText(text) {
    return text
        .replace(/(?:^|\r?\n)\[Automatically attached images\]\r?\n(?:Attachment \d+: [^\r\n]*(?:\r?\n|$))+/g, "\n")
        .replace(/(?:^|\r?\n)\[Images available to analysis tools\]\r?\n[\s\S]*?\r?\n\[End image references\]/g, "\n")
        .trim();
}
function urlsIn(text) {
    const clean = userRequestText(text).replace(/```[\s\S]*?```/g, "");
    return [...new Set((clean.match(/https?:\/\/[^\s<>"`]+/g) ?? []).flatMap(raw => {
            let url = raw.replace(/[。、,」』】》]+$/u, "");
            while (url.endsWith(")") && (url.match(/\)/g)?.length ?? 0) > (url.match(/\(/g)?.length ?? 0))
                url = url.slice(0, -1);
            const normalized = httpUrl(url);
            return normalized ? [normalized] : [];
        }))];
}
function request(text) {
    text = userRequestText(text);
    const urls = urlsIn(text);
    if (/読ま(?:ない|ず)|見ない|開か(?:ない|ず)|取得(?:しない|せず)|アクセス(?:不要|しない|せず)|接続(?:しない|せず)|URLの(?:構文|形式|文字列)|do not (?:open|read|fetch|visit|access)|don't (?:open|read|fetch|visit|access)|never (?:open|read|fetch|visit|access)|without (?:opening|fetching|accessing)/i.test(text))
        return;
    if (urls.length) {
        const onlyUrl = text.trim().replace(/^<|>$/g, "");
        if (httpUrl(onlyUrl) || /読[むんみめ]|開[いくけ]|取得|見て|調べ|確認|要約|内容|\b(?:read|open|visit|fetch|summarize|summarise)\b|读取|阅读|读一下|打开|요약|읽어|열어|resumir|leer|abre/i.test(text))
            return { kind: "open_url", urls };
    }
    const id = /\bpageId\s*[=::]?\s*["']?([a-f0-9]{32})\b/.exec(text)?.[1];
    if (id && (/読|見て|確認|要約|\b(?:read|open|summarize|summarise)\b/i.test(text) || /^pageId\s*[=::]\s*["']?[a-f0-9]{32}["']?\s*$/i.test(text.trim())))
        return { kind: "read_saved", pageId: id };
    if (/そのページ|このページ|保存済みページ|保存したページ|\b(?:that|saved) page\b/i.test(text))
        return { kind: "read_saved" };
}
function inspectWebTurn(history, definitions) {
    const entries = [...history], latestUser = entries.reduce((last, m, i) => m.getRole() === "user" ? i : last, -1);
    if (latestUser < 0)
        return;
    const current = request(entries[latestUser].getText());
    if (!current)
        return;
    const bridge = new toolBridge_1.ToolBridge(definitions);
    const capabilities = webCapabilities(definitions), resources = [], calls = [], pending = new Map();
    let turn = -1;
    for (const [i, message] of entries.entries()) {
        if (message.getRole() === "user")
            turn = i;
        if (message.getRole() === "assistant")
            for (const call of message.getToolCallRequests()) {
                const name = bridge.original(call.name) ?? call.name, operation = webOperation(name);
                if (!operation || !call.id || !capabilities.some(c => c.id === operation && c.name === name))
                    continue;
                const entry = { id: call.id, operation, name, args: call.arguments ?? {}, turn, status: "pending" };
                pending.set(call.id, entry);
                calls.push(entry);
            }
        if (message.getRole() === "tool")
            for (const result of message.getToolCallResults()) {
                const call = result.toolCallId ? pending.get(result.toolCallId) : undefined;
                if (!call)
                    continue;
                pending.delete(call.id);
                call.result = result.content;
                let data;
                try {
                    data = JSON.parse(result.content);
                }
                catch {
                    call.status = "failed";
                    continue;
                }
                if (!data || data.error || data.isError) {
                    call.status = "failed";
                    continue;
                }
                if (call.operation === "fetch_page") {
                    const url = httpUrl(data.url), requestedUrl = httpUrl(call.args.url);
                    if (typeof data.pageId !== "string" || !/^[a-f0-9]{32}$/.test(data.pageId) || !url || !requestedUrl) {
                        call.status = "failed";
                        continue;
                    }
                    resources.push({ id: data.pageId, url, requestedUrl, turn: call.turn, ...(Number.isInteger(data.totalBlocks) && data.totalBlocks >= 0 ? { blocks: data.totalBlocks } : {}) });
                    call.status = "ok";
                }
                else {
                    call.status = data.pageId === call.args.pageId && (Array.isArray(data.blocks) || Array.isArray(data.hits) || typeof data.text === "string" || (call.operation === "read_saved_json_ld" && data.jsonLd === true)) ? "ok" : "failed";
                    if (call.operation === "read_saved_page" && call.status === "ok") {
                        call.sourceRead = typeof data.text === "string" && Number.isInteger(data.htmlBlockId) && Number.isInteger(data.offset)
                            && (call.args.htmlBlockId === undefined || call.args.htmlBlockId === data.htmlBlockId)
                            && (call.args.postNumber === undefined || call.args.postNumber === data.postNumber);
                        if (Array.isArray(data.blocks))
                            call.blockIds = data.blocks.map((b) => b.htmlBlockId).filter((id) => Number.isInteger(id) && Number(id) >= 0);
                        if (call.args.htmlBlockId !== undefined && !call.sourceRead)
                            call.status = "failed";
                    }
                }
            }
    }
    if (current.kind === "open_url")
        return { ...current, resources, calls, latestUser, capabilities };
    let pageId = current.pageId;
    if (!pageId) {
        // Only an unambiguous immediately preceding page task can supply focus.
        const previous = entries.map((m, i) => ({ m, i })).filter(({ m, i }) => i < latestUser && m.getRole() === "user").at(-1);
        const prior = previous ? request(previous.m.getText()) : undefined;
        if (prior?.kind === "open_url" && prior.urls.length === 1)
            pageId = [...resources].reverse().find(r => r.turn === previous.i && r.requestedUrl === prior.urls[0])?.id;
        else if (prior?.kind === "read_saved") {
            const focused = [...new Set(calls.filter(c => c.turn === previous.i && c.operation === "read_saved_page" && c.status === "ok").map(c => c.args.pageId))];
            pageId = prior.pageId ?? (focused.length === 1 && typeof focused[0] === "string" ? focused[0] : undefined);
        }
    }
    return { kind: "read_saved", urls: [], pageId, resources, calls, latestUser, capabilities };
}
function planWebTurn(turn) {
    if (turn.urls.length > 8)
        return { state: "blocked", code: "too_many_urls" };
    const current = turn.calls.filter(c => c.turn === turn.latestUser);
    const capability = (operation) => turn.capabilities.filter(c => c.id === operation);
    const action = (operation, args) => {
        const candidates = capability(operation);
        if (candidates.length !== 1)
            return { state: "blocked", code: candidates.length ? "ambiguous_capability" : "required_capability_unavailable" };
        const schema = candidates[0].definition.function.parameters;
        if (!new jsonschema_1.Validator().validate(args, schema).valid)
            return { state: "blocked", code: "incompatible_tool_schema" };
        return { state: "action", capability: candidates[0], args };
    };
    const pages = [];
    if (turn.kind === "open_url")
        for (const url of turn.urls) {
            const attempts = current.filter(c => c.operation === "fetch_page" && httpUrl(c.args.url) === url);
            const page = [...turn.resources].reverse().find(r => r.turn === turn.latestUser && r.requestedUrl === url);
            if (!page) {
                if (attempts.length)
                    return { state: "blocked", code: attempts.at(-1).status === "pending" ? "awaiting_tool_result" : "page_fetch_failed" };
                return action("fetch_page", { url });
            }
            pages.push(page);
        }
    else {
        const page = [...turn.resources].reverse().find(r => r.id === turn.pageId);
        if (!page)
            return { state: "blocked", code: "unknown_page_reference" };
        pages.push(page);
    }
    for (const page of pages) {
        const reads = current.filter(c => c.operation === "read_saved_page" && c.args.pageId === page.id);
        if (!reads.length)
            return action("read_saved_page", { pageId: page.id, ...(page.blocks && page.blocks > 0 ? { htmlBlockId: 0 } : {}) });
        if (!reads.some(c => c.status === "ok"))
            return { state: "blocked", code: reads.at(-1).status === "pending" ? "awaiting_tool_result" : "saved_page_unavailable" };
        if (!reads.some(c => c.sourceRead)) {
            const first = reads.flatMap(c => c.status === "ok" ? c.blockIds ?? [] : [])[0];
            if (first !== undefined) {
                const attempted = reads.filter(c => c.args.htmlBlockId === first).at(-1);
                if (attempted)
                    return { state: "blocked", code: attempted.status === "pending" ? "awaiting_tool_result" : "saved_page_unavailable" };
                return action("read_saved_page", { pageId: page.id, htmlBlockId: first });
            }
            if (page.blocks !== 0)
                return { state: "blocked", code: "saved_page_unavailable" };
        }
    }
    return { state: "answer" };
}