Spaces:
Running

Aynkhn's picture
Deploy WorkPilot demo
fd5dd94 verified
Raw History Blame Contribute Delete
3.19 kB
"""Human decisions that need both the approval store and the gateway (edits re-run policy
and dry-run before the edited call is pre-approved)."""
from __future__ import annotations
import uuid
from dataclasses import dataclass
from typing import Any
from core.approvals.models import Approval
from core.approvals.service import ApprovalError, ApprovalService, Decision
from core.db.session import Database
from core.gateway.gateway import Gateway, ToolCall
from core.gateway.policy import PolicyOutcome
from core.tenancy.models import Role
@dataclass(frozen=True)
class DecisionResult:
approval: Approval
replacement: Approval | None = None
async def apply_decision(
db: Database,
gateway: Gateway,
service: ApprovalService,
*,
tenant_id: uuid.UUID,
approval_id: uuid.UUID,
user_id: uuid.UUID,
user_role: Role,
decision: Decision,
note: str | None = None,
edited_args: dict[str, Any] | None = None,
stepup_ok: bool = False,
) -> DecisionResult:
if decision == "edit":
async with db.session(tenant_id=tenant_id) as s:
original = await service.get(s, approval_id)
if edited_args is None:
raise ApprovalError("edit requires edited_args")
# An edit may not switch tools: the tool comes from the original approval only.
check = ToolCall(
tenant_id=tenant_id,
actor=original.actor,
tool=original.tool,
args=edited_args,
run_id=original.run_id,
dry_run=True,
)
policy, preview = await gateway.preview(check)
if policy.outcome is PolicyOutcome.DENY:
raise ApprovalError(f"edited call is forbidden by policy: {policy.reasons}")
if preview is not None and not preview.ok:
raise ApprovalError(f"edited call failed dry run: {preview.error}")
normalized = (
gateway.registry.get(original.tool)
.spec.input_model.model_validate(edited_args)
.model_dump(mode="json")
)
async with db.session(tenant_id=tenant_id) as s, s.begin():
a = await service.decide(
s,
approval_id,
user_id=user_id,
user_role=user_role,
decision="edit",
note=note,
edited_args=normalized,
stepup_ok=stepup_ok,
)
new = await service.grant_edited(
s,
a,
args=normalized,
preview=(preview.data or {}) if preview else {},
preview_hash=preview.preview_hash if preview else None,
)
return DecisionResult(approval=a, replacement=new)
async with db.session(tenant_id=tenant_id) as s, s.begin():
a = await service.decide(
s,
approval_id,
user_id=user_id,
user_role=user_role,
decision=decision,
note=note,
stepup_ok=stepup_ok,
)
return DecisionResult(approval=a)