> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sovseal.com/llms.txt
> Use this file to discover all available pages before exploring further.

# sovseal-sdk: Python SDK Reference for Agent Memory

> Complete reference for sovseal-sdk (PyPI) — install, AgentStateClient configuration, local store/recall semantic memory, snapshot/restore/lineage replication methods, and error handling.

The `sovseal-sdk` package (PyPI) gives you a programmatic Python client for the sovseal zero-knowledge memory replication protocol and local semantic memory engine. Cryptographic operations — AES-256-GCM encryption and SHA-256 payload hashing — run entirely client-side via the `cryptography` package before any data leaves your process.

## Install

```bash theme={null}
pip install sovseal-sdk
```

Requires Python 3.9+. Uses `httpx` for the replication HTTP transport.

## Configuration

```python theme={null}
from sovseal import AgentStateClient

client = AgentStateClient(
    endpoint="https://ksrlmubaxzwufziwarps.supabase.co/functions/v1/v2-agent-state",
    api_key="sov_live_abc123...",  # or a project token: "sov_proj_..."
)
```

`AgentStateClient` also supports the context-manager protocol, which closes both the native-host IPC transport and the underlying `httpx.Client`:

```python theme={null}
with AgentStateClient(endpoint="...", api_key="...") as client:
    client.store("User prefers dark mode")
```

| Parameter          | Type           | Required                | Notes                                                                                                        |
| ------------------ | -------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------ |
| `endpoint`         | `str`          | For replication methods | Base Edge Function URL. Not needed for `store`/`recall` alone.                                               |
| `api_key`          | `str`          | For replication methods | `sov_live_...` or `sov_proj_...`. Not needed for `store`/`recall` alone.                                     |
| `client`           | `httpx.Client` | No                      | Bring your own configured `httpx.Client` (timeouts, proxies, retries). Defaults to a plain `httpx.Client()`. |
| `native_host_path` | `str`          | No                      | Override the native host launcher path. Defaults to `~/.sovseal/native-host/run.sh` (`run.cmd` on Windows).  |

## Method catalog

`sovseal-sdk` covers the same two subsystems as the Node SDK: **local semantic memory** (`store`, `recall`), which talks to a native host process over framed IPC and never touches the network, and **zero-knowledge state replication** (`snapshot`, `restore`, `restore_at`, `lineage`), which talks to your configured `endpoint`.

<Note>
  `store`/`recall` require the native host launcher at `~/.sovseal/native-host/run.sh`, which `sovseal-sdk` does not install itself. Run `npx -y @sovseal/mcp-server` once (or its installer, `sovseal-install-native-host`) to register it — the same host also serves the browser extension, `@sovseal/sdk`, and `@sovseal/mcp-server`'s own tools. Without it, `store`/`recall` raise `EngineUnavailableError("not-installed")`.
</Note>

### `store(content: str) -> dict`

Stores a memory in the local ONEBRAIN engine.

```python theme={null}
result = client.store("User prefers dark mode in the dashboard")
print(result["id"], result["reinforced"])
```

* `content` — non-empty string, max 65,536 characters (validated client-side; raises `ValueError` if violated).
* Returns `{"id": str, "reinforced": bool, "redacted": int, "redactedRules": list[str]}`. `reinforced` is `True` when the content deduplicated against an existing memory instead of inserting a new row.

### `recall(query: str, top_k: int = 3) -> list[dict]`

Retrieves memories relevant to a query, ranked by composite score.

```python theme={null}
hits = client.recall("frontend stack preferences", top_k=5)
for hit in hits:
    print(hit["score"], hit["text"])
```

* `query` — non-empty string.
* `top_k` — integer, `1`–`20`. Defaults to `3` if omitted (unlike `@sovseal/sdk`, which has no client-side default).
* Returns a list of `{"id": str, "text": str, "score": float}`, highest score first.

### `snapshot(...) -> dict`

Encrypts `active_context` client-side with AES-256-GCM and submits a zero-knowledge snapshot envelope.

```python theme={null}
import os

key_bytes = os.urandom(32)  # 256-bit AES key — store this in your KMS

receipt = client.snapshot(
    agent_id="agent-id-hash",
    sequence_number=0,
    active_context={"content": "User prefers dark mode"},
    key_bytes=key_bytes,
    parent_snapshot=None,
    policy_hash="0" * 64,
)

print(receipt["snapshot_id"])
```

| Parameter         | Type    | Required | Notes                                                              |
| ----------------- | ------- | -------- | ------------------------------------------------------------------ |
| `agent_id`        | `str`   | Yes      | Stable identifier for this agent. Never sent in plaintext.         |
| `sequence_number` | `int`   | Yes      | Monotonically increasing.                                          |
| `active_context`  | `dict`  | Yes      | Free-form JSON representing the agent's current working state.     |
| `key_bytes`       | `bytes` | Yes      | 32 raw bytes (256-bit AES key). The key never leaves your process. |
| `parent_snapshot` | `str`   | No       | Snapshot ID of the preceding checkpoint.                           |
| `policy_hash`     | `str`   | No       | 64-char hex SHA-256 of your policy document.                       |
| `timestamp`       | `int`   | No       | Unix ms. Defaults to the current time.                             |

<Warning>
  **Known issue, `sovseal-sdk` 1.1.0:** this method's client-side validation currently rejects `sequence_number=0` (`raise ValueError` for anything `< 1`), but the server requires **exactly `0`** for an agent's first snapshot — `sequence_number=1` will be rejected server-side with `409 sequence_gap` for a new agent. As shipped, **`snapshot()` cannot succeed for a brand-new agent via any input.** Existing agents with prior snapshots (continuing from `sequence_number >= 1`) are unaffected. Tracked in `logs/escalation/PYTHON-SDK-genesis-snapshot-impossible.md`; use `@sovseal/sdk` (Node) for genesis snapshots until a patched `sovseal-sdk` ships.
</Warning>

### `restore(agent_id: str) -> dict`

Fetches the metadata receipt and ciphertext download URL for the **latest confirmed checkpoint**.

```python theme={null}
latest = client.restore(agent_id="agent-id-hash")
print(latest)
```

### `restore_at(agent_id: str, sequence: int) -> dict`

Fetches metadata and a ciphertext download URL for a checkpoint at a **specific sequence number** — point-in-time recovery or audit replay.

```python theme={null}
snap = client.restore_at(agent_id="agent-id-hash", sequence=4)
```

### `lineage(agent_id: str, limit: int = 50) -> list[dict]`

Walks backward along the parent-snapshot chain, most-recent first.

```python theme={null}
history = client.lineage(agent_id="agent-id-hash", limit=50)
for entry in history:
    print(entry["sequence_number"], entry["snapshot_id"])
```

### `close()`

Closes the native-host IPC transport and the underlying `httpx.Client`. Call this explicitly if you're not using the `with` context-manager form.

## Error handling

### `EngineUnavailableError` — local native host unreachable

`store` and `recall` raise `EngineUnavailableError` if the local ONEBRAIN native host can't be reached over IPC.

```python theme={null}
from sovseal import AgentStateClient, EngineUnavailableError

client = AgentStateClient()

try:
    client.store("User prefers dark mode")
except EngineUnavailableError as e:
    print(f"Engine unavailable: {e.reason}")  # "not-installed" | "version-mismatch" | "timeout"
```

`e.reason` is one of `"not-installed"`, `"version-mismatch"`, or `"timeout"`. This error is specific to `store`/`recall` — it is never raised by `snapshot`, `restore`, `restore_at`, or `lineage`, which only depend on your configured `endpoint`.

### `ValueError` — invalid input

All methods validate their arguments client-side and raise a plain `ValueError` with a descriptive message before any I/O — for `snapshot`, before any encryption happens. See the known-issue callout above for the current `sequence_number` validation bug.

### `RuntimeError` — HTTP failure

Replication methods (`snapshot`, `restore`, `restore_at`, `lineage`) raise `RuntimeError(f"HTTP {status}: {body}")` on any non-2xx response from the replication server.
