Metadata-Version: 2.4
Name: watchlight-langgraph
Version: 0.5.2
Summary: Watchlight governance for LangGraph agents: while a governed run is open, every tool a ToolNode runs is decided by policy before it runs, fail-closed. Also explicit calls to authorize actions, validate plans and spawn attenuated sub-agents. 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
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.27
Requires-Dist: langchain-core<2,>=1.3.3
Requires-Dist: langgraph>=1.0.10
Requires-Dist: watchlight-agent-sdk<0.12,>=0.11.0
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Dynamic: license-file

# watchlight-langgraph

Governance for LangGraph agents with Watchlight. While a governed run is open,
every tool that LangGraph's `ToolNode` runs is decided by your Cedar policies
before it runs, with no change to your graph. The plugin also gives your nodes
explicit calls: authorize an action, check a plan, and spawn a sub-agent with a
narrower scope. The same code runs against the Developer Edition engine inside
your process and against Watchlight Beacon (Enterprise).

The plugin is open source (Apache-2.0). It is an independent integration; see
[Trademarks](#trademarks).

## Install

```bash
pip install watchlight-langgraph "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, `langgraph`
1.0.10 or later and `langchain-core` 1.3.3 or later (earlier releases of both
carry known advisories), and `watchlight-agent-sdk` 0.11, which
`pip` installs with it. CI tests it on Python 3.12 and 3.13.

## Quickstart

```python
import asyncio
from watchlight_core import InProcessClient
from watchlight_langgraph import WatchlightLangGraphPlugin

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

async def main():
    plugin = WatchlightLangGraphPlugin(governance=InProcessClient(POLICIES))  # decisions are made in-process
    async with await plugin.start_run(agent_slug="research-agent") as handle:
        print(await handle.authorize_action("read", "dataset"))
        print(await handle.authorize_action("delete", "dataset"))

asyncio.run(main())
```

```text
True
False
```

The policy lets the research agent read and nothing else, so `delete` is
denied. The principal is the agent's id, `Agent::"<agent uuid>"`;
`principal.name` is its registered name (under `InProcessClient`, the slug it
was started with). The quickstart also writes the run's start and completion
events to `.watchlight/audit.jsonl` in the current directory; the completion
event carries the counts of actions taken and denied.

Inside the `async with` block, run your graph as usual: every tool its
`ToolNode` runs is decided for this run. The plugin asks for the action
`execute` on the tool's name; with `InProcessClient` that is
`Action::"execute"` on `Resource::"<tool name>"`. The policy above permits
only `read`, so it denies every tool: add a `permit` for `Action::"execute"`
for the tools the agent may run.

## What is and is not enforced

No setting lets an action run undecided. A decision that cannot be made
refuses the action. That covers an unreachable backend, an unreadable answer and a missing
wrap the plugin relies on, and nothing in the plugin's configuration turns it
off. The one related setting, `WATCHLIGHT_PLAN_GOVERNANCE_MODE=degrade`, only
lets a run start without a pre-flight manifest; every action in that run is
still decided.

Enforced:

- `handle.authorize_action(...)` and `handle.authorize_action_detailed(...)` ask for a decision before an action. `authorize_action` returns `True` only for an Allow. A Deny returns `False` (or a Deny result). When no decision can be made, the call returns `False` or raises, so the action does not run as long as your code honours the answer and does not catch and ignore the exception.
- `governed_tool_call(handle, tool_name, ...)` (in `watchlight_langgraph.governance`) wraps a tool implementation: it runs the tool only on Allow, raises `ToolDenied` on Deny, and pauses the graph with LangGraph `interrupt` when a human approval is needed.
- `handle.submit_plan(...)` and `handle.preflight_step(...)` validate a plan or a step and return Allow, Modify or Deny. Your code must act on the result. With the Developer Edition engine (`InProcessClient`), `submit_plan` raises `NotImplementedError`: validate each step with `preflight_step`, or authorize each action.
- `handle.spawn_subagent(..., child_intent=ChildIntent(category, objective))` asks the backend for an attenuated child run. The child intent is required and must derive from the parent run's intent and goal. A refused spawn raises, and the child gets its own credential and scope, granted exactly the declared intent category.
- `plugin.start_run(...)` refuses to start (raises `AgentNotRegistered` or `GovernanceUnavailable`) when the agent is not registered, the backend does not accept the session, or a Watchlight proxy URL is configured but governed egress cannot be set up. **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.
- Every tool that LangGraph's `ToolNode` runs while a governed run is open is authorized before it runs, with no change to your graph. This covers `create_agent`, `create_react_agent` and graphs you build yourself with `ToolNode`. A run is open from the moment `start_run` (or `spawn_subagent`) returns it until it completes or is terminated. The call is decided for the run acting where the graph runs: the sub-agent that `spawn_subagent` bound there, its parent again once that sub-agent has completed, or else the run that `start_run` returned. An allowed tool runs, a denied tool raises `ToolDenied` and its body never runs, a tool that needs a human approval pauses the graph through `interrupt`, and a tool whose decision cannot be made is refused. Decisions need the run entered with `async with handle:`. A graph that runs after a bare `start_run` is refused with an error that says so. If the installed LangGraph does not have the `ToolNode` methods the plugin wraps, `start_run` refuses the run.
- While a governed run is open, any other tool start in the process is refused with `UngovernedToolCall`: a tool called directly with `tool.invoke(...)`, a tool started with `callbacks=[]`, from a raw thread or from a fresh context, and a second tool started inside an allowed tool's body. A model call that binds tools is allowed as the acting run's own turn, and refused inside a tool body (an agent built inside a tool) or where no run acts, with `UngovernedModelCall`. A model call without tools inside a tool body is allowed. Each refusal is recorded in the run's lineage, when the run was entered with `async with`.
- Each provider-hosted tool on a model call is decided before the provider request is sent. See [Provider-hosted tools](#provider-hosted-tools).
- Sub-agents: a sub-agent's graph runs as that sub-agent, never with its parent's authority, whether or not you enter it with `async with child:`. While a live sub-agent is bound in a context, `spawn_subagent` there raises `SiblingSubagentLive` unless that sub-agent is the one spawning (nesting). This covers a sibling, a grandchild and any other live sub-agent. Finish a sub-agent before you spawn its sibling in the same context, or spawn each sub-agent in an asyncio task created before any sub-agent is bound (a task copies the context it was created in).
- Root runs: one live root run per context. Start concurrent root runs in separate asyncio tasks.
- A run that is never completed or terminated stays open for the life of the process, and every tool start outside it stays refused. Use `async with`, or call `complete()` or `terminate()`.

Not enforced:

- The callback handlers (`WatchlightCallbackHandler`, `WatchlightAsyncCallbackHandler`, `handle.callback_handler()`) only observe. They record tool, model and chain events for lineage and never block a call.
- Plain Python code is not a LangChain tool. A function that your graph calls directly, such as a tool's underlying `tool.func` or any helper in a node, runs in the run's context without a tool start, so neither the `ToolNode` gate nor the backstop sees it. Put actions behind a tool that `ToolNode` runs, or call them through `governed_tool_call`.
- A failed lineage report never stops the run.

## Settings

Arguments of `WatchlightLangGraphPlugin(...)`, and the environment variables
the plugin reads. Where both exist, the argument wins.

| Argument | Variable | What it sets |
|---|---|---|
| `governance` | | The backend that decides: `InProcessClient(...)` for the Developer Edition. When it is given, `apdp_url` is not used. |
| `apdp_url` | | Enterprise: the server's URL. The default is `http://localhost:8081`. |
| | `WATCHLIGHT_PLUGIN_TOKEN` | Enterprise: the plugin credential, loaded with `Credential.from_default()`. If no credential is found, the client sends none and the server refuses. |
| `connect_proxy_url` | `WATCHLIGHT_PROXY_URL` | Enterprise: the Watchlight proxy for governed egress. When it is set, a run starts only if governed egress is set up. |
| | `WATCHLIGHT_PROXY_CA_CERT` | A PEM CA bundle used to verify an `https://` Watchlight proxy. |
| `application_id` | `WATCHLIGHT_APPLICATION_ID` | Enterprise: the AI application every run belongs to. `start_run(application_id=...)` sets it for one run. See [Attributing runs to an AI application](#attributing-runs-to-an-ai-application). |
| `intent_enforcement_mode` | `WATCHLIGHT_INTENT_ENFORCEMENT_MODE` | `brownfield` (the default) or `greenfield`. In `greenfield`, `handle.bind_tools(model, tools)` adds the `watchlight.declare_intent` tool to the tools it binds. `bind_tools(..., mode=...)` sets it for one call. |
| `registered_mcp_servers` | | Remote MCP servers a model call may enable: `{"<server URL>": "<name>"}`. |
| `allowed_model_classes` | | Chat model classes a governed run may use beyond the supported ones: `["package.module:ClassName"]`. |
| `tenant_id` | | A tenant id stamped on the events the plugin reports. |
| `log_decisions` | | `True` (the default) logs the governance mode of each run that opens. |
| | `WATCHLIGHT_PLAN_GOVERNANCE_MODE` | `degrade` lets a run start without a pre-flight manifest. For development only. |

`start_run(agent_slug, goal_id=None, max_actions=None, ttl_seconds=3600,
subject_token=None, application_id=None)` opens a run. The other settings of
the SDK, such as the credential file and the log format, are listed in the
[SDK README](https://github.com/watchlight-ai-beacon/watchlight-de/blob/main/integrations/plugins/python/watchlight-core/README.md#settings).

## Errors

Branch on the error class, not on the message text.

| Error | Meaning |
|---|---|
| `AgentNotRegistered` | `start_run` or `spawn_subagent` named an agent that is not registered. |
| `GovernanceUnavailable` | The backend did not open the run or could not be reached, governed egress could not be set up, or the tool gate could not be put in place. Do not proceed. |
| `SidecarRunActive` | Another run in this process owns the egress proxy. A kind of `GovernanceUnavailable`. |
| `ToolDenied` (`watchlight_langgraph.governance`) | A tool was denied; its body did not run. The message is a generic refusal, and `reason` carries the backend's reason for your own code. |
| `UngovernedToolCall`, `UngovernedModelCall` | A tool or a tool-binding model call started outside the acting run's `ToolNode` while a governed run is open. Kinds of `GovernanceUnavailable`. |
| `SiblingSubagentLive` | `spawn_subagent` was called where another live sub-agent is bound. A kind of `GovernanceUnavailable`. |
| `ScopeAttenuationDenied` | A sub-agent was refused because it asked for more than its parent has. |
| `RunHandleInvalidated` | A sub-agent was refused because its parent's run handle is no longer valid. |
| `AgentQuarantinedError` | The run was quarantined; it cannot act or spawn. |
| `HostedToolRefused`, `UnknownModelClassRefused`, `UnmarkedToolBindingRefused` | A model call was refused before its request was sent. See [Provider-hosted tools](#provider-hosted-tools). |
| `ValueError` | An `application_id` that is not a UUID, or `delegation_scope` mixed with the scope arguments of `spawn_subagent`. |

All of these except `ToolDenied`, `AgentQuarantinedError` and `ValueError` are
`WatchlightError`s from `watchlight_core`.

## Moving to Watchlight Beacon (Enterprise)

The Developer Edition decides with the engine inside your process. Watchlight
Beacon is the Enterprise server. Your graph and your plugin calls stay the
same. You change the backend:

```python
plugin = WatchlightLangGraphPlugin(apdp_url="https://watchlight.your-company.example")
```

The plugin credential comes from your secret store or the environment, never
from source code. What changes when you move (configuration, identity, agent
ids, lineage and the features the Developer Edition refuses) 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).

## Provider-hosted tools

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

Inside `async with await plugin.start_run(...)`, the run's context is marked. Every request that a supported provider SDK (`anthropic`, `openai`, `google-genai`) sends from that context 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>/"`). 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=...)`. A deny, a required approval, an error or a timeout raises `HostedToolRefused`, and nothing is sent. Function tools are not decided here; your tool nodes govern them. The full list of provider APIs, and which are decided or refused, is in the SDK README under "Deciding on the request the provider SDK sends".

- **Chat model classes.** In a run, a LangChain chat 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 `WatchlightLangGraphPlugin(...)`. 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. 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 when a run opens.
- **Remote MCP servers.** Pass `registered_mcp_servers={"<server URL>": "<name>"}` to `WatchlightLangGraphPlugin(...)`. A request that enables a server not in that map is refused before any decision.
- **Synchronous calls.** `model.invoke(...)` from a worker thread, the way LangGraph runs a sync node, is decided on the run's event loop while the thread waits. A synchronous call that enables a hosted tool on the run's own event-loop thread is refused, because waiting there would deadlock. Use `ainvoke` in async code.
- **Calls outside the run's context.** While a governed run is live in the process, a request that binds any tool but does not carry a run's context is refused with `UnmarkedToolBindingRefused`. Such a call might come from a raw thread that did not copy the context, or from code outside `async with`. A task that outlives its run is refused the same way. The refusal is logged at WARNING with the reason `unmarked_tool_binding`, and it does not end the live run. A call with no tools passes. With no governed run live, nothing changes, so run unrelated LangChain agents in a separate process.
- **Conformance.** Running the conformance suite against this plugin (`watchlight-conformance watchlight_langgraph`) needs the `openai` package installed: the hosted-tool check sends its probe through that SDK and fails without it.
- **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`, or of a provider client from a tool, 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.

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

## 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 `WatchlightLangGraphPlugin(...)`, or per run to `start_run(...)`, or set `WATCHLIGHT_APPLICATION_ID` in the environment — an explicit argument wins over the env var. The id is sent on session create and bound to the run credential and to every sub-agent the run spawns; the server refuses the session 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 it is an Enterprise feature: the in-process Developer Edition engine refuses it.

## Learn more

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

## License

Apache-2.0.

## Trademarks

This is an independent integration built by Watchlight AI. It is not
affiliated with, endorsed by or sponsored by LangChain. LangGraph, LangChain,
Anthropic, OpenAI, Azure, Gemini, xAI and other product names in this README
belong to their respective owners. They are used only to describe
compatibility.
