Metadata-Version: 2.4
Name: watchlight-langchain
Version: 0.1.0
Summary: Independent Watchlight governance for LangChain v1 create_agent agents: every tool call decided before it runs and every model call checked before it is sent, fail-closed. 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: LangChain, https://github.com/langchain-ai/langchain
Keywords: watchlight,langchain,ai-agents,ai-governance,agent-runtime
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
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.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: watchlight-agent-sdk<0.13,>=0.12.2
Requires-Dist: langchain<2,>=1.4.5
Requires-Dist: langchain-core<2,>=1.3.3
Requires-Dist: langgraph>=1.0.10
Requires-Dist: httpx>=0.27
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"
Requires-Dist: langchain-anthropic>=1.7.6; extra == "dev"
Dynamic: license-file

# watchlight-langchain

Watchlight authorization for LangChain `create_agent` tool calls and model calls, fail-closed.

`watchlight-langchain` puts a Watchlight authorization decision in front of every tool call your LangChain v1 agent makes, so each one is allowed or denied *before* it runs, and checks every model call before its provider request is sent. It is a drop-in `create_governed_agent(...)` factory built on the LangChain `AgentMiddleware` protocol, with 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. `LangChain`, `LangGraph`, and related names are trademarks of LangChain, used here nominatively only to describe compatibility.

**Two limits to know first.**

- **One governed root run at a time in a process**, unless each is declared with `root_run()`. A second governed agent invoked while a run is live, for example from a tool body, is refused with `NestedRunEscapedError` before its first model call. To run an agent from your agent, make it a governed [sub-agent](#sub-agents). With Watchlight Beacon (Enterprise), a server that handles one request per run wraps each request:

  ```python
  from watchlight_langchain import root_run

  async with root_run():
      result = await agent.ainvoke(request)
  ```

  `root_run()` needs Watchlight Beacon (Enterprise). The Developer Edition engine refuses a declared root with `DeclaredRootRefused` before anything runs. With the Developer Edition, run one governed root run per process.

- **One run per process can send its egress through the Watchlight proxy.** With `WATCHLIGHT_PROXY_URL` set, a second run that would use the proxy while one is open is refused with `SidecarRunActive`. Run one agent process per concurrent proxied run.

## Install

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

`watchlight-engine` is the compiled Developer Edition engine that `InProcessClient` uses. The plugin needs Python 3.10 or later, `langchain` 1.4.5 or later (below 2) and `watchlight-agent-sdk` 0.12.2 or later (below 0.13); `pip` installs both with it. The quickstart model needs `langchain-anthropic` and `ANTHROPIC_API_KEY`.

## Quickstart

Swap `create_agent` for `create_governed_agent`, name the agent with `agent_slug`, and give the plugin a backend. Your tool code and the model loop do not change.

```python
import asyncio
from watchlight_core import InProcessClient
from watchlight_langchain import WatchlightLangChainPlugin, create_governed_agent

# A tool call is decided as Action::"execute" on Resource::"<tool name>". This policy lets the agent search and nothing else.
POLICIES = [{"name": "search-only", "code": 'permit(principal is Agent, action == Action::"execute", resource == Resource::"search_web") when { principal.name == "research-agent" };'}]
plugin = WatchlightLangChainPlugin(governance=InProcessClient(POLICIES))  # decisions are made in-process, with no network
agent = create_governed_agent("anthropic:claude-sonnet-5-5", [search_web, send_email], agent_slug="research-agent", plugin=plugin)
result = asyncio.run(agent.ainvoke({"messages": [{"role": "user", "content": "Find the Q3 filings and email them."}]}))
for message in result["messages"]:
    if message.type == "tool": print(message.name, message.status, message.content)
```

Here `search_web` and `send_email` are your own tools. When the model calls both, the output is:

```text
search_web success <what your search_web returned>
send_email error Watchlight refused this action. The tool did not run.
```

The `send_email` call is refused: the model gets that error in place of the tool's result, and the tool never runs. 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; its `method` and `path` are empty, and a refused model call carries `response_status` 403), and one event per tool call with its decision. No argument value and no prompt text is written or sent: a decision sees the argument names, count and types only.

## Which Watchlight package for my agent

| Your agent | Package |
|---|---|
| LangChain v1 `create_agent` | `watchlight-langchain` (this package) |
| A LangGraph graph you build yourself (`StateGraph`, `ToolNode`) | `watchlight-langgraph` |
| DeepAgents `create_deep_agent` | `watchlight-deepagents` |

Use one of them per process: see [Two Watchlight plugins in one process](#two-watchlight-plugins-in-one-process).

## What is and is not enforced

Enforced:

- **Every tool call is decided before it runs**, as `Action::"execute"` on `Resource::"<exact tool name>"`. An Allow runs the call once. A Deny, a backend that cannot be reached and a decision that takes longer than 30 seconds each give the model the error `Watchlight refused this action. The tool did not run.`, and the tool never runs.
- **An action that needs human approval is refused.** This agent cannot pause for an approval yet, so the model gets `Watchlight: this action needs human approval, which this agent does not support yet. The tool did not run. Do not retry it.` The event records the decision as `needs_approval`, not as a denial.
- **A run opens before the first model call and closes on every exit**: completion, an exception, a cancel, a recursion limit, a stream you stop reading, on the agent or a copy of it (`with_config`, `with_retry`). A run paused at an interrupt stays open for its resume for at most its TTL (`ttl_seconds`, one hour by default). Never resumed, it is closed as failed; a resume after the TTL, from another thread, or in another process is refused with `RunNotOpen` before anything runs. If you read the agent with `astream` and stop at the interrupt, close the stream (`await stream.aclose()`) before you resume: while the old stream is still open, its invocation still holds the run, and the resume is refused with `RunNotOpen`.
- **Only the async runtime is governed.** `invoke`, `stream`, `batch` and a synchronous resume are refused with `GovernanceUnavailable` before any model call. Use `await agent.ainvoke(...)` or `agent.astream(...)`, or `asyncio.run(...)` from synchronous code.
- **While a run is live, a tool start or a tool-binding provider request that no governed call authorized is refused** (`UngovernedToolCall`, `UnmarkedToolBindingRefused`), and a quarantined run stops before its next model call.

Not enforced:

- Code inside a tool body runs as written once the call is allowed. Egress from it is governed only through the Watchlight proxy.
- The goal (`goal_id=`) is checked by the server: the Developer Edition engine does not model goals.
- A governed agent started from inside a governed run is refused (see the first section) unless it is a governed [sub-agent](#sub-agents).
- **Handoffs** are governed only as the tool call that returns the `Command` (for example `Command(goto=..., graph=Command.PARENT)`): that call is decided like any other, and the run closes, as completed, when the handoff leaves the agent. Whatever runs after the handoff is not governed by this run. To govern a delegated agent, use a [sub-agent](#sub-agents) or build the multi-agent graph with `watchlight-langgraph`.
- A model call that your own middleware makes directly (calling `request.model` itself instead of passing the request on) does not go through the gate. A plain-chat call made that way is not recorded; one that binds a tool or a provider-hosted tool is refused with `UngovernedModelCall` before it is sent.

## Sub-agents

A sub-agent is an agent your agent calls as a tool. Build it with `create_governed_subagent`, turn it into a tool with `plugin.subagent`, and give the tool to the parent:

```python
from watchlight_core import RequestedScope
from watchlight_langchain import create_governed_subagent

researcher = create_governed_subagent("anthropic:claude-sonnet-5-5", [search_web], plugin=plugin)
research = plugin.subagent(
    researcher,
    name="research",
    description="Research one question on the web and answer in one paragraph.",
    agent_slug="research-subagent",
    scope=RequestedScope(allowed_tools=["search_web"]),
)
agent = create_governed_agent("anthropic:claude-sonnet-5-5", [send_email], subagents=[research], agent_slug="research-agent", plugin=plugin)
```

**A quarantine, terminate, revoke or sever decision in a sub-agent ends the whole tree, the parent included,** even when a middleware inside the sub-agent catches the error. The sub-agent's run closes, the decision's exception (`AgentQuarantinedError`, `ExecutionTerminatedError`, `AgentRevokedError` or `SubtreeSeveredError`) is raised from the parent's `ainvoke` instead of being returned to the parent model, the parent's run closes, and any sub-agent still running beside it is stopped. The record names the sub-agent the decision came from. A tree that one of these decisions reached is no longer trusted, so the parent does not go on with the sub-agent's output or try another route to the same goal.

How a sub-agent is governed:

- **Built governed.** `plugin.subagent` accepts only a graph from `create_governed_subagent` built for the same plugin. A plain `create_agent` graph, a `create_governed_agent` agent, a runnable or a factory is refused with `GovernanceUnavailable`, and so is a sub-agent with a `checkpointer`, `interrupt_before`, `interrupt_after` or a `HumanInTheLoopMiddleware`. Invoked directly, a sub-agent graph is refused before its first model call: it runs only from its tool.
- **Each call is a spawn the server decides.** The sub-agent runs as `agent_slug` with `scope`, which the server accepts only when it is within the parent's own; it is never widened or shortened. A refused spawn never runs the sub-agent: no model call, no tool call. There is no separate `Action::"execute"` decision on the sub-agent tool. The sub-agent then calls only the tools its scope names, each decided as the sub-agent.
- **`scope` is required.** `RequestedScope()` grants nothing. `allowed_tools` may name only tools the sub-agent has. A sub-agent that holds a sub-agent tool of its own must name that tool in `allowed_tools` and give it a scope within its own, with a smaller `max_depth`. A named `time_budget_seconds` above what the parent or the tenant allows is refused, never shortened.
- **Always timed.** Every sub-agent runs under a timer in your process, set to the nearer of its granted budget and its granted deadline. When the grant names neither, the timer is the plugin's `subagent_timeout_seconds` (600 by default). That setting is a ceiling in your process only, never sent as a named budget. A sub-agent still running when its timer ends is stopped. A grant whose deadline has already passed, or whose budget or deadline cannot be read, refuses the spawn before the sub-agent runs.
- **Isolated.** The tool takes one string, `request` (at most 32 KiB), which is the sub-agent's only message. The sub-agent starts from empty state and sees nothing of the parent's conversation. It runs as a graph of its own: it gets the parent's callbacks, so your tracing shows it under the parent, and nothing else of the parent's config (no `configurable` keys, thread, checkpoint, store, tags or metadata). The tool returns the text of the sub-agent's last answer, or `Watchlight: the sub-agent finished without a text answer.`; the sub-agent's state never reaches the parent's.
- **Intent from configuration.** The sub-agent's objective is the tool's `description`, never the request text. Its intent category is `child_intent=`, else the one category the scope's `allowed_intents` pins, else the plugin's `child_intent_category=`, else the parent's. A `child_intent=` that differs from the pinned category is refused when the tool is built.
- **Fixed messages.** The parent model gets one of these, with `<name>` the tool name, and never a reason from the server or the sub-agent:

  | Case | Message |
  |---|---|
  | The spawn was refused | `Watchlight: the sub-agent '<name>' was not started. Do not retry it.` |
  | The spawn needs approval | `Watchlight: starting this sub-agent needs human approval, which this agent does not support yet. The sub-agent did not run. Do not retry it.` |
  | The sub-agent stopped for human input | `Watchlight: the sub-agent '<name>' asked for human input, which a sub-agent does not support yet. It was stopped. Do not retry it.` |
  | The sub-agent failed or ran out of time | `Watchlight: the sub-agent '<name>' did not complete. Its result is not available.` |

  At a spawn, the server cannot yet signal that an approval is needed in a way this plugin can read for certain, so a spawn that needs approval may be recorded as a Deny with the first message. Either way the sub-agent does not run.

  A sub-agent that stops for human input (an `interrupt`) is closed as failed, and the parent goes on. A handoff, a drain or a cancel in a sub-agent closes it and reaches the parent as it would from a tool.
- Parallel tool calls each spawn their own sub-agent. Two tools with one name in one agent are refused when the agent is built.

## Using your own middleware

Pass your middleware with `middleware=[...]`. The factory places the Watchlight lifecycle middleware first and the Watchlight gate last, around yours:

```text
[watchlight_lifecycle, *your_middleware, watchlight_gate]
```

The gate holds the innermost tool and model wraps, so it decides on the call your middleware pass on, and nothing can change the call after its decision. A retry middleware of yours gets one decision per attempt. The Watchlight middleware cannot be built or passed by hand in this version.

## Two Watchlight plugins in one process

`watchlight-langchain`, `watchlight-langgraph` and `watchlight-deepagents` each govern LangChain tool calls process-wide while a run is live. While a run of one is live, a root run of another is refused with `OtherPluginGoverns` before it opens. A run that has ended does not block.

## Intent (greenfield)

With `intent_enforcement_mode="greenfield"` (or `WATCHLIGHT_INTENT_ENFORCEMENT_MODE=greenfield`) the agent is given a `watchlight.declare_intent` tool. A declaration sets the run's objective and intent category for every later decision. It can only narrow: the goal is set in code with `goal_id=` when the run opens, no tool argument changes it, and the server refuses an action whose declared category the goal does not allow.

## Provider-hosted tools

A provider can run a tool on its own servers inside a model call (web search, code execution, a remote MCP server). Every hosted tool on a governed model call is decided on the request the provider SDK sends, and a refused one is never sent; the refusal is written to the run's events. A chat model class the plugin does not know is refused unless you list it in `allowed_model_classes=` (as plain chat only). The SDK README describes [provider-hosted tools](https://github.com/watchlight-ai-beacon/watchlight-de/blob/main/integrations/plugins/python/watchlight-core/README.md) in full.

**Conformance.** To run the conformance suite against this plugin (`watchlight-conformance watchlight_langchain`), 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.

## Settings

`create_governed_agent(model, tools, ...)` takes the arguments of `create_agent` and these:

| Argument | What it sets |
|---|---|
| `agent_slug` | Required. The registered slug of the agent. Configuration only, never taken from a prompt. |
| `plugin` | The `WatchlightLangChainPlugin` to use. Without it, the factory calls `WatchlightLangChainPlugin.from_env()`. |
| `middleware` | Your own middleware, placed between the Watchlight middleware. |
| `subagents` | Governed sub-agents: tools from `plugin.subagent`, or mappings of its keyword arguments. |
| `goal_id` | The run's goal, set in code. |
| `ttl_seconds` | The session TTL, and how long a paused run waits for its resume. Default 3600. |

`WatchlightLangChainPlugin(...)` takes `governance=` (a backend such as `InProcessClient`), or `apdp_url=` for the Enterprise server, and:

| 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. |
| `intent_enforcement_mode` | `brownfield` (the default) or `greenfield`. |
| `application_id` | The AI application the runs belong to (Enterprise). |
| `child_intent_category` | The intent category of a sub-agent whose `plugin.subagent` names none and whose scope pins none. |
| `subagent_timeout_seconds` | The timer of a sub-agent whose grant names no budget and no deadline. Default 600; below 1 raises `ValueError`. Never sent to the server. |

`plugin.subagent(agent, ...)` takes `name` (the tool name), `description` (what the model reads and the sub-agent's objective), `agent_slug` (the registered agent it runs as), `scope` (required) and `child_intent` (its intent category).

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()`. Required with `WATCHLIGHT_PLUGIN_TOKEN`. |
| `WATCHLIGHT_PLUGIN_TOKEN` | Enterprise: the plugin credential. |
| `WATCHLIGHT_PROXY_URL` | The Watchlight proxy that egress goes through. The same as `connect_proxy_url=`. |
| `WATCHLIGHT_APPLICATION_ID` | The AI application the runs belong to. An explicit argument wins. |
| `WATCHLIGHT_INTENT_ENFORCEMENT_MODE` | `brownfield` or `greenfield`. |

## Errors

A refused tool call is not an exception: the model gets an error tool message and the tool never runs. 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, a synchronous `invoke`, `stream` or `batch`, Watchlight middleware used outside `create_governed_agent`, or a sub-agent that is refused when it is built or called without its spawn. |
| `RunNotOpen` | A hook found no open run: the run was closed, its pause expired, or it was opened on another thread or in another process. A kind of `GovernanceUnavailable`. |
| `AgentNotRegistered` | The 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 while a governed run was live, without `root_run()`. |
| `DeclaredRootRefused` | From `watchlight_core`. A root declared with `root_run()` was not opened, for example on the Developer Edition engine, which does not support declared roots. A kind of `GovernanceUnavailable`. |
| `OtherPluginGoverns` | Another LangChain-governing Watchlight plugin has a run live in this process. A kind of `GovernanceUnavailable`. |
| `UngovernedModelCall`, `UngovernedToolCall` | A model or tool call that no governed agent authorized was refused. |
| `HostedToolRefused`, `UnknownModelClassRefused`, `UnmarkedToolBindingRefused` | A model call or provider request was refused before it was sent. |
| `AgentQuarantinedError` | The backend quarantined the run, and the agent stops. Raised by a sub-agent, it ends the whole tree. |
| `ExecutionTerminatedError`, `AgentRevokedError`, `SubtreeSeveredError` | From `watchlight_core`. The backend ended the run; raised by a sub-agent, they end the whole tree. |

## 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 its tenant (`WATCHLIGHT_TENANT_ID`, required with a plugin token), and leave out `plugin=`, so the factory builds the plugin with `WatchlightLangChainPlugin.from_env()`. What changes when you move is described 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

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.
