Metadata-Version: 2.5
Name: xtrom-sdk
Version: 0.5.0
Summary: Xtrom SDK — wrap AI-agent tools with runtime enforcement (taint/IFC + policy).
Project-URL: Homepage, https://github.com/xtrom-ai/xtrom
Project-URL: Source, https://github.com/xtrom-ai/xtrom/tree/main/product/xtrom-sdk-python
Project-URL: Issues, https://github.com/xtrom-ai/xtrom/issues
Author: Xtrom
License: Apache-2.0
License-File: LICENSE
Keywords: ai-agents,guardrails,llm,mcp,prompt-injection,security,taint-tracking
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: xtrom-engine>=0.3.1
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == 'dev'
Provides-Extra: update
Requires-Dist: cryptography>=42; extra == 'update'
Description-Content-Type: text/markdown

# xtrom-sdk-python  ✅ built &amp; tested (6/6)

Thin Python SDK / middleware that wraps agent frameworks (LangGraph, CrewAI, Bedrock Agents,
LlamaIndex) and enforces via `xtrom-engine`. For teams that want in-process enforcement
without running the gateway.

## Install
```bash
pip install xtrom-sdk --no-index --find-links https://console.xtrom.ai/pkgs/index.html
```
The SDK is self-hosted, not on PyPI. Each deploy builds the `xtrom-sdk` and `xtrom-engine` wheels
into the console's `/pkgs/` page, and **Govern › Connect** shows this line for your environment.
Public PyPI/npm publishing is opt-in (`PUBLISH_SDK=true` in `.github/workflows/publish.yml`).

> **Windows / `pip install --user`:** if `xtrom` prints *"not recognized as a command"*, the
> per-user Scripts dir (e.g. `%APPDATA%\Python\Python3xx\Scripts`) isn't on PATH — pip warns about
> this at install time. Run the CLI as a module instead; it's identical to the `xtrom` launcher.
> Use `py` (the python.org launcher); if you don't have it, swap in `python`:
> ```bash
> py -m xtrom_sdk install --url https://api.xtrom.ai --token-stdin
> ```

`--token-stdin` keeps the token out of argv and shell history — paste it at the hidden prompt, or
set `XTROM_INSTALL_TOKEN` (CI). `--token <TOKEN>` still works for throwaway scripts.

## Protect your local coding agent
Xtrom protects your coding agents locally through each agent's official command hooks. One
decision engine serves them all; a small adapter per agent (`xtrom_sdk/local/agents.py`) speaks
that agent's hook protocol.

No account needed: decisions are made on this machine and nothing is sent anywhere.

```bash
pipx install xtrom               # or: uvx xtrom install  (`xtrom` is the short name for xtrom-sdk)
xtrom install                    # every coding agent found on this machine, user scope
xtrom install --agent cursor,codex   # or pick: claude (claude-code), copilot, cursor, codex, gemini, windsurf, all
xtrom install --project          # this repo only
xtrom install --monitor          # observe and audit, never deny
xtrom log                        # what Xtrom stopped (--all for everything, --since 2h, --json)
xtrom status                     # what's protected (--json for scripts); --agent narrows it
xtrom connect --url https://api.xtrom.ai --token-stdin    # optional: report to your team's console (--off stops)
xtrom uninstall
```

| Agent | `--agent` | Hook config (user · `--project`) | "ask" verdict |
|---|---|---|---|
| Claude Code | `claude` | `~/.claude/settings.json` · `.claude/settings.json` | asks you |
| GitHub Copilot CLI | `copilot` | `~/.copilot/hooks/xtrom.json` · `.github/hooks/xtrom.json` | asks you |
| Cursor | `cursor` | `~/.cursor/hooks.json` · `.cursor/hooks.json` | blocked¹ |
| OpenAI Codex CLI | `codex` | `~/.codex/hooks.json` · `.codex/hooks.json` | blocked¹ |
| Gemini CLI | `gemini` | `~/.gemini/settings.json` · `.gemini/settings.json` | blocked¹ |
| Windsurf | `windsurf` | `~/.codeium/windsurf/hooks.json` · `.devin/hooks.json` | blocked¹ |

¹ These agents' hooks can't pause for a human, so Xtrom fails closed: the call is blocked and the
reason tells you to run it yourself in a terminal if you meant it. Codex asks you to trust new
hooks once: open Codex and approve Xtrom in `/hooks`. Windsurf has no web-fetch hook, so its
untrusted-input signal comes from MCP tools and `curl`/`gh` output.

The hook registers for each agent's before-tool and after-tool events. Web results, every MCP tool's output, and
`curl`/`gh` output are marked as untrusted session context. After that, any shell command that
isn't recognised local dev work asks you. Writes to `~/.xtrom` are always denied, and changes to
any coding agent's hook or permission settings always ask. Later sinks such as file writes, shell commands, git pushes, and
outbound MCP tools are adjudicated by `xtrom-engine`. `BLOCK` becomes the agent's deny,
`STEP_UP` asks you (or blocks, where the agent can't ask), and `ALLOW` stays silent. Hook processes are short-lived, so Xtrom persists
only metadata taint state under `~/.xtrom/local/sessions/` and appends a metadata-only audit line
to `~/.xtrom/local/audit.jsonl` (tool name, verdict, reason code, taint origins, timestamp,
session id; no raw tool arguments). If state is corrupt or unreadable, Xtrom fails safe: it asks
before sink tools and stays silent for non-sinks.

**Reporting is decoupled from the short-lived hook.** When reporting is configured, each decision is
written to a local spool and a single **detached background shipper** process delivers it to your
console with retry/backoff — the hook never blocks a tool call on the network, and an undelivered
event survives the hook exiting (durable spool, redelivered on the next run). The shipper also emits a
liveness **heartbeat** so the console's Enforcement-health view shows the agent as live rather than
silent. Cross-platform: the shipper is spawned detached (POSIX `start_new_session` / Windows
`DETACHED_PROCESS`) and outlives the agent that started it.

**Updating (one-time refresh, then self-updating).** An agent already installed keeps running its
current version until refreshed **once** — `pip install -U xtrom-sdk --find-links <console>/pkgs/index.html`
then `xtrom install`. After that, signed updates self-apply per your console policy (approve/auto),
no manual command. (The very first update can't self-deliver: an old agent doesn't yet have the
background shipper that applies updates.)

Every agent runs the hook through a `/bin/sh` launcher. If this Python disappears or the hook
crashes, the launcher exits 2, which every supported agent treats as a block, so the call is
stopped rather than run unchecked. To fix it, re-run
`xtrom install` or `xtrom uninstall` from a terminal. `--url`/`--token` are stored 0600 in
`~/.xtrom/local/config.json`, never in your shell profile, where the agent could read them. Only
`https://` is accepted, except for localhost.

**Browser agents.** Browser automation runs through the Playwright, Puppeteer, Chrome DevTools,
Browserbase/Stagehand and Claude in Chrome MCP servers, and Anthropic's `computer` tool. Every page
the agent reads, including screenshots, marks the session untrusted. Xtrom then gates the moments
that have consequences, not every click:

| Browser action | Clean session | After untrusted content |
|---|---|---|
| Snapshot, screenshot, scroll, hover, typing into a field, ordinary clicks | allowed | allowed |
| Submit: `submit`/Enter, accepting a dialog, clicking Send/Pay/Delete/Sign in…, the first click after typing | allowed | **ask** |
| Navigate to a URL | allowed | **ask** |
| Run script in the page (`evaluate`, `run_code`), install extensions, mock routes; upload files | allowed | **ask** |
| Read or change cookies, localStorage or sessionStorage (including via script) | **ask** | **ask** |
| Type a secret (API key, token) into a page | **ask** | **deny** |
| Navigate to a URL carrying a secret; upload a credential file (`~/.ssh/id_rsa`, `.env`) | **deny** | **deny** |

The click-after-typing rule exists because a button's label is whatever the page or the model calls
it. Once data has been entered, the next click may be the one that sends it.

**What it is, and isn't.** This is a guardrail inside your coding agent, not a sandbox. It sees each
tool call the agent reports to its hooks and judges it from the command text. Known limits:
- In a session that hasn't read untrusted content, ordinary shell commands run without a prompt.
  The hook assumes the agent's own instructions came from you.
- `npm test`, `make` and `npm run` stay silent after untrusted input, but they run code the agent
  may have edited.
- A command's text isn't its behaviour. After untrusted input, anything not on the local-dev
  allowlist asks you; a cleverly disguised command can still look harmless to you.

For real isolation, pair it with your agent's sandboxing and permission rules.

`xtrom discover` inventories MCP servers from common Claude, Cursor, Codex, and VS Code config
files and flags remote URLs or secret-looking env key names without printing secret values.

## In-process SDK and framework adapters
```python
from xtrom_sdk import Session
from xtrom_sdk.adapters import wrap_openai_tools, wrap_langchain_tool

session = Session("svc-support-bot")

def read_web(url: str) -> str: ...
def http_post(url: str, body: str) -> str: ...

dispatch = wrap_openai_tools(
    session,
    {"read_web": read_web, "http_post": http_post},
    sources={"read_web"},                  # output is untrusted ingress
)

tool_message = dispatch({
    "id": "call_1",
    "function": {"name": "read_web", "arguments": "{\"url\":\"https://docs.example\"}"},
})

safe_langchain_tool = wrap_langchain_tool(session, existing_tool, sources={"retriever"})
```

Adapters in `xtrom_sdk.adapters`:

- `wrap_openai_tools(session, tools, *, sources=...)` returns a dispatcher for OpenAI Chat
  Completions / Responses tool calls. It parses the tool name and JSON arguments, adjudicates
  through `Session` before execution, runs only on `ALLOW`, and returns a tool message. `BLOCK`
  and `STEP_UP` return structured JSON content for the model instead of running the tool.
- `wrap_anthropic_tools(session, tools, *, sources=...)` does the same for Anthropic Messages
  `tool_use` blocks and returns `tool_result` blocks.
- `wrap_langchain_tool(session, tool, ...)` wraps a LangChain/LangGraph-style tool by duck type
  (`.name`, `.invoke` / `._run`) and preserves the callable interface.
- `wrap_crewai_tool(session, tool, ...)` wraps a CrewAI-style tool by duck type (`.name`,
  `._run` / `.run`).

Framework packages are not hard dependencies; imports are lazy/duck-typed so the SDK imports
without OpenAI, Anthropic, LangChain, LangGraph, or CrewAI installed. Adapter tests use minimal
fake framework objects. Live framework CI is not wired yet; the supported contract is the stable
tool-call/tool object shape above.

## Session taint (on by default)
Once an agent reads untrusted content (a web page, an MCP tool result, an email), the model's
context is influenced even if the attacker's text is *paraphrased* before it reaches a sink.
`Session` therefore tracks two tiers of taint:

- **Value taint** (proven): untrusted bytes reach a sink argument → `BLOCK` (L3).
- **Context taint** (inferred): any sensitive sink after untrusted ingress in the same session → `STEP_UP`
  (human approval), never a silent allow. It lasts for the whole `Session`: the model can carry a
  reworded copy of untrusted content into a later task, so `new_task()` does not clear it.

```python
s = Session("svc-support-bot")              # session_taint=True by default
s.context_tainted                            # True after the first untrusted ingress
Session("svc-support-bot")                   # a genuinely fresh conversation: a new Session
Session("batch-bot", session_taint=False)    # opt out (e.g. no untrusted inputs at all)
```
`@s.guard(source=True)` marks where a tool's *output* goes, not what the tool can do, so source
tools get no special exemption from context taint. Read-only tools (rated `LOW` in the policy,
e.g. `read_file`) are never held; a dual-use tool such as `execute_sql` or a generic MCP call is,
because a reworded write through it is exactly what context taint exists to catch. Rate genuine
read-only tools `LOW`; fetches to allowlisted hosts are fine. Tools in `Policy.context_taint_exempt`
are the explicit, auditable opt-out (e.g. a browsing agent). Every decision
shipped to the control plane carries `session_id` and `mode` (enforce / monitor) as metadata —
never argument values.

## Signed workspace mode

The control plane can switch every agent to monitor for a bounded time (the workspace mode). By default an
SDK takes that switch from the control plane's response over TLS. To accept it only when it is signed, set
`XTROM_POLICY_VERIFY_KEY` (the PEM from `GET /v1/signing-keys`, or a path to it) and `XTROM_TENANT`, and
install `xtrom-sdk[update]` for ES256. The SDK then honours monitor only from a directive signed with that
key, for that workspace, and no older than the last one it accepted; anything else means enforce.

## Heartbeat (enforcement liveness)
`DecisionReporter` sends a `heartbeat` every `heartbeat_interval` seconds (default 60; `0`
disables) — even when the agent is idle — carrying only instance id, SDK version, mode, policy
version, per-verdict counts, p50/p95/p99 latency, events dropped since the previous beat, and up
to 200 identity names for the window (`identities_truncated: true` when more were seen).
The control plane stamps it on its own clock, so the console's **Enforcement health** screen can
tell "no attacks" apart from "enforcement stopped running" (`GET /v1/mediator-health`).
Each decision carries the reporter's random per-process `stream` and a `seq` counted from 1, and
the heartbeat adds `last_seq` and `dropped_total`, so the console also flags decisions that were
made but never arrived and weren't reported as dropped.
Heartbeats are never metered. Use an **agent**-kind enrollment token for the SDK: the control plane
labels the beat with the token kind, and agent tokens cannot impersonate a gateway/MCP proxy or
send MCP tool inventories.

## Version handshake (P2 hardening)
`xtrom_headers()` returns the headers every HTTP integration should send:
`X-Xtrom-API-Version` (contract), `X-Xtrom-SDK-Version` (build), `X-Xtrom-SDK-Lang: python`.
Unknown API version → 400 pre-auth on the server, so misconfigured clients fail loud.

## Status
Built and tested against `xtrom-engine` (v0.1). The core `Session` decorator, local coding-agent
hooks, reporter, heartbeat, and first framework adapters are implemented in this package.
