企業 AI 如何為新一代 Agent 協議設計治理攔截與人工介入架構
Next-Gen Agent Protocols & Governance Interceptions: Designing Human-in-the-Loop Architecture for Enterprise AI
企業 AI 可透過治理攔截層,讓 A2A、AG-UI、AP2、x402 與 Pydantic AI 工作流程在需要時暫停,交由人員處理後保留狀態並恢復任務。文中分別示範以 Slack 處理 A2A 談判停滯、以 Microsoft Teams 審批智能體付款,以及把 Pydantic AI 的驗證例外轉交技術客戶經理。
Autonomous AI agents have moved beyond isolated chat windows. They now run multi-step workflows that cross team and company boundaries. Enterprise architectures increasingly rely on open protocols for each layer of that traffic:
- A2A (Agent2Agent) for agent-to-agent delegation.
- AG-UI (Agent-User Interaction) for streaming agent state to front ends.
- AP2 (Agent Payments Protocol) for verifiable payment authorization.
- x402 for HTTP-native payments.
The governance of these standards has changed quickly. Google introduced A2A in April 2025 and donated it to the Linux Foundation in June 2025. A2A v1.0, its first stable specification, shipped on 12 March 2026. By April 2026 the Linux Foundation counted more than 150 supporting organizations. Google released AP2 on 16 September 2025 with more than 60 partners. It donated AP2 to the FIDO Alliance in April 2026 together with the v0.2 release. Coinbase created x402 and moved it to the Linux Foundation. The x402 Foundation was announced on 2 April 2026 and became operational on 14 July 2026 with 40 members.
Autonomy without deterministic escape hatches is still an operational risk. An automated negotiation can stall, a partner agent can ask for more access, or a strict schema can reject ambiguous input. The result is a silent failure or a retry loop that burns tokens and goodwill.
The fix is a governance interception. It is middleware that pauses agent execution, captures enough state to resume it, and routes a human-in-the-loop (HITL) decision card into a tool people already watch, such as Slack or Microsoft Teams. This article walks through three interception patterns and the engineering rules that make them safe.
The Agent Protocol Stack
Each protocol answers a different question, and a governance layer needs to understand where each one can pause.
| Protocol / Framework | Layer | What it standardizes | Where a human gate fits |
|---|---|---|---|
| MCP | Agent ↔ tools | How an agent discovers and calls tools and data sources. | Approval before a high-impact tool call. |
| A2A | Agent ↔ agent | Agent discovery through Agent Cards and a task lifecycle (submitted, working, input-required, auth-required, completed, failed, canceled, rejected). |
Tasks parked in input-required or auth-required. |
| AG-UI | Agent ↔ frontend | A typed event stream (RUN_STARTED, TOOL_CALL_START, STATE_SNAPSHOT, STATE_DELTA, RUN_ERROR and others). It runs over HTTP+SSE or HTTP+Protobuf, and custom transports such as WebSockets are allowed. |
Disconnects mid-run, or human edits to shared state. |
| AP2 | Payment authorization | Cryptographically signed mandates that prove what a user authorized an agent to buy. | Spend above policy, or a missing or out-of-scope mandate. |
| x402 | Payment settlement | The HTTP 402 Payment Required handshake. A server returns the price, the client signs a payment and retries, and a facilitator verifies and settles. |
An approval before an agent’s wallet signs a payment. |
| Pydantic AI | Typed execution | Python agent framework with validated structured output, dependency injection, retries and deferred tool approval. | Exhausted validation retries, or a deferred tool call. |
Some details are worth getting right:
-
A2A is no longer Google-run. It sits under the Linux Foundation and has been reported to be hosted by the Agentic AI Foundation alongside MCP. In v1.0, enum values in the wire format are prefixed, for example
TASK_STATE_INPUT_REQUIRED. This article uses the readable names. -
AG-UI was developed by CopilotKit. It is not a Google protocol. Its
STATE_DELTAevents carry JSON Patch (RFC 6902) operations, andSTATE_SNAPSHOTandMESSAGES_SNAPSHOTlet a client resynchronize. The draft specification also lists an interrupt–resume event pattern. - AP2 and x402 are complementary. AP2 covers who authorized a purchase. x402 covers how a payment is demanded and settled over HTTP. Google’s AP2 materials include an A2A x402 extension, developed with Coinbase, the Ethereum Foundation and MetaMask. x402 itself does not verify identity or intent.
- AP2 mandates changed between versions. The original design used Intent, Cart and Payment mandates. The v0.2 specification describes Checkout and Payment mandates, each with an open stage (user constraints for autonomous execution) and a closed stage (a finalized transaction). v0.2 added “Human Not Present” payments.
1. Routing A2A and AG-UI Stalls to a Deal Desk in Slack
In revenue operations, a buyer’s procurement agent can talk to a vendor’s quoting agent over A2A. An account executive watches the negotiation in an AG-UI-powered deal room.
Anatomy of a stall
A2A tasks move through a defined lifecycle. When the vendor’s quoting agent meets a term outside its mandate, such as a custom indemnity clause or a discount beyond its authority, the natural move is to set the task to input-required (or auth-required if credentials are the problem). Those states exist so a task can pause and ask the caller for more. The protocol does not tell you who answers, or how fast.
Two separate failure modes tend to hide behind the same symptom:
-
A task that nobody is watching. It sits in
input-requiredbecause the human who should respond doesn’t know. A2A defines the states but no escalation routing. - A front end that has gone away. AG-UI streams typed events to the client. If the browser tab closes or the network drops mid-run, the stream ends. The protocol has no built-in notion of “a human must take over,” so that logic belongs in your application layer.
Relying on error logs means a high-value deal sits frozen until someone notices. An interception broker should watch both the task state and the stream.
Architecture for a real-time takeover
-
Watchdog. A proxy in front of the A2A server and the AG-UI event emitter triggers an interception when:
- a task stays in
input-requiredorworkingbeyond an SLA you choose (say 45 seconds for a live negotiation; tune it to your process); - an AG-UI run emits
RUN_ERROR, or the stream drops while a tool call (TOOL_CALL_STARTseen, no matchingTOOL_CALL_END) is still open; - the agent calls an explicit escalation tool because a policy boundary was hit.
- a task stays in
-
Snapshot and lock. Before notifying anyone, the broker reads the task (the v1.0 operation is
GetTask) and the latestSTATE_SNAPSHOT, which holds the active quote, line items and transcript. It takes a lock with an expiry, for example in Redis, so another worker doesn’t retry the same step. Remember that A2A tasks become immutable once they reach a terminal state such asfailed. A failed task can’t be revived, so the resolution would have to start a new task in the same context. -
Slack Block Kit card. The broker posts an interactive card to a channel such as
#deal-desk-escalations, or DMs the account owner. The names and figures below are illustrative.
{
"blocks": [
{
"type": "header",
"text": {
"type": "plain_text",
"text": "🚨 A2A Deal Negotiation Stalled: Acme Corp ($240,000 ARR)"
}
},
{
"type": "section",
"fields": [
{ "type": "mrkdwn", "text": "*Interrupt Trigger:*\nA2A `input-required` (discount > 25%)" },
{ "type": "mrkdwn", "text": "*AG-UI Session:*\nDisconnected (last `STATE_DELTA` 12s ago)" }
]
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*Buyer Agent Request:* 32% multi-year discount + Net-60 payment terms. Quoting agent paused."
}
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": { "type": "plain_text", "text": "Approve 32% & Resume" },
"style": "primary",
"action_id": "a2a_approve_override",
"value": "intr_98a7f6c2"
},
{
"type": "button",
"text": { "type": "plain_text", "text": "Counter at 28%" },
"action_id": "a2a_counter_modal",
"value": "intr_98a7f6c2"
},
{
"type": "button",
"text": { "type": "plain_text", "text": "Take Over Thread" },
"style": "danger",
"action_id": "agui_human_takeover",
"value": "intr_98a7f6c2"
}
]
}
]
}
Keep the button value opaque, such as an interception ID. Look up the real task and quote server-side rather than trusting data that round-trips through a chat client.
Handling the click
Slack requires an acknowledgment within about three seconds. The handler should verify the request, record the decision, return 200, and do the slow work asynchronously. It can post follow-ups to the interaction’s response_url, which Slack documents as valid for 30 minutes and up to five uses. A button that opens a modal, such as the counter-offer, must call views.open quickly with the interaction’s trigger_id, which also expires within seconds.
Once the human decides, the broker:
- Records an attributable human approval, including who approved, what and when, on the task as metadata.
- Sends the decision into the existing task as a follow-up message with the same task ID. In A2A, the caller supplies the missing input and the agent moves the task back to
working. The broker should not write task states directly. - Updates the shared state store and emits a fresh
STATE_SNAPSHOT(or aSTATE_DELTApatch) when the front end reconnects, so the UI shows the approved discount without drift.
2. Step-Up Human Approval for Agent Payments and Cross-Boundary Requests, with Microsoft Teams
When agents cross organizational boundaries, internal role-based access control is not enough. A partner’s supply-chain agent might query your inventory, or your procurement agent might pay an outside service. Two distinct flows need separate gates.
Outbound: your agent is about to pay
In x402 the client does the paying. The server answers an unpaid request with 402 Payment Required and a PAYMENT-REQUIRED header describing the price, network and accepted payment options. The client signs one option and retries with a PAYMENT-SIGNATURE header. The server verifies the payload directly or through a facilitator (/verify, then /settle) and returns the resource with a PAYMENT-RESPONSE header. x402 is stateless and needs no account or API key.
That design is exactly why you need a policy gate on the paying side. The only moment a human can intervene is before your agent’s wallet signs. After that, settlement can be quick and final. A step-up rule should fire when:
- the amount exceeds an automated spend cap (the example below uses $5,000; set it from your own risk policy);
- the payee is new, or isn’t on an approved list;
- the request would release data or scopes your policy marks as restricted.
If you use AP2 for the user-authorization layer, remember what a mandate is. In AP2, a user approves a checkout or payment on a trusted surface, and the result is a signed credential. A button click in Teams is an enterprise approval record. It does not replace a signed mandate. If your flow needs an AP2 mandate, the approval should trigger the signing step in the user’s credential provider or wallet.
Inbound: a partner agent asks for something
When an external agent calls your A2A endpoint, A2A already has the right states for pausing. auth-required means the agent needs additional authentication, and input-required means it is blocked on the caller. A2A Agent Cards declare supported auth schemes using OpenAPI-style security schemes: API key, HTTP bearer, OAuth 2.0, OpenID Connect and mutual TLS. A2A defines no reputation or trust score, so if your policy needs one, it must come from your own partner registry.
For non-A2A HTTP APIs, the standard asynchronous pattern is 202 Accepted with a status URL. It is better than a hard 403 when a human might say yes. Evaluate policy in a Policy Enforcement Point backed by an engine such as Open Policy Agent.
Building the Teams approval
Interactive Adaptive Cards in Teams need a bot or agent app behind them. Microsoft’s Bot Framework SDK has been archived, and support tickets stopped being serviced on 31 December 2025. Microsoft now points Teams-only builders to the Teams SDK and cross-surface builders to the Microsoft 365 Agents SDK.
Microsoft also recommends Action.Execute (Universal Actions, schema 1.4+, with 1.5 recommended) over the older Action.Submit. Your bot receives clicks as an adaptiveCard/action invoke. For older clients, set fallback to Action.Submit and handle both.
{
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"type": "AdaptiveCard",
"version": "1.5",
"body": [
{
"type": "TextBlock",
"size": "Large",
"weight": "Bolder",
"color": "Attention",
"text": "🛡️ Agent Payment Needs Approval"
},
{
"type": "FactSet",
"facts": [
{ "title": "Requesting Agent:", "value": "Procurement Agent (prod)" },
{ "title": "Payee:", "value": "GlobalLogistics (new vendor)" },
{ "title": "Amount:", "value": "$18,450.00 (exceeds $5,000 auto-cap)" },
{ "title": "Mandate / Request ID:", "value": "req_7741" }
]
},
{
"type": "Input.Text",
"id": "approver_notes",
"placeholder": "Add audit justification or conditions..."
}
],
"actions": [
{
"type": "Action.Execute",
"title": "✅ Approve & Release",
"verb": "approve_payment",
"style": "positive",
"data": { "interception_id": "req_7741" },
"fallback": "Action.Submit"
},
{
"type": "Action.Execute",
"title": "⛔ Reject",
"verb": "reject_payment",
"style": "destructive",
"data": { "interception_id": "req_7741" },
"fallback": "Action.Submit"
}
]
}
On approval, the backend does five things:
- Authenticates the bot request, resolves the approver’s Microsoft Entra identity from the activity, and checks it against the approver group for that spend tier.
- Records the decision, with notes, in an append-only audit store.
- Releases the pending signing step (for x402, the wallet signature) exactly once.
- Surfaces the settlement result from the
PAYMENT-RESPONSEheader. - Updates the card to show who decided and when.
Write-once (WORM) storage for these records can support audit evidence needs, including those of SOC 2 and ISO/IEC 42001, the AI management system standard. No framework dictates it by name.
3. Pydantic AI Guardrail Trips: Routing Edge Cases to Technical Account Managers
A2A and AP2 govern the external boundary. Internal reliability depends on strict contracts. Pydantic AI provides typed output_type schemas, dependency injection through RunContext, @agent.output_validator hooks, and ModelRetry for asking the model to correct itself.
When guardrails trip
Customer requests rarely fit clean schemas. Imagine a Solutions Engineering agent that parses RFPs and provisions cloud sandboxes. It can fail in three ways:
-
Validation exhaustion. Each failed validation or
ModelRetryconsumes the output retry budget. In Pydantic AI, exhausting that budget raisesUnexpectedModelBehavior. A configuration that is invalid for good, such as an unsupported compliance tier paired with an incompatible region, ends here. - Capability boundary miss. A tool dependency checks tenant entitlements and signals that the request is out of scope. The exception name in the code below is a custom one you would define. It is not part of the library.
- Ambiguity. A custom validator catches contradictory instructions, such as “zero-downtime active-active, but keep single-AZ database costs.”
If the agent just returns a generic error, an enterprise account sees a dead end. Catching the exception lets you hand the problem to a human with context.
A wrapper that captures the failure
Pydantic AI’s capture_run_messages context manager exposes the message history, including failed attempts, even when the run raises. The handler below sends that context to a Technical Account Manager (TAM). dispatch_tam_claim_card stands in for your own Slack or Teams posting code.
from dataclasses import dataclass
from pydantic import BaseModel, Field, field_validator
from pydantic_ai import (
Agent,
ModelRetry,
RunContext,
UnexpectedModelBehavior,
capture_run_messages,
)
class SandboxProvisionSpec(BaseModel):
tenant_id: str
region: str
node_count: int = Field(ge=1, le=64)
compliance_tier: str
@field_validator("compliance_tier")
@classmethod
def validate_tier(cls, v: str) -> str:
allowed = {"SOC2", "HIPAA", "ISO27001"}
if v.upper() not in allowed:
raise ValueError(f"Unsupported compliance tier: {v}. Must be one of {allowed}.")
return v.upper()
@dataclass
class EnterpriseDeps:
tenant_id: str
tam_channel: str
ticket_id: str
provisioning_agent = Agent(
"anthropic:claude-sonnet-5-5",
deps_type=EnterpriseDeps,
output_type=SandboxProvisionSpec,
retries={"output": 2}, # unnamed budgets keep the default of 1
)
@provisioning_agent.output_validator
async def check_entitlements(
ctx: RunContext[EnterpriseDeps], spec: SandboxProvisionSpec
) -> SandboxProvisionSpec:
if spec.compliance_tier == "HIPAA" and spec.region == "ap-south-1":
# Asks the model to try again. If the budget runs out,
# the run raises UnexpectedModelBehavior.
raise ModelRetry(
"HIPAA workloads in ap-south-1 require explicit TAM architectural sign-off."
)
return spec
async def run_with_tam_fallback(
prompt: str, deps: EnterpriseDeps
) -> SandboxProvisionSpec | None:
with capture_run_messages() as messages:
try:
result = await provisioning_agent.run(prompt, deps=deps)
return result.output
except UnexpectedModelBehavior as exc:
await dispatch_tam_claim_card( # your own function
channel=deps.tam_channel,
ticket_id=deps.ticket_id,
tenant_id=deps.tenant_id,
raw_request=prompt,
failure_reason=str(exc),
transcript=messages,
)
return None
For approvals at the tool-call level, Pydantic AI has a built-in mechanism. A tool can raise ApprovalRequired or CallDeferred. The run then ends with a DeferredToolRequests output instead of an error. Your handler can collect a human decision and continue the run. Those two exceptions are control flow, not failures, and they are not retried. Use them when “ask a person before running this tool” is the normal path rather than an exceptional one.
Anatomy of an effective TAM claim card
Dumping a stack trace into a channel causes alert fatigue. A good claim card follows four principles:
- Single-owner claim. Several TAMs may watch an account channel. The first button should be Claim & Lock, which updates the card to show who owns it.
-
A structured diff. Show the fields that parsed (
tenant_id,node_count: 16) next to the constraint that tripped (compliance_tier: HIPAAwithregion: ap-south-1). Link or attach the captured transcript for depth. -
One-click patching. Let the TAM override the tripped field in a modal and push the corrected
SandboxProvisionSpecback into the downstream queue. Re-validate it with the same schema first, and skip the LLM when the fix is deterministic. -
A feedback loop. Log each
(prompt, corrected_spec)pair into an evaluation dataset so the same edge case stops tripping the agent.
Architectural Best Practices
When you add human-in-the-loop interceptions across these protocols, a few rules matter more than the rest:
-
Make every resume idempotent. Slack retries deliveries that aren’t acknowledged with a
2xxwithin about three seconds, and users double-click. Bind each card to a single-useinterception_idand use an atomic compare-and-swap transition fromPENDING_HUMANtoRESOLVED. A second click should become a no-op. - Put TTLs and escalation ladders on every card. Humans go offline. Choose timeouts per workflow (minutes for a live negotiation, hours for a TAM edge case). When one expires, escalate to a secondary channel and tell the waiting peer something explicit. In A2A that means a status update or a rejection, not a silently dropped socket.
-
Verify every inbound action. For Slack, check the
X-Slack-Signatureheader. It isv0=followed by an HMAC-SHA256 hex digest ofv0:{timestamp}:{raw body}under your signing secret. Compare in constant time against the raw bytes, and reject timestamps more than five minutes from your clock. For Teams, validate the bot request’s JWT. In both cases, check the clicking user’s role against the required approval tier before changing agent state. - Keep secrets out of buttons. Pass opaque IDs and look up details server-side.
- Preserve conversational continuity. When a human resolves an interrupt, add a short system note to the agent’s context, for example “Deal Desk approved a 32% discount on condition of 24-month upfront billing.” Without it, the resumed agent may re-trigger the same guardrail or invent a reason for its changed state.
- Match the control to the regulation. Under the EU AI Act, human oversight (Article 14) is a requirement for high-risk systems. The Digital Omnibus on AI, published in the EU Official Journal in July 2026, moved the application date for standalone high-risk systems to 2 December 2027, and for those embedded in regulated products to 2 August 2028. Most deal-desk or sandbox-provisioning agents are probably not high-risk, but your use case determines that. Treat the interception log as evidence you may need.
Conclusion
Autonomous agents need an explicit place for human judgment, and the protocols do not provide one. A2A gives you input-required and auth-required. AG-UI gives you typed state and error events. AP2 gives you signed authorization. x402 gives you a payment handshake you can gate. Pydantic AI gives you validated outputs and deferred approvals. A thin interception layer ties these together, and its job is to notice a pause, preserve state, ask the right person in the right tool, and resume exactly once.
Sources and Further Reading
- A2A protocol: a2a-protocol.org and the Linux Foundation’s A2A project announcement (23 June 2025)
- AG-UI: docs.ag-ui.com and its transports specification
- AP2: ap2-protocol.org, Google’s AP2 announcement and FIDO Alliance donation post
- x402: Linux Foundation x402 Foundation launch and Coinbase’s x402 flow documentation
- Pydantic AI: retries and output documentation
- Slack: Verifying requests from Slack
- Microsoft: Universal Actions for Adaptive Cards and Bot Framework resources and support notice
- EU AI Act: Digital Omnibus on AI publication summary
Originally published at https://instachime.com/blog/next-gen-agent-protocols-governance-interceptions-designing-human-in-the-loop-architecture-for-enterprise-ai
來源:DEV Community · dev.to