Metadata-Version: 2.4
Name: ica-capture
Version: 0.1.0
Summary: Emit AI agent steps to ICA. ICA signs and governs them. A tool guard, tool hooks, a callback recorder and an approval pause for agent frameworks (the framework is a setting), MCP, plus outside eval intake.
Author: ALEETH
License: Apache-2.0
Project-URL: Homepage, https://aleeth.com
Keywords: ai,agents,governance,audit,approvals,tool-guard,mcp,evals,ica
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: callbacks
Requires-Dist: langchain-core>=0.2; extra == "callbacks"
Dynamic: license-file

# ICA Capture SDK (Python)

Emit your AI agent's steps to ICA in one line. ICA does the rest: it mints a
signed, append-only receipt for every step, scores the run into continuous
posture, and can halt an agent that crosses a control. You sign nothing and hold
no key.

A receipt of what ran is the floor. ICA also decides what is allowed to run: a
gated call waits for ICA's decision before the tool body executes, a call held
for people waits for their approval, and an agent that crosses a control can be
halted. Each decision ICA seals carries a signed receipt that anyone can
re-check later.

## Install

```bash
pip install ica-capture            # core, zero dependencies
pip install "ica-capture[callbacks]"   # adds the framework callback recorder
```

## Configure

```python
from ica import IcaClient

ica = IcaClient(
    token="YOUR_ICA_INGEST_TOKEN",   # X-ICA-Ingest-Token
    agent_handle="your-agent",        # resolves to your registered identity
)
```

Your ingest credential names your tenant, so `customer_id` is optional. If you
pass it, it must be the same tenant: ICA refuses any other (403
`ingest_tenant_mismatch`).

Telemetry never breaks your agent. Emit failures are swallowed by default; pass
`raise_on_error=True` while you are wiring things up.

## Three drop-in surfaces

### Callback recorder (one line)

```python
from ica.callbacks import IcaCallbackHandler

agent.invoke(payload, config={"callbacks": [IcaCallbackHandler(ica)]})
```

Every tool call, ok or error, is recorded with timing, through the agent framework's own callback surface
(install the `[callbacks]` extra).

### Decorator

```python
from ica import ica_tool

@ica_tool(ica, reversibility_tag="reversible")
def search(query):
    ...
```

### MCP or any callable

```python
from ica import wrap_mcp_tool

guarded = wrap_mcp_tool(ica, raw_tool_call, name="filesystem.read")
```

### Manual

```python
ica.record_tool_call(
    tool_name="web.search",
    tool_input={"query": "..."},
    tool_output={"hits": 3},
    duration_ms=142,
)
```

## What ICA does with it

Each step posts to `POST /api/ingest/agent-step`. On arrival ICA:

1. Mints an L7 receipt over the step, signed server-side. You never touch a key.
2. Appends it to an append-only, tamper-evident audit trail.
3. Feeds it to the assessment engine: decision control, containment,
   reversibility, observability, continuous posture.
4. Enforces. A step that bypasses a gate or runs an irreversible action ungated
   is flagged, and a halted agent is quarantined at ingest.

Verify any receipt without publishing your data. Public chains are optional, not
required, and never the default.

## Step fields

| Field | Notes |
|-------|-------|
| `step_type` | `reasoning`, `tool_call`, `sub_agent_dispatch`, `final_answer`, `gate_request`, `gate_response` |
| `tool_name` | the tool invoked |
| `tool_input` / `tool_output` | JSON-safe; coerced if needed |
| `reversibility_tag` | `reversible`, `partial`, `irreversible`, `unclassified` |
| `gate_state` | `not_gated`, `pending`, `approved`, `denied`, `bypassed` |
| `duration_ms`, `tokens_used` | optional metrics |

## Tool guard and tool hooks

For a graph whose held calls should wait for people, use `ica.approval_pause` (below): a held call pauses the
graph instead of ending it, and the block is hard. The callback recorder above still records graph runs. Two
more, neither of which adds a dependency. The agent framework is a setting, never a module name:

| Use | `framework=` | Hard block with `gate=True` |
|---|---|---|
| `from ica.tool_guard import guard_tools`; `tools = guard_tools(ica, tools, framework=..., gate=True)` | `"openai_agents"` | yes: wraps each dataclass function tool's `on_invoke_tool` |
| the same | `"crewai"` | yes: wraps each tool's `_run` |
| the same | `"llamaindex"` | yes: wraps `FunctionTool` `_fn` and `_async_fn` |
| `from ica.tool_hooks import IcaHooks`; `Agent(tools=..., hooks=[IcaHooks(ica, gate=True)])` | (frameworks that call tool hooks) | yes: a deny sets `cancel_tool` |

An unknown `framework=` raises `ValueError`, so a typo never leaves tools unguarded. A tool of another shape is
returned unchanged.

## Stated confidence

An agent can tell ICA how sure it is of each gated call, as a number from 0 to 1. When the agent's scope
contract sets a confidence floor (`operating_envelope.confidence_floor`), ICA holds a call below the floor,
or one that states nothing, for a person: `gate()` answers `pending` and the tool does not run. A high
number never loosens anything; every other check still decides.

- `ica.gate(action, tool_name=..., stated_confidence=0.82)` sends it on one call.
- Every adapter and decorator takes `confidence=`: a number, or a function `(tool_name, payload) -> number`
  that reads the model's own statement (for example a `confidence` field your tool schema asks the model to
  fill). A function that raises states nothing, so with a floor set the call is held.

```python
tools = guard_tools(ica, tools, framework="crewai", gate=True, confidence=lambda name, payload: payload.get("kwargs", {}).get("confidence"))
```

## Approval pause: a held call pauses the graph

Every other adapter treats a call ICA holds for a person (`pending`) as a deny: the run ends. In a graph runtime
with `interrupt()` and a checkpointer the graph can wait instead.

```python
from langchain_core.tools import tool
from langgraph.checkpoint.memory import MemorySaver
from langgraph.prebuilt import ToolNode
from ica.approval_pause import ica_approval_pause_tool, route_tool_calls

@tool
@ica_approval_pause_tool(ica, reversibility_tag="irreversible")
def update_claim(claim_id: int, amount: int) -> str:
    ...

builder.add_node("tools", ToolNode([update_claim]))
builder.add_conditional_edges("agent", route_tool_calls, ["tools", END])   # one task per tool call
graph = builder.compile(checkpointer=MemorySaver())                       # pausing needs a checkpointer
```

- Approved: the tool runs and its step carries the single-use token. Denied: `GateDenied`, the tool never runs.
- Held: ICA raises a two-person approval request bound to the exact arguments, and the graph pauses
  (`interrupt()`); the payload carries `approval_request_id`. Two named people approve it in the ICA console.
  Resume with `Command(resume=...)` (one value per pending interrupt when several pause at once). The resume
  value is only a wake-up: the tool asks ICA, and runs only when ICA releases a token for that call. Still
  pending, or ICA briefly unreachable: it pauses again. Denied, expired, arguments changed, or the agent halted,
  retired or cert-blocked since the approval: `GateDenied`. Already released (a re-run after it ran): it does
  not run again and returns a message saying so.
- One tool call per task. A resumed graph task runs again from the top, and a plain `ToolNode` wired on the
  messages list runs every call of a turn in one task, so the other calls of that turn would run again when one
  pauses. Use `route_tool_calls` (above) or `create_react_agent` (its default version "v2" already sends each
  call on its own). Tested with the graph runtime package at 1.2.14 (tests/test_approval_pause_real.py): with the routing, an approved call beside a held one runs once;
  without it, twice.
- Needs a per-customer ingest credential: only the credential that raised a request can collect it, and a
  shared token raises none. A tenant that approves with one person gets no request either: this path releases
  only on two named approvals. Outside a graph run nothing is requested and a hold ends the call, as before.
- A request waits up to an hour for a person, an approval must be collected within an hour of being given, and a
  credential can have at most 25 requests waiting. Arguments holding an integer past 2^53 are refused (JSON cannot
  carry it exactly): send such ids as strings.
- Each resume re-asks the gate (one more sealed `pending` decision). A `hold_key` derived from the thread and
  task makes the re-ask find the same request. Pass `key_fn=` to name calls yourself.
- Under it: `ica.gate(..., request_approval=True, args=..., hold_key=...)` and `ica.release(approval_request_id,
  args)`, which any framework can use.

## Signed proof in your agent's trace

Every gate decision ICA seals comes back with its signed receipt. Give the client an `on_proof` function and that proof lands
in your agent's own trace, beside the tool call it decided:

```python
ica = IcaClient(token="...", agent_handle="pay-bot", on_proof=add_to_current_run)
```

`add_to_current_run(proof)` is yours: add the dict to the current run's metadata in whatever tracing tool you use. The dict
is flat strings: `ica_receipt_hash`, `ica_verify_url`, `ica_decision`, `ica_gate_id`, `ica_signing_key_id`, `ica_tool`.
Anyone holding the hash re-checks the decision at the verify URL (public, no sign-in) or offline against ICA's published
keys, without trusting your tracer or ALEETH. Every adapter above that gates (`gate=True`, the tool guard, the tool hooks,
the approval pause) goes through `gate()`, so it carries the proof; the same dict is on the verdict as `verdict["proof"]`,
and `proof_of(verdict)` builds it from any gate answer. A decision ICA could not seal gives no proof. A function that raises
never changes the decision (it raises only with `raise_on_error=True`). A step recorded without a gate is signed just after
ICA answers, so its receipt is not in that answer.

## Outside eval results

`from ica.evals import record_eval`, then `record_eval(ica, result, framework="ragas", run_name=..., thresholds={...})`.
Reads Ragas, DeepEval, Giskard, TruLens, promptfoo and plain `{metric: score}` results, and files the
summary (per-metric mean, min, max, count, pass and fail counts, failed thresholds, never the eval's
prompts or answers) as one step on the agent's ICA record, where it is sealed like every other step.

## License

This SDK is licensed under the Apache License 2.0 (see LICENSE). Using ICA needs an ingest token: contact ALEETH
(https://aleeth.com).
