Metadata-Version: 2.4
Name: watchlight-deepagents
Version: 0.2.1
Summary: Watchlight governance middleware for DeepAgents agents: authorize every tool and filesystem call and gate sub-agent spawns, fail-closed. Model turns are not authorized one by one. Independent plugin, not affiliated with or endorsed by LangChain.
Author-email: Watchlight AI <team@watchlight.ai>
License-Expression: Apache-2.0
Project-URL: Homepage, https://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: DeepAgents, https://github.com/langchain-ai/deepagents
Keywords: watchlight,deepagents,langchain,ai-agents,ai-governance,agent-runtime
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: watchlight-agent-sdk<0.13,>=0.12.2
Requires-Dist: deepagents<0.8,>=0.7
Provides-Extra: otlp
Requires-Dist: watchlight-agent-sdk[otlp]<0.13,>=0.12.2; extra == "otlp"
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Requires-Dist: mypy>=1.8; extra == "dev"
Dynamic: license-file

# watchlight-deepagents

Watchlight authorization for DeepAgents tool calls and sub-agent spawns, fail-closed.

`watchlight-deepagents` puts a Watchlight authorization decision in front of the tool calls, virtual-filesystem calls and `task` sub-agent spawns your DeepAgents agent makes, so each one is allowed or denied *before* it runs. It is a governance middleware plus a drop-in `create_governed_deep_agent(...)` factory, built on the DeepAgents `AgentMiddleware` protocol, with no monkey-patching and no changes to your tool code. The decisions are made by the Developer Edition engine inside your process, or by Watchlight Beacon (Enterprise).

> **Independent third-party plugin.** This is an independent integration built by Watchlight AI. It is **not affiliated with, endorsed by, or sponsored by** LangChain. `deepagents`, `LangChain`, `LangGraph`, and related names are trademarks of LangChain, used here nominatively only to describe compatibility.

## Install

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

`watchlight-engine` is the compiled Developer Edition engine that `InProcessClient` uses. The plugin needs Python 3.11 or later, `deepagents` 0.7 and `watchlight-agent-sdk` 0.12; `pip` installs both with it. CI tests it on Python 3.12 and 3.13.

## Quickstart

Swap `create_deep_agent` for `create_governed_deep_agent`, name the agent with `agent_slug`, and give the plugin a backend. Your tool code, sub-agent prompts and the model loop do not change.

```python
from watchlight_core import InProcessClient
from watchlight_deepagents import WatchlightDeepAgentsPlugin, create_governed_deep_agent

# The principal is the id of the agent. `principal.name` is its registered name (with InProcessClient, the slug it is started with).
POLICIES = [{"name": "reader", "code": 'permit(principal is Agent, action == Action::"read", resource) when { principal.name == "research-orchestrator" };'}]
plugin = WatchlightDeepAgentsPlugin(governance=InProcessClient(POLICIES))  # decisions are made in-process, with no network

agent = create_governed_deep_agent(model=model, tools=[search_web, send_email], agent_slug="research-orchestrator", plugin=plugin)
result = await agent.ainvoke({"messages": [{"role": "user", "content": "Find the Q3 filings and email them."}]})
```

Here `model` is your LangChain chat model (`ChatAnthropic`, `ChatOpenAI`, `AzureChatOpenAI`, `ChatXAI` or `ChatGoogleGenerativeAI`; any other class must be listed in `allowed_model_classes=`, see [Provider-hosted tools](#provider-hosted-tools)) and `search_web` and `send_email` are your own tools. The policy lets the research agent read and nothing else, so a `search_web` call runs and a `send_email` call is refused: the model gets an error message in place of the tool's result, and the tool never runs. DeepAgents runs on the async LangGraph runtime, so invoke the agent with `await`. The quickstart also writes the run's events to `.watchlight/audit.jsonl` in the current directory: the run's start and completion, one event per model call (it names the model; the plugin sees the call and not an HTTP request, so the event's `method` and `path` are empty, and a model call that was refused carries `response_status` 403), and one event per tool call with its decision (Allow or Deny).

## What is and is not enforced

Enforced:

- **Run start.** Every agent run opens a governed Watchlight run before the model loop starts. If the run cannot be opened (unregistered agent, unreachable backend), the agent does not run.
- **Tool and filesystem calls.** Each call is authorized by Watchlight first. A denial, a required approval, or an unreachable backend returns an error to the model and the tool never runs. Only argument names, count and types are sent with the request, never argument values.
- **Sub-agent spawns (`task`).** A spawn opens an attenuated child run under the parent, gated by Watchlight. If the spawn is refused, the sub-agent never runs. The sub-agent runs only on the handle its own spawn produced, and only while that `task` call is running; it never reuses another sub-agent's handle. Spawns are refused unless the agent was built with `create_governed_deep_agent(...)`, which installs governance in every sub-agent.
- **Provider-hosted tools.** Web search, code execution, file search or a remote MCP server that a model call puts in its provider request is decided before the request is sent, under the run that makes the call (the root's, or a `task` sub-agent's own run). A refusal raises `HostedToolRefused` and nothing is sent. Chat model classes are checked too. See [Provider-hosted tools](#provider-hosted-tools).
- **Egress.** When a Watchlight proxy URL is configured (`connect_proxy_url` or `WATCHLIGHT_PROXY_URL`), the run is refused with `GovernanceUnavailable` if Watchlight issued no proxy token or the local sidecar fails to start. It never falls back to direct egress. **One governed run per process.** While a run owns the egress proxy, starting another run in the same process raises `SidecarRunActive` (a `GovernanceUnavailable`) and leaves the running one as it is. The owning run releases it when it ends, or when its session expires (`ttl_seconds`, 3600 by default) if it is never completed. Once the owner has ended, its sidecar is stopped and `HTTPS_PROXY` stays on the stopped port, so traffic fails rather than going direct. Run concurrent governed runs in separate processes.
- **Async only.** DeepAgents runs on the async LangGraph runtime. The synchronous invocation path is refused.
- **A governed agent started inside a live run does not open a root of its own.**
  - While a governed run is live in the process, another `create_governed_deep_agent(...)` agent that would start a root outside it is refused with `NestedRunEscapedError` (a `WatchlightError`) before its first model turn. This covers an agent built and invoked inside a tool (awaited directly, or from an executor, a thread pool, a `threading.Thread`, a fresh `contextvars.Context`, or a deferred start after the tool returned) and two undeclared roots started at once.
  - Without this, it would run with none of its parent's attenuation and no link to its lineage. Run sub-agents through `task` instead.
  - Independent roots that run at the same time are declared with `root_run()` (from `watchlight_deepagents`), a context manager (sync or async) and a decorator:

    ```python
    async with root_run():
        await agent.ainvoke({"messages": [...]})
    ```

  - The server decides `Action::"open_declared_root"` with the root execution ids live in the process, and records the declaration. A refusal raises `DeclaredRootRefused`. A server that does not confirm the declaration (an older server) gets its session closed, and the run is refused (`declared_root_unsupported`).
  - `root_run()` is refused inside a live run, including a tool body.
  - An agent whose `task` spawn was refused cannot start through `root_run()` while that run tree is live (`SpawnRefusedRootRunError`).
  - With no governed run live, a run opens as before. There is no setting that turns this off.
- **Ungoverned agents built inside a tool are refused.** An agent that one of your tools builds and runs itself, such as a plain `create_deep_agent(...)` called inside a tool, has no Watchlight middleware. (A governed one is covered by the previous item.) While a governed run is live in the process, the plugin refuses such an agent's work before it runs, whatever thread, config or callbacks it is given:
  - Each tool call the plugin authorizes may start exactly one tool: the one with that call's id and name, once. Any other tool start is refused before the tool runs.
  - A model call made inside the body of a governed tool is refused. If a tool really needs to call a model directly, for example to summarize text, wrap that call in `with direct_model_use():` (from `watchlight_deepagents`). A model call that binds tools is refused even then, so the escape never covers an agent's turn.
  - A model call that binds tools, local or hosted by the provider, is refused unless it is a governed agent's own turn. Hosted tools run on the provider's side, where no tool start is visible, so this is where they are stopped.
  - Each refusal is recorded in the run's lineage as a denied call, with names only and never argument values.

  This is a change in behaviour: a tool that used to run an inner agent, or call a model directly, now fails with `UngovernedModelCall` or `UngovernedToolCall` (both are `GovernanceUnavailable`). Spawn sub-agents through `task` with `create_governed_deep_agent(...)`, which governs them, or use `direct_model_use()` for a direct, tool-less model call. Governed `task` sub-agents and DeepAgents' own summarization are not affected. With no governed run live, nothing is refused.

  The check is a callback the plugin registers once with LangChain, through LangChain's public configure hook; no framework class is patched. It has limits:
  - The live-run state is shared by the whole process. While a governed run is live, an ungoverned agent running at the same time elsewhere in the same process is refused too.
  - A model call that binds no tools, made on a new thread or in a fresh `contextvars.Context` started from a tool body, is not refused. It can run no tool: its tool starts are refused, and it binds no hosted tool.
  - A governed agent run inside another governed agent's ordinary tool has its own summarization refused. Run it as a `task` sub-agent instead.
  - Each authorized call may start its tool once, so a retry must pass through Watchlight's middleware again. A retry middleware must sit outside Watchlight's: one that runs inside it and calls the tool again within the same call has the retry refused. `create_governed_deep_agent(...)` places Watchlight's middleware ahead of the `middleware=` you pass, so a tool-retry middleware passed there runs inside it. Retry at the model level instead, as a new tool call, which is authorized again.
  - A refusal that cannot be published to lineage still stands. It is logged at warning level and counted in `watchlight_core.langchain_tool_backstop.emit_failures()`.
  - Code that calls a tool's private `_run`, a model's private `_generate`, or a provider SDK directly bypasses LangChain's callbacks and is not seen by this check. A provider request that such code sends through a supported SDK while a run is live is still refused when it binds a tool (see [Provider-hosted tools](#provider-hosted-tools)). Neither is code that deliberately removes LangChain's configure hooks or resets the plugin's context variables, which turns governance off on purpose.

Not enforced:

- **Model turns are not authorized one by one.** The plugin records each model turn and refuses it when there is no governed run or when the run is quarantined. It does not send a per-turn authorization request; only the provider-hosted tools a turn enables are decided. Governance of the model's network calls comes from the Watchlight proxy, when you configure it.
- **A policy does not see argument values.** The plugin sends argument names, count and types only. The path of a filesystem call is in the resource name (`deepagents://fs/<path>`).
- **Reporting is best-effort.** A model-turn or tool-call event that the plugin cannot publish does not stop the run.
- **The check on agents built inside a tool has limits.** They are listed with it, above.

- **One LangChain-governing plugin per process.** `watchlight-langgraph` and `watchlight-deepagents` govern the same LangChain surfaces. While one of them has a governed run live, or opening, in the process, the other refuses to open one with `OtherPluginGoverns` (a `GovernanceUnavailable`) that names both plugins, and it works again once that run has ended (completed or severed; a quarantined run still counts, and so does a run that was started and never completed, so complete or terminate every run). This covers a deepagents-governed agent invoked inside a `watchlight-langgraph` run, the reverse, and a run in another task. Two plugins on one agent would decide each tool call twice, under two resource names, in two root runs. Use one of them per process; runs of the same plugin are not affected.

## Provider-hosted tools

Some model providers run tools on their own servers, inside the model call: web search, code execution, file search or a remote MCP server. No tool node sees them, so the plugin decides them before the request is sent, with no change to your agent.

The governance middleware marks each governed model call with the run that makes it: the root agent's run, or a `task` sub-agent's own run. Every request that a supported provider SDK (`anthropic`, `openai`, `google-genai`) sends from that call is read as it leaves, and each hosted tool in it gets one policy decision, on `Tool::"<kind>"` (a remote MCP server is `Resource::"mcp://<name>/"`), under that run. The decision is made on the request the SDK actually sends, so it also covers fields a model class adds on its own, such as `ChatAnthropic(mcp_servers=...)` (but see "Hosted capabilities set on the model" below). A deny, a required approval, an error or a timeout raises `HostedToolRefused`, nothing is sent, and the run ends. Function tools are not decided here; the tool gate decides them when they are called.

- **Chat model classes.** A governed model call must use a class whose requests go through one of those SDKs: `ChatAnthropic`, `ChatOpenAI`, `AzureChatOpenAI`, `ChatXAI` or `ChatGoogleGenerativeAI`. Any other class, including a subclass of one of these, is refused with `UnknownModelClassRefused` before it is called. To use another class, list it in `allowed_model_classes=["package.module:ClassName"]` on `WatchlightDeepAgentsPlugin(...)`. An allowed class is plain chat only: a call of it that binds any tool is refused with `UnknownModelClassRefused`, because its requests may not go through a supported SDK. A deep agent binds its tools to every model call, so in practice an allowed class works only when its `bind_tools` binds nothing, as a scripted test model's does. Listing a class is your statement that it has no hosted capability, including one set on the model itself, such as an MCP server field. Each listed class is logged at WARNING on every governed model call.
- **Remote MCP servers.** Pass `registered_mcp_servers={"<server URL>": "<name>"}` to `WatchlightDeepAgentsPlugin(...)`. A request that enables a server not in that map is refused before any decision.
- **Calls outside a governed model call.** While a root run is open, a provider request that binds any tool but is not made by a governed model call is refused with `UnmarkedToolBindingRefused`: for example a direct `anthropic` client call in a tool body, or a call from a raw thread. The refusal is logged at WARNING with the reason `unmarked_tool_binding`. It is raised where the request was made: code that catches it carries on and the run goes on, but uncaught in a tool body it escapes the tool and ends the run, like any other exception from a tool. A LangChain model call refused this way is also recorded in the run's lineage as a denied model call; a request made with a provider SDK directly is logged and counted, not recorded. A request with no tools passes. With no governed run live, nothing changes. The live-run state is shared by the whole process, so run unrelated agents in a separate process.
- **When a run ends.** A root run stops counting as open when it completes, and when it ends with an error or a cancel. In a model or tool call, every agent closes its run. For an agent built with `create_governed_deep_agent(...)`, the run also closes when its graph ends anywhere else (a recursion limit, another middleware's error, a cancel, a stream you stop reading), with its sub-agents' runs, also when the invocation resumed the run with `Command(resume=...)`, and through copies of the graph (`with_config`, `copy`, `with_retry`). A run at an interrupt is paused, not ended, and stays open until it is resumed: a stream you stop reading at the interrupt (the root's, or with `subgraphs=True` a sub-agent's, which is streamed first), and a resume that fails before it answers the interrupt. To tell the two apart the graph reads the thread's checkpoint for at most one second; a read that fails, takes longer or is cancelled counts as not paused, and the run closes. The run stops counting as open before that read, and counts again only if it is paused. A stream you stop reading with no interrupt pending ends the run, and continuing that thread later is refused with `GovernanceUnavailable`. New input on a paused thread moves it past the interrupt: the paused run is closed. An invocation never closes a run that another invocation is running, for example a second one refused on the same thread. An agent built with `plugin.middleware()` closes only in model and tool calls: if its graph fails elsewhere, the run stays open and every tool-binding provider request in the process is refused, so build agents with `create_governed_deep_agent(...)`.
- **Hosted capabilities set on the model.** DeepAgents' summarization middleware runs ahead of Watchlight's and calls your model itself, outside the governed model call. A hosted capability set on the model object, such as `ChatAnthropic(mcp_servers=...)`, goes on that request too, so when the agent summarizes, the request is refused with `UnmarkedToolBindingRefused` (nothing is sent) and the run ends. Bind hosted tools with `tools=[...]` instead, which summarization does not send. The chat model class check does not apply to the summarization call either; it binds no tools.
- **The wraps must be in place.** A run whose provider SDK or LangChain wrap was replaced is refused with `GovernanceUnavailable` before its first model call.
- **Not covered.** A hosted capability that an allowed class turns on by itself, without binding a tool, is not seen; that is why the allow-list is your statement that the class has none. Governed egress covers its traffic. A direct call of a model's `_generate` reports no LangChain callback, so the class check does not run for it; the SDK gate still decides its request when it goes through a supported SDK.
- **Conformance.** To run the conformance suite against this plugin (`watchlight-conformance watchlight_deepagents`), the hosted-tool check sends its probe through whichever supported provider SDK is installed (`anthropic`, `openai` or `google-genai`, tried in that order), so install any one of them with the plugin and `watchlight-agent-sdk-testing`. With none installed the check fails, never skips.

The provider SDK gate supports `anthropic` from 0.69, `openai` from 1.109 and `google-genai` from 1.53.

## Settings

`create_governed_deep_agent(...)` takes the arguments of `create_deep_agent` and these:

| Argument | What it sets |
|---|---|
| `agent_slug` | Required. The registered slug of the root agent. |
| `plugin` | The `WatchlightDeepAgentsPlugin` to use. Without it, the factory calls `WatchlightDeepAgentsPlugin.from_env()`. |
| `subagent_scopes` | For each sub-agent name, the scope its spawn asks for: `allowed_tools`, `allowed_resources`, `allowed_intents`, `max_depth` and `time_budget_seconds`. Name a tool as `deepagents://tool/<name>`. A sub-agent with no entry is spawned with no tools and `max_depth` 0. |
| `subagent_slugs` | The registered slug of each sub-agent name. The default is the sub-agent's name. |

`WatchlightDeepAgentsPlugin(...)` takes `governance=` (a backend such as `InProcessClient`), or `apdp_url=` for the Enterprise server, and these arguments for [provider-hosted tools](#provider-hosted-tools):

| Argument | What it sets |
|---|---|
| `registered_mcp_servers` | Remote MCP servers a model call may enable: `{"<server URL>": "<name>"}`. Policy sees a server as `Resource::"mcp://<name>/"`. |
| `allowed_model_classes` | Chat model classes a governed run may use beyond the supported ones: `["package.module:ClassName"]`. A malformed entry raises `ValueError` when the plugin is built. |

It reads these variables:

| Variable | What it sets |
|---|---|
| `WATCHLIGHT_APDP_URL` | Enterprise: the server URL. `from_env()` requires it and raises `GovernanceUnavailable` when it is not set. |
| `WATCHLIGHT_TENANT_ID` | Enterprise: the tenant, read by `from_env()`. |
| `WATCHLIGHT_PLUGIN_TOKEN` | Enterprise: the plugin credential. The SDK README lists the [other places a credential is read from](https://github.com/watchlight-ai-beacon/watchlight-de/blob/main/integrations/plugins/python/watchlight-core/README.md#settings). |
| `WATCHLIGHT_PROXY_URL` | The Watchlight proxy that egress goes through. The same as `connect_proxy_url=`. |
| `WATCHLIGHT_PROXY_CA_CERT` | A PEM CA bundle used to verify an `https://` Watchlight proxy. |
| `WATCHLIGHT_APPLICATION_ID` | The AI application the runs belong to. See below. |
| `WATCHLIGHT_INTENT_ENFORCEMENT_MODE` | `brownfield` (the default) or `greenfield`. The same as `intent_enforcement_mode=`. In `greenfield` the agent is given the `watchlight.declare_intent` tool. |
| `WATCHLIGHT_PLAN_GOVERNANCE_MODE` | `degrade` lets a run start when no constraint manifest could be obtained. Without it the run is refused. Use it only for development. |

### Attributing runs to an AI application

Every governed run can be attributed to the AI application the agent belongs to. Pass `application_id="<application UUID>"` to `WatchlightDeepAgentsPlugin(...)`, or per run to `start_run(...)`, or set `WATCHLIGHT_APPLICATION_ID` in the environment (`from_env()` picks it up too). An explicit argument wins over the variable. The middleware opens runs with the plugin-level value, so a deployment attributes an agent without a code change. The server refuses the run if the agent is not a member of that application. An agent in exactly one application needs nothing here. The id is explicit configuration, never inferred from prompts or names, and a value that is not a UUID raises `ValueError`. It is an Enterprise feature: the Developer Edition engine refuses it.

## Errors

A refused tool call is not an exception. The model gets an error tool message in place of the tool's result and the tool never runs: for a denial by policy (`Denied by Watchlight policy.`, without the backend's reason), for an action that needs approval, for a tool the sub-agent was not granted, and for a `task` spawn refused for its scope or for a sub-agent that is not registered.

The errors below are raised to your code. Branch on the error class, not on the message text.

| Error | Meaning |
|---|---|
| `GovernanceUnavailable` | A governed run could not be opened or kept: `from_env()` without `WATCHLIGHT_APDP_URL`, a backend that did not open the run, no constraint manifest, a configured Watchlight proxy that cannot be used, a synchronous `invoke`, or a sub-agent the factory cannot govern (a pre-compiled `runnable` or a remote `graph_id`). |
| `AgentNotRegistered` | The root agent's slug is not registered. |
| `SidecarRunActive` | Another run in this process owns the egress proxy. A kind of `GovernanceUnavailable`. |
| `NestedRunEscapedError` | A governed agent tried to open a root of its own while a governed run was live. `SpawnRefusedRootRunError` is the kind raised for an agent whose `task` spawn was refused. |
| `DeclaredRootRefused` | A root declared with `root_run()` was not opened. A kind of `GovernanceUnavailable`. |
| `OtherPluginGoverns` | Another LangChain-governing Watchlight plugin (`watchlight-langgraph`) has a run live in this process, so the root run was refused before it opened. A kind of `GovernanceUnavailable`. |
| `UngovernedModelCall`, `UngovernedToolCall` | A model or tool call that no governed agent authorized was refused. Both are kinds of `GovernanceUnavailable`. |
| `HostedToolRefused`, `UnknownModelClassRefused`, `UnmarkedToolBindingRefused` | A model call or provider request was refused before it was sent. See [Provider-hosted tools](#provider-hosted-tools). Kinds of `WatchlightError`. |
| `AgentQuarantinedError` | The backend quarantined the run, and the agent loop stops. |

## Moving to Watchlight Beacon (Enterprise)

The Developer Edition decides with the engine inside your process. Watchlight Beacon is the Enterprise server. Your agent code stays the same: set `WATCHLIGHT_APDP_URL`, a credential (`WATCHLIGHT_PLUGIN_TOKEN`) and, in a multi-tenant deployment, `WATCHLIGHT_TENANT_ID`, and leave out `plugin=`, so the factory builds the plugin with `WatchlightDeepAgentsPlugin.from_env()`.

What changes when you move is described once, in the SDK README: [Moving to Watchlight Beacon (Enterprise)](https://github.com/watchlight-ai-beacon/watchlight-de/blob/main/integrations/plugins/python/watchlight-core/README.md#moving-to-watchlight-beacon-enterprise).

## Links

- Documentation: https://docs.watchlight.ai/de
- Source and issues: https://github.com/watchlight-ai-beacon/watchlight-de
- Website: https://watchlight.ai

## License

Apache-2.0

## Trademarks

DeepAgents, LangChain, LangGraph and other product names in this README belong to their respective owners. They are used only to describe compatibility. This plugin is not affiliated with, endorsed by or sponsored by them.
