Metadata-Version: 2.4
Name: kyvvu
Version: 0.23.0
Summary: Python SDK for AI compliance monitoring and policy enforcement under the EU AI Act
Author-email: "Kyvvu B.V." <info@kyvvu.com>
License: Copyright 2026 Kyvvu B.V.
        
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
        
        http://www.apache.org/licenses/LICENSE-2.0
        
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
        
        This license applies only to the contents of the kyvvu-sdk/ directory
        of the Kyvvu monorepo. Other directories in this monorepo are governed
        by their own LICENSE files.
Project-URL: Homepage, https://github.com/kyvvu/platform
Keywords: ai,compliance,eu-ai-act,monitoring,logging,policy-enforcement
Classifier: Development Status :: 4 - Beta
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
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
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: kyvvu-engine<1.0.0,>=0.13.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: typer>=0.12
Requires-Dist: rich>=13
Requires-Dist: httpx>=0.27
Requires-Dist: tomli-w>=1.0
Requires-Dist: tomli>=2.0; python_version < "3.11"
Provides-Extra: serve
Requires-Dist: kyvvu-engine[serve]<1.0.0,>=0.13.0; extra == "serve"
Provides-Extra: dev
Requires-Dist: pytest>=7.4.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: jsonschema<5,>=4.23; extra == "dev"
Requires-Dist: rfc3339-validator>=0.1.4; extra == "dev"
Requires-Dist: ruff>=0.16.9; extra == "dev"
Requires-Dist: mypy>=1.0.0; extra == "dev"
Requires-Dist: types-PyYAML>=6.0; extra == "dev"
Dynamic: license-file

# Kyvvu SDK

The Agent Security Kernel (ASK) for Python agents. Enforce security and safety policies on every agent action before it runs — stopping data leakage and destructive actions — with EU AI Act, OWASP, and GDPR compliance as a bonus.

## Get started in 2 minutes

```bash
pip install kyvvu
kyvvu auth              # log in via device code (no password)
# then: open the dashboard, go to Workspace → API Keys, and create one
kyvvu init my-agent     # scaffold a demo agent
cd my-agent && python agent.py
```

`kyvvu serve` (the HTTP server for non-Python agents) needs two more packages.
Install them with `pip install "kyvvu[serve]"`.

The demo agent runs four steps: a data fetch, an LLM call, a reply to the user, and a code execution. The reply draws an EU AI Act warning (model output delivered unmarked, with no AI disclosure), and the code execution is blocked by the OWASP security policy — a compliance finding and a security stop, showing runtime enforcement in action.

**Free tier:** 1,000 active agent-hours/month at no cost. See https://kyvvu.com/pricing for details.

**Docs:** https://docs.kyvvu.com · **Issues:** https://github.com/Kyvvu/issues · **License:** Apache 2.0 (SDK), BSL 1.1 (engine)

---

## What the SDK does

1. **Registers your agent** with the Kyvvu API (`POST /api/v1/agents`) on
   startup. This is a real HTTP call that acquires an `agent_id` and
   evaluates agent-registration policies.
2. **Evaluates every step** your agent takes against loaded policies *before*
   execution. Policies are fetched from the API and cached (this is done by
   `kyvvu-engine`, which is included as a dependency).
3. **Records completed steps** into an in-memory per-task history so that
   path-dependent policies (predecessors, sequences, rate limits) work.
4. **Queues the audit trail** for delivery to the Kyvvu API at the latest by `end_task()`; a task may be delivered in several batches (a background worker sends them; a short script calls `kv.flush()` before it exits).

The SDK makes HTTP calls at two points:
- **Agent registration** — `POST /api/v1/agents` (once at startup).
- **Policy fetch** — `GET /api/v1/policies` (on first evaluation, then
  every `KV_POLICY_TTL_SECONDS`; handled by `kyvvu-engine`).
- **Log flush** — `POST` to the configured log endpoint (at the latest by
  `end_task()`, possibly in several batches; handled by `kyvvu-engine`, off
  by default).
- **Incident webhook** — `POST` to the configured incident endpoint (on
  policy violation; handled by `kyvvu-engine`, off by default).

---

## Quickstart

```python
from kyvvu import Kyvvu, ActionKind, Verb

kv = Kyvvu(api_key="KvKey-...", agent_key="my-bot")
kv.register_agent(
    name="My Bot",
    purpose="Customer support triage and response",
    # Step names of the tool steps (step.resource / step.exec /
    # step.credential) this agent runs. The bundled baseline every
    # registered agent gets blocks any tool step not on this list.
    declared_tools=["read_ticket"],
)

@kv.step(ActionKind.step_model)
def chat(prompt: str) -> str:
    return llm.complete(prompt)

@kv.step(ActionKind.step_resource, Verb.GET)
def read_ticket(ticket_id: str) -> dict:
    return db.get_ticket(ticket_id)

task_id = kv.start_task()
ticket = read_ticket("T-1")
result = chat(f"Reply to: {ticket['subject']}")
kv.end_task()
```

### Bring-your-own identity

```python
# If agent_id is provisioned externally (Terraform, config file, admin console):
kv = Kyvvu(api_key="KvKey-...", agent_key="my-bot", agent_id="ag_abc123")
# No register_agent() call needed — start using @kv.step immediately.
```

### Task lifecycle (programmatic API)

```python
task_id = kv.start_task()
try:
    result = my_agent_function()
except Exception as e:
    kv.error_task(error=e)
    raise
else:
    kv.end_task()
```

All three methods accept optional `context=`, `properties=`, and `meta=` kwargs for template matching and caller overrides.
When work continues in another request or thread **of the same process, on the
same `Kyvvu` instance**, call `kv.resume_task(task_id)` in that context before
recording a step or closing the task. `add_step()`, `end_task()`, `idle_task()`,
and `error_task()` also accept `task_id=` directly.
The SDK never selects a task just because it is the only one open.

A task is written only by the client that started it, between `start_task()`
and `end_task()` / `error_task()`. A step, idle marker or end into any other
task raises `KyvvuConfigError`: in 1.0 a task cannot be continued after it has
ended, or from another process. Starting a task whose id is already open in
this client is refused too, and **a `task_id` must never be reused** — not after
the task ended, and not across processes. Each step's `action_id` (an optional
`add_step()` argument) must be unique within its task, except to pair an
intended step with its completion; a duplicate raises `ValueError`.

Identifiers follow a fixed grammar, because they are hashed into the audit
trail and used as storage keys: `task_id` is letters, digits and `. _ : -`,
1-100 characters; `action_id` the same alphabet, 1-255; `step_name` any text of
1-255 characters without control characters. A `task_id` you pass to
`start_task()`, `resume_task()`, `end_task()` or `add_step()` (and an
`action_id` or `step_name` you pass to `add_step()`) that breaks the rule raises
`KyvvuValidationError` naming the field and the rule, before anything is
recorded. Generated ids always comply. Names and ids taken from your code or a
framework (a function or tool name, a framework run id) are adjusted instead
of refused: control characters become U+FFFD, names are cut to 255 characters,
and an id that does not fit becomes `x-` plus 32 hex digits of its SHA-256.
See `docs/concepts/tasks.md`, "Identifier rules".

---

## Integration modes

The SDK supports three integration patterns. All produce the same stream of
`Behavior` objects; they differ in how agent actions are captured:

1. **Decorator** (`@kv.step`) — for custom Python agents.
2. **LangChain / LangGraph callback handler** — `KyvvuLangChainHandler` (shared,
   works for both) and `KyvvuLangGraphHandler` (adds node metadata).
3. **CrewAI listener** — `KyvvuCrewAIListener`, wired to the CrewAI event bus.

### 1. Decorator integration (`@kv.step`)

For custom Python agents. Wrap each function with `@kv.step(kind, verb)`.
The decorator handles evaluate → execute → record automatically.

```python
from kyvvu import Kyvvu, ActionKind, Verb, RiskClassification

kv = Kyvvu(
    api_key="KvKey-...",
    agent_key="gmail-assistant",
    risk_classification=RiskClassification.HIGH,
)
kv.register_agent(
    name="Gmail Assistant",
    purpose="Reads the inbox and drafts replies for a human to approve",
    declared_tools=["send_reply"],
)

class GmailAgent:
    @kv.step(ActionKind.task_start)
    def fetch_email(self):
        return self._read_inbox()

    @kv.step(ActionKind.step_model,
             properties={"model": "gpt-4o"})
    def generate_reply(self, email):
        return llm.complete(email["body"])

    @kv.step(ActionKind.step_resource, Verb.POST)
    def send_reply(self, email, reply):
        return gmail.send(email["from"], reply)

    @kv.step(ActionKind.task_end)
    def finish(self):
        pass  # queues the audit log for delivery
```

See `examples/custom-agent/gmail-agent/agent.py` for a full working example.

### 2. LangChain / LangGraph callback handler

Install the integration with `pip install kyvvu-langchain`.

For LangChain-based agents. Construct a `Kyvvu` instance, register the agent,
then pass a `KyvvuLangChainHandler` as a callback. LLM calls, tool invocations,
and agent decisions are captured automatically.

```python
from kyvvu import Kyvvu
from kyvvu.schemas import Environment, RiskClassification
from kyvvu_langchain import KyvvuLangChainHandler

kv = Kyvvu(
    api_key="KvKey-...",
    agent_key="finance-agent",
    environment=Environment.DEVELOPMENT,
    risk_classification=RiskClassification.LIMITED,
    read_only_tools=["search"],
)
kv.register_agent(
    name="Finance Agent",
    purpose="Stock ticker lookup and portfolio analysis for internal use",
    declared_tools=["search"],  # the LangChain tool's name; others are blocked
    metadata={"framework": "langchain", "tools": ["search"]},
)

handler = KyvvuLangChainHandler(kv)
result = agent.invoke(query, config={"callbacks": [handler]})
```

The handler is a pure adapter — it does not manage identity or registration.
Same `Kyvvu()` + `register_agent()` pattern as the decorator integration.
Callback tools record `POST` unless their exact name is in `read_only_tools`; `write_tools` explicitly declares writes. Both are constructor-only. A tool with `data.*` or `target.trust` properties needs one of these declarations or raises `KyvvuConfigError` when recorded. CrewAI declarations are matched after its tool-name sanitization. Retriever and message verbs are unaffected.

See `examples/langchain-agent/finance-agent/agent.py` for a full working example.

For LangGraph, the shared `KyvvuLangChainHandler` works (LangGraph runs on
`langchain_core` callbacks); pass it via `config={"callbacks": [handler]}`. Use
`KyvvuLangGraphHandler` (from `kyvvu_langchain`) to additionally capture
node metadata (`langgraph.node_name`) and map `GraphInterrupt` to `step.gate`.

### 3. CrewAI listener

For CrewAI crews. Install `kyvvu-crewai`; `KyvvuCrewAIListener` (`kyvvu_crewai`) registers
synchronous before-call hooks to enforce tool and model policies, and uses the
event bus for task boundaries and messages. A blocked tool or model call never
executes; the crew aborts, the engine records the blocked step, and the
listener closes the task with `task.error`. `listener.blocked_exception` retains the original policy block.

### Behaviour templates

All three integrations use YAML templates to map framework events to the v0.05
atomic behaviour vocabulary (`step.model`, `step.resource`, `task.start`, etc.).
Every SDK `task.start` declares the pinned AAG version as
`aag_version: "0.7.0"`. This declares conformance to the pinned vocabulary.
The template engine lives in `kyvvu_engine.templates`; each package ships its
own template, which the SDK loader finds by name:

```python
from kyvvu.templates import load                  # installed package templates
from kyvvu_engine import BehaviorTemplate  # engine: the template engine
from kyvvu_langchain import KyvvuLangChainHandler

dec = load("decorator")
lc  = load("langchain")

# Custom template from file
custom = BehaviorTemplate.from_path("/path/to/template.yaml")
kv = Kyvvu(api_key="...", agent_key="bot", template=custom)   # decorator + start_task
handler = KyvvuLangChainHandler(kv, template=custom)          # a framework handler
```

Or set `KV_TEMPLATE_LOCATION` to a YAML file path.

- **An integration's template governs both its steps and the task boundaries it
  opens.** A custom template **replaces** the built-in, it does not extend it,
  so it must contain a rule for each boundary (the `Kyvvu` client needs all four
  `task.*` types; a LangChain handler needs `on_chain_start`, `on_chain_end`
  and `on_chain_error`). This is checked when the client or
  handler is built. Print a built-in to start from:
  `kyvvu template show langchain > my.yaml` (`decorator`, `langchain`,
  `langgraph`, `crewai`).
- The default `template` is the sentinel `kyvvu.default_template`.
  `template=None` means no template: `@kv.step` and `kv.add_step` still work,
  `start_task()` refuses, and the callback handlers refuse it.
- Templates are validated when loaded: every rule needs a unique `id`, a rule
  has only `id`, `description`, `match` and `behavior`, and `behavior` only
  `kind`, `step_name`, `verb` and `properties`. There is one name key,
  `name` / `name_pattern` (a case-insensitive `re.search`), on every surface.
- A callback event the template has no rule for is recorded as `step.unknown`.
- A framework handler **owns the task it opens**: do not wrap it in
  `kv.start_task()` (it raises if a task is already active), and do not put
  `@kv.step` on a tool the handler runs (it would record the call twice and
  raises).
- A policy block never ends a task. The blocked step is recorded,
  `KyvvuBlockedError` is raised, and the task stays open: call `error_task()`
  or `end_task()`, or record an approval gate and retry.
- A decorated `step.gate` passes unless it raises `kyvvu.GateDenied`.

### Async support

The `@kv.step` decorator automatically detects `async def` functions and wraps them correctly:

```python
@kv.step(ActionKind.step_model)
async def chat(prompt: str) -> str:
    return await openai_client.chat.completions.create(
        model="gpt-4o", messages=[{"role": "user", "content": prompt}]
    )
```

Policy evaluation and recording are synchronous (sub-millisecond, in-process) — only the decorated function call is awaited. Error handling, blocked-step propagation, and task lifecycle all work identically to sync functions.

---

## Project structure

```
kyvvu-sdk/
├── kyvvu/
│   ├── __init__.py              # Public API surface (__all__)
│   ├── __version__.py           # SDK version string
│   ├── core.py                  # Kyvvu class — registration, task API, runner
│   ├── schemas.py               # Enums, Behavior, EvalContext (re-exports from engine)
│   ├── exceptions.py            # Exception hierarchy + KyvvuBlockedError
│   ├── logging.py               # setup_logging re-export from engine
│   ├── _task_context.py         # ContextVar for active task_id
│   ├── _limits.py               # Truncation constants for input/output capture
│   ├── templates/               # SDK template and installed integration template lookup
│   │   ├── __init__.py          # load(name) — find a template by name
│   │   └── decorator.template.yaml
│   ├── integrations/
│   │   ├── __init__.py          # FrameworkAdapter export
│   │   ├── _base.py             # FrameworkAdapter base class
│   │   ├── decorator.py         # @kv.step implementation
│   └── cli/
│       ├── main.py              # Typer app (kyvvu command)
│       ├── auth.py              # auth (device-code login), logout, whoami
│       ├── agents.py            # list-agents
│       ├── policies.py          # list-policies
│       ├── manifests.py         # list-manifests, assign-manifest, list-assignments, unassign-manifest
│       ├── config.py            # config management
│       ├── init_cmd.py          # kyvvu init (scaffold project)
│       ├── serve.py             # kyvvu serve (local engine server)
│       └── client.py            # HTTP client for CLI commands
├── tests/
│   ├── conftest.py
│   ├── test_decorator*.py       # Decorator integration tests
│   ├── test_programmatic_task_api.py
│   ├── test_identity_acquisition.py
│   ├── test_register_agent_side_effects.py
│   ├── templates/               # Template matching/loading tests
│   ├── integrations/
│   │   └── test_framework_adapter_base.py
│   └── cli/                     # CLI command tests
├── pyproject.toml
├── pytest.ini
└── .env.example

kyvvu-langchain/
├── kyvvu_langchain/            # LangChain and LangGraph handlers and templates
├── tests/                      # Framework regression and AAG conformance tests
└── pyproject.toml
```

---

## Configuration

The `Kyvvu` constructor accepts explicit kwargs or reads from environment
variables. Precedence: kwargs > env vars > `.env` in cwd > defaults.

| Parameter | Env var | Default | Purpose |
|-----------|---------|---------|---------|
| `api_url` | `KV_API_URL` | `https://platform.kyvvu.com` | Kyvvu API base URL |
| `api_key` | `KV_API_KEY` | — | Bearer API key (`KvKey-...`) |
| `agent_key` | `KV_AGENT_KEY` | — | Stable agent identifier for policy fetch |
| `agent_id` | — | — | Pre-provisioned agent ID (skips registration) |
| `environment` | `KV_ENVIRONMENT` | `production` | Deployment environment. The argument wins, then `KV_ENVIRONMENT`, then `production`; set `KV_ENVIRONMENT=development` for local work |
| `risk_classification` | — | `minimal` | EU AI Act risk tier |
| `template` | `KV_TEMPLATE_LOCATION` | `kyvvu.default_template` | A `BehaviorTemplate` (replaces the built-in), the default sentinel (the built-in, or the YAML file named by `KV_TEMPLATE_LOCATION`), or `None` (no template) |
| `timeout` | — | `10` | HTTP timeout (seconds) |
| `log_location` | `KV_LOG_LOCATION` | `auto` | WHERE logs go: URL, file path, `stdout`, `none`, or `auto` — the platform when it is the policy source, else `stdout` (#357). |
| `log_format` | `KV_LOG_FORMAT` | `kv` | HOW logs are formatted: `kv`, `json`, or `otlp`. |

For the complete environment-variable reference (engine-level settings such as
`KV_POLICY_TTL_SECONDS`, resilience options, etc.), see the
[Configuration Reference](../docs/deployment/configuration.md).

---

## CLI

The SDK includes a CLI (`kyvvu` command) for development and debugging:

```bash
kyvvu --version
kyvvu auth                  # log in via device code (no password)
kyvvu logout                # clear session
kyvvu whoami                # show current user

kyvvu list-agents           # list registered agents
kyvvu list-policies         # list policies (--agent-id for per-agent)
kyvvu list-manifests        # list manifests from connected repos
kyvvu assign-manifest       # assign manifest to agent
kyvvu unassign-manifest     # remove assignment
kyvvu list-assignments      # list current assignments

kyvvu init my-agent         # scaffold a new agent project
kyvvu serve                 # start local policy evaluation server (pip install "kyvvu[serve]")
```

Install CLI dependencies (included by default): `typer`, `rich`, `httpx`.

---

## Development

```bash
# Install all workspace packages from the repo root:
uv sync --all-packages --all-extras

# Run the SDK tests
cd kyvvu-sdk
python -m pytest tests/ -v

# Type checking
mypy --strict kyvvu/

# Linting
ruff check kyvvu/ tests/
```

---

## Public API surface

The following symbols are the public API (`kyvvu.__all__`):

**Core**: `Kyvvu`, `default_template`, `get_current_task_id`, `setup_logging`. Set `agent_version=` and `framework=` on `Kyvvu(...)` to include them on each `task.start`.

**Exceptions**: `KyvvuError`, `KyvvuAPIError`, `KyvvuBlockedError`,
`GateDenied`, `KyvvuConfigError`, `KyvvuKeyRevokedError`, `KyvvuRateLimitError`,
`KyvvuTimeoutError`, `KyvvuValidationError`

**Vocabulary**: `ActionKind`, `Verb`, `TASK_BOUNDARY_KINDS`, `Behavior`, `EvalContext`,
`EvalResult`, `PolicyResult`, `Action`

`TASK_BOUNDARY_KINDS` is the frozen set of the four action kinds that mark
task boundaries (`task.start`, `task.end`, `task.error`,
`task.idle`) — use it to tell them apart from the eight steps that
describe what an agent does inside a task. `Behavior` is constructed from
`kind` and rejects unknown kwargs.

**Agent registration**: `Environment`, `RiskClassification`

**Submodule exports** (importable from submodules):
- `kyvvu.templates.load` — load a core or installed integration template by name (the template
  engine `BehaviorTemplate` / `deep_merge` / `load_template` live in
  `kyvvu_engine.templates`)
- `kyvvu.integrations.FrameworkAdapter`
- `kyvvu_langchain.KyvvuLangChainHandler` (install `kyvvu-langchain`)

---

## Releasing

1. Edit `VERSIONS` at the repo root.
2. Run `./scripts/bump-version.sh`.
3. Merge to `main`.
4. Tag: `git tag sdk-v0.x.y && git push origin sdk-v0.x.y`.

---

## Licence

The Kyvvu SDK is licensed under the **Apache License 2.0**. See `LICENSE`
in this directory.

**Important:** The SDK depends on `kyvvu-engine` at runtime, which is
separately licensed under the **Business Source License 1.1** (BSL 1.1).
The SDK's permissive license does not extend to the engine. Bundling,
vendoring, or depending on the SDK does not grant rights to the engine
beyond what BSL 1.1 permits. See `kyvvu-engine/LICENSE` for the engine's
terms.

Production use of the engine requires a Kyvvu commercial subscription
or license agreement: licensing@kyvvu.com

By using Kyvvu you agree to the
[Terms of Service](https://kyvvu.com/terms-of-service/),
[Privacy Policy](https://kyvvu.com/privacy-policy/), and
[Acceptable Use Policy](https://kyvvu.com/aup/).
