__init__.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. """plugin-deliverable-inject — 把本轮已上云的成果链接真正写进回复正文。
  2. 背景(必须记住的坑):
  3. `hooks.transform_llm_output` 配成 **shell 脚本**时,`agent/shell_hooks.py::_parse_response`
  4. 对非 pre_tool_call / pre_verify 的事件统一走 `_parse_context`,只认 `{"context": "..."}`
  5. 并返回 **dict**;而 `agent/turn_finalizer.py::_apply_output_hooks` 只接受
  6. `isinstance(result, str) and result`。两者对不上 → shell hook 的 stdout 无论怎么写,
  7. 都**永远无法替换回复文本**。所以「追加 https」这件事只能由 Python 插件做:
  8. 插件回调返回 str 才会被 turn_finalizer 采纳(first non-None wins)。
  9. 本插件职责(只做一件事):
  10. 读 /opt/data/cache/deliverable-hook/<session>.json 里本轮已推送成功的 pushed[],
  11. 把 https 追加到回复正文末尾。上传/登记仍由 fmode-deliverable-hook.py 的
  12. post_tool_call 与 transform 阶段完成,两边通过该状态文件交接。
  13. 幂等:正文里已含该 URL 就跳过;同一 turn 重复调用不会重复追加。
  14. 开关:PLUGIN_DELIVERABLE_INJECT_DISABLE=1 关闭。
  15. """
  16. from __future__ import annotations
  17. import json
  18. import logging
  19. import os
  20. from pathlib import Path
  21. from typing import Any, List, Optional
  22. logger = logging.getLogger(__name__)
  23. STATE_DIR = Path(os.environ.get("DELIVERABLE_HOOK_STATE_DIR", "/opt/data/cache/deliverable-hook"))
  24. # 正文里绝不出现的本地路径前缀(临时防线;主清洗在 fmode-deliverable-hook.py)
  25. _LOCAL_HINTS = ("/opt/data/", "/tmp/", "/home/", "file://")
  26. # Hermes 的 MEDIA 投递扩展名白名单(与 gateway/platforms/base.py:1188 MEDIA_DELIVERY_EXTS 逐项一致)。
  27. # 写进来而不是 import: 插件运行在 gateway 进程外/不同 sys.path,且这份清单必须可独立校验。
  28. _MEDIA_DELIVERY_EXTS = frozenset({
  29. ".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".tiff", ".svg",
  30. ".mp4", ".mov", ".avi", ".mkv", ".webm", ".3gp",
  31. ".mp3", ".m2a", ".wav", ".ogg", ".opus", ".m4a", ".flac",
  32. ".pdf", ".docx", ".doc", ".odt", ".rtf", ".txt", ".md", ".epub",
  33. ".xlsx", ".xls", ".ods", ".csv", ".tsv", ".json", ".xml", ".yaml", ".yml",
  34. ".kmz", ".kml", ".geojson", ".gpx",
  35. ".pptx", ".ppt", ".odp", ".key",
  36. ".zip", ".tar", ".gz", ".tgz", ".bz2", ".xz", ".7z", ".rar", ".apk", ".ipa",
  37. ".html", ".htm",
  38. })
  39. HEADER = "**已上云(可直接下载)**"
  40. # 成果对象存储域名:只有这些域名上的链接受「必须来自本轮上传回执」约束;
  41. # 其他域名是普通参考链接(官方文档等),任何渠道都原样保留。
  42. _STORAGE_HOSTS = frozenset({"s3.fmode.cn", "file-cloud.fmode.cn"})
  43. def _storage_url(url: str) -> bool:
  44. from urllib.parse import urlsplit
  45. try:
  46. return (urlsplit(url).hostname or "").lower() in _STORAGE_HOSTS
  47. except ValueError:
  48. return False
  49. def _platform_name(kwargs: dict) -> str:
  50. """本条回复的来源渠道(matrix/wecom…);hook 未提供时返回空串,按 Matrix 旧行为处理。"""
  51. value = kwargs.get("platform")
  52. if value is None:
  53. value = getattr(kwargs.get("source"), "platform", None)
  54. value = getattr(value, "value", value)
  55. return str(value or "").strip().lower()
  56. def _disabled() -> bool:
  57. return str(os.environ.get("PLUGIN_DELIVERABLE_INJECT_DISABLE", "")).strip().lower() in {"1", "true", "yes", "on"}
  58. def _load_state(session_id: str) -> dict:
  59. """读会话状态;优先精确 session_id,其次 latest 指针。"""
  60. if not session_id:
  61. return {}
  62. p = STATE_DIR / f"{session_id}.json"
  63. try:
  64. if p.is_file():
  65. return json.loads(p.read_text(encoding="utf-8")) or {}
  66. except Exception as exc:
  67. logger.debug("deliverable-inject: state read failed (%s): %s", p, exc)
  68. return {}
  69. ROUNDS_DIR = STATE_DIR / "rounds"
  70. def _current_turn_id(session_id: str) -> str:
  71. """本轮 turn_id:由 fmode-round-marker.py 在 pre_llm_call 写入。
  72. 只读,不写 —— transform_llm_output 同轮可能被调用多次,绝不在渲染期改轮次标记。
  73. """
  74. if not session_id:
  75. return ""
  76. try:
  77. p = ROUNDS_DIR / f"{session_id}.json"
  78. if p.is_file():
  79. return str((json.loads(p.read_text(encoding="utf-8")) or {}).get("turn_id") or "").strip()
  80. except Exception as exc:
  81. logger.debug("deliverable-inject: rounds 读取失败 (%s): %s", session_id, exc)
  82. return ""
  83. def _in_current_round(item: dict, cur_turn: str) -> bool:
  84. """只认明确的本轮标识;不把旧无tag记录按时间窗注入新回复。"""
  85. tag = str(item.get("turn_id") or "").strip()
  86. return bool(cur_turn) and tag == cur_turn
  87. def _input_record(item: dict) -> bool:
  88. """历史错误台账也不能把用户输入再次注入为本轮交付成果。"""
  89. import posixpath
  90. import re
  91. from urllib.parse import unquote, urlsplit
  92. path = posixpath.normpath(str(item.get("path") or "").replace("\\", "/")) + "/"
  93. if path.startswith("/opt/data/work/uploads/"):
  94. return True
  95. try:
  96. url = urlsplit(str(item.get("url") or ""))
  97. return (url.hostname or "").lower() in {"s3.fmode.cn", "file-cloud.fmode.cn"} and bool(
  98. re.match(r"^/user/[^/]+/chat/", unquote(url.path)))
  99. except ValueError:
  100. return False
  101. def _collect_urls(state: dict, cur_turn: str = "") -> List[str]:
  102. urls: List[str] = []
  103. for item in state.get("pushed") or []:
  104. if not isinstance(item, dict) or _input_record(item):
  105. continue
  106. url = item.get("url")
  107. if not isinstance(url, str) or not url.startswith("http"):
  108. continue
  109. if not _in_current_round(item, cur_turn):
  110. continue
  111. if url not in urls:
  112. urls.append(url)
  113. return urls
  114. def _collect_pushed_paths(state: dict, cur_turn: str = "") -> List[str]:
  115. """本轮已上云的本地源文件路径(用来给 MEDIA: 行背书)。"""
  116. paths: List[str] = []
  117. for item in state.get("pushed") or []:
  118. if not isinstance(item, dict) or _input_record(item):
  119. continue
  120. path = item.get("path")
  121. if isinstance(path, str) and path and _in_current_round(item, cur_turn) and path not in paths:
  122. paths.append(path)
  123. return paths
  124. def _find_pushed_url(body_line: str, pushed: List[dict], cur_turn: str = "") -> Optional[str]:
  125. """按文件名把正文里的一条 s3 链接对到本轮 pushed 记录,返回**真实** URL。
  126. 为什么要这一步:正文里模型自己写出的 s3 链接,路径段/哈希段常常和真实上传结果
  127. 不一致(模型按 pattern 编),字面比对永远对不上,于是白名单清洗会把**整行删掉**,
  128. 用户看到「已上云(可直接下载)」下面是空的 `- `。这里改按 basename 认领:
  129. 文件名对得上 → 用真实 URL 顶替,保留链接。
  130. """
  131. import os as _os
  132. import re as _re
  133. m = _re.search(r"([\w.\-]+\.[A-Za-z0-9]{1,8})(?:$|[?#'\s)\]},。])", body_line.strip())
  134. if not m:
  135. return None
  136. name = m.group(1).lower()
  137. for item in pushed:
  138. if not isinstance(item, dict) or _input_record(item):
  139. continue
  140. url = item.get("url")
  141. path = item.get("path")
  142. if not isinstance(url, str) or not isinstance(path, str) or not url.startswith("http"):
  143. continue
  144. if not _in_current_round(item, cur_turn):
  145. continue
  146. if _os.path.basename(path).lower() == name:
  147. return url
  148. return None
  149. def _media_attachment_lines(pushed: List[dict], body: str) -> List[str]:
  150. """**已废弃的附件通道(2026-11-14 用户裁决:一次上传,一个 URL)。**
  151. 历史行为:为每个成果生成 `MEDIA:<本地源文件路径>` 行,让 gateway 的
  152. extract_media() 去发 m.file —— 但那条路会**再上传一次**,于是在 S3 上生成
  153. 第二个对象、第二个 URL,App 侧出现两张卡片(实测
  154. `.../0-mwg1ud2jlb-table.html` 与 `.../0-mwg1tu9vuj-table.html` 内容相同)。
  155. 现在规则 1 明令:插件不许触发任何上传,只复用 `pushed[].url`。
  156. 附件因此不再由 MEDIA 行产生 —— 需要 m.file 时由 outbound 侧直接拿现成 url
  157. 构造事件(见 plugin-matrix-outbound-s3 的 PREUPLOADED 复用分支)。
  158. 本函数保留但恒返回空,供 env 回滚(PLUGIN_DELIVERABLE_MEDIA_LEGACY=1)。
  159. """
  160. if str(os.environ.get("PLUGIN_DELIVERABLE_MEDIA_LEGACY", "")).strip().lower() not in {"1", "true", "yes", "on"}:
  161. return []
  162. lines: List[str] = []
  163. seen: set = set()
  164. for item in pushed:
  165. path = item.get("path") if isinstance(item, dict) else None
  166. if not isinstance(path, str) or not path.startswith("/"):
  167. continue
  168. if path in seen:
  169. continue
  170. seen.add(path)
  171. try:
  172. if not os.path.isfile(path):
  173. logger.warning("deliverable-inject: 跳过 MEDIA(源文件已不在)%s", path)
  174. continue
  175. except OSError:
  176. continue
  177. ext = os.path.splitext(path)[1].lower()
  178. if ext not in _MEDIA_DELIVERY_EXTS:
  179. logger.info("deliverable-inject: 跳过 MEDIA(扩展名不在投递白名单)%s", path)
  180. continue
  181. if f"MEDIA:{path}" in body:
  182. continue
  183. lines.append(f"MEDIA:{path}")
  184. return lines
  185. def _on_transform_llm_output(response_text: Any = None, session_id: str = "", turn_id: str = "", **kwargs: Any) -> Optional[str]:
  186. if _disabled():
  187. return None
  188. if not isinstance(response_text, str) or not response_text.strip():
  189. return None
  190. # 本条回复属于哪一轮:优先 hook 直接给的 turn_id,其次 pre_llm_call 落的 rounds 文件。
  191. cur_turn = str(turn_id or "").strip() or _current_turn_id(session_id)
  192. platform = _platform_name(kwargs)
  193. # ── 步骤 0:剥离远程 MEDIA: 标记(必须在注入之前)──
  194. # 为什么在这里而不是独立插件:plugins_dispatch.invoke_hook 对同一 hook 的多个回调
  195. # 传同一份 kwargs、只 collect 返回值(互不可见),且 turn_finalizer._apply_output_hooks
  196. # 只取第一个 non-None str。两插件无法串联,只能同回调内按序执行。
  197. # 只对 Matrix(及未标明渠道的旧调用)生效:企微等渠道的 adapter 自己消费 MEDIA 引用。
  198. original_input = response_text
  199. try:
  200. from . import media_strip # type: ignore
  201. stripped = media_strip.strip_media(response_text) if platform in ("", "matrix") else None
  202. if stripped is not None:
  203. response_text = stripped
  204. except Exception as exc:
  205. logger.warning("deliverable-inject: MEDIA 剥离失败,继续注入(%s)", exc)
  206. urls = _collect_urls(_load_state(session_id), cur_turn)
  207. pushed = [
  208. i for i in (_load_state(session_id).get("pushed") or [])
  209. if isinstance(i, dict) and not _input_record(i) and _in_current_round(i, cur_turn)
  210. ]
  211. # 防编造:成果存储域名上的非白名单链接先删掉;白名单只有一个来源 —— push 回来的真地址。
  212. # 这样「模型自己写的形似成果 URL」永远不会被当成真实链接留在正文。
  213. # 其他域名是普通参考链接,不属于成果,原样保留(2026-12-01 双渠道修订)。
  214. #
  215. # 2026-11-13 修订:字面比对会把**文件名正确、哈希段不同**的 s3 链接整行删掉,
  216. # 于是「已上云(可直接下载)」下面只剩空 `- `。改为按 basename 认领:
  217. # 对得上本轮 pushed 记录 → 用真实 URL 顶替;对不上 → 才删。
  218. import re
  219. allow = {u.rstrip("/") for u in urls}
  220. def _keep(m):
  221. raw = m.group(0)
  222. core = re.split(r"[)\],。、;:\"'`]", raw, maxsplit=1)[0].rstrip("/")
  223. if core in allow or not _storage_url(core):
  224. return raw
  225. real = _find_pushed_url(core, pushed, cur_turn)
  226. if real:
  227. logger.info("deliverable-inject: 按文件名改写真链接 %s -> %s", core[-60:], real[-60:])
  228. return real
  229. logger.warning("deliverable-inject: 删除非白名单 URL %s", core[:200])
  230. return ""
  231. text = re.sub(r"https?://[^\s<>\"'`))]+", _keep, response_text)
  232. text = re.sub(r"(?m)^[ \t]*MEDIA:[ \t]*$\n?", "", text)
  233. text = re.sub(r"\n{3,}", "\n\n", text).strip()
  234. if not urls:
  235. return text if text != original_input.strip() else None
  236. # 顺带把本地路径整行删掉(绝不留下「(本地工作目录)」这类假地址占位)
  237. # 行首可能带 ** 粗体标记,行内容也可能是文字占位而非绝对路径 —— 一律整行删。
  238. text = re.sub(
  239. r"(?m)^[ \t]*(?:\*\*|__)?[ \t]*(?:本地路径|本地文件|本地地址|存放路径|落盘路径)[ \t]*(?:\*\*|__)?[ \t]*[::][^\n]*\n?",
  240. "",
  241. text,
  242. )
  243. # MEDIA 行的处理已统一由 media_strip 在步骤 0 完成:远程 URL 剥、本地路径留。
  244. # 下面这段本地路径清洗**必须避开 MEDIA 行** —— 剥掉 `MEDIA:/opt/data/...` 等于砍掉
  245. # 附件投递锚点(hooked 到 /opt/data、/tmp 的路径都在 _LOCAL_HINTS 里,会被一并扫掉)。
  246. protected_media: List[str] = []
  247. def _park_media(m):
  248. protected_media.append(m.group(0))
  249. return f"\x00MEDIA{len(protected_media) - 1}\x00"
  250. text = re.sub(r"(?m)^[ \t]*MEDIA:[^\n]*$", _park_media, text)
  251. for hint in _LOCAL_HINTS:
  252. if hint in text:
  253. text = re.sub(r"`?" + re.escape(hint) + r"[^\s`'\"))]*`?", "", text)
  254. text = text.replace(hint, "")
  255. for idx, original_line in enumerate(protected_media):
  256. text = text.replace(f"\x00MEDIA{idx}\x00", original_line)
  257. text = re.sub(r"[((]\s*[))]", "", text)
  258. text = re.sub(r"(?m)^[ \t]*[::][ \t]*$", "", text)
  259. text = re.sub(r"\n{3,}", "\n\n", text).strip()
  260. # 幂等:真链接已在正文里 → 不动
  261. missing = [u for u in urls if u not in text]
  262. # ── 附件(2026-11-14 用户裁决:一次上传,一个 URL)──
  263. # 不再生成 `MEDIA:<本地路径>` 行 —— extract_media 会把同一份文件再上传一次,
  264. # 产生第二个 S3 对象与第二个 URL,App 显示两张卡片。正文只贴平台签发的
  265. # publicUrl,附件事件由 outbound 侧复用同一个 URL(PREUPLOADED 分支)。
  266. media_lines = _media_attachment_lines(pushed, text)
  267. if media_lines:
  268. logger.warning("deliverable-inject: 走了 LEGACY MEDIA 通道(会二次上传)%d 条", len(media_lines))
  269. if not urls and not media_lines:
  270. return text if text != original_input.strip() else None
  271. block = []
  272. if missing:
  273. block += [HEADER] + [f"- {u}" for u in missing]
  274. if media_lines:
  275. block += media_lines
  276. new_text = text + "\n\n" + "\n".join(block) if block else text
  277. logger.info("deliverable-inject: 注入 %d 条链接 / %d 条 MEDIA 附件 session=%s turn=%s",
  278. len(missing), len(media_lines), session_id, cur_turn or "-")
  279. return new_text
  280. def register(ctx) -> None:
  281. ctx.register_hook("transform_llm_output", _on_transform_llm_output)