# -*- coding: utf-8 -*- """Pure helper functions lifted from the enterprise AI assistant behaviour. These are protocol-level utilities: date arithmetic for the model, markdown rendering of answers, and the record previews shown before a write. They are intentionally free of business logic so they can be unit tested. """ import ast import calendar import json import re from datetime import UTC, datetime, timedelta from zoneinfo import ZoneInfo from markupsafe import Markup, escape from odoo.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT VALID_INTERVALS = ['day', 'week', 'month', 'quarter', 'year'] VALID_QUARTERS = ['first_quarter', 'second_quarter', 'third_quarter', 'fourth_quarter'] QUARTER_MONTHS = { 1: (1, 2, 3), 2: (4, 5, 6), 3: (7, 8, 9), 4: (10, 11, 12), } MAX_OFFSET = 100 MIN_OFFSET = -100 BOUNDARY_TIME_RESETS = { 'start': { 'minute': {'second': 0, 'microsecond': 0}, 'hour': {'minute': 0, 'second': 0, 'microsecond': 0}, 'day': {'hour': 0, 'minute': 0, 'second': 0, 'microsecond': 0}, }, 'end': { 'minute': {'second': 59, 'microsecond': 999999}, 'hour': {'minute': 59, 'second': 59, 'microsecond': 999999}, 'day': {'hour': 23, 'minute': 59, 'second': 59, 'microsecond': 999999}, }, } ALLOWED_ROLES = ('user', 'assistant') def get_text_from_parts(parts): """Extract the text payload from a parts list.""" if isinstance(parts, str): return parts texts = [part['text'] for part in parts or [] if part.get('type') == 'text'] if not texts: return '' return texts[0] if len(texts) == 1 else '\n'.join(texts) def is_ai_parts(obj): if not isinstance(obj, list): return False for part in obj: if not isinstance(part, dict): return False if part.get('type') not in ('text', 'inline_data'): return False if part['type'] == 'text' and 'text' not in part: return False if part['type'] == 'inline_data' and ('mimetype' not in part or 'data' not in part): return False return True def format_tool_result(tool_call, result=None, error=None): """Normalise a tool outcome into a ``tool_result`` part payload.""" if not is_ai_parts(result): if error is not None: text = f"Error: {error}" elif result is None: text = 'success' elif not isinstance(result, str): text = json.dumps(result, default=str, ensure_ascii=False) else: text = result result = [{'type': 'text', 'text': text}] return { 'type': 'tool_result', 'tool_name': tool_call['name'], 'tool_call_id': tool_call['call_id'], 'result': result, 'success': error is None, } # --------------------------------------------------------------------------- # compute_date: relative date expressions for the model # --------------------------------------------------------------------------- def _clamp_day_to_month(year, month, day): return min(day, calendar.monthrange(year, month)[1]) def _add_months_with_clamping(working_dt, months_offset): total = (working_dt.month - 1) + months_offset new_year = working_dt.year + (total // 12) new_month = (total % 12) + 1 new_day = _clamp_day_to_month(new_year, new_month, working_dt.day) return working_dt.replace(year=new_year, month=new_month, day=new_day) def _navigate(working_dt, op): period = op['period'] offset = op.get('offset') or 0 boundary = op.get('boundary') if offset < MIN_OFFSET or offset > MAX_OFFSET: raise ValueError(f"offset must be between {MIN_OFFSET} and {MAX_OFFSET}") match period: case 'minute': result = working_dt + timedelta(minutes=offset) case 'hour': result = working_dt + timedelta(hours=offset) case 'day': result = working_dt + timedelta(days=offset) case 'week': result = working_dt + timedelta(weeks=offset) case 'month': result = _add_months_with_clamping(working_dt, offset) case 'quarter': result = _add_months_with_clamping(working_dt, offset * 3) case 'year': result = _add_months_with_clamping(working_dt, offset * 12) case _: raise ValueError(f"Unknown period: {period}") if boundary in BOUNDARY_TIME_RESETS: resets = BOUNDARY_TIME_RESETS[boundary] match period: case 'minute' | 'hour' | 'day': result = result.replace(**resets[period]) case 'week': days = -result.weekday() if boundary == 'start' else 6 - result.weekday() result = (result + timedelta(days=days)).replace(**resets['day']) case 'month': day = 1 if boundary == 'start' else calendar.monthrange(result.year, result.month)[1] result = result.replace(day=day, **resets['day']) case 'quarter': quarter = (result.month - 1) // 3 + 1 month = QUARTER_MONTHS[quarter][0 if boundary == 'start' else -1] day = 1 if boundary == 'start' else calendar.monthrange(result.year, month)[1] result = result.replace(month=month, day=day, **resets['day']) case 'year': month = 1 if boundary == 'start' else 12 day = 1 if boundary == 'start' else 31 result = result.replace(month=month, day=day, **resets['day']) return result def _find_weekday(working_dt, target_weekday, direction): if target_weekday < 0 or target_weekday > 6: raise ValueError("weekday must be between 0 (Monday) and 6 (Sunday)") current = working_dt.weekday() days = (direction * (target_weekday - current)) % 7 or 7 return working_dt + timedelta(days=days * direction) def _apply_pin(working_dt, pin): result = working_dt if pin.get('day') is not None: day_value = pin['day'] if isinstance(day_value, int): if not 1 <= day_value <= 31: raise ValueError("pin.day must be between 1 and 31") max_day = calendar.monthrange(result.year, result.month)[1] if day_value > max_day: raise ValueError(f"pin.day must be <= {max_day} for {result.year}-{result.month:02d}") result = result.replace(day=day_value) elif isinstance(day_value, dict): if 'weekday' not in day_value: raise ValueError("pin.day object must have a 'weekday' field") target = day_value['weekday'] if not isinstance(target, int) or not 0 <= target <= 6: raise ValueError("pin.day.weekday must be an integer 0..6") occurrence = day_value.get('occurrence') if occurrence is not None: if not isinstance(occurrence, int) or not 1 <= occurrence <= 5: raise ValueError("pin.day.occurrence must be an integer 1..5") first = result.replace(day=1) days_to_first = (target - first.weekday()) % 7 first_hit = first + timedelta(days=days_to_first) target_day = first_hit + timedelta(weeks=occurrence - 1) if target_day.month != result.month: raise ValueError( f"The {occurrence}th occurrence of weekday {target} " f"does not exist in month {result.month}" ) result = result.replace(day=target_day.day) else: result = result + timedelta(days=target - result.weekday()) else: raise ValueError("pin.day must be an integer (1-31) or object {weekday, occurrence?}") if pin.get('time') is not None: time_str = pin['time'] if not isinstance(time_str, str): raise ValueError("pin.time must be a string 'HH:MM' or 'HH:MM:SS'") chunks = time_str.split(':') if len(chunks) not in (2, 3): raise ValueError("pin.time must be 'HH:MM' or 'HH:MM:SS'") try: hour, minute = int(chunks[0]), int(chunks[1]) second = int(chunks[2]) if len(chunks) == 3 else 0 except ValueError: raise ValueError("pin.time components must be integers") from None if not (0 <= hour <= 23 and 0 <= minute <= 59 and 0 <= second <= 59): raise ValueError("pin.time out of range") result = result.replace(hour=hour, minute=minute, second=second, microsecond=0) return result def compute_date(field_type, user_tz, today, operations=None, pin=None): """Turn ``navigate`` / ``find_next`` operations into an absolute date.""" if field_type not in ('date', 'datetime'): raise ValueError("field_type must be 'date' or 'datetime'") working_dt = datetime.combine(today, datetime.min.time(), tzinfo=ZoneInfo(user_tz or 'UTC')) for op in operations or []: match op.get('type'): case 'navigate': working_dt = _navigate(working_dt, op) case 'find_previous': working_dt = _find_weekday(working_dt, op['weekday'], direction=-1) case 'find_next': working_dt = _find_weekday(working_dt, op['weekday'], direction=1) case _: raise ValueError(f"Unknown operation type: {op.get('type')}") if pin: working_dt = _apply_pin(working_dt, pin) if field_type == 'date': return working_dt.strftime(DEFAULT_SERVER_DATE_FORMAT) return working_dt.astimezone(UTC).strftime(DEFAULT_SERVER_DATETIME_FORMAT) # --------------------------------------------------------------------------- # markdown -> safe html # --------------------------------------------------------------------------- _FENCED_CODE = re.compile(r'```(\w*)\n(.*?)```', re.S) _HEADING_RE = re.compile(r'^(#{1,6})\s+(.*)$') _ORDERED_RE = re.compile(r'^(\d{1,9})[.)]\s+(.*)$') _UNORDERED_RE = re.compile(r'^[-*+]\s+(.*)$') _QUOTE_RE = re.compile(r'^>\s?(.*)$') _HR_RE = re.compile(r'^(?:-{3,}|\*{3,}|_{3,})$') # One cell of the `|---|:--:|` separator row: dashes, optionally colon-aligned. _TABLE_SEP_RE = re.compile(r'^:?-{1,}:?$') # Only these schemes survive in a rendered link; the model can emit anything. _SAFE_URL_RE = re.compile(r'^(?:https?:|mailto:|/|#)', re.I) def markdown_format(text): """Render the model's markdown into safe HTML. Deliberately dependency-free: the enterprise build vendors markdown2, which is not available here. Everything unrecognised is HTML-escaped, so the output can be injected into a chatter body without a sanitiser pass. Supported blocks: fenced code, GFM tables (with column alignment), headings, bullet/ordered lists, block quotes, horizontal rules and paragraphs. Inline: bold, italics, inline code and links. Tables matter most in practice: an assistant answering "here is the order I created" produces a table, and before this renderer every row was wrapped in its own ``
``, so the user saw raw pipes instead of a grid. """ if not text: return Markup('') text = str(text) placeholders = {} def stash(html): key = f"\x00{len(placeholders)}\x00" placeholders[key] = html return key def code_block(match): lang = match.group(1) or '' body = escape(match.group(2)) cls = f' class="language-{lang}"' if lang else '' return stash( f'
'
f'{body}'
)
text = _FENCED_CODE.sub(code_block, text)
lines = text.split('\n')
out = []
index = 0
total = len(lines)
while index < total:
raw = lines[index]
stripped = raw.strip()
if not stripped:
index += 1
continue
# ---- table ----------------------------------------------------
# A table needs a header row followed by a separator row; requiring
# both is what keeps a paragraph containing a pipe from turning into
# a one-column table.
if '|' in stripped and _table_separator(lines, index):
html, index = _render_table(lines, index, escape)
out.append(html)
continue
# ---- fenced code placeholder ----------------------------------
if stripped.startswith('\x00') and stripped.endswith('\x00'):
out.append(f'{"') continue # ---- paragraph -------------------------------------------------- # Consecutive lines belong to one paragraph and keep their line # breaks: the assistant formats answers line by line ("客户:… / 合计:…") # and collapsing those into spaces makes the text harder to scan. paragraph = [] while index < total: candidate = lines[index].strip() if not candidate: break if paragraph and _starts_block(lines, index): break paragraph.append(_inline_md(candidate, escape)) index += 1 out.append(f'
".join(quoted)}
{"
".join(paragraph)}
\1', text)
text = re.sub(r'\*\*([^*]+)\*\*', r'\1', text)
text = re.sub(r'(?\1', text)
# Links: the href is dropped unless it is a real address. The model is an
# untrusted source of markup, and `javascript:` is one generated reply away
# from stored XSS in a chatter body.
text = re.sub(r'\[([^\]]+)\]\(([^)\s]+)\)', _link, text)
return Markup(text)
def _link(match):
label, url = match.group(1), match.group(2)
if not _SAFE_URL_RE.match(url):
return label
return f'{label}'
def format_tool_summary(summary, tool_call):
"""Small inline status line shown while a tool runs."""
args = tool_call.get('args') or {}
data_id = ''
if set(args) - {'tool_status', '__final_message', 'explanation'}:
data_id = f'data-id="{escape(tool_call.get("call_id"))}"'
icon = summary.get('icon', 'build')
text = escape(summary.get('text', ''))
return Markup(
'