Metadata-Version: 2.4
Name: zanii
Version: 0.16.0
Summary: Zanii Python SDK — verifiable identity and proof-of-action for AI agents
License-Expression: Apache-2.0
Project-URL: Homepage, https://ledger.zanii.agency
Project-URL: Documentation, https://ledger.zanii.agency/docs
Keywords: ai-agents,identity,transparency-log,merkle,ed25519,audit
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security :: Cryptography
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cryptography>=42
Provides-Extra: mcp
Requires-Dist: mcp>=1.10; extra == "mcp"
Provides-Extra: runtime
Provides-Extra: otel
Requires-Dist: opentelemetry-api>=1.20; extra == "otel"
Provides-Extra: langchain
Requires-Dist: langchain-core>=0.2; extra == "langchain"
Provides-Extra: openai-agents
Requires-Dist: openai-agents>=0.0.1; extra == "openai-agents"
Provides-Extra: crewai
Requires-Dist: crewai>=0.30; extra == "crewai"
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: httpx>=0.27; extra == "dev"
Requires-Dist: mcp>=1.10; extra == "dev"
Requires-Dist: opentelemetry-api>=1.20; extra == "dev"
Dynamic: license-file

# zanii

**Verifiable identity and proof-of-action for AI agents.** Give every agent a
cryptographic identity (`did:key`), scope what it's allowed to do with signed
delegation certificates, and emit a tamper-proof, hash-chained receipt for every
action it takes — anchored in an RFC 6962 Merkle transparency log. Anyone can
verify what an agent did, offline, without trusting the server that stored it.

Full protocol parity with the TypeScript SDK (`@zanii/core` / `@zanii/sdk`) —
cross-language test vectors guarantee byte-identical hashes and signatures. The
only runtime dependency is [`cryptography`](https://cryptography.io).

```sh
pip install zanii
```

## Quickstart

```python
from zanii import ZaniiAgent, fetch_and_verify_proof
from zanii.core import generate_keypair, create_cert

# 1. Identities. The owner delegates a scoped, expiring capability to the agent.
owner = generate_keypair()
agent = generate_keypair()
cert = create_cert(
    issuer=owner.did,
    subject=agent.did,
    scopes=["crm.*"],                 # this agent may only act within crm.*
    exp="2027-01-01T00:00:00Z",
    issuer_private_key=owner.private_key,
)

# 2. Instrument the agent. Every action is signed and hash-chained locally,
#    then batched to the log.
zanii = ZaniiAgent(
    server_url="https://ledger.zanii.agency",
    agent_did=agent.did,
    agent_private_key=agent.private_key,
    delegation=[cert],
    # api_key="zk_live_...",          # required when the log enforces write auth
)
receipt, receipt_hash = zanii.record(target="crm.lookup", payload={"email": "a@b.co"})
zanii.flush()                         # ship queued receipts to the log

# 3. Anyone can verify that proof — offline, zero trust in the server.
proof = fetch_and_verify_proof("https://ledger.zanii.agency", receipt_hash)
assert proof.ok
```

`wrap_tool` instruments an existing function so every call (sync or async) is
recorded automatically — result on success, error on failure:

```python
lookup = zanii.wrap_tool("crm.lookup", crm.find)   # crm.find is your own function
lookup("a@b.co")                                    # transparently receipted
```

## `zanii.core` — pure verification, no network

Import from `zanii.core` when you only build or verify proofs and never touch the
network (an auditor, a third-party verifier, an offline signer). Everything there
is deterministic and does no I/O; the network client lives on the top-level
`zanii` package.

```python
from zanii.core import verify_audit_bundle

# A self-contained audit bundle (GET /v1/export/{agent_did}) is verified with no
# trusted party: signatures, delegation scope, Merkle inclusion, the per-agent
# hash chain, and on-chain anchor consistency.
report = verify_audit_bundle(bundle)
assert report.ok, [c for c in report.checks if not c["ok"]]
```

Fully typed — ships `py.typed` (PEP 561), so your type-checker sees every
signature.

## MCP proxy

Front any [MCP](https://modelcontextprotocol.io) server so every tool call is
receipted — **no changes to the agent or the upstream server.** Install the
extra:

```sh
pip install "zanii[mcp]"
```

Wrap a connected upstream `ClientSession` with a `ZaniiAgent`; serve the result
in place of the real server. Tool lists pass through unchanged; each call is
recorded as `mcp.<tool>` — result on success, error on failure.

```python
from zanii import ZaniiAgent
from zanii.mcp_proxy import create_zanii_proxy

proxy = create_zanii_proxy(upstream_session, ZaniiAgent(...))
```

Or run it standalone over stdio, wrapping an upstream stdio MCP server:

```sh
ZANII_SERVER=https://ledger.zanii.agency ZANII_IDENTITY=./identity.json \
    python -m zanii.mcp_proxy -- npx some-mcp-server --its-args
```

## Agent runtime — deterministic rails

The SDK above records proofs. `zanii.runtime` (optional) is the layer that *governs
the action itself*: the model **proposes**, tested code **disposes**. It enforces
the accountability rules that sit above the ledger — scoped authority, "no external
receipt → no claim of success", a fixed status vocabulary, manifest validation, and
a human confirmation gate for irreversible actions.

```sh
pip install "zanii[runtime]"   # pure logic, no extra deps — ships with base zanii too
```

```python
from zanii import ZaniiAgent
from zanii.runtime import Runtime, Tool, ToolResult

def send_email(to, subject):
    provider_id = mail.send(to, subject)          # your real integration
    return ToolResult(ok=True, receipt_id=provider_id)   # the provider's receipt

rt = Runtime(ZaniiAgent(...), [
    Tool("email.send", scope="email.*", run=send_email, irreversible=True),
])

d = rt.propose("email.send", {"to": "a@b.co", "subject": "Hi"}, intent="follow up")
# → irreversible ⇒ d.status == "awaiting_confirmation"; nothing sent yet
d = rt.confirm(d.confirmation_id)                 # owner says yes (bound to this exact action)
# → d.status == "sent" (a provider receipt was returned) and it's recorded on the ledger
```

Status is **earned**: no `receipt_id` ⇒ `attempted` (never `sent`); a matched
read-back ⇒ `confirmed`; a thrown tool ⇒ `failed`. Out-of-scope or unknown tools are
rejected before anything runs; low `confidence` returns `clarify` instead of guessing.

## Links

- **Docs & concepts** — https://ledger.zanii.agency/docs
- **Live transparency log** — https://ledger.zanii.agency

## More optional modules

Everything below ships **inside this one `zanii` package** — no extra install unless a
module needs a third-party dep (those are opt-in extras, shown as `zanii[…]`). Import
only what a task needs.

**Test, observe, receive:**
- **`zanii.webhooks`** — verify `X-Zanii-Signature` and dispatch typed webhook events:
  `create_webhook_receiver(secret, on={...})`. Stdlib only.
- **`zanii.testing`** — `fake_ledger()` + `make_identity` / `make_cert` / `make_receipt`
  fixtures. Unit-test agents offline (no server, real Merkle proofs).
- **`zanii.monitor`** — independent append-only + anchor watchdog. `check_once(server)`,
  or the `zanii-monitor` CLI.
- **`zanii.witness`** — independent co-signer: verify append-only, then counter-sign
  (`create_witness(kp).cosign(sth, …)`, `verify_cosignature`).
- **`zanii.otel`** (`pip install "zanii[otel]"`) — `with_tracing(agent)` makes every
  `record` an OpenTelemetry span.

**Agent-framework adapters** (receipt a whole run via the framework's own hook):
- **`zanii.langchain`** (`zanii[langchain]`) — `zanii_callbacks(agent)` receipts every
  tool call in a LangChain **or LangGraph** run.
- **`zanii.openai_agents`** (`zanii[openai-agents]`) — `ZaniiRunHooks(agent)` for the
  OpenAI Agents SDK.
- **`zanii.crewai`** (`zanii[crewai]`) — `instrument_crew(crew, agent)` for CrewAI.
- **`zanii.connectors`** — `wrap_toolbox` / `run_tool_calls` for raw OpenAI/Anthropic tool calls.

**Compliance & privacy:**
- **`zanii.compliance`** — `build_compliance_report(bundle, controls=…)` → an auditor report.
- **`zanii.retention`** — GDPR Art. 17 deletion attestations (`build_retention_attestation`) **and the
  inverse** `build_retention_hold` — a signed attestation that records were *kept* (UAE 5-yr rule).
- **`zanii.redact`** — selective disclosure: `commit` / `disclose` / `verify_disclosure`.
- **`zanii.consent`** — PDPL consent grant/withdrawal receipts (`build_consent_receipt`, `verify_consent`).
- **`zanii.admissibility`** — court-ready **bilingual (Arabic/English)** evidence pack for UAE Electronic
  Transactions 46/2021 (`build_evidence_pack`, `render_evidence_pack_markdown`).
- **`zanii.fta`** — FTA filing evidence (Meezan/Books): `build_filing_prep_receipt` (prepared, never filed),
  `build_tax_agent_handoff`, `verify_filing_evidence`, `FTA_WALL`.
- **`zanii.walls`** — UAE vertical wall presets (SCA trading, RERA, TDRA, Legal, Consumer, DIFC/ADGM):
  `WALLS`, `wall_policy`, `wall_manifest_hash`, `check_output`, `build_eval_receipt`.

**Discovery, payments & identity:**
- **`zanii.a2a_directory`** — resolve an agent DID to its **verified** history for A2A / agent cards.
  `resolve_agent(did)`, `resolve_and_verify(did)` (pulls + verifies the audit bundle offline), `agent_did_from_card`.
- **`zanii.x402`** — bind a payment receipt to its on-chain settlement. `verify_settlement`,
  `build_x402_payment`, zero-dep `json_rpc_tx_fetcher` for any EVM chain.
- **`zanii.erc8004`** — build/resolve/verify ERC-8004 agent registration files wired to Zanii proof
  endpoints. `build_registration_file`, `to_data_uri`, `resolve_registration`, `verify_resolved_agent`.
- **`zanii.memory`** — provable agent memory: hash-chained `memory.write` receipts (salted content
  commitments, tamper-evident links) so an auditor can prove "why did it decide that?".
  `append_memory`, `build_memory_write`, `verify_memory`, `verify_memory_chain`, `commit_content`.
- **`zanii.kya`** — Know Your Agent: screen a counterparty against a deny-list / injected sanctions
  provider before transacting, and receipt it (`kya.screening`). `screen_agent`, `resolve_and_screen`,
  `build_screening_receipt`, `verify_screening`.
- **`zanii.swarm`** — N-party (3+) co-signed receipts for agent teams: genuine M-of-N Ed25519 threshold
  signatures. Offline: `build_swarm_body`, `sign_swarm`, `verify_swarm`. On-ledger (SPEC §14, live at
  `POST /v1/swarm`): `swarm_signer`, `build_swarm_receipt`, and the authority-complete `verify_swarm_receipt`
  (delegation + scope + prev + revocation + distinct-owner segregation).
- **`zanii.attest`** — bind *which code ran* to a receipt: an attestation claim + `attestation_hash`
  provenance field, quote verification delegated to an injected verifier. `attestation_hash`,
  `attestation_field`, `verify_attestation`.
- **`zanii.subject`** — **per-subject auditability**: end users hold their own key and independently
  verify what agents did on *their* account (pseudonymous, platform-scoped `subject_tag` slice via
  `GET /v1/subjects/{tag}`). `subject_tag`, `subject_identity`, `sign_subject_claim`/`verify_subject_claim`,
  `fetch_subject_history`/`fetch_my_history`; stamp with `agent.record(..., subject_tag=tag)`.

- **`zanii.sentinel`** — **runtime behavioral monitoring** ("antivirus for agents"): score drift
  between what an agent *actually does* and what it was *made to do* (declared scopes + learned
  habits) from the receipt stream; alerts are themselves `sentinel.alert` receipts (watcher ≠
  watched). `build_baseline`, `scan` (novel-target, scope-edge, rate-spike, intent-gap, exfil
  sequence, off-hours, + operator-mode content hook), `Watcher`, `escalation_rule`,
  `build_alert_receipt`/`verify_alert`.

- **`zanii.credentials`** — **verifiable institutional credentials** (diplomas, licences,
  certifications): offline-verifiable in ms, no call to the registrar. Four checks — signature,
  expiry, revocation (signed list with an **explicit freshness window**), and a **domain-bound
  issuer root-of-trust** (`.well-known/zanii-issuer.json`). `build_credential`, `verify_credential`,
  `resolve_issuer`, `build_revocation_list`, `build_presentation`/`verify_presentation` (possession,
  not a bearer token). *Zanii verifies institutional identity; it is never the accreditor.*
- **`zanii.gov`** — **public-sector algorithmic accountability** (benefits, visas, fines, licences):
  a state decision with no governing rulebook cannot be constructed, and `appeal_pack` puts a
  bilingual, court-ready proof of what the algorithm did to you into the **citizen's own hands**.
  `build_gov_decision`, `citizen_tag`, `appeal_pack`, `render_appeal_pack_markdown`.

- **`zanii.health`** — **medical audit trails without leaking the pattern**: per-episode *unlinkable*
  tags (the patient supplies the tag, **never the seed**), plus who accessed the record, which model
  recommended what under which protocol, and **which named clinician took responsibility**.
  Break-glass is **loud, not impossible** (`pending_break_glass` — the metric, not the mandate).
  `episode_seed`, `episode_tag`, `build_access_receipt`, `build_recommendation`,
  `build_clinician_confirmation`, `build_break_glass`, `protocol_trail` (**not** `rule_consistency` —
  individualised care is correct medicine), `fetch_episodes`.

**Real-world provenance:**
- **`zanii.provenance`** — AI-content credentials: sign an artifact's hash with the creating agent's
  did:key, anchor as `content.created`, resolve the creator to their verified history.
  `build_content_credential`, `verify_content_credential`, `credential_receipt`, `resolve_creator`.
- **`zanii.custody`** — supply-chain custody chains: co-signed handoffs (a2a) + N-party events (swarm)
  + pseudonymous item slices. `item_tag`, `build_handoff`, `build_custody_event`, `verify_custody_chain`
  (continuity: receiver of *n* = giver of *n+1*), `custody_summary`. Attestations, not atoms.
- **`zanii.decisions`** — auditable algorithmic decisions for gig/creator workers: completeness +
  rule-consistency (`manifest_hash` required) + committed factors. `build_decision_receipt`,
  `verify_decision`, `rule_consistency` (interleaved rulebooks = the red flag).

**Keys, money, embeds, CLI:**
- **`zanii.kms`** — seal agent keys at rest (`seal_identity` / `open_identity`, scrypt + AES-256-GCM).
- **`zanii.policy`** — pre-action allow/deny/require_approval (`create_policy_engine`).
- **`zanii.payments`** — correct money for payment receipts (`build_payment`, integer minor units).
- **`zanii.embed`** — "Verified by Zanii" badge builders (`agent_badge`, `badge_svg`).
- **`zanii` console script** — the CLI: `zanii keygen`, `zanii delegate`, `zanii verify <hash>`, …

## Changelog

- **0.16.0** — `zanii.cv`: AgentCV — a signed, portable view over the ledger (the summary is
  the un-inflatable ledger aggregate; curated entries each point at a verifiable ref; proves the
  entries are real, never that the history is complete). A Python-signed CV verifies in TS.
- **0.15.0** — `zanii.health`: medical audit trails without leaking the pattern (per-episode
  unlinkable tags; the four-party accountability question; break-glass that is loud, not
  impossible; `protocol_trail` deliberately passes no uniformity verdict).
- **0.14.0** — institutional trust layer: `zanii.credentials` (institutional credentials +
  the domain-bound issuer root-of-trust — the four checks, with the fourth being the one that
  matters) and `zanii.gov` (public-sector accountability; `appeal_pack` — the state proves what
  its algorithm did to you, and you hold the proof).
- **0.13.0** — `zanii.sentinel`: runtime behavioral monitoring (drift detection over the receipt
  stream, six detectors + operator content hook, injected responses, and tamper-evident
  `sentinel.alert` receipts). Baselines are float-free (integer milli-units) so their hash is
  byte-identical to `@zanii/sentinel`.
- **0.12.0** — real-world provenance: `zanii.provenance` (content credentials — the thin
  anti-deepfake layer), `zanii.custody` (co-signed supply-chain custody chains: a2a handoffs,
  swarm N-party events, pseudonymous item slices), `zanii.decisions` (auditable algorithmic
  decisions: completeness + rule-consistency + committed factors).
- **0.11.0** — per-subject auditability: `zanii.subject` (`subject_tag` — a pseudonymous,
  platform-scoped, signature-covered receipt field + `fetch_subject_history` offline verification of
  exactly one end user's slice via `GET /v1/subjects/{tag}`); `record(..., subject_tag=...)` in the SDK.
- **0.10.0** — loophole packages: `zanii.kya` (screen a counterparty before transacting, injected
  sanctions provider), `zanii.swarm` (N-party M-of-N threshold co-signed receipts; now with the
  authority-complete `verify_swarm_receipt` + `build_swarm_receipt`/`swarm_signer` for **SPEC §14
  on-ledger ingest via `POST /v1/swarm`** — sig + delegation + scope + prev + revocation + distinct
  owners), `zanii.attest` (bind which code ran via an attestation claim + injected quote verifier —
  honest by default: no verifier means quote NOT verified).
- **0.9.0** — `zanii.memory`: provable agent memory — hash-chained `memory.write` receipts with
  salted content commitments and tamper-evident links (`append_memory`, `verify_memory_chain`);
  `entry_hash` is RFC 8785 canonical, so chains verify byte-identically against `@zanii/memory` (TS).
- **0.8.0** — UAE compliance: `zanii.retention.build_retention_hold` (kept-records attestation, inverse of
  deletion), `zanii.consent` (PDPL consent receipts), `zanii.admissibility` (bilingual court evidence pack,
  46/2021), `zanii.fta` (filing evidence + `FTA_WALL`), `zanii.walls` (SCA/RERA/TDRA/Legal/Consumer + DIFC/ADGM presets).
- **0.7.0** — discovery & commerce: `zanii.a2a_directory` (resolve a DID to its verified history),
  `zanii.x402` (verify a payment receipt's on-chain settlement), `zanii.erc8004` (register/resolve/verify
  ERC-8004 agent identities).
- **0.6.0** — accountability fixes: **salted payload commitments by default** (`record()` — privacy/PDPL;
  `salted_payload_hash`/`verify_payload`, opt out with `salt=False`); **owner-signed confirmations**
  (`zanii.core.create_confirmation`; `Runtime(owner_did=…)` requires a signed owner approval);
  receipt **provenance** (`runtime_hash`/`model_id`/`manifest_hash`) + `Runtime(intent_receipts=True)`
  two-phase; **infrastructure co-signatures** (`create_cosignature`, segregation of duties) and
  `zanii.compliance.reconcile` (omission catcher).
- **0.5.1** — docs: this page now lists every bundled module + extra (no code change).
- **0.5.0** — framework adapters `zanii.langchain` / `zanii.openai_agents` / `zanii.crewai`
  (extras `zanii[langchain,openai-agents,crewai]`), plus `zanii.retention` and `zanii.redact`.
- **0.4.0** — `zanii.cli` (+ the `zanii` console script), `zanii.compliance`, `zanii.kms`,
  `zanii.witness`, `zanii.policy`, `zanii.payments`, `zanii.embed`, `zanii.connectors`,
  and `zanii.otel` (`zanii[otel]`).
- **0.3.0** — added `zanii.webhooks`, `zanii.testing`, and `zanii.monitor` (+ `zanii-monitor` CLI).
- **0.2.0** — added `zanii.runtime` (deterministic agent rails).
- **0.1.0** — initial release: the client SDK, the pure `zanii.core` verification namespace,
  `verify_audit_bundle`, `py.typed`, and the `zanii.mcp_proxy` (`pip install "zanii[mcp]"`).

## License

Apache-2.0.
