__init__.py 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013
  1. """事件驱动主动上报 · plugin-active-reporter
  2. 把「定时轮询上报」改成「turn 事件驱动上报」。
  3. 触发点(这就是我调研的结论 —— 用的是真正的 turn 生命周期 hook,
  4. 不是上一版方案里说的 pre_api_request / post_api_request):
  5. * pre_llm_call → 每个 turn 开始时**整轮只触发一次**,报 status=running + currentTask
  6. * post_llm_call → 每个 turn 结束后**整轮只触发一次**(turn_finalizer._apply_output_hooks
  7. 注释原文 "Fire transform_llm_output then post_llm_call once per turn"),
  8. 报 status=idle
  9. * 心跳 → 后台线程,1 小时 + 每容器随机偏移,只报 heartbeatAt + balance
  10. **为什么不需要去重**:post_llm_call 本身是 once-per-turn 语义(源码在
  11. /opt/hermes/agent/turn_finalizer.py:_apply_output_hooks),不是 pre_api_request 那种
  12. 每个 API 调用都触发。所以任务书里要求的「本 turn 是否已报过 idle」标记在这里天然不需要。
  13. 仍然保留了一个按 turn_id 的幂等保护,纯属防御(防止同一 turn 被重复 finalize)。
  14. **不阻塞回复**:所有 HTTP 都在后台线程里跑,主路径只做一次 dict 赋值。
  15. 失败静默、有超时、绝不重试到卡住。
  16. """
  17. from __future__ import annotations
  18. import json
  19. import os
  20. import random
  21. import re
  22. import sqlite3
  23. import threading
  24. import time
  25. import urllib.parse
  26. import urllib.request
  27. import urllib.error
  28. from pathlib import Path
  29. from typing import Any
  30. HOME = Path(os.environ.get("HERMES_HOME") or os.environ.get("HOME") or "/opt/data")
  31. SKILL_SCRIPTS = HOME / "git-repos" / "agent-status-reporter" / "scripts"
  32. STATE_DIR = HOME / ".fmode" / "active-reporter"
  33. STATE = STATE_DIR / "state.json"
  34. LOG = STATE_DIR / "plugin.log"
  35. FUNCTION_ID = "xlosi3m46q"
  36. API_BASE = "https://server.fmode.cn/api/functions"
  37. APP_ID = "ncloudmaster"
  38. HEARTBEAT_BASE_SEC = float(os.environ.get("ACTIVE_REPORT_HEARTBEAT_SEC", "3600"))
  39. # 进程启动时随机一次(0~900 秒),之后每次心跳固定用这个偏移,间隔可预测、容器间自然错峰
  40. HEARTBEAT_JITTER_SEC = float(os.environ.get("ACTIVE_REPORT_HEARTBEAT_JITTER", "900"))
  41. BALANCE_WARN = float(os.environ.get("ACTIVE_REPORT_BALANCE_WARN", "10"))
  42. HTTP_TIMEOUT = float(os.environ.get("ACTIVE_REPORT_TIMEOUT", "8"))
  43. _LOG_LOCK = threading.Lock()
  44. _SENT_LOCK = threading.Lock()
  45. _SENT_TURNS: dict[str, str] = {} # turn_id -> 最后一次上报的状态(幂等保护,防重复 finalize)
  46. _BG: set[threading.Thread] = set()
  47. # 会话级状态:session_key -> {"status": "running"|"idle", "turnStartAt": epoch_ms, "updatedAt": epoch_ms}
  48. # 进程内内存即可,gateway 重启后由后续 turn 重新填充。
  49. #
  50. # updatedAt = 该会话状态最后一次变化的时间(turn 开始或结束),是 App 判断
  51. # 「这条会话新鲜还是别的会话在跑」的依据;turnStartAt 只是本轮开始的时刻,
  52. # 一个 30 秒的 turn 结束后 turnStartAt 会显得很旧,绝不能拿它当新鲜度用。
  53. _ACTIVE_SESSIONS: dict[str, dict] = {}
  54. _IDLE_TTL_MS = 10 * 60 * 1000 # idle 记录超过 10 分钟清理,防字典无限增长
  55. _RUNNING_STALE_MS = 2 * 60 * 60 * 1000 # running 记录兜底上限:进程被杀/hook 丢失时不至于永远 running
  56. _ACTIVE_LOCK = threading.Lock()
  57. # 内部 session_id -> thread_id 的进程内缓存,避免每次上报都查库
  58. _THREAD_CACHE: dict[str, str | None] = {}
  59. _THREAD_LOCK = threading.Lock()
  60. # extra 的写前合并策略(任务 1):
  61. # 每次都 GET 云端当前 extra 作为底,以云端为准,本地只覆盖 currentSessions/extraUpdatedAt。
  62. # GET 失败 → 返回 None → **跳过本次 extra 写入**(heartbeatAt 等常规字段照常写),
  63. # 下轮自然重试。绝不把失败结果固化成 {} 当底,否则一次抖动就会把所有业务键抹掉。
  64. # 这里只保留一个「最近一次成功读到的底」作为失败时的诊断参考,不参与合并。
  65. _EXTRA_LAST_OK: dict | None = None
  66. _EXTRA_FAILS = 0 # 连续失败次数(日志用,不阻断重试)
  67. _EXTRA_LOCK = threading.Lock()
  68. _HEARTBEAT_STARTED = False
  69. # ------------------------------------------------------------------ utils
  70. def _log(msg: str) -> None:
  71. try:
  72. STATE_DIR.mkdir(parents=True, exist_ok=True)
  73. line = "%s %s\n" % (time.strftime("%Y-%m-%d %H:%M:%S"), msg)
  74. with _LOG_LOCK:
  75. with open(LOG, "a", encoding="utf-8") as f:
  76. f.write(line)
  77. except Exception:
  78. pass
  79. def _read_cred(key: str) -> str:
  80. """按 容器 s6 环境文件 → 数据目录 .fmode/ → 进程环境 的顺序读一个凭据。"""
  81. for p in ("/run/s6/container_environment/" + key,
  82. str(HOME / ".fmode" / key.lower())):
  83. try:
  84. v = Path(p).read_text(encoding="utf-8").strip()
  85. if v:
  86. return v
  87. except Exception:
  88. continue
  89. return os.environ.get(key, "").strip()
  90. def _session_token() -> str:
  91. """过门用的 Parse 会话(2026-12-04 双 Token)。
  92. 🔴 平台入口 `/api/functions` 只拿 body.token 查 _Session,
  93. 非会话 token(64 hex 访问凭证)一律 401 —— 这就是新提示词容器「永远离线」的根因。
  94. 专属会话缺失时回落到旧变量(老容器 env 里可能把它叫 FMODE_SESSION_TOKEN 或用户 token)。
  95. """
  96. return _read_cred("FMODE_SESSION_TOKEN")
  97. def _access_token() -> str:
  98. """身份与有效期判定用的容器访问凭证(写到 params.accessToken)。
  99. 老容器没有这个变量 → 返回空,云函数自然走 owner 回落通道(兼容)。
  100. """
  101. return _read_cred("FMODE_ACCESS_TOKEN")
  102. def _token() -> str:
  103. """对话框等「只带一个 token」的场景用:有会话用会话,没会话退回访问凭证。"""
  104. return _session_token() or _access_token()
  105. def _agent_id() -> str:
  106. for p in ("/run/s6/container_environment/AGENT_ID",):
  107. try:
  108. v = Path(p).read_text(encoding="utf-8").strip()
  109. if v:
  110. return v
  111. except Exception:
  112. continue
  113. return os.environ.get("AGENT_ID", "").strip()
  114. # 入口层(HAProxy 后端池)会随机对有效 token 回 401/403,属已知抖动:
  115. # 同 token 连调可出现 401/200/401 交替。故 401/403 视为可重试,最多 8 次、间隔 1.5s。
  116. # 注意区分业务层真 403:响应体 {"code":403,"mess":"无权更新该 Agent..."} 是归属校验失败,
  117. # 重试无用 —— 只有响应体不含业务 code 的 401/403 才按入口抖动重试。
  118. _CALL_RETRIES = 8
  119. _CALL_RETRY_GAP = 1.5
  120. # 心跳失败后的补推间隔:8 次重试全败 -> 睡 300s 后整轮重来,直到恢复
  121. HEARTBEAT_RETRY_SLEEP_SEC = float(os.environ.get("ACTIVE_REPORT_FAIL_SLEEP_SEC", "300"))
  122. def _is_entry_jitter(code: int, body_txt: str) -> bool:
  123. """是否属于「值得重试的网关/入口层失败」。
  124. - 401/403:入口层 HAProxy 后端池坏实例会随机拒绝有效 token,响应体无业务 code 即为假失败
  125. - 5xx:网关/上游瞬时错误,可重试
  126. - 业务语义错误(4xx 且响应体带明确 code/error 字段):不重试,重试无用
  127. """
  128. if code >= 500:
  129. return True
  130. if code not in (401, 403):
  131. return False
  132. try:
  133. j = json.loads(body_txt)
  134. except Exception:
  135. return True
  136. return "code" not in j
  137. def _call(params: dict, timeout: float = HTTP_TIMEOUT) -> dict:
  138. """调云函数。最多尝试 _CALL_RETRIES(8) 次,每次间隔 _CALL_RETRY_GAP(1.5s)。
  139. 仅对「网关/入口层类失败」重试:401/403(响应体无业务 code 的假拒绝)、5xx、
  140. 超时与连接类异常。业务语义错误(4xx 且响应体带明确错误码)立即抛出,不重试。
  141. 全部尝试耗尽后抛出最后一次异常。调用方(_push/_heartbeat_loop)负责吞掉异常,
  142. 调用发生在后台线程内,不阻塞主流程。
  143. """
  144. # 双 Token(2026-12-04):SESSION 过门,ACCESS 判身份与有效期
  145. access = _access_token()
  146. if access:
  147. params = dict(params or {}, accessToken=access)
  148. body = json.dumps({"id": FUNCTION_ID, "token": _session_token(), "params": params}).encode()
  149. last_exc = None
  150. for attempt in range(_CALL_RETRIES):
  151. req = urllib.request.Request(API_BASE, data=body, headers={
  152. "Content-Type": "application/json",
  153. "X-Parse-Application-Id": APP_ID})
  154. try:
  155. with urllib.request.urlopen(req, timeout=timeout) as r:
  156. return json.loads(r.read())
  157. except urllib.error.HTTPError as e:
  158. try:
  159. txt = e.read().decode("utf-8", "replace")
  160. except Exception:
  161. txt = ""
  162. if _is_entry_jitter(e.code, txt) and attempt < _CALL_RETRIES - 1:
  163. _log("entry jitter %d, retry %d/%d" % (e.code, attempt + 1, _CALL_RETRIES))
  164. time.sleep(_CALL_RETRY_GAP)
  165. last_exc = e
  166. continue
  167. raise
  168. except Exception as e:
  169. last_exc = e
  170. if attempt < _CALL_RETRIES - 1:
  171. time.sleep(_CALL_RETRY_GAP)
  172. continue
  173. raise
  174. if last_exc:
  175. raise last_exc
  176. raise RuntimeError("call failed")
  177. def _push(fields: dict) -> bool:
  178. """把若干字段写进 FmodeAgent 表。后台线程调用,异常全吞。"""
  179. agent_id = _agent_id()
  180. if not agent_id or not _session_token():
  181. _log("skip: no agent_id/session-token")
  182. return False
  183. ok = True
  184. for field, value in fields.items():
  185. try:
  186. res = _call({"op": "update", "agentId": agent_id, "field": field, "value": value})
  187. if res.get("code") != 200:
  188. ok = False
  189. _log("update %s failed: %s" % (field, str(res)[:160]))
  190. except Exception as e:
  191. ok = False
  192. _log("update %s error: %s" % (field, str(e)[:160]))
  193. return ok
  194. def _bg(fn, *args) -> None:
  195. """fire-and-forget 线程,主路径立即返回。"""
  196. def _run():
  197. try:
  198. fn(*args)
  199. except Exception as e:
  200. _log("bg error: %s" % str(e)[:200])
  201. t = threading.Thread(target=_run, daemon=True)
  202. _BG.add(t)
  203. t.start()
  204. # 清掉已结束的线程引用,避免无限增长
  205. if len(_BG) > 32:
  206. for x in [x for x in _BG if not x.is_alive()]:
  207. _BG.discard(x)
  208. def _state_read() -> dict:
  209. try:
  210. return json.loads(STATE.read_text(encoding="utf-8"))
  211. except Exception:
  212. return {}
  213. def _state_write(d: dict) -> None:
  214. try:
  215. STATE_DIR.mkdir(parents=True, exist_ok=True)
  216. STATE.write_text(json.dumps(d, ensure_ascii=False), encoding="utf-8")
  217. except Exception:
  218. pass
  219. def _now_iso() -> str:
  220. return time.strftime("%Y-%m-%dT%H:%M:%S+08:00", time.localtime())
  221. def _balance_value() -> tuple[str, float | None]:
  222. """查余额,返回 (要上报的字符串, 数值)。查不到就返回 ('', None)。"""
  223. try:
  224. # 余额查询走用户维度,用过门会话(访问凭证不是会话)
  225. body = json.dumps({"sessionToken": _session_token(), "page": 1, "pageSize": 1}).encode()
  226. req = urllib.request.Request(
  227. "https://server.fmode.cn/api/functions/lfYlgU7SkK",
  228. data=body, headers={"Content-Type": "application/json",
  229. "X-Parse-Application-Id": APP_ID})
  230. with urllib.request.urlopen(req, timeout=HTTP_TIMEOUT) as r:
  231. d = json.loads(r.read())
  232. # 该函数不返回余额时静默降级
  233. v = d.get("balance") if isinstance(d, dict) else None
  234. if v is None:
  235. return "", None
  236. return json.dumps({"balance": v, "currency": "CNY"}), float(v)
  237. except Exception:
  238. return "", None
  239. def _warn_suffix(bal: float | None) -> str:
  240. if bal is not None and bal < BALANCE_WARN:
  241. return " · ⚠️ 余额 ¥%.2f 偏低,请充值" % bal
  242. return ""
  243. # ------------------------------------------------------------------ session registry
  244. def _now_ms() -> int:
  245. return int(time.time() * 1000)
  246. def _prune_locked(now: int) -> None:
  247. """清理过期记录。调用方必须已持有 _ACTIVE_LOCK。
  248. 两条规则:
  249. * idle 且 updatedAt(无则回退 turnStartAt)超过 _IDLE_TTL_MS → 删
  250. * running 且 updatedAt 超过 _RUNNING_STALE_MS → 删(兜底:hook 丢失/进程异常时
  251. 不能让一条记录永远显示 running,否则 App 会一直以为该会话在跑)
  252. """
  253. stale = []
  254. for k, v in _ACTIVE_SESSIONS.items():
  255. stamp = int(v.get("updatedAt") or v.get("turnStartAt") or 0)
  256. age = now - stamp
  257. if v.get("status") == "idle" and age > _IDLE_TTL_MS:
  258. stale.append(k)
  259. elif v.get("status") == "running" and age > _RUNNING_STALE_MS:
  260. stale.append(k)
  261. for k in stale:
  262. _ACTIVE_SESSIONS.pop(k, None)
  263. if stale:
  264. _log("pruned %d stale session(s)" % len(stale))
  265. def _prune_sessions() -> int:
  266. """对外入口:心跳前也调它,让清理不再依赖「有新 turn 发生」。"""
  267. now = _now_ms()
  268. with _ACTIVE_LOCK:
  269. before = len(_ACTIVE_SESSIONS)
  270. _prune_locked(now)
  271. return before - len(_ACTIVE_SESSIONS)
  272. def _session_mark_running(session_key: str, task: str = "") -> None:
  273. """标记某会话开始跑,并记下**本会话本轮**的提问摘要。顺带清掉过期的 idle 记录。
  274. task 只属于这个 session_key:容器级 currentTask 是「最近一次 turn」的,
  275. 多会话并发时会让用户在会话 B 里看到会话 A 的任务名,所以会话级必须独立存。
  276. """
  277. now = _now_ms()
  278. with _ACTIVE_LOCK:
  279. _ACTIVE_SESSIONS[session_key] = {
  280. "status": "running", "turnStartAt": now, "updatedAt": now,
  281. "task": task or "",
  282. }
  283. _prune_locked(now)
  284. def _session_mark_idle(session_key: str) -> None:
  285. """标记某会话跑完:保留原 turnStartAt(本轮开始时刻),同时刷新 updatedAt。
  286. task 一并清空——任务名只在 running 时有意义,idle 还留着会让 App 显示
  287. 「这个会话还在做那件事」。
  288. """
  289. now = _now_ms()
  290. with _ACTIVE_LOCK:
  291. prev = _ACTIVE_SESSIONS.get(session_key) or {}
  292. _ACTIVE_SESSIONS[session_key] = {
  293. "status": "idle",
  294. "turnStartAt": prev.get("turnStartAt") or now,
  295. "updatedAt": now,
  296. "task": "",
  297. }
  298. _prune_locked(now)
  299. def _state_db_path() -> str:
  300. """定位 state.db。优先环境变量,其次常见路径。"""
  301. env = os.environ.get("HERMES_STATE_DB")
  302. if env and os.path.exists(env):
  303. return env
  304. for cand in ("/opt/hermes/state.db", (os.environ.get("HERMES_HOME") or "/opt/data") + "/state.db"):
  305. if os.path.exists(cand):
  306. return cand
  307. return ""
  308. def _thread_id_of(session_id: str) -> str | None:
  309. """内部 session_id -> thread_id(形如 $approot_xxx:fmode.cn)。
  310. 只读查库,带进程内缓存。任何异常都返回 None,绝不让异常冒泡到钩子。
  311. """
  312. if not session_id:
  313. return None
  314. with _THREAD_LOCK:
  315. if session_id in _THREAD_CACHE:
  316. return _THREAD_CACHE[session_id]
  317. tid: str | None = None
  318. try:
  319. path = _state_db_path()
  320. if path:
  321. conn = sqlite3.connect("file:%s?mode=ro" % path, uri=True, timeout=2)
  322. try:
  323. row = conn.execute(
  324. "SELECT thread_id FROM sessions WHERE id = ?", (session_id,)
  325. ).fetchone()
  326. if row and isinstance(row[0], str) and row[0].strip():
  327. tid = row[0].strip()
  328. finally:
  329. conn.close()
  330. except Exception as e:
  331. _log("thread_id lookup failed for %s: %s" % (session_id, str(e)[:120]))
  332. tid = None
  333. # 只缓存查到的非空值:turn 开始时 thread_id 可能还没写进库(NULL),
  334. # 若把 None 也缓存下来,该会话此后永远命中缓存、永远回落到内部 id。
  335. if tid:
  336. with _THREAD_LOCK:
  337. _THREAD_CACHE[session_id] = tid
  338. if len(_THREAD_CACHE) > 500:
  339. for k in list(_THREAD_CACHE)[:250]:
  340. _THREAD_CACHE.pop(k, None)
  341. return tid
  342. _INTERNAL_ID_RE = re.compile(r"^\d{8}_\d{6}_[0-9a-f]{6,}$")
  343. def _looks_internal_id(v: str | None) -> bool:
  344. """判断一个 session 标识是不是网关内部 id(如 20261111_195708_eebcd2d8)。
  345. App 侧靠 !roomId / $approot_xxx 这类真标识匹配,内部 id 永远匹配不上。
  346. """
  347. if not v:
  348. return True
  349. v = v.strip()
  350. if not v:
  351. return True
  352. return bool(_INTERNAL_ID_RE.match(v))
  353. def _chat_id_of(session_id: str) -> str | None:
  354. """内部 session_id -> chat_id(Matrix roomId,形如 !xxxx:fmode.cn)。只读查库,带缓存。"""
  355. if not session_id:
  356. return None
  357. key = "chat:" + session_id
  358. with _THREAD_LOCK:
  359. if key in _THREAD_CACHE:
  360. return _THREAD_CACHE[key]
  361. cid: str | None = None
  362. try:
  363. path = _state_db_path()
  364. if path:
  365. conn = sqlite3.connect("file:%s?mode=ro" % path, uri=True, timeout=2)
  366. try:
  367. row = conn.execute(
  368. "SELECT chat_id FROM sessions WHERE id = ?", (session_id,)
  369. ).fetchone()
  370. if row and isinstance(row[0], str) and row[0].strip():
  371. cid = row[0].strip()
  372. finally:
  373. conn.close()
  374. except Exception as e:
  375. _log("chat_id lookup failed for %s: %s" % (session_id, str(e)[:120]))
  376. cid = None
  377. if cid:
  378. with _THREAD_LOCK:
  379. _THREAD_CACHE[key] = cid
  380. if len(_THREAD_CACHE) > 500:
  381. for k in list(_THREAD_CACHE)[:250]:
  382. _THREAD_CACHE.pop(k, None)
  383. return cid
  384. def _user_id_of(session_id: str) -> str | None:
  385. """内部 session_id -> user_id(形如 @xhvrjtmwqh:fmode.cn)。只读查库,带缓存。
  386. 照 _chat_id_of() 的模式:只查 sessions 表、进程内缓存、异常静默并写日志。
  387. 查不到返回 None —— 调用方据此省略字段,而不是写空串。
  388. """
  389. if not session_id:
  390. return None
  391. key = "user:" + session_id
  392. with _THREAD_LOCK:
  393. if key in _THREAD_CACHE:
  394. return _THREAD_CACHE[key]
  395. uid: str | None = None
  396. try:
  397. path = _state_db_path()
  398. if path:
  399. conn = sqlite3.connect("file:%s?mode=ro" % path, uri=True, timeout=2)
  400. try:
  401. row = conn.execute(
  402. "SELECT user_id FROM sessions WHERE id = ?", (session_id,)
  403. ).fetchone()
  404. if row and isinstance(row[0], str) and row[0].strip():
  405. uid = row[0].strip()
  406. finally:
  407. conn.close()
  408. except Exception as e:
  409. _log("user_id lookup failed for %s: %s" % (session_id, str(e)[:120]))
  410. uid = None
  411. if uid:
  412. with _THREAD_LOCK:
  413. _THREAD_CACHE[key] = uid
  414. if len(_THREAD_CACHE) > 500:
  415. for k in list(_THREAD_CACHE)[:250]:
  416. _THREAD_CACHE.pop(k, None)
  417. return uid
  418. def _session_key_for(session_id: str) -> str:
  419. """sessionKey 取值优先级(任务 2):thread_id → chat_id(roomId) → 内部 id。
  420. - thread_id 为 NULL/空/内部 id 形态 → 不能用,往下走
  421. - chat_id 是 Matrix roomId(! 开头)→ 用它,App 的 includes() 能匹配上
  422. - 都没有 → 才回落到内部 id(此时 App 匹配不上,属于最差情况)
  423. 已知代价:roomId 粒度比 thread 粗,同房间的多条会话会互相误判。这是主动选择:
  424. 「完全匹配不上」比「偶尔误判」更糟。
  425. """
  426. tid = _thread_id_of(session_id)
  427. if tid and not _looks_internal_id(tid):
  428. return tid
  429. cid = _chat_id_of(session_id)
  430. if cid and not _looks_internal_id(cid):
  431. return cid
  432. return tid or cid or session_id
  433. def _sessions_snapshot() -> list[dict]:
  434. """转成上报用的列表:sessionKey 按 thread_id → chat_id → 内部 id 的优先级取。
  435. 每条带三个时间:turnStartAt(本轮开始)、updatedAt(状态最后变化)、
  436. ttlMs(该记录还能活多久,idle→10 分钟,running→2 小时)。App 可以据此
  437. 直接判断「这条是不是还新鲜」,不必自己猜。
  438. 注意:先出锁再查库,不在持锁期间做 IO。
  439. """
  440. with _ACTIVE_LOCK:
  441. items = [(k, v.get("status"), v.get("turnStartAt"), v.get("updatedAt"),
  442. v.get("task") or "")
  443. for k, v in _ACTIVE_SESSIONS.items()]
  444. rows: list[dict] = []
  445. for k, status, started, updated, task in items:
  446. row: dict[str, Any] = {
  447. "sessionKey": _session_key_for(k),
  448. "status": status,
  449. "turnStartAt": started,
  450. "updatedAt": updated or started,
  451. "ttlMs": _IDLE_TTL_MS if status == "idle" else _RUNNING_STALE_MS,
  452. }
  453. # userId 只在真查到时才落字段;查不到/查询异常一律省略该键
  454. uid = _user_id_of(k)
  455. if uid:
  456. row["userId"] = uid
  457. # task 只在 running 且本轮确实拿到提问时才有值;否则省略该键,不编造
  458. if status == "running" and task:
  459. row["task"] = task
  460. rows.append(row)
  461. return rows
  462. def _extra_cloud() -> dict | None:
  463. """GET 云端当前 extra。成功返回 dict(可能为空 dict),**失败返回 None**。
  464. 任务 1 的核心修复:失败绝不返回 {}。{} 会被上层当成「云端本来就没键」,
  465. 一写就把业务键全抹掉。返回 None 让上层明确区分「读到空的」和「没读到」。
  466. """
  467. global _EXTRA_LAST_OK, _EXTRA_FAILS
  468. try:
  469. old = _call({"op": "get", "agentId": _agent_id()}, timeout=HTTP_TIMEOUT)
  470. if old.get("code") != 200:
  471. with _EXTRA_LOCK:
  472. _EXTRA_FAILS += 1
  473. n = _EXTRA_FAILS
  474. _log("extra cloud read non-200 (%s), skip extra write this round; consecutive=%d"
  475. % (str(old)[:120], n))
  476. return None
  477. agent = old.get("agent") or {}
  478. raw = agent.get("extra")
  479. base: dict[str, Any] = {}
  480. if isinstance(raw, str):
  481. if raw.strip():
  482. loaded = json.loads(raw)
  483. if not isinstance(loaded, dict):
  484. _log("extra cloud read: extra is str but not an object, skip write")
  485. return None
  486. base = loaded
  487. elif isinstance(raw, dict):
  488. base = dict(raw)
  489. elif raw is None:
  490. base = {}
  491. else:
  492. _log("extra cloud read: unexpected extra type %s, skip write" % type(raw).__name__)
  493. return None
  494. with _EXTRA_LOCK:
  495. _EXTRA_FAILS = 0
  496. _EXTRA_LAST_OK = dict(base)
  497. return base
  498. except Exception as e:
  499. with _EXTRA_LOCK:
  500. _EXTRA_FAILS += 1
  501. n = _EXTRA_FAILS
  502. _log("extra cloud read failed (%s), skip extra write this round; consecutive=%d"
  503. % (str(e)[:160], n))
  504. return None
  505. def _extra_value() -> str | None:
  506. """构造 extra:以**本次 GET 到的云端值**为底,只更新 currentSessions/extraUpdatedAt。
  507. 返回 None 表示本轮读不到云端底 —— 调用方必须跳过 extra 写入,
  508. 只写 heartbeatAt 等常规字段,等下轮重试。
  509. """
  510. base = _extra_cloud()
  511. if base is None:
  512. return None
  513. extra_obj = dict(base)
  514. extra_obj["currentSessions"] = _sessions_snapshot()
  515. extra_obj["extraUpdatedAt"] = _now_iso() # 与其他字段一致,用 ISO 字符串
  516. return json.dumps(extra_obj, ensure_ascii=False)
  517. def _push_with_sessions(fields: dict) -> bool:
  518. """先写常规字段,再把会话快照合并进 extra。
  519. extra 写失败/读不到时不重试、不影响常规字段,也不污染云端 —— 下一轮再来。
  520. """
  521. ok = _push(fields)
  522. try:
  523. extra = _extra_value()
  524. if extra is None:
  525. # 任务 1:读不到云端底就跳过本次 extra 写入,heartbeatAt 已由 _push 写过了
  526. _log("extra write skipped (cloud base unavailable); other fields already written")
  527. return ok
  528. res = _call({"op": "update", "agentId": _agent_id(),
  529. "field": "extra", "value": extra})
  530. if res.get("code") != 200:
  531. ok = False
  532. _log("update extra failed: %s" % str(res)[:160])
  533. except Exception as e:
  534. ok = False
  535. _log("update extra error: %s" % str(e)[:160])
  536. return ok
  537. # ------------------------------------------------------------------ hooks
  538. def _on_pre_llm_call(**kw: Any) -> None:
  539. """turn 开始:整轮只触发一次。整段只做赋值 + 起线程,不阻塞。"""
  540. turn_id = str(kw.get("turn_id") or "")
  541. # 会话标识:hook 实际传的是 session_id(turn_context.py:695 / turn_finalizer.py:422)
  542. session_key = str(kw.get("session_id") or kw.get("sessionKey") or "")
  543. user_msg = kw.get("user_message")
  544. # 只取首行、截断,避免把用户原文大段写进平台字段
  545. if isinstance(user_msg, str):
  546. task = user_msg.strip().splitlines()[0][:60] if user_msg.strip() else ""
  547. else:
  548. task = str(user_msg)[:60] if user_msg else ""
  549. platform = str(kw.get("platform") or "")
  550. with _SENT_LOCK:
  551. if turn_id and _SENT_TURNS.get(turn_id) == "running":
  552. return
  553. if turn_id:
  554. _SENT_TURNS[turn_id] = "running"
  555. if len(_SENT_TURNS) > 200:
  556. for k in list(_SENT_TURNS)[:100]:
  557. _SENT_TURNS.pop(k, None)
  558. # 会话级状态登记(同步、持锁时间极短):task 存进本会话自己的记录
  559. if session_key:
  560. _session_mark_running(session_key, task)
  561. action = "处理中" + ("(%s)" % platform if platform else "")
  562. def _work():
  563. bal_str, bal_val = _balance_value()
  564. fields = {
  565. "status": "running",
  566. "currentTask": task,
  567. "currentAction": action + _warn_suffix(bal_val),
  568. "heartbeatAt": {"__type": "Date", "iso": _now_iso()},
  569. }
  570. if bal_str:
  571. fields["balance"] = bal_str
  572. _push_with_sessions(fields)
  573. st = _state_read()
  574. st.update({"last_status": "running", "last_turn": turn_id, "last_at": time.time()})
  575. _state_write(st)
  576. _log("turn start -> running session=%s task=%r" % (session_key[-40:] or "-", task))
  577. _bg(_work)
  578. # ---------------------------------------------------------------- Matrix turn_status 推送
  579. #
  580. # App 拉云函数是 15 秒轮询,turn 结束后「正在执行」要等 30 秒左右才停。
  581. # 这里在 turn 收尾时额外推一个自定义 Matrix 事件 com.fmode.turn_status,
  582. # App 收到即刷新,不用等轮询。
  583. #
  584. # 与 ✅ reaction 完全独立:✅ 仍只表示「这条消息发完了」,本事件表示「这一轮结束了」。
  585. # 发送失败只记日志,绝不影响 turn 收尾与原有上报。
  586. _MATRIX_ENV: dict[str, str] | None = None
  587. _MATRIX_ENV_LOCK = threading.Lock()
  588. def _matrix_env() -> dict[str, str]:
  589. """读 MATRIX_HOMESERVER / MATRIX_ACCESS_TOKEN。优先进程环境,其次 /opt/data/.env。
  590. .env 只在首次读取并解析,之后进程内缓存。
  591. """
  592. global _MATRIX_ENV
  593. with _MATRIX_ENV_LOCK:
  594. if _MATRIX_ENV is not None:
  595. return _MATRIX_ENV
  596. out: dict[str, str] = {}
  597. for k in ("MATRIX_HOMESERVER", "MATRIX_ACCESS_TOKEN"):
  598. v = os.environ.get(k, "").strip()
  599. if v:
  600. out[k] = v
  601. if not out.get("MATRIX_HOMESERVER") or not out.get("MATRIX_ACCESS_TOKEN"):
  602. try:
  603. for line in open(str(HOME / ".env"), encoding="utf-8", errors="ignore"):
  604. line = line.strip()
  605. if not line or line.startswith("#") or "=" not in line:
  606. continue
  607. k, v = line.split("=", 1)
  608. k = k.strip()
  609. if k in ("MATRIX_HOMESERVER", "MATRIX_ACCESS_TOKEN") and k not in out:
  610. out[k] = v.strip().strip('"').strip("'")
  611. except Exception:
  612. pass
  613. _MATRIX_ENV = out
  614. return out
  615. def _room_id_of_session(session_id: str) -> str | None:
  616. """内部 session_id -> Matrix roomId。复用 _chat_id_of 的只读查库与缓存。"""
  617. return _chat_id_of(session_id)
  618. def _push_turn_status(session_id: str, status: str) -> None:
  619. """往当前会话所在房间推一个 com.fmode.turn_status 事件。失败静默,只记日志。"""
  620. try:
  621. if not session_id:
  622. return
  623. env = _matrix_env()
  624. hs = env.get("MATRIX_HOMESERVER", "").rstrip("/")
  625. tok = env.get("MATRIX_ACCESS_TOKEN", "")
  626. if not hs or not tok:
  627. _log("turn_status skip: no MATRIX_HOMESERVER/TOKEN")
  628. return
  629. room = _room_id_of_session(session_id)
  630. if not room:
  631. _log("turn_status skip: no room for session=%s" % session_id)
  632. return
  633. # sessionKey 与 currentSessions 上报保持同一口径:thread_id → chat_id → 内部 id
  634. key = _session_key_for(session_id)
  635. content = {"sessionKey": key, "status": status}
  636. # 有 thread 就发进同一个 thread,否则 App 在 thread 视图里看不到
  637. tid = _thread_id_of(session_id)
  638. if tid and not _looks_internal_id(tid):
  639. content["m.relates_to"] = {"rel_type": "m.thread", "event_id": tid}
  640. txn = "ts%d" % int(time.time() * 1000)
  641. url = "%s/_matrix/client/v3/rooms/%s/send/com.fmode.turn_status/%s" % (
  642. hs, urllib.parse.quote(room, safe=""), txn)
  643. body = json.dumps(content).encode("utf-8")
  644. req = urllib.request.Request(url, data=body, method="PUT", headers={
  645. "Authorization": "Bearer " + tok,
  646. "Content-Type": "application/json",
  647. })
  648. with urllib.request.urlopen(req, timeout=HTTP_TIMEOUT) as resp:
  649. raw = resp.read().decode("utf-8", "replace")
  650. eid = ""
  651. try:
  652. eid = json.loads(raw).get("event_id", "")
  653. except Exception:
  654. pass
  655. _log("turn_status sent status=%s room=%s key=%s event=%s" % (status, room, key, eid))
  656. except Exception as e:
  657. _log("turn_status failed: %s" % str(e)[:200])
  658. def _on_post_llm_call(**kw: Any) -> None:
  659. """turn 结束:once-per-turn。这里天然不需要「本 turn 是否已报过 idle」的去重机制。"""
  660. turn_id = str(kw.get("turn_id") or "")
  661. session_key = str(kw.get("session_id") or kw.get("sessionKey") or "")
  662. with _SENT_LOCK:
  663. if turn_id and _SENT_TURNS.get(turn_id) == "idle":
  664. return # 纯防御:同一 turn 被重复 finalize 时不重复发
  665. if turn_id:
  666. _SENT_TURNS[turn_id] = "idle"
  667. # 先把本会话标记 idle,再判断全局是否还有别的会话在跑
  668. if session_key:
  669. _session_mark_idle(session_key)
  670. # 立刻推一个 Matrix turn_status 事件给 App(与 ✅ reaction 独立,失败不影响主流程)
  671. _push_turn_status(session_key, "idle")
  672. still_running = [s for s in _sessions_snapshot() if s.get("status") == "running"]
  673. def _work():
  674. bal_str, bal_val = _balance_value()
  675. if still_running:
  676. # 别的会话还在跑 —— 全局 status 保持 running,不覆盖它
  677. fields = {
  678. "status": "running",
  679. "currentTask": "",
  680. "currentAction": ("仍有 %d 个会话执行中%s"
  681. % (len(still_running), _warn_suffix(bal_val))),
  682. "heartbeatAt": {"__type": "Date", "iso": _now_iso()},
  683. }
  684. log_msg = "turn end -> session idle, %d still running" % len(still_running)
  685. st_status = "running"
  686. else:
  687. fields = {
  688. "status": "idle",
  689. "currentTask": "",
  690. "currentAction": ("空闲" + _warn_suffix(bal_val)).strip(),
  691. "heartbeatAt": {"__type": "Date", "iso": _now_iso()},
  692. }
  693. log_msg = "turn end -> idle"
  694. st_status = "idle"
  695. if bal_str:
  696. fields["balance"] = bal_str
  697. _push_with_sessions(fields)
  698. st = _state_read()
  699. st.update({"last_status": st_status, "last_turn": turn_id, "last_at": time.time()})
  700. _state_write(st)
  701. _log(log_msg)
  702. _bg(_work)
  703. # ------------------------------------------------------------------ heartbeat
  704. def _heartbeat_loop() -> None:
  705. """1 小时基础间隔 + 进程启动时随机一次的固定偏移(0~15 分钟),多容器自然错峰。
  706. 偏移只在进程启动时算一次并保持:每轮重新随机会让间隔忽长忽短、无法预测。
  707. 心跳**必须**带 currentSessions:App 靠 extra.currentSessions 判断「这条会话在跑
  708. 还是别的会话在跑」。若只在 turn 事件写,两个 turn 之间的长静默期里 App 拿到的
  709. 就是上一次的快照,而 idle 会话再过 10 分钟就被删掉 —— 表现为「会话列表空了/
  710. 显示成别的会话」。所以心跳前先 _prune_sessions()(顺带把过期的清掉),再用
  711. _push_with_sessions() 把当前快照写进 extra。
  712. 心跳不改 status/currentTask/currentAction —— 业务状态由 turn 事件负责,
  713. 心跳碰它会覆盖真实状态。
  714. **健壮性**(本点由 _heartbeat_once 承担):
  715. * 启动即推一次,避免重启后最长一个心跳周期的盲区
  716. * 单次推送内部已有 8x1.5s 重试(在 _call 里)
  717. * 若仍失败,缩短为 HEARTBEAT_RETRY_SLEEP_SEC(300s) 后补推,
  718. 补推成功即恢复原 interval;持续失败则每 300s 一轮
  719. 所有重试都只发生在该后台线程内,不阻塞主流程。
  720. """
  721. # 启动时随机一次,之后恒定(周期算法保持不变)
  722. jitter = random.uniform(0, HEARTBEAT_JITTER_SEC)
  723. interval = HEARTBEAT_BASE_SEC + jitter
  724. _log("heartbeat thread started base=%.1fs jitter=%.1fs (fixed) interval=%.1fs"
  725. % (HEARTBEAT_BASE_SEC, jitter, interval))
  726. # 启动即推一次:避免重启后最长一个 interval 的盲区
  727. ok = _heartbeat_once(jitter)
  728. if ok:
  729. _log("heartbeat startup push ok; entering loop with interval=%.0fs" % interval)
  730. next_sleep = interval
  731. else:
  732. _log("heartbeat startup push failed; retry in %.0fs" % HEARTBEAT_RETRY_SLEEP_SEC)
  733. next_sleep = HEARTBEAT_RETRY_SLEEP_SEC
  734. while True:
  735. time.sleep(next_sleep)
  736. ok = _heartbeat_once(jitter)
  737. if ok:
  738. next_sleep = interval
  739. else:
  740. _log("heartbeat push failed after retries; retry in %.0fs"
  741. % HEARTBEAT_RETRY_SLEEP_SEC)
  742. next_sleep = HEARTBEAT_RETRY_SLEEP_SEC
  743. def _fmode_channel_snapshot():
  744. import json as _json
  745. import os as _os
  746. import time as _time
  747. from pathlib import Path as _Path
  748. home = _Path(_os.environ.get("HERMES_HOME", "/opt/data"))
  749. try:
  750. platforms = _json.loads((home / "gateway_state.json").read_text()).get("platforms") or {}
  751. except (OSError, ValueError, TypeError, AttributeError):
  752. platforms = {}
  753. if not isinstance(platforms, dict):
  754. platforms = {}
  755. def _state(name):
  756. entry = platforms.get(name)
  757. return entry.get("state", "unknown") if isinstance(entry, dict) else "unknown"
  758. # Report every platform the gateway knows about: the status function merges
  759. # channels per key, so a Matrix-only snapshot would hide a connected WeCom bot.
  760. state = _state("matrix")
  761. snapshot = {"matrix": state == "connected", "matrixConfig": {
  762. "homeserver": _os.environ.get("MATRIX_HOMESERVER", "https://matrix.fmode.cn"),
  763. "userId": _os.environ.get("MATRIX_USER_ID", ""),
  764. "channelState": state,
  765. "listenerOk": state == "connected",
  766. }}
  767. wecom_state = _state("wecom")
  768. if "wecom" in platforms or _os.environ.get("WECOM_BOT_ID"):
  769. snapshot["wecom"] = wecom_state == "connected"
  770. snapshot["wecomConfig"] = {"botId": _os.environ.get("WECOM_BOT_ID", ""), "channelState": wecom_state}
  771. if _os.environ.get("WECOM_BOT_ID"):
  772. snapshot["wecomBotId"] = _os.environ["WECOM_BOT_ID"]
  773. snapshot["platformStates"] = {name: _state(name) for name in sorted(platforms)}
  774. snapshot["observedAt"] = int(_time.time() * 1000)
  775. return snapshot
  776. def _start_app_channels():
  777. import json as _json
  778. import threading as _threading
  779. import time as _time
  780. def publish():
  781. for _ in range(75):
  782. _time.sleep(2)
  783. channels = _fmode_channel_snapshot()
  784. if channels["matrix"]:
  785. try:
  786. if _push_with_sessions({"channels": _json.dumps(channels, ensure_ascii=False)}):
  787. _log("app matrix channels registered")
  788. return
  789. except Exception:
  790. pass
  791. _log("app matrix channels pending; heartbeat will retry")
  792. _threading.Thread(target=publish, name="app-channels", daemon=True).start()
  793. def _start_fmode_heartbeat():
  794. import os as _os
  795. import random as _random
  796. import threading as _threading
  797. import time as _time
  798. global _FMODE_HEARTBEAT_STARTED
  799. if globals().get("_FMODE_HEARTBEAT_STARTED"):
  800. return
  801. if _os.environ.get("AGENT_STATUS_ENABLED", "true").strip().lower() == "false":
  802. _log("app heartbeat disabled by configuration")
  803. return
  804. try:
  805. interval = max(60, int(_os.environ.get("AGENT_STATUS_HEARTBEAT", "3600")))
  806. jitter = max(0, min(900, int(_os.environ.get("AGENT_STATUS_JITTER", "900"))))
  807. except (TypeError, ValueError):
  808. interval, jitter = 3600, 900
  809. _FMODE_HEARTBEAT_STARTED = True
  810. def run():
  811. # Send one immediate liveness snapshot so a newly provisioned container can be verified.
  812. try:
  813. _heartbeat_once(0)
  814. except Exception as _exc:
  815. _log("app heartbeat failed: %s" % type(_exc).__name__)
  816. while True:
  817. _time.sleep(interval + _random.uniform(0, jitter))
  818. try:
  819. _heartbeat_once(0)
  820. except Exception as _exc:
  821. _log("app heartbeat failed: %s" % type(_exc).__name__)
  822. _threading.Thread(target=run, name="fmode-jittered-heartbeat", daemon=True).start()
  823. def _heartbeat_once(jitter: float) -> bool:
  824. """执行一轮心跳推送。返回是否成功。异常全吞,只记日志。"""
  825. try:
  826. # 1) 先清理过期会话 —— 不依赖「有新 turn 发生」,空闲容器也能收敛
  827. pruned = _prune_sessions()
  828. # 2) 取当前快照(必须在心跳里取,不能复用 turn 开始时的旧值)
  829. rows = _sessions_snapshot()
  830. bal_str, bal_val = _balance_value()
  831. fields = {"heartbeatAt": {"__type": "Date", "iso": _now_iso()}}
  832. fields["channels"] = json.dumps(_fmode_channel_snapshot(), ensure_ascii=False)
  833. if bal_str:
  834. fields["balance"] = bal_str
  835. # 3) 带 currentSessions 一起上(_push_with_sessions 会写 extra)
  836. ok = _push_with_sessions(fields)
  837. st = _state_read()
  838. st.update({"last_heartbeat": time.time(), "jitter": round(jitter, 1),
  839. "last_heartbeat_sessions": len(rows),
  840. "last_heartbeat_pruned": pruned,
  841. "last_heartbeat_ok": bool(ok)})
  842. _state_write(st)
  843. _log("heartbeat sent (jitter=%.0fs, sessions=%d, pruned=%d, ok=%s)"
  844. % (jitter, len(rows), pruned, ok))
  845. return bool(ok)
  846. except Exception as e:
  847. _log("heartbeat error: %s" % str(e)[:200])
  848. return False
  849. def _start_heartbeat() -> None:
  850. global _HEARTBEAT_STARTED
  851. if _HEARTBEAT_STARTED:
  852. return
  853. _HEARTBEAT_STARTED = True
  854. t = threading.Thread(target=_heartbeat_loop, daemon=True, name="active-reporter-heartbeat")
  855. t.start()
  856. _log("heartbeat thread started base=%ss jitter=0~%ss" % (HEARTBEAT_BASE_SEC, HEARTBEAT_JITTER_SEC))
  857. # ------------------------------------------------------------------ register
  858. def register(ctx) -> None:
  859. ctx.register_hook("pre_llm_call", _on_pre_llm_call)
  860. ctx.register_hook("post_llm_call", _on_post_llm_call)
  861. _start_fmode_heartbeat()
  862. _start_app_channels()
  863. _log("registered: pre_llm_call, post_llm_call, heartbeat")