Metadata-Version: 2.4
Name: watchlight-agent-sdk
Version: 0.12.0
Summary: Watchlight Agent SDK — build governed AI-agent plugins for any framework
Author-email: Watchlight AI <team@watchlight.ai>
License-Expression: Apache-2.0
Project-URL: Homepage, https://www.watchlight.ai
Project-URL: Documentation, https://docs.watchlight.ai/de
Project-URL: Repository, https://github.com/watchlight-ai-beacon/watchlight-de
Project-URL: Issues, https://github.com/watchlight-ai-beacon/watchlight-de/issues
Project-URL: Plugin SDK Guide, https://docs.watchlight.ai
Keywords: watchlight,ai-governance,agent-runtime,ai-agents,agent-sdk,policy-decision-point,cedar-policy
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: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: System :: Monitoring
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.27
Requires-Dist: pydantic>=2.4
Requires-Dist: typing-extensions>=4.5; python_version < "3.12"
Provides-Extra: aws
Requires-Dist: boto3>=1.34; extra == "aws"
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Requires-Dist: mypy>=1.8; extra == "dev"
Requires-Dist: cryptography>=42; extra == "dev"
Requires-Dist: requests>=2.32; extra == "dev"
Requires-Dist: aiohttp>=3.14.5; extra == "dev"
Provides-Extra: otlp
Requires-Dist: opentelemetry-api>=1.45.2; extra == "otlp"
Requires-Dist: opentelemetry-sdk>=1.45.2; extra == "otlp"
Requires-Dist: opentelemetry-exporter-otlp-proto-http>=1.45.2; extra == "otlp"
Dynamic: license-file

# watchlight-agent-sdk

The Watchlight Agent SDK asks a Watchlight backend "may this agent do this?"
before an agent acts, and reports what the agent did. The backend answers
`Allow` or `Deny` by evaluating your Cedar policies. The same code runs
against the Developer Edition engine inside your process and against
Watchlight Beacon (Enterprise).

Import it as `watchlight_core`. The SDK is open source (Apache-2.0).

## Install

```bash
pip install watchlight-agent-sdk "watchlight-engine>=0.2.5,<0.3"
```

`watchlight-engine` is the compiled Developer Edition engine that
`InProcessClient` uses. Python 3.10 or later.

## Quickstart

```python
import asyncio
from watchlight_core import InProcessClient

POLICIES = [{"name": "reader", "code": 'permit(principal is Agent, action == Action::"read", resource) when { principal.name == "research-agent" };'}]

async def main():
    gov = InProcessClient(POLICIES)  # decisions are made in-process, with no network
    agent = await gov.resolve_agent("research-agent")
    me = f'Agent::"{agent["id"]}"'  # the principal is the agent's id, never its slug
    print((await gov.authorize(me, "read", "dataset"))["decision"])
    print((await gov.authorize(me, "delete", "dataset"))["decision"])

asyncio.run(main())
```

```text
Allow
Deny
```

The policy lets the research agent read and nothing else, so `delete` is
denied. These two calls write no file: `InProcessClient` writes lineage
events to `.watchlight/audit.jsonl` in the current directory when a run
publishes them, and this quickstart starts no run.

## What is and is not enforced

Every decision is made by the backend, never in this package. The SDK shapes
the request, sends it and gives your code the answer.

Enforced:

- `authorize` answers `Allow` or `Deny`. With `ApdpClient`, anything that is
  not a well-formed decision from the server is a `Deny`: a connection error,
  a timeout, an HTTP error status, a body that is not JSON, or a response the
  SDK does not recognise.
- A run-ending decision (quarantine, terminate, sever, revoke) raises its own
  error, listed under [Errors](#errors).
- A sub-agent spawn that the backend refuses raises, so your code gets no run
  handle for the child.
- `ApdpClient` refuses a plain `http://` server URL to a host that is not
  loopback, when it is built, with `InsecureChannelError`.
  `WATCHLIGHT_APDP_ALLOW_PLAINTEXT=true` turns that check off; use it only on
  a private link that does not leave the node.

Not enforced:

- The SDK does not stop code that never asks. An action is governed only where
  your code, or a framework plugin, asks for a decision before it acts and
  honours a `Deny`.
- A failed lineage report never stops the run. `publish_events` returns
  `False` and logs the failure. See
  [Lineage delivery and retries](#lineage-delivery-and-retries) for the one
  event that `authorize` waits for.
- With `InProcessClient`, lineage is the local file `.watchlight/audit.jsonl`.
  Nothing is sent to a server.
- `InProcessClient` refuses what needs Enterprise: `application_id`, a
  declared root run and `subject_token`.
- The provider SDK gate and the connector route have limits of their own.
  They are listed where those features are described, under
  [Provider-hosted tools](#provider-hosted-tools).

## Settings

| Variable | What it sets |
|---|---|
| `WATCHLIGHT_BACKEND` | `sidecar` or `in_process`. Any other value is refused. See [Choosing a backend](#choosing-a-backend). |
| `WATCHLIGHT_AGENT` | Developer Edition: the agent slug the process runs as, when `InProcessClient(agent=...)` is not given. |
| `WATCHLIGHT_APDP_URL`, `WATCHLIGHT_PROXY_URL` | Enterprise: the server and the Watchlight proxy. |
| `WATCHLIGHT_PLUGIN_TOKEN` | Enterprise: the plugin credential, read by `Credential.from_env()`. |
| `WATCHLIGHT_CREDENTIAL_FILE` | Enterprise: the path of a credential file. The default is `/etc/watchlight/plugin.cred` on Linux and macOS. |
| `WATCHLIGHT_CREDENTIAL_AWS_SECRET_ID` | Enterprise: an AWS Secrets Manager secret that holds the credential. Needs the `aws` extra. |
| `WATCHLIGHT_APDP_ALLOW_PLAINTEXT` | `true` allows a plain `http://` server URL to a host that is not loopback. |
| `WATCHLIGHT_PROXY_ALLOW_PLAINTEXT` | `true` allows a plain `http://` Watchlight proxy URL to a host that is not loopback. |
| `WATCHLIGHT_PROXY_CA_CERT` | A PEM CA bundle used to verify an `https://` Watchlight proxy. |
| `WATCHLIGHT_PROXY_NO_PROXY` | A comma-separated list of hosts that replaces the default list of hosts not sent through the proxy. A wildcard entry is refused. |
| `WATCHLIGHT_SIDECAR_SOCKET`, `WATCHLIGHT_SIDECAR_ADDR`, `WATCHLIGHT_SIDECAR_SECRET_FILE` | Where the Watchlight connector is. See [How `SidecarBackend` reaches the connector](#how-sidecarbackend-reaches-the-connector). |
| `WATCHLIGHT_LINEAGE_RETRY_MAX_ATTEMPTS`, `WATCHLIGHT_LINEAGE_RETRY_MAX_WAIT_SECONDS` | Lineage retries. See [Lineage delivery and retries](#lineage-delivery-and-retries). |
| `WATCHLIGHT_LOG_LEVEL`, `WATCHLIGHT_LOG_FORMAT` | Read by `configure_logging()`: the level (default `INFO`) and `text` (default) or `json`. |

The full list of variables that select Enterprise is
`watchlight_core.sidecar_backend.ENTERPRISE_ENV_VARS`.

## Errors

`authorize` does not raise for a deny or for an unreachable server: it
returns a `Deny`. The errors below are raised by the other calls. Branch on
the error class and its attributes, not on the message text.

| Error | Meaning |
|---|---|
| `GovernanceUnavailable` | The backend did not open the run or could not be reached. Do not proceed. |
| `GovernanceRefused` | The server answered `401` or `403`. `status_code`, `error`, `reason` and `code` carry its refusal code. A kind of `GovernanceUnavailable`. |
| `CredentialBindsNoAgent` | A root run was opened without naming an agent, and the credential is not bound to one agent. |
| `DeclaredRootRefused` | A declared root run was not opened. |
| `AgentNotRegistered` | The agent slug is not registered. Not transient; do not retry. |
| `CredentialNotFound`, `InvalidCredential` | No credential could be loaded, or the one loaded is malformed or incomplete. |
| `InsecureChannelError` | The server URL would send credentials over plain HTTP. |
| `ScopeAttenuationDenied` | A sub-agent was refused because it asked for more than its parent has. `violations` lists the dimensions. |
| `RunHandleInvalidated` | A sub-agent was refused because its parent's run handle is no longer valid. |
| `IntentRefused` | The intent is not a typed intent. Raised before any request is sent. |
| `HostedToolRefused` | A provider-hosted tool was not allowed, so the model call must not be sent. |
| `WatchlightContractError` | An SDK call was made in a state its contract forbids. |
| `AgentQuarantinedError`, `ExecutionTerminatedError`, `SubtreeSeveredError`, `AgentRevokedError` | The backend's decision ended the run. |

## Moving to Watchlight Beacon (Enterprise)

The Developer Edition decides with the engine inside your process. Watchlight
Beacon is the Enterprise server: it makes the decisions, knows your agents and
receives the lineage. Your agent and plugin code stay the same. You change
the backend.

| Backend | Use |
|---|---|
| `InProcessClient` | Developer Edition: the compiled engine in your process, with no server and no network. |
| `ApdpClient` | Enterprise: the Beacon server, over HTTPS. |
| `SidecarBackend` | Enterprise, through the Watchlight connector (`wl-sidecar`) on the same host or pod. |

What changes when you move:

- **Configuration.** Build an `ApdpClient` with your server's URL and a
  credential, or set the Enterprise variables and let `select_backend()`
  choose. See [Settings](#settings) and
  [Choosing a backend](#choosing-a-backend).
- **Identity.** The root run is the agent your credential is bound to. See
  [Install once at the root](#install-once-at-the-root).
- **Agent ids and names.** They come from the registry record, not from the
  slug. See [Agent-scoped policies](#agent-scoped-policies).
- **Lineage.** Events go to the server instead of the local file.
- **Features.** `application_id`, declared root runs and `subject_token` work;
  the Developer Edition refuses them.

On either backend the SDK returns a decision and your code, or a plugin, acts
on it. See [What is and is not enforced](#what-is-and-is-not-enforced).

## Choosing a backend

`select_backend()` picks the backend for a plugin. The rules are short, and
the SDK never falls back quietly from one backend to another:

1. If you pass a backend explicitly (`select_backend(my_backend)`), that
   backend is used.
2. Otherwise, if `WATCHLIGHT_BACKEND=sidecar` or any Enterprise variable is
   set, the SDK uses `SidecarBackend` and requires the connector. The
   Enterprise variables are every endpoint, credential, run-grant, TLS and
   connector setting the plugins read, such as `WATCHLIGHT_APDP_URL`,
   `WATCHLIGHT_PROXY_URL`, `WATCHLIGHT_PLUGIN_TOKEN`,
   `WATCHLIGHT_CREDENTIAL_FILE`, `WATCHLIGHT_RUN_CREDENTIAL`,
   `WATCHLIGHT_APDP_MTLS_CERT_PATH` and `WATCHLIGHT_SIDECAR_SOCKET`; the
   full list is `watchlight_core.sidecar_backend.ENTERPRISE_ENV_VARS`. If
   the connector is not running or cannot be reached, the run is refused
   with `GovernanceUnavailable`.
3. Otherwise the SDK uses the Developer Edition backend, `InProcessClient`.

`WATCHLIGHT_BACKEND` accepts `sidecar` or `in_process`. Any other value is
refused, and so is `in_process` together with an Enterprise variable.

### How `SidecarBackend` reaches the connector

`SidecarBackend` is a thin client. The connector holds the plugin credential,
every run credential and every egress token, and talks to the control plane
itself. Your process only ever holds an opaque run reference, so no token can
end up in your heap, your logs or an exception.

You tell the SDK where the connector is; it never guesses.

- **A Unix socket** is the preferred way. Set `WATCHLIGHT_SIDECAR_SOCKET` to
  the socket's absolute path. Without it, the SDK uses the connector's default
  path, `$XDG_RUNTIME_DIR/watchlight/control.sock` or
  `/tmp/wl-<uid>/control.sock`. Before connecting, the SDK checks that the
  socket's directory has mode 0700 and belongs to your user, that no parent
  directory lets another user replace it, and that the socket itself is yours.
  After connecting, it asks the kernel which user is on the other end and
  refuses any user but yours.
- **Loopback TCP** is for platforms where a shared socket is not possible. Set
  `WATCHLIGHT_SIDECAR_ADDR` to the connector's address as an IP literal and a
  port, such as `127.0.0.1:41000` or `[::1]:41000` (host names such as
  `localhost` are refused). Set `WATCHLIGHT_SIDECAR_SECRET_FILE` to the path
  of the secret file the connector writes. The secret never goes in an
  environment variable or on a command line, and it never crosses the
  connection: the SDK and the connector prove to each other that they know
  it, and the SDK checks the connector's proof before it sends anything else.
- **A connector you launch yourself**: `SidecarBackend.launch(argv)` starts
  the connector, reads its address and secret from its standard output pipe,
  and keeps the secret in memory only. Once that connector exits, the backend
  never connects to its port again.

Every error, timeout or malformed answer from the connector is treated as a
refusal: `authorize` returns a Deny, and a refused sub-agent spawn raises, so
the child never runs. If the connection to the connector is lost, every run
that was open on it is treated as killed.

A request the connector does not answer within `request_timeout_s` (60
seconds by default) gets its fail-closed answer at that point, but a late
answer alone does not end the connection, because some connector paths are
slow on purpose: a session create that waits on the control plane, or a
lineage publish or session close that the connector retries for up to its
retry budget, which operators can raise to 300 seconds. Instead the SDK then
asks the connector for its health. If that also gets no answer within 5
seconds, the connection is dropped and its runs are treated as killed,
because a connection that has stopped answering can no longer deliver kill
signals either. A run that a timed-out create or spawn makes later is ended
as soon as its answer arrives.

### Egress

`await backend.fetch_egress(run)` returns where the run's outbound traffic
goes: the connector's local proxy URL and the name of the header that carries
the run's marker. It does not return a CA bundle, and the SDK does not change
any trust settings. The connector inspects traffic with a CA that your
organisation issues, and you configure your clients to trust that CA in the
same way you configure any other internal CA.

## Agent-scoped policies

The principal of a governed call is the agent's **id**, `Agent::"<agent uuid>"`,
never its slug. `start_run("research-agent")` resolves the slug to that id before
the first decision. On Enterprise the id is the agent's registry id. Under
`InProcessClient` it is the id `resolve_agent` returns, a UUID derived from the
slug. A policy that names the slug as the id, `principal == Agent::"research-agent"`,
therefore matches neither.

Scope a rule to one agent with its attributes instead. Both backends set them from
a trusted source, never from the request:

- `principal.name` is the agent's registered name: the `name` that `resolve_agent`
  returns. On Enterprise it is the name on the registry record. Under `InProcessClient`
  it is the slug, because the Developer Edition has no other name for an agent.
- `principal.slug` is the slug you start the run with, on both backends. The
  registry derives a slug from the name (an agent registered as `research-agent`
  gets the slug `agent-research-agent`), so when one policy must decide the same on
  both backends, use the slug.

```cedar
permit(principal is Agent, action == Action::"read", resource)
when { principal.name == "research-agent" };
```

- To allow every governed agent, write `principal is Agent`.
- A `forbid` scoped by name or slug applies to that agent. Still prefer a `forbid`
  for every principal, for example
  `forbid(principal, action == Action::"delete", resource);`, and narrow the
  `permit` rules instead: a `forbid` whose condition never matches forbids nothing,
  so a mistyped name there allows what it was meant to stop. A mistyped name in a
  `permit` only denies.
- `principal in Group::"..."` does not match: the engine builds no group membership
  yet.

## Govern a framework agent

Install the plugin for your framework and point it at a backend — your agent code
doesn't change:

```python
from watchlight_langgraph import WatchlightLangGraphPlugin   # or -adk, -bedrock, -pydantic-ai, …
from watchlight_core import InProcessClient

# The backend is the one argument that differs from production.
plugin = WatchlightLangGraphPlugin(governance=InProcessClient(POLICIES))

async with await plugin.start_run("research-agent") as handle:
    if not await handle.authorize_action("read", "dataset"):
        raise PermissionError("denied by policy")
    # ... your agent runs, every action governed ...
```

## Install once at the root

A plugin is installed once, at the root of your agent system, and governs
everything beneath it. Identity is not declared in code: the root run is the
agent your verified credential is bound to, and sub-agents need no
registration.

Open the root run without naming an agent. With `ApdpClient`, Watchlight opens
it as the agent the credential is bound to (an agent API key, or an identity
provider client mapped to an agent) and tells the SDK which agent that is. A
credential that is not bound to one agent, such as a tenant's shared plugin
credential, is refused with `CredentialBindsNoAgent`; nothing guesses an agent.
In the Developer Edition there is no credential, so the process's configured
identity plays that role: `InProcessClient(agent="orchestrator")` or the
`WATCHLIGHT_AGENT` environment variable.

```python
from watchlight_core import InProcessClient, open_root_session

gov = InProcessClient(POLICIES, agent="orchestrator")
session = await open_root_session(gov)        # the run is the credential's agent
print(session.agent_id)
```

Spawn a sub-agent by its label, the name your framework already gives it (a
deepagents or Claude `subagent_type`, an ADK `agent.name`, a Strands node id):

```python
from watchlight_core import ChildIntent

child = await handle.spawn_subagent(
    child_label="research-agent",
    child_intent=ChildIntent("research", "collect the filings"),
    allowed_tools=["search"],
)
```

`child_intent` is required: the child's own intent category, within the
parent's intent bounds, and the objective the parent gives it. A call without
it raises `TypeError`.

The child is always attenuated to a strict subset of its parent's scope, under
the usual rules: a time budget above what the parent has left is refused, and
delegation depth is limited. Its label is recorded in lineage and reaches
policy as `context.subagent_label`, as evidence only; it never grants anything.
Without further configuration the child runs as its parent's agent. An
operator can map a label to a registered agent for a tenant, and the child then
runs as that agent, still spawned and attenuated under its parent. In the
Developer Edition the equivalent is `InProcessClient(subagent_agents={"critic":
"critic-agent"})`.

Naming the agent is still supported as an optional override:
`open_root_session(backend, agent_slug="research-agent")`,
`create_session(agent_id=...)`, and `spawn_subagent(child_agent_id=...,
child_intent=...)` still take a name. When the credential is bound to an agent, Watchlight refuses a name
that does not match it. The connector backend (`SidecarBackend`) still needs the
agent to be named.

## Provider-hosted tools

Some tools run on the model provider's servers during the model call: web
search, code execution, file search, image generation and remote MCP servers.
No framework tool hook runs for them, so a plugin authorizes each one before it
sends the model call. Call `require_hosted_request_allowed` as the last step
before every model call, with the full request you are about to send:

```python
from watchlight_core import HostedToolTurn, require_hosted_request_allowed

turn = HostedToolTurn()  # one per model call
await require_hosted_request_allowed(
    handle,
    request,  # the whole request, not only its tools
    turn,
    registered_mcp_servers={"https://mcp.example.com/mcp": "docs-mcp"},
)
response = await client.call(request)  # reached only when every tool is allowed
turn.seal()
```

Pass the full request, not just its `tools`. Some fields outside `tools` turn
on a hosted capability too, and the gate reads them, at the top level and in
the passthrough scopes `config` (read as Gemini, so a function in
`config.tools` is gated), `extra_body`, `additionalModelRequestFields` (Bedrock
Converse) and `http_options.extra_body` (Gemini):

- `web_search_options` (OpenAI Chat Completions) is decided as `web_search`.
- `prompt` given as anything but a string (an OpenAI Responses stored prompt, which can
  carry its own tools) is decided as `Tool::"stored_prompt"`. It is refused
  unless a policy allows that resource.
- `mcp_servers` (Anthropic) is decided per server, like any remote MCP server.
- `cached_content` (Gemini, which can carry tools) is decided as
  `Tool::"cached_content"`. It is refused unless a policy allows that
  resource.
- `search_parameters` (xAI Live Search) is decided as `live_search`.
- `container` (Anthropic) is decided per skill: each `container.skills` entry
  is one decision on `Tool::"skill"`, with `context.hosted_tool.skill_type`
  and `context.hosted_tool.skill_id` naming it. A container given as an id
  loads no skills. A container that is neither a plain id nor `{id, skills}`
  with well-formed skills is refused, and so is a container or skill entry
  with a key the gate does not know.

The gate makes one decision per hosted tool, as `Action::"execute"` on
`Tool::"<kind>"` (for example `Tool::"web_search"`) with
`context.builtin_tool` set to `true` and `context.hosted_tool` naming the
provider and kind. A remote MCP server is decided as
`Resource::"mcp://<name>/"`, where the name is the one you registered for its
URL. A server you did not register is refused, and so is a server URL with
credentials, a backslash, whitespace, control characters or non-ASCII
characters. An `allowed_tools` list with more than 64 names, or with a name
that is not a plain token, is refused rather than shortened. A deny, a
required approval, an error or a timeout refuses the whole model call, and the
gate never removes a tool to make a call pass.

A `file_search` tool is decided with the stores it searches:
`context.hosted_tool.vector_store_ids` lists them, sorted and without
repeats (OpenAI `vector_store_ids`, Gemini `fileSearchStoreNames`, and in the
Python SDK Pydantic AI `file_store_ids`), so a policy can limit which stores
an agent may search. The same tool with other stores is another decision.
Store ids that are not a list of at most 64 plain ids are refused before any
decision. Store ids and skill ids appear only in the decision's context, never
in a hosted tool's summary.

`require_hosted_request_allowed` raises `HostedToolRefused` on a refusal; its
`gate.result` carries the decision (a required approval keeps its approval
request id, which you must not log). `authorize_hosted_request` returns the
result instead; test its `allowed` attribute, because the result itself has
no truth value and raises `TypeError` if you test it. A turn caches allows
only for its own model call; seal it once the call is made.

For a synchronous model call, use `require_hosted_request_allowed_blocking`.
It takes the same arguments plus `run_loop`, the event loop the run was opened
on. It makes the same decisions on an event loop on another thread while the
calling thread waits. It uses the backend's own I/O-loop thread when the
backend has one (the Enterprise sidecar backend), and otherwise `run_loop` if
that loop is running on another thread. Otherwise it refuses the call. That
covers: no such loop, a caller on that loop's own thread (waiting there would
deadlock), a closed or stopped loop, and no answer within the timeout. A
request that enables no hosted tool passes without any loop.
Any other error, such as a misused turn, an unreadable request or a failure
inside the gate, also refuses the call with `HostedToolRefused`. A run-ending
decision (quarantine, terminate, sever, revoke) raises its own error. Every
refusal seals the turn, so a decision that arrives after the wait gave up is
never reused.

`authorize_hosted_tools` and `normalize_hosted_tools` read a tools list only.
They miss request-level hosted tools; use `require_hosted_request_allowed` for
a full request. A request that is not a mapping or pydantic model, or that
looks like a single tool, raises `TypeError`. So does a passthrough scope or
`toolConfig` that is present but is not a mapping or pydantic model (a list, a
string or another class instance), and scopes nested more than three levels
deep, and a scope that carries two spellings of one key (`extra_body` and
`extraBody`, `http_options` and `httpOptions`, `toolConfig` and `tool_config`,
`additionalModelRequestFields` and `additional_model_request_fields`,
`cached_content` and `cachedContent`): the gate refuses what it cannot read
unambiguously. Mappings and lists are read only as an exact `dict` with
string keys, `list` or `tuple`: a dict subclass, another `Mapping`, a list
subclass or any other iterable (a generator, a view, a custom iterable)
raises `TypeError`, because its iteration can leave out a key or an entry
that the provider SDK's JSON body still carries, or yield different entries
when the SDK iterates it again. A dict value that is callable raises
`TypeError` too, as a function value does in the TypeScript SDK (where
`JSON.stringify` would call a `toJSON` function). A pydantic model is read
from what pydantic serializes (its `__dict__` and its extra fields), never through
attribute access, and a model class that replaces `__getattribute__`,
`__getattr__`, `model_dump`, `model_dump_json` or its serializer, or that has a
custom model or field serializer, a computed field, an excluded field
(`Field(exclude=True)` or `exclude_if`), or an alias naming another field,
raises `TypeError`. A Pydantic AI native tool is read from its dataclass
fields in `__dict__`; a class that hooks attribute access or shadows a field
with a property raises `TypeError`. The TypeScript SDK reads plain
objects only; this SDK also reads pydantic models, because the Python SDKs'
request types (such as google-genai's `GenerateContentConfig`) are pydantic
models. A malformed registry raises
`WatchlightContractError`, and a remote MCP entry that names both a
`server_url` and a `connector_id` is refused as ambiguous. Register an OpenAI
connector under the key `connector:<id>`; a `connector:` string given as a
server URL is refused. A `HostedTool` shows only the server's origin
(`scheme://host[:port]`) and label; the full URL stays private to the registry
lookup. It is not a dataclass field, so `dataclasses.asdict`, `vars`, `copy`
and `pickle` never carry it, and a copied MCP tool is refused as unregistered.

`normalize_hosted_request` and `normalize_hosted_tools` read the OpenAI,
Anthropic, Gemini (including `mcp_servers`), xAI, Bedrock Converse and
Pydantic AI shapes. Function tools are left to the framework's tool hook.
A tool entry of one shape (a function, a Bedrock `toolSpec` or `systemTool`, a
typed entry) that also carries a key another provider reads as a hosted tool
(a Gemini field such as `googleSearch` or `mcpServers`, an MCP `server_url` or
`server_label`, or `systemTool`) raises `TypeError`, as does an entry with
both `systemTool` and `toolSpec`: a provider SDK that copies the keys it knows
would otherwise send a hosted tool that was never decided. A
tool of a shape they do not know is reported by its type name, so a policy
decides it, and without a policy that allows it, it is denied. Summaries
carry no arguments, headers, tokens or URL paths: an MCP server appears by
its host. `publish_hosted_tool_observed` records a hosted tool invocation as
a `tool_call_observed` event with `metadata.hosted_tool` set to `true`.

A plugin whose framework can put hosted tools on a model call sets
`supports_hosted_tools = True` and defines
`async def conformance_hosted_tool_call(self, probe)`, which makes one model
call of `probe.request` through the plugin's own wiring, using
`probe.wrap(handle)` as the run handle, `probe.registered_mcp_servers` as the
registry and `probe.model_client` as the provider client. A plugin that passes
a provider hint to the gate also sets `hosted_tool_provider`. The probe request
carries request-level hosted tools, so a plugin that gates only
`request["tools"]` fails. Conformance invariant 19 drives that hook and fails a
plugin that calls the model without the gate, or after a refusal, and a
plugin whose hook raises while every hosted tool is allowed. The plugins
whose frameworks can carry hosted tools are listed in
`HOSTED_TOOL_PLUGINS_REQUIRED`; one of them that does not declare support
fails, unless it is still in `HOSTED_TOOL_PLUGINS_PENDING`. This release,
0.12.0, ships with `watchlight-deepagents` and `watchlight-pydantic-ai` still
pending, by a one-time exception to the rule that the set be empty after
0.11.0: neither yet decides provider-hosted tools before a model call. The set
must be empty before the next core release after 0.12.0. `check_required_hosted_tool_plugin(module)`
runs invariant 19 for one listed plugin on its own (some never call
`run_conformance`); the core tests run it for every listed plugin in the
environment that installs them all, where a plugin that cannot be imported
fails. A plugin whose constructor needs more than `apdp_url` defines a
`conformance_hosted_tool_instance()` classmethod that returns an instance to
drive.

### Deciding on the request the provider SDK sends

A framework sees only part of what its model integration sends. An
integration can add request fields of its own, such as
`ChatAnthropic(mcp_servers=...)`, so a gate placed in the framework can miss
a hosted tool. `watchlight_core.provider_sdk_gate` makes the decision where
the request leaves the process: it wraps, once and at class level, the method
that every request of a supported provider SDK passes through, and reads the
request body the SDK is about to send.

| SDK | Wrapped | Body read |
|---|---|---|
| `anthropic` (from 0.69) | `SyncAPIClient.request`, `AsyncAPIClient.request` | `json_data` merged with `extra_body`, as the SDK merges them |
| `openai` (from 1.109; also xAI through its base URL) | `SyncAPIClient.request`, `AsyncAPIClient.request`; Realtime `connect` | the same |
| `google-genai` (from 1.53) | `BaseApiClient.request`, `async_request`, `request_streamed`, `async_request_streamed`; Live `connect` | the REST body |

That covers every resource method of those SDKs, including streams, `parse`,
the beta resources and batches. Each request is then treated by its
endpoint. Reads and deletes always pass. A write that matches no row below is
refused, because an API the gate does not know is never assumed to be safe.

| Endpoint | Treatment |
|---|---|
| Anthropic Messages, count tokens | decided |
| Anthropic Message Batches | each request decided; one refusal refuses the batch |
| OpenAI Chat Completions, Responses, input tokens, Completions | decided |
| OpenAI Responses with `previous_response_id` or `conversation` | refused (the tools of the stored response are not in the request) |
| OpenAI Batches | refused (the requests are in a file, not in the request) |
| OpenAI Assistants, Threads and runs | refused (the tools are stored on the server) |
| OpenAI Realtime, Gemini Live | refused (the tools are set over the socket) |
| Gemini `generateContent`, `streamGenerateContent`, `countTokens`, cached contents | decided |
| Gemini batches | refused |
| Files, uploads, embeddings, moderations, audio, images, vector stores, containers, conversations, cancels | pass (they send no tools) |
| Anthropic Skills API (creating a skill or a version) | pass (a skill runs only when a model call loads it, and each loaded skill is decided) |
| Anything else that writes | refused |

The gate acts only inside a governed context. A plugin marks each run with
`attach_run(handle, run_loop=..., registered_mcp_servers=...)` when the run
opens, and ends it with `detach_run(attachment)`. `attach_run` installs the
wraps, and refuses the run with `GovernanceUnavailable` when a wrap was
replaced. Then:

- In the run's own context, while the run is open, a decided request needs an
  allow for every hosted tool it enables, as `require_hosted_request_allowed`
  makes them. A synchronous request waits on
  `require_hosted_request_allowed_blocking`, deciding on the run's loop, so a
  synchronous call made on that loop's own thread is refused rather than
  deadlocking. A refused API raises `ProviderApiRefused`. Nothing is sent
  after a refusal.
- A task that outlived its run still carries the run's context. It is
  refused every request that binds a tool (a function tool or a hosted tool)
  and every refused API.
- Code with no run in its context, while a governed run is live anywhere in
  the process (a bare thread, a fresh `contextvars.Context`), is refused every
  request that binds a tool, with `UnmarkedToolBindingRefused`, and every
  refused API. The refusal is logged at WARNING with the reason
  `unmarked_tool_binding` and counted (`unmarked_refusals()`); it does not end
  the live run. A request that binds no tool passes. As with the other
  process-wide backstops, an unrelated agent in the same process is refused
  while a governed run is live, so run such agents in a separate process.
- With no governed run live, nothing changes.

A function tool alone needs no decision here: the framework's tool hook
decides each call. The plugins' own framework layer sets the run marker and
checks their entry points; the hosted-tool decision is made here.

A request whose path the HTTP client could rewrite before sending is
refused in a governed context, never normalised. That covers a `.` or `..`
segment, an empty segment, a percent-encoded dot, slash or backslash, or a
backslash: `files/../responses` would be sent to `responses`.

What this gate does not cover. It stops mistakes, not deliberate bypass by
code in the same process:

- a subclass of an SDK client that overrides `request` itself, since the wrap
  is on the SDK's base class;
- code that puts a wrapped method's `__wrapped__` original back after a run
  has opened, since the wraps are checked when a run opens, not on every
  request;
- a model call made without one of these SDKs, such as with raw `httpx` or
  another HTTP client.

For those, route the workload's outbound HTTPS through the Watchlight proxy
(Enterprise). The proxy then decides which hosts the process can reach. On
that route it does not read the request body, so it limits where a request
can go rather than deciding the hosted tools in it.

#### Naming the run on each request

The same wrap names the run for the Watchlight connector. While a process has a run on the connector, every request of a supported provider SDK leaves with the marker of the run acting in its context. Each sub-agent sends its own marker and never its parent's, and runs that share one client stay separate request by request, even on a pooled connection. When a run starts, core routes the process to the connector. It sets every proxy variable to the connector's egress listener and replaces `NO_PROXY` with loopback only, keeping both for the life of the process. A value already set is overwritten, and there's no exclusion list. It then does a real TLS handshake through the listener under each installed provider SDK's own trust, once per process and endpoint, and refuses the run if none passes. If only some pass, it logs a warning naming the SDK and host, and that SDK's requests fail at TLS. Watch for that warning: the matching metric, `wl.egress.handshake_partial_failures`, exports only if your process sets a global OpenTelemetry meter provider. The handshake shows trust reaches a certificate through that endpoint; it doesn't prove the endpoint is the connector. A connector that restarts on a new port refuses runs until the process restarts. Core installs no trust: distribute your CA to the agents as you do any internal CA, and with name constraints make sure they cover your providers' hosts.

A provider SDK client must be built with that route. Each request is refused unless the client's route for that URL is the connector, so a client built at import needs the proxy variables set in the deployment before the process starts. Google's google-auth transport (`Vertex` mTLS) is refused too. google-genai's file upload and download aren't checked and carry no marker: built after the route they reach the connector and are refused, and built before it they go direct.

**Other traffic isn't covered by these checks.** Ordinary tool HTTP in the process, and calls to private non-loopback services, now go to the connector with no marker. They're attributed by the connection report on Linux and refused with a 407 elsewhere. Subprocesses inherit the variables. A client given its own transport, `trust_env=False`, or plain `aiohttp`, which ignores the proxy variables by default, may go direct: for those, your deployment's network policy is what stops direct egress.

The connector removes the marker before it forwards the request. The marker is an opaque value that holds no session id or credential, and only the local listener can redeem it, so a remote host can do nothing with one. It doesn't confine the client: a client set up to bypass the connector sends the marker to wherever it connects. The provider SDK check above refuses that client when its route can be read; for anything else the control is your network policy, not the marker.

If no live run can be named, the request is refused with `EgressRefused` and nothing is sent. That covers a run that has ended, a sub-agent with no egress of its own, and a thread that lost its context. A process on the relay, or with no governed egress, is unchanged.

A deployment puts a plugin on the connector with `WATCHLIGHT_BACKEND=sidecar`, or with `WATCHLIGHT_SIDECAR_SOCKET` or `WATCHLIGHT_SIDECAR_ADDR`. The other Watchlight variables don't select it, so an install with no connector stays where it is. Nothing falls back from the connector to the relay. A sub-agent is refused at spawn if the connector gives it no egress endpoint, and its session is closed.

Other traffic, such as a tool's own HTTP client or an unsupported SDK, has no marker. It falls to the connection report, which the connector honours only on Linux. On any other platform the connector refuses that request with a 407, so such a client stops working there rather than leaving unattributed.

## Custom agents (any framework)

For an agent not built on a supported framework, the `@watchlight` decorator
governs any function:

```python
from watchlight_core import InProcessClient, watchlight

gov = InProcessClient(POLICIES)

@watchlight(agent_id="custom-research", client=gov)
async def run_research(query: str) -> str:
    ...
```

## Optional: OpenTelemetry export

Install the `[otlp]` extra to export a subset of the lineage stream to your OTel
collector (off by default):

```bash
pip install 'watchlight-agent-sdk[otlp]'
```

## Lineage delivery and retries

Lineage events and the run's session close are retried when the server answers
`429`, `502`, `503` (it cannot yet know the run's state) or `504`, or the
connection fails. The SDK waits with exponential backoff and jitter and honours
`Retry-After`. A retried event is deduplicated by its `event_id`. A `500` and
every other `4xx` are final and never retried.

| Variable | Default | Range |
|---|---|---|
| `WATCHLIGHT_LINEAGE_RETRY_MAX_ATTEMPTS` | `6` | 1 to 20 |
| `WATCHLIGHT_LINEAGE_RETRY_MAX_WAIT_SECONDS` | `30` (hard wall-clock bound) | 0 to 300 |

A run's events are sent in call order. Authorization is never retried or delayed by lineage. The
`execution_started` sent before `authorize` is one direct attempt that never
waits behind a retry; if it fails, `authorize` fails closed (an action whose
execution was never started would be dropped from lineage), and a transient
failure is also queued for background delivery. Other events emitted while a
decision is applied (`execution_quarantined`) get one attempt if nothing else
is being sent for the run, and are otherwise queued; such an event can land
after a batch that was being retried when it was emitted, and the lineage view
orders events by timestamp. The quarantine kill signal fires before any
lineage is sent.

When a batch runs out of budget, the SDK logs one WARNING with
`reason=lineage_retry_exhausted` (event types and counts, no payloads), and
the run's later events get one attempt each and are then queued, until one is
delivered. When the run ends, the SDK waits up to one budget for its queued
events. `ApdpClient.lineage_delivery_counters` counts retries, give-ups,
queued batches and cancelled publishes.

## Learn more

- **Documentation:** https://docs.watchlight.ai/de
- **Developer Edition** and **Enterprise:** https://watchlight.ai

## License

Apache-2.0.

## Trademarks

LangGraph, Google ADK, Amazon Bedrock, Microsoft Agent Framework, Pydantic AI,
Anthropic, OpenAI, Gemini, xAI and other product names in this README belong
to their respective owners. They are used only to describe compatibility.
This SDK is not affiliated with, endorsed by or sponsored by them.
