/** * features/chat/shipping/shippingText.ts * 用途:发货聊天消息文本净化与 HTML 动作指令解析(纯函数,无 Vue 依赖)。 * 依赖:constants/shippingNoticeActions、types/shipping.types。 * 逻辑:ChatView 渲染前 sanitize;shippingMenu 解析 注释块。 */ import { SHIPPING_INTERNAL_STATUS_TOKENS, SHIPPING_KNOWN_ACTION_ID_SET } from '@/constants/shippingNoticeActions'; import type { ShippingActionButton, ShippingActionVariant } from '../types/shipping.types'; /** * 文本归一化用于判断 Agent 正文编号项是否重复描述了结构化按钮。 */ const normalizeActionComparableText = (value: string) => String(value || '') .toLowerCase() .replace(/[\s`"'“”‘’《》〈〉()()[\]{}【】|::,,.。;;、\-—_!?!?/\\]+/g, ''); const isNumberedActionLine = (line: string) => /^\s*(?:[-*]\s*)?[1-91-9][\.\、\)::]\s*/.test(line); const isActionListContextLine = (line: string) => /(?:请选择操作|选择操作|操作选项|按钮)/.test(line); const isActionListTailLine = (line: string) => /(?:选择哪|希望.*(?:处理|执行|操作)|要.*哪一项|点击.*按钮)/.test(line); const isShippingActionListContextLine = (line: string) => /(?:请选择操作|选择操作|操作选项|下方按钮|按钮继续操作|以下.*方式|任一方式|库存上传|提供当前库存|提供.*库存数据)/.test(line); const isShippingActionChoiceLine = (line: string) => /(?:选择库存文件|上传库存|粘贴库存|重试\s*RPA|修改映射|确认字段|继续处理|查看卡点|返回修订|重新匹配|重试当前步骤|切换为当前任务|确认|驳回|重新解析)/i.test(line); const isPlainActionMenuLine = (line: string) => /^\s*(?:[-*]\s*)?(?:\*\*)?(?:确认|驳回|重新解析|更正映射|重新匹配|继续处理|重试当前步骤|选择库存文件|上传库存|粘贴库存)(?:\*\*)?\s*(?:[-—-::]|$)/.test(line); /** * 移除 Agent 正文里重复描述按钮的 1/2/3 编号动作列表。 * * 这些动作已经由结构化按钮承载,正文再展示会显得像提示词/后端兜底泄漏。 * 为避免误删订单行,只在“按钮/库存/操作方式”上下文中,且编号行命中动作词时移除。 */ export function stripShippingRedundantNumberedActionList(text: string): string { const lines = String(text || '').split('\n'); const remove = new Set(); for (let index = 0; index < lines.length; index += 1) { if (!isNumberedActionLine(lines[index] || '')) continue; const block: number[] = []; let cursor = index; while (cursor < lines.length && isNumberedActionLine(lines[cursor] || '')) { block.push(cursor); cursor += 1; } const actionLineCount = block.filter((lineIndex) => isShippingActionChoiceLine(lines[lineIndex] || '')).length; if (block.length < 2 || actionLineCount === 0) { index = cursor - 1; continue; } const nearbyStart = Math.max(0, index - 3); const nearbyEnd = Math.min(lines.length - 1, cursor + 2); const hasActionContext = lines .slice(nearbyStart, nearbyEnd + 1) .some((line) => isShippingActionListContextLine(line)); if (!hasActionContext) { index = cursor - 1; continue; } block.forEach((lineIndex) => remove.add(lineIndex)); for (let before = index - 1; before >= nearbyStart; before -= 1) { const line = lines[before] || ''; if (!line.trim() || isShippingActionListContextLine(line)) { remove.add(before); continue; } break; } for (let after = cursor; after <= nearbyEnd; after += 1) { const line = lines[after] || ''; if (!line.trim() || isShippingActionListContextLine(line)) { remove.add(after); continue; } break; } index = cursor - 1; } return lines .filter((_, index) => !remove.has(index)) .join('\n') .replace(/\n{3,}/g, '\n\n') .trim(); } /** * 移除 Agent 正文中手写的操作菜单段落。 * * 核心逻辑:结构化按钮已经由系统渲染,正文里再写“请使用下方按钮/确认/驳回/重新解析” * 会形成两套入口。只删除明确处在按钮/操作上下文附近的菜单行,避免误删普通业务说明。 */ export function stripShippingPlainActionMenu(text: string): string { const lines = String(text || '').split('\n'); const remove = new Set(); lines.forEach((line, index) => { if (!isPlainActionMenuLine(line)) return; const nearby = lines.slice(Math.max(0, index - 4), Math.min(lines.length, index + 4)); const hasContext = nearby.some((item) => isShippingActionListContextLine(item) || /(?:按钮|确认操作|进行确认操作|操作$)/.test(item)); if (!hasContext) return; remove.add(index); for (let before = index - 1; before >= 0 && before >= index - 4; before -= 1) { const prev = lines[before] || ''; if (!prev.trim() || isShippingActionListContextLine(prev) || /(?:按钮|确认操作|进行确认操作|操作$)/.test(prev)) { remove.add(before); continue; } break; } }); return lines .filter((_, index) => !remove.has(index)) .join('\n') .replace(/\n{3,}/g, '\n\n') .trim(); } /** * 根据后端 action_buttons 移除 Agent 正文中重复生成的编号操作列表。 * * 核心逻辑:不写死具体按钮文案;只在编号行命中当前 action_buttons 的 label/message 时移除, * 并顺带移除相邻的“请选择操作”类上下文行。正常新链路不应依赖本兜底。 */ export function stripShippingActionListByButtons( text: string, buttons: Array> | null | undefined, ): string { const source = String(text || ''); const normalizedActions = (buttons || []) .flatMap((button) => [button.label, button.message]) .map((item) => normalizeActionComparableText(String(item || ''))) .filter((item) => item.length >= 2); if (!normalizedActions.length) return source; const lines = source.split('\n'); const remove = new Set(); lines.forEach((line, index) => { if (!isNumberedActionLine(line)) return; const normalizedLine = normalizeActionComparableText(line); if (normalizedActions.some((action) => normalizedLine.includes(action) || action.includes(normalizedLine))) { remove.add(index); } }); if (!remove.size) return source; for (const index of Array.from(remove)) { for (let cursor = index - 1; cursor >= 0 && cursor >= index - 3; cursor -= 1) { const line = lines[cursor] || ''; if (!line.trim()) { remove.add(cursor); continue; } if (isActionListContextLine(line)) { remove.add(cursor); continue; } break; } for (let cursor = index + 1; cursor < lines.length && cursor <= index + 3; cursor += 1) { const line = lines[cursor] || ''; if (!line.trim()) { remove.add(cursor); continue; } if (isNumberedActionLine(line)) continue; if (isActionListTailLine(line)) { remove.add(cursor); continue; } break; } } return stripShippingRedundantNumberedActionList(lines .filter((_, index) => !remove.has(index)) .join('\n') .replace(/\n{3,}/g, '\n\n') .trim()); } /** * 隐藏 Agent 回复中的内部状态 token,并将 task_id 统一为「任务编号」展示。 */ export function sanitizeShippingConversationText(text: string, enabled: boolean): string { if (!enabled) return text; let result = String(text || '') .replace( /已回到列映射步骤。?请根据\s*schema_preview\s*提供新的\s*map_json\s*[,,]\s*再调用\s*(?:应用库存字段映射|apply_inventory_mapping)[^。.\n]*[。.]?/gi, '已回到库存字段确认步骤。请检查系统识别的库存列名,确认无误后继续;如有问题请修改映射。', ) .replace( /请根据\s*schema_preview\s*提供新的\s*map_json\s*[,,]\s*再调用\s*(?:应用库存字段映射|apply_inventory_mapping)[^。.\n]*[。.]?/gi, '请检查系统识别的库存列名,确认无误后继续;如有问题请修改映射。', ) .replace( /根据\s*data\.schema_preview\.headers\s*与\s*sample_rows\s*推断\s*JSON[^。.\n]*再调用\s*(?:应用库存字段映射|apply_inventory_mapping)[^。.\n]*[。.]?/gi, '请根据库存表头和样例行确认字段对应关系。', ) .replace(/通过\s*(?:Hxops|HXOPS|hxops)\s*聊天区上传/gi, '在当前对话中上传') .replace(/在\s*(?:Hxops|HXOPS|hxops)\s*聊天区上传/gi, '在当前对话中上传') .replace(/(?:Hxops|HXOPS|hxops)\s*聊天区/gi, '当前对话') .replace(/(?:Hxops|HXOPS|hxops)\s*Chat/gi, '当前对话') .replace(/到\s*(?:Hxops|HXOPS|hxops)(\s*[??])?/gi, '到当前对话$1') .replace(/\b(?:Hxops|HXOPS|hxops)\b/g, '当前系统') .replace(/\btask_id\s*[::]/gi, '任务编号:') .replace(/\btask_id\b/gi, '任务编号'); result = result .replace(/\bcreate_task\b/gi, '新建任务') .replace(/\bget_task_status\b/gi, '查询任务状态') .replace(/\bparse_notice\b/gi, '解析发货通知') .replace(/\bsubmit_decision\b/gi, '提交处理结果') .replace(/\bmatch_inventory\b/gi, '匹配库存') .replace(/\bgenerate_excel\b/gi, '生成发货 Excel') .replace(/\bgenerate_shipment_excel\b/gi, '生成发货 Excel') .replace(/\bupload_to_freight\b/gi, '上传货代系统') .replace(/\bapply_inventory_mapping\b/gi, '应用库存字段映射') .replace(/\bget_inventory_schema_preview\b/gi, '读取库存表头预览') .replace(/\bschema_preview(?:\.headers)?\b/gi, '库存表头预览') .replace(/\bdata\.库存表头预览\b/gi, '库存表头预览') .replace(/\bmap_json\b/gi, '字段映射') .replace(/\bsample_rows\b/gi, '样例行') .replace(/\bretry_rpa\b/gi, '重试库存抓取') .replace(/\bretry_upload\b/gi, '重试上传货代') .replace(/\bstructured\b/gi, '结构化内容') .replace(/\braw_text\b/gi, '通知原文'); result = result.replace(/[((]\s*显示\s*[「"'`][^"'`]+[」"'`]\s*[))]/g, ''); result = result.replace( /\b(process_status|pending_human_reason|review_status|checkpoint|match_status|human_options)\s*[::=]\s*[「"'`]?[\w.-]+[「"'`]?/gi, '', ); for (const token of SHIPPING_INTERNAL_STATUS_TOKENS) { const quoted = new RegExp(`[「"'“”‘’]\\s*${token}\\s*[」"'“”‘’]`, 'gi'); result = result.replace(quoted, ''); result = result.replace(new RegExp(`\`${token}\``, 'gi'), ''); } return stripShippingPlainActionMenu(stripShippingRedundantNumberedActionList(result.replace(/\n{3,}/g, '\n\n').trim())); } /** * 解析消息中的 HXOPS_SHIPPING_ACTIONS HTML 注释,提取 action_buttons 并返回净化后文本。 */ export function extractShippingActionsDirective(rawText: string): { cleanedText: string; buttons: ShippingActionButton[]; } { const text = String(rawText || ''); const re = //gi; const buttons: ShippingActionButton[] = []; for (;;) { const m = re.exec(text); if (!m) break; const body = String(m[1] || '').trim(); if (!body) continue; try { const parsed = JSON.parse(body); if (Array.isArray(parsed)) { for (const item of parsed) { if (!item || typeof item !== 'object') continue; const id = String((item as Record).id || '').trim(); const label = String((item as Record).label || '').trim(); const message = String((item as Record).message || '').trim(); const variantRaw = String((item as Record).variant || '').trim(); const variant: ShippingActionVariant | undefined = (variantRaw === 'primary' || variantRaw === 'secondary' || variantRaw === 'danger') ? (variantRaw as ShippingActionVariant) : undefined; if (!id || !label || !message) continue; if (!SHIPPING_KNOWN_ACTION_ID_SET.has(id)) { console.warn(`[shipping] unknown action id in HXOPS_SHIPPING_ACTIONS: ${id}`); } buttons.push({ id, label, message, variant }); } } } catch { // ignore malformed directive } } const cleaned = text.replace(re, '').trim(); return { cleanedText: cleaned, buttons }; } /** * 库存表头列名展示规范化(空格转 NBSP,避免 Markdown 表格换行)。 */ export function normalizeShippingHeaderForDisplay(raw: unknown): string { const text = String(raw ?? '').replace(/\s+/g, ' ').trim(); return text.replace(/ /g, '\u00A0'); }