Metadata-Version: 2.4
Name: xenovia-sdk
Version: 0.3.0
Summary: Decision-first Python SDK for policy-aware agent action control
Project-URL: Homepage, https://xenovia.io
Project-URL: Documentation, https://docs.xenovia.io
Project-URL: Source, https://github.com/Xenovia-io/xenovia-sdk-python
Project-URL: Issues, https://github.com/Xenovia-io/xenovia-sdk-python/issues
Keywords: agents,policy,security,governance,sdk
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: Other/Proprietary License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: httpx<1,>=0.23
Provides-Extra: dev
Requires-Dist: build>=1.2.2; extra == "dev"
Requires-Dist: twine>=5.1.1; extra == "dev"
Requires-Dist: ruff>=0.6.9; extra == "dev"
Requires-Dist: mypy>=1.11.2; extra == "dev"

# Xenovia SDK for Python

Decision-first control hook for agent actions.

> **Endpoint:** the SDK talks to the Xenovia runtime's `POST /v1/execute` (runtime 0.2 line and later). The default `endpoint` is the runtime host, `https://runtime.xenovia.io`. Local unreachable fallbacks are not server policy decisions.

Full documentation:

- `docs/SDK_REFERENCE.md` (complete API and mode behavior)

## Core Model

Xenovia decides. Your code executes.

- The SDK sends action intent to Xenovia for policy decisioning.
- The SDK returns a typed response with decision and trace context.
- Local execution stays in your environment, never in Xenovia.

## Before vs After SDK

Before (ad-hoc wiring in each tool integration):

- Request/response shape is custom per tool.
- Block/failed/success handling is inconsistent across agents.
- Sequence tracking and result-to-decision mapping are harder to do reliably.

After (SDK-wrapped integration):

- Every call uses one contract: `operation + payload + session_id + identity + env`.
- Every outcome uses one response object: `status + decision + result + trace_id`.
- You can enforce consistently and map call sequence + outcomes deterministically.

```mermaid
flowchart LR
    subgraph BEFORE["Before SDK (manual wiring)"]
      B1["Agent"] --> B2["Custom tool wrapper(s)"]
      B2 --> B3["Xenovia decision API"]
      B3 --> B4["Local execution"]
      B4 --> B5["Raw / inconsistent tool result handling"]
    end

    subgraph AFTER["After SDK (standardized control hook)"]
      A1["Agent"] --> A2["Xenovia SDK execute/guard"]
      A2 --> A3["Xenovia decision API + trace_id"]
      A3 --> A4{"decision"}
      A4 -- "deny" --> A5["blocked response"]
      A4 -- "allow or redact" --> A6["Local execution"]
      A6 --> A7["Unified XenoviaResponse<br/>status + decision + result + trace_id"]
      A7 --> A8["Sequence mapping + behavior controls"]
    end
```

## Execution Flow

```mermaid
flowchart TD
    A["Agent / App"] --> B["Xenovia SDK (execute/guard)<br/>infers operation from module.function"]
    B --> C["Xenovia decision API<br/>policy decision + trace_id"]
    C --> D{"Decision"}
    D -- "deny" --> E["Blocked response<br/>status=blocked + trace_id"]
    D -- "allow" --> F["Local tool execution<br/>(your infra)"]
    F --> G["Capture actual result/outcome"]
    G --> H["Return unified response<br/>decision + result + trace_id"]
    H --> I["Sequence mapping<br/>session_id + operation + call order"]
    I --> J["Behavior controls<br/>detect/limit duplicate or multi-call patterns"]
```

## Installation

```bash
pip install xenovia-sdk
```

For local development:

```bash
pip install -e ".[dev]"
```

## Quick Start

Operation is inferred automatically from the calling module and function name — you do not need to name it.

```python
from xenovia_sdk import Xenovia

xenovia = Xenovia(
    api_key="xe_...",
    default_env="prod",
    auto_session=True,
)

# operation inferred as "payments.transfer" when called from payments.py
decision = xenovia.execute({"service": "checkout", "version": "v2"})

if decision.is_blocked():
    print("Blocked; see the trace in the console:", decision.trace_id)
elif decision.is_success():
    print("Allowed:", decision.trace_id)
else:
    print("Failed:", decision.error)
```

## Simulation-ready in three lines

Xenovia Simulation talks to your agent like a user would, and sends an `X-Xenovia-Session-Id` header with every turn. To let Xenovia see and apply its checks to what the agent does, the agent's model calls must go through the Xenovia runtime and carry that header **exactly as received**. For a Python web agent that is three lines:

```bash
pip install "xenovia-sdk>=0.3.0"
export XENOVIA_API_KEY=xe_...            # an API key for the Agent
export XENOVIA_AGENT_ID=<agent id>       # the Agent ID shown in Xenovia
# export XENOVIA_RUNTIME_URL=...         # only for a hybrid runtime; default https://runtime.xenovia.io
```

```python
from openai import OpenAI
from xenovia_sdk import XenoviaASGIMiddleware, openai_client_kwargs

app.add_middleware(XenoviaASGIMiddleware)        # FastAPI / Starlette: read the header from each request
client = OpenAI(**openai_client_kwargs())         # model calls go through Xenovia and forward it
```

- **Flask:** `app.wsgi_app = XenoviaWSGIMiddleware(app.wsgi_app)`. **Django:** wrap the WSGI or ASGI application, for example `application = XenoviaWSGIMiddleware(get_wsgi_application())`.
- **Async OpenAI:** `AsyncOpenAI(**openai_client_kwargs(async_=True))`.
- **LangChain:** `ChatOpenAI(model="gpt-4o-mini", **openai_client_kwargs(), http_async_client=xenovia_async_http_client())`. `ChatOpenAI` uses `http_client` for sync calls and `http_async_client` for async ones, so pass both unless the agent is purely sync. The model name is a placeholder; the Agent's configured model is used.
- **Anthropic and other providers:** the runtime endpoint speaks the OpenAI format for every provider the Agent uses, Anthropic included, so use an OpenAI-compatible client as above. The `anthropic` SDK's own Messages API is not served by the endpoint.
- **Any other `httpx`-based client:** pass `http_client=xenovia_http_client()` (or `xenovia_async_http_client()`).
- **SDK checks:** inside a request, `execute()`, `@guard()` and every hook send the same header value as `session_id` when you don't pass one.

`openai_client_kwargs()` returns `{"base_url": "{XENOVIA_RUNTIME_URL}/{XENOVIA_AGENT_ID}/v1", "api_key": XENOVIA_API_KEY, "http_client": ...}` and raises `ValueError` naming the missing variable. Build the model client once, at startup: the session is looked up per request, not when the client is built.

The header value is opaque. A simulation sends a signed value (`xsim1.…`) that tells Xenovia which run, mode and model this turn belongs to. An altered value fails verification and the runtime rejects the call with `400`; a dropped header means Xenovia cannot tie the call to the run, so the simulation only sees the conversation. The SDK never parses or alters the value. Outside a request (a queue worker, a script, or a thread you start yourself, since threads do not inherit the request's context), set it with `with session_scope(value): ...`, and read it with `current_session()`.

## Guard Modes

`guard()` wraps existing tool functions with decision-aware control. Operation is inferred from the decorated function's module and name.

```python
# operation inferred as "k8s.deploy" when defined in k8s.py
@xenovia.guard(mode="enforce")
def deploy(payload):
    return kubectl_apply(payload)
```

`guard()` always applies what Xenovia decided: `allow` runs the function, `redact` runs it with the masked arguments Xenovia returned, `deny` skips it, and an escalated `allow` runs it while the operator is asked. Whether a check only watches (Monitor) or acts (Enforce) is set per check in the Xenovia console, so the SDK's old `observe` mode is gone in 0.2.0.

## Hooks: one call per stage

Frameworks that expose lifecycle hooks call one method per stage. Each returns a `XenoviaResponse`; `is_blocked()`, `is_redacted()` and `is_escalated()` tell you what to do, and `response.payload` carries the material after redaction.

```python
xenovia.next_turn()                                   # once per conversation turn
xenovia.model_pre(messages, system_prompt=..., tools=...)   # leave off when model calls use the runtime inference URL
xenovia.model_post(reply_text, messages=messages)
xenovia.tool_pre("send_email", {"to": "a@b.com"})    # before the tool runs
xenovia.tool_post("send_email", tool_output)         # before the agent reads the output
xenovia.memory_write(content)                        # before memory is saved
xenovia.context_summary(summary, original)           # before a summary replaces the conversation
```

When the agent's model calls go through the runtime inference URL, `https://runtime.xenovia.io/{agent_id}/v1`, the runtime checks those model calls: call only the tool, memory and summary hooks, and pass that session's ID as `session_id` so every decision lands on the same session.

`model_pre` and `model_post` send each message as `{role, content}` with text content and each tool as `{name, description}`. Text parts, refusal parts and the text of Anthropic `tool_result`, `mcp_tool_result` and `search_result` blocks are joined and checked; media and file parts, the model's own tool calls and thinking, and Anthropic server tool results (web search, web fetch, code execution) are not sent. Any other part type, or a malformed message, role, content or tool, raises `ValueError` before anything is sent. `response.payload` holds your own message and tool objects, with any redaction written in.

For an agent that delegates to others, `child = xenovia.subagent(role="researcher")` gives the subagent a client with the same key, so Xenovia treats it as the same agent. It gets its own session and sends its role and one more level of depth.

When Xenovia cannot be reached the SDK blocks by default (`unreachable_mode="block"`); `"error"` raises and `"allow"` lets the call through and must be chosen deliberately.

## API Surface

```python
Xenovia(
    api_key: str,
    endpoint: str = "https://runtime.xenovia.io",
    default_env: str = "prod",
    raise_on_block: bool = False,
    timeout: int = 65,
    auto_session: bool = False,
    debug: bool = False,
    identity_id: str | None = None,
    identity_type: str = "agent",
    unreachable_mode: str = "block",
    allow_insecure_http: bool = False,
)
```

Primary methods:

- `execute(payload, operation=None, session_id=None, env=None) -> XenoviaResponse`
- `guard(operation=None, mode="enforce") -> decorator`

Integration helpers (`xenovia_sdk.integration`, also importable from `xenovia_sdk`):

- `XenoviaASGIMiddleware(app)`, `XenoviaWSGIMiddleware(app)`
- `current_session() -> str | None`, `session_scope(value)` (context manager)
- `xenovia_http_client(**httpx_kwargs)`, `xenovia_async_http_client(**httpx_kwargs)`
- `openai_client_kwargs(async_=False) -> {"base_url", "api_key", "http_client"}`

`capability=` is accepted on both as a deprecated alias of `operation=` and emits a `DeprecationWarning`.

Operation is inferred as `module.function_name` when not provided. It can always be overridden explicitly.

`XenoviaResponse` fields:

- `status`: `success` | `blocked` | `failed`
- `result`: local function output (if executed via `guard`)
- `error`: string error when present
- `decision`: decision payload (`outcome`, `escalated`)
- `trace_id`: request trace identifier
- `payload`: the material after redaction

## Wire Contract

SDK request envelope:

```json
{
  "stage": "tool_call",
  "operation": "payments.transfer",
  "payload": { "...": "..." },
  "session_id": "sess_123",
  "identity": { "type": "agent", "id": "agent_7" },
  "env": "prod",
  "sdk": { "version": "0.3.0", "language": "python" }
}
```

The key alone identifies the agent; `identity`, `env` and `sdk` are informational.

Typical response shape (a deny, HTTP 403):

```json
{
  "status": "blocked",
  "decision": { "outcome": "deny", "escalated": false },
  "payload": {},
  "trace_id": "0b6f6c3e-7d4a-4c0e-9c59-2f3e7a1c5b90"
}
```

The runtime never returns a reason or rule ID; the reason is on the session in the console, and `trace_id` finds it.

## Security Defaults

The SDK ships with opinionated safety defaults:

- HTTPS endpoint enforcement by default (`allow_insecure_http=False`).
- If `allow_insecure_http=True`, only localhost/loopback HTTP endpoints are permitted.
- No secret or payload logging in normal operation.
- Explicit fail-mode for Xenovia outages:
  - `unreachable_mode="block"` (fail-closed, default)
  - `unreachable_mode="error"`
  - `unreachable_mode="allow"` (fail-open)
- Structured identity metadata on every request.
- Timeout required and validated.
- HTTP errors and invalid decision responses fail closed. A valid policy denial returned with HTTP 403 remains a blocked response; other unsuccessful HTTP responses raise `XenoviaExecutionError` with the runtime's error text and trace ID.
- Explicit, consistent success or allow fields are required for enforced execution. Unknown or contradictory decision fields raise `XenoviaExecutionError`.

Network-unreachable fallbacks remain configurable. Synthetic fallback responses have `rule_id="SDK_UNREACHABLE_ALLOW"` or `"SDK_UNREACHABLE_BLOCK"` and `trace_id=None`; they do not establish that Xenovia evaluated a policy. HTTP or response-validation errors never use the `unreachable_mode="allow"` fallback.

## Production Configuration Example

```python
import os
from xenovia_sdk import Xenovia

xenovia = Xenovia(
    api_key=os.environ["XENOVIA_API_KEY"],
    endpoint=os.environ.get("XENOVIA_ENDPOINT", "https://runtime.xenovia.io"),
    default_env=os.environ.get("XENOVIA_ENV", "prod"),
    identity_id=os.environ.get("XENOVIA_AGENT_ID", "payments-agent"),
    auto_session=True,
    raise_on_block=False,
    unreachable_mode="block",  # fail closed for sensitive environments
)
```

## Development

Run tests:

```bash
python -m unittest discover -s tests -v
```

## Publishing and Security Docs

- See `PUBLISHING.md` for release workflow and publishing checklist.
- See `SECURITY.md` for vulnerability reporting and operational controls.
- See `CHANGELOG.md` for release history.
- See `docs/SDK_REFERENCE.md` for full mode matrix and behavior reference.

## CI and Release Automation

- `.github/workflows/ci.yml` runs tests, builds the package, and checks metadata.
- `.github/workflows/publish.yml` is manual (`workflow_dispatch`) and supports separate targets: `testpypi` and `pypi`.
- `.github/dependabot.yml` keeps dependencies and GitHub Actions updated weekly.
