Download coworker/graph/runtime.py from EnergyVenom/patchwise-agent-studio: direct link, hf CLI and curl.
- Browser
- Download file 4.78 kB
-
https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/coworker/graph/runtime.py
- Command line
-
hf download hf://spaces/EnergyVenom/patchwise-agent-studio/coworker/graph/runtime.py
-
curl -L -o runtime.py https://huggingface.co/spaces/EnergyVenom/patchwise-agent-studio/resolve/main/coworker/graph/runtime.py
4.78 kB
| """Node wrapper: kill check -> run_event 'started' -> fn -> run_event 'finished' + audit 'node.finished' (output digest); | |
| on exception a NodeError is recorded and re-raised. Interrupts (human gates) pass through as 'interrupted'.""" | |
| from __future__ import annotations | |
| import logging | |
| import time | |
| import traceback | |
| import uuid | |
| from typing import Callable | |
| from langchain_core.runnables import RunnableConfig | |
| from langgraph.errors import GraphBubbleUp | |
| from ..platform.audit import canonical, sha256_text | |
| from ..platform.killswitch import KillSwitchEngaged | |
| log = logging.getLogger("fpt.node") | |
| class FatalNodeError(RuntimeError): | |
| """Aborts the run (status failed), e.g. the Scout found a non-test pod.""" | |
| def _run_id(state: dict, config: dict | None) -> str: | |
| rid = (state or {}).get("run_id") if isinstance(state, dict) else None | |
| if not rid and config: | |
| rid = (config.get("configurable") or {}).get("thread_id") | |
| return str(rid or "unknown") | |
| def _summary(out) -> dict: | |
| if not isinstance(out, dict): | |
| return {"type": type(out).__name__} | |
| s: dict = {"keys": sorted(out)} | |
| for k in ("decision", "decisions", "retry_count", "failures", "counts"): | |
| if k in out: | |
| s[k] = out[k] | |
| for k in ("test_cases", "research", "heal_proposals", "tickets", "review_items", "deferred", "proposed_cases"): | |
| if isinstance(out.get(k), list): | |
| s[f"n_{k}"] = len(out[k]) | |
| if isinstance(out.get("research"), list) and out["research"]: | |
| s["module"] = out["research"][0].get("module") | |
| return s | |
| class NodeSpan: | |
| """One node execution: kill check -> 'started' event -> work -> 'finished' event + audit node.finished (output digest). | |
| Errors: a short message + error id go to the run events (visible to viewers / SSE); the traceback goes only to the | |
| log and the admin-only audit payload. Used by the LangGraph wrapper AND by the Temporal activities (same rows).""" | |
| def __init__(self, svc, run_id: str, name: str, extra: dict | None = None): | |
| self.svc, self.run_id, self.name, self.extra = svc, run_id, name, dict(extra or {}) | |
| self.t0 = time.time() | |
| def __enter__(self) -> "NodeSpan": | |
| self.svc.kill.check(f"node {self.name}") | |
| self.svc.db.add_event(self.run_id, self.name, "started", self.extra) | |
| self.svc.db.update_run(self.run_id, current_node=self.name) | |
| return self | |
| def finish(self, out) -> None: | |
| summ = {**_summary(out), "ms": int((time.time() - self.t0) * 1000), **self.extra} | |
| self.svc.db.add_event(self.run_id, self.name, "finished", summ) | |
| self.svc.audit.append("node.finished", actor="system", run_id=self.run_id, node=self.name, | |
| summary=str(summ.get("keys", ""))[:200], payload={"digest": sha256_text(canonical(out)), "summary": summ}) | |
| def __exit__(self, et, e, tb) -> bool: | |
| if e is None: | |
| return False | |
| if isinstance(e, GraphBubbleUp): | |
| self.svc.db.add_event(self.run_id, self.name, "interrupted", {"ms": int((time.time() - self.t0) * 1000)}) | |
| elif isinstance(e, KillSwitchEngaged): | |
| self.svc.db.add_event(self.run_id, self.name, "killed", {"error": str(e)}) | |
| elif isinstance(e, Exception): | |
| err_id = uuid.uuid4().hex[:10] | |
| trace = "".join(traceback.format_exception(et, e, tb))[-4000:] | |
| log.error("node %s failed in run %s (error id %s): %s", self.name, self.run_id, err_id, trace) | |
| from ..platform.failures import plain | |
| code, words = plain(e) # viewers see a sentence; the raw text and trace stay in the admin audit log | |
| self.svc.db.add_event(self.run_id, self.name, "error", {"error": f"{words} (error id {err_id})", "code": code, | |
| "fatal": isinstance(e, FatalNodeError), "error_id": err_id}) | |
| self.svc.audit.append("node.error", actor="system", run_id=self.run_id, node=self.name, | |
| summary=f"{type(e).__name__}: {str(e)[:300]} (error id {err_id})", payload={"error_id": err_id, "trace": trace}) | |
| return False | |
| def wrap(name: str, fn: Callable, svc) -> Callable: | |
| def node(state, config: RunnableConfig = None): # type: ignore[assignment] | |
| run_id = _run_id(state, config) | |
| sub = state.get("module") if isinstance(state, dict) and name == "research_module" else None | |
| with NodeSpan(svc, run_id, name, {"module": sub} if sub else None) as span: | |
| out = fn(state, config, svc) | |
| span.finish(out) | |
| return out | |
| node.__name__ = name | |
| node.__qualname__ = name | |
| return node | |