Metadata-Version: 2.5
Name: hitl-handoff
Version: 0.2.0
Summary: Deterministic approval gate for sensitive AI-agent actions and agent-to-agent handoffs
Project-URL: Homepage, https://github.com/hitl-handoff/hitl-handoff
Author: hitl-handoff contributors
License: MIT
License-File: LICENSE
Keywords: a2a,ai-agents,approval,guard,hitl,pydantic
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.11
Requires-Dist: pydantic<3,>=2
Provides-Extra: dev
Requires-Dist: build>=1.2; extra == 'dev'
Requires-Dist: mypy>=1.13; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.8; extra == 'dev'
Description-Content-Type: text/markdown

# 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

```python
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.

```python
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)

```python
@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

```python
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

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

## License

MIT
