| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984 |
- """事件驱动主动上报 · plugin-active-reporter
- 把「定时轮询上报」改成「turn 事件驱动上报」。
- 触发点(这就是我调研的结论 —— 用的是真正的 turn 生命周期 hook,
- 不是上一版方案里说的 pre_api_request / post_api_request):
- * pre_llm_call → 每个 turn 开始时**整轮只触发一次**,报 status=running + currentTask
- * post_llm_call → 每个 turn 结束后**整轮只触发一次**(turn_finalizer._apply_output_hooks
- 注释原文 "Fire transform_llm_output then post_llm_call once per turn"),
- 报 status=idle
- * 心跳 → 后台线程,1 小时 + 每容器随机偏移,只报 heartbeatAt + balance
- **为什么不需要去重**:post_llm_call 本身是 once-per-turn 语义(源码在
- /opt/hermes/agent/turn_finalizer.py:_apply_output_hooks),不是 pre_api_request 那种
- 每个 API 调用都触发。所以任务书里要求的「本 turn 是否已报过 idle」标记在这里天然不需要。
- 仍然保留了一个按 turn_id 的幂等保护,纯属防御(防止同一 turn 被重复 finalize)。
- **不阻塞回复**:所有 HTTP 都在后台线程里跑,主路径只做一次 dict 赋值。
- 失败静默、有超时、绝不重试到卡住。
- """
- from __future__ import annotations
- import json
- import os
- import random
- import re
- import sqlite3
- import threading
- import time
- import urllib.parse
- import urllib.request
- import urllib.error
- from pathlib import Path
- from typing import Any
- HOME = Path(os.environ.get("HERMES_HOME") or os.environ.get("HOME") or "/opt/data")
- SKILL_SCRIPTS = HOME / "git-repos" / "agent-status-reporter" / "scripts"
- STATE_DIR = HOME / ".fmode" / "active-reporter"
- STATE = STATE_DIR / "state.json"
- LOG = STATE_DIR / "plugin.log"
- FUNCTION_ID = "xlosi3m46q"
- API_BASE = "https://server.fmode.cn/api/functions"
- APP_ID = "ncloudmaster"
- HEARTBEAT_BASE_SEC = float(os.environ.get("ACTIVE_REPORT_HEARTBEAT_SEC", "3600"))
- # 进程启动时随机一次(0~900 秒),之后每次心跳固定用这个偏移,间隔可预测、容器间自然错峰
- HEARTBEAT_JITTER_SEC = float(os.environ.get("ACTIVE_REPORT_HEARTBEAT_JITTER", "900"))
- BALANCE_WARN = float(os.environ.get("ACTIVE_REPORT_BALANCE_WARN", "10"))
- HTTP_TIMEOUT = float(os.environ.get("ACTIVE_REPORT_TIMEOUT", "8"))
- _LOG_LOCK = threading.Lock()
- _SENT_LOCK = threading.Lock()
- _SENT_TURNS: dict[str, str] = {} # turn_id -> 最后一次上报的状态(幂等保护,防重复 finalize)
- _BG: set[threading.Thread] = set()
- # 会话级状态:session_key -> {"status": "running"|"idle", "turnStartAt": epoch_ms, "updatedAt": epoch_ms}
- # 进程内内存即可,gateway 重启后由后续 turn 重新填充。
- #
- # updatedAt = 该会话状态最后一次变化的时间(turn 开始或结束),是 App 判断
- # 「这条会话新鲜还是别的会话在跑」的依据;turnStartAt 只是本轮开始的时刻,
- # 一个 30 秒的 turn 结束后 turnStartAt 会显得很旧,绝不能拿它当新鲜度用。
- _ACTIVE_SESSIONS: dict[str, dict] = {}
- _IDLE_TTL_MS = 10 * 60 * 1000 # idle 记录超过 10 分钟清理,防字典无限增长
- _RUNNING_STALE_MS = 2 * 60 * 60 * 1000 # running 记录兜底上限:进程被杀/hook 丢失时不至于永远 running
- _ACTIVE_LOCK = threading.Lock()
- # 内部 session_id -> thread_id 的进程内缓存,避免每次上报都查库
- _THREAD_CACHE: dict[str, str | None] = {}
- _THREAD_LOCK = threading.Lock()
- # extra 的写前合并策略(任务 1):
- # 每次都 GET 云端当前 extra 作为底,以云端为准,本地只覆盖 currentSessions/extraUpdatedAt。
- # GET 失败 → 返回 None → **跳过本次 extra 写入**(heartbeatAt 等常规字段照常写),
- # 下轮自然重试。绝不把失败结果固化成 {} 当底,否则一次抖动就会把所有业务键抹掉。
- # 这里只保留一个「最近一次成功读到的底」作为失败时的诊断参考,不参与合并。
- _EXTRA_LAST_OK: dict | None = None
- _EXTRA_FAILS = 0 # 连续失败次数(日志用,不阻断重试)
- _EXTRA_LOCK = threading.Lock()
- _HEARTBEAT_STARTED = False
- # ------------------------------------------------------------------ utils
- def _log(msg: str) -> None:
- try:
- STATE_DIR.mkdir(parents=True, exist_ok=True)
- line = "%s %s\n" % (time.strftime("%Y-%m-%d %H:%M:%S"), msg)
- with _LOG_LOCK:
- with open(LOG, "a", encoding="utf-8") as f:
- f.write(line)
- except Exception:
- pass
- def _token() -> str:
- for p in ("/run/s6/container_environment/FMODE_SESSION_TOKEN",
- str(HOME / ".fmode" / "session_token")):
- try:
- v = Path(p).read_text(encoding="utf-8").strip()
- if v:
- return v
- except Exception:
- continue
- return os.environ.get("FMODE_SESSION_TOKEN", "").strip()
- def _agent_id() -> str:
- for p in ("/run/s6/container_environment/AGENT_ID",):
- try:
- v = Path(p).read_text(encoding="utf-8").strip()
- if v:
- return v
- except Exception:
- continue
- return os.environ.get("AGENT_ID", "").strip()
- # 入口层(HAProxy 后端池)会随机对有效 token 回 401/403,属已知抖动:
- # 同 token 连调可出现 401/200/401 交替。故 401/403 视为可重试,最多 8 次、间隔 1.5s。
- # 注意区分业务层真 403:响应体 {"code":403,"mess":"无权更新该 Agent..."} 是归属校验失败,
- # 重试无用 —— 只有响应体不含业务 code 的 401/403 才按入口抖动重试。
- _CALL_RETRIES = 8
- _CALL_RETRY_GAP = 1.5
- # 心跳失败后的补推间隔:8 次重试全败 -> 睡 300s 后整轮重来,直到恢复
- HEARTBEAT_RETRY_SLEEP_SEC = float(os.environ.get("ACTIVE_REPORT_FAIL_SLEEP_SEC", "300"))
- def _is_entry_jitter(code: int, body_txt: str) -> bool:
- """是否属于「值得重试的网关/入口层失败」。
- - 401/403:入口层 HAProxy 后端池坏实例会随机拒绝有效 token,响应体无业务 code 即为假失败
- - 5xx:网关/上游瞬时错误,可重试
- - 业务语义错误(4xx 且响应体带明确 code/error 字段):不重试,重试无用
- """
- if code >= 500:
- return True
- if code not in (401, 403):
- return False
- try:
- j = json.loads(body_txt)
- except Exception:
- return True
- return "code" not in j
- def _call(params: dict, timeout: float = HTTP_TIMEOUT) -> dict:
- """调云函数。最多尝试 _CALL_RETRIES(8) 次,每次间隔 _CALL_RETRY_GAP(1.5s)。
- 仅对「网关/入口层类失败」重试:401/403(响应体无业务 code 的假拒绝)、5xx、
- 超时与连接类异常。业务语义错误(4xx 且响应体带明确错误码)立即抛出,不重试。
- 全部尝试耗尽后抛出最后一次异常。调用方(_push/_heartbeat_loop)负责吞掉异常,
- 调用发生在后台线程内,不阻塞主流程。
- """
- body = json.dumps({"id": FUNCTION_ID, "token": _token(), "params": params}).encode()
- last_exc = None
- for attempt in range(_CALL_RETRIES):
- req = urllib.request.Request(API_BASE, data=body, headers={
- "Content-Type": "application/json",
- "X-Parse-Application-Id": APP_ID})
- try:
- with urllib.request.urlopen(req, timeout=timeout) as r:
- return json.loads(r.read())
- except urllib.error.HTTPError as e:
- try:
- txt = e.read().decode("utf-8", "replace")
- except Exception:
- txt = ""
- if _is_entry_jitter(e.code, txt) and attempt < _CALL_RETRIES - 1:
- _log("entry jitter %d, retry %d/%d" % (e.code, attempt + 1, _CALL_RETRIES))
- time.sleep(_CALL_RETRY_GAP)
- last_exc = e
- continue
- raise
- except Exception as e:
- last_exc = e
- if attempt < _CALL_RETRIES - 1:
- time.sleep(_CALL_RETRY_GAP)
- continue
- raise
- if last_exc:
- raise last_exc
- raise RuntimeError("call failed")
- def _push(fields: dict) -> bool:
- """把若干字段写进 FmodeAgent 表。后台线程调用,异常全吞。"""
- agent_id = _agent_id()
- if not agent_id or not _token():
- _log("skip: no agent_id/token")
- return False
- ok = True
- for field, value in fields.items():
- try:
- res = _call({"op": "update", "agentId": agent_id, "field": field, "value": value})
- if res.get("code") != 200:
- ok = False
- _log("update %s failed: %s" % (field, str(res)[:160]))
- except Exception as e:
- ok = False
- _log("update %s error: %s" % (field, str(e)[:160]))
- return ok
- def _bg(fn, *args) -> None:
- """fire-and-forget 线程,主路径立即返回。"""
- def _run():
- try:
- fn(*args)
- except Exception as e:
- _log("bg error: %s" % str(e)[:200])
- t = threading.Thread(target=_run, daemon=True)
- _BG.add(t)
- t.start()
- # 清掉已结束的线程引用,避免无限增长
- if len(_BG) > 32:
- for x in [x for x in _BG if not x.is_alive()]:
- _BG.discard(x)
- def _state_read() -> dict:
- try:
- return json.loads(STATE.read_text(encoding="utf-8"))
- except Exception:
- return {}
- def _state_write(d: dict) -> None:
- try:
- STATE_DIR.mkdir(parents=True, exist_ok=True)
- STATE.write_text(json.dumps(d, ensure_ascii=False), encoding="utf-8")
- except Exception:
- pass
- def _now_iso() -> str:
- return time.strftime("%Y-%m-%dT%H:%M:%S+08:00", time.localtime())
- def _balance_value() -> tuple[str, float | None]:
- """查余额,返回 (要上报的字符串, 数值)。查不到就返回 ('', None)。"""
- try:
- body = json.dumps({"sessionToken": _token(), "page": 1, "pageSize": 1}).encode()
- req = urllib.request.Request(
- "https://server.fmode.cn/api/functions/lfYlgU7SkK",
- data=body, headers={"Content-Type": "application/json",
- "X-Parse-Application-Id": APP_ID})
- with urllib.request.urlopen(req, timeout=HTTP_TIMEOUT) as r:
- d = json.loads(r.read())
- # 该函数不返回余额时静默降级
- v = d.get("balance") if isinstance(d, dict) else None
- if v is None:
- return "", None
- return json.dumps({"balance": v, "currency": "CNY"}), float(v)
- except Exception:
- return "", None
- def _warn_suffix(bal: float | None) -> str:
- if bal is not None and bal < BALANCE_WARN:
- return " · ⚠️ 余额 ¥%.2f 偏低,请充值" % bal
- return ""
- # ------------------------------------------------------------------ session registry
- def _now_ms() -> int:
- return int(time.time() * 1000)
- def _prune_locked(now: int) -> None:
- """清理过期记录。调用方必须已持有 _ACTIVE_LOCK。
- 两条规则:
- * idle 且 updatedAt(无则回退 turnStartAt)超过 _IDLE_TTL_MS → 删
- * running 且 updatedAt 超过 _RUNNING_STALE_MS → 删(兜底:hook 丢失/进程异常时
- 不能让一条记录永远显示 running,否则 App 会一直以为该会话在跑)
- """
- stale = []
- for k, v in _ACTIVE_SESSIONS.items():
- stamp = int(v.get("updatedAt") or v.get("turnStartAt") or 0)
- age = now - stamp
- if v.get("status") == "idle" and age > _IDLE_TTL_MS:
- stale.append(k)
- elif v.get("status") == "running" and age > _RUNNING_STALE_MS:
- stale.append(k)
- for k in stale:
- _ACTIVE_SESSIONS.pop(k, None)
- if stale:
- _log("pruned %d stale session(s)" % len(stale))
- def _prune_sessions() -> int:
- """对外入口:心跳前也调它,让清理不再依赖「有新 turn 发生」。"""
- now = _now_ms()
- with _ACTIVE_LOCK:
- before = len(_ACTIVE_SESSIONS)
- _prune_locked(now)
- return before - len(_ACTIVE_SESSIONS)
- def _session_mark_running(session_key: str, task: str = "") -> None:
- """标记某会话开始跑,并记下**本会话本轮**的提问摘要。顺带清掉过期的 idle 记录。
- task 只属于这个 session_key:容器级 currentTask 是「最近一次 turn」的,
- 多会话并发时会让用户在会话 B 里看到会话 A 的任务名,所以会话级必须独立存。
- """
- now = _now_ms()
- with _ACTIVE_LOCK:
- _ACTIVE_SESSIONS[session_key] = {
- "status": "running", "turnStartAt": now, "updatedAt": now,
- "task": task or "",
- }
- _prune_locked(now)
- def _session_mark_idle(session_key: str) -> None:
- """标记某会话跑完:保留原 turnStartAt(本轮开始时刻),同时刷新 updatedAt。
- task 一并清空——任务名只在 running 时有意义,idle 还留着会让 App 显示
- 「这个会话还在做那件事」。
- """
- now = _now_ms()
- with _ACTIVE_LOCK:
- prev = _ACTIVE_SESSIONS.get(session_key) or {}
- _ACTIVE_SESSIONS[session_key] = {
- "status": "idle",
- "turnStartAt": prev.get("turnStartAt") or now,
- "updatedAt": now,
- "task": "",
- }
- _prune_locked(now)
- def _state_db_path() -> str:
- """定位 state.db。优先环境变量,其次常见路径。"""
- env = os.environ.get("HERMES_STATE_DB")
- if env and os.path.exists(env):
- return env
- for cand in ("/opt/hermes/state.db", (os.environ.get("HERMES_HOME") or "/opt/data") + "/state.db"):
- if os.path.exists(cand):
- return cand
- return ""
- def _thread_id_of(session_id: str) -> str | None:
- """内部 session_id -> thread_id(形如 $approot_xxx:fmode.cn)。
- 只读查库,带进程内缓存。任何异常都返回 None,绝不让异常冒泡到钩子。
- """
- if not session_id:
- return None
- with _THREAD_LOCK:
- if session_id in _THREAD_CACHE:
- return _THREAD_CACHE[session_id]
- tid: str | None = None
- try:
- path = _state_db_path()
- if path:
- conn = sqlite3.connect("file:%s?mode=ro" % path, uri=True, timeout=2)
- try:
- row = conn.execute(
- "SELECT thread_id FROM sessions WHERE id = ?", (session_id,)
- ).fetchone()
- if row and isinstance(row[0], str) and row[0].strip():
- tid = row[0].strip()
- finally:
- conn.close()
- except Exception as e:
- _log("thread_id lookup failed for %s: %s" % (session_id, str(e)[:120]))
- tid = None
- # 只缓存查到的非空值:turn 开始时 thread_id 可能还没写进库(NULL),
- # 若把 None 也缓存下来,该会话此后永远命中缓存、永远回落到内部 id。
- if tid:
- with _THREAD_LOCK:
- _THREAD_CACHE[session_id] = tid
- if len(_THREAD_CACHE) > 500:
- for k in list(_THREAD_CACHE)[:250]:
- _THREAD_CACHE.pop(k, None)
- return tid
- _INTERNAL_ID_RE = re.compile(r"^\d{8}_\d{6}_[0-9a-f]{6,}$")
- def _looks_internal_id(v: str | None) -> bool:
- """判断一个 session 标识是不是网关内部 id(如 20261111_195708_eebcd2d8)。
- App 侧靠 !roomId / $approot_xxx 这类真标识匹配,内部 id 永远匹配不上。
- """
- if not v:
- return True
- v = v.strip()
- if not v:
- return True
- return bool(_INTERNAL_ID_RE.match(v))
- def _chat_id_of(session_id: str) -> str | None:
- """内部 session_id -> chat_id(Matrix roomId,形如 !xxxx:fmode.cn)。只读查库,带缓存。"""
- if not session_id:
- return None
- key = "chat:" + session_id
- with _THREAD_LOCK:
- if key in _THREAD_CACHE:
- return _THREAD_CACHE[key]
- cid: str | None = None
- try:
- path = _state_db_path()
- if path:
- conn = sqlite3.connect("file:%s?mode=ro" % path, uri=True, timeout=2)
- try:
- row = conn.execute(
- "SELECT chat_id FROM sessions WHERE id = ?", (session_id,)
- ).fetchone()
- if row and isinstance(row[0], str) and row[0].strip():
- cid = row[0].strip()
- finally:
- conn.close()
- except Exception as e:
- _log("chat_id lookup failed for %s: %s" % (session_id, str(e)[:120]))
- cid = None
- if cid:
- with _THREAD_LOCK:
- _THREAD_CACHE[key] = cid
- if len(_THREAD_CACHE) > 500:
- for k in list(_THREAD_CACHE)[:250]:
- _THREAD_CACHE.pop(k, None)
- return cid
- def _user_id_of(session_id: str) -> str | None:
- """内部 session_id -> user_id(形如 @xhvrjtmwqh:fmode.cn)。只读查库,带缓存。
- 照 _chat_id_of() 的模式:只查 sessions 表、进程内缓存、异常静默并写日志。
- 查不到返回 None —— 调用方据此省略字段,而不是写空串。
- """
- if not session_id:
- return None
- key = "user:" + session_id
- with _THREAD_LOCK:
- if key in _THREAD_CACHE:
- return _THREAD_CACHE[key]
- uid: str | None = None
- try:
- path = _state_db_path()
- if path:
- conn = sqlite3.connect("file:%s?mode=ro" % path, uri=True, timeout=2)
- try:
- row = conn.execute(
- "SELECT user_id FROM sessions WHERE id = ?", (session_id,)
- ).fetchone()
- if row and isinstance(row[0], str) and row[0].strip():
- uid = row[0].strip()
- finally:
- conn.close()
- except Exception as e:
- _log("user_id lookup failed for %s: %s" % (session_id, str(e)[:120]))
- uid = None
- if uid:
- with _THREAD_LOCK:
- _THREAD_CACHE[key] = uid
- if len(_THREAD_CACHE) > 500:
- for k in list(_THREAD_CACHE)[:250]:
- _THREAD_CACHE.pop(k, None)
- return uid
- def _session_key_for(session_id: str) -> str:
- """sessionKey 取值优先级(任务 2):thread_id → chat_id(roomId) → 内部 id。
- - thread_id 为 NULL/空/内部 id 形态 → 不能用,往下走
- - chat_id 是 Matrix roomId(! 开头)→ 用它,App 的 includes() 能匹配上
- - 都没有 → 才回落到内部 id(此时 App 匹配不上,属于最差情况)
- 已知代价:roomId 粒度比 thread 粗,同房间的多条会话会互相误判。这是主动选择:
- 「完全匹配不上」比「偶尔误判」更糟。
- """
- tid = _thread_id_of(session_id)
- if tid and not _looks_internal_id(tid):
- return tid
- cid = _chat_id_of(session_id)
- if cid and not _looks_internal_id(cid):
- return cid
- return tid or cid or session_id
- def _sessions_snapshot() -> list[dict]:
- """转成上报用的列表:sessionKey 按 thread_id → chat_id → 内部 id 的优先级取。
- 每条带三个时间:turnStartAt(本轮开始)、updatedAt(状态最后变化)、
- ttlMs(该记录还能活多久,idle→10 分钟,running→2 小时)。App 可以据此
- 直接判断「这条是不是还新鲜」,不必自己猜。
- 注意:先出锁再查库,不在持锁期间做 IO。
- """
- with _ACTIVE_LOCK:
- items = [(k, v.get("status"), v.get("turnStartAt"), v.get("updatedAt"),
- v.get("task") or "")
- for k, v in _ACTIVE_SESSIONS.items()]
- rows: list[dict] = []
- for k, status, started, updated, task in items:
- row: dict[str, Any] = {
- "sessionKey": _session_key_for(k),
- "status": status,
- "turnStartAt": started,
- "updatedAt": updated or started,
- "ttlMs": _IDLE_TTL_MS if status == "idle" else _RUNNING_STALE_MS,
- }
- # userId 只在真查到时才落字段;查不到/查询异常一律省略该键
- uid = _user_id_of(k)
- if uid:
- row["userId"] = uid
- # task 只在 running 且本轮确实拿到提问时才有值;否则省略该键,不编造
- if status == "running" and task:
- row["task"] = task
- rows.append(row)
- return rows
- def _extra_cloud() -> dict | None:
- """GET 云端当前 extra。成功返回 dict(可能为空 dict),**失败返回 None**。
- 任务 1 的核心修复:失败绝不返回 {}。{} 会被上层当成「云端本来就没键」,
- 一写就把业务键全抹掉。返回 None 让上层明确区分「读到空的」和「没读到」。
- """
- global _EXTRA_LAST_OK, _EXTRA_FAILS
- try:
- old = _call({"op": "get", "agentId": _agent_id()}, timeout=HTTP_TIMEOUT)
- if old.get("code") != 200:
- with _EXTRA_LOCK:
- _EXTRA_FAILS += 1
- n = _EXTRA_FAILS
- _log("extra cloud read non-200 (%s), skip extra write this round; consecutive=%d"
- % (str(old)[:120], n))
- return None
- agent = old.get("agent") or {}
- raw = agent.get("extra")
- base: dict[str, Any] = {}
- if isinstance(raw, str):
- if raw.strip():
- loaded = json.loads(raw)
- if not isinstance(loaded, dict):
- _log("extra cloud read: extra is str but not an object, skip write")
- return None
- base = loaded
- elif isinstance(raw, dict):
- base = dict(raw)
- elif raw is None:
- base = {}
- else:
- _log("extra cloud read: unexpected extra type %s, skip write" % type(raw).__name__)
- return None
- with _EXTRA_LOCK:
- _EXTRA_FAILS = 0
- _EXTRA_LAST_OK = dict(base)
- return base
- except Exception as e:
- with _EXTRA_LOCK:
- _EXTRA_FAILS += 1
- n = _EXTRA_FAILS
- _log("extra cloud read failed (%s), skip extra write this round; consecutive=%d"
- % (str(e)[:160], n))
- return None
- def _extra_value() -> str | None:
- """构造 extra:以**本次 GET 到的云端值**为底,只更新 currentSessions/extraUpdatedAt。
- 返回 None 表示本轮读不到云端底 —— 调用方必须跳过 extra 写入,
- 只写 heartbeatAt 等常规字段,等下轮重试。
- """
- base = _extra_cloud()
- if base is None:
- return None
- extra_obj = dict(base)
- extra_obj["currentSessions"] = _sessions_snapshot()
- extra_obj["extraUpdatedAt"] = _now_iso() # 与其他字段一致,用 ISO 字符串
- return json.dumps(extra_obj, ensure_ascii=False)
- def _push_with_sessions(fields: dict) -> bool:
- """先写常规字段,再把会话快照合并进 extra。
- extra 写失败/读不到时不重试、不影响常规字段,也不污染云端 —— 下一轮再来。
- """
- ok = _push(fields)
- try:
- extra = _extra_value()
- if extra is None:
- # 任务 1:读不到云端底就跳过本次 extra 写入,heartbeatAt 已由 _push 写过了
- _log("extra write skipped (cloud base unavailable); other fields already written")
- return ok
- res = _call({"op": "update", "agentId": _agent_id(),
- "field": "extra", "value": extra})
- if res.get("code") != 200:
- ok = False
- _log("update extra failed: %s" % str(res)[:160])
- except Exception as e:
- ok = False
- _log("update extra error: %s" % str(e)[:160])
- return ok
- # ------------------------------------------------------------------ hooks
- def _on_pre_llm_call(**kw: Any) -> None:
- """turn 开始:整轮只触发一次。整段只做赋值 + 起线程,不阻塞。"""
- turn_id = str(kw.get("turn_id") or "")
- # 会话标识:hook 实际传的是 session_id(turn_context.py:695 / turn_finalizer.py:422)
- session_key = str(kw.get("session_id") or kw.get("sessionKey") or "")
- user_msg = kw.get("user_message")
- # 只取首行、截断,避免把用户原文大段写进平台字段
- if isinstance(user_msg, str):
- task = user_msg.strip().splitlines()[0][:60] if user_msg.strip() else ""
- else:
- task = str(user_msg)[:60] if user_msg else ""
- platform = str(kw.get("platform") or "")
- with _SENT_LOCK:
- if turn_id and _SENT_TURNS.get(turn_id) == "running":
- return
- if turn_id:
- _SENT_TURNS[turn_id] = "running"
- if len(_SENT_TURNS) > 200:
- for k in list(_SENT_TURNS)[:100]:
- _SENT_TURNS.pop(k, None)
- # 会话级状态登记(同步、持锁时间极短):task 存进本会话自己的记录
- if session_key:
- _session_mark_running(session_key, task)
- action = "处理中" + ("(%s)" % platform if platform else "")
- def _work():
- bal_str, bal_val = _balance_value()
- fields = {
- "status": "running",
- "currentTask": task,
- "currentAction": action + _warn_suffix(bal_val),
- "heartbeatAt": {"__type": "Date", "iso": _now_iso()},
- }
- if bal_str:
- fields["balance"] = bal_str
- _push_with_sessions(fields)
- st = _state_read()
- st.update({"last_status": "running", "last_turn": turn_id, "last_at": time.time()})
- _state_write(st)
- _log("turn start -> running session=%s task=%r" % (session_key[-40:] or "-", task))
- _bg(_work)
- # ---------------------------------------------------------------- Matrix turn_status 推送
- #
- # App 拉云函数是 15 秒轮询,turn 结束后「正在执行」要等 30 秒左右才停。
- # 这里在 turn 收尾时额外推一个自定义 Matrix 事件 com.fmode.turn_status,
- # App 收到即刷新,不用等轮询。
- #
- # 与 ✅ reaction 完全独立:✅ 仍只表示「这条消息发完了」,本事件表示「这一轮结束了」。
- # 发送失败只记日志,绝不影响 turn 收尾与原有上报。
- _MATRIX_ENV: dict[str, str] | None = None
- _MATRIX_ENV_LOCK = threading.Lock()
- def _matrix_env() -> dict[str, str]:
- """读 MATRIX_HOMESERVER / MATRIX_ACCESS_TOKEN。优先进程环境,其次 /opt/data/.env。
- .env 只在首次读取并解析,之后进程内缓存。
- """
- global _MATRIX_ENV
- with _MATRIX_ENV_LOCK:
- if _MATRIX_ENV is not None:
- return _MATRIX_ENV
- out: dict[str, str] = {}
- for k in ("MATRIX_HOMESERVER", "MATRIX_ACCESS_TOKEN"):
- v = os.environ.get(k, "").strip()
- if v:
- out[k] = v
- if not out.get("MATRIX_HOMESERVER") or not out.get("MATRIX_ACCESS_TOKEN"):
- try:
- for line in open(str(HOME / ".env"), encoding="utf-8", errors="ignore"):
- line = line.strip()
- if not line or line.startswith("#") or "=" not in line:
- continue
- k, v = line.split("=", 1)
- k = k.strip()
- if k in ("MATRIX_HOMESERVER", "MATRIX_ACCESS_TOKEN") and k not in out:
- out[k] = v.strip().strip('"').strip("'")
- except Exception:
- pass
- _MATRIX_ENV = out
- return out
- def _room_id_of_session(session_id: str) -> str | None:
- """内部 session_id -> Matrix roomId。复用 _chat_id_of 的只读查库与缓存。"""
- return _chat_id_of(session_id)
- def _push_turn_status(session_id: str, status: str) -> None:
- """往当前会话所在房间推一个 com.fmode.turn_status 事件。失败静默,只记日志。"""
- try:
- if not session_id:
- return
- env = _matrix_env()
- hs = env.get("MATRIX_HOMESERVER", "").rstrip("/")
- tok = env.get("MATRIX_ACCESS_TOKEN", "")
- if not hs or not tok:
- _log("turn_status skip: no MATRIX_HOMESERVER/TOKEN")
- return
- room = _room_id_of_session(session_id)
- if not room:
- _log("turn_status skip: no room for session=%s" % session_id)
- return
- # sessionKey 与 currentSessions 上报保持同一口径:thread_id → chat_id → 内部 id
- key = _session_key_for(session_id)
- content = {"sessionKey": key, "status": status}
- # 有 thread 就发进同一个 thread,否则 App 在 thread 视图里看不到
- tid = _thread_id_of(session_id)
- if tid and not _looks_internal_id(tid):
- content["m.relates_to"] = {"rel_type": "m.thread", "event_id": tid}
- txn = "ts%d" % int(time.time() * 1000)
- url = "%s/_matrix/client/v3/rooms/%s/send/com.fmode.turn_status/%s" % (
- hs, urllib.parse.quote(room, safe=""), txn)
- body = json.dumps(content).encode("utf-8")
- req = urllib.request.Request(url, data=body, method="PUT", headers={
- "Authorization": "Bearer " + tok,
- "Content-Type": "application/json",
- })
- with urllib.request.urlopen(req, timeout=HTTP_TIMEOUT) as resp:
- raw = resp.read().decode("utf-8", "replace")
- eid = ""
- try:
- eid = json.loads(raw).get("event_id", "")
- except Exception:
- pass
- _log("turn_status sent status=%s room=%s key=%s event=%s" % (status, room, key, eid))
- except Exception as e:
- _log("turn_status failed: %s" % str(e)[:200])
- def _on_post_llm_call(**kw: Any) -> None:
- """turn 结束:once-per-turn。这里天然不需要「本 turn 是否已报过 idle」的去重机制。"""
- turn_id = str(kw.get("turn_id") or "")
- session_key = str(kw.get("session_id") or kw.get("sessionKey") or "")
- with _SENT_LOCK:
- if turn_id and _SENT_TURNS.get(turn_id) == "idle":
- return # 纯防御:同一 turn 被重复 finalize 时不重复发
- if turn_id:
- _SENT_TURNS[turn_id] = "idle"
- # 先把本会话标记 idle,再判断全局是否还有别的会话在跑
- if session_key:
- _session_mark_idle(session_key)
- # 立刻推一个 Matrix turn_status 事件给 App(与 ✅ reaction 独立,失败不影响主流程)
- _push_turn_status(session_key, "idle")
- still_running = [s for s in _sessions_snapshot() if s.get("status") == "running"]
- def _work():
- bal_str, bal_val = _balance_value()
- if still_running:
- # 别的会话还在跑 —— 全局 status 保持 running,不覆盖它
- fields = {
- "status": "running",
- "currentTask": "",
- "currentAction": ("仍有 %d 个会话执行中%s"
- % (len(still_running), _warn_suffix(bal_val))),
- "heartbeatAt": {"__type": "Date", "iso": _now_iso()},
- }
- log_msg = "turn end -> session idle, %d still running" % len(still_running)
- st_status = "running"
- else:
- fields = {
- "status": "idle",
- "currentTask": "",
- "currentAction": ("空闲" + _warn_suffix(bal_val)).strip(),
- "heartbeatAt": {"__type": "Date", "iso": _now_iso()},
- }
- log_msg = "turn end -> idle"
- st_status = "idle"
- if bal_str:
- fields["balance"] = bal_str
- _push_with_sessions(fields)
- st = _state_read()
- st.update({"last_status": st_status, "last_turn": turn_id, "last_at": time.time()})
- _state_write(st)
- _log(log_msg)
- _bg(_work)
- # ------------------------------------------------------------------ heartbeat
- def _heartbeat_loop() -> None:
- """1 小时基础间隔 + 进程启动时随机一次的固定偏移(0~15 分钟),多容器自然错峰。
- 偏移只在进程启动时算一次并保持:每轮重新随机会让间隔忽长忽短、无法预测。
- 心跳**必须**带 currentSessions:App 靠 extra.currentSessions 判断「这条会话在跑
- 还是别的会话在跑」。若只在 turn 事件写,两个 turn 之间的长静默期里 App 拿到的
- 就是上一次的快照,而 idle 会话再过 10 分钟就被删掉 —— 表现为「会话列表空了/
- 显示成别的会话」。所以心跳前先 _prune_sessions()(顺带把过期的清掉),再用
- _push_with_sessions() 把当前快照写进 extra。
- 心跳不改 status/currentTask/currentAction —— 业务状态由 turn 事件负责,
- 心跳碰它会覆盖真实状态。
- **健壮性**(本点由 _heartbeat_once 承担):
- * 启动即推一次,避免重启后最长一个心跳周期的盲区
- * 单次推送内部已有 8x1.5s 重试(在 _call 里)
- * 若仍失败,缩短为 HEARTBEAT_RETRY_SLEEP_SEC(300s) 后补推,
- 补推成功即恢复原 interval;持续失败则每 300s 一轮
- 所有重试都只发生在该后台线程内,不阻塞主流程。
- """
- # 启动时随机一次,之后恒定(周期算法保持不变)
- jitter = random.uniform(0, HEARTBEAT_JITTER_SEC)
- interval = HEARTBEAT_BASE_SEC + jitter
- _log("heartbeat thread started base=%.1fs jitter=%.1fs (fixed) interval=%.1fs"
- % (HEARTBEAT_BASE_SEC, jitter, interval))
- # 启动即推一次:避免重启后最长一个 interval 的盲区
- ok = _heartbeat_once(jitter)
- if ok:
- _log("heartbeat startup push ok; entering loop with interval=%.0fs" % interval)
- next_sleep = interval
- else:
- _log("heartbeat startup push failed; retry in %.0fs" % HEARTBEAT_RETRY_SLEEP_SEC)
- next_sleep = HEARTBEAT_RETRY_SLEEP_SEC
- while True:
- time.sleep(next_sleep)
- ok = _heartbeat_once(jitter)
- if ok:
- next_sleep = interval
- else:
- _log("heartbeat push failed after retries; retry in %.0fs"
- % HEARTBEAT_RETRY_SLEEP_SEC)
- next_sleep = HEARTBEAT_RETRY_SLEEP_SEC
- def _fmode_channel_snapshot():
- import json as _json
- import os as _os
- import time as _time
- from pathlib import Path as _Path
- home = _Path(_os.environ.get("HERMES_HOME", "/opt/data"))
- try:
- platforms = _json.loads((home / "gateway_state.json").read_text()).get("platforms") or {}
- except (OSError, ValueError, TypeError, AttributeError):
- platforms = {}
- if not isinstance(platforms, dict):
- platforms = {}
- def _state(name):
- entry = platforms.get(name)
- return entry.get("state", "unknown") if isinstance(entry, dict) else "unknown"
- # Report every platform the gateway knows about: the status function merges
- # channels per key, so a Matrix-only snapshot would hide a connected WeCom bot.
- state = _state("matrix")
- snapshot = {"matrix": state == "connected", "matrixConfig": {
- "homeserver": _os.environ.get("MATRIX_HOMESERVER", "https://matrix.fmode.cn"),
- "userId": _os.environ.get("MATRIX_USER_ID", ""),
- "channelState": state,
- "listenerOk": state == "connected",
- }}
- wecom_state = _state("wecom")
- if "wecom" in platforms or _os.environ.get("WECOM_BOT_ID"):
- snapshot["wecom"] = wecom_state == "connected"
- snapshot["wecomConfig"] = {"botId": _os.environ.get("WECOM_BOT_ID", ""), "channelState": wecom_state}
- if _os.environ.get("WECOM_BOT_ID"):
- snapshot["wecomBotId"] = _os.environ["WECOM_BOT_ID"]
- snapshot["platformStates"] = {name: _state(name) for name in sorted(platforms)}
- snapshot["observedAt"] = int(_time.time() * 1000)
- return snapshot
- def _start_app_channels():
- import json as _json
- import threading as _threading
- import time as _time
- def publish():
- for _ in range(75):
- _time.sleep(2)
- channels = _fmode_channel_snapshot()
- if channels["matrix"]:
- try:
- if _push_with_sessions({"channels": _json.dumps(channels, ensure_ascii=False)}):
- _log("app matrix channels registered")
- return
- except Exception:
- pass
- _log("app matrix channels pending; heartbeat will retry")
- _threading.Thread(target=publish, name="app-channels", daemon=True).start()
- def _start_fmode_heartbeat():
- import os as _os
- import random as _random
- import threading as _threading
- import time as _time
- global _FMODE_HEARTBEAT_STARTED
- if globals().get("_FMODE_HEARTBEAT_STARTED"):
- return
- if _os.environ.get("AGENT_STATUS_ENABLED", "true").strip().lower() == "false":
- _log("app heartbeat disabled by configuration")
- return
- try:
- interval = max(60, int(_os.environ.get("AGENT_STATUS_HEARTBEAT", "3600")))
- jitter = max(0, min(900, int(_os.environ.get("AGENT_STATUS_JITTER", "900"))))
- except (TypeError, ValueError):
- interval, jitter = 3600, 900
- _FMODE_HEARTBEAT_STARTED = True
- def run():
- # Send one immediate liveness snapshot so a newly provisioned container can be verified.
- try:
- _heartbeat_once(0)
- except Exception as _exc:
- _log("app heartbeat failed: %s" % type(_exc).__name__)
- while True:
- _time.sleep(interval + _random.uniform(0, jitter))
- try:
- _heartbeat_once(0)
- except Exception as _exc:
- _log("app heartbeat failed: %s" % type(_exc).__name__)
- _threading.Thread(target=run, name="fmode-jittered-heartbeat", daemon=True).start()
- def _heartbeat_once(jitter: float) -> bool:
- """执行一轮心跳推送。返回是否成功。异常全吞,只记日志。"""
- try:
- # 1) 先清理过期会话 —— 不依赖「有新 turn 发生」,空闲容器也能收敛
- pruned = _prune_sessions()
- # 2) 取当前快照(必须在心跳里取,不能复用 turn 开始时的旧值)
- rows = _sessions_snapshot()
- bal_str, bal_val = _balance_value()
- fields = {"heartbeatAt": {"__type": "Date", "iso": _now_iso()}}
- fields["channels"] = json.dumps(_fmode_channel_snapshot(), ensure_ascii=False)
- if bal_str:
- fields["balance"] = bal_str
- # 3) 带 currentSessions 一起上(_push_with_sessions 会写 extra)
- ok = _push_with_sessions(fields)
- st = _state_read()
- st.update({"last_heartbeat": time.time(), "jitter": round(jitter, 1),
- "last_heartbeat_sessions": len(rows),
- "last_heartbeat_pruned": pruned,
- "last_heartbeat_ok": bool(ok)})
- _state_write(st)
- _log("heartbeat sent (jitter=%.0fs, sessions=%d, pruned=%d, ok=%s)"
- % (jitter, len(rows), pruned, ok))
- return bool(ok)
- except Exception as e:
- _log("heartbeat error: %s" % str(e)[:200])
- return False
- def _start_heartbeat() -> None:
- global _HEARTBEAT_STARTED
- if _HEARTBEAT_STARTED:
- return
- _HEARTBEAT_STARTED = True
- t = threading.Thread(target=_heartbeat_loop, daemon=True, name="active-reporter-heartbeat")
- t.start()
- _log("heartbeat thread started base=%ss jitter=0~%ss" % (HEARTBEAT_BASE_SEC, HEARTBEAT_JITTER_SEC))
- # ------------------------------------------------------------------ register
- def register(ctx) -> None:
- ctx.register_hook("pre_llm_call", _on_pre_llm_call)
- ctx.register_hook("post_llm_call", _on_post_llm_call)
- _start_fmode_heartbeat()
- _start_app_channels()
- _log("registered: pre_llm_call, post_llm_call, heartbeat")
|