| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448 |
- """Patch the copied process-notice script for per-tool Matrix progress events.
- The source template stays read-only. This patch is applied only to the copied
- data directory of an agent-node-app container.
- """
- from __future__ import annotations
- import ast
- import os
- from pathlib import Path
- import re
- import stat
- import sys
- MARKER = "# FMODE_PROCESS_NOTICE_PATCH_V4"
- PREVIOUS_MARKERS = ("# FMODE_PROCESS_NOTICE_PATCH_V3", "# FMODE_PROCESS_NOTICE_PATCH_V2")
- MATRIX_AUTH_HELPERS = r'''# FMODE_PROCESS_NOTICE_PATCH_V4
- AUTH_CACHE_ROOT = Path("/tmp")
- def _matrix_access_token(env: dict, homeserver: str, rejected_token: str = "") -> str:
- """Use a supplied token or securely cache a token for the Matrix password account."""
- import fcntl
- import json as _json
- import os as _os
- import stat as _stat
- import urllib.error as _urlerror
- import urllib.request as _urlrequest
- import uuid as _uuid
- supplied = env.get("MATRIX_ACCESS_TOKEN") or ""
- if supplied:
- return supplied
- user = env.get("MATRIX_USER_ID") or ""
- password = env.get("MATRIX_PASSWORD") or ""
- if not user or not password:
- return ""
- localpart = user[1:].split(":", 1)[0] if user.startswith("@") else user
- cache_name = re.sub(r"[^A-Za-z0-9_.-]", "_", localpart)[:80] or "unknown"
- cache_dir = AUTH_CACHE_ROOT / ("fmode-process-notice-auth-" + cache_name)
- cache_file = cache_dir / "matrix-access.json"
- lock_file = cache_dir / "matrix-access.lock"
- try:
- cache_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
- directory_info = cache_dir.lstat()
- directory_owner_ok = not hasattr(_os, "getuid") or directory_info.st_uid == _os.getuid()
- if not _stat.S_ISDIR(directory_info.st_mode) or not directory_owner_ok:
- raise PermissionError("unsafe cache directory")
- if _os.name == "posix" and directory_info.st_mode & 0o077:
- _os.chmod(str(cache_dir), 0o700)
- lock_flags = _os.O_CREAT | _os.O_RDWR
- if hasattr(_os, "O_NOFOLLOW"):
- lock_flags |= _os.O_NOFOLLOW
- lock_fd = _os.open(str(lock_file), lock_flags, 0o600)
- except Exception as e:
- log("MATRIX-AUTH-FAIL storage=%s" % type(e).__name__)
- return ""
- try:
- lock_info = _os.fstat(lock_fd)
- lock_owner_ok = not hasattr(_os, "getuid") or lock_info.st_uid == _os.getuid()
- if (not _stat.S_ISREG(lock_info.st_mode) or lock_info.st_nlink != 1 or
- not lock_owner_ok):
- log("MATRIX-AUTH-FAIL unsafe-lock-file")
- return ""
- if _os.name == "posix" and lock_info.st_mode & 0o077:
- _os.fchmod(lock_fd, 0o600)
- fcntl.flock(lock_fd, fcntl.LOCK_EX)
- cached = ""
- try:
- info = cache_file.lstat()
- owner_ok = not hasattr(_os, "getuid") or info.st_uid == _os.getuid()
- mode_ok = (_stat.S_ISREG(info.st_mode) and
- info.st_nlink == 1 and
- (_os.name != "posix" or (info.st_mode & 0o077) == 0) and owner_ok)
- if mode_ok:
- data = _json.loads(cache_file.read_text(encoding="utf-8"))
- value = data.get("access_token") if isinstance(data, dict) else None
- if isinstance(value, str):
- cached = value
- except (OSError, ValueError, TypeError):
- cached = ""
- if cached and cached != rejected_token:
- return cached
- if cached and cached == rejected_token:
- try:
- cache_file.unlink()
- except OSError:
- pass
- request_body = {
- "type": "m.login.password",
- "identifier": {"type": "m.id.user", "user": user},
- "password": password,
- "device_id": "FMODEPROC01",
- "initial_device_display_name": "Fmode process notices",
- }
- request = _urlrequest.Request(
- homeserver + "/_matrix/client/v3/login",
- data=_json.dumps(request_body).encode("utf-8"),
- method="POST",
- headers={"Content-Type": "application/json"},
- )
- try:
- with _urlrequest.urlopen(request, timeout=8) as response:
- result = _json.loads(response.read() or b"{}")
- except _urlerror.HTTPError as e:
- log("MATRIX-LOGIN-FAIL status=%s" % e.code)
- return ""
- except Exception as e:
- log("MATRIX-LOGIN-FAIL error=%s" % type(e).__name__)
- return ""
- token = result.get("access_token") if isinstance(result, dict) else None
- if not isinstance(token, str) or not token:
- log("MATRIX-LOGIN-FAIL missing-token")
- return ""
- temp_file = cache_dir / ("matrix-access." + _uuid.uuid4().hex + ".tmp")
- try:
- flags = _os.O_CREAT | _os.O_EXCL | _os.O_WRONLY
- if hasattr(_os, "O_NOFOLLOW"):
- flags |= _os.O_NOFOLLOW
- temp_fd = _os.open(str(temp_file), flags, 0o600)
- with _os.fdopen(temp_fd, "w", encoding="utf-8") as stream:
- _json.dump({"access_token": token}, stream)
- _os.chmod(str(temp_file), 0o600)
- _os.replace(str(temp_file), str(cache_file))
- _os.chmod(str(cache_file), 0o600)
- except Exception as e:
- try:
- temp_file.unlink()
- except OSError:
- pass
- log("MATRIX-AUTH-FAIL cache=%s" % type(e).__name__)
- return ""
- return token
- finally:
- try:
- fcntl.flock(lock_fd, fcntl.LOCK_UN)
- finally:
- _os.close(lock_fd)
- '''
- SAFE_SUMMARIZE = r'''def _redact_notice_text(value: str) -> str:
- """Mask common credential forms before a tool summary is sent to Matrix."""
- import re as _re
- text = str(value or "")
- text = _re.sub(r"(?i)\bBearer\s+[^\s,;\"']+", "Bearer [REDACTED]", text)
- keyed = (r"(?i)\b((?:access[_-]?token|refresh[_-]?token|token|password|passwd|"
- r"secret|client[_-]?secret|api[_-]?key|apikey|authorization|cookie|credential)"
- r"\b\s*[:=]\s*)(?:\"[^\"]*\"|'[^']*'|[^\s,;&]+)")
- text = _re.sub(keyed, r"\1[REDACTED]", text)
- flagged = (r"(?i)(--?(?:access[_-]?token|refresh[_-]?token|token|password|passwd|"
- r"secret|client[_-]?secret|api[_-]?key|apikey|authorization|cookie)\s+)"
- r"(?:\"[^\"]*\"|'[^']*'|[^\s]+)")
- text = _re.sub(flagged, r"\1[REDACTED]", text)
- text = _re.sub(r"(?i)\bsk-[A-Za-z0-9_-]{8,}\b", "sk-[REDACTED]", text)
- return text
- def _redact_notice_args(value):
- import re as _re
- if isinstance(value, dict):
- clean = {}
- for key, item in value.items():
- normalized = _re.sub(r"[^a-z0-9]+", "_", str(key).lower()).strip("_")
- sensitive = any(word in normalized for word in (
- "token", "password", "passwd", "secret", "authorization",
- "cookie", "credential", "api_key", "private_key",
- )) or normalized in ("key", "auth")
- clean[key] = "[REDACTED]" if sensitive else _redact_notice_args(item)
- return clean
- if isinstance(value, list):
- return [_redact_notice_args(item) for item in value]
- if isinstance(value, str):
- return _redact_notice_text(value)
- return value
- def summarize(tool: str, args: dict) -> str:
- """Create a short, credential-redacted tool summary."""
- raw = ""
- if isinstance(args, dict):
- for key in ("command", "path", "file_path", "query", "url", "pattern", "code"):
- value = args.get(key)
- if isinstance(value, str) and value.strip():
- raw = _redact_notice_text(value.strip())
- break
- if not raw:
- raw = json.dumps(_redact_notice_args(args), ensure_ascii=False)
- raw = re.sub(r"\s+", " ", raw)
- if len(raw) > TEXT_LIMIT:
- raw = raw[:TEXT_LIMIT] + "…"
- return "%s · %s" % (tool, raw) if raw else tool
- '''
- NO_THROTTLE = r'''def throttled(session_id: str, tool: str) -> bool:
- """A post_tool_call invocation already represents one completed tool call."""
- return False
- '''
- THREAD_HELPERS = r'''def _thread_root(session_id: str, env: dict) -> str:
- direct = (env.get("HERMES_SESSION_THREAD_ID") or "").strip()
- if direct.startswith("$"):
- return direct
- sid = (session_id or env.get("HERMES_SESSION_ID") or "").strip()
- if not sid:
- return ""
- try:
- import sqlite3
- home = Path(env.get("HERMES_HOME", "/opt/data"))
- db = home / "state.db"
- if not db.is_file():
- return ""
- conn = sqlite3.connect("file:" + str(db) + "?mode=ro", uri=True, timeout=2)
- try:
- row = conn.execute("SELECT thread_id FROM sessions WHERE id=?", (sid,)).fetchone()
- finally:
- conn.close()
- value = str(row[0] or "").strip() if row else ""
- return value if value.startswith("$") else ""
- except Exception:
- return ""
- '''
- SAFE_SEND = r'''def send(env: dict, room: str, text: str, kind: str = "process", session_id: str = "") -> bool:
- import urllib.error
- import urllib.parse
- import urllib.request
- import uuid
- homeserver = (env.get("MATRIX_HOMESERVER") or "").rstrip("/")
- if not homeserver or not room:
- log("SEND-SKIP no homeserver or room")
- return False
- token = env.get("MATRIX_ACCESS_TOKEN") or _matrix_access_token(env, homeserver)
- if not token:
- log("SEND-SKIP no creds")
- return False
- body = {"msgtype": "m.text", "body": text, "fmode.kind": kind}
- thread_root = _thread_root(session_id, env)
- if thread_root:
- body["m.relates_to"] = {
- "rel_type": "m.thread",
- "event_id": thread_root,
- "is_falling_back": True,
- "m.in_reply_to": {"event_id": thread_root},
- }
- data = json.dumps(body, ensure_ascii=False).encode("utf-8")
- url = "%s/_matrix/client/v3/rooms/%s/send/m.room.message/%s" % (
- homeserver, urllib.parse.quote(room, safe=""), "fmproc" + uuid.uuid4().hex)
- for attempt in range(2):
- request = urllib.request.Request(
- url, data=data, method="PUT",
- headers={"Authorization": "Bearer " + token,
- "Content-Type": "application/json"},
- )
- try:
- with urllib.request.urlopen(request, timeout=8) as response:
- result = json.loads(response.read() or b"{}")
- event_id = result.get("event_id") if isinstance(result, dict) else None
- if event_id:
- log("SEND-OK room=%s event=%s text=%s" % (room, event_id, text[:40]))
- return True
- log("SEND-FAIL missing-event-id")
- return False
- except urllib.error.HTTPError as e:
- if (e.code == 401 and attempt == 0 and
- not env.get("MATRIX_ACCESS_TOKEN")):
- token = _matrix_access_token(env, homeserver, rejected_token=token)
- if token:
- continue
- log("SEND-FAIL status=%s" % e.code)
- return False
- except Exception as e:
- log("SEND-FAIL error=%s" % type(e).__name__)
- return False
- return False
- '''
- def _replace_function(source: str, name: str, replacement: str) -> str:
- tree = ast.parse(source)
- found = [node for node in tree.body
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name]
- if len(found) != 1:
- raise ValueError("Expected exactly one top-level %s()" % name)
- node = found[0]
- lines = source.splitlines(keepends=True)
- start = node.lineno - 1
- end = node.end_lineno
- block = replacement.rstrip() + "\n\n"
- return "".join(lines[:start]) + block + "".join(lines[end:])
- def _insert_before_function(source: str, name: str, insertion: str) -> str:
- tree = ast.parse(source)
- found = [node for node in tree.body
- if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == name]
- if len(found) != 1:
- raise ValueError("Expected exactly one top-level %s()" % name)
- lines = source.splitlines(keepends=True)
- offset = found[0].lineno - 1
- block = insertion.rstrip() + "\n\n"
- return "".join(lines[:offset]) + block + "".join(lines[offset:])
- def _bind_send_call_to_session(source: str) -> str:
- """Pass the hook's actual session id so notices can join the correct Matrix thread."""
- tree = ast.parse(source)
- main = next((node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == "main"), None)
- if main is None:
- raise ValueError("Expected exactly one top-level main()")
- assignments = set()
- for node in ast.walk(main):
- if isinstance(node, (ast.Assign, ast.AnnAssign, ast.NamedExpr)):
- targets = node.targets if isinstance(node, ast.Assign) else [node.target]
- for target in targets:
- if isinstance(target, ast.Name):
- assignments.add(target.id)
- sid_name = next((name for name in ("sid", "session_id") if name in assignments), "")
- calls = [node for node in ast.walk(main)
- if isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id == "send"]
- if not calls:
- return source
- # The real template also has an early manual --room/--text self-test. Its
- # session id is intentionally unavailable; only the hook call gets bound.
- manual = [call for call in calls if len(call.args) >= 3 and
- isinstance(call.args[1], ast.Name) and call.args[1].id == "room_override" and
- isinstance(call.args[2], ast.Name) and call.args[2].id == "text_override"]
- if len(manual) > 1:
- raise ValueError("Unexpected duplicate process-notice manual self-test")
- calls = [call for call in calls if call not in manual]
- if len(calls) != 1 or not sid_name:
- raise ValueError("Cannot safely associate the process-notice send with its session")
- call = calls[0]
- if any(keyword.arg == "session_id" for keyword in call.keywords):
- return source
- lines = source.splitlines(keepends=True)
- line_offsets = []
- offset = 0
- for line in lines:
- line_offsets.append(offset)
- offset += len(line.encode("utf-8"))
- end_line = call.end_lineno - 1
- prefix = b"".join(line.encode("utf-8") for line in lines[:end_line])
- end_byte = len(prefix) + call.end_col_offset - 1
- encoded = source.encode("utf-8")
- patched = encoded[:end_byte] + (", session_id=" + sid_name).encode("ascii") + encoded[end_byte:]
- return patched.decode("utf-8")
- def patch_text(source: str) -> str:
- if MARKER in source:
- ast.parse(source)
- return source
- if any(marker in source for marker in PREVIOUS_MARKERS):
- raise ValueError("Restore the verified unpatched backup before upgrading this patch")
- tree = ast.parse(source)
- functions = {node.name for node in tree.body if isinstance(node, ast.FunctionDef)}
- required = {"summarize", "throttled", "send", "main"}
- if not required.issubset(functions):
- raise ValueError("Process-notice source does not match the verified function layout")
- if source.count("THROTTLE_SECONDS = 60") != 1:
- raise ValueError("Expected the verified 60-second per-tool throttle")
- throttle_gate = re.compile(
- r"(?m)^(?P<indent>[ \t]*)if throttled\(sid, tool\):"
- r"(?:[ \t]+return 0|[ \t]*\n(?P=indent)[ \t]+return 0)[ \t]*$"
- )
- if len(list(throttle_gate.finditer(source))) != 1:
- raise ValueError("Expected the verified post_tool_call throttle gate")
- if source.count('tok = env.get("MATRIX_ACCESS_TOKEN") or ""') != 1:
- raise ValueError("Expected the verified Matrix token check")
- updated = _replace_function(source, "send", SAFE_SEND)
- updated = _replace_function(updated, "throttled", NO_THROTTLE)
- updated = _replace_function(updated, "summarize", SAFE_SUMMARIZE)
- updated = _insert_before_function(updated, "send", MATRIX_AUTH_HELPERS)
- updated = _insert_before_function(updated, "send", THREAD_HELPERS)
- updated = _bind_send_call_to_session(updated)
- updated = updated.replace("THROTTLE_SECONDS = 60", "THROTTLE_SECONDS = 0", 1)
- updated, replaced = throttle_gate.subn(
- lambda match: match.group("indent") +
- "# One post_tool_call callback represents one call; keep every invocation visible.",
- updated,
- count=1,
- )
- if replaced != 1:
- raise ValueError("Could not remove the verified post_tool_call throttle gate")
- ast.parse(updated)
- if throttle_gate.search(updated) or "THROTTLE_SECONDS = 60" in updated:
- raise ValueError("Per-tool throttling was not fully removed")
- return updated
- def main() -> None:
- if len(sys.argv) != 2:
- raise ValueError("Provide one copied App-container process-notice path")
- target = Path(sys.argv[1]).resolve(strict=True)
- self_path = Path("/opt/data/scripts/fmode-process-notice.py")
- self_agent = os.environ.get("AGENT_ID", "")
- self_mode = target == self_path.resolve() and self_agent.startswith("agent-node-app-")
- if self_mode:
- container_name = self_agent
- else:
- root = Path("/opt/fmode-containers").resolve(strict=True)
- relative = target.relative_to(root)
- if (not relative.parts or not relative.parts[0].startswith("agent-node-app-") or
- relative.parts[1:] != ("data", "scripts", "fmode-process-notice.py")):
- raise ValueError("Only a copied App-container process-notice script can be patched")
- container_name = relative.parts[0]
- original = target.read_text(encoding="utf-8")
- backup = Path("/tmp") / (container_name + ".fmode-process-notice.before-v2")
- if any(marker in original for marker in PREVIOUS_MARKERS):
- if not backup.is_file():
- raise ValueError("Cannot upgrade v2 without its verified pre-v2 backup")
- original = backup.read_text(encoding="utf-8")
- updated = patch_text(original)
- if updated != original:
- mode = stat.S_IMODE(target.stat().st_mode)
- if self_mode:
- # The copied scripts directory may be root-owned while this file is
- # writable by hermes. Keep its backup in /tmp and write the owned
- # file in place, without changing directory permissions.
- if not backup.exists():
- backup.write_text(original, encoding="utf-8")
- os.chmod(str(backup), 0o600)
- target.write_text(updated, encoding="utf-8")
- else:
- backup = target.with_name(target.name + ".before-process-notice-v2")
- if not backup.exists():
- backup.write_text(original, encoding="utf-8")
- os.chmod(str(backup), mode)
- temp = target.with_name(target.name + ".process-notice-v2.tmp")
- temp.write_text(updated, encoding="utf-8")
- os.chmod(str(temp), mode)
- os.replace(str(temp), str(target))
- print("Process-notice patch verified:", container_name)
- if __name__ == "__main__":
- main()
|