Files
gcp_solution_architecture_a…/app/execution/tools.py
Jonathan Boniface d9214c671a feat: add the hierarchical Execution engine on LangGraph
Increment 4 of .scratch/solution-architect-agent/spec.md, test-first.

- app/agents/runtime.py: framework-neutral AgentRuntime interface
  (RoleSpec, AgentTask, ToolSpec, outcomes); fake_runtime.py replays
  scripted tool calls through the real tools with step budgets.
- app/execution/graph.py: Orchestrator turn fans out to parallel
  Specialist tasks (Send), pauses with interrupt() for questions,
  Approvals and cloud-read permission, and finalizes or ends with
  warnings. Only the Orchestrator turn writes the Ledger.
- app/execution/tools.py: Orchestrator tools, Specialist submit and
  needs_input, and the cloud-read permission gate.
- app/execution/engine.py: ExecutionEngine.start/resume returning an
  Interaction; the single interface for A2A, /generate and eval.
- Recorders (in-memory, DatabaseManager), configurable checkpointer
  (memory, sqlite, postgres), engine settings, langgraph checkpoint
  dependencies.
- 19 new tests; full suite 121 passed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-16 09:38:13 +01:00

319 lines
11 KiB
Python

"""Execution tools: how agents act on an Execution.
Tools enforce the Ledger's rules at the moment an agent acts, and return refusals as
messages so a ReAct agent can recover. A tool ends the agent's turn by returning an
outcome.
"""
from __future__ import annotations
from collections.abc import Mapping, Sequence
from pathlib import PurePosixPath
from typing import Any
from app.agents.runtime import (
NeedsInput,
Submitted,
ToolResult,
ToolSpec,
TurnEnded,
)
from app.execution.deliverables import (
DEPENDENCY_GRAPH,
DeliverableKind,
PhaseId,
check_submission,
deliverables_in,
)
from app.execution.ledger import Ledger, LedgerRefusal, PhaseStatus
ORCHESTRATOR = "orchestrator"
CLOUD_READ = "cloud_read"
_NO_ARGS: Mapping[str, Any] = {"type": "object", "properties": {}}
def _schema(properties: Mapping[str, Any], required: Sequence[str]) -> dict[str, Any]:
return {
"type": "object",
"properties": dict(properties),
"required": list(required),
}
def _refused(reason: object) -> ToolResult:
return ToolResult(f"Refused: {reason}")
class OrchestratorToolbox:
"""The Orchestrator's tools, bound to a working copy of the Ledger for one turn."""
def __init__(
self,
ledger: Ledger,
deliverables: Mapping[str, Mapping[str, Any]],
pending_questions: Sequence[Mapping[str, Any]],
) -> None:
self.ledger = ledger
self._deliverables = deliverables
self._pending_questions = pending_questions
self.started: dict[DeliverableKind, int] = {}
self.questions: list[dict[str, str]] = []
self.approval: dict[str, Any] | None = None
self.escalation: str | None = None
def tools(self) -> list[ToolSpec]:
return [
ToolSpec(
"ready_work",
"List Deliverables ready to delegate and Phases ready for Approval.",
_NO_ARGS,
self.ready_work,
tier="execution",
),
ToolSpec(
"delegate",
"Start Specialists on ready Deliverables, in parallel. Ends your turn.",
_schema(
{"kinds": {"type": "array", "items": {"type": "string"}}},
["kinds"],
),
self.delegate,
tier="execution",
),
ToolSpec(
"ask_user",
"Ask the user your questions together with any waiting Specialist "
"questions. Ends your turn.",
_schema(
{"questions": {"type": "array", "items": {"type": "string"}}}, []
),
self.ask_user,
tier="execution",
),
ToolSpec(
"request_approval",
"Ask the user to approve a Phase whose Deliverables are all "
"submitted. Ends your turn unless the Execution is pre-approved.",
_schema(
{"phase": {"type": "string"}, "summary": {"type": "string"}},
["phase", "summary"],
),
self.request_approval,
tier="execution",
),
ToolSpec(
"reopen",
"Revise a submitted Deliverable; everything depending on it returns "
"to draft.",
_schema(
{"kind": {"type": "string"}, "reason": {"type": "string"}},
["kind", "reason"],
),
self.reopen,
tier="execution",
),
ToolSpec(
"read_deliverable",
"Read a submitted Deliverable's content.",
_schema({"kind": {"type": "string"}}, ["kind"]),
self.read_deliverable,
tier="execution",
),
ToolSpec(
"finish",
"Complete the Execution once packaging is approved. Ends your turn.",
_NO_ARGS,
self.finish,
tier="execution",
),
]
async def ready_work(self) -> ToolResult:
ready = ", ".join(self.ledger.ready_work()) or "none"
phases = ", ".join(self.ledger.phases_ready_for_approval()) or "none"
return ToolResult(
f"Ready to delegate: {ready}. Phases ready for approval: {phases}."
)
async def delegate(self, kinds: Sequence[str]) -> ToolResult:
try:
parsed = [DeliverableKind(kind) for kind in kinds]
if not parsed:
raise LedgerRefusal("name at least one Deliverable")
started = self.ledger.start(parsed, actor=ORCHESTRATOR)
except (ValueError, LedgerRefusal) as exc:
return _refused(exc)
self.started.update(started)
return ToolResult(f"Started: {', '.join(started)}.", TurnEnded("delegate"))
async def ask_user(self, questions: Sequence[str] = ()) -> ToolResult:
waiting = sorted(
self._pending_questions,
key=lambda item: list(DEPENDENCY_GRAPH).index(
DeliverableKind(item["kind"])
),
)
combined = [
{"from": item["kind"], "question": question}
for item in waiting
for question in item["questions"]
]
combined += [{"from": ORCHESTRATOR, "question": q} for q in questions if q]
if not combined:
return _refused("there is nothing to ask the user")
self.questions = combined
return ToolResult("Asked the user.", TurnEnded("ask_user"))
async def request_approval(self, phase: str, summary: str) -> ToolResult:
try:
phase_id = PhaseId(phase)
except ValueError as exc:
return _refused(exc)
if self.ledger.phase_status(phase_id) is not PhaseStatus.AWAITING_APPROVAL:
try:
self.ledger.request_approval(phase_id, actor=ORCHESTRATOR)
except LedgerRefusal as exc:
return _refused(exc)
if self.ledger.phase_status(phase_id) is PhaseStatus.APPROVED:
return ToolResult(
f"Phase {phase_id} approved (pre-approved Execution)."
)
self.approval = {
"phase": phase_id.value,
"summary": summary,
"deliverables": [kind.value for kind in deliverables_in(phase_id)],
}
return ToolResult(
f"Asked the user to approve {phase_id}.", TurnEnded("request_approval")
)
async def reopen(self, kind: str, reason: str) -> ToolResult:
try:
result = self.ledger.reopen(
DeliverableKind(kind), reason, actor=ORCHESTRATOR
)
except (ValueError, LedgerRefusal) as exc:
return _refused(exc)
if result.escalation:
if self.ledger.pre_approved:
self.escalation = result.escalation
return ToolResult(result.escalation, TurnEnded("escalate"))
return ToolResult(
f"{result.escalation} Use ask_user to put this to the user."
)
withdrawn = ", ".join(result.withdrawn_approvals) or "none"
return ToolResult(
f"Reopened {kind}. Returned to draft: {', '.join(result.reset)}. "
f"Approvals withdrawn: {withdrawn}."
)
async def read_deliverable(self, kind: str) -> ToolResult:
deliverable = self._deliverables.get(kind)
if deliverable is None:
return ToolResult(f"{kind} has not been submitted.")
return ToolResult(deliverable["content"])
async def finish(self) -> ToolResult:
if not self.ledger.can_finish():
return _refused("packaging has not been approved")
return ToolResult("Finishing the Execution.", TurnEnded("finish"))
def _safe_relative(name: str) -> bool:
path = PurePosixPath(name)
return bool(name) and not path.is_absolute() and ".." not in path.parts
def specialist_tools(
kind: DeliverableKind,
extra: Sequence[ToolSpec],
allow_cloud_read: bool | None,
) -> list[ToolSpec]:
"""A Specialist's tools: submit, ask, and its role's tools with the cloud-read gate."""
async def submit_deliverable(
content: str, attachments: Mapping[str, str] | None = None
) -> ToolResult:
attachments = dict(attachments or {})
unsafe = [name for name in attachments if not _safe_relative(name)]
if unsafe:
return _refused(
"attachment names must be relative paths without '..': "
+ ", ".join(unsafe)
)
missing = check_submission(kind, content, attachments)
if missing:
return ToolResult(
"Not submitted. The Deliverable is missing: " + "; ".join(missing)
)
return ToolResult(f"Submitted {kind}.", Submitted(content, attachments))
async def needs_input(questions: Sequence[str]) -> ToolResult:
questions = tuple(q for q in questions if q)
if not questions:
return _refused("ask at least one question")
return ToolResult("Questions sent to the user.", NeedsInput(questions))
return [
ToolSpec(
"submit_deliverable",
f"Submit the {kind} Deliverable once it meets its contract. Ends your turn.",
_schema(
{
"content": {"type": "string"},
"attachments": {
"type": "object",
"additionalProperties": {"type": "string"},
},
},
["content"],
),
submit_deliverable,
tier="execution",
),
ToolSpec(
"needs_input",
"Ask the user questions you can't proceed without. Ends your turn.",
_schema(
{"questions": {"type": "array", "items": {"type": "string"}}},
["questions"],
),
needs_input,
tier="execution",
),
*(gate_cloud_read(tool, allow_cloud_read) for tool in extra),
]
def gate_cloud_read(tool: ToolSpec, allow_cloud_read: bool | None) -> ToolSpec:
"""Apply the Execution's cloud-read permission to a tool in that tier."""
if tool.tier != CLOUD_READ or allow_cloud_read is True:
return tool
if allow_cloud_read is False:
async def refuse(**_: Any) -> ToolResult:
return _refused(
"reading live cloud resources is not permitted for this Execution. "
"Work from what the user has told you and record the gap."
)
handler = refuse
else:
async def ask_permission(**_: Any) -> ToolResult:
return ToolResult(
"Permission to read live cloud resources is needed first.",
NeedsInput(
(
f"May I read live resources in your cloud environment? ({tool.name})",
),
permission=CLOUD_READ,
),
)
handler = ask_permission
return ToolSpec(tool.name, tool.description, tool.parameters, handler, tool.tier)