patch_process_notice.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. """Patch the copied process-notice script for per-tool Matrix progress events.
  2. The source template stays read-only. This patch is applied only to the copied
  3. data directory of an agent-node-app container.
  4. """
  5. from __future__ import annotations
  6. import ast
  7. import os
  8. from pathlib import Path
  9. import re
  10. import stat
  11. import sys
  12. MARKER = "# FMODE_PROCESS_NOTICE_PATCH_V4"
  13. PREVIOUS_MARKERS = ("# FMODE_PROCESS_NOTICE_PATCH_V3", "# FMODE_PROCESS_NOTICE_PATCH_V2")
  14. MATRIX_AUTH_HELPERS = r'''# FMODE_PROCESS_NOTICE_PATCH_V4
  15. AUTH_CACHE_ROOT = Path("/tmp")
  16. def _matrix_access_token(env: dict, homeserver: str, rejected_token: str = "") -> str:
  17. """Use a supplied token or securely cache a token for the Matrix password account."""
  18. import fcntl
  19. import json as _json
  20. import os as _os
  21. import stat as _stat
  22. import urllib.error as _urlerror
  23. import urllib.request as _urlrequest
  24. import uuid as _uuid
  25. supplied = env.get("MATRIX_ACCESS_TOKEN") or ""
  26. if supplied:
  27. return supplied
  28. user = env.get("MATRIX_USER_ID") or ""
  29. password = env.get("MATRIX_PASSWORD") or ""
  30. if not user or not password:
  31. return ""
  32. localpart = user[1:].split(":", 1)[0] if user.startswith("@") else user
  33. cache_name = re.sub(r"[^A-Za-z0-9_.-]", "_", localpart)[:80] or "unknown"
  34. cache_dir = AUTH_CACHE_ROOT / ("fmode-process-notice-auth-" + cache_name)
  35. cache_file = cache_dir / "matrix-access.json"
  36. lock_file = cache_dir / "matrix-access.lock"
  37. try:
  38. cache_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
  39. directory_info = cache_dir.lstat()
  40. directory_owner_ok = not hasattr(_os, "getuid") or directory_info.st_uid == _os.getuid()
  41. if not _stat.S_ISDIR(directory_info.st_mode) or not directory_owner_ok:
  42. raise PermissionError("unsafe cache directory")
  43. if _os.name == "posix" and directory_info.st_mode & 0o077:
  44. _os.chmod(str(cache_dir), 0o700)
  45. lock_flags = _os.O_CREAT | _os.O_RDWR
  46. if hasattr(_os, "O_NOFOLLOW"):
  47. lock_flags |= _os.O_NOFOLLOW
  48. lock_fd = _os.open(str(lock_file), lock_flags, 0o600)
  49. except Exception as e:
  50. log("MATRIX-AUTH-FAIL storage=%s" % type(e).__name__)
  51. return ""
  52. try:
  53. lock_info = _os.fstat(lock_fd)
  54. lock_owner_ok = not hasattr(_os, "getuid") or lock_info.st_uid == _os.getuid()
  55. if (not _stat.S_ISREG(lock_info.st_mode) or lock_info.st_nlink != 1 or
  56. not lock_owner_ok):
  57. log("MATRIX-AUTH-FAIL unsafe-lock-file")
  58. return ""
  59. if _os.name == "posix" and lock_info.st_mode & 0o077:
  60. _os.fchmod(lock_fd, 0o600)
  61. fcntl.flock(lock_fd, fcntl.LOCK_EX)
  62. cached = ""
  63. try:
  64. info = cache_file.lstat()
  65. owner_ok = not hasattr(_os, "getuid") or info.st_uid == _os.getuid()
  66. mode_ok = (_stat.S_ISREG(info.st_mode) and
  67. info.st_nlink == 1 and
  68. (_os.name != "posix" or (info.st_mode & 0o077) == 0) and owner_ok)
  69. if mode_ok:
  70. data = _json.loads(cache_file.read_text(encoding="utf-8"))
  71. value = data.get("access_token") if isinstance(data, dict) else None
  72. if isinstance(value, str):
  73. cached = value
  74. except (OSError, ValueError, TypeError):
  75. cached = ""
  76. if cached and cached != rejected_token:
  77. return cached
  78. if cached and cached == rejected_token:
  79. try:
  80. cache_file.unlink()
  81. except OSError:
  82. pass
  83. request_body = {
  84. "type": "m.login.password",
  85. "identifier": {"type": "m.id.user", "user": user},
  86. "password": password,
  87. "device_id": "FMODEPROC01",
  88. "initial_device_display_name": "Fmode process notices",
  89. }
  90. request = _urlrequest.Request(
  91. homeserver + "/_matrix/client/v3/login",
  92. data=_json.dumps(request_body).encode("utf-8"),
  93. method="POST",
  94. headers={"Content-Type": "application/json"},
  95. )
  96. try:
  97. with _urlrequest.urlopen(request, timeout=8) as response:
  98. result = _json.loads(response.read() or b"{}")
  99. except _urlerror.HTTPError as e:
  100. log("MATRIX-LOGIN-FAIL status=%s" % e.code)
  101. return ""
  102. except Exception as e:
  103. log("MATRIX-LOGIN-FAIL error=%s" % type(e).__name__)
  104. return ""
  105. token = result.get("access_token") if isinstance(result, dict) else None
  106. if not isinstance(token, str) or not token:
  107. log("MATRIX-LOGIN-FAIL missing-token")
  108. return ""
  109. temp_file = cache_dir / ("matrix-access." + _uuid.uuid4().hex + ".tmp")
  110. try:
  111. flags = _os.O_CREAT | _os.O_EXCL | _os.O_WRONLY
  112. if hasattr(_os, "O_NOFOLLOW"):
  113. flags |= _os.O_NOFOLLOW
  114. temp_fd = _os.open(str(temp_file), flags, 0o600)
  115. with _os.fdopen(temp_fd, "w", encoding="utf-8") as stream:
  116. _json.dump({"access_token": token}, stream)
  117. _os.chmod(str(temp_file), 0o600)
  118. _os.replace(str(temp_file), str(cache_file))
  119. _os.chmod(str(cache_file), 0o600)
  120. except Exception as e:
  121. try:
  122. temp_file.unlink()
  123. except OSError:
  124. pass
  125. log("MATRIX-AUTH-FAIL cache=%s" % type(e).__name__)
  126. return ""
  127. return token
  128. finally:
  129. try:
  130. fcntl.flock(lock_fd, fcntl.LOCK_UN)
  131. finally:
  132. _os.close(lock_fd)
  133. '''
  134. SAFE_SUMMARIZE = r'''def _redact_notice_text(value: str) -> str:
  135. """Mask common credential forms before a tool summary is sent to Matrix."""
  136. import re as _re
  137. text = str(value or "")
  138. text = _re.sub(r"(?i)\bBearer\s+[^\s,;\"']+", "Bearer [REDACTED]", text)
  139. keyed = (r"(?i)\b((?:access[_-]?token|refresh[_-]?token|token|password|passwd|"
  140. r"secret|client[_-]?secret|api[_-]?key|apikey|authorization|cookie|credential)"
  141. r"\b\s*[:=]\s*)(?:\"[^\"]*\"|'[^']*'|[^\s,;&]+)")
  142. text = _re.sub(keyed, r"\1[REDACTED]", text)
  143. flagged = (r"(?i)(--?(?:access[_-]?token|refresh[_-]?token|token|password|passwd|"
  144. r"secret|client[_-]?secret|api[_-]?key|apikey|authorization|cookie)\s+)"
  145. r"(?:\"[^\"]*\"|'[^']*'|[^\s]+)")
  146. text = _re.sub(flagged, r"\1[REDACTED]", text)
  147. text = _re.sub(r"(?i)\bsk-[A-Za-z0-9_-]{8,}\b", "sk-[REDACTED]", text)
  148. return text
  149. def _redact_notice_args(value):
  150. import re as _re
  151. if isinstance(value, dict):
  152. clean = {}
  153. for key, item in value.items():
  154. normalized = _re.sub(r"[^a-z0-9]+", "_", str(key).lower()).strip("_")
  155. sensitive = any(word in normalized for word in (
  156. "token", "password", "passwd", "secret", "authorization",
  157. "cookie", "credential", "api_key", "private_key",
  158. )) or normalized in ("key", "auth")
  159. clean[key] = "[REDACTED]" if sensitive else _redact_notice_args(item)
  160. return clean
  161. if isinstance(value, list):
  162. return [_redact_notice_args(item) for item in value]
  163. if isinstance(value, str):
  164. return _redact_notice_text(value)
  165. return value
  166. def summarize(tool: str, args: dict) -> str:
  167. """Create a short, credential-redacted tool summary."""
  168. raw = ""
  169. if isinstance(args, dict):
  170. for key in ("command", "path", "file_path", "query", "url", "pattern", "code"):
  171. value = args.get(key)
  172. if isinstance(value, str) and value.strip():
  173. raw = _redact_notice_text(value.strip())
  174. break
  175. if not raw:
  176. raw = json.dumps(_redact_notice_args(args), ensure_ascii=False)
  177. raw = re.sub(r"\s+", " ", raw)
  178. if len(raw) > TEXT_LIMIT:
  179. raw = raw[:TEXT_LIMIT] + "…"
  180. return "%s · %s" % (tool, raw) if raw else tool
  181. '''
  182. NO_THROTTLE = r'''def throttled(session_id: str, tool: str) -> bool:
  183. """A post_tool_call invocation already represents one completed tool call."""
  184. return False
  185. '''
  186. THREAD_HELPERS = r'''def _thread_root(session_id: str, env: dict) -> str:
  187. direct = (env.get("HERMES_SESSION_THREAD_ID") or "").strip()
  188. if direct.startswith("$"):
  189. return direct
  190. sid = (session_id or env.get("HERMES_SESSION_ID") or "").strip()
  191. if not sid:
  192. return ""
  193. try:
  194. import sqlite3
  195. home = Path(env.get("HERMES_HOME", "/opt/data"))
  196. db = home / "state.db"
  197. if not db.is_file():
  198. return ""
  199. conn = sqlite3.connect("file:" + str(db) + "?mode=ro", uri=True, timeout=2)
  200. try:
  201. row = conn.execute("SELECT thread_id FROM sessions WHERE id=?", (sid,)).fetchone()
  202. finally:
  203. conn.close()
  204. value = str(row[0] or "").strip() if row else ""
  205. return value if value.startswith("$") else ""
  206. except Exception:
  207. return ""
  208. '''
  209. SAFE_SEND = r'''def send(env: dict, room: str, text: str, kind: str = "process", session_id: str = "") -> bool:
  210. import urllib.error
  211. import urllib.parse
  212. import urllib.request
  213. import uuid
  214. homeserver = (env.get("MATRIX_HOMESERVER") or "").rstrip("/")
  215. if not homeserver or not room:
  216. log("SEND-SKIP no homeserver or room")
  217. return False
  218. token = env.get("MATRIX_ACCESS_TOKEN") or _matrix_access_token(env, homeserver)
  219. if not token:
  220. log("SEND-SKIP no creds")
  221. return False
  222. body = {"msgtype": "m.text", "body": text, "fmode.kind": kind}
  223. thread_root = _thread_root(session_id, env)
  224. if thread_root:
  225. body["m.relates_to"] = {
  226. "rel_type": "m.thread",
  227. "event_id": thread_root,
  228. "is_falling_back": True,
  229. "m.in_reply_to": {"event_id": thread_root},
  230. }
  231. data = json.dumps(body, ensure_ascii=False).encode("utf-8")
  232. url = "%s/_matrix/client/v3/rooms/%s/send/m.room.message/%s" % (
  233. homeserver, urllib.parse.quote(room, safe=""), "fmproc" + uuid.uuid4().hex)
  234. for attempt in range(2):
  235. request = urllib.request.Request(
  236. url, data=data, method="PUT",
  237. headers={"Authorization": "Bearer " + token,
  238. "Content-Type": "application/json"},
  239. )
  240. try:
  241. with urllib.request.urlopen(request, timeout=8) as response:
  242. result = json.loads(response.read() or b"{}")
  243. event_id = result.get("event_id") if isinstance(result, dict) else None
  244. if event_id:
  245. log("SEND-OK room=%s event=%s text=%s" % (room, event_id, text[:40]))
  246. return True
  247. log("SEND-FAIL missing-event-id")
  248. return False
  249. except urllib.error.HTTPError as e:
  250. if (e.code == 401 and attempt == 0 and
  251. not env.get("MATRIX_ACCESS_TOKEN")):
  252. token = _matrix_access_token(env, homeserver, rejected_token=token)
  253. if token:
  254. continue
  255. log("SEND-FAIL status=%s" % e.code)
  256. return False
  257. except Exception as e:
  258. log("SEND-FAIL error=%s" % type(e).__name__)
  259. return False
  260. return False
  261. '''
  262. def _replace_function(source: str, name: str, replacement: str) -> str:
  263. tree = ast.parse(source)
  264. found = [node for node in tree.body
  265. if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name]
  266. if len(found) != 1:
  267. raise ValueError("Expected exactly one top-level %s()" % name)
  268. node = found[0]
  269. lines = source.splitlines(keepends=True)
  270. start = node.lineno - 1
  271. end = node.end_lineno
  272. block = replacement.rstrip() + "\n\n"
  273. return "".join(lines[:start]) + block + "".join(lines[end:])
  274. def _insert_before_function(source: str, name: str, insertion: str) -> str:
  275. tree = ast.parse(source)
  276. found = [node for node in tree.body
  277. if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name]
  278. if len(found) != 1:
  279. raise ValueError("Expected exactly one top-level %s()" % name)
  280. lines = source.splitlines(keepends=True)
  281. offset = found[0].lineno - 1
  282. block = insertion.rstrip() + "\n\n"
  283. return "".join(lines[:offset]) + block + "".join(lines[offset:])
  284. def _bind_send_call_to_session(source: str) -> str:
  285. """Pass the hook's actual session id so notices can join the correct Matrix thread."""
  286. tree = ast.parse(source)
  287. main = next((node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "main"), None)
  288. if main is None:
  289. raise ValueError("Expected exactly one top-level main()")
  290. assignments = set()
  291. for node in ast.walk(main):
  292. if isinstance(node, (ast.Assign, ast.AnnAssign, ast.NamedExpr)):
  293. targets = node.targets if isinstance(node, ast.Assign) else [node.target]
  294. for target in targets:
  295. if isinstance(target, ast.Name):
  296. assignments.add(target.id)
  297. sid_name = next((name for name in ("sid", "session_id") if name in assignments), "")
  298. calls = [node for node in ast.walk(main)
  299. if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "send"]
  300. if not calls:
  301. return source
  302. # The real template also has an early manual --room/--text self-test. Its
  303. # session id is intentionally unavailable; only the hook call gets bound.
  304. manual = [call for call in calls if len(call.args) >= 3 and
  305. isinstance(call.args[1], ast.Name) and call.args[1].id == "room_override" and
  306. isinstance(call.args[2], ast.Name) and call.args[2].id == "text_override"]
  307. if len(manual) > 1:
  308. raise ValueError("Unexpected duplicate process-notice manual self-test")
  309. calls = [call for call in calls if call not in manual]
  310. if len(calls) != 1 or not sid_name:
  311. raise ValueError("Cannot safely associate the process-notice send with its session")
  312. call = calls[0]
  313. if any(keyword.arg == "session_id" for keyword in call.keywords):
  314. return source
  315. lines = source.splitlines(keepends=True)
  316. line_offsets = []
  317. offset = 0
  318. for line in lines:
  319. line_offsets.append(offset)
  320. offset += len(line.encode("utf-8"))
  321. end_line = call.end_lineno - 1
  322. prefix = b"".join(line.encode("utf-8") for line in lines[:end_line])
  323. end_byte = len(prefix) + call.end_col_offset - 1
  324. encoded = source.encode("utf-8")
  325. patched = encoded[:end_byte] + (", session_id=" + sid_name).encode("ascii") + encoded[end_byte:]
  326. return patched.decode("utf-8")
  327. def patch_text(source: str) -> str:
  328. if MARKER in source:
  329. ast.parse(source)
  330. return source
  331. if any(marker in source for marker in PREVIOUS_MARKERS):
  332. raise ValueError("Restore the verified unpatched backup before upgrading this patch")
  333. tree = ast.parse(source)
  334. functions = {node.name for node in tree.body if isinstance(node, ast.FunctionDef)}
  335. required = {"summarize", "throttled", "send", "main"}
  336. if not required.issubset(functions):
  337. raise ValueError("Process-notice source does not match the verified function layout")
  338. if source.count("THROTTLE_SECONDS = 60") != 1:
  339. raise ValueError("Expected the verified 60-second per-tool throttle")
  340. throttle_gate = re.compile(
  341. r"(?m)^(?P<indent>[ \t]*)if throttled\(sid, tool\):"
  342. r"(?:[ \t]+return 0|[ \t]*\n(?P=indent)[ \t]+return 0)[ \t]*$"
  343. )
  344. if len(list(throttle_gate.finditer(source))) != 1:
  345. raise ValueError("Expected the verified post_tool_call throttle gate")
  346. if source.count('tok = env.get("MATRIX_ACCESS_TOKEN") or ""') != 1:
  347. raise ValueError("Expected the verified Matrix token check")
  348. updated = _replace_function(source, "send", SAFE_SEND)
  349. updated = _replace_function(updated, "throttled", NO_THROTTLE)
  350. updated = _replace_function(updated, "summarize", SAFE_SUMMARIZE)
  351. updated = _insert_before_function(updated, "send", MATRIX_AUTH_HELPERS)
  352. updated = _insert_before_function(updated, "send", THREAD_HELPERS)
  353. updated = _bind_send_call_to_session(updated)
  354. updated = updated.replace("THROTTLE_SECONDS = 60", "THROTTLE_SECONDS = 0", 1)
  355. updated, replaced = throttle_gate.subn(
  356. lambda match: match.group("indent") +
  357. "# One post_tool_call callback represents one call; keep every invocation visible.",
  358. updated,
  359. count=1,
  360. )
  361. if replaced != 1:
  362. raise ValueError("Could not remove the verified post_tool_call throttle gate")
  363. ast.parse(updated)
  364. if throttle_gate.search(updated) or "THROTTLE_SECONDS = 60" in updated:
  365. raise ValueError("Per-tool throttling was not fully removed")
  366. return updated
  367. def main() -> None:
  368. if len(sys.argv) != 2:
  369. raise ValueError("Provide one copied App-container process-notice path")
  370. target = Path(sys.argv[1]).resolve(strict=True)
  371. self_path = Path("/opt/data/scripts/fmode-process-notice.py")
  372. self_agent = os.environ.get("AGENT_ID", "")
  373. self_mode = target == self_path.resolve() and self_agent.startswith("agent-node-app-")
  374. if self_mode:
  375. container_name = self_agent
  376. else:
  377. root = Path("/opt/fmode-containers").resolve(strict=True)
  378. relative = target.relative_to(root)
  379. if (not relative.parts or not relative.parts[0].startswith("agent-node-app-") or
  380. relative.parts[1:] != ("data", "scripts", "fmode-process-notice.py")):
  381. raise ValueError("Only a copied App-container process-notice script can be patched")
  382. container_name = relative.parts[0]
  383. original = target.read_text(encoding="utf-8")
  384. backup = Path("/tmp") / (container_name + ".fmode-process-notice.before-v2")
  385. if any(marker in original for marker in PREVIOUS_MARKERS):
  386. if not backup.is_file():
  387. raise ValueError("Cannot upgrade v2 without its verified pre-v2 backup")
  388. original = backup.read_text(encoding="utf-8")
  389. updated = patch_text(original)
  390. if updated != original:
  391. mode = stat.S_IMODE(target.stat().st_mode)
  392. if self_mode:
  393. # The copied scripts directory may be root-owned while this file is
  394. # writable by hermes. Keep its backup in /tmp and write the owned
  395. # file in place, without changing directory permissions.
  396. if not backup.exists():
  397. backup.write_text(original, encoding="utf-8")
  398. os.chmod(str(backup), 0o600)
  399. target.write_text(updated, encoding="utf-8")
  400. else:
  401. backup = target.with_name(target.name + ".before-process-notice-v2")
  402. if not backup.exists():
  403. backup.write_text(original, encoding="utf-8")
  404. os.chmod(str(backup), mode)
  405. temp = target.with_name(target.name + ".process-notice-v2.tmp")
  406. temp.write_text(updated, encoding="utf-8")
  407. os.chmod(str(temp), mode)
  408. os.replace(str(temp), str(target))
  409. print("Process-notice patch verified:", container_name)
  410. if __name__ == "__main__":
  411. main()