Skip to main content

hitl-handoff

Deterministic approval gate for sensitive AI-agent actions and agent-to-agent (A2A) handoffs.

hitl-handoff solves one problem: an AI agent must never execute an action whose action + payload + context differs from what a human approved — and an approval can only ever authorize one execution.

It is framework-neutral. It is not an agent framework, not an A2A implementation, not an LLM client, and not an idempotency layer.

The problem

User → Source Agent → Cancel Order → A2A → Order Agent

A source agent collects parameters, asks the user for confirmation, then delegates the action. Without a deterministic gate, the agent can mutate the payload after approval, skip approval entirely, reuse an approval granted for a different action, or execute the same approval twice.

hitl-handoff sits between parameter collection and execution:

User → Source Agent → HANDOFF GUARD → A2A → Destination Agent
                     ├── validate schema
                     ├── detect missing input
                     ├── determine approval requirement
                     ├── request approval
                     ├── bind approval to exact payload fingerprint + context
                     ├── verify approval at execution time
                     └── consume the approval (single-use)

Core guarantees

  1. Required input is present and valid (Pydantic v2, structured errors — no LLM validation).
  2. The action cannot execute before required human approval.
  3. Approval is bound to the exact payload via canonical serialization + SHA-256 (FINGERPRINT_VERSION = "v1").
  4. If the payload changes after approval, execution is blocked and new approval is required.
  5. An approval for action A never authorizes action B.
  6. An approval can be bound to an execution context (user/session/tenant/correlation id) that must match at execution time.
  7. Approvals expire — default TTL is 5 minutes (DEFAULT_APPROVAL_TTL).
  8. An approval authorizes execution exactly once, enforced by an atomic APPROVED → EXECUTING claim — safe under asyncio.gather concurrency.
  9. All checks re-run immediately before the protected function is invoked — prepare() results are never trusted.

Quick start

from pydantic import BaseModel, ConfigDict
from hitl_handoff import GuardContext, guard


class CancelRequest(BaseModel):
    # Recommended for security-sensitive actions: forbid unexpected fields
    # so LLM- or caller-generated extras can't slip through silently.
    model_config = ConfigDict(extra="forbid")

    order_id: str
    item_ids: list[str]
    reason: str


@guard(schema=CancelRequest, approval=True)
async def cancel_items(request: CancelRequest):
    # May call an A2A agent, MCP tool, HTTP API, database — anything async.
    return await destination_agent.send(request)

Strict schemas: for security-sensitive actions, always set model_config = ConfigDict(extra="forbid") on your payload model. Without it, Pydantic silently ignores unexpected fields — which means a mutated or hallucinated payload could carry smuggled data that never reaches the fingerprinted model. extra="forbid" turns those into validation errors. This is a per-schema decision; hitl-handoff deliberately does not force it.

The complete host flow

The host application drives the lifecycle. hitl-handoff never talks to a UI.

context = GuardContext(user_id=current_user.id, session_id=session.id)

# 1. Prepare — validate and (if needed) open an approval request.
prepared = await cancel_items.prepare(payload, context=context)

if prepared.status == GuardStatus.INPUT_REQUIRED:
    # Ask the user / agent to fix missing_fields and invalid_fields, then retry.
    ...

if prepared.status == GuardStatus.APPROVAL_REQUIRED:
    req = prepared.approval_request
    # 2. Show req (action, payload hash, expiry, context) in your HITL UI.
    human_decision = await show_approval_dialog(req)

    if human_decision == "approve":
        # 3. Record the human's decision. Optionally pass approved_by=...
        await cancel_items.approve(req.approval_id, approved_by=human.id)
    else:
        await cancel_items.reject(req.approval_id, rejected_by=human.id)
        return

# 4. Execute — everything is re-validated and re-verified against the CURRENT
#    payload; the approval is atomically claimed and consumed.
result = await cancel_items.execute(payload, approval_id=req.approval_id,
                                    context=context)

execute returns an ExecuteResult:

  • EXECUTED → result.value is the protected function's return value.
  • INPUT_REQUIRED → payload no longer validates; fix and prepare again.
  • APPROVAL_REQUIRED → no/insufficient approval (missing id, still pending).
  • APPROVAL_INVALID → unknown id, wrong action, payload/context mismatch, fingerprint-version mismatch, or an already-consumed/failed approval.
  • REJECTED / APPROVAL_EXPIRED → terminal; prepare a fresh request.

If the protected function itself raises, the original exception propagates to you and the approval becomes EXECUTION_FAILED — it is never retried automatically (the destination operation may not be idempotent). To retry safely, run prepare() again for a fresh approval.

Approval lifetime (TTL)

@guard(schema=CancelRequest, approval=True)                    # 5 min default
@guard(schema=CancelRequest, approval=True, ttl=timedelta(minutes=10))
@guard(schema=CancelRequest, approval=True, ttl=NEVER_EXPIRE)  # explicit opt-in

Approvals never live forever by accident. NEVER_EXPIRE must be requested deliberately.

Execution context

ctx = GuardContext(user_id="u-1", session_id="s-9", tenant_id="acme")
prepared = await action.prepare(payload, context=ctx)
...
await action.execute(payload, approval_id=aid, context=ctx)  # must match

The context is stored on the approval record and compared at execution time. An approval granted under user_id="alice" cannot execute under "bob". Context is a binding mechanism only — hitl-handoff does not authenticate these values; your host application determines the real identity.

Approval lifecycle

PENDING → APPROVED → EXECUTING → CONSUMED          (success)
                      EXECUTING → EXECUTION_FAILED (exception)
PENDING → REJECTED
PENDING → EXPIRED   (lazy, when expires_at elapses)

ApprovalStatus is a StrEnum. CONSUMED, EXECUTION_FAILED, REJECTED, and EXPIRED are all terminal. approve()/reject() atomically transition PENDING and return the updated ApprovalRecord (with optional approved_by/rejected_by audit labels).

GuardStatus (prepare/execute results): READY, INPUT_REQUIRED, APPROVAL_REQUIRED, REJECTED, APPROVAL_EXPIRED, APPROVAL_INVALID, EXECUTED.

Fingerprinting

Payloads are canonicalized (Pydantic models dumped, datetime/UUID/ Decimal/Enum normalized, dict keys sorted) then SHA-256 hashed and tagged with FINGERPRINT_VERSION.

  • Dictionary key order does not affect the fingerprint.
  • List order does affect the fingerprint.
  • Nested changes produce a different fingerprint.

Approval storage

ApprovalStore is a minimal async Protocol: save, get, and — critically — claim(approval_id, expected=..., new=..., patch=...), an atomic compare-and-set that makes single-use execution safe across concurrent callers. Distributed implementations (Redis WATCH/Lua, SQL UPDATE ... WHERE status = ...) must provide the same atomicity.

v0.2 ships InMemoryApprovalStore (asyncio-lock safe within one process). It is NOT appropriate for distributed/multi-pod production deployments — records are not shared across processes and are lost on restart. For production, implement ApprovalStore on Redis or a database.

What this package does NOT do

hitl-handoff provides:

  • payload validation (Pydantic v2, structured errors)
  • approval gating (human-in-the-loop decisions surfaced as data)
  • payload-to-approval binding (canonical fingerprint + optional context)
  • execution-time revalidation (prepare results are never trusted)
  • replay protection (single-use, atomic claim; TTL expiry)

It does NOT provide:

  • Authentication — it never verifies who the caller or approver is.
  • Authorization of the human user — your host decides who may approve.
  • Approval UI — the host connects approve()/reject()/execute() to its own HITL mechanism.
  • A2A transport — it gates whether an action runs, not how it is sent.
  • Agent framework features — no LLM clients, no agent loops, no tools.
  • Destination-operation idempotency — if the network fails after the protected function ran, exactly-once downstream is a separate problem.
  • Durable production storage — unless you supply a durable ApprovalStore, approvals live in memory only.

Development

uv sync --extra dev
uv run pytest
uv run ruff check .
uv run mypy
uv run python -m build

License

MIT

Metadata

Release files for hitl-handoff 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for hitl-handoff 0.2.0
File Size Uploaded Provenance Actions
hitl_handoff-0.2.0.tar.gz 69.2 kB Without provenance Details for hitl_handoff-0.2.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for hitl-handoff 0.2.0
File Interpreter ABI Platform Actions
hitl_handoff-0.2.0-py3-none-any.whl Python 3 none any Details for hitl_handoff-0.2.0-py3-none-any.whl

Total release size: 90.6 kB

Release files / hitl_handoff-0.2.0.tar.gz

Download URL hitl_handoff-0.2.0.tar.gz
Size 69.2 kB
Tags Source
SHA-256 checksum
How to use checksums
6bc30b31b3ff6a63c6cabe628b350dc00b02f9adc67222a1286e00d715443000
BLAKE2b-256 checksum
How to use checksums
5bb49f7256d55b0a04377085aeba8dccda9095430e12c9102554bde86ce05bb2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.24 {"installer":{"name":"uv","version":"0.9.24","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Release files / hitl_handoff-0.2.0-py3-none-any.whl

Download URL hitl_handoff-0.2.0-py3-none-any.whl
Size 21.4 kB
Tags Python 3
SHA-256 checksum
How to use checksums
2557d0e9eedd3a4e11b7a6fbb8f52c321163b772283604a75051d970564450d1
BLAKE2b-256 checksum
How to use checksums
67c82d502f7b18a031d33059a5a2acb15f1a3a251d4c866477d08f9da708f0e9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.9.24 {"installer":{"name":"uv","version":"0.9.24","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}

Security for hitl-handoff 0.2.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page