"""Resolve product mentions against the caller's already-authorized catalogue. This module only identifies catalogue names. It does not construct queries, change filters, aggregate products, or infer results from an absent name. """ from __future__ import annotations import re import unicodedata from decimal import Decimal, InvalidOperation _DIMENSIONS = re.compile(r'(? limit, **({'intent':'exclude'} if excluded else {})}) for (start, end), candidate_set in sorted(prefix_by_span.items()): candidates = sorted(candidate_set) excluded = exclusion_for_span(start) if excluded: excluded_names.update(candidates) full_candidates_by_span[(start, end)] = candidates mentions.append({'query': text[start:end], 'normalizedSpan': [start, end], 'status': 'ambiguous' if len(candidates) > 1 else 'unique', 'candidates': records(candidates), 'candidateCount': len(candidates), 'truncated': len(candidates) > limit, 'matchType': 'catalog_prefix', **({'intent':'exclude'} if excluded else {})}) if respect_exclusions: positive = [] for mention in mentions: if mention.get('intent') == 'exclude': continue original = full_candidates_by_span[tuple(mention['normalizedSpan'])] kept = [name for name in original if name not in excluded_names] status = mention['status'] if kept == original else 'unique' if len(kept)==1 else 'ambiguous' if kept else 'none' positive.append({**mention,'candidates':records(kept),'candidateCount':len(kept), 'truncated':len(kept)>limit,'status':status}) effective_mentions = positive else: effective_mentions = mentions if not mentions and exact: selected = sorted(exact) mentions = [{'query': '', 'status': 'exact' if len(selected) == 1 else 'multiple', 'candidates': records(selected), 'candidateCount': len(selected), 'truncated': len(selected) > limit}] effective_mentions = mentions if not effective_mentions: match = {'query': '', 'status': 'none', 'candidates': [], 'candidateCount': 0, 'truncated': False} elif len(effective_mentions) == 1: match = dict(effective_mentions[0]) else: selected = sorted({entry['name'] for mention in effective_mentions for entry in mention['candidates']}) match = {'query': '', 'status': 'ambiguous' if any(m['status'] == 'ambiguous' for m in effective_mentions) else 'multiple', 'candidates': records(selected), 'candidateCount': len(selected), 'truncated': any(m['truncated'] for m in mentions) or len(selected) > limit} match['mentions'] = mentions return {'mentionedProducts': sorted(exact)[:limit], 'productMatch': match, **({'explicitlyExcludedProducts':sorted(excluded_names)} if respect_exclusions else {})} def authorized_extra_fields(catalog): """Extract only field metadata returned by the actor-scoped API catalog.""" if not isinstance(catalog, dict) or catalog.get('kind') != 'analysis_catalog' or not isinstance(catalog.get('extraFields'), list): return {'extraFieldsStatus': 'unavailable', 'extraFields': []} fields = [] for item in catalog['extraFields']: if not isinstance(item, dict) or item.get('enabled') is False: continue key, label = item.get('key'), item.get('label') if (not isinstance(key, str) or not re.fullmatch(r'[A-Za-z][A-Za-z0-9_]{0,63}', key) or not isinstance(label, str) or not label.strip() or len(label) > 80): continue fields.append({'key': key, 'label': label.strip()}) return {'extraFieldsStatus': 'ready', 'extraFields': fields} def resolve_clarification_choice(question, options, previous_task): """Resolve a short suffix selection only within the saved pending choices. The caller must supply the prior task from the same authorized session and release, and current options must come from the permission-filtered API. ``None`` means the reply did not unambiguously select a saved candidate. """ if not isinstance(previous_task, dict): return None pending = previous_task.get('productResolution') if not isinstance(pending, dict) or not isinstance(pending.get('originalQuestion'), str): return None # Once a choice has been planned, restore it only for the same short reply # on retry. Never attach a previously selected product to a new question. is_pending = previous_task.get('needsClarification') is True if not is_pending: if (not isinstance(pending.get('selectedName'), str) or not isinstance(pending.get('selectionQuestion'), str) or _normalized(question) != _normalized(pending['selectionQuestion'])): return None previous_match = pending.get('productMatch') if (not isinstance(previous_match, dict) or previous_match.get('status') != 'ambiguous' or previous_match.get('truncated') is not False): return None entries = previous_match.get('candidates') if not isinstance(entries, list) or type(previous_match.get('candidateCount')) is not int: return None names = [item.get('name') for item in entries if isinstance(item, dict) and isinstance(item.get('name'), str)] if len(names) != len(entries) or len(set(names)) != len(names) or len(names) != previous_match['candidateCount']: return None # A short explicit selection only; unrelated follow-ups or requests for # multiple variants do not silently reuse an old pending clarification. reply = str(question).strip() ui_prefix = '继续上一轮分析,保留未修改的原目标和条件。\n我的选择:' if reply.startswith(ui_prefix): reply = reply[len(ui_prefix):].strip() text = _normalized(reply) full_reply = re.sub(r'^(?:我想选|我选择|我选|我要|选择|查看|分析|选|看|用)', '', text) full_reply = re.sub(r'(?:这个|那个|这款|那款|的|规格|产品|型号|即可|吧|[。!?.!?])+$', '', full_reply) full_names = [name for name in names if _normalized(name) == full_reply] choice = re.fullmatch(r'(?:我想选|我选择|我选|我要|选|选择|查看|分析|看|用)?\+?([a-z0-9][a-z0-9_-]{0,19})(?:这个|那个|这款|那款|的|规格|产品|型号|即可|吧|[。!?.!?])*', text) if not choice and len(full_names) != 1: return None token = choice.group(1) if choice else None available = options.get('products') if isinstance(options, dict) else None if not isinstance(available, list): return None authorized = {item for item in available if isinstance(item, str)} selected = [] for name in names: if name not in authorized: continue suffix = re.search(r'\+([a-z0-9][a-z0-9_-]{0,19})$', _normalized(name)) if name in full_names or suffix and suffix.group(1) == token: selected.append(name) if len(selected) != 1: return None if not is_pending and selected[0] != pending['selectedName']: return None result = identify_products(selected[0], options) match = result['productMatch'] if (match['status'] != 'exact' or match['candidateCount'] != 1 or match['candidates'][0]['name'] != selected[0]): return None match['selectedFromClarification'] = True match['previousQuestion'] = pending['originalQuestion'] match['previousQuery'] = previous_match.get('query', '') return result