# Part of Odoo. See LICENSE file for full copyright and licensing details. import contextlib import json import re import secrets from lxml import etree, html as lxml_html from odoo import api, models from odoo.addons.ai_website.models.ai_website_service import _WHOLE_ZONE_SELECTORS # The public form runtime re-injects a fresh signature on every render # (website/tools.py add_form_signature), so any signature in generated or # fetched markup is dead weight, and a hardcoded hash trips the safety # reviewer. Strip them everywhere. _FORM_SIGNATURE_RE = re.compile(r']*website_form_signature[^>]*>\s*', re.IGNORECASE) _SUCCESS_MODES = ('redirect', 'message', 'nothing') # The field types the editor can render, one website.form_field_* template # each (website_form_editor.xml). Any other data-type crashes the sidebar's # field rendering. _FIELD_TYPES = frozenset(( 'char', 'text', 'email', 'tel', 'url', 'integer', 'float', 'monetary', 'date', 'datetime', 'binary', 'boolean', 'selection', 'many2one', 'one2many', 'many2many', 'html', )) _EMAIL_TO_INPUT_RE = re.compile(r']*\bname="email_to"[^>]*>', re.IGNORECASE) # The accept values the editor's file-type options produce. The submit # validator matches them against the files' MIME types, so anything else # (e.g. an extension list) rejects every upload. _FILE_ACCEPT_VALUES = frozenset(( 'image/*', 'application/pdf', 'application/*', 'video/*', 'audio/*', )) def _blank_email_to_values(html): """Clear the `value` attribute of any `email_to` inputs in the HTML. This prevents the AI from silently copying the default company address from snippets without the user's explicit approval.""" return _EMAIL_TO_INPUT_RE.sub( lambda match: re.sub(r'\bvalue="[^"]*"', 'value=""', match.group(0)), html, ) def _with_class(cls): """Generate an XPath condition to safely match a class name within a space-separated class attribute.""" return f'contains(concat(" ", normalize-space(@class), " "), " {cls} ")' def _field_name(field_el): """The name a field wrapper submits under. A multi-option field carries it on its group wrapper, every other field on its input.""" return next(iter(field_el.xpath( f'.//*[{_with_class("s_website_form_multiple")}]/@data-name' f' | .//*[{_with_class("s_website_form_input")}]/@name')), None) class AIToolWebform(models.AbstractModel): """Webform support for the website builder agent. The agent builds forms by writing HTML adapted from the canonical form snippets; this layer makes those forms functional by construction: - a normalizer gates every HTML apply: purely mechanical details (signatures, ids, submit anchor, custom-vs-bound markers) are repaired in place, while anything that would break the submission or the editor and needs the model's (or the user's) intent raises, so the error goes back through the tool result and the model corrects its own output; - the "Set Form Action" tool wires a form through the form editor's own client-side code paths, and the "Get Webform Info" tool describes the available form actions and their bindable fields. """ _inherit = 'ai.tool' @api.model def _ai_tool_apply_html_to_page(self, tool_context, actions): """Normalize the webforms in the actions before the base apply pipeline runs.""" # Some providers send structured arguments JSON-encoded; parse before # normalizing. if isinstance(actions, str): with contextlib.suppress(json.JSONDecodeError): actions = json.loads(actions) if isinstance(actions, list): # Before super(): the safety reviewer must never see a signature. self._normalize_webform_actions(actions) return super()._ai_tool_apply_html_to_page(tool_context, actions) @api.model def _ai_tool_get_snippets(self, snippet_keys): """Strip live signatures and blank out email recipients from fetched snippets to prevent the model from faithfully copying them.""" result = super()._ai_tool_get_snippets(snippet_keys) if isinstance(result, str): result = _FORM_SIGNATURE_RE.sub('', result) result = _blank_email_to_values(result) return result @api.model def _normalize_webform_actions(self, actions): """Validate and normalize the webforms of every action's content, in place.""" for index, action in enumerate(actions): if not isinstance(action, dict): continue content = action.get('content') or '' if 's_website_form' not in content and '