Metadata-Version: 2.4
Name: watchlight-deepagents
Version: 0.1.2
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.12,>=0.11.0
Requires-Dist: deepagents<0.8,>=0.7
Provides-Extra: otlp
Requires-Dist: watchlight-agent-sdk[otlp]<0.12,>=0.11.0; 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.11; `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 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.
- **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. 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. 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.

## 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 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`. |
| `UngovernedModelCall`, `UngovernedToolCall` | A model or tool call that no governed agent authorized was refused. Both are kinds of `GovernanceUnavailable`. |
| `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.
