Metadata-Version: 2.5
Name: kollguard
Version: 0.2.0
Summary: KollGuard Agent Watch gate for Python agents: authorize tool calls before they run (LangGraph, OpenAI Agents SDK).
Project-URL: Homepage, https://kollguard.com
Author: Kollitech Corp
License: MIT
License-File: LICENSE
Keywords: ai-agents,governance,human-in-the-loop,kollguard,langgraph,openai-agents
Classifier: Development Status :: 4 - Beta
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Typing :: Typed
Requires-Python: >=3.9
Provides-Extra: langgraph
Requires-Dist: langchain-core<2,>=1.0; extra == 'langgraph'
Requires-Dist: langgraph-prebuilt<2,>=1.1; extra == 'langgraph'
Requires-Dist: langgraph<2,>=1.2; extra == 'langgraph'
Provides-Extra: openai-agents
Requires-Dist: openai-agents<1,>=0.25; extra == 'openai-agents'
Provides-Extra: test
Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
Requires-Dist: pytest>=8; extra == 'test'
Description-Content-Type: text/markdown

# kollguard (Python)

Authorize every tool call your Python agent makes **before it runs**. Each call is checked against your KollGuard
Agent Watch policy and answers `allow`, `deny`, or `pending` (a named human approves it in KollGuard).

- Adapters for **LangGraph** and the **OpenAI Agents SDK**, both optional extras.
- Zero runtime dependencies (stdlib only). Sync and async. Python 3.9+.
- **Argument values never leave your host.** KollGuard sees the tool name, the argument *names*, and the optional
  `resource` string you choose to pass. The `kgw_` token goes only in the `x-agent-token` header and is never logged
  or included in an exception message.
- **Fail modes per tool.** If KollGuard cannot answer (network, timeout, 5xx, 429, bad token), a tool marked
  `fail: "closed"` is blocked and a tool marked `fail: "open"` runs. The default is closed.

> Enforcement is **cooperative**: this SDK gates the calls that go through it. It is not a sandbox, and code that
> bypasses the wrapper is not gated. Agent Watch labels it that way on the agent's passport.

Get an agent token in KollGuard under Agent Control, then:

```bash
export KOLLGUARD_AGENT_TOKEN=kgw_...
```

## LangGraph in 3 steps

```bash
pip install "kollguard[langgraph]"
```

1. Swap `ToolNode` for the gated one.
2. Compile with a checkpointer (needed for approvals that pause the graph).
3. Resume with `Command(resume=...)` after the human decides in KollGuard.

```python
from kollguard import KollGuard
from kollguard.langgraph import kollguard_tool_node
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command

kg = KollGuard(policy={"tools": {"send_email": {"class": "external_comm"},
                                 "lookup":     {"class": "read", "fail": "open"}}})

graph.add_node("tools", kollguard_tool_node([send_email, lookup], kg))      # step 1
app = graph.compile(checkpointer=InMemorySaver())                           # step 2

out = app.invoke({"messages": [("user", "email the customer")]}, {"configurable": {"thread_id": "t1"}})
if "__interrupt__" in out:                                                  # pending approval
    print(out["__interrupt__"][0].value)   # {"kind": "kollguard_approval", "kollguard_request_id": ..., ...}
    # ...the approver clicks Approve in KollGuard...
    out = app.invoke(Command(resume=True), {"configurable": {"thread_id": "t1"}})   # step 3
```

What happens: allow runs the tool; deny returns a `ToolMessage(status="error")` to the model and the tool never
runs; pending calls `interrupt()`. LangGraph re-executes the node on resume, and the idempotency key
(`thread_id` + `tool_call_id`) makes the second check a replay of the *same* request, never a duplicate. The resume
value is never treated as approval: KollGuard is asked again, and if it is still pending the graph interrupts again.

`ToolNode(..., **kollguard_wrappers(kg))` and `kollguard.langgraph.check(kg, name, args, ...)` (for your own nodes)
are also available. The wrapper has the `(request, handler)` shape of `AgentMiddleware.wrap_tool_call`.

## OpenAI Agents SDK in 3 steps

```bash
pip install "kollguard[openai-agents]"
```

1. Wrap your tools with `guard_tool`.
2. Run the agent; a call that needs a human stops the run with an interruption.
3. After the human decides in KollGuard, call `resolve_interruptions` and run again from the state.

```python
from agents import Agent, Runner, function_tool
from kollguard import KollGuard
from kollguard.openai_agents import guard_tool, aresolve_interruptions

kg = KollGuard(policy={"tools": {"refund": {"class": "money_auth"}}})

@function_tool
def refund(order_id: str) -> str: ...

agent = Agent(name="support", tools=[guard_tool(refund, kg)])                # step 1
result = await Runner.run(agent, "refund order 42")                          # step 2
while result.interruptions:
    # ...wait for the approver in KollGuard...
    state = result.to_state()
    await aresolve_interruptions(state, kg)      # approves/rejects each call from KollGuard's answer   (step 3)
    result = await Runner.run(agent, state)
```

`guard_tool` attaches two things: a `ToolInputGuardrail` that is the real gate (runs just before the tool, after any
approval, so a local `state.approve()` can never bypass KollGuard) and a `needs_approval` that returns True only
while KollGuard has the call pending. Both use the model's `call_id` as the idempotency key. Use
`kollguard_tool_guardrail(kg)` / `kollguard_needs_approval(kg, "tool_name")` separately if you prefer.

## Resumable approvals (hours or days)

A pending request normally expires after 15 minutes, which only suits a process that waits. With a server that reports
`resumable` in `GET /v2/policy` (hosted KollGuard does, with `v2`, `webhooks` and `quorum`), the request waits **up to
72 hours (7 days on Enterprise)** and the run can suspend and exit:

```python
kg = KollGuard(contract="auto")          # probes GET /v2/policy once; "v2" assumes it, the default "v1" never uses it
kg.capabilities()                        # ["v2", "resumable", "webhooks", "quorum"]

d = kg.decide("refund", args, action_class="money_auth", ids=(run_id, tool_call_id), wait="resumable")
if d.pending:                            # d.resumable is True; returned at once, nothing is polling
    suspend(d.request_id, d.expires_at)
# ...when the run resumes (any process), call decide() again with the SAME ids:
d = kg.decide("refund", args, action_class="money_auth", ids=(run_id, tool_call_id), wait="resumable")
```

- **Resume = re-decide with the same ids.** The ids make a stable key with no time component, so the server replays the
  stored request. Once a human approved it, the first re-decide returns `allow`, and **the allow counts 15 minutes from
  that first use**, not from the approval. A deny or an expiry replays as `deny`. A resumable wait with no stable ids
  raises `KollGuardConfigError` (a time-based key would file a second request on resume).
- Without the capability, the same call is an inline wait (15-minute request); nothing else changes.
- `kg.choose_wait(ids)` returns `"resumable"` or `"inline"` for adapters. The LangGraph and OpenAI Agents adapters use
  it: resumable when the server reports it, an inline-window request otherwise.
- An agent may hold 500 open resumable requests; beyond that the server answers `deny` (HTTP 429).

### Decision webhooks

Register a webhook (owner or admin: `POST /api/agent-watch/authorizations/webhooks` with `{"url": "https://..."}`; the
answer carries `webhook.webhookId` and a `whsec_...` secret, shown once), then name it per request and verify the
callbacks:

```python
d = kg.decide("refund", args, ids=(run_id, call_id), wait="resumable", callback=WEBHOOK_ID)   # lowercase uuid; needs 'webhooks'

# in your https endpoint (Flask shown); use the RAW body
@app.post("/kollguard")
def kollguard_hook():
    try:
        p = verify_webhook(request.headers, request.get_data(), WEBHOOK_SECRET)   # or kg.verify_webhook(...)
    except WebhookError:
        return "", 400
    resume_run(p["requestId"], p.get("runRef"))      # then re-decide with the same ids: that answer is the truth
    return "", 204
```

Payload: `{"requestId", "decision": "allow" | "deny" | "expired", "idempotencyKey"?, "runRef"?, "framework"?}`; no action
text or approver identity. Headers: `webhook-id` (the **same on every retry**: dedupe on it), `webhook-timestamp` (unix
seconds, fresh per attempt; more than 300 s off is rejected) and `webhook-signature` (`v1,<base64 HMAC-SHA256>` over
`<id>.<timestamp>.<body>`; several space-separated signatures are accepted). Failures are retried after 30 s, 2 min, 10
min, 30 min, 1 h, 2 h and 6 h (8 attempts in all). Callbacks are advisory: a lost or forged one can only delay a run,
never allow one. `verify_webhook` is byte-compatible with `@kollguard/core`; both are tested against signatures from the
live signer.

## Any other agent

```python
d = kg.gate("send_email", {"to": to, "body": body}, framework="my-agent", resource="mail:outbound")
if not d.allowed:            # d.decision is "deny" or "pending"; d.reason says why
    raise PermissionError(d.reason)
```

`kg.decide()` asks once; `kg.gate()` also waits inline (default 120 s) for a human; `kg.wait_for_decision(request_id)`
polls. Async twins: `adecide`, `agate`, `await_decision`, `apoll`. None of them raise for an answer or a network
problem (only a call that can never work, such as a malformed `callback`, raises `KollGuardConfigError`).

## Policy file

A compatible subset (`tools`, `default`) of the JSON `kollguard-claude-hook` reads (`mcp` and `mcpServers` are ignored):

```json
{
  "tools": {
    "send_email": {"class": "external_comm", "fail": "closed"},
    "lookup_order": {"class": "read", "fail": "open"},
    "get_time": {"gate": false},
    "stripe_*": {"class": "money_auth"}
  },
  "default": {"class": "unclassified", "fail": "closed"}
}
```

`KollGuard(policy="kollguard.policy.json")`. Classes: read, propose, write, external_comm, money_auth, phi_access,
patient_facing, unclassified. `"gate": false` makes no network call (zero added latency).

## What is sent

| Sent | Never sent |
|---|---|
| tool name, framework label, argument **names**, action class, your optional `resource` and `summary` text, an HMAC idempotency key | argument values, prompts, completions, tool results, the token in any body or log |

`resource` is sent exactly as you give it (the server redacts it before storage): pass a template such as
`stripe:refund`, not a value.

## Limits in this release

- Python: the core client runs on 3.9+. The LangGraph and OpenAI Agents extras need 3.10+ (their own floor). Using
  LangGraph with **async** graphs and approvals (`interrupt()`) needs Python 3.11+ (LangGraph relies on contextvars
  there; verified failing on 3.10). Sync graphs work on 3.10.
- OpenAI Agents: do not enable `RunConfig.tool_execution.pre_approval_tool_input_guardrails` together with
  `guard_tool`. The guardrail would then run before the pause and turn a pending call into a refusal instead of an
  interruption.
- If one `tool_call_id` is asked again after its request has expired twice, the deterministic retry key replays the
  expired row and the call is denied (fail-safe) rather than re-filed.
- The default `contract="v1"` (works with every deployed server): pending requests expire after 15 minutes and an allow
  is valid for 15 minutes. Use `contract="auto"` for resumable approvals (72 h, 7 days on Enterprise) and webhooks.
- If a resumable request expires unanswered, the re-decide is treated like any expired replay: one deterministic
  retry key files a new request.
- Not included yet: the OpenTelemetry span processor.

## Develop

```bash
uv venv && uv pip install -e ".[langgraph,openai-agents,test]"
pytest
```

The tests run a fake gate that enforces the route's exact validation, and the adapter tests run against the real
frameworks when installed (mocked otherwise).

## Release

```bash
python -m pip install build twine
python -m build            # dist/kollguard-<version>.tar.gz and .whl
twine upload dist/*        # needs a PyPI account and API token for the `kollguard` project
```

MIT licensed.
