# -*- 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'
{stripped}
') index += 1 continue # ---- horizontal rule ------------------------------------------ if _HR_RE.match(stripped): out.append('
') index += 1 continue # ---- heading --------------------------------------------------- heading = _HEADING_RE.match(stripped) if heading: level = len(heading.group(1)) out.append( f'{_inline_md(heading.group(2), escape)}' ) index += 1 continue # ---- bullet list ----------------------------------------------- if _UNORDERED_RE.match(stripped): html, index = _render_list(lines, index, _UNORDERED_RE, 'ul', escape) out.append(html) continue # ---- ordered list ---------------------------------------------- if _ORDERED_RE.match(stripped): html, index = _render_list(lines, index, _ORDERED_RE, 'ol', escape) out.append(html) continue # ---- block quote ----------------------------------------------- if _QUOTE_RE.match(stripped): quoted = [] while index < total: match = _QUOTE_RE.match(lines[index].strip()) if not match: break quoted.append(_inline_md(match.group(1), escape)) index += 1 out.append(f'
{"
".join(quoted)}
') 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(paragraph)}

') html = '\n'.join(out) for key, value in placeholders.items(): html = html.replace(key, value) return Markup(html) def _starts_block(lines, index): """True when ``lines[index]`` opens a block that must end a paragraph.""" stripped = lines[index].strip() if not stripped: return True if stripped.startswith('\x00') and stripped.endswith('\x00'): return True return bool( _HR_RE.match(stripped) or _HEADING_RE.match(stripped) or _UNORDERED_RE.match(stripped) or _ORDERED_RE.match(stripped) or _QUOTE_RE.match(stripped) or ('|' in stripped and _table_separator(lines, index)) ) def _table_separator(lines, index): """Return the alignment list when a table starts at ``index``, else None.""" if index + 1 >= len(lines): return None header = lines[index].strip() separator = lines[index + 1].strip() if '|' not in header or '|' not in separator: return None cells = _split_table_row(separator) if not cells or not all(_TABLE_SEP_RE.match(cell) for cell in cells): return None if len(cells) != len(_split_table_row(header)): return None alignments = [] for cell in cells: left = cell.startswith(':') right = cell.endswith(':') if left and right: alignments.append('center') elif right: alignments.append('right') elif left: alignments.append('left') else: alignments.append('') return alignments def _split_table_row(line): """Split one table row into stripped cells. Leading/trailing pipes are optional (GFM allows both), and ``\\|`` is an escaped pipe that belongs to the cell content rather than the row. """ row = line.strip().replace('\\|', '\x01') if row.startswith('|'): row = row[1:] if row.endswith('|'): row = row[:-1] return [cell.strip().replace('\x01', '|') for cell in row.split('|')] def _render_table(lines, index, escape): """Render a GFM table starting at ``index``; return ``(html, next_index)``.""" alignments = _table_separator(lines, index) or [] headers = _split_table_row(lines[index]) rows = [] cursor = index + 2 while cursor < len(lines): stripped = lines[cursor].strip() # A blank line or anything without a pipe ends the table: without this # a trailing "合计:128.00" line would be swallowed as a one-cell row. if not stripped or '|' not in stripped: break rows.append(_split_table_row(stripped)) cursor += 1 def cell(value, tag, column): alignment = alignments[column] if column < len(alignments) else '' style = f' style="text-align: {alignment}"' if alignment else '' return f'<{tag}{style}>{_inline_md(value, escape)}' head = ''.join(cell(value, 'th', column) for column, value in enumerate(headers)) body = ''.join( '' + ''.join( cell(value, 'td', column) for column, value in enumerate(row) ) + '' for row in rows ) html = ( '
' '' f'{head}' f'{body}' '
' ) return html, cursor def _render_list(lines, index, pattern, tag, escape): """Render a consecutive run of list items; return ``(html, next_index)``.""" items = [] while index < len(lines): match = pattern.match(lines[index].strip()) if not match: break items.append(_inline_md(match.groups()[-1], escape)) index += 1 body = ''.join(f'
  • {item}
  • ' for item in items) return f'<{tag}>{body}', index def _inline_md(text, escape): text = str(escape(text)) text = re.sub(r'`([^`]+)`', r'\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( '
    %s
    ' ) % (Markup(data_id), icon, text) # --------------------------------------------------------------------------- # previews # --------------------------------------------------------------------------- def coerce_domain(domain): """Accept a domain as JSON string, python literal or list.""" if domain in (None, ''): return [] if isinstance(domain, str): try: parsed = json.loads(domain) except ValueError: parsed = ast.literal_eval(domain) return parsed return domain