hitl-handoff 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hitl_handoff-0.2.0/.github/workflows/ci.yml +58 -0
- hitl_handoff-0.2.0/.gitignore +9 -0
- hitl_handoff-0.2.0/CHANGELOG.md +60 -0
- hitl_handoff-0.2.0/LICENSE +21 -0
- hitl_handoff-0.2.0/PKG-INFO +245 -0
- hitl_handoff-0.2.0/README.md +219 -0
- hitl_handoff-0.2.0/SECURITY.md +27 -0
- hitl_handoff-0.2.0/docs/gotchas.md +30 -0
- hitl_handoff-0.2.0/docs/implementation_details.md +53 -0
- hitl_handoff-0.2.0/docs/mental_model.md +33 -0
- hitl_handoff-0.2.0/docs/quick_reference.md +59 -0
- hitl_handoff-0.2.0/examples/agent_handoff.py +143 -0
- hitl_handoff-0.2.0/examples/transfer.py +72 -0
- hitl_handoff-0.2.0/pyproject.toml +63 -0
- hitl_handoff-0.2.0/src/hitl_handoff/__init__.py +56 -0
- hitl_handoff-0.2.0/src/hitl_handoff/action.py +350 -0
- hitl_handoff-0.2.0/src/hitl_handoff/approval.py +281 -0
- hitl_handoff-0.2.0/src/hitl_handoff/exceptions.py +21 -0
- hitl_handoff-0.2.0/src/hitl_handoff/fingerprint.py +82 -0
- hitl_handoff-0.2.0/src/hitl_handoff/guard.py +84 -0
- hitl_handoff-0.2.0/src/hitl_handoff/models.py +98 -0
- hitl_handoff-0.2.0/src/hitl_handoff/py.typed +0 -0
- hitl_handoff-0.2.0/src/hitl_handoff/status.py +34 -0
- hitl_handoff-0.2.0/src/hitl_handoff/stores/__init__.py +1 -0
- hitl_handoff-0.2.0/src/hitl_handoff/stores/base.py +52 -0
- hitl_handoff-0.2.0/src/hitl_handoff/stores/memory.py +55 -0
- hitl_handoff-0.2.0/src/hitl_handoff/validation.py +45 -0
- hitl_handoff-0.2.0/tests/test_approval.py +180 -0
- hitl_handoff-0.2.0/tests/test_fingerprint.py +99 -0
- hitl_handoff-0.2.0/tests/test_guard.py +322 -0
- hitl_handoff-0.2.0/tests/test_single_use.py +316 -0
- hitl_handoff-0.2.0/uv.lock +599 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
name: ci
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
push:
|
|
5
|
+
branches: [main]
|
|
6
|
+
pull_request:
|
|
7
|
+
|
|
8
|
+
jobs:
|
|
9
|
+
test:
|
|
10
|
+
runs-on: ubuntu-latest
|
|
11
|
+
strategy:
|
|
12
|
+
matrix:
|
|
13
|
+
python: ["3.11", "3.12", "3.13"]
|
|
14
|
+
steps:
|
|
15
|
+
- uses: actions/checkout@v4
|
|
16
|
+
- uses: astral-sh/setup-uv@v5
|
|
17
|
+
with:
|
|
18
|
+
python-version: ${{ matrix.python }}
|
|
19
|
+
- run: uv sync --extra dev
|
|
20
|
+
- run: uv run ruff check .
|
|
21
|
+
- run: uv run mypy
|
|
22
|
+
- run: uv run pytest
|
|
23
|
+
|
|
24
|
+
build:
|
|
25
|
+
runs-on: ubuntu-latest
|
|
26
|
+
steps:
|
|
27
|
+
- uses: actions/checkout@v4
|
|
28
|
+
- uses: astral-sh/setup-uv@v5
|
|
29
|
+
with:
|
|
30
|
+
python-version: "3.12"
|
|
31
|
+
- run: uv sync --extra dev
|
|
32
|
+
- run: uv run python -m build
|
|
33
|
+
- run: uv pip install --python .venv/bin/python dist/*.whl
|
|
34
|
+
- name: smoke test installed wheel
|
|
35
|
+
run: |
|
|
36
|
+
.venv/bin/python - <<'EOF'
|
|
37
|
+
import asyncio
|
|
38
|
+
from pydantic import BaseModel
|
|
39
|
+
from hitl_handoff import guard, GuardStatus
|
|
40
|
+
|
|
41
|
+
class Req(BaseModel):
|
|
42
|
+
x: int
|
|
43
|
+
|
|
44
|
+
async def fn(r: Req) -> str:
|
|
45
|
+
return "ok"
|
|
46
|
+
|
|
47
|
+
async def main() -> None:
|
|
48
|
+
action = guard(schema=Req, approval=False)(fn)
|
|
49
|
+
out = await action.execute({"x": 1})
|
|
50
|
+
assert out.status == GuardStatus.EXECUTED
|
|
51
|
+
print("wheel smoke test OK")
|
|
52
|
+
|
|
53
|
+
asyncio.run(main())
|
|
54
|
+
EOF
|
|
55
|
+
- uses: actions/upload-artifact@v4
|
|
56
|
+
with:
|
|
57
|
+
name: dist
|
|
58
|
+
path: dist/
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
All notable changes to this project will be documented in this file.
|
|
4
|
+
|
|
5
|
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
+
and this project adheres to [Semantic Versioning](https://semver.org/).
|
|
7
|
+
|
|
8
|
+
## [0.2.0] - 2026-11-20
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
|
|
12
|
+
- **Single-use approvals.** Approval records now have a full lifecycle:
|
|
13
|
+
`PENDING → APPROVED → EXECUTING → CONSUMED` on success, or
|
|
14
|
+
`EXECUTING → EXECUTION_FAILED` when the protected function raises. Both
|
|
15
|
+
`CONSUMED` and `EXECUTION_FAILED` are terminal — an approval can never
|
|
16
|
+
authorize execution twice.
|
|
17
|
+
- **Atomic claiming.** `ApprovalStore.claim(approval_id, expected=..., new=...)`
|
|
18
|
+
is a compare-and-set transition. Only the caller that flips
|
|
19
|
+
`APPROVED → EXECUTING` invokes the protected function, so concurrent
|
|
20
|
+
`execute()` calls can never double-execute. `InMemoryApprovalStore`
|
|
21
|
+
implements it under an `asyncio.Lock`; distributed stores (Redis, DB)
|
|
22
|
+
should implement it atomically server-side.
|
|
23
|
+
- **`ApprovalStatus` is now a `StrEnum`** with `PENDING`, `APPROVED`,
|
|
24
|
+
`REJECTED`, `EXPIRED`, `EXECUTING`, `CONSUMED`, `EXECUTION_FAILED`.
|
|
25
|
+
- **Safe default TTL.** Approvals expire after `DEFAULT_APPROVAL_TTL`
|
|
26
|
+
(5 minutes) unless overridden via `@guard(..., ttl=timedelta(...))`.
|
|
27
|
+
Non-expiring approvals require explicit opt-in: `ttl=NEVER_EXPIRE`.
|
|
28
|
+
- **Execution context binding.** `GuardContext(user_id, session_id,
|
|
29
|
+
tenant_id, correlation_id)` can be passed to `prepare()`/`execute()`;
|
|
30
|
+
the context is stored on the approval and verified again at execution.
|
|
31
|
+
- **Richer `ApprovalRecord`**: `fingerprint_version`, `context`,
|
|
32
|
+
`consumed_at`, `approved_by`, `rejected_by` audit fields.
|
|
33
|
+
- **`FINGERPRINT_VERSION = "v1"`** recorded on every approval so future
|
|
34
|
+
canonicalization changes stay unambiguous.
|
|
35
|
+
- `approve()`/`reject()` now return the updated `ApprovalRecord` and accept
|
|
36
|
+
optional `approved_by`/`rejected_by` actor labels.
|
|
37
|
+
- `GuardedAction.approvals.claim(...)` exposed for advanced use.
|
|
38
|
+
|
|
39
|
+
### Changed
|
|
40
|
+
|
|
41
|
+
- `execute()` verifies, in order: payload validity → approval exists →
|
|
42
|
+
action match → status → expiration → fingerprint version → payload
|
|
43
|
+
fingerprint → context → atomic claim → invoke.
|
|
44
|
+
- Exceptions raised by the protected function propagate unchanged; the
|
|
45
|
+
approval is marked `EXECUTION_FAILED` and is NOT reusable (no automatic
|
|
46
|
+
retry — the destination may not be idempotent).
|
|
47
|
+
- `ApprovalManager.request()`/`approve()`/`reject()` signatures extended
|
|
48
|
+
(backward compatible).
|
|
49
|
+
|
|
50
|
+
### Removed
|
|
51
|
+
|
|
52
|
+
- `GuardStatus.APPROVED` — it was never returned by `execute()` and is not
|
|
53
|
+
part of the actual result lifecycle.
|
|
54
|
+
|
|
55
|
+
### Security
|
|
56
|
+
|
|
57
|
+
- Replay protection: a spent or failed approval returns
|
|
58
|
+
`APPROVAL_INVALID` on any subsequent `execute()`.
|
|
59
|
+
- Context binding prevents an approval granted for one user/session from
|
|
60
|
+
being executed under another.
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 hitl-handoff contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: hitl-handoff
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Deterministic approval gate for sensitive AI-agent actions and agent-to-agent handoffs
|
|
5
|
+
Project-URL: Homepage, https://github.com/hitl-handoff/hitl-handoff
|
|
6
|
+
Author: hitl-handoff contributors
|
|
7
|
+
License: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: a2a,ai-agents,approval,guard,hitl,pydantic
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
17
|
+
Requires-Python: >=3.11
|
|
18
|
+
Requires-Dist: pydantic<3,>=2
|
|
19
|
+
Provides-Extra: dev
|
|
20
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
21
|
+
Requires-Dist: mypy>=1.13; extra == 'dev'
|
|
22
|
+
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
|
|
23
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
24
|
+
Requires-Dist: ruff>=0.8; extra == 'dev'
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
# hitl-handoff
|
|
28
|
+
|
|
29
|
+
Deterministic approval gate for sensitive AI-agent actions and agent-to-agent (A2A) handoffs.
|
|
30
|
+
|
|
31
|
+
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.**
|
|
32
|
+
|
|
33
|
+
It is framework-neutral. It is not an agent framework, not an A2A implementation, not an LLM client, and not an idempotency layer.
|
|
34
|
+
|
|
35
|
+
## The problem
|
|
36
|
+
|
|
37
|
+
```
|
|
38
|
+
User → Source Agent → Cancel Order → A2A → Order Agent
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
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.
|
|
42
|
+
|
|
43
|
+
hitl-handoff sits between parameter collection and execution:
|
|
44
|
+
|
|
45
|
+
```
|
|
46
|
+
User → Source Agent → HANDOFF GUARD → A2A → Destination Agent
|
|
47
|
+
├── validate schema
|
|
48
|
+
├── detect missing input
|
|
49
|
+
├── determine approval requirement
|
|
50
|
+
├── request approval
|
|
51
|
+
├── bind approval to exact payload fingerprint + context
|
|
52
|
+
├── verify approval at execution time
|
|
53
|
+
└── consume the approval (single-use)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Core guarantees
|
|
57
|
+
|
|
58
|
+
1. Required input is present and valid (Pydantic v2, structured errors — no LLM validation).
|
|
59
|
+
2. The action cannot execute before required human approval.
|
|
60
|
+
3. Approval is bound to the **exact payload** via canonical serialization + SHA-256 (`FINGERPRINT_VERSION = "v1"`).
|
|
61
|
+
4. If the payload changes after approval, execution is blocked and new approval is required.
|
|
62
|
+
5. An approval for action A never authorizes action B.
|
|
63
|
+
6. An approval can be bound to an execution **context** (user/session/tenant/correlation id) that must match at execution time.
|
|
64
|
+
7. Approvals **expire** — default TTL is 5 minutes (`DEFAULT_APPROVAL_TTL`).
|
|
65
|
+
8. An approval authorizes execution **exactly once**, enforced by an atomic `APPROVED → EXECUTING` claim — safe under `asyncio.gather` concurrency.
|
|
66
|
+
9. All checks re-run immediately before the protected function is invoked — `prepare()` results are never trusted.
|
|
67
|
+
|
|
68
|
+
## Quick start
|
|
69
|
+
|
|
70
|
+
```python
|
|
71
|
+
from pydantic import BaseModel, ConfigDict
|
|
72
|
+
from hitl_handoff import GuardContext, guard
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class CancelRequest(BaseModel):
|
|
76
|
+
# Recommended for security-sensitive actions: forbid unexpected fields
|
|
77
|
+
# so LLM- or caller-generated extras can't slip through silently.
|
|
78
|
+
model_config = ConfigDict(extra="forbid")
|
|
79
|
+
|
|
80
|
+
order_id: str
|
|
81
|
+
item_ids: list[str]
|
|
82
|
+
reason: str
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
@guard(schema=CancelRequest, approval=True)
|
|
86
|
+
async def cancel_items(request: CancelRequest):
|
|
87
|
+
# May call an A2A agent, MCP tool, HTTP API, database — anything async.
|
|
88
|
+
return await destination_agent.send(request)
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
> **Strict schemas:** for security-sensitive actions, always set
|
|
92
|
+
> `model_config = ConfigDict(extra="forbid")` on your payload model. Without
|
|
93
|
+
> it, Pydantic silently ignores unexpected fields — which means a mutated or
|
|
94
|
+
> hallucinated payload could carry smuggled data that never reaches the
|
|
95
|
+
> fingerprinted model. `extra="forbid"` turns those into validation errors.
|
|
96
|
+
> This is a per-schema decision; hitl-handoff deliberately does not force it.
|
|
97
|
+
|
|
98
|
+
### The complete host flow
|
|
99
|
+
|
|
100
|
+
The host application drives the lifecycle. hitl-handoff never talks to a UI.
|
|
101
|
+
|
|
102
|
+
```python
|
|
103
|
+
context = GuardContext(user_id=current_user.id, session_id=session.id)
|
|
104
|
+
|
|
105
|
+
# 1. Prepare — validate and (if needed) open an approval request.
|
|
106
|
+
prepared = await cancel_items.prepare(payload, context=context)
|
|
107
|
+
|
|
108
|
+
if prepared.status == GuardStatus.INPUT_REQUIRED:
|
|
109
|
+
# Ask the user / agent to fix missing_fields and invalid_fields, then retry.
|
|
110
|
+
...
|
|
111
|
+
|
|
112
|
+
if prepared.status == GuardStatus.APPROVAL_REQUIRED:
|
|
113
|
+
req = prepared.approval_request
|
|
114
|
+
# 2. Show req (action, payload hash, expiry, context) in your HITL UI.
|
|
115
|
+
human_decision = await show_approval_dialog(req)
|
|
116
|
+
|
|
117
|
+
if human_decision == "approve":
|
|
118
|
+
# 3. Record the human's decision. Optionally pass approved_by=...
|
|
119
|
+
await cancel_items.approve(req.approval_id, approved_by=human.id)
|
|
120
|
+
else:
|
|
121
|
+
await cancel_items.reject(req.approval_id, rejected_by=human.id)
|
|
122
|
+
return
|
|
123
|
+
|
|
124
|
+
# 4. Execute — everything is re-validated and re-verified against the CURRENT
|
|
125
|
+
# payload; the approval is atomically claimed and consumed.
|
|
126
|
+
result = await cancel_items.execute(payload, approval_id=req.approval_id,
|
|
127
|
+
context=context)
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
`execute` returns an `ExecuteResult`:
|
|
131
|
+
|
|
132
|
+
- `EXECUTED` → `result.value` is the protected function's return value.
|
|
133
|
+
- `INPUT_REQUIRED` → payload no longer validates; fix and `prepare` again.
|
|
134
|
+
- `APPROVAL_REQUIRED` → no/insufficient approval (missing id, still pending).
|
|
135
|
+
- `APPROVAL_INVALID` → unknown id, wrong action, payload/context mismatch,
|
|
136
|
+
fingerprint-version mismatch, or an already-consumed/failed approval.
|
|
137
|
+
- `REJECTED` / `APPROVAL_EXPIRED` → terminal; `prepare` a fresh request.
|
|
138
|
+
|
|
139
|
+
If the protected function itself raises, the **original exception propagates**
|
|
140
|
+
to you and the approval becomes `EXECUTION_FAILED` — it is never retried
|
|
141
|
+
automatically (the destination operation may not be idempotent). To retry
|
|
142
|
+
safely, run `prepare()` again for a fresh approval.
|
|
143
|
+
|
|
144
|
+
### Approval lifetime (TTL)
|
|
145
|
+
|
|
146
|
+
```python
|
|
147
|
+
@guard(schema=CancelRequest, approval=True) # 5 min default
|
|
148
|
+
@guard(schema=CancelRequest, approval=True, ttl=timedelta(minutes=10))
|
|
149
|
+
@guard(schema=CancelRequest, approval=True, ttl=NEVER_EXPIRE) # explicit opt-in
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Approvals never live forever by accident. `NEVER_EXPIRE` must be requested
|
|
153
|
+
deliberately.
|
|
154
|
+
|
|
155
|
+
### Execution context
|
|
156
|
+
|
|
157
|
+
```python
|
|
158
|
+
ctx = GuardContext(user_id="u-1", session_id="s-9", tenant_id="acme")
|
|
159
|
+
prepared = await action.prepare(payload, context=ctx)
|
|
160
|
+
...
|
|
161
|
+
await action.execute(payload, approval_id=aid, context=ctx) # must match
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
The context is stored on the approval record and compared at execution time.
|
|
165
|
+
An approval granted under `user_id="alice"` cannot execute under `"bob"`.
|
|
166
|
+
Context is a *binding* mechanism only — hitl-handoff does not authenticate
|
|
167
|
+
these values; your host application determines the real identity.
|
|
168
|
+
|
|
169
|
+
## Approval lifecycle
|
|
170
|
+
|
|
171
|
+
```
|
|
172
|
+
PENDING → APPROVED → EXECUTING → CONSUMED (success)
|
|
173
|
+
EXECUTING → EXECUTION_FAILED (exception)
|
|
174
|
+
PENDING → REJECTED
|
|
175
|
+
PENDING → EXPIRED (lazy, when expires_at elapses)
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
`ApprovalStatus` is a `StrEnum`. `CONSUMED`, `EXECUTION_FAILED`, `REJECTED`,
|
|
179
|
+
and `EXPIRED` are all terminal. `approve()`/`reject()` atomically transition
|
|
180
|
+
`PENDING` and return the updated `ApprovalRecord` (with optional
|
|
181
|
+
`approved_by`/`rejected_by` audit labels).
|
|
182
|
+
|
|
183
|
+
`GuardStatus` (prepare/execute results): `READY`, `INPUT_REQUIRED`,
|
|
184
|
+
`APPROVAL_REQUIRED`, `REJECTED`, `APPROVAL_EXPIRED`, `APPROVAL_INVALID`,
|
|
185
|
+
`EXECUTED`.
|
|
186
|
+
|
|
187
|
+
## Fingerprinting
|
|
188
|
+
|
|
189
|
+
Payloads are canonicalized (Pydantic models dumped, `datetime`/`UUID`/
|
|
190
|
+
`Decimal`/`Enum` normalized, dict keys sorted) then SHA-256 hashed and tagged
|
|
191
|
+
with `FINGERPRINT_VERSION`.
|
|
192
|
+
|
|
193
|
+
- Dictionary key order does **not** affect the fingerprint.
|
|
194
|
+
- List order **does** affect the fingerprint.
|
|
195
|
+
- Nested changes produce a different fingerprint.
|
|
196
|
+
|
|
197
|
+
## Approval storage
|
|
198
|
+
|
|
199
|
+
`ApprovalStore` is a minimal async Protocol: `save`, `get`, and — critically —
|
|
200
|
+
`claim(approval_id, expected=..., new=..., patch=...)`, an atomic
|
|
201
|
+
compare-and-set that makes single-use execution safe across concurrent
|
|
202
|
+
callers. Distributed implementations (Redis `WATCH`/Lua, SQL
|
|
203
|
+
`UPDATE ... WHERE status = ...`) must provide the same atomicity.
|
|
204
|
+
|
|
205
|
+
v0.2 ships `InMemoryApprovalStore` (asyncio-lock safe within one process).
|
|
206
|
+
**It is NOT appropriate for distributed/multi-pod production deployments** —
|
|
207
|
+
records are not shared across processes and are lost on restart. For
|
|
208
|
+
production, implement `ApprovalStore` on Redis or a database.
|
|
209
|
+
|
|
210
|
+
## What this package does NOT do
|
|
211
|
+
|
|
212
|
+
hitl-handoff provides:
|
|
213
|
+
|
|
214
|
+
- payload validation (Pydantic v2, structured errors)
|
|
215
|
+
- approval gating (human-in-the-loop decisions surfaced as data)
|
|
216
|
+
- payload-to-approval binding (canonical fingerprint + optional context)
|
|
217
|
+
- execution-time revalidation (prepare results are never trusted)
|
|
218
|
+
- replay protection (single-use, atomic claim; TTL expiry)
|
|
219
|
+
|
|
220
|
+
It does **NOT** provide:
|
|
221
|
+
|
|
222
|
+
- **Authentication** — it never verifies who the caller or approver is.
|
|
223
|
+
- **Authorization of the human user** — your host decides who may approve.
|
|
224
|
+
- **Approval UI** — the host connects `approve()`/`reject()`/`execute()` to
|
|
225
|
+
its own HITL mechanism.
|
|
226
|
+
- **A2A transport** — it gates *whether* an action runs, not how it is sent.
|
|
227
|
+
- **Agent framework features** — no LLM clients, no agent loops, no tools.
|
|
228
|
+
- **Destination-operation idempotency** — if the network fails after the
|
|
229
|
+
protected function ran, exactly-once downstream is a separate problem.
|
|
230
|
+
- **Durable production storage** — unless you supply a durable
|
|
231
|
+
`ApprovalStore`, approvals live in memory only.
|
|
232
|
+
|
|
233
|
+
## Development
|
|
234
|
+
|
|
235
|
+
```bash
|
|
236
|
+
uv sync --extra dev
|
|
237
|
+
uv run pytest
|
|
238
|
+
uv run ruff check .
|
|
239
|
+
uv run mypy
|
|
240
|
+
uv run python -m build
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
## License
|
|
244
|
+
|
|
245
|
+
MIT
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
# hitl-handoff
|
|
2
|
+
|
|
3
|
+
Deterministic approval gate for sensitive AI-agent actions and agent-to-agent (A2A) handoffs.
|
|
4
|
+
|
|
5
|
+
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.**
|
|
6
|
+
|
|
7
|
+
It is framework-neutral. It is not an agent framework, not an A2A implementation, not an LLM client, and not an idempotency layer.
|
|
8
|
+
|
|
9
|
+
## The problem
|
|
10
|
+
|
|
11
|
+
```
|
|
12
|
+
User → Source Agent → Cancel Order → A2A → Order Agent
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
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.
|
|
16
|
+
|
|
17
|
+
hitl-handoff sits between parameter collection and execution:
|
|
18
|
+
|
|
19
|
+
```
|
|
20
|
+
User → Source Agent → HANDOFF GUARD → A2A → Destination Agent
|
|
21
|
+
├── validate schema
|
|
22
|
+
├── detect missing input
|
|
23
|
+
├── determine approval requirement
|
|
24
|
+
├── request approval
|
|
25
|
+
├── bind approval to exact payload fingerprint + context
|
|
26
|
+
├── verify approval at execution time
|
|
27
|
+
└── consume the approval (single-use)
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Core guarantees
|
|
31
|
+
|
|
32
|
+
1. Required input is present and valid (Pydantic v2, structured errors — no LLM validation).
|
|
33
|
+
2. The action cannot execute before required human approval.
|
|
34
|
+
3. Approval is bound to the **exact payload** via canonical serialization + SHA-256 (`FINGERPRINT_VERSION = "v1"`).
|
|
35
|
+
4. If the payload changes after approval, execution is blocked and new approval is required.
|
|
36
|
+
5. An approval for action A never authorizes action B.
|
|
37
|
+
6. An approval can be bound to an execution **context** (user/session/tenant/correlation id) that must match at execution time.
|
|
38
|
+
7. Approvals **expire** — default TTL is 5 minutes (`DEFAULT_APPROVAL_TTL`).
|
|
39
|
+
8. An approval authorizes execution **exactly once**, enforced by an atomic `APPROVED → EXECUTING` claim — safe under `asyncio.gather` concurrency.
|
|
40
|
+
9. All checks re-run immediately before the protected function is invoked — `prepare()` results are never trusted.
|
|
41
|
+
|
|
42
|
+
## Quick start
|
|
43
|
+
|
|
44
|
+
```python
|
|
45
|
+
from pydantic import BaseModel, ConfigDict
|
|
46
|
+
from hitl_handoff import GuardContext, guard
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class CancelRequest(BaseModel):
|
|
50
|
+
# Recommended for security-sensitive actions: forbid unexpected fields
|
|
51
|
+
# so LLM- or caller-generated extras can't slip through silently.
|
|
52
|
+
model_config = ConfigDict(extra="forbid")
|
|
53
|
+
|
|
54
|
+
order_id: str
|
|
55
|
+
item_ids: list[str]
|
|
56
|
+
reason: str
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
@guard(schema=CancelRequest, approval=True)
|
|
60
|
+
async def cancel_items(request: CancelRequest):
|
|
61
|
+
# May call an A2A agent, MCP tool, HTTP API, database — anything async.
|
|
62
|
+
return await destination_agent.send(request)
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
> **Strict schemas:** for security-sensitive actions, always set
|
|
66
|
+
> `model_config = ConfigDict(extra="forbid")` on your payload model. Without
|
|
67
|
+
> it, Pydantic silently ignores unexpected fields — which means a mutated or
|
|
68
|
+
> hallucinated payload could carry smuggled data that never reaches the
|
|
69
|
+
> fingerprinted model. `extra="forbid"` turns those into validation errors.
|
|
70
|
+
> This is a per-schema decision; hitl-handoff deliberately does not force it.
|
|
71
|
+
|
|
72
|
+
### The complete host flow
|
|
73
|
+
|
|
74
|
+
The host application drives the lifecycle. hitl-handoff never talks to a UI.
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
context = GuardContext(user_id=current_user.id, session_id=session.id)
|
|
78
|
+
|
|
79
|
+
# 1. Prepare — validate and (if needed) open an approval request.
|
|
80
|
+
prepared = await cancel_items.prepare(payload, context=context)
|
|
81
|
+
|
|
82
|
+
if prepared.status == GuardStatus.INPUT_REQUIRED:
|
|
83
|
+
# Ask the user / agent to fix missing_fields and invalid_fields, then retry.
|
|
84
|
+
...
|
|
85
|
+
|
|
86
|
+
if prepared.status == GuardStatus.APPROVAL_REQUIRED:
|
|
87
|
+
req = prepared.approval_request
|
|
88
|
+
# 2. Show req (action, payload hash, expiry, context) in your HITL UI.
|
|
89
|
+
human_decision = await show_approval_dialog(req)
|
|
90
|
+
|
|
91
|
+
if human_decision == "approve":
|
|
92
|
+
# 3. Record the human's decision. Optionally pass approved_by=...
|
|
93
|
+
await cancel_items.approve(req.approval_id, approved_by=human.id)
|
|
94
|
+
else:
|
|
95
|
+
await cancel_items.reject(req.approval_id, rejected_by=human.id)
|
|
96
|
+
return
|
|
97
|
+
|
|
98
|
+
# 4. Execute — everything is re-validated and re-verified against the CURRENT
|
|
99
|
+
# payload; the approval is atomically claimed and consumed.
|
|
100
|
+
result = await cancel_items.execute(payload, approval_id=req.approval_id,
|
|
101
|
+
context=context)
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
`execute` returns an `ExecuteResult`:
|
|
105
|
+
|
|
106
|
+
- `EXECUTED` → `result.value` is the protected function's return value.
|
|
107
|
+
- `INPUT_REQUIRED` → payload no longer validates; fix and `prepare` again.
|
|
108
|
+
- `APPROVAL_REQUIRED` → no/insufficient approval (missing id, still pending).
|
|
109
|
+
- `APPROVAL_INVALID` → unknown id, wrong action, payload/context mismatch,
|
|
110
|
+
fingerprint-version mismatch, or an already-consumed/failed approval.
|
|
111
|
+
- `REJECTED` / `APPROVAL_EXPIRED` → terminal; `prepare` a fresh request.
|
|
112
|
+
|
|
113
|
+
If the protected function itself raises, the **original exception propagates**
|
|
114
|
+
to you and the approval becomes `EXECUTION_FAILED` — it is never retried
|
|
115
|
+
automatically (the destination operation may not be idempotent). To retry
|
|
116
|
+
safely, run `prepare()` again for a fresh approval.
|
|
117
|
+
|
|
118
|
+
### Approval lifetime (TTL)
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
@guard(schema=CancelRequest, approval=True) # 5 min default
|
|
122
|
+
@guard(schema=CancelRequest, approval=True, ttl=timedelta(minutes=10))
|
|
123
|
+
@guard(schema=CancelRequest, approval=True, ttl=NEVER_EXPIRE) # explicit opt-in
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
Approvals never live forever by accident. `NEVER_EXPIRE` must be requested
|
|
127
|
+
deliberately.
|
|
128
|
+
|
|
129
|
+
### Execution context
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
ctx = GuardContext(user_id="u-1", session_id="s-9", tenant_id="acme")
|
|
133
|
+
prepared = await action.prepare(payload, context=ctx)
|
|
134
|
+
...
|
|
135
|
+
await action.execute(payload, approval_id=aid, context=ctx) # must match
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
The context is stored on the approval record and compared at execution time.
|
|
139
|
+
An approval granted under `user_id="alice"` cannot execute under `"bob"`.
|
|
140
|
+
Context is a *binding* mechanism only — hitl-handoff does not authenticate
|
|
141
|
+
these values; your host application determines the real identity.
|
|
142
|
+
|
|
143
|
+
## Approval lifecycle
|
|
144
|
+
|
|
145
|
+
```
|
|
146
|
+
PENDING → APPROVED → EXECUTING → CONSUMED (success)
|
|
147
|
+
EXECUTING → EXECUTION_FAILED (exception)
|
|
148
|
+
PENDING → REJECTED
|
|
149
|
+
PENDING → EXPIRED (lazy, when expires_at elapses)
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
`ApprovalStatus` is a `StrEnum`. `CONSUMED`, `EXECUTION_FAILED`, `REJECTED`,
|
|
153
|
+
and `EXPIRED` are all terminal. `approve()`/`reject()` atomically transition
|
|
154
|
+
`PENDING` and return the updated `ApprovalRecord` (with optional
|
|
155
|
+
`approved_by`/`rejected_by` audit labels).
|
|
156
|
+
|
|
157
|
+
`GuardStatus` (prepare/execute results): `READY`, `INPUT_REQUIRED`,
|
|
158
|
+
`APPROVAL_REQUIRED`, `REJECTED`, `APPROVAL_EXPIRED`, `APPROVAL_INVALID`,
|
|
159
|
+
`EXECUTED`.
|
|
160
|
+
|
|
161
|
+
## Fingerprinting
|
|
162
|
+
|
|
163
|
+
Payloads are canonicalized (Pydantic models dumped, `datetime`/`UUID`/
|
|
164
|
+
`Decimal`/`Enum` normalized, dict keys sorted) then SHA-256 hashed and tagged
|
|
165
|
+
with `FINGERPRINT_VERSION`.
|
|
166
|
+
|
|
167
|
+
- Dictionary key order does **not** affect the fingerprint.
|
|
168
|
+
- List order **does** affect the fingerprint.
|
|
169
|
+
- Nested changes produce a different fingerprint.
|
|
170
|
+
|
|
171
|
+
## Approval storage
|
|
172
|
+
|
|
173
|
+
`ApprovalStore` is a minimal async Protocol: `save`, `get`, and — critically —
|
|
174
|
+
`claim(approval_id, expected=..., new=..., patch=...)`, an atomic
|
|
175
|
+
compare-and-set that makes single-use execution safe across concurrent
|
|
176
|
+
callers. Distributed implementations (Redis `WATCH`/Lua, SQL
|
|
177
|
+
`UPDATE ... WHERE status = ...`) must provide the same atomicity.
|
|
178
|
+
|
|
179
|
+
v0.2 ships `InMemoryApprovalStore` (asyncio-lock safe within one process).
|
|
180
|
+
**It is NOT appropriate for distributed/multi-pod production deployments** —
|
|
181
|
+
records are not shared across processes and are lost on restart. For
|
|
182
|
+
production, implement `ApprovalStore` on Redis or a database.
|
|
183
|
+
|
|
184
|
+
## What this package does NOT do
|
|
185
|
+
|
|
186
|
+
hitl-handoff provides:
|
|
187
|
+
|
|
188
|
+
- payload validation (Pydantic v2, structured errors)
|
|
189
|
+
- approval gating (human-in-the-loop decisions surfaced as data)
|
|
190
|
+
- payload-to-approval binding (canonical fingerprint + optional context)
|
|
191
|
+
- execution-time revalidation (prepare results are never trusted)
|
|
192
|
+
- replay protection (single-use, atomic claim; TTL expiry)
|
|
193
|
+
|
|
194
|
+
It does **NOT** provide:
|
|
195
|
+
|
|
196
|
+
- **Authentication** — it never verifies who the caller or approver is.
|
|
197
|
+
- **Authorization of the human user** — your host decides who may approve.
|
|
198
|
+
- **Approval UI** — the host connects `approve()`/`reject()`/`execute()` to
|
|
199
|
+
its own HITL mechanism.
|
|
200
|
+
- **A2A transport** — it gates *whether* an action runs, not how it is sent.
|
|
201
|
+
- **Agent framework features** — no LLM clients, no agent loops, no tools.
|
|
202
|
+
- **Destination-operation idempotency** — if the network fails after the
|
|
203
|
+
protected function ran, exactly-once downstream is a separate problem.
|
|
204
|
+
- **Durable production storage** — unless you supply a durable
|
|
205
|
+
`ApprovalStore`, approvals live in memory only.
|
|
206
|
+
|
|
207
|
+
## Development
|
|
208
|
+
|
|
209
|
+
```bash
|
|
210
|
+
uv sync --extra dev
|
|
211
|
+
uv run pytest
|
|
212
|
+
uv run ruff check .
|
|
213
|
+
uv run mypy
|
|
214
|
+
uv run python -m build
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
## License
|
|
218
|
+
|
|
219
|
+
MIT
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
# Security Policy
|
|
2
|
+
|
|
3
|
+
## Reporting a vulnerability
|
|
4
|
+
|
|
5
|
+
Please do **not** open a public issue for security vulnerabilities. Report
|
|
6
|
+
them privately to the maintainers via GitHub's private vulnerability
|
|
7
|
+
reporting ("Report a vulnerability" on the repository's Security tab), or
|
|
8
|
+
contact the maintainers directly.
|
|
9
|
+
|
|
10
|
+
We aim to acknowledge reports within 72 hours.
|
|
11
|
+
|
|
12
|
+
## Scope and guarantees
|
|
13
|
+
|
|
14
|
+
hitl-handoff enforces that a protected function executes only when:
|
|
15
|
+
|
|
16
|
+
1. the current payload validates against the configured schema,
|
|
17
|
+
2. when approval is required, a valid, unexpired approval exists for that
|
|
18
|
+
exact action, payload fingerprint, and execution context,
|
|
19
|
+
3. that approval has not been used before (single-use, atomic claim).
|
|
20
|
+
|
|
21
|
+
It does **not** provide authentication, human-authorization decisions,
|
|
22
|
+
approval UI, transport security, or destination-operation idempotency — see
|
|
23
|
+
"What this package does NOT do" in the README. Deployments requiring
|
|
24
|
+
cross-process approval integrity must supply a durable `ApprovalStore`
|
|
25
|
+
implementation (e.g. Redis/Postgres) whose `claim()` is atomic; the bundled
|
|
26
|
+
`InMemoryApprovalStore` is for development, tests, and single-process use
|
|
27
|
+
only.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# Gotchas & Edge Cases
|
|
2
|
+
|
|
3
|
+
- **`EXECUTING` is terminal on crash.** If the process dies between claim and
|
|
4
|
+
completion, the approval stays `EXECUTING` forever — intentionally. There
|
|
5
|
+
is no automatic retry because the destination may not be idempotent; the
|
|
6
|
+
host must `prepare()` a fresh approval.
|
|
7
|
+
- **`EXECUTION_FAILED` is terminal.** The original exception propagates to
|
|
8
|
+
the caller; the approval cannot be reused. Retry = new `prepare()`.
|
|
9
|
+
- **Exception during the post-execute `claim`.** If the store fails while
|
|
10
|
+
marking `CONSUMED`/`EXECUTION_FAILED`, the function already ran — the
|
|
11
|
+
result/exception still propagates. The record may be stuck in
|
|
12
|
+
`EXECUTING`; treat store errors as operational incidents.
|
|
13
|
+
- **`asyncio.CancelledError`** inherits `BaseException`, not `Exception`, so
|
|
14
|
+
a cancelled `execute()` leaves the approval in `EXECUTING` (terminal, not
|
|
15
|
+
reusable). This is deliberate.
|
|
16
|
+
- **Context is strict equality.** `GuardContext(user_id="a")` !=
|
|
17
|
+
`GuardContext(user_id="a", session_id=None)`? — actually equal (defaults
|
|
18
|
+
are `None`). But `GuardContext()` (all-None) != `None`. Pass `None` or a
|
|
19
|
+
fully-populated context consistently.
|
|
20
|
+
- **`InMemoryApprovalStore` is per-process.** The default store is a module
|
|
21
|
+
singleton shared by all `@guard` actions *without* an explicit store —
|
|
22
|
+
approvals are keyed by UUID so actions can't collide, but nothing survives
|
|
23
|
+
restart and nothing is shared across pods.
|
|
24
|
+
- **Lazy expiry only fires for `PENDING`.** An `APPROVED` record past
|
|
25
|
+
`expires_at` is expired by `execute()`'s own check, not by
|
|
26
|
+
`ApprovalManager.get()` — both paths converge on `APPROVAL_EXPIRED`.
|
|
27
|
+
- **`prepare()` with `approval=False` predicate returning False** yields
|
|
28
|
+
`READY` and `execute()` skips all approval checks — including context.
|
|
29
|
+
- **Fingerprint version mismatch** blocks execution even if hashes would
|
|
30
|
+
match — protects against canonicalization drift across upgrades.
|