Metadata-Version: 2.5
Name: kollguard
Version: 0.1.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.

## 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.

## 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.
- v1 wire contract: pending requests expire after 15 minutes and an allow is valid for 15 minutes. Approvals that
  must outlive a process (72 h) need the resumable gate (server PR1b); until then keep the process or checkpointer
  alive, or the call is asked again with a new request after expiry.
- Not included yet: webhook signature verification and the OpenTelemetry span processor (they depend on server
  pieces that have not shipped).

## 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.
