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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
"""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


@dataclass
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)}"],
        }

    @staticmethod
    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"])

    @staticmethod
    def _after_step(state: RunState) -> str:
        return ADVANCE if state.get("plan") else FINISH

    @staticmethod
    async def _advance_node(state: RunState) -> dict[str, Any]:
        return {"cursor": state.get("cursor", 0) + 1}

    @staticmethod
    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.",
        }

    @staticmethod
    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", []))}

    @staticmethod
    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]