"""The hooks: one request is one turn of an Execution, from a workflow step or a conversation. A workflow step names its `phase` and runs until that Phase awaits its Approval. Reaching the next step means the reviewer let the last one through, and `hitl_feedback` means they asked for it again with comments. The last step, `complete`, approves packaging and ends the Execution. A conversation sends a message, and each turn answers whatever the Execution last asked. Nothing is kept in the process between requests. """ from __future__ import annotations import fcntl import json import os import re import time import uuid from typing import Any import structlog from kyndryl_agent_runtime import Reply from app.assembly import assemble, output_root from app.engine.agent import ExecutionEngine, Interaction from app.engine.execution_nodes import NO_USER_REPLY from app.engine.presentation import describe_prompt # Time kept back from the runtime's limit, to stop between steps and reply. MARGIN_SECONDS = 120 ROOT = "cp1-solution-architecture-agent" _APPROVES = re.compile(r"\s*(approve|approved|i approve|yes,? approve)[.! ]*", re.IGNORECASE) _YES = re.compile(r"\s*(yes|allow|granted)[.! ]*", re.IGNORECASE) _NO = re.compile(r"\s*(no|refuse|denied|deny)[.! ]*", re.IGNORECASE) # Replies this process produced, so post_process can tell one from a model's own words. _issued: dict[str, dict[str, Any]] = {} def _time_left() -> Any: limit = float(os.getenv("AGENT_MAX_DURATION_SECONDS", "1500")) - MARGIN_SECONDS started = time.monotonic() return lambda: limit - (time.monotonic() - started) def _context_id() -> str: return str(structlog.contextvars.get_contextvars().get("context_id") or "") def _execution_id(payload: dict[str, Any]) -> str: """One Execution per workflow run or conversation.""" from kyndryl_agent_runtime.context import get_workflow_execution_id run = get_workflow_execution_id() if payload.get("phase") else "" if run and run != "unknown": return re.sub(r"[^A-Za-z0-9_.-]", "-", run) named = str(payload.get("conversation_id") or _context_id()) if not named: raise ValueError("A conversation needs a conversation_id or an A2A contextId.") return re.sub(r"[^A-Za-z0-9_.-]", "-", named) def _spoken_reply(prompt: dict[str, Any], message: str) -> dict[str, Any]: """What a person's words mean to the prompt. Only a plain approval approves: anything longer is read by the router, so a sentence can never approve by accident.""" if "approval" in prompt and _APPROVES.fullmatch(message): return {"approval": {"phase": prompt["approval"]["phase"], "decision": "approve"}} if "permission" in prompt: tier = prompt["permission"]["tier"] if _YES.fullmatch(message): return {"permission": {tier: True}} if _NO.fullmatch(message): return {"permission": {tier: False}} return {"reply": message} async def _start(engine: ExecutionEngine, execution_id: str, payload: dict[str, Any], left: Any) -> Interaction: return await engine.start( str(payload.get("message") or ""), execution_id=execution_id, session_id=execution_id, customer_case=payload.get("engagement"), scope=payload.get("scope_spec"), pre_approved=payload.get("pre_approved"), allow_cloud_read=payload.get("allow_cloud_read"), time_left=left, ) async def _exists(engine: ExecutionEngine, execution_id: str) -> bool: try: await engine.interaction(execution_id) except KeyError: return False return True async def _conversation(engine: ExecutionEngine, execution_id: str, payload: dict[str, Any], left: Any) -> Interaction: if not await _exists(engine, execution_id): return await _start(engine, execution_id, payload, left) current = await engine.interaction(execution_id) if current.status == "running": return await engine.carry_on(execution_id, left) if current.status != "awaiting_user" or current.prompt is None: return current return await engine.resume(execution_id, _spoken_reply(dict(current.prompt), str(payload.get("message") or "")), left) async def _workflow(engine: ExecutionEngine, execution_id: str, payload: dict[str, Any], left: Any) -> Interaction: wanted, feedback = str(payload["phase"]), str(payload.get("hitl_feedback") or "") if not await _exists(engine, execution_id): current = await _start(engine, execution_id, payload, left) else: current = await engine.interaction(execution_id) if current.status == "running": current = await engine.carry_on(execution_id, left) while current.status == "awaiting_user" and current.prompt is not None: prompt = dict(current.prompt) if "approval" in prompt: phase = prompt["approval"]["phase"] if phase != wanted: reply: dict[str, Any] = {"approval": {"phase": phase, "decision": "approve"}} elif feedback: reply = {"approval": {"phase": phase, "decision": "changes", "feedback": feedback}} else: break elif "permission" in prompt: reply = {"permission": {prompt["permission"]["tier"]: bool(payload.get("allow_cloud_read"))}} else: # The reviewer's comments answer the questions. Without them there is nobody # to ask in this step, so the Specialist records its assumptions. reply = {"reply": feedback or NO_USER_REPLY} feedback = "" current = await engine.resume(execution_id, reply, left) return current def _reply(interaction: Interaction, phase: str | None) -> dict[str, Any]: state = interaction.state deliverables = sorted(state.get("deliverables", {})) reply: dict[str, Any] = {"phase": phase, "deliverables": deliverables, "execution_id": interaction.execution_id} if interaction.status == "awaiting_user" and interaction.prompt is not None: prompt = dict(interaction.prompt) approving = "approval" in prompt reply.update( status="phase_complete" if approving and phase else "awaiting_approval" if approving else "awaiting_answer", reply=describe_prompt(prompt), ) if not approving: reply["open_questions"] = [item.get("question", "") for item in prompt.get("questions", [])] elif interaction.status == "completed": reply.update(status="completed", reply="The solution architecture is complete and approved.") elif interaction.status == "running": reply.update(status="running", reply="This turn ran out of time. Finished work is kept: send any message to carry on.") else: warnings = list(state.get("warnings", [])) reply.update(status="failed", reply="The Execution ended with warnings: " + "; ".join(warnings)) return reply def _provider(payload: dict[str, Any]) -> str: """The Cloud provider is set once, on an Execution's first request, and kept with it.""" folder = output_root() / "providers" folder.mkdir(parents=True, exist_ok=True) kept = folder / _execution_id(payload) if kept.exists(): return kept.read_text(encoding="utf-8").strip() provider = str(payload.get("cloud_provider") or "gcp") kept.write_text(provider, encoding="utf-8") return provider async def turn(payload: dict[str, Any], *, engine: ExecutionEngine | None = None) -> dict[str, Any]: try: provider = _provider(payload) # A workflow step has its review point, so drafts aren't shown to anyone first. engine = engine or assemble(provider, confirm_drafts=False if payload.get("phase") else None) execution_id = _execution_id(payload) locks = output_root() / "locks" locks.mkdir(parents=True, exist_ok=True) with (locks / f"{execution_id}.lock").open("a+") as lock: try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError: return {"status": "running", "reply": "Still working on your last message."} left = _time_left() handled = _workflow if payload.get("phase") else _conversation reply = _reply(await handled(engine, execution_id, payload, left), payload.get("phase")) except ValueError as exc: return {"status": "failed", "reply": str(exc)} token = uuid.uuid4().hex _issued[token] = reply return {**reply, "turn": token} async def pre_process(payload: Any) -> Reply: return Reply(json.dumps(await turn(dict(payload)))) async def run_turn(message: str) -> str: """Run one conversation turn for the user's message, and return its reply.""" return json.dumps(await turn({"message": message})) def before_model(call: Any) -> None: """The root model only passes a message on, so it is offered run_turn alone. Without this, every plain-text turn would send it every declared MCP tool. Specialists reach those tools through their own code, and sub-agents aren't given them.""" if call.framework != "adk" or call.agent != ROOT: return request = call.native[1] request.tools_dict = {k: v for k, v in request.tools_dict.items() if k == "run_turn"} for tool in (request.config.tools or []): declared = getattr(tool, "function_declarations", None) if declared: tool.function_declarations = [d for d in declared if d.name == "run_turn"] def post_process(result: Any) -> Any: """A turn's reply comes from code. If the model answered without calling run_turn, or changed what it returned, its words are not passed on.""" token = result.get("turn") if isinstance(result, dict) else None if token in _issued: return _issued.pop(token) return {"status": "failed", "reply": "That message wasn't processed. Please send it again."}