Spaces:
Running
Running
Download core/agent/runtime.py from Aynkhn/WorkPilot-AI: direct link, hf CLI and curl.
- Browser
- Download file 17.8 kB
-
https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/agent/runtime.py
- Command line
-
hf download hf://spaces/Aynkhn/WorkPilot-AI/core/agent/runtime.py
-
curl -L -o runtime.py https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/agent/runtime.py
17.8 kB
| """Builds the main LangGraph graph from installed packs and runs/resumes it durably. | |
| Graph shape:: | |
| START -> router -> <pack intent subgraph> -> finish -> END | |
| -> supervisor -> <step subgraph> -> advance -> <next step> ... -> finish | |
| -> unsupported -> finish | |
| State is checkpointed in Postgres after every step (PostgresSaver), so a run that pauses on | |
| an approval can be resumed days later by ``thread_id`` from any process. | |
| """ | |
| from __future__ import annotations | |
| import uuid | |
| from dataclasses import dataclass, field | |
| from datetime import UTC, datetime | |
| from typing import Any | |
| from langgraph.checkpoint.base import BaseCheckpointSaver | |
| from langgraph.errors import NodeError | |
| from langgraph.graph import END, START, StateGraph | |
| from langgraph.runtime import RunControl | |
| from langgraph.types import Command, TimeoutPolicy | |
| from sqlalchemy import select, update | |
| from sqlalchemy.ext.asyncio import AsyncSession | |
| from core.agent.models import ModelTiers | |
| from core.agent.router import SUPERVISOR, UNSUPPORTED, route | |
| from core.agent.runs import Run | |
| from core.agent.state import Event, RunState | |
| from core.agent.supervisor import PlanRejected, make_plan | |
| from core.agent.tenant_config import ( | |
| collect_alias_claims, | |
| default_aliases, | |
| load_tenant_config, | |
| tenant_aliases, | |
| time_context, | |
| ) | |
| from core.agent.tools import ToolCaller | |
| from core.db.session import Database | |
| from core.gateway.gateway import Gateway | |
| from core.memory.client import MemoryClient | |
| from core.observability.context import RunContext, current_run, run_context | |
| from core.observability.costs import db_cost_sink | |
| from core.observability.injection import detect | |
| from core.observability.models import SecuritySignal | |
| from core.observability.tracing import run_span, set_attrs | |
| from core.packs.loader import AgentDeps, IntentInfo, Pack | |
| from core.tools.preview import canonical_json, sha256_hex | |
| FINISH = "finish" | |
| ADVANCE = "advance" | |
| CORE_NODES = ("router", SUPERVISOR, ADVANCE, UNSUPPORTED, FINISH) | |
| class RunNotFound(Exception): | |
| pass | |
| class IncompatibleGraph(Exception): | |
| pass | |
| class RunResult: | |
| run_id: uuid.UUID | |
| thread_id: str | |
| status: str | |
| intent: str | None = None | |
| output: str | None = None | |
| error: str | None = None | |
| pending: list[dict[str, Any]] = field(default_factory=list) | |
| actions: list[dict[str, Any]] = field(default_factory=list) | |
| log: list[str] = field(default_factory=list) | |
| class AgentRuntime: | |
| def __init__( | |
| self, | |
| db: Database, | |
| gateway: Gateway, | |
| models: ModelTiers, | |
| packs: list[Pack], | |
| checkpointer: BaseCheckpointSaver, | |
| *, | |
| node_timeout_s: float = 120.0, | |
| ) -> None: | |
| self.db = db | |
| # Phase 15: every tier traced (GenAI spans) and costed into runs.cost_usd. | |
| self.models = models.instrumented() | |
| self.packs = packs | |
| caller = ToolCaller(gateway) | |
| self.deps = AgentDeps(tools=caller, models=self.models, memory=MemoryClient(caller)) | |
| self.intents: list[IntentInfo] = [i for p in packs for i in p.intents()] | |
| # External event type -> intent, from packs that declare ``event_aliases()`` (default | |
| # claims) or ``tenant_event_aliases()`` (opt-in). Phase 15 (ADR-0009 G1): several packs | |
| # may claim one event; each tenant's binding picks (``tenant_config.tenant_aliases``). | |
| self.alias_claims = collect_alias_claims(packs) | |
| self.aliases: dict[str, str] = default_aliases(self.alias_claims) | |
| self.subgraphs: dict[str, Any] = {} | |
| for p in packs: | |
| for name, sg in p.subgraphs(self.deps).items(): | |
| if name in self.subgraphs or name in CORE_NODES: | |
| raise ValueError(f"duplicate node name {name}") | |
| self.subgraphs[name] = sg | |
| # Phase 11: owner-approved workflows (DSL) run as the core ``workflow.run`` subgraph. | |
| from core.workflows.executor import install as install_workflows | |
| install_workflows(self) | |
| missing = {i.name for i in self.intents} - set(self.subgraphs) | |
| if missing: | |
| raise ValueError(f"intents without subgraphs: {missing}") | |
| self.node_timeout_s = node_timeout_s | |
| # Phase 13: optional voice-note transcriber (None unless enabled in settings). | |
| from core.i18n.pipeline import configured_transcriber | |
| self.transcriber = configured_transcriber() | |
| self.graph = self._build().compile(checkpointer=checkpointer) | |
| self.nodes = sorted([*CORE_NODES, *self.subgraphs]) | |
| self.version = sha256_hex( | |
| canonical_json({"nodes": self.nodes, "packs": {p.name: p.version for p in packs}}) | |
| ) | |
| self._controls: dict[str, RunControl] = {} | |
| # Phase 15: optional online LLM judge on sampled finished runs (a score, never an | |
| # action); see core.memory.langfuse_prompts.JudgeHook. | |
| self.judge: Any = None | |
| # ------------------------------------------------------------------ graph | |
| def _build(self) -> StateGraph: | |
| g = StateGraph(RunState) | |
| g.set_node_defaults( | |
| timeout=TimeoutPolicy(run_timeout=self.node_timeout_s), | |
| error_handler=self._on_error, # type: ignore[arg-type] | |
| ) | |
| g.add_node("router", self._router_node) | |
| g.add_node(SUPERVISOR, self._supervisor_node) | |
| g.add_node(ADVANCE, self._advance_node) | |
| g.add_node(UNSUPPORTED, self._unsupported_node) | |
| g.add_node(FINISH, self._finish_node) | |
| for name, sg in self.subgraphs.items(): | |
| g.add_node(name, sg) | |
| g.add_conditional_edges(name, self._after_step, [ADVANCE, FINISH]) | |
| targets = [*self.subgraphs, SUPERVISOR, UNSUPPORTED] | |
| g.add_edge(START, "router") | |
| g.add_conditional_edges("router", lambda s: s["intent"], targets) | |
| g.add_conditional_edges(SUPERVISOR, self._dispatch, [*self.subgraphs, UNSUPPORTED, FINISH]) | |
| g.add_conditional_edges(ADVANCE, self._dispatch, [*self.subgraphs, UNSUPPORTED, FINISH]) | |
| g.add_edge(UNSUPPORTED, FINISH) | |
| g.add_edge(FINISH, END) | |
| return g | |
| async def _router_node(self, state: RunState) -> dict[str, Any]: | |
| event = Event.model_validate(state["event"]) | |
| # Phase 15: the tenant's config snapshot (G5) picks channel-event bindings (G1) and | |
| # gives the router the business date and time zone (G6). | |
| run = current_run() | |
| config = dict(run.tenant_config) if run is not None else {} | |
| aliases = tenant_aliases(self.alias_claims, config) if config else self.aliases | |
| intent = await route( | |
| event, | |
| self.intents, | |
| self.models.router, | |
| aliases, | |
| context=time_context(config) if config else None, | |
| ) | |
| return { | |
| "intent": intent, | |
| "status": "running", | |
| "tenant_config": config, | |
| "log": [f"routed to {intent}"], | |
| } | |
| async def _supervisor_node(self, state: RunState) -> dict[str, Any]: | |
| event = Event.model_validate(state["event"]) | |
| try: | |
| steps = await make_plan(event.text or "", self.intents, self.models.planner) | |
| except PlanRejected as exc: | |
| return {"plan": [], "cursor": 0, "log": [f"plan rejected: {exc}"]} | |
| plan = [s.model_dump() for s in steps] | |
| return { | |
| "plan": plan, | |
| "cursor": 0, | |
| "log": [f"plan: {' -> '.join(s['intent'] for s in plan)}"], | |
| } | |
| def _dispatch(state: RunState) -> str: | |
| plan = state.get("plan") or [] | |
| cursor = state.get("cursor", 0) | |
| if not plan: | |
| return UNSUPPORTED | |
| if state.get("status") == "failed" or cursor >= len(plan): | |
| return FINISH | |
| return str(plan[cursor]["intent"]) | |
| def _after_step(state: RunState) -> str: | |
| return ADVANCE if state.get("plan") else FINISH | |
| async def _advance_node(state: RunState) -> dict[str, Any]: | |
| return {"cursor": state.get("cursor", 0) + 1} | |
| async def _unsupported_node(state: RunState) -> dict[str, Any]: | |
| return { | |
| "status": "unsupported", | |
| "output": "I can't help with that request. It is outside what this workspace " | |
| "is set up to do.", | |
| } | |
| async def _finish_node(state: RunState) -> dict[str, Any]: | |
| status = state.get("status", "running") | |
| if status == "running": | |
| status = "completed" | |
| return {"status": status, "output": state.get("output") or "; ".join(state.get("log", []))} | |
| async def _on_error(state: RunState, error: NodeError) -> Command: | |
| return Command( | |
| update={ | |
| "status": "failed", | |
| "error": f"{error.node}: {type(error.error).__name__}: {error.error}", | |
| }, | |
| goto=FINISH, | |
| ) | |
| # ---------------------------------------------------------------- running | |
| async def start( | |
| self, tenant_id: uuid.UUID, event: Event, *, run_id: uuid.UUID | None = None | |
| ) -> RunResult: | |
| """Start a run. With an explicit ``run_id`` this is idempotent: if that run already | |
| exists (a durable dispatcher retrying after a crash), it continues from its last | |
| checkpoint, or returns its current state if it is no longer running.""" | |
| if run_id is not None: | |
| existing = await self._existing(tenant_id, run_id) | |
| if existing is not None: | |
| return existing | |
| run_id = run_id or uuid.uuid4() | |
| thread_id = f"{tenant_id}:{run_id}" | |
| # Phase 13: transcribe voice notes (if enabled), detect language, normalize spelling. | |
| from core.i18n.pipeline import prepare_event | |
| event = await prepare_event(event, self.transcriber) | |
| # Phase 15: heuristic injection signal on untrusted text (a routing/alerting SIGNAL, | |
| # never a permission: the gateway decides every side effect regardless). | |
| signal = detect(event.text) if not event.trusted else detect(None) | |
| async with self.db.session(tenant_id=tenant_id) as s, s.begin(): | |
| s.add( | |
| Run( | |
| id=run_id, | |
| tenant_id=tenant_id, | |
| thread_id=thread_id, | |
| event=event.model_dump(mode="json"), | |
| graph_version=self.version, | |
| graph_nodes=self.nodes, | |
| ) | |
| ) | |
| if signal.flagged: | |
| s.add( | |
| SecuritySignal( | |
| tenant_id=tenant_id, | |
| run_id=run_id, | |
| kind="injection", | |
| score=signal.score, | |
| detail={"rules": list(signal.rules), "source": event.source}, | |
| ) | |
| ) | |
| initial: RunState = { | |
| "tenant_id": str(tenant_id), | |
| "run_id": str(run_id), | |
| "thread_id": thread_id, | |
| "event": event.model_dump(mode="json"), | |
| "log": [], | |
| "actions": [], | |
| "status": "running", | |
| "signals": {"injection": signal.as_dict()}, | |
| } | |
| return await self._invoke(tenant_id, run_id, thread_id, initial) | |
| async def resume(self, tenant_id: uuid.UUID, thread_id: str) -> RunResult: | |
| async with self.db.session(tenant_id=tenant_id) as s: | |
| run = ( | |
| await s.execute(select(Run).where(Run.thread_id == thread_id)) | |
| ).scalar_one_or_none() | |
| if run is None: # also the cross-tenant case: RLS hides other tenants' runs | |
| raise RunNotFound(thread_id) | |
| if run.status != "waiting_approval": | |
| raise RunNotFound(f"run {run.id} is {run.status}, not waiting") | |
| if run.graph_version != self.version and not set(run.graph_nodes) <= set(self.nodes): | |
| raise IncompatibleGraph(f"run {run.id} needs nodes missing from this deploy") | |
| return await self._invoke(tenant_id, run.id, thread_id, Command(resume={"resumed": True})) | |
| async def _existing(self, tenant_id: uuid.UUID, run_id: uuid.UUID) -> RunResult | None: | |
| async with self.db.session(tenant_id=tenant_id) as s: | |
| run = (await s.execute(select(Run).where(Run.id == run_id))).scalar_one_or_none() | |
| if run is None: | |
| return None | |
| config: Any = {"configurable": {"thread_id": run.thread_id}} | |
| snapshot = await self.graph.aget_state(config) | |
| if run.status == "running": | |
| if not snapshot.values: # crashed before the first checkpoint: start over | |
| initial: RunState = { | |
| "tenant_id": str(tenant_id), | |
| "run_id": str(run_id), | |
| "thread_id": run.thread_id, | |
| "event": run.event, | |
| "log": [], | |
| "actions": [], | |
| "status": "running", | |
| } | |
| return await self._invoke(tenant_id, run_id, run.thread_id, initial) | |
| # Continue from the last checkpoint; completed nodes are not re-run, and tool | |
| # calls inside a re-run node replay through gateway idempotency keys. | |
| return await self._invoke(tenant_id, run_id, run.thread_id, None) | |
| values = snapshot.values or {} | |
| return RunResult( | |
| run_id=run_id, | |
| thread_id=run.thread_id, | |
| status=run.status, | |
| intent=run.intent, | |
| output=run.output, | |
| error=run.error, | |
| pending=[i.value for i in snapshot.interrupts], | |
| actions=list(values.get("actions", [])), | |
| log=list(values.get("log", [])), | |
| ) | |
| def request_drain(self, reason: str = "shutdown") -> None: | |
| """Graceful deploys: stop in-flight runs at the next step boundary (state is saved).""" | |
| for control in self._controls.values(): | |
| control.request_drain(reason) | |
| async def _invoke( | |
| self, tenant_id: uuid.UUID, run_id: uuid.UUID, thread_id: str, payload: Any | |
| ) -> RunResult: | |
| control = RunControl() | |
| self._controls[thread_id] = control | |
| # Phase 15: run context (tenant config for prompts, LLM cost into runs.cost_usd) and | |
| # the run span every LLM and tool span nests under. | |
| async with self.db.session(tenant_id=tenant_id) as s: | |
| config = await load_tenant_config(s, tenant_id, [p.name for p in self.packs]) | |
| ctx = RunContext( | |
| tenant_id=tenant_id, | |
| run_id=run_id, | |
| thread_id=thread_id, | |
| tenant_config=config, | |
| cost_sink=db_cost_sink(self.db), | |
| ) | |
| operation = "start" if isinstance(payload, dict) else "resume" | |
| try: | |
| with run_context(ctx), run_span(tenant_id, run_id, thread_id, operation) as span: | |
| result = await self.graph.ainvoke( | |
| payload, {"configurable": {"thread_id": thread_id}}, control=control | |
| ) | |
| set_attrs( | |
| span, | |
| { | |
| "workpilot.run.intent": result.get("intent"), | |
| "workpilot.run.status": result.get("status"), | |
| "workpilot.cost_usd": ctx.cost_usd, | |
| "gen_ai.usage.input_tokens": ctx.input_tokens, | |
| "gen_ai.usage.output_tokens": ctx.output_tokens, | |
| }, | |
| ) | |
| finally: | |
| self._controls.pop(thread_id, None) | |
| interrupts = result.get("__interrupt__", []) if isinstance(result, dict) else [] | |
| pending = [i.value for i in interrupts] | |
| status = "waiting_approval" if pending else result.get("status", "completed") | |
| async with self.db.session(tenant_id=tenant_id) as s, s.begin(): | |
| await s.execute( | |
| update(Run) | |
| .where(Run.id == run_id) | |
| .values( | |
| status=status, | |
| intent=result.get("intent"), | |
| output=result.get("output"), | |
| error=result.get("error"), | |
| ended_at=None if pending else datetime.now(UTC), | |
| ) | |
| ) | |
| if self.judge is not None and not pending: | |
| await self.judge.maybe_judge( | |
| run_id, result.get("output"), list(result.get("actions", [])) | |
| ) | |
| return RunResult( | |
| run_id=run_id, | |
| thread_id=thread_id, | |
| status=status, | |
| intent=result.get("intent"), | |
| output=result.get("output"), | |
| error=result.get("error"), | |
| pending=pending, | |
| actions=list(result.get("actions", [])), | |
| log=list(result.get("log", [])), | |
| ) | |
| async def incompatible_waiting_runs(session: AsyncSession, new_nodes: list[str]) -> list[str]: | |
| """Deploy check (run with the owner role, across tenants): waiting runs whose nodes would | |
| be missing from the new graph. LangGraph cannot migrate removed/renamed nodes on threads | |
| paused at an interrupt, so these must be drained first.""" | |
| rows = await session.execute( | |
| select(Run.id, Run.graph_nodes).where(Run.status == "waiting_approval") | |
| ) | |
| new = set(new_nodes) | |
| return [str(r.id) for r in rows if not set(r.graph_nodes) <= new] | |