Metadata-Version: 2.5
Name: viewport-hitl
Version: 0.1.1
Summary: Human approval and policy gates before agent side effects: declarative policies, durable approvals, signed channels, hash-chained receipts.
Project-URL: Homepage, https://getviewport.com
Project-URL: Documentation, https://docs.getviewport.com/hitl
Project-URL: Repository, https://github.com/viewportai/hitl
Project-URL: Issues, https://github.com/viewportai/hitl/issues
Author: Viewport
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: agents,ai,approval,claude-agent-sdk,human-in-the-loop,langgraph,openai-agents,policy
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: Pytest
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: pydantic>=2.7
Requires-Dist: viewport-core>=0.1.0
Provides-Extra: claude-agent-sdk
Requires-Dist: claude-agent-sdk>=0.2.189; extra == 'claude-agent-sdk'
Provides-Extra: langgraph
Requires-Dist: langchain>=1.5; extra == 'langgraph'
Requires-Dist: langgraph>=1.2; extra == 'langgraph'
Provides-Extra: openai-agents
Requires-Dist: openai-agents>=0.26; extra == 'openai-agents'
Provides-Extra: otel
Requires-Dist: opentelemetry-api>=1.27; extra == 'otel'
Provides-Extra: postgres
Requires-Dist: psycopg[binary]>=3.2; extra == 'postgres'
Provides-Extra: pydantic-ai
Requires-Dist: pydantic-ai-slim>=2.75; extra == 'pydantic-ai'
Provides-Extra: sign
Requires-Dist: cryptography>=42; extra == 'sign'
Provides-Extra: slack
Requires-Dist: httpx>=0.27; extra == 'slack'
Description-Content-Type: text/markdown

# viewport-hitl

Human approval and policy gates before agent side effects. Declare in YAML what an agent may do alone, what needs a
person, and what it may never do. HITL enforces it at the tool boundary, asks the right people through the right
channel, survives restarts while it waits, binds every approval to the exact arguments that were approved, and writes
a hash-chained receipt for all of it.

Status: beta (v0.1). Python >= 3.11. The TypeScript twin is `@viewportai/hitl`; both pass the same
conformance vectors.

```sh
pip install viewport-hitl   # or: uv add viewport-hitl
```

To build from source, see https://github.com/viewportai/hitl#from-source.

| Extra | Adds |
| --- | --- |
| `slack` | `hitl.slack(...)` (httpx) |
| `postgres` | `hitl.postgres(dsn)` (psycopg 3) |
| `sign` | Ed25519 verification for `hitl.console(...)` reviews (cryptography) |
| `otel` | OpenTelemetry spans (opentelemetry-api) |
| `langgraph`, `claude-agent-sdk`, `openai-agents`, `pydantic-ai` | the framework adapter of the same name |

`hitl.sqlite(path)`, `hitl.webhook(...)`, `hitl.web(...)` and `hitl.terminal()` need no extra.

## Quickstart

Runs with no API key. Save the program below as `quickstart.py` and the policy that follows as `policies/refunds.yaml`, next to it:

<!-- include: examples/python/quickstart/main.py#quickstart -->
```python
from pathlib import Path

from viewportai import hitl

gate = hitl.Gate(Path(__file__).parent / "policies" / "refunds.yaml")


@gate
def issue_refund(order_id: str, amount: float) -> str:
    return f"Refunded ${amount:g} on {order_id}"


print(issue_refund("A-1001", 20))  # policy allows it: runs now

try:
    print(issue_refund("A-1002", 900))  # asks you in the terminal first
except hitl.ActionDenied as denied:
    print(denied.status, denied.message)  # your "no", or no terminal to ask: denied
```

```yaml
# policies/refunds.yaml
rules:
  refunds: { allow: issue_refund }
  negative-refunds:
    deny: issue_refund
    when: { args: { amount: { lt: 0 } } }
    reason: A refund amount cannot be negative
  large-refunds:
    ask: issue_refund
    when: { args: { amount: { gt: 50 } } }
    reason: Refunds over $50 need a human
```

Run it with `python quickstart.py`. With no terminal attached it prints `Refunded $20 on A-1001`, then
`denied No approver or channel is available for "default"`; on a terminal the $900 refund asks you first.

The package installs a `viewport-hitl` command (check policies, explain decisions, verify receipts): `viewport-hitl --help`.

The most restrictive matching rule wins (deny > ask > allow), so a broad allow can never mask a narrow deny. Anything
no rule mentions is denied. Sync functions stay sync, async functions stay async; `issue_refund.tool` is a core `Tool`
for any adapter.

## Production shape

A durable store shares approvals, limits, grants and receipts across processes (`hitl.postgres(dsn)` the same way):

<!-- include: examples/python/durable-settle/main.py#process -->
```python
def process_start() -> hitl.Gate:
    """One process: a fresh gate on the shared SQLite file, with receipts in the same file."""
    # redact_key="store" keeps a development redaction key in the store; production sets VIEWPORT_REDACT_KEY.
    return hitl.Gate(POLICY, store=hitl.sqlite(DB), receipts=True, clock=clock, redact_key="store")


invoice = {"tool": "send_invoice", "args": {"invoice_id": "INV-7"}, "call_id": "call_1"}
key = "workflow-42:step-3"  # your runtime's stable step identity
```

Channels are referenced by name from YAML approvers; their answers arrive through one ASGI app:

<!-- include: examples/python/marketing-send/main.py#gate -->
```python
clock = FakeClock("2026-11-25T10:00:00Z")
gate = hitl.Gate(
    POLICY,
    mode="suspend",  # a web app: never block a request waiting for a human
    clock=clock,
    channels=[
        hitl.slack(token="xox" + "b-your-bot-token", signing_secret=SLACK_SIGNING_SECRET, transport=slack_api),
        hitl.webhook(
            name="compliance",
            url="https://compliance.example/hitl",
            secret=OUTBOUND_SECRET,
            inbound_secret=INBOUND_SECRET,  # a receiver of the requests cannot sign answers
            transport=compliance,
            now=clock.now,
        ),
    ],
)


@gate
async def send_campaign(campaign: str, audience: str) -> str:
    return f"Sent {campaign} to {audience}"


# Mount this at /hitl in your ASGI app: Slack buttons and webhook replies land here.
webhooks = gate.webhooks(base_path="/hitl")
```

Suspend instead of waiting, so any process can answer later:

<!-- include: examples/python/approval-expires/main.py#suspend -->
```python
action = {"tool": "send_wire", "args": {"to": "ACME-002", "amount": 9_000}, "call_id": "call_2"}
auth = await gate.authorize(action, wait=False)  # returns "pending" at once
assert auth.approval is not None
approval_id = auth.approval.id

clock.advance(FOUR_HOURS)  # nobody answered
swept = await gate.sweep()  # optional: expiry is also applied lazily on every read

late = await gate.respond(approval_id, hitl.approve(by="pager:kim"))  # too late: "conflict", already expired
retry = await gate.authorize(action, wait=False)  # status "expired", never runs
```

## Testing

<!-- include: examples/python/quickstart/main.py#test -->
```python
with hitl.testing.fake_approvals(answer="approve") as approvals:
    assert issue_refund("A-1002", 900) == "Refunded $900 on A-1002"
    assert approvals.asked("issue_refund", args={"amount": {"gt": 50}})
```

The pytest plugin gives the same thing as the `approvals` fixture. `tests:` blocks in `policies/*.yaml` and
`policies/*.test.yaml` run as pytest items (`pytest policies/`) and with `viewport-hitl test`.

## CLI

`viewport-hitl check | explain | test | receipts verify | pending | approve | deny | init`

Docs: https://docs.getviewport.com/hitl

## License

Apache-2.0.
