__init__.py 39 KB

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