import { AgentCompletion } from "../models"; import { ToolDefinition, ToolHandler } from "../models/types"; import * as cheerio from "cheerio"; import { Customizer } from "../customizer"; import { Attachment, Builder, ContextSection } from "../builders/types"; import { PageValidationResult } from "./pageValidator"; // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- export interface TransformPageArgs { pageState: string; message: string; instructions?: string; builder: Builder; additionalSections: ContextSection[]; /** True when this is the builder page (has chat panel). */ isBuilder?: boolean; /** Product name for branding in prompts (defaults to 'SynthOS'). */ productName?: string; /** Optional image attachments sent alongside the user message. */ attachments?: Attachment[]; /** Chat history from the shell — used for newBuild detection instead of counting DOM elements. */ history?: { role: string; content: string }[]; /** Optional tool definitions exposed to the builder (on-demand context loading). */ tools?: ToolDefinition[]; /** Executors keyed by tool name. Required when `tools` is provided. */ toolHandlers?: Record; /** Fired once per tool-use iteration with the names of tools about to execute. */ onToolCall?: (names: string[]) => void; } export type ChangeOp = | { op: "update"; nodeId: string; html: string } | { op: "replace"; nodeId: string; html: string } | { op: "delete"; nodeId: string } | { op: "insert"; parentId: string; position: "prepend" | "append" | "before" | "after"; html: string } | { op: "style-element"; nodeId: string; style: string } | { op: "search-replace"; nodeId: string; search: string; replace: string } | { op: "search-insert"; nodeId: string; after: string; content: string }; export type ChangeList = ChangeOp[]; // --------------------------------------------------------------------------- // Public entry point // --------------------------------------------------------------------------- export interface TransformPageResult { html: string; changeCount: number; /** For 'reply' results — the assistant's text response (shell displays it). */ replyText?: string; /** For 'error' results — the error message (shell displays it). */ errorText?: string; /** Page validation results (undefined if validation was skipped). */ validation?: PageValidationResult; /** Number of change ops that were silently skipped (missing target, locked, etc.). */ skippedOps?: number; /** Short human-readable reasons for each skipped op, in order. */ skipReasons?: string[]; } export interface ApplyChangeListReport { html: string; skippedOps: number; skipReasons: string[]; } export async function transformPage(args: TransformPageArgs): Promise> { const { message, builder, additionalSections } = args; // 0. Strip the early error-capture script so the LLM never sees it const pageState = stripErrorCapture(args.pageState); // 1. Assign data-nid to every element const { html: annotatedHtml } = assignNodeIds(pageState); // 1b. Strip HTML comments from the annotated copy sent to the LLM (saves tokens). // The original pageState is preserved — changes are applied to the annotated copy // and then node IDs are stripped, so comments survive in the saved page. const llmHtml = annotatedHtml.replace(//g, ''); try { // 2. Build CURRENT_PAGE section const currentPage: ContextSection = { title: '', content: llmHtml, sketch: null, mode: 'always-full', instructions: '', }; // 3. Determine newBuild: if isBuilder, check chat history length let newBuild = false; if (args.isBuilder) { if (args.history) { // Shell provides explicit history — empty or greeting-only means new build newBuild = args.history.length <= 1; } else { // Fallback: count .chat-message in annotated HTML (legacy pages without chat-history.json) const $ = cheerio.load(annotatedHtml, { decodeEntities: false }); const messageCount = $('#chatMessages .chat-message').length; newBuild = messageCount <= 1; } } // 4. Call builder (with timeout guard) const TRANSFORM_TIMEOUT_MS = 600_000; // 10 minutes const result = await Promise.race([ builder.run(currentPage, additionalSections, message, newBuild, args.attachments, args.tools, args.toolHandlers, args.onToolCall), new Promise((_, reject) => setTimeout(() => reject(new Error('Page transform timed out — the AI took too long to respond. Please try again.')), TRANSFORM_TIMEOUT_MS) ), ]); // 5. Switch on result kind switch (result.kind) { case 'transforms': { const report = applyChangeListWithReport(annotatedHtml, result.changes); const safe = postProcessHtml(report.html); return { completed: true, value: { html: safe, changeCount: result.changes.length, replyText: result.message, skippedOps: report.skippedOps, skipReasons: report.skipReasons, } }; } case 'reply': { const safe = postProcessHtml(annotatedHtml); return { completed: true, value: { html: safe, changeCount: -1, replyText: result.text } }; } case 'error': { const clean = stripNodeIds(annotatedHtml); return { completed: true, value: { html: clean, changeCount: -1, errorText: result.error.message } }; } } } catch (err: unknown) { const errorMessage = err instanceof Error ? err.message : String(err); const clean = stripNodeIds(annotatedHtml); return { completed: true, value: { html: clean, changeCount: -1, errorText: errorMessage } }; } } // --------------------------------------------------------------------------- // Internal helpers // --------------------------------------------------------------------------- /** Tags the LLM will never target — skip annotation to save tokens. */ const SKIP_ANNOTATION_TAGS = new Set(['br', 'wbr', 'col', 'source']); /** * Assign sequential `data-nid` to every element in the HTML. * Skips trivial elements (br, wbr, col, source) that the LLM never targets. */ export function assignNodeIds(html: string): { html: string; nodeCount: number } { const $ = cheerio.load(html, { decodeEntities: false }); let counter = 0; $('*').each(function (this: cheerio.Element) { const el = $(this); if (this.type === 'tag' || this.type === 'script' || this.type === 'style') { const tag = (this as any).tagName?.toLowerCase() ?? (this as any).name?.toLowerCase(); if (SKIP_ANNOTATION_TAGS.has(tag)) return; el.attr('data-nid', String(counter++)); } }); return { html: $.html(), nodeCount: counter }; } /** * Remove all `data-nid` attributes from the HTML. */ export function stripNodeIds(html: string): string { const $ = cheerio.load(html, { decodeEntities: false }); $('[data-nid]').removeAttr('data-nid'); return $.html(); } /** * Consolidated post-processing: strip node IDs, deduplicate scripts, and * ensure script ordering — all in a single cheerio parse/serialize cycle. */ function postProcessHtml(html: string): string { const $ = cheerio.load(html, { decodeEntities: false }); // Strip data-nid attributes $('[data-nid]').removeAttr('data-nid'); // Deduplicate inline scripts (ID-based pass) const SYSTEM_IDS = new Set(['page-info', 'page-helpers', 'page-script', 'error', 'shell-v3', 'server-v3', 'storage-v3', 'script-v3', 'connector-v3', 'agent-v3']); const idGroups = new Map(); $('script').each(function (_, rawEl) { const el = $(rawEl); if (el.attr('src')) return; const id = el.attr('id'); if (!id || SYSTEM_IDS.has(id)) return; if (!idGroups.has(id)) idGroups.set(id, []); idGroups.get(id)!.push(el); }); for (const [id, group] of idGroups) { if (group.length < 2) continue; for (let i = 0; i < group.length - 1; i++) { console.log(`deduplicateInlineScripts: removing duplicate script id="${id}" (keeping last of ${group.length})`); group[i].remove(); } } // Deduplicate inline scripts (declaration-overlap pass for id-less scripts) const declPattern = /(?:^|;|\n)\s*(?:let|const|var|function|class)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g; interface ScriptInfo { el: cheerio.Cheerio; declarations: Set; } const scripts: ScriptInfo[] = []; $('script').each(function (_, rawEl) { const el = $(rawEl); if (el.attr('src')) return; if (el.attr('id')) return; if ((el.attr('type') ?? '').toLowerCase() === 'application/json') return; const code = (el.html() ?? '').trim(); if (!code) return; const declarations = new Set(); let m: RegExpExecArray | null; declPattern.lastIndex = 0; while ((m = declPattern.exec(code)) !== null) declarations.add(m[1]); scripts.push({ el, declarations }); }); const toRemove = new Set(); for (let i = 0; i < scripts.length; i++) { if (toRemove.has(i)) continue; for (let j = i + 1; j < scripts.length; j++) { if (toRemove.has(j)) continue; const a = scripts[i].declarations, b = scripts[j].declarations; if (a.size < 2 || b.size < 2) continue; let overlap = 0; for (const name of a) if (b.has(name)) overlap++; if (overlap / Math.min(a.size, b.size) >= 0.6) { console.log(`deduplicateInlineScripts: removing duplicate script (${overlap}/${Math.min(a.size, b.size)} declaration overlap)`); toRemove.add(i); break; } } } for (const idx of toRemove) scripts[idx].el.remove(); // Ensure page-helpers and page-script are last children of const body = $('body'); if (body.length > 0) { const helpers = $('script#page-helpers'); const pageScript = $('script#page-script'); const helpersHtml = helpers.length > 0 ? $.html(helpers.first()) : ''; const pageScriptHtml = pageScript.length > 0 ? $.html(pageScript.first()) : ''; if (helpers.length > 0) helpers.remove(); if (pageScript.length > 0) pageScript.remove(); if (helpersHtml) body.append(helpersHtml); if (pageScriptHtml) body.append(pageScriptHtml); } return $.html(); } /** * Remove the early error-capture script injected into so the LLM * never sees it during page transformation. */ function stripErrorCapture(html: string): string { const id = 'synthos-error-capture'; if (!html.includes(id)) return html; const $ = cheerio.load(html, { decodeEntities: false }); $(`#${id}`).remove(); return $.html(); } /** * Find `needle` in `haystack` using whitespace-normalized comparison. * Collapses runs of whitespace (spaces, tabs, newlines) into a single space * for comparison purposes but returns the position in the original string. * Returns -1 if no match found. */ export function normalizedIndexOf(haystack: string, needle: string): { start: number; end: number } | null { // Build a mapping from normalized-string positions to original-string positions const normChars: string[] = []; const origPositions: number[] = []; // origPositions[i] = original index of normChars[i] let inWhitespace = false; for (let i = 0; i < haystack.length; i++) { const ch = haystack[i]; if (ch === ' ' || ch === '\t' || ch === '\n' || ch === '\r') { if (!inWhitespace) { normChars.push(' '); origPositions.push(i); inWhitespace = true; } } else { normChars.push(ch); origPositions.push(i); inWhitespace = false; } } const normHaystack = normChars.join(''); // Normalize the needle the same way const normNeedle = needle.replace(/\s+/g, ' '); const idx = normHaystack.indexOf(normNeedle); if (idx === -1) return null; const start = origPositions[idx]; // The end position: find the original position of the last matched char, then go one past const lastNormIdx = idx + normNeedle.length - 1; const lastOrigPos = origPositions[lastNormIdx]; // Advance past any trailing whitespace that was collapsed in the original let end = lastOrigPos + 1; if (haystack[lastOrigPos] === ' ' || haystack[lastOrigPos] === '\t' || haystack[lastOrigPos] === '\n' || haystack[lastOrigPos] === '\r') { // The last matched normalized char was a whitespace collapse — extend to include all original whitespace while (end < haystack.length && (haystack[end] === ' ' || haystack[end] === '\t' || haystack[end] === '\n' || haystack[end] === '\r')) { end++; } } return { start, end }; } /** * Remove duplicate inline `