Spaces:
Running

File size: 4,140 Bytes
fd5dd94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
"""Gateway-backed tool calling for graph nodes, with per-call human-in-the-loop.



A node calls ``ToolCaller.call(state, step_id, tool, args)``. The idempotency key is derived

from (run_id, step_id), so when LangGraph re-runs a node after a crash or a resume, every

call already executed is replayed instead of repeated. If the gateway answers

``needs_approval`` the node pauses with ``interrupt()``; after a human decides, the node

re-runs, the gateway consumes the approval and executes exactly once.

"""

from __future__ import annotations

import uuid
from typing import Any

from langgraph.types import interrupt

from core.agent.state import RunState
from core.approvals.models import Approval
from core.gateway.gateway import Gateway, GatewayOutcome, ToolCall
from core.gateway.taint import split_taint

# Gateway reason when the human edited the call (see Gateway._approval_needed).
EDITED = "human edited the call"
_NS = uuid.UUID("6f1b3c1e-3a52-4a57-9d6e-1f2b0b7f5a10")


def step_key(run_id: str, step_id: str) -> uuid.UUID:
    return uuid.uuid5(_NS, f"{run_id}:{step_id}")


class ToolCaller:
    def __init__(self, gateway: Gateway) -> None:
        self.gateway = gateway

    async def call(

        self,

        state: RunState,

        step_id: str,

        tool: str,

        args: dict[str, Any],

        *,

        model: str | None = None,

    ) -> GatewayOutcome:
        plain, taint = split_taint(args)
        run_id = state["run_id"]
        call = ToolCall(
            tenant_id=uuid.UUID(state["tenant_id"]),
            actor=f"agent:{run_id}",
            tool=tool,
            args=plain,
            taint=taint,
            idempotency_key=step_key(run_id, step_id),
            run_id=uuid.UUID(run_id),
            thread_id=state.get("thread_id"),
            model=model,
        )
        outcome = await self.gateway.execute(call)
        while outcome.status == "needs_approval":
            # Pauses the run. On resume this node runs again from the top and the gateway is
            # the source of truth (it consumes the approval). If we get here after a resume,
            # the decision is still pending, so ask again (a new interrupt pauses again).
            interrupt(
                {
                    "type": "approval",
                    "approval_id": str(outcome.approval_id),
                    "tool": tool,
                    "reason": outcome.reason,
                }
            )
            outcome = await self.gateway.execute(call)
        if outcome.status == "rejected" and outcome.reason == EDITED and outcome.approval_id:
            # A human edited the call: run the edited version (same tool, values now from the
            # human, so untainted). The gateway consumes the pre-approved replacement once; a
            # replay after a crash hits the idempotency key instead.
            edited = await self._replacement_args(call.tenant_id, outcome.approval_id)
            if edited is not None:
                outcome = await self.gateway.execute(
                    call.model_copy(
                        update={
                            "args": edited,
                            "taint": {},
                            "idempotency_key": step_key(run_id, f"{step_id}:edited"),
                        }
                    )
                )
        return outcome

    async def _replacement_args(

        self, tenant_id: uuid.UUID, approval_id: uuid.UUID

    ) -> dict[str, Any] | None:
        async with self.gateway.db.session(tenant_id=tenant_id) as s:
            a = await s.get(Approval, approval_id)
        return dict(a.args) if a is not None else None


def action_record(step_id: str, tool: str, outcome: GatewayOutcome) -> dict[str, Any]:
    return {
        "step": step_id,
        "tool": tool,
        "status": outcome.status,
        "reason": outcome.reason,
        "approval_id": str(outcome.approval_id) if outcome.approval_id else None,
        "data": outcome.result.data if outcome.result else None,
    }