|
@@ -0,0 +1,1626 @@
|
|
|
|
|
+#!/usr/bin/env python3
|
|
|
|
|
+"""fmode-deliverable-hook.py — 交付成果自动上云 + 自动登记成果表
|
|
|
|
|
+
|
|
|
|
|
+被 Hermes 的两个 shell hook 事件调用:
|
|
|
|
|
+ post_tool_call 写文件类工具跑完后,判断该文件是不是「交付成果」,是则排队
|
|
|
|
|
+ transform_llm_output 回复生成后、发送前,把本轮排队的成果真正上传 + 登记,并把 https 追加进回复
|
|
|
|
|
+
|
|
|
|
|
+判定核心(成果 vs 过程缓存)见 RULES_DOC(就在本文件里,是唯一事实源)。
|
|
|
|
|
+不确定就不传:默认 DENY,只有命中「白名单扩展名 + 非缓存目录 + 非缓存文件名特征」才放行,
|
|
|
|
|
+或者模型/用户显式打标(DELIVERABLE_MARK 目录)。
|
|
|
|
|
+
|
|
|
|
|
+状态文件(每个 session 一份,按 session_id 隔离):
|
|
|
|
|
+ /opt/data/cache/deliverable-hook/<session_id>.json
|
|
|
|
|
+ {"queued": [{path, tool, ts, title?, reason?}], "pushed": [{path,url,did,ts}], "seen": [...]}
|
|
|
|
|
+"""
|
|
|
|
|
+from __future__ import annotations
|
|
|
|
|
+
|
|
|
|
|
+import fnmatch
|
|
|
|
|
+import hashlib
|
|
|
|
|
+import importlib.util
|
|
|
|
|
+import json
|
|
|
|
|
+import os
|
|
|
|
|
+import re
|
|
|
|
|
+import subprocess
|
|
|
|
|
+import sys
|
|
|
|
|
+import time
|
|
|
|
|
+from pathlib import Path
|
|
|
|
|
+
|
|
|
|
|
+HOME = Path("/opt/data")
|
|
|
|
|
+CACHE_DIR = HOME / "cache" / "deliverable-hook"
|
|
|
|
|
+LEDGER = HOME / "cache" / "deliverable-hook" / "ledger.jsonl"
|
|
|
|
|
+LOG = HOME / "cache" / "deliverable-hook" / "hook.log"
|
|
|
|
|
+PUSH_SCRIPT = HOME / "scripts" / "fmode-artifact-push.py"
|
|
|
|
|
+
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+# 判定规则(唯一事实源,SOUL.md 里的表述必须与本段一致)
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+RULES_DOC = """
|
|
|
|
|
+交付成果(要上云 + 登记成果表)必须同时满足 A、B、C 三条:
|
|
|
|
|
+ A. 扩展名属于成果白名单:
|
|
|
|
|
+ .html .htm .pdf .docx .doc .xlsx .xls .pptx .ppt .csv .json .md .txt .zip
|
|
|
|
|
+ .png .jpg .jpeg .webp .svg .gif .mp4 .mp3 .m4a .wav
|
|
|
|
|
+ B. 不在过程缓存目录 / 系统目录(任一命中即拒绝):
|
|
|
|
|
+ /tmp/** /var/tmp/** /root/** .cache /cache/ node_modules/ .venv*/
|
|
|
|
|
+ venv/ __pycache__/ .git/ site-packages/ /opt/data/logs/ /opt/data/cron/output/
|
|
|
|
|
+ 以及 /opt/data/work/**/node_modules/** 这类嵌套
|
|
|
|
|
+ **系统文件区(绝不是用户的交付成果)**:
|
|
|
|
|
+ /opt/data/skills/** 技能定义(SKILL.md 等)——agent 自己的知识库
|
|
|
|
|
+ /opt/data/git-repos/** git 工作区
|
|
|
|
|
+ /opt/data/scripts/** agent 自己的运维脚本
|
|
|
|
|
+ /opt/data/plugins/** agent 自己的插件代码
|
|
|
|
|
+ /opt/data/config.yaml etc. 配置文件
|
|
|
|
|
+ /opt/data/.env 等 dotfile 凭据
|
|
|
|
|
+ /opt/data/memories/** 记忆文件
|
|
|
|
|
+ /opt/data/cron/** 定时任务定义
|
|
|
|
|
+ /opt/data/cache/** 各类缓存
|
|
|
|
|
+ C. 文件名不含过程缓存特征(任一命中即拒绝):
|
|
|
|
|
+ *.bak* *.tmp *.temp *.pyc *.pyo *~ .DS_Store
|
|
|
|
|
+ 前缀/子串:tmp- temp- test- probe- debug- scratch- ._ .nfs
|
|
|
|
|
+ 正则:^(a|b|c|d)-result-.*\\.md$ (当天回归测试产物)
|
|
|
|
|
+ ^.*(-test|\\.test|\\.spec)\\.(py|js|mjs|ts)$
|
|
|
|
|
+除上述规则外,以下任一情况直接视为交付成果(显式打标,优先于 B/C,但**不能**绕过系统文件闸门):
|
|
|
|
|
+ D1. 写在标记目录里:/opt/data/work/deliverables/**(模型显式选择放这里)
|
|
|
|
|
+ D2. 路径出现在本轮 tool_input 的显式标记里(见 MARK_KEYS)
|
|
|
|
|
+**系统闸门最高优先**:/opt/data/skills/、/opt/data/git-repos/、/opt/data/scripts/、
|
|
|
|
|
+/opt/data/plugins/、/opt/data/memories/、/opt/data/cron/、/opt/data/cache/、
|
|
|
|
|
+/opt/data/profiles/、.env/config.* 等点文件,无论是否落在 D1/D2,一律不上云。
|
|
|
|
|
+反向:命中任一即一定不上云(黑名单先于白名单)
|
|
|
|
|
+ E1. 文本里出现 [cache-only] / #cache-only / CACHE_ONLY=1
|
|
|
|
|
+ E2. 文件大小 > 40MB(聊天通道与成果表都放不下,走 bigfile 网关另说)
|
|
|
|
|
+"""
|
|
|
|
|
+
|
|
|
|
|
+MARK_KEYS = ("deliverable", "is_deliverable", "deliverables", "attach", "attachments")
|
|
|
|
|
+MARK_DIRS = ("/opt/data/work/deliverables/",)
|
|
|
|
|
+
|
|
|
|
|
+# C-2:上传并回读 md5 一致后删除本地源文件(用户本地空间有限,文件以云端为准)
|
|
|
|
|
+CLEANUP_LOCAL = True
|
|
|
|
|
+
|
|
|
|
|
+EXT_ALLOW = {
|
|
|
|
|
+ ".html", ".htm", ".pdf", ".docx", ".doc", ".xlsx", ".xls", ".pptx", ".ppt",
|
|
|
|
|
+ ".csv", ".json", ".md", ".txt", ".zip", ".log",
|
|
|
|
|
+ ".png", ".jpg", ".jpeg", ".webp", ".svg", ".gif",
|
|
|
|
|
+ ".mp4", ".mp3", ".m4a", ".wav",
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+DIR_DENY_SUBSTR = (
|
|
|
|
|
+ "/tmp/", "/var/tmp/", "/root/", "/.cache/", "/cache/", "/node_modules/",
|
|
|
|
|
+ "/.venv", "/venv/", "/__pycache__/", "/.git/", "/site-packages/",
|
|
|
|
|
+ "/opt/data/logs/", "/opt/data/cron/output/", "/.fmode/", "/.claude/",
|
|
|
|
|
+ # Hermes/gateway 自己的状态目录(衍生状态文件不交付)
|
|
|
|
|
+ "/opt/data/state/", "/opt/data/sessions/", "/cache/deliverable-hook/",
|
|
|
|
|
+)
|
|
|
|
|
+
|
|
|
|
|
+# 系统文件区:agent 自身的知识库/脚本/配置,永远不是「用户的交付成果」。
|
|
|
|
|
+# 前缀匹配(以 / 结尾),先于白名单检查。
|
|
|
|
|
+SYSTEM_PREFIX_DENY = (
|
|
|
|
|
+ "/opt/data/skills/", # 技能定义(SKILL.md、references、scripts…)
|
|
|
|
|
+ "/opt/data/git-repos/", # git 工作区
|
|
|
|
|
+ "/opt/data/scripts/", # 运维脚本
|
|
|
|
|
+ "/opt/data/plugins/", # 插件代码
|
|
|
|
|
+ "/opt/data/memories/", # 记忆文件
|
|
|
|
|
+ "/opt/data/cron/", # 定时任务定义与产物(含已存在的 /opt/data/cron/output/)
|
|
|
|
|
+ "/opt/data/cache/", # 各类缓存
|
|
|
|
|
+ "/opt/data/profiles/", # 其它 profile 的配置
|
|
|
|
|
+ "/opt/data/shell-hooks-allowlist.json",
|
|
|
|
|
+)
|
|
|
|
|
+
|
|
|
|
|
+# 系统配置文件(精确名,含 dotfile 凭据)
|
|
|
|
|
+# 注意:config.json 已从这里移除 —— 它是用户极常见的交付格式(「给我一个 JSON 配置文件」),
|
|
|
|
|
+# 按名字一刀切会把用户明确要的成果拦掉。Hermes 自己的配置只住在 HOME 根,
|
|
|
|
|
+# 由下面的 SYSTEM_CONFIG_ROOT_ONLY 只在 HOME 根拦截。
|
|
|
|
|
+SYSTEM_FILE_DENY = {
|
|
|
|
|
+ ".env", ".env.local", ".env.production",
|
|
|
|
|
+ "config.yaml", "config.yml", "config.toml",
|
|
|
|
|
+ "SOUL.md", "MEMORY.md", "USER.md", "AGENTS.md", "CLAUDE.md",
|
|
|
|
|
+ "shell-hooks-allowlist.json",
|
|
|
|
|
+}
|
|
|
|
|
+
|
|
|
|
|
+# 这两个名字只在 HOME 根(= /opt/data/)算系统文件:用户在家目录外任意位置生成
|
|
|
|
|
+# 名为 config.json 的交付物都是正当成果(2026-11-18 事故:用户要 3 个文件,
|
|
|
|
|
+# config.json 被 internal-file(config.json) 挡掉,只上云 2 个)。
|
|
|
|
|
+SYSTEM_CONFIG_ROOT_ONLY = {"config.json"}
|
|
|
|
|
+
|
|
|
|
|
+# 系统文件名(无论在哪个目录,出现在 agent 家目录区域都拒)
|
|
|
|
|
+SYSTEM_NAME_DENY = {"skill.md"}
|
|
|
|
|
+
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+# 内部运行时/状态文件黑名单(glob,按 basename 小写匹配)
|
|
|
|
|
+#
|
|
|
|
|
+# 为什么需要它:Hermes 自己会把运行态写到 $HERMES_HOME(= /opt/data)根目录下,
|
|
|
|
|
+# channel_directory.json ← gateway/channel_directory.py 每 5 分钟刷新
|
|
|
|
|
+# gateway_state.json ← service_manager / gateway 心跳
|
|
|
|
|
+# state.db / sessions/… ← 会话库
|
|
|
|
|
+# 这些文件 mtime 随时在动,而 fallback sweep 是按 mtime 兜底的 → 会被当成
|
|
|
|
|
+# 「本轮新产出的成果」入队、上传、并出现在「已上云」清单里。
|
|
|
|
|
+# 用户要的是「我让生成的文件」,不是容器自己的运行时快照。
|
|
|
|
|
+#
|
|
|
|
|
+# 黑名单先于一切白名单(连 MARK_DIRS 显式打标都不许绕过)。
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+INTERNAL_NAME_GLOB = (
|
|
|
|
|
+ "channel-directory.json",
|
|
|
|
|
+ "channel_directory.json",
|
|
|
|
|
+ "channel-aliases.json",
|
|
|
|
|
+ "channel_aliases.json",
|
|
|
|
|
+ "gateway-state.json",
|
|
|
|
|
+ "gateway_state.json",
|
|
|
|
|
+ "processes.json",
|
|
|
|
|
+ "sessions.json",
|
|
|
|
|
+ "matrix_threads.json",
|
|
|
|
|
+ "*.state.json",
|
|
|
|
|
+ "state.db",
|
|
|
|
|
+ "*.db",
|
|
|
|
|
+ "*.db-wal",
|
|
|
|
|
+ "*.db-shm",
|
|
|
|
|
+ "*.db-journal",
|
|
|
|
|
+ "*.sqlite",
|
|
|
|
|
+ "*.sqlite3",
|
|
|
|
|
+ "*.sqlite-*",
|
|
|
|
|
+)
|
|
|
|
|
+
|
|
|
|
|
+# 家目录根下的运行时状态目录(绝对路径前缀)
|
|
|
|
|
+STATE_DIR_DENY = (
|
|
|
|
|
+ "/opt/data/state/",
|
|
|
|
|
+ "/opt/data/sessions/",
|
|
|
|
|
+ "/opt/data/work/uploads/", # 原始用户输入不是容器交付成果;先于显式标记拦截。
|
|
|
|
|
+)
|
|
|
|
|
+
|
|
|
|
|
+# 只挡「临时/备份」文件。*.log 不在这里 —— 日志是用户可能要的正常产物
|
|
|
|
|
+# (2026-11-17 用户裁决:第 2 轮就是 5.log 被 *.log 挡掉 → pushed[] 为空 → 附件丢失)。
|
|
|
|
|
+NAME_DENY_GLOB = ("*.tmp", "*.temp", "*.bak*", "*.pyc", "*.pyo", "*~", ".DS_Store", "*.part", "*.swp")
|
|
|
|
|
+NAME_DENY_SUBSTR = ("tmp-", "temp-", "test-", "probe-", "scratch-", "._", ".nfs", "poor_guard")
|
|
|
|
|
+NAME_DENY_RE = (
|
|
|
|
|
+ re.compile(r"^(a|b|c|d|e)-result-.*\.md$", re.I),
|
|
|
|
|
+ re.compile(r".*(-test|\.test|\.spec)\.(py|js|mjs|ts|sh)$", re.I),
|
|
|
|
|
+)
|
|
|
|
|
+
|
|
|
|
|
+# 中间产物(生成过程的素材/脚本),**不是**用户要的交付物,一律不推云、不进链接块。
|
|
|
|
|
+# 2026-11-11 用户裁决:data.json 被当成成果列进交付清单 → 清单里出现用户没要的文件。
|
|
|
|
|
+# 只挡明确的「构建期素材」命名,不误伤用户真的要的 data.csv / report.json 这类成品。
|
|
|
|
|
+INTERMEDIATE_GLOB = (
|
|
|
|
|
+ # 中间数据 / 中转文件
|
|
|
|
|
+ "data.json", "tmp*.json", "temp*.json", "*_source.json", "*-source.json",
|
|
|
|
|
+ "state.json", "seed.json", "raw.json",
|
|
|
|
|
+ # 生成脚本
|
|
|
|
|
+ "build.py", "build.mjs", "build.sh", "make.py", "make.sh",
|
|
|
|
|
+ "gen*.py", "gen*.mjs", "gen*.js", "generate*.py",
|
|
|
|
|
+ # 自测探针 / 草稿(2026-11-18 用户裁决:probe.txt / same.txt 被传上 S3)
|
|
|
|
|
+ "probe*.txt", "probe*.json", "test*.txt", "same.txt", "new.txt",
|
|
|
|
|
+ "a.txt", "b.txt", "c.txt", "d.txt", "e.txt",
|
|
|
|
|
+ "*probe*", "*scratch*", "*draft*", "*.bak", "*~",
|
|
|
|
|
+ # 缩略图 / 预览图(不是用户要的成品图)
|
|
|
|
|
+ "preview.png", "thumbnail.png", "thumb.png", "screenshot*.png",
|
|
|
|
|
+)
|
|
|
|
|
+
|
|
|
|
|
+# 成果对象存储域名:只有这些域名上的链接受「必须来自上传回执」约束。
|
|
|
|
|
+STORAGE_HOSTS = frozenset({"s3.fmode.cn", "file-cloud.fmode.cn"})
|
|
|
|
|
+
|
|
|
|
|
+MAX_BYTES = int(os.environ.get("FMODE_DELIVERABLE_MAX_BYTES", str(800 * 1024 * 1024)))
|
|
|
|
|
+
|
|
|
|
|
+# 因体积超限被跳过的文件(每轮重算):用于在回复正文里给用户一行明确提示,
|
|
|
|
|
+# 而不是像以前那样 classify() 返回 False 后静默消失。
|
|
|
|
|
+TOO_LARGE: list[tuple[str, int]] = []
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _mb(n: int) -> float:
|
|
|
|
|
+ return n / 1048576.0
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+# 模型说明「这是交付物」时,正文里可写的标记
|
|
|
|
|
+INLINE_MARK_RE = re.compile(r"\[deliverable\]|\[交付\]|DELIVERABLE:", re.I)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def log(msg: str) -> None:
|
|
|
|
|
+ try:
|
|
|
|
|
+ LOG.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
+ with LOG.open("a", encoding="utf-8") as f:
|
|
|
|
|
+ f.write("%s %s\n" % (time.strftime("%Y-%m-%dT%H:%M:%S"), msg))
|
|
|
|
|
+ except OSError:
|
|
|
|
|
+ pass
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+# 判定
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+def _denied(path: str) -> str | None:
|
|
|
|
|
+ """内部运行时/状态文件闸门。命中返回理由字符串,否则 None。
|
|
|
|
|
+
|
|
|
|
|
+ 这是**最高优先**闸门:classify() 第一件事就是调它,sweep_new_files() 也单独调它,
|
|
|
|
|
+ 所以命中者既不会进 queued[],也不会被上传、不会出现在「已上云」链接块里。
|
|
|
|
|
+ """
|
|
|
|
|
+ try:
|
|
|
|
|
+ p = os.path.abspath(os.path.expanduser(str(path)))
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ return "internal-path-unparsable"
|
|
|
|
|
+ low = p.lower()
|
|
|
|
|
+ name = os.path.basename(p).lower()
|
|
|
|
|
+ # config.json 之类只在 HOME 根算内部文件;子目录里的同名文件是用户成果
|
|
|
|
|
+ home_root = os.path.abspath(os.environ.get("HERMES_HOME", "/opt/data")).rstrip("/")
|
|
|
|
|
+ is_home_root = os.path.dirname(p).rstrip("/") == home_root
|
|
|
|
|
+ for g in INTERNAL_NAME_GLOB:
|
|
|
|
|
+ if fnmatch.fnmatch(name, g):
|
|
|
|
|
+ return "internal-file(%s)" % g
|
|
|
|
|
+ if is_home_root and name in SYSTEM_CONFIG_ROOT_ONLY:
|
|
|
|
|
+ return "internal-file(%s@home-root)" % name
|
|
|
|
|
+ low_dir = p + "/"
|
|
|
|
|
+ for d in STATE_DIR_DENY:
|
|
|
|
|
+ if low_dir.startswith(d):
|
|
|
|
|
+ return "internal-dir(%s)" % d
|
|
|
|
|
+ return None
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def classify(path: str, size: int | None = None) -> tuple[bool, str]:
|
|
|
|
|
+ """返回 (是否交付成果, 判定理由)。默认拒绝;只有明确命中才放行。"""
|
|
|
|
|
+ try:
|
|
|
|
|
+ p = os.path.abspath(os.path.expanduser(path))
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ return False, "path-unparsable"
|
|
|
|
|
+
|
|
|
|
|
+ low = p.lower()
|
|
|
|
|
+ name = os.path.basename(p)
|
|
|
|
|
+ ext = os.path.splitext(name)[1].lower()
|
|
|
|
|
+
|
|
|
|
|
+ # ── 0. 内部运行时/状态文件闸门(最高优先,连 MARK_DIRS/扩展名白名单都不许绕过)──
|
|
|
|
|
+ _why = _denied(p)
|
|
|
|
|
+ if _why:
|
|
|
|
|
+ return False, _why
|
|
|
|
|
+
|
|
|
|
|
+ # E2 体积(先取到,稍后判;路径/名称规则优先,便于审计与测试)
|
|
|
|
|
+ if size is None:
|
|
|
|
|
+ try:
|
|
|
|
|
+ size = os.path.getsize(p)
|
|
|
|
|
+ except OSError:
|
|
|
|
|
+ return False, "missing-on-disk"
|
|
|
|
|
+ if size > MAX_BYTES:
|
|
|
|
|
+ return False, "too-large(>%dMB)" % (MAX_BYTES // 1048576)
|
|
|
|
|
+
|
|
|
|
|
+ # ── 系统文件闸门(最高优先,连 D1 显式标记目录都不许绕过)──────────────
|
|
|
|
|
+ for pre in SYSTEM_PREFIX_DENY:
|
|
|
|
|
+ if p == pre or p.startswith(pre):
|
|
|
|
|
+ return False, "system-path(%s)" % pre
|
|
|
|
|
+ if name.lower() in SYSTEM_FILE_DENY:
|
|
|
|
|
+ return False, "system-config-file(%s)" % name
|
|
|
|
|
+ if name.lower() in SYSTEM_CONFIG_ROOT_ONLY:
|
|
|
|
|
+ home_root = os.path.abspath(os.environ.get("HERMES_HOME", "/opt/data")).rstrip("/")
|
|
|
|
|
+ if os.path.dirname(p).rstrip("/") == home_root:
|
|
|
|
|
+ return False, "system-config-file(%s@home-root)" % name
|
|
|
|
|
+ if name.lower() in SYSTEM_NAME_DENY:
|
|
|
|
|
+ return False, "system-filename(%s)" % name
|
|
|
|
|
+ # dotfile 凭据:家目录下任何 .xxx(非 .yyy 白名单)一律不传
|
|
|
|
|
+ if name.startswith(".") and name not in (".", ".."):
|
|
|
|
|
+ return False, "dotfile(%s)" % name
|
|
|
|
|
+
|
|
|
|
|
+ # D1 显式标记目录:优先放行(目录本身就是模型的选择)
|
|
|
|
|
+ for d in MARK_DIRS:
|
|
|
|
|
+ if p.startswith(d):
|
|
|
|
|
+ if ext in EXT_ALLOW:
|
|
|
|
|
+ return True, "marked-dir"
|
|
|
|
|
+ return False, "marked-dir-but-ext-not-allowlisted(%s)" % ext
|
|
|
|
|
+
|
|
|
|
|
+ # E1 显式缓存标记(路径里带 cache-only)
|
|
|
|
|
+ if "cache-only" in low:
|
|
|
|
|
+ return False, "explicit-cache-only"
|
|
|
|
|
+
|
|
|
|
|
+ # E0 中间产物闸门:生成脚本/中间数据不是交付物(data.json 曾在清单里出现过)
|
|
|
|
|
+ for g in INTERMEDIATE_GLOB:
|
|
|
|
|
+ if fnmatch.fnmatch(name.lower(), g.lower()):
|
|
|
|
|
+ return False, "intermediate-artifact(%s)" % g
|
|
|
|
|
+
|
|
|
|
|
+ # B 目录黑名单
|
|
|
|
|
+ for frag in DIR_DENY_SUBSTR:
|
|
|
|
|
+ if frag in low:
|
|
|
|
|
+ return False, "denied-dir(%s)" % frag
|
|
|
|
|
+
|
|
|
|
|
+ # C 文件名黑名单
|
|
|
|
|
+ for g in NAME_DENY_GLOB:
|
|
|
|
|
+ if fnmatch.fnmatch(name.lower(), g):
|
|
|
|
|
+ return False, "denied-name-glob(%s)" % g
|
|
|
|
|
+ for s in NAME_DENY_SUBSTR:
|
|
|
|
|
+ if s in name.lower():
|
|
|
|
|
+ return False, "denied-name-substr(%s)" % s
|
|
|
|
|
+ for rx in NAME_DENY_RE:
|
|
|
|
|
+ if rx.match(name):
|
|
|
|
|
+ return False, "denied-name-regex(%s)" % rx.pattern
|
|
|
|
|
+
|
|
|
|
|
+ # A 扩展名白名单
|
|
|
|
|
+ if ext not in EXT_ALLOW:
|
|
|
|
|
+ return False, "ext-not-allowlisted(%s)" % (ext or "none")
|
|
|
|
|
+
|
|
|
|
|
+ # 空文件虽然扩展名合规,但没内容,不是成果
|
|
|
|
|
+ if size <= 0:
|
|
|
|
|
+ return False, "empty-file"
|
|
|
|
|
+
|
|
|
|
|
+ return True, "allowlisted-ext"
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+# 从工具调用里提取被写的文件路径
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+WRITE_TOOLS = {"write_file", "patch", "execute_code", "terminal", "create_file", "edit_file"}
|
|
|
|
|
+
|
|
|
|
|
+PATH_ARG_KEYS = ("path", "file_path", "filepath", "filename", "file", "target", "dest", "output")
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def paths_from_tool(tool: str, ti: dict) -> list[str]:
|
|
|
|
|
+ out: list[str] = []
|
|
|
|
|
+ if not isinstance(ti, dict):
|
|
|
|
|
+ return out
|
|
|
|
|
+ for k in PATH_ARG_KEYS:
|
|
|
|
|
+ v = ti.get(k)
|
|
|
|
|
+ if isinstance(v, str) and v.strip():
|
|
|
|
|
+ out.append(v.strip())
|
|
|
|
|
+ elif isinstance(v, list):
|
|
|
|
|
+ out.extend([x for x in v if isinstance(x, str)])
|
|
|
|
|
+ # 显式标记键
|
|
|
|
|
+ for k in MARK_KEYS:
|
|
|
|
|
+ v = ti.get(k)
|
|
|
|
|
+ if isinstance(v, bool):
|
|
|
|
|
+ continue
|
|
|
|
|
+ if isinstance(v, str):
|
|
|
|
|
+ out.append(v)
|
|
|
|
|
+ elif isinstance(v, list):
|
|
|
|
|
+ out.extend([x for x in v if isinstance(x, str)])
|
|
|
|
|
+ # execute_code / terminal:从代码/命令里捞绝对路径(只认带白名单扩展名的)
|
|
|
|
|
+ blob = ""
|
|
|
|
|
+ for k in ("code", "command", "script"):
|
|
|
|
|
+ v = ti.get(k)
|
|
|
|
|
+ if isinstance(v, str):
|
|
|
|
|
+ blob += v + "\n"
|
|
|
|
|
+ if blob:
|
|
|
|
|
+ for mt in re.finditer(r"[\"']?(/(?:opt/data|tmp|home|var)[\w./\-]+\.[A-Za-z0-9]{1,5})[\"']?", blob):
|
|
|
|
|
+ out.append(mt.group(1))
|
|
|
|
|
+ for mt in re.finditer(r"(?:>|\btee\b)\s*[\"']?(/[\w./\-]+\.[A-Za-z0-9]{1,5})", blob):
|
|
|
|
|
+ out.append(mt.group(1))
|
|
|
|
|
+ # 去重保序
|
|
|
|
|
+ seen, uniq = set(), []
|
|
|
|
|
+ for x in out:
|
|
|
|
|
+ if x not in seen:
|
|
|
|
|
+ seen.add(x)
|
|
|
|
|
+ uniq.append(x)
|
|
|
|
|
+ return uniq
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+# 状态
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+def state_path(session_id: str) -> Path:
|
|
|
|
|
+ sid = re.sub(r"[^A-Za-z0-9_.-]", "_", session_id or "nosession")[:120]
|
|
|
|
|
+ return CACHE_DIR / ("%s.json" % sid)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def load_state(session_id: str) -> dict:
|
|
|
|
|
+ p = state_path(session_id)
|
|
|
|
|
+ try:
|
|
|
|
|
+ return json.loads(p.read_text(encoding="utf-8"))
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ return {"queued": [], "pushed": [], "seen": []}
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def save_state(session_id: str, st: dict) -> None:
|
|
|
|
|
+ p = state_path(session_id)
|
|
|
|
|
+ p.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
+ tmp = p.with_suffix(".tmp")
|
|
|
|
|
+ tmp.write_text(json.dumps(st, ensure_ascii=False, indent=1), encoding="utf-8")
|
|
|
|
|
+ os.replace(tmp, p)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+# post_tool_call:只排队,不做网络 IO(快,不拖慢工具链)
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+# 过程消息:往 Matrix 发一条「💻 tool · <摘要>」,带 fmode.kind=process
|
|
|
|
|
+# 必须异步——hook 是同步执行的,Hermes 给 post_tool_call 只有 20s,
|
|
|
|
|
+# 网络 IO 塞进主流程会拖慢工具链。用 Popen 拉起独立进程后立即返回。
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+NOTICE_SCRIPT = HOME / "scripts" / "fmode-process-notice.py"
|
|
|
|
|
+NOTICE_TOOLS = {"terminal", "write_file", "patch", "execute_code", "browser_exec"}
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _spawn_process_notice(payload: dict) -> None:
|
|
|
|
|
+ """fire-and-forget 派生过程消息发送进程,失败绝不影响工具链。"""
|
|
|
|
|
+ try:
|
|
|
|
|
+ tool = payload.get("tool_name") or ""
|
|
|
|
|
+ if tool not in NOTICE_TOOLS:
|
|
|
|
|
+ return
|
|
|
|
|
+ if not NOTICE_SCRIPT.is_file():
|
|
|
|
|
+ return
|
|
|
|
|
+ env = dict(os.environ)
|
|
|
|
|
+ # payload 里没有 HERMES_SESSION_CHAT_ID(那是 gateway 的进程环境变量),
|
|
|
|
|
+ # 所以除了 payload 显式给的,还要把当前进程环境里的会话标识透传下去。
|
|
|
|
|
+ for k in ("HERMES_SESSION_CHAT_ID", "HERMES_SESSION_ID",
|
|
|
|
|
+ "HERMES_SESSION_PLATFORM", "HERMES_SESSION_KEY",
|
|
|
|
|
+ "MATRIX_HOMESERVER", "MATRIX_ACCESS_TOKEN", "MATRIX_USER_ID"):
|
|
|
|
|
+ v = payload.get(k) or os.environ.get(k)
|
|
|
|
|
+ if v:
|
|
|
|
|
+ env[k] = str(v)
|
|
|
|
|
+ # FMODE_NOTICE_NONBLOCKING_V1: file-backed stdin cannot wait on child network I/O.
|
|
|
|
|
+ import tempfile
|
|
|
|
|
+ import threading
|
|
|
|
|
+ with tempfile.TemporaryFile(mode="w+b") as input_stream:
|
|
|
|
|
+ input_stream.write(json.dumps(payload, ensure_ascii=False).encode("utf-8"))
|
|
|
|
|
+ input_stream.seek(0)
|
|
|
|
|
+ worker = subprocess.Popen(
|
|
|
|
|
+ ["python3", str(NOTICE_SCRIPT)], stdin=input_stream,
|
|
|
|
|
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
|
|
|
|
+ env=env, start_new_session=True,
|
|
|
|
|
+ )
|
|
|
|
|
+ threading.Thread(target=worker.wait, daemon=True).start()
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ log("NOTICE-SPAWN-FAIL %s" % e)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+# 本轮(turn)标记:由 pre_llm_call 的 fmode-round-marker.py 落盘,这里只读
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+ROUNDS_DIR = CACHE_DIR / "rounds"
|
|
|
|
|
+# 只扫这些根:本轮 tool_input 里出现过的目录 + /opt/data/work。
|
|
|
|
|
+# 绝不全局扫 /opt/data —— 那会把 skills/plugins/cache 全捞一遍。
|
|
|
|
|
+SWEEP_EXTRA_ROOTS = ("/opt/data/work",)
|
|
|
|
|
+# 永不作为 sweep 根的目录:家目录根就是运行时状态堆放区(state.db / *_state.json / 目录索引)。
|
|
|
|
|
+# 这里只放 /opt/data 本身;子目录(/opt/data/work/x、/opt/data/apptest-*/ 等)照常可扫。
|
|
|
|
|
+SWEEP_ROOT_DENY = ("/opt/data", "/opt", "/", "/tmp", "/var/tmp")
|
|
|
|
|
+_ABS_PATH_IN_ARGS_RE = re.compile(r"(/(?:opt/data|tmp|home|var/tmp)[\w./\-]+)")
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def round_marker_path(session_id: str) -> Path:
|
|
|
|
|
+ sid = re.sub(r"[^A-Za-z0-9_.-]", "_", session_id or "nosession")[:120]
|
|
|
|
|
+ return ROUNDS_DIR / ("%s.json" % sid)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def load_round(session_id: str) -> dict:
|
|
|
|
|
+ """读本轮标记(turn_id / start_ts / cwd_hints)。读不到返回空 dict。"""
|
|
|
|
|
+ try:
|
|
|
|
|
+ return json.loads(round_marker_path(session_id).read_text(encoding="utf-8")) or {}
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ return {}
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _in_current_round(item: dict, cur_turn: str) -> bool:
|
|
|
|
|
+ """链接必须有本轮标识;历史无tag记录不能用时间窗冒充本轮交付。"""
|
|
|
|
|
+ if not isinstance(item, dict):
|
|
|
|
|
+ return False
|
|
|
|
|
+ tag = str(item.get("turn_id") or "").strip()
|
|
|
|
|
+ return bool(cur_turn) and tag == cur_turn
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _queued_in_round(item: dict, turn_id: str) -> bool:
|
|
|
|
|
+ """队列必须明确属于本轮;旧无tag失败项保留,当前工具可重新认领。"""
|
|
|
|
|
+ tag = str(item.get("turn_id") or "").strip()
|
|
|
|
|
+ return bool(turn_id) and tag == turn_id
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _pushed_current_paths(state: dict, turn_id: str) -> set[str]:
|
|
|
|
|
+ """仅跳过本轮已确认且字节未变的文件;同路径改写仍交给内容复用链核验。"""
|
|
|
|
|
+ paths = set()
|
|
|
|
|
+ for item in state.get("pushed", []):
|
|
|
|
|
+ if not isinstance(item, dict) or not _in_current_round(item, turn_id):
|
|
|
|
|
+ continue
|
|
|
|
|
+ path, expected, url = item.get("path"), item.get("sha256"), item.get("url")
|
|
|
|
|
+ if (not isinstance(path, str) or not expected or _denied(path)
|
|
|
|
|
+ or not isinstance(url, str) or not url.startswith("https://")
|
|
|
|
|
+ or _user_upload_url(url)):
|
|
|
|
|
+ continue
|
|
|
|
|
+ try:
|
|
|
|
|
+ digest = hashlib.sha256()
|
|
|
|
|
+ with open(path, "rb") as stream:
|
|
|
|
|
+ for chunk in iter(lambda: stream.read(1 << 20), b""):
|
|
|
|
|
+ digest.update(chunk)
|
|
|
|
|
+ if digest.hexdigest() == expected:
|
|
|
|
|
+ paths.add(path)
|
|
|
|
|
+ except OSError:
|
|
|
|
|
+ continue
|
|
|
|
|
+ return paths
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _user_upload_url(url: str) -> bool:
|
|
|
|
|
+ from urllib.parse import unquote, urlsplit
|
|
|
|
|
+ try:
|
|
|
|
|
+ parsed = urlsplit(url)
|
|
|
|
|
+ return (parsed.hostname or "").lower() in {"s3.fmode.cn", "file-cloud.fmode.cn"} and bool(
|
|
|
|
|
+ re.match(r"^/user/[^/]+/chat/", unquote(parsed.path)))
|
|
|
|
|
+ except (TypeError, ValueError):
|
|
|
|
|
+ return False
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+# 「本轮」起点容差:`> file` 重定向会把 mtime 截到整秒,start_ts 带毫秒小数,
|
|
|
|
|
+# 同秒内生成的文件会被 stat.st_mtime < turn_start_ts 判成「上一轮的」。
|
|
|
|
|
+# 这不是放宽规则,是修时间精度:mtime 粒度就是 1s。
|
|
|
|
|
+SWEEP_MTIME_SLACK_S = 1.0
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def tool_dir_hints(tool_input: dict, round_cwd_hints: list | None = None) -> list[str]:
|
|
|
|
|
+ """本轮该扫的目录:只认**本轮 tool_input 里显式出现过的绝对路径的父目录** + /opt/data/work。
|
|
|
|
|
+
|
|
|
|
|
+ 只做**一层** scandir,所以目录必须收敛。凡命中 DIR_DENY_SUBSTR / SYSTEM_PREFIX_DENY 的跳过。
|
|
|
|
|
+
|
|
|
|
|
+ 2026-11-17 收紧:以前 round_cwd_hints(pre_llm_call 落盘的 cwd,常常是 /opt/data 家目录根)
|
|
|
|
|
+ 也会被加进来,等于每轮都把 /opt/data 根扫一遍 → channel_directory.json / gateway_state.json
|
|
|
|
|
+ 这类 Hermes 运行态文件因 mtime 新鲜被当成成果。现在:
|
|
|
|
|
+ - cwd_hints 只在它**确实是本轮 tool_input 里出现过的路径的父目录时**才接受;
|
|
|
|
|
+ - 家目录根 /opt/data 本身永不作为扫描根(状态文件都堆在那里)。
|
|
|
|
|
+ """
|
|
|
|
|
+ dirs: list[str] = []
|
|
|
|
|
+
|
|
|
|
|
+ def _add(d: str) -> None:
|
|
|
|
|
+ if not d:
|
|
|
|
|
+ return
|
|
|
|
|
+ try:
|
|
|
|
|
+ d = os.path.abspath(os.path.expanduser(d))
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ return
|
|
|
|
|
+ if d == "/" or not d.startswith("/"):
|
|
|
|
|
+ return
|
|
|
|
|
+ # 家目录根及其上都不是「产物目录」,是运行时状态堆放区
|
|
|
|
|
+ if d in SWEEP_ROOT_DENY:
|
|
|
|
|
+ return
|
|
|
|
|
+ low = d + "/"
|
|
|
|
|
+ if any(frag in low for frag in DIR_DENY_SUBSTR):
|
|
|
|
|
+ return
|
|
|
|
|
+ if any(d == pre.rstrip("/") or d.startswith(pre) for pre in SYSTEM_PREFIX_DENY):
|
|
|
|
|
+ return
|
|
|
|
|
+ try:
|
|
|
|
|
+ if not os.path.isdir(d):
|
|
|
|
|
+ return
|
|
|
|
|
+ except OSError:
|
|
|
|
|
+ return
|
|
|
|
|
+ if d not in dirs:
|
|
|
|
|
+ dirs.append(d)
|
|
|
|
|
+
|
|
|
|
|
+ blob = ""
|
|
|
|
|
+ if isinstance(tool_input, dict):
|
|
|
|
|
+ for k in ("command", "code", "script", "path", "file_path", "target", "notebook_path"):
|
|
|
|
|
+ v = tool_input.get(k)
|
|
|
|
|
+ if isinstance(v, str):
|
|
|
|
|
+ blob += v + "\n"
|
|
|
|
|
+ elif isinstance(v, list):
|
|
|
|
|
+ blob += "\n".join(x for x in v if isinstance(x, str)) + "\n"
|
|
|
|
|
+
|
|
|
|
|
+ # 本轮 tool_input 显式出现过的绝对路径 → 取其父目录。这是唯一「明确要产出」的信号。
|
|
|
|
|
+ # 另外:路径本身若是目录(`cd /opt/data/xxx && …`、`--outdir /opt/data/xxx`),
|
|
|
|
|
+ # 它自己就是扫描根 —— 否则 `cd <dir> && python gen.py` 只会把 /opt/data 提上来后被拒,
|
|
|
|
|
+ # 真实产出目录反而扫不到。
|
|
|
|
|
+ explicit_dirs: list[str] = []
|
|
|
|
|
+ for mt in _ABS_PATH_IN_ARGS_RE.finditer(blob):
|
|
|
|
|
+ raw = mt.group(1).rstrip("/")
|
|
|
|
|
+ if not raw:
|
|
|
|
|
+ continue
|
|
|
|
|
+ ap = os.path.abspath(raw)
|
|
|
|
|
+ try:
|
|
|
|
|
+ if os.path.isdir(ap) and ap not in explicit_dirs:
|
|
|
|
|
+ explicit_dirs.append(ap)
|
|
|
|
|
+ except OSError:
|
|
|
|
|
+ pass
|
|
|
|
|
+ pd = os.path.dirname(ap)
|
|
|
|
|
+ if pd not in explicit_dirs:
|
|
|
|
|
+ explicit_dirs.append(pd)
|
|
|
|
|
+
|
|
|
|
|
+ def _add_known(d: str) -> None:
|
|
|
|
|
+ """与 _add 相同,但跳过 isdir 检查 —— 目录是否已存在由调用方保证。
|
|
|
|
|
+
|
|
|
|
|
+ sweep_new_files 里的 scandir 自己会 OSError 兜底,所以「本轮刚 mkdir 出来的目录」
|
|
|
|
|
+ 与「本轮参数里写了但还没建的目录」走同一条安全路径,不会抛。
|
|
|
|
|
+ """
|
|
|
|
|
+ if not d:
|
|
|
|
|
+ return
|
|
|
|
|
+ try:
|
|
|
|
|
+ d = os.path.abspath(os.path.expanduser(d))
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ return
|
|
|
|
|
+ if d == "/" or not d.startswith("/"):
|
|
|
|
|
+ return
|
|
|
|
|
+ if d in SWEEP_ROOT_DENY:
|
|
|
|
|
+ return
|
|
|
|
|
+ low = d + "/"
|
|
|
|
|
+ if any(frag in low for frag in DIR_DENY_SUBSTR):
|
|
|
|
|
+ return
|
|
|
|
|
+ if any(d == pre.rstrip("/") or d.startswith(pre) for pre in SYSTEM_PREFIX_DENY):
|
|
|
|
|
+ return
|
|
|
|
|
+ if d not in dirs:
|
|
|
|
|
+ dirs.append(d)
|
|
|
|
|
+
|
|
|
|
|
+ for d in explicit_dirs:
|
|
|
|
|
+ _add_known(d)
|
|
|
|
|
+
|
|
|
|
|
+ # cwd_hints 只在「已被本轮显式路径证据证明」时才接受(即它是某个显式父目录的祖先/自身)
|
|
|
|
|
+ for d in (round_cwd_hints or []):
|
|
|
|
|
+ if not isinstance(d, str):
|
|
|
|
|
+ continue
|
|
|
|
|
+ try:
|
|
|
|
|
+ ad = os.path.abspath(os.path.expanduser(d))
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ continue
|
|
|
|
|
+ if ad in SWEEP_ROOT_DENY:
|
|
|
|
|
+ continue
|
|
|
|
|
+ if not any(ed == ad or ed.startswith(ad.rstrip("/") + "/") for ed in explicit_dirs):
|
|
|
|
|
+ continue
|
|
|
|
|
+ _add(ad)
|
|
|
|
|
+
|
|
|
|
|
+ for d in SWEEP_EXTRA_ROOTS:
|
|
|
|
|
+ _add(d)
|
|
|
|
|
+ return dirs[:60]
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def sweep_new_files(session_id: str, turn_id: str, turn_start_ts: float,
|
|
|
|
|
+ dirs: list[str], st: dict) -> list[str]:
|
|
|
|
|
+ """把「本轮新写/改写的、符合交付规则、还没推送过」的文件捞出来(只入队,不上传)。
|
|
|
|
|
+
|
|
|
|
|
+ 为什么要这一步:pushed[] 是唯一投递凭证,而正常路径只认「工具参数里出现白名单扩展名」。
|
|
|
|
|
+ `python gen.py` 生成的产物、命中 deny-glob 的产物一律进不去 → 出站 no-preuploaded-url
|
|
|
|
|
+ → 附件丢失。这里按 mtime 兜底,走同一套 classify()/queued[] 通道。
|
|
|
|
|
+ """
|
|
|
|
|
+ if turn_start_ts <= 0:
|
|
|
|
|
+ return []
|
|
|
|
|
+ pushed_paths = _pushed_current_paths(st, turn_id)
|
|
|
|
|
+ queued_paths = {q.get("path") for q in st.get("queued", [])
|
|
|
|
|
+ if isinstance(q, dict) and _queued_in_round(q, turn_id)}
|
|
|
|
|
+ hits: list[str] = []
|
|
|
|
|
+ for d in dirs:
|
|
|
|
|
+ try:
|
|
|
|
|
+ entries = list(os.scandir(d))
|
|
|
|
|
+ except OSError as e:
|
|
|
|
|
+ log("SWEEP-SCAN-FAIL %s %s" % (d, e))
|
|
|
|
|
+ continue
|
|
|
|
|
+ for ent in entries:
|
|
|
|
|
+ try:
|
|
|
|
|
+ if not ent.is_file(follow_symlinks=False):
|
|
|
|
|
+ continue
|
|
|
|
|
+ ap = os.path.abspath(ent.path)
|
|
|
|
|
+ if ap in pushed_paths or ap in queued_paths:
|
|
|
|
|
+ continue
|
|
|
|
|
+ stat = ent.stat(follow_symlinks=False)
|
|
|
|
|
+ if stat.st_mtime < turn_start_ts - SWEEP_MTIME_SLACK_S:
|
|
|
|
|
+ continue
|
|
|
|
|
+ name = os.path.basename(ap)
|
|
|
|
|
+ ext = os.path.splitext(name)[1].lower()
|
|
|
|
|
+ if ext not in EXT_ALLOW:
|
|
|
|
|
+ continue
|
|
|
|
|
+ # 内部运行时/状态文件:连入队都不许(黑名单先于一切)
|
|
|
|
|
+ _why = _denied(ap)
|
|
|
|
|
+ if _why:
|
|
|
|
|
+ log("SWEEP-DENY %s reason=%s" % (ap, _why))
|
|
|
|
|
+ continue
|
|
|
|
|
+ if any(fnmatch.fnmatch(name.lower(), g) for g in NAME_DENY_GLOB):
|
|
|
|
|
+ continue
|
|
|
|
|
+ ok, why = classify(ap, stat.st_size)
|
|
|
|
|
+ if not ok:
|
|
|
|
|
+ continue
|
|
|
|
|
+ st.setdefault("queued", []).append({
|
|
|
|
|
+ "path": ap, "tool": "sweep", "ts": int(time.time()), "reason": why,
|
|
|
|
|
+ "size": stat.st_size, "turn_id": turn_id, "sweep": True,
|
|
|
|
|
+ })
|
|
|
|
|
+ queued_paths.add(ap)
|
|
|
|
|
+ hits.append(ap)
|
|
|
|
|
+ log("SWEEP enqueue %s reason=round-new-file turn=%s" % (ap, turn_id or "-"))
|
|
|
|
|
+ except OSError as e:
|
|
|
|
|
+ log("SWEEP-ENTRY-FAIL %s %s" % (getattr(ent, "path", "?"), e))
|
|
|
|
|
+ return hits
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def handle_post_tool_call(payload: dict) -> int:
|
|
|
|
|
+ tool = payload.get("tool_name") or ""
|
|
|
|
|
+ ti = payload.get("tool_input") or {}
|
|
|
|
|
+ sid = payload.get("session_id") or "nosession"
|
|
|
|
|
+
|
|
|
|
|
+ # 先发过程消息(异步,不阻塞),再做成果判定
|
|
|
|
|
+ _spawn_process_notice(payload)
|
|
|
|
|
+
|
|
|
|
|
+ if tool not in WRITE_TOOLS and not isinstance(ti, dict):
|
|
|
|
|
+ return 0
|
|
|
|
|
+
|
|
|
|
|
+ # 本轮标记(pre_llm_call 落盘):turn_id 用于归属,start_ts 用于「本轮新文件」兜底
|
|
|
|
|
+ rnd = load_round(sid)
|
|
|
|
|
+ turn_id = str(rnd.get("turn_id") or "").strip()
|
|
|
|
|
+ try:
|
|
|
|
|
+ turn_start_ts = float(rnd.get("start_ts") or 0)
|
|
|
|
|
+ except (TypeError, ValueError):
|
|
|
|
|
+ turn_start_ts = 0.0
|
|
|
|
|
+ if turn_start_ts > time.time():
|
|
|
|
|
+ turn_start_ts = 0.0 # 时钟漂移保护:未来时间会让「本轮新增」判定失效
|
|
|
|
|
+
|
|
|
|
|
+ cands = paths_from_tool(tool, ti)
|
|
|
|
|
+
|
|
|
|
|
+ # 先做兜底扫描:脚本生成(python gen.py)、命中 deny-glob 的产物不会出现在工具参数里,
|
|
|
|
|
+ # 只能靠「本轮 mtime + 目录白名单」捞回来。命中项直接进 queued[],与下方 QUEUE 同一通道。
|
|
|
|
|
+ st = load_state(sid)
|
|
|
|
|
+ swept = sweep_new_files(
|
|
|
|
|
+ sid, turn_id, turn_start_ts,
|
|
|
|
|
+ tool_dir_hints(ti if isinstance(ti, dict) else {}, rnd.get("cwd_hints")), st)
|
|
|
|
|
+ if swept:
|
|
|
|
|
+ save_state(sid, st)
|
|
|
|
|
+
|
|
|
|
|
+ if not cands:
|
|
|
|
|
+ return 0
|
|
|
|
|
+
|
|
|
|
|
+ queued_paths = {q["path"] for q in st.get("queued", [])
|
|
|
|
|
+ if isinstance(q, dict) and _queued_in_round(q, turn_id)}
|
|
|
|
|
+ changed = False
|
|
|
|
|
+ for c in cands:
|
|
|
|
|
+ ap = os.path.abspath(os.path.expanduser(c))
|
|
|
|
|
+ if not os.path.isfile(ap):
|
|
|
|
|
+ continue
|
|
|
|
|
+ ok, why = classify(ap)
|
|
|
|
|
+ if not ok:
|
|
|
|
|
+ log("SKIP %s tool=%s reason=%s" % (ap, tool, why))
|
|
|
|
|
+ if why.startswith("too-large"):
|
|
|
|
|
+ try:
|
|
|
|
|
+ sz = os.path.getsize(ap)
|
|
|
|
|
+ except OSError:
|
|
|
|
|
+ sz = 0
|
|
|
|
|
+ TOO_LARGE.append((os.path.basename(ap), sz))
|
|
|
|
|
+ log("TOO-LARGE-NOTICE %s (%d bytes)" % (ap, sz))
|
|
|
|
|
+ continue
|
|
|
|
|
+ if ap in queued_paths:
|
|
|
|
|
+ continue
|
|
|
|
|
+ st.setdefault("queued", []).append({
|
|
|
|
|
+ "path": ap, "tool": tool, "ts": int(time.time()), "reason": why,
|
|
|
|
|
+ "size": os.path.getsize(ap), "turn_id": turn_id,
|
|
|
|
|
+ })
|
|
|
|
|
+ queued_paths.add(ap)
|
|
|
|
|
+ changed = True
|
|
|
|
|
+ log("QUEUE %s tool=%s reason=%s" % (ap, tool, why))
|
|
|
|
|
+
|
|
|
|
|
+ if changed:
|
|
|
|
|
+ save_state(sid, st)
|
|
|
|
|
+ return 0
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+# 上传 + 登记(复用 fmode-artifact-push.py 的 report→enqueue→PUT→回读 链路)
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+def _load_pusher():
|
|
|
|
|
+ spec = importlib.util.spec_from_file_location("fmode_push", str(PUSH_SCRIPT))
|
|
|
|
|
+ mod = importlib.util.module_from_spec(spec)
|
|
|
|
|
+ spec.loader.exec_module(mod)
|
|
|
|
|
+ return mod
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+STATE_DB = HOME / "state.db"
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _thread_root(sid: str | None = None) -> str | None:
|
|
|
|
|
+ """取本会话的 threadRoot(三级回落)。
|
|
|
|
|
+
|
|
|
|
|
+ App 侧约定:云函数 listBySession 按 user + threadRoot 查,threadRoot 必填;
|
|
|
|
|
+ 右栏「成果」页签就靠它,登记不进去用户就看不到文件。所以宁可回落到房间 id,
|
|
|
|
|
+ 也不要返回 None(None = 跳过登记 = 文件不在成果里)。
|
|
|
|
|
+
|
|
|
|
|
+ ① sessions.thread_id(App 发的 Matrix thread 根)——优先
|
|
|
|
|
+ ② 该会话的 chat_id(房间 id,DM/群都一样)或 session_key 的 :!roomId: 段
|
|
|
|
|
+ ③ 都没有才 None(调用方照常上传、跳过登记,打 SKIP-REGISTER)
|
|
|
|
|
+
|
|
|
|
|
+ 注:HERMES_SESSION_THREAD_ID 在 hook 子进程里拿不到(父进程没导出这个 ContextVar),
|
|
|
|
|
+ 所以一律走 state.db。
|
|
|
|
|
+ """
|
|
|
|
|
+ sid = sid or os.environ.get("HERMES_SESSION_ID")
|
|
|
|
|
+ if not sid:
|
|
|
|
|
+ log("SKIP-REGISTER reason=no-session-id")
|
|
|
|
|
+ return None
|
|
|
|
|
+ try:
|
|
|
|
|
+ import sqlite3
|
|
|
|
|
+ con = sqlite3.connect("file:%s?mode=ro" % STATE_DB, uri=True, timeout=5)
|
|
|
|
|
+ try:
|
|
|
|
|
+ row = con.execute(
|
|
|
|
|
+ "SELECT thread_id, chat_id, session_key FROM sessions WHERE id=?", (sid,)
|
|
|
|
|
+ ).fetchone()
|
|
|
|
|
+ finally:
|
|
|
|
|
+ con.close()
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ log("THREAD-ROOT-FAIL sid=%s %s" % (sid, e))
|
|
|
|
|
+ return None
|
|
|
|
|
+ if not row:
|
|
|
|
|
+ log("SKIP-REGISTER sid=%s reason=no-sessions-row" % sid)
|
|
|
|
|
+ return None
|
|
|
|
|
+ tid, chat_id, session_key = row[0], row[1], row[2]
|
|
|
|
|
+
|
|
|
|
|
+ # ① thread 根
|
|
|
|
|
+ if tid:
|
|
|
|
|
+ return str(tid)
|
|
|
|
|
+
|
|
|
|
|
+ # ② 回落到房间 id
|
|
|
|
|
+ room = (chat_id or "").strip()
|
|
|
|
|
+ if not room and session_key:
|
|
|
|
|
+ # session_key 形如 agent:main:matrix:dm:!roomId 或 ...:dm:!roomId:thread
|
|
|
|
|
+ for seg in str(session_key).split(":"):
|
|
|
|
|
+ if seg.startswith("!"):
|
|
|
|
|
+ room = seg
|
|
|
|
|
+ break
|
|
|
|
|
+ if room:
|
|
|
|
|
+ log("THREADROOT-FALLBACK sid=%s -> room=%s" % (sid, room))
|
|
|
|
|
+ return room
|
|
|
|
|
+
|
|
|
|
|
+ # ③ 实在没有
|
|
|
|
|
+ log("SKIP-REGISTER sid=%s reason=no-thread-no-room" % sid)
|
|
|
|
|
+ return None
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+HUB_FN = "THXAOGKiPK" # fmode-file-hub:带会话归属的成果登记
|
|
|
|
|
+LEGACY_FN = "lfYlgU7SkK" # 老成果表云函数,保持并存不动
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _hub_call(params: dict) -> dict:
|
|
|
|
|
+ """调新云函数 fmode-file-hub(THXAOGKiPK)。"""
|
|
|
|
|
+ import urllib.request
|
|
|
|
|
+ import urllib.error
|
|
|
|
|
+ tok = _token()
|
|
|
|
|
+ if not tok:
|
|
|
|
|
+ return {"code": -1, "error": "no-FMODE_SESSION_TOKEN"}
|
|
|
|
|
+ body = json.dumps({"id": HUB_FN, "token": tok, "params": params}).encode()
|
|
|
|
|
+ req = urllib.request.Request(
|
|
|
|
|
+ "https://server.fmode.cn/api/functions", data=body,
|
|
|
|
|
+ headers={"Content-Type": "application/json",
|
|
|
|
|
+ "X-Parse-Application-Id": "ncloudmaster"})
|
|
|
|
|
+ try:
|
|
|
|
|
+ with urllib.request.urlopen(req, timeout=30) as r:
|
|
|
|
|
+ return json.loads(r.read())
|
|
|
|
|
+ except urllib.error.HTTPError as e:
|
|
|
|
|
+ return {"code": e.code, "error": e.read().decode("utf-8", "replace")[:400]}
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ return {"code": -1, "error": str(e)[:400]}
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _mime_for(path: str) -> str:
|
|
|
|
|
+ import mimetypes
|
|
|
|
|
+ mt = mimetypes.guess_type(path)[0]
|
|
|
|
|
+ return mt or "application/octet-stream"
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _hub_register(path: str, url: str, thread_root: str, room_id: str,
|
|
|
|
|
+ deliverable_id: str | None = None) -> dict:
|
|
|
|
|
+ """登记单个文件到 fmode-file-hub。返回 {ok, detail, id, key}。
|
|
|
|
|
+
|
|
|
|
|
+ 🔴 登记前先查 listByUrl:同一 url 已登记过就跳过,绝不重复写台账
|
|
|
|
|
+ (2026-11-14 用户裁决:台账一轮只允许一条记录)。
|
|
|
|
|
+
|
|
|
|
|
+ 🔴 deliverableId:不要再传给云函数了(见下方 2026-11-18 说明)。
|
|
|
|
|
+ 参数保留只为兼容老调用方,当前实现**不使用**它。
|
|
|
|
|
+ """
|
|
|
|
|
+ # 登记前先查(同一 url 已存在则直接返回,不再 registerFile)
|
|
|
|
|
+ try:
|
|
|
|
|
+ chk = _hub_call({"action": "listByUrl", "url": url})
|
|
|
|
|
+ # FMODE_ROOM_SCOPED_REUSE_V1: a URL in another room is not this room's registration.
|
|
|
|
|
+ matches = [item for item in (chk.get("files") or [])
|
|
|
|
|
+ if isinstance(item, dict) and item.get("roomId") == room_id
|
|
|
|
|
+ and (not item.get("agentId") or item.get("agentId") == _resolve_agent_id())]
|
|
|
|
|
+ if matches:
|
|
|
|
|
+ first = matches[0]
|
|
|
|
|
+ log("SKIP-REGISTER already exists: %s id=%s"
|
|
|
|
|
+ % (url, first.get("id") if isinstance(first, dict) else "?"))
|
|
|
|
|
+ return {"ok": True,
|
|
|
|
|
+ "id": first.get("id") if isinstance(first, dict) else None,
|
|
|
|
|
+ "key": first.get("key") if isinstance(first, dict) else "",
|
|
|
|
|
+ "detail": "already-exists"}
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ log("LISTBYURL-CHECK-FAIL %s" % str(e)[:160])
|
|
|
|
|
+
|
|
|
|
|
+ key = ""
|
|
|
|
|
+ # 云盘对象键:从 s3 公开地址反推(https://s3.fmode.cn/<bucket>/... → 去掉域名与 bucket)
|
|
|
|
|
+ try:
|
|
|
|
|
+ from urllib.parse import urlsplit
|
|
|
|
|
+ p = urlsplit(url).path.lstrip("/")
|
|
|
|
|
+ seg = p.split("/", 1)
|
|
|
|
|
+ key = seg[1] if len(seg) == 2 else p
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ key = ""
|
|
|
|
|
+ size = os.path.getsize(path)
|
|
|
|
|
+ # 🔴 2026-11-18:绝不能把 deliverableId 传给 THXAOGKiPK 的 registerFile。
|
|
|
|
|
+ # 平台侧云函数在「按 deliverableId 认领 report 记录」分支里调了未定义的 _idOf()
|
|
|
|
|
+ # → 直接回 {"code":500,"msg":"_idOf is not defined"},成果表写不进任何记录
|
|
|
|
|
+ # (S3 上传是另一条路,所以表现为「上云成功、登记失败」)。
|
|
|
|
|
+ # 实测:同一请求带 deliverableId → 500;去掉该字段 → 200 且正常返回 id。
|
|
|
|
|
+ # 归属(roomId/threadRoot/agentId)由本请求的字段自带,不依赖认领。
|
|
|
|
|
+ # 去重由上面的 listByUrl 提前挡住,不需要靠云函数侧认领来防重复。
|
|
|
|
|
+ r = _hub_call({
|
|
|
|
|
+ "action": "registerFile",
|
|
|
|
|
+ "threadRoot": thread_root,
|
|
|
|
|
+ "agentId": _resolve_agent_id(),
|
|
|
|
|
+ "roomId": room_id,
|
|
|
|
|
+ "name": os.path.basename(path),
|
|
|
|
|
+ "url": url,
|
|
|
|
|
+ "key": key,
|
|
|
|
|
+ "mimeType": _mime_for(path),
|
|
|
|
|
+ "size": size,
|
|
|
|
|
+ "uploadedBy": "agent",
|
|
|
|
|
+ "source": path,
|
|
|
|
|
+ })
|
|
|
|
|
+ if r.get("code") == 200 and (r.get("id") or r.get("duplicated") is True):
|
|
|
|
|
+ claimed = r.get("claimed") is True
|
|
|
|
|
+ if claimed:
|
|
|
|
|
+ log("CLAIMED deliverableId=%s -> id=%s (认领 report 记录,未新建)"
|
|
|
|
|
+ % (deliverable_id, r.get("id")))
|
|
|
|
|
+ return {"ok": True, "id": r.get("id"), "key": key, "claimed": claimed,
|
|
|
|
|
+ "detail": "claimed" if claimed else ("duplicated" if r.get("duplicated") else "registered")}
|
|
|
|
|
+ return {"ok": False, "key": key,
|
|
|
|
|
+ "detail": "hub-failed:%s" % json.dumps(r, ensure_ascii=False)[:220]}
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _resolve_agent_id() -> str:
|
|
|
|
|
+ for p in ("/run/s6/container_environment/FMODE_AGENT_ID",
|
|
|
|
|
+ "/run/s6/container_environment/AGENT_ID"):
|
|
|
|
|
+ try:
|
|
|
|
|
+ v = Path(p).read_text(encoding="utf-8").strip()
|
|
|
|
|
+ if v:
|
|
|
|
|
+ return v
|
|
|
|
|
+ except OSError:
|
|
|
|
|
+ continue
|
|
|
|
|
+ return os.environ.get("FMODE_AGENT_ID") or os.environ.get("AGENT_ID") or "agent-node-lj-test"
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _token() -> str:
|
|
|
|
|
+ t = os.environ.get("FMODE_SESSION_TOKEN")
|
|
|
|
|
+ if t:
|
|
|
|
|
+ return t.strip()
|
|
|
|
|
+ for p in ("/run/s6/container_environment/FMODE_SESSION_TOKEN",
|
|
|
|
|
+ "/opt/data/.fmode/config/user.json"):
|
|
|
|
|
+ try:
|
|
|
|
|
+ raw = Path(p).read_text(encoding="utf-8").strip()
|
|
|
|
|
+ except OSError:
|
|
|
|
|
+ continue
|
|
|
|
|
+ if not raw:
|
|
|
|
|
+ continue
|
|
|
|
|
+ if p.endswith(".json"):
|
|
|
|
|
+ try:
|
|
|
|
|
+ d = json.loads(raw)
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ continue
|
|
|
|
|
+ for k in ("sessionToken", "session_token", "token"):
|
|
|
|
|
+ if d.get(k):
|
|
|
|
|
+ return str(d[k])
|
|
|
|
|
+ else:
|
|
|
|
|
+ return raw
|
|
|
|
|
+ return ""
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _ascii_safe_filename(name: str) -> str:
|
|
|
|
|
+ """OBS SigV2 签名对非 ASCII 对象名不兼容(PUT 会 403)。
|
|
|
|
|
+ 对象名转 ASCII,人文名保留在成果记录 title 里,链接末尾保留可读后缀。
|
|
|
|
|
+ """
|
|
|
|
|
+ import unicodedata
|
|
|
|
|
+ base, ext = os.path.splitext(name)
|
|
|
|
|
+ # 中文等非 ASCII 直接丢弃,只留 ASCII 词;全空则用时间戳兜底
|
|
|
|
|
+ keep = []
|
|
|
|
|
+ for ch in base:
|
|
|
|
|
+ if ord(ch) < 128:
|
|
|
|
|
+ keep.append(ch)
|
|
|
|
|
+ elif unicodedata.east_asian_width(ch) in ("W", "F"):
|
|
|
|
|
+ keep.append("-")
|
|
|
|
|
+ slug = re.sub(r"[-_\s]+", "-", "".join(keep)).strip("-.").lower()
|
|
|
|
|
+ slug = re.sub(r"[^a-z0-9._-]", "", slug)
|
|
|
|
|
+ if not slug:
|
|
|
|
|
+ slug = "deliverable-" + time.strftime("%Y%m%d-%H%M%S")
|
|
|
|
|
+ return slug[:80] + ext.lower()
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _content_key(path: str) -> str:
|
|
|
|
|
+ """文件内容指纹:同一内容重复推送时不重复登记(避免重试产生空 artifact 的脏记录)。"""
|
|
|
|
|
+ try:
|
|
|
|
|
+ h = hashlib.md5()
|
|
|
|
|
+ with open(path, "rb") as f:
|
|
|
|
|
+ for chunk in iter(lambda: f.read(1 << 20), b""):
|
|
|
|
|
+ h.update(chunk)
|
|
|
|
|
+ return h.hexdigest()
|
|
|
|
|
+ except OSError:
|
|
|
|
|
+ return ""
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _remote_matches(url: str, local_md5: str) -> bool:
|
|
|
|
|
+ """回读线上文件,md5 与本地一致才算复用有效。"""
|
|
|
|
|
+ if not url or not local_md5:
|
|
|
|
|
+ return False
|
|
|
|
|
+ try:
|
|
|
|
|
+ import urllib.request
|
|
|
|
|
+ from urllib.parse import quote as _q
|
|
|
|
|
+ with urllib.request.urlopen(_q(url, safe=":/?&=%@+~!$'()*,;#[]"), timeout=30) as r:
|
|
|
|
|
+ h = hashlib.md5(r.read()).hexdigest()
|
|
|
|
|
+ return h == local_md5
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ return False
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def upload_and_register(files: list[dict], title: str, summary: str) -> list[dict]:
|
|
|
|
|
+ """每一步都真实调用平台接口;返回 [{path,url,did,ok,detail}]。"""
|
|
|
|
|
+ push = _load_pusher()
|
|
|
|
|
+ agent_id = _resolve_agent_id()
|
|
|
|
|
+ paths = [f["path"] for f in files]
|
|
|
|
|
+ res: list[dict] = []
|
|
|
|
|
+
|
|
|
|
|
+ # 会话归属闸门:threadRoot 只决定「是否登记成果表」,**不决定是否上传**。
|
|
|
|
|
+ # 拿不到 threadRoot 时照常上传拿 URL(这才是交付物的本体),只是跳过登记步骤。
|
|
|
|
|
+ thread_root = _thread_root()
|
|
|
|
|
+ sid_env = os.environ.get("HERMES_SESSION_ID")
|
|
|
|
|
+ if not thread_root:
|
|
|
|
|
+ log("NO-THREADROOT sid=%s(照常上传,跳过登记)" % sid_env)
|
|
|
|
|
+ room_id = os.environ.get("HERMES_SESSION_CHAT_ID") or ""
|
|
|
|
|
+ # 兜底:hook 子进程偶尔没有该环境变量(cron/后台触发),从 state.db 的
|
|
|
|
|
+ # sessions.chat_id 补上。roomId 传空串会让云函数按 (user,"",fileUrl) 查重,
|
|
|
|
|
+ # 与 registerFile 写入时的真实 roomId 对不上 → 查不中 → 又新建第二条台账。
|
|
|
|
|
+ if not room_id and sid_env:
|
|
|
|
|
+ try:
|
|
|
|
|
+ import sqlite3
|
|
|
|
|
+ _con = sqlite3.connect("file:%s?mode=ro" % STATE_DB, uri=True, timeout=5)
|
|
|
|
|
+ try:
|
|
|
|
|
+ _row = _con.execute(
|
|
|
|
|
+ "SELECT chat_id FROM sessions WHERE id=?", (sid_env,)).fetchone()
|
|
|
|
|
+ finally:
|
|
|
|
|
+ _con.close()
|
|
|
|
|
+ if _row and _row[0]:
|
|
|
|
|
+ room_id = str(_row[0]).strip()
|
|
|
|
|
+ log("ROOMID-FALLBACK sid=%s -> room=%s" % (sid_env, room_id))
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ log("ROOMID-FALLBACK-FAIL sid=%s %s" % (sid_env, e))
|
|
|
|
|
+
|
|
|
|
|
+ for p in paths:
|
|
|
|
|
+ if not os.path.isfile(p):
|
|
|
|
|
+ res.append({"path": p, "ok": False, "detail": "missing"})
|
|
|
|
|
+ live = [p for p in paths if os.path.isfile(p)]
|
|
|
|
|
+ if not live:
|
|
|
|
|
+ return res
|
|
|
|
|
+
|
|
|
|
|
+ # ⓿ 幂等闸门:同一 (文件名, 内容md5) 已成功推过 → 直接复用旧 URL,不建新记录
|
|
|
|
|
+ # (平台无删除接口,重试留下空 artifact 的脏记录无法清理,所以必须在入口拦住)
|
|
|
|
|
+ ck = {p: _content_key(p) for p in live}
|
|
|
|
|
+ try:
|
|
|
|
|
+ hist = push.call({"action": "list", "agentId": agent_id, "limit": 50})
|
|
|
|
|
+ for old in (hist.get("deliverables") or []):
|
|
|
|
|
+ if not isinstance(old, dict):
|
|
|
|
|
+ continue
|
|
|
|
|
+ for art in (old.get("artifacts") or []):
|
|
|
|
|
+ # 历史记录里 artifacts 可能是纯字符串(老格式只存路径),跳过
|
|
|
|
|
+ if not isinstance(art, dict) or not art.get("url"):
|
|
|
|
|
+ continue
|
|
|
|
|
+ if _user_upload_url(art["url"]):
|
|
|
|
|
+ continue # 用户输入不能通过同名内容复用变成成果。
|
|
|
|
|
+ nm = art.get("name") or ""
|
|
|
|
|
+ src = art.get("source") or ""
|
|
|
|
|
+ # 同一文件名 + 线上内容 md5 与本地一致 → 判定为已推送过,直接复用
|
|
|
|
|
+ if nm and any(os.path.basename(s) == nm for s in ck):
|
|
|
|
|
+ cached_url = art["url"]
|
|
|
|
|
+ owner = next(s for s in ck if os.path.basename(s) == nm)
|
|
|
|
|
+ if _remote_matches(cached_url, ck[owner]):
|
|
|
|
|
+ if any(item.get("path") == owner and item.get("url") for item in res):
|
|
|
|
|
+ continue
|
|
|
|
|
+ hub = _hub_register(owner, cached_url, thread_root, room_id, old.get("id"))
|
|
|
|
|
+ digest = hashlib.sha256()
|
|
|
|
|
+ with open(owner, "rb") as stream:
|
|
|
|
|
+ for chunk in iter(lambda: stream.read(1 << 20), b""):
|
|
|
|
|
+ digest.update(chunk)
|
|
|
|
|
+ log("REUSE %s url=%s did=%s registered=%s" % (owner, cached_url, old.get("id"), hub.get("ok")))
|
|
|
|
|
+ res.append({"path": owner, "ok": hub.get("ok") is True, "url": cached_url,
|
|
|
|
|
+ "did": old.get("id"), "hub": hub, "sha256": digest.hexdigest(),
|
|
|
|
|
+ "detail": "reused-existing" if hub.get("ok") is True else "reuse-register-failed"})
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ log("IDEMPOTENT-CHECK-FAIL %s" % e)
|
|
|
|
|
+ reused = {r["path"] for r in res if r.get("ok") or r.get("detail") == "reuse-register-failed"}
|
|
|
|
|
+ # 同一路径只保留一条(历史里可能有多个内容相同的成功记录)
|
|
|
|
|
+ deduped, seen_paths = [], set()
|
|
|
|
|
+ for r in res:
|
|
|
|
|
+ if r.get("ok") and r["path"] in seen_paths:
|
|
|
|
|
+ continue
|
|
|
|
|
+ if r.get("ok"):
|
|
|
|
|
+ seen_paths.add(r["path"])
|
|
|
|
|
+ deduped.append(r)
|
|
|
|
|
+ res[:] = deduped
|
|
|
|
|
+ live = [p for p in live if p not in reused]
|
|
|
|
|
+ if not live:
|
|
|
|
|
+ return res
|
|
|
|
|
+
|
|
|
|
|
+ # ① report:建成果记录(artifacts 里带原始中文名,成果表可读)
|
|
|
|
|
+ # 2026-11-14 云函数 lfYlgU7SkK 已把 roomId/threadRoot/fileUrl 加入 UPDATABLE,
|
|
|
|
|
+ # 并在写入时从 artifacts[0] 提取 https 链接落顶层 fileUrl。
|
|
|
|
|
+ # 必须带上 roomId/threadRoot,registerFile 才能按 (user,roomId,fileUrl) 命中本条
|
|
|
|
|
+ # 返回 duplicated:true,而不是再新建第二条台账。
|
|
|
|
|
+ rep = push.call({"action": "report", "agentId": agent_id, "title": title,
|
|
|
|
|
+ "summary": summary,
|
|
|
|
|
+ "roomId": room_id,
|
|
|
|
|
+ "threadRoot": thread_root or "",
|
|
|
|
|
+ "artifacts": [{"name": os.path.basename(p), "source": p} for p in live],
|
|
|
|
|
+ "tags": ["auto-deliverable-hook"]})
|
|
|
|
|
+ did = rep.get("id")
|
|
|
|
|
+ if rep.get("code") != 200 or not did:
|
|
|
|
|
+ for p in live:
|
|
|
|
|
+ res.append({"path": p, "ok": False, "detail": "report-failed:%s" % json.dumps(rep, ensure_ascii=False)[:200]})
|
|
|
|
|
+ return res
|
|
|
|
|
+ log("REPORT did=%s agent=%s title=%s" % (did, agent_id, title))
|
|
|
|
|
+
|
|
|
|
|
+ # ② enqueueArtifact — 对象名必须纯 ASCII(OBS 签名限制),中文原名只留在 title/name
|
|
|
|
|
+ stored = {}
|
|
|
|
|
+ for idx, p in enumerate(live):
|
|
|
|
|
+ safe = _ascii_safe_filename(os.path.basename(p))
|
|
|
|
|
+ stored[p] = safe
|
|
|
|
|
+ push.call({"action": "enqueueArtifact", "deliverableId": did, "agentId": agent_id,
|
|
|
|
|
+ "source": p, "filename": safe, "index": idx})
|
|
|
|
|
+
|
|
|
|
|
+ # ③ pendingArtifacts → PUT → ackArtifact → ④ 回读校验
|
|
|
|
|
+ # 🔴 2026-11-17 并发正确性修复:pendingArtifacts 只按 agentId 取,返回的是**本 agent 的
|
|
|
|
|
+ # 全部**未 ack job。原来只按 source/filename 过滤,并发两个 turn 各自 report/enqueue 后
|
|
|
|
|
+ # 互取对方的 job:A 会 PUT+ack 掉 B 的文件(#36 串 did 的根因),B 再取就是空队列。
|
|
|
|
|
+ # 入队时就把 deliverableId=did 记住,这里只认 job.deliverableId == did。
|
|
|
|
|
+ # 平台侧老 job 不带该字段 → did_of(job) 为空 → 直接跳过(绝不退回「只按 agentId」的宽匹配)。
|
|
|
|
|
+ pend = push.call({"action": "pendingArtifacts", "agentId": agent_id})
|
|
|
|
|
+ jobs = pend.get("jobs") or []
|
|
|
|
|
+
|
|
|
|
|
+ def _job_did(j: dict) -> str:
|
|
|
|
|
+ return str(j.get("deliverableId") or j.get("deliverable_id") or "").strip()
|
|
|
|
|
+
|
|
|
|
|
+ foreign = [j for j in jobs if _job_did(j) and _job_did(j) != str(did)]
|
|
|
|
|
+ if foreign:
|
|
|
|
|
+ log("PENDING-ISOLATE did=%s 跳过他人 job %d 条(%s)"
|
|
|
|
|
+ % (did, len(foreign), sorted({_job_did(j) for j in foreign})[:5]))
|
|
|
|
|
+ my_jobs = [j for j in jobs if _job_did(j) == str(did)]
|
|
|
|
|
+ log("PENDING did=%s jobs_total=%d mine=%d" % (did, len(jobs), len(my_jobs)))
|
|
|
|
|
+ # 同一 source 可能残留多次入队的旧 job(尤其早期失败重试),
|
|
|
|
|
+ # 只认本次入队的 ASCII 文件名 + 尚未 ack 的那条,避免取到过期签名。
|
|
|
|
|
+ want = set(stored.values())
|
|
|
|
|
+ by_src = {}
|
|
|
|
|
+ for j in my_jobs:
|
|
|
|
|
+ src = j.get("source")
|
|
|
|
|
+ if src not in live:
|
|
|
|
|
+ continue
|
|
|
|
|
+ fname = (j.get("filename") or os.path.basename(j.get("uploadUrl", "").split("?")[0]))
|
|
|
|
|
+ ascii_ok = all(ord(c) < 128 for c in (j.get("uploadUrl") or ""))
|
|
|
|
|
+ if fname not in want and not ascii_ok:
|
|
|
|
|
+ continue
|
|
|
|
|
+ prev = by_src.get(src)
|
|
|
|
|
+ if prev is None or (ascii_ok and not all(ord(c) < 128 for c in (prev.get("uploadUrl") or ""))):
|
|
|
|
|
+ by_src[src] = j
|
|
|
|
|
+
|
|
|
|
|
+ for p in live:
|
|
|
|
|
+ j = by_src.get(p)
|
|
|
|
|
+ if not j:
|
|
|
|
|
+ res.append({"path": p, "ok": False, "did": did, "detail": "not-in-queue"})
|
|
|
|
|
+ log("PUSH-FAIL [%s: not-in-queue did=%s]" % (p, did))
|
|
|
|
|
+ continue
|
|
|
|
|
+ try:
|
|
|
|
|
+ data = open(p, "rb").read()
|
|
|
|
|
+ import urllib.request
|
|
|
|
|
+ import urllib.error as _uerr
|
|
|
|
|
+ from urllib.parse import quote
|
|
|
|
|
+ # 签名 URL 里的对象名可能含中文/空格;urllib 只接受 ASCII,需百分号编码
|
|
|
|
|
+ # (safe 保留 :/ ?&= 等 URL 结构字符,只编码路径与查询里的非 ASCII)
|
|
|
|
|
+ put_url = quote(j["uploadUrl"], safe=":/?&=%@+~!$'()*,;#[]")
|
|
|
|
|
+ req = urllib.request.Request(put_url, data=data, method="PUT")
|
|
|
|
|
+ for k, v in (j.get("headers") or {}).items():
|
|
|
|
|
+ req.add_header(k, v)
|
|
|
|
|
+ with urllib.request.urlopen(req, timeout=180) as r:
|
|
|
|
|
+ if r.status // 100 != 2:
|
|
|
|
|
+ raise RuntimeError("PUT status=%s" % r.status)
|
|
|
|
|
+ except _uerr.HTTPError as e:
|
|
|
|
|
+ body_txt = ""
|
|
|
|
|
+ try:
|
|
|
|
|
+ body_txt = e.read().decode("utf-8", "replace")[:200]
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ body_txt = "<unreadable>"
|
|
|
|
|
+ detail = "put-http-%s body=%s" % (e.code, body_txt)
|
|
|
|
|
+ push.call({"action": "ackArtifact", "objectId": j["id"], "ok": False, "error": detail[:200]})
|
|
|
|
|
+ res.append({"path": p, "ok": False, "did": did, "detail": detail})
|
|
|
|
|
+ log("PUSH-FAIL [%s: HTTP %s body=%s]" % (p, e.code, body_txt))
|
|
|
|
|
+ continue
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ detail = "put-failed:%s" % str(e)[:160]
|
|
|
|
|
+ push.call({"action": "ackArtifact", "objectId": j["id"], "ok": False, "error": str(e)[:200]})
|
|
|
|
|
+ res.append({"path": p, "ok": False, "did": did, "detail": detail})
|
|
|
|
|
+ log("PUSH-FAIL [%s: %s]" % (p, str(e)[:200]))
|
|
|
|
|
+ continue
|
|
|
|
|
+
|
|
|
|
|
+ url = j.get("publicUrl") or ""
|
|
|
|
|
+ push.call({"action": "ackArtifact", "objectId": j["id"], "ok": True, "publicUrl": url})
|
|
|
|
|
+
|
|
|
|
|
+ # 回读:字节数 + md5 必须一致
|
|
|
|
|
+ import urllib.request
|
|
|
|
|
+ from urllib.parse import quote as _q
|
|
|
|
|
+ try:
|
|
|
|
|
+ with urllib.request.urlopen(_q(url, safe=":/?&=%@+~!$'()*,;#[]"), timeout=120) as r:
|
|
|
|
|
+ got = r.read()
|
|
|
|
|
+ same = hashlib.md5(got).hexdigest() == hashlib.md5(data).hexdigest()
|
|
|
|
|
+ detail = "readback-ok bytes=%d" % len(got) if same else "readback-mismatch"
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ same, detail = False, "readback-error:%s" % str(e)[:120]
|
|
|
|
|
+
|
|
|
|
|
+ res.append({"path": p, "ok": same, "url": url, "did": did, "bytes": len(data), "sha256": hashlib.sha256(data).hexdigest(), "detail": detail})
|
|
|
|
|
+ log("PUSH %s ok=%s url=%s" % (p, same, url))
|
|
|
|
|
+
|
|
|
|
|
+ # ⑤ 新云函数 fmode-file-hub 登记:带 threadRoot 会话归属(老 lfYlgU7SkK 链路并存不动)
|
|
|
|
|
+ # 登记是可选步骤 —— 有 threadRoot 才登记;没有就跳过,文件本身已上云。
|
|
|
|
|
+ if same and url:
|
|
|
|
|
+ if thread_root:
|
|
|
|
|
+ hub = _hub_register(p, url, thread_root, room_id, deliverable_id=did)
|
|
|
|
|
+ else:
|
|
|
|
|
+ hub = {"ok": False, "skipped": True, "detail": "no-threadRoot"}
|
|
|
|
|
+ log("SKIP-REGISTER no threadRoot sid=%s(文件已上云,仅缺归属)%s" % (sid_env, p))
|
|
|
|
|
+ for r in res:
|
|
|
|
|
+ if r["path"] == p:
|
|
|
|
|
+ r["hub"] = hub
|
|
|
|
|
+ log("HUB %s ok=%s detail=%s id=%s" % (p, hub.get("ok"), hub.get("detail"), hub.get("id")))
|
|
|
|
|
+
|
|
|
|
|
+ # C-2 清理:**延迟清理**。
|
|
|
|
|
+ # 已上云且回读 md5 一致 → 不立即删;源文件必须活到「发送时刻」,
|
|
|
|
|
+ # 否则回复里的 MEDIA: /media-to-send 路径在 adapter 发送前就已消失。
|
|
|
|
|
+ # 真正的删除交给 /opt/data/scripts/fmode-media-gc.py(cron 每 30 分钟跑一次,
|
|
|
|
|
+ # 只清 pushed 登记里 mtime 超过 1 小时的源文件)。
|
|
|
|
|
+ if same:
|
|
|
|
|
+ log("DEFER-CLEANUP keep local %s(交给 fmode-media-gc.py,1h 后清理)" % p)
|
|
|
|
|
+ return res
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _scrub_local_paths(text: str) -> str:
|
|
|
|
|
+ """C-1:回复正文里绝不能出现容器本地路径。
|
|
|
|
|
+ 分三种情况,绝不留下「(本地工作目录)」这类假地址占位:
|
|
|
|
|
+ 1) 行内「本地路径:/opt/data/xxx.md」→ 整行删掉,交给「已上云」段给真地址
|
|
|
|
|
+ 2) 正文里的绝对路径 → 替换成裸文件名
|
|
|
|
|
+ 3) 已有的假占位文字 → 一并清掉
|
|
|
|
|
+ """
|
|
|
|
|
+ if not text:
|
|
|
|
|
+ return text
|
|
|
|
|
+
|
|
|
|
|
+ def _repl(m):
|
|
|
|
|
+ p = m.group(0).rstrip(",。、;:),.;:")
|
|
|
|
|
+ return os.path.basename(p)
|
|
|
|
|
+
|
|
|
|
|
+ # 0) 先删掉遗留的假占位(老版本插件写过;标点后面可能还跟着裸文字)
|
|
|
|
|
+ text = re.sub(r"[((]本地工作目录[))]", "", text)
|
|
|
|
|
+ text = re.sub(r"(?m)^\s*本地路径\s*[::]\s*$", "", text)
|
|
|
|
|
+
|
|
|
|
|
+ # 0.5) 「本地路径」行无论行首是否带 ** 粗体标记、无论后面是不是绝对路径,
|
|
|
|
|
+ # 整行删除。真地址一律由「已上云」段给出,正文不留任何本地线索。
|
|
|
|
|
+ text = re.sub(
|
|
|
|
|
+ r"(?m)^[ \t]*(?:\*\*|__)?[ \t]*(?:本地路径|本地文件|本地地址|存放路径|落盘路径)[ \t]*(?:\*\*|__)?[ \t]*[::][^\n]*\n?",
|
|
|
|
|
+ "",
|
|
|
|
|
+ text,
|
|
|
|
|
+ )
|
|
|
|
|
+ # 0.6) MEDIA: 行若指向本地目录占位符或不存在的文件,整行删除,避免 App 渲染出假附件;
|
|
|
|
|
+ # 指向真实文件的 MEDIA 行是渠道 adapter(企微原生附件等)的投递锚点,原样保留。
|
|
|
|
|
+ def _media_line(m):
|
|
|
|
|
+ target = m.group(1).strip().strip("`").strip()
|
|
|
|
|
+ return m.group(0) if target.startswith("/") and os.path.isfile(target) else ""
|
|
|
|
|
+
|
|
|
|
|
+ text = re.sub(r"(?m)^[ \t]*MEDIA:[ \t]*((?:[((]|/opt/data|/tmp|/home)[^\n]*)\n?", _media_line, text)
|
|
|
|
|
+ # 0.7) 兜底:占位符已被上一步清空后留下的裸「MEDIA:」空行,同样删除
|
|
|
|
|
+ text = re.sub(r"(?m)^[ \t]*MEDIA:[ \t]*$\n?", "", text)
|
|
|
|
|
+
|
|
|
|
|
+ # 2) 绝对路径:/opt/data/... /tmp/... /var/... /root/... /home/...(保留下来的 MEDIA 行除外)
|
|
|
|
|
+ media_lines: list[str] = []
|
|
|
|
|
+
|
|
|
|
|
+ def _park(m):
|
|
|
|
|
+ media_lines.append(m.group(0))
|
|
|
|
|
+ return "\x00MEDIA%d\x00" % (len(media_lines) - 1)
|
|
|
|
|
+
|
|
|
|
|
+ text = re.sub(r"(?m)^[ \t]*MEDIA:[^\n]*$", _park, text)
|
|
|
|
|
+ text = re.sub(r"/(?:opt/data|tmp|var/tmp|root|home)/[\w./\-]*[\w\-]", _repl, text)
|
|
|
|
|
+ for idx, line in enumerate(media_lines):
|
|
|
|
|
+ text = text.replace("\x00MEDIA%d\x00" % idx, line)
|
|
|
|
|
+
|
|
|
|
|
+ # 3) 收尾:清掉因整行删除留下的连续空行与空占位标点
|
|
|
|
|
+ text = re.sub(r"\n{3,}", "\n\n", text)
|
|
|
|
|
+ text = re.sub(r"(?m)^[ \t]*[::][ \t]*$", "", text)
|
|
|
|
|
+ text = re.sub(r"\n{3,}", "\n\n", text)
|
|
|
|
|
+ return text.strip()
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _mtime_or_0(path: str) -> float:
|
|
|
|
|
+ """源文件 mtime;文件已不在(或不可读)返回 0。GC 用它判断「上云时的源文件」时间。"""
|
|
|
|
|
+ try:
|
|
|
|
|
+ return os.path.getmtime(path)
|
|
|
|
|
+ except OSError:
|
|
|
|
|
+ return 0.0
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _title_for(files: list[dict], user_msg: str) -> str:
|
|
|
|
|
+ names = [os.path.basename(f["path"]) for f in files]
|
|
|
|
|
+ head = (user_msg or "").strip().splitlines()
|
|
|
|
|
+ demand = head[0][:60] if head else ""
|
|
|
|
|
+ if demand:
|
|
|
|
|
+ return demand if len(names) == 1 else "%s 等%d个文件" % (demand, len(names))
|
|
|
|
|
+ return names[0] if len(names) == 1 else "%s 等%d个文件" % (names[0], len(names))
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _storage_url(url: str) -> bool:
|
|
|
|
|
+ """成果存储域名上的地址才可能是「交付链接」;其他域名是普通参考链接。"""
|
|
|
|
|
+ from urllib.parse import urlsplit
|
|
|
|
|
+ try:
|
|
|
|
|
+ return (urlsplit(url).hostname or "").lower() in STORAGE_HOSTS
|
|
|
|
|
+ except ValueError:
|
|
|
|
|
+ return False
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _scrub_fake_urls(text: str, allowed: set) -> str:
|
|
|
|
|
+ """禁止输出编造的成果 URL。
|
|
|
|
|
+
|
|
|
|
|
+ 成果存储域名(STORAGE_HOSTS)上的链接必须是本轮 push 返回的真实地址:
|
|
|
|
|
+ - 在 allowed 白名单里 → 保留
|
|
|
|
|
+ - 不在白名单里 → 整条删掉(连同它所在行的标题性文字留白由调用方处理)
|
|
|
|
|
+ 其他域名是模型引用的普通参考链接(官方文档等),两个渠道都原样保留。
|
|
|
|
|
+ """
|
|
|
|
|
+ if not text:
|
|
|
|
|
+ return text
|
|
|
|
|
+ allowed = {u.rstrip("/") for u in allowed if isinstance(u, str) and u.startswith("http")}
|
|
|
|
|
+
|
|
|
|
|
+ def _repl(m):
|
|
|
|
|
+ url = m.group(0)
|
|
|
|
|
+ tail = re.split(r"[)\],。、;:\"'`]", url, maxsplit=1)
|
|
|
|
|
+ core = (tail[0] if tail else url).rstrip("/")
|
|
|
|
|
+ if core in allowed or not _storage_url(core):
|
|
|
|
|
+ return m.group(0) # 白名单内或普通参考链接:原样保留(含后面标点)
|
|
|
|
|
+ log("SCRUB-FAKE-URL %s" % core[:200])
|
|
|
|
|
+ return "" # 非白名单 → 删除
|
|
|
|
|
+
|
|
|
|
|
+ text = re.sub(r"https?://[^\s<>\"'`))]+", _repl, text)
|
|
|
|
|
+
|
|
|
|
|
+ # 删掉因 URL 被移除而变成空壳的行(只剩 -、*、短横线、括号)
|
|
|
|
|
+ text = re.sub(r"(?m)^[ \t]*[-*•]?[ \t]*[((]?[ \t]*[))]?[ \t]*$", "", text)
|
|
|
|
|
+ text = re.sub(r"[((][ \t]*[))]", "", text)
|
|
|
|
|
+ text = re.sub(r"(?m)^[ \t]*[-*•][ \t]*$\n?", "", text)
|
|
|
|
|
+ text = re.sub(r"\n{3,}", "\n\n", text)
|
|
|
|
|
+ return text.strip()
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _too_large_note() -> str:
|
|
|
|
|
+ """把本轮因超过 MAX_BYTES 被跳过的文件拼成一段说明(无文件时返回空串)。
|
|
|
|
|
+
|
|
|
|
|
+ 2026-11-14 用户裁决:超限必须有提示,不许静默丢弃。
|
|
|
|
|
+ """
|
|
|
|
|
+ if not TOO_LARGE:
|
|
|
|
|
+ return ""
|
|
|
|
|
+ lines = ["", "**⚠️ 超过交付上限,未上传云端**"]
|
|
|
|
|
+ seen = set()
|
|
|
|
|
+ for name, size in TOO_LARGE:
|
|
|
|
|
+ if name in seen:
|
|
|
|
|
+ continue
|
|
|
|
|
+ seen.add(name)
|
|
|
|
|
+ lines.append("- 文件「%s」有 %.1f MB,超过 %dMB 交付上限,未上传云端。"
|
|
|
|
|
+ % (name, _mb(size), MAX_BYTES // 1048576))
|
|
|
|
|
+ return "\n".join(lines)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _emit(text: str, allowed_urls=None) -> int:
|
|
|
|
|
+ """统一出口:净化 + 追加超限提示 + 输出 JSON。"""
|
|
|
|
|
+ body = _scrub_local_paths(text)
|
|
|
|
|
+ if allowed_urls is not None:
|
|
|
|
|
+ body = _scrub_fake_urls(body, allowed_urls)
|
|
|
|
|
+ note = _too_large_note()
|
|
|
|
|
+ if note:
|
|
|
|
|
+ body = body.rstrip() + "\n" + note
|
|
|
|
|
+ log("EMIT-TOO-LARGE-NOTE %s" % [n for n, _ in TOO_LARGE])
|
|
|
|
|
+ print(json.dumps({"response_text": body}, ensure_ascii=False))
|
|
|
|
|
+ return 0
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def handle_transform_llm_output(payload: dict) -> int:
|
|
|
|
|
+ """上传本轮排队成果,返回(必要时)替换后的回复文本。"""
|
|
|
|
|
+ text = payload.get("response_text") or ""
|
|
|
|
|
+ sid = payload.get("session_id") or "nosession"
|
|
|
|
|
+ rnd = load_round(sid)
|
|
|
|
|
+ turn_id = str(rnd.get("turn_id") or "").strip()
|
|
|
|
|
+ st = load_state(sid)
|
|
|
|
|
+ # 内部运行时/状态文件闸门(再次拦截):即使 queued[] 里已残留旧条目(收紧前入队的),
|
|
|
|
|
+ # 也不许上传、不许出现在「已上云」清单里 —— 直接丢弃并记日志。
|
|
|
|
|
+ _kept, _dropped = [], []
|
|
|
|
|
+ for q in st.get("queued", []):
|
|
|
|
|
+ if not isinstance(q, dict):
|
|
|
|
|
+ continue
|
|
|
|
|
+ if _denied(q.get("path") or ""):
|
|
|
|
|
+ _dropped.append(q.get("path"))
|
|
|
|
|
+ continue
|
|
|
|
|
+ _kept.append(q)
|
|
|
|
|
+ if _dropped:
|
|
|
|
|
+ st["queued"] = _kept
|
|
|
|
|
+ save_state(sid, st)
|
|
|
|
|
+ for _p in _dropped:
|
|
|
|
|
+ log("PURGE-INTERNAL %s reason=internal-state-file" % _p)
|
|
|
|
|
+ queued = [q for q in st.get("queued", [])
|
|
|
|
|
+ if isinstance(q, dict) and _queued_in_round(q, turn_id)
|
|
|
|
|
+ and os.path.isfile(q.get("path") or "")]
|
|
|
|
|
+
|
|
|
|
|
+ # 白名单:只有明确属于本轮的真实 push 成功地址允许出现在正文。
|
|
|
|
|
+ allowed_urls = {
|
|
|
|
|
+ p.get("url") for p in st.get("pushed", [])
|
|
|
|
|
+ if isinstance(p, dict) and isinstance(p.get("url"), str)
|
|
|
|
|
+ and p["url"].startswith("https://") and not _user_upload_url(p["url"])
|
|
|
|
|
+ and not _denied(p.get("path") or "") and _in_current_round(p, turn_id)
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ if not queued:
|
|
|
|
|
+ # 无交付物:仅做卫生清洗(清路径 / 清编造 URL),不改语义
|
|
|
|
|
+ return _emit(text, allowed_urls)
|
|
|
|
|
+
|
|
|
|
|
+ # 回复里已经给了真实 https(且不是本hook自己上一轮写的)→ 仍按队列判定是否已传过
|
|
|
|
|
+ pushed_paths = _pushed_current_paths(st, turn_id)
|
|
|
|
|
+ todo = [q for q in queued if q["path"] not in pushed_paths]
|
|
|
|
|
+
|
|
|
|
|
+ # 同轮同名文件去重(2026-11-11 用户裁决:index.html 被列两次)。
|
|
|
|
|
+ # 成因:同一份产物在旧目录(login-page/)和新目录(loginpage-1118/)各存一份,
|
|
|
|
|
+ # 两处都被 sweep 命中 → 上传成两个 S3 对象 → 正文出现两个同名链接。
|
|
|
|
|
+ # 规则:同 basename 且内容相同才只留 mtime 最新的那个;同名不同内容是两个成果,都上传。
|
|
|
|
|
+ if todo:
|
|
|
|
|
+ _by_name: dict[tuple[str, str], dict] = {}
|
|
|
|
|
+ for q in todo:
|
|
|
|
|
+ _nm = os.path.basename(str(q.get("path") or "")).lower()
|
|
|
|
|
+ if not _nm:
|
|
|
|
|
+ continue
|
|
|
|
|
+ _key = (_nm, _content_key(q["path"]) or q["path"])
|
|
|
|
|
+ _prev = _by_name.get(_key)
|
|
|
|
|
+ if _prev is None:
|
|
|
|
|
+ _by_name[_key] = q
|
|
|
|
|
+ continue
|
|
|
|
|
+ try:
|
|
|
|
|
+ _keep = q if os.path.getmtime(q["path"]) >= os.path.getmtime(_prev["path"]) else _prev
|
|
|
|
|
+ except OSError:
|
|
|
|
|
+ _keep = q
|
|
|
|
|
+ _drop = _prev if _keep is q else q
|
|
|
|
|
+ log("DEDUPE-SAME-NAME drop=%s keep=%s" % (_drop.get("path"), _keep.get("path")))
|
|
|
|
|
+ _by_name[_key] = _keep
|
|
|
|
|
+ _keep_ids = {id(v) for v in _by_name.values()}
|
|
|
|
|
+ _deduped = [q for q in todo if id(q) in _keep_ids]
|
|
|
|
|
+ if len(_deduped) != len(todo):
|
|
|
|
|
+ log("DEDUPE-SUM %d -> %d" % (len(todo), len(_deduped)))
|
|
|
|
|
+ todo = _deduped
|
|
|
|
|
+ if not todo:
|
|
|
|
|
+ st["queued"] = [q for q in st.get("queued", [])
|
|
|
|
|
+ if not (_queued_in_round(q, turn_id) and q.get("path") in pushed_paths)]
|
|
|
|
|
+ save_state(sid, st)
|
|
|
|
|
+ return _emit(text, allowed_urls)
|
|
|
|
|
+
|
|
|
|
|
+ user_msg = ""
|
|
|
|
|
+ extra = payload.get("extra") if isinstance(payload.get("extra"), dict) else {}
|
|
|
|
|
+ for k in ("user_message", "original_user_message", "prompt"):
|
|
|
|
|
+ v = payload.get(k) or extra.get(k)
|
|
|
|
|
+ if isinstance(v, str) and v.strip():
|
|
|
|
|
+ user_msg = v
|
|
|
|
|
+ break
|
|
|
|
|
+
|
|
|
|
|
+ title = _title_for(todo, user_msg)
|
|
|
|
|
+ summary = "自动上云:由 post_tool_call hook 判定为交付成果"
|
|
|
|
|
+
|
|
|
|
|
+ results = upload_and_register(todo, title, summary)
|
|
|
|
|
+ ok = [r for r in results if r.get("ok") and r.get("url")]
|
|
|
|
|
+ bad = [r for r in results if not r.get("ok") and not r.get("skipped")]
|
|
|
|
|
+
|
|
|
|
|
+ # ② 日志语义:三种状态必须分清,不能「没执行也打失败」
|
|
|
|
|
+ if not results:
|
|
|
|
|
+ log("PUSH-SKIP reason=no-results(upload_and_register 未产出任何结果)sid=%s" % sid)
|
|
|
|
|
+ elif ok and not bad:
|
|
|
|
|
+ log("PUSH-OK %s" % json.dumps([r["url"] for r in ok], ensure_ascii=False))
|
|
|
|
|
+ elif ok and bad:
|
|
|
|
|
+ log("PUSH-OK %s" % json.dumps([r["url"] for r in ok], ensure_ascii=False))
|
|
|
|
|
+ log("PUSH-FAIL %s" % json.dumps(
|
|
|
|
|
+ [{"path": b["path"], "reason": str(b.get("detail"))[:200]} for b in bad],
|
|
|
|
|
+ ensure_ascii=False))
|
|
|
|
|
+ else:
|
|
|
|
|
+ log("PUSH-FAIL %s" % json.dumps(
|
|
|
|
|
+ [{"path": b["path"], "reason": str(b.get("detail"))[:200]} for b in bad],
|
|
|
|
|
+ ensure_ascii=False))
|
|
|
|
|
+
|
|
|
|
|
+ # 成功后清理队列,记录已推送
|
|
|
|
|
+ for r in ok:
|
|
|
|
|
+ st.setdefault("pushed", []).append({
|
|
|
|
|
+ "path": r["path"], "url": r["url"], "did": r.get("did"), "ts": int(time.time()),
|
|
|
|
|
+ "src_mtime": int(_mtime_or_0(r["path"])), "gc": False,
|
|
|
|
|
+ "uploadedAt": int(time.time() * 1000),
|
|
|
|
|
+ "cloudAck": True,
|
|
|
|
|
+ "hubRegistered": isinstance(r.get("hub"), dict) and r["hub"].get("ok") is True,
|
|
|
|
|
+ "sha256": r.get("sha256"), # FMODE_VERIFIED_DELIVERABLE_ACK_V1
|
|
|
|
|
+ "turn_id": turn_id,
|
|
|
|
|
+ })
|
|
|
|
|
+ st["queued"] = [q for q in st.get("queued", [])
|
|
|
|
|
+ if not (_queued_in_round(q, turn_id) and q.get("path") in {r["path"] for r in ok})]
|
|
|
|
|
+ save_state(sid, st)
|
|
|
|
|
+
|
|
|
|
|
+ # 写台账
|
|
|
|
|
+ try:
|
|
|
|
|
+ LEDGER.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
|
+ with LEDGER.open("a", encoding="utf-8") as f:
|
|
|
|
|
+ for r in results:
|
|
|
|
|
+ f.write(json.dumps({**r, "session": sid, "ts": int(time.time())}, ensure_ascii=False) + "\n")
|
|
|
|
|
+ except OSError:
|
|
|
|
|
+ pass
|
|
|
|
|
+
|
|
|
|
|
+ if not ok:
|
|
|
|
|
+ if not bad:
|
|
|
|
|
+ # 没执行(例如无候选/全部被复用/前置条件不满足)≠ 失败
|
|
|
|
|
+ log("PUSH-SKIP reason=no-attempted-files sid=%s" % sid)
|
|
|
|
|
+ # C-1 失败路径:明确说「已生成但未上云」+ 原因,绝不拿本地路径冒充交付
|
|
|
|
|
+ lines = ["", "**⚠️ 文件已生成但未上云**"]
|
|
|
|
|
+ for b in bad:
|
|
|
|
|
+ lines.append("- %s:上传失败(%s)" % (os.path.basename(b["path"]), str(b.get("detail"))[:120]))
|
|
|
|
|
+ if not bad:
|
|
|
|
|
+ lines.append("- 本次未执行上传(无可用候选文件)")
|
|
|
|
|
+ return _emit(text.rstrip() + "\n" + "\n".join(lines))
|
|
|
|
|
+
|
|
|
|
|
+ # 先净化正文:清本地路径 + 清掉所有非白名单的编造 URL
|
|
|
|
|
+ ok_urls = {r["url"] for r in ok}
|
|
|
|
|
+ allowed_all = allowed_urls | ok_urls
|
|
|
|
|
+ body = _scrub_fake_urls(_scrub_local_paths(text.rstrip()), allowed_all)
|
|
|
|
|
+
|
|
|
|
|
+ # 只有在「真链接没出现在正文里」时才补交付段。
|
|
|
|
|
+ # 注意:判据是「本轮 push 回来的真地址是否已在正文」,绝不能用「正文里有任意 https」
|
|
|
|
|
+ # —— 否则模型自己编的假链接会把真链接挡在门外(历史缺陷)。
|
|
|
|
|
+ missing = [r["url"] for r in ok if r["url"] not in body]
|
|
|
|
|
+ if not missing:
|
|
|
|
|
+ return _emit(body)
|
|
|
|
|
+
|
|
|
|
|
+ lines = ["", "**已上云(可直接下载)**"]
|
|
|
|
|
+ for r in ok:
|
|
|
|
|
+ if r["url"] in missing:
|
|
|
|
|
+ lines.append("- %s → %s" % (os.path.basename(r["path"]), r["url"]))
|
|
|
|
|
+ if bad:
|
|
|
|
|
+ lines.append("- ⚠️ 未能上传:%s" % "、".join(os.path.basename(b["path"]) for b in bad))
|
|
|
|
|
+ new_text = body + "\n" + "\n".join(lines)
|
|
|
|
|
+ return _emit(new_text, allowed_all)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def handle_share(session_id: str, paths: list[str], title: str) -> int:
|
|
|
|
|
+ """模型主动分享文件(plugin-fmode-share 工具调用):上传 S3 + 登记成果表,打印链接 JSON。
|
|
|
|
|
+
|
|
|
|
|
+ 记进本会话 pushed,post_tool_call/sweep 不会再把同一文件排队上传一次。
|
|
|
|
|
+ """
|
|
|
|
|
+ sid = session_id or "nosession"
|
|
|
|
|
+ os.environ.setdefault("HERMES_SESSION_ID", sid)
|
|
|
|
|
+ turn_id = str(load_round(sid).get("turn_id") or "").strip()
|
|
|
|
|
+ files, out = [], []
|
|
|
|
|
+ for raw_path in paths:
|
|
|
|
|
+ ap = os.path.abspath(os.path.expanduser(raw_path))
|
|
|
|
|
+ why = _denied(ap)
|
|
|
|
|
+ if why or not os.path.isfile(ap):
|
|
|
|
|
+ out.append({"name": os.path.basename(ap), "ok": False, "error": why or "文件不存在"})
|
|
|
|
|
+ continue
|
|
|
|
|
+ files.append({"path": ap})
|
|
|
|
|
+ if files:
|
|
|
|
|
+ st = load_state(sid)
|
|
|
|
|
+ results = upload_and_register(files, title or os.path.basename(files[0]["path"]), "模型调用分享工具")
|
|
|
|
|
+ for r in results:
|
|
|
|
|
+ ok = bool(r.get("ok") and r.get("url"))
|
|
|
|
|
+ out.append({"name": os.path.basename(r["path"]), "ok": ok, "url": r.get("url") if ok else None,
|
|
|
|
|
+ "error": None if ok else str(r.get("detail") or "上传失败")[:200]})
|
|
|
|
|
+ if ok:
|
|
|
|
|
+ st.setdefault("pushed", []).append({
|
|
|
|
|
+ "path": r["path"], "url": r["url"], "did": r.get("did"), "ts": int(time.time()),
|
|
|
|
|
+ "src_mtime": int(_mtime_or_0(r["path"])), "gc": False,
|
|
|
|
|
+ "uploadedAt": int(time.time() * 1000), "cloudAck": True,
|
|
|
|
|
+ "hubRegistered": isinstance(r.get("hub"), dict) and r["hub"].get("ok") is True,
|
|
|
|
|
+ "sha256": r.get("sha256"), "turn_id": turn_id, "shared": True,
|
|
|
|
|
+ })
|
|
|
|
|
+ st["queued"] = [q for q in st.get("queued", [])
|
|
|
|
|
+ if q.get("path") not in {r["path"] for r in results if r.get("ok")}]
|
|
|
|
|
+ save_state(sid, st)
|
|
|
|
|
+ log("SHARE sid=%s %s" % (sid, json.dumps(out, ensure_ascii=False)))
|
|
|
|
|
+ print(json.dumps({"files": out}, ensure_ascii=False))
|
|
|
|
|
+ return 0 if out and all(o["ok"] for o in out) else 1
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+# ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
|
+def main() -> int:
|
|
|
|
|
+ if sys.argv[1:2] == ["share"]:
|
|
|
|
|
+ import argparse
|
|
|
|
|
+ ap = argparse.ArgumentParser(prog="fmode-deliverable-hook.py share")
|
|
|
|
|
+ ap.add_argument("--session", default=os.environ.get("HERMES_SESSION_ID", ""))
|
|
|
|
|
+ ap.add_argument("--title", default="")
|
|
|
|
|
+ ap.add_argument("paths", nargs="+")
|
|
|
|
|
+ args = ap.parse_args(sys.argv[2:])
|
|
|
|
|
+ return handle_share(args.session, args.paths, args.title)
|
|
|
|
|
+ raw = sys.stdin.read() or "{}"
|
|
|
|
|
+ try:
|
|
|
|
|
+ payload = json.loads(raw)
|
|
|
|
|
+ except Exception:
|
|
|
|
|
+ payload = {}
|
|
|
|
|
+ event = payload.get("hook_event_name") or payload.get("event") or ""
|
|
|
|
|
+ try:
|
|
|
|
|
+ if event == "post_tool_call":
|
|
|
|
|
+ return handle_post_tool_call(payload)
|
|
|
|
|
+ if event == "transform_llm_output":
|
|
|
|
|
+ return handle_transform_llm_output(payload)
|
|
|
|
|
+ # CLI 手动测试用
|
|
|
|
|
+ if sys.argv[1:2] == ["classify"]:
|
|
|
|
|
+ for p in sys.argv[2:]:
|
|
|
|
|
+ ok, why = classify(p)
|
|
|
|
|
+ print(json.dumps({"path": p, "deliverable": ok, "reason": why}, ensure_ascii=False))
|
|
|
|
|
+ return 0
|
|
|
|
|
+ if sys.argv[1:2] == ["rules"]:
|
|
|
|
|
+ print(RULES_DOC)
|
|
|
|
|
+ return 0
|
|
|
|
|
+ except Exception as e:
|
|
|
|
|
+ log("ERROR event=%s %s" % (event, e))
|
|
|
|
|
+ if event == "transform_llm_output":
|
|
|
|
|
+ print(json.dumps({"response_text": payload.get("response_text") or ""}, ensure_ascii=False))
|
|
|
|
|
+ return 0
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+if __name__ == "__main__":
|
|
|
|
|
+ sys.exit(main())
|