Metadata-Version: 2.5
Name: tenet-langchain
Version: 0.7.0
Summary: Tenet PII governance integration for LangChain agents
Project-URL: Homepage, https://tenetlabs.com
Project-URL: Documentation, https://docs.tenetlabs.com/sdk/tenet-langchain
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: compliance,governance,langchain,pii,redaction
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Requires-Python: <3.14,>=3.11
Requires-Dist: langchain>=1.2.13
Requires-Dist: tenet-client<0.8.0,>=0.7.7
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: respx>=0.21; extra == 'dev'
Requires-Dist: ruff==0.15.12; extra == 'dev'
Description-Content-Type: text/markdown

# tenet-langchain

LangChain integration for the [Tenet](https://tenetlabs.com) compliance SDK.
Built on top of the framework-agnostic [`tenet-client`](../tenet-client)
package — install this one if you're building a LangChain agent; install
`tenet-client` directly if you're not.

```bash
pip install tenet-langchain
```

## What's new in 0.7.0

Needs `tenet-client>=0.7.7`. Everything below is opt-in; with no new option set the
requests the judge receives are unchanged.

- [`request_shaper` and friends](#tell-the-judge-what-the-tool-does--request-shaping): per-tool
  surface, tool descriptions, the user's own ask and candidate text, without subclassing the client.
- [`on_decision`](#record-every-decision--on_decision): one `DecisionRecord` per judged call, with
  Langfuse and logging sinks.
- [`mode="shadow"`](#try-it-before-you-enforce-it--modeshadow) and the
  [final-reply check](#try-it-before-you-enforce-it--modeshadow) (`check_agent_output`): see what
  the judge would do before enforcing.
- [Human review](#recipes) with `interrupt_policy()`, and
  [review state that survives a restart](#reviews-that-survive-a-restart), including
  [rewrites and refusals](#rewrites-and-refusals).
- [`strict_tools`](#make-sure-every-tool-is-classified) and the
  [recursion-limit helper](#recursion-limit).
- [Per-thread state](#sharing-one-instance-across-conversations) and
  [`on_timeout`](#primary-path--create_agent--tenetjudgemiddleware--judgepolicy) dispatch
  (a timeout reaches `on_timeout`, and falls back to `on_unavailable` when unset).

## You own the agent lifecycle

Tenet evaluates and returns a *verdict*. Your application *policy*
decides what to do with it — allow, review, block, override the call,
fail-open, hand off to a human reviewer. Modeled loosely on Galileo
Protect's stage/action split: the centralized judge produces the verdict,
your local policy maps it to a runtime action.

That means you keep calling `langchain.agents.create_agent` yourself.
Tenet ships as a middleware you drop into the `middleware=[...]` list,
not a façade that owns agent creation.

## Three control levels

| Level | Surface | When to use |
|---|---|---|
| **1. Raw client** | [`TenetCloudJudgeClient`](../tenet-client) + [`evaluate_phase`](../tenet-client/src/tenet_client/cloud_client.py) | Custom agents (no LangChain), FastAPI middleware, queue workers, anywhere you want full control. |
| **2. LangChain middleware** | [`TenetJudgeMiddleware`](src/tenet_langchain/tenet_judge_middleware.py) + [`JudgePolicy`](../tenet-client/src/tenet_client/policy.py) | The primary path. Drop into a `create_agent(...)` middleware list; policy callbacks decide every outcome. |
| **3. Convenience helper** | [`wrap()`](src/tenet_langchain/wrap.py) (deprecated) | Preserved for alpha integrations. Owns the agent lifecycle for you, which removes control over middleware order and policy dispatch. New code should use level 2. |

The local-server path ([`TenetMiddleware`](src/tenet_langchain/middleware.py))
remains unchanged for self-hosted Tenet desktop / on-prem deployments.

## Primary path — `create_agent` + `TenetJudgeMiddleware` + `JudgePolicy`

```python
from langchain.agents import create_agent
from tenet_client import (
    JudgeAction,
    JudgePolicy,
    TenetCloudJudgeClient,
)
from tenet_langchain import TenetJudgeMiddleware

judge = TenetCloudJudgeClient.from_env()

policy = JudgePolicy(
    on_block=lambda ctx, verdict: JudgeAction.tool_error(
        verdict.safe_message or "Blocked by Tenet."
    ),
    on_review=lambda ctx, verdict: JudgeAction.allow(metadata={"tenet_review": True}),
    on_unavailable=lambda ctx, error: JudgeAction.raise_error(error),
    on_timeout=lambda ctx, error: JudgeAction.raise_error(error),
)

agent = create_agent(
    model="claude-sonnet-4-5-20250514",
    tools=[],
    middleware=[
        TenetJudgeMiddleware(judge, policy=policy),
    ],
)
```

`JudgePolicy()` with no callbacks gives you the safe defaults — block →
`tool_error`, review → soft-allow with metadata, unavailable / timeout →
re-raise (fail-closed). Override only what you want to change.

`on_unavailable` runs when the judge cannot be reached or returns an error.
`on_timeout` runs when the call times out (`JudgeTimeoutError`); if you leave
it unset, a timeout falls back to `on_unavailable`, so setting only
`on_unavailable` covers both.

### `from_env()` environment variables

`TenetCloudJudgeClient.from_env()` needs two variables — the credentials
Tenet provisions for your account:

- `TENET_CLIENT_ID`
- `TENET_CLIENT_SECRET`

Both are required; `from_env()` raises `ValueError` naming any that are
missing. Everything else (cloud URL, Auth0 audience, Auth0 issuer)
points at Tenet-operated infrastructure and uses sensible production
defaults — you should not need to set them.

Optional tuning knobs, if you want them: `TENET_JUDGE_ID` (defaults to
`hr-1`; set `healthcare-1` for the PHI / clinical-safety judge) and
`TENET_JUDGE_TIMEOUT_SECONDS` (defaults to `3.0`).

If you'd rather pass credentials explicitly, call `TenetCloudJudgeClient(...)`
directly with the same keyword arguments.

### Per-tool and per-phase policies

Stricter rules for high-risk tools, softer rules for low-risk ones:

```python
from tenet_client import JudgeAction, JudgePolicy
from tenet_langchain import TenetJudgeMiddleware

policy = JudgePolicy(
    per_tool={
        "send_email": JudgePolicy(
            on_block=lambda ctx, v: JudgeAction.tool_error("Cannot send PHI."),
        ),
        "search": JudgePolicy(
            on_block=lambda ctx, v: JudgeAction.allow(),
        ),
    },
    per_phase={
        "tool_post": JudgePolicy(
            on_block=lambda ctx, v: JudgeAction.override_output(
                "Sorry, I can't share that."
            ),
        ),
    },
)
```

Per-tool wins over per-phase wins over the top-level callbacks.

### Read-intent — `read_tools` / `intent_resolver` (0.4.0)

The engine reads a top-level `intent` field on the `/decide` body as its
**highest-precedence** intent signal. On a benign first-party read (e.g.
"what have we said to this candidate") a missing intent resolves to `unknown`,
which grades the call against the strict *action* ceiling and needlessly
escalates. Declaring which tools are reads lets the middleware assert
`intent="read"` so those calls fast-pass.

Declare the read taxonomy **once** at construction. Either enumerate the read
tools, or supply a resolver (for a computed taxonomy):

```python
from tenet_langchain import TenetJudgeMiddleware  # or CloudJudgeMiddleware

mw = TenetJudgeMiddleware(
    judge,
    policy=policy,
    judge_tools_pre={"schedule_interview", "send_phone_screen"},  # mutating → pre
    judge_tools_post={"top_candidates", "read_messages"},         # reads → post
    read_tools={"top_candidates", "read_messages"},               # ← intent="read"
    # or, for a computed taxonomy (wins over read_tools):
    # intent_resolver=lambda tool_name: "read" if tool_name.startswith("read_") else None,
)
```

The `intent` wire field takes `read` | `action` | `unknown` (default *unset* ==
`unknown`, omitted from the body). `read` / `action` are emitted; `unknown` /
`None` are omitted so the envelope is byte-identical to not sending it.

#### Safety contract — `tool_post`-only, enforced in code

> A caller-asserted `intent="read"` is stamped **only at `phase == "tool_post"`**
> for a tool in `read_tools` (or one the resolver classifies `read`). It is
> **never** emitted at `agent_input` or `tool_pre` — even if the tool name
> matches `read_tools`.

This is not a convention; it is enforced by `resolve_read_intent`
(`tenet_langchain._intent`), which applies the phase gate **before** consulting
`read_tools` / `intent_resolver`. The reason: a read is authoritative only where
the judged tool's read-only nature is verifiable (at `tool_post`, backed by the
engine's operator read-tool allowlist + the `tool_input` protected-class
ratchet). At `agent_input` a caller read is a **guardrail bypass** — the engine
proved that forcing `intent="read"` on the `agent_input` traps leaked 8/10 (probe
709cd6a) — so the engine now treats an `agent_input` caller intent as advisory,
re-derives read-eligibility from the prompt itself, and the SDK never sends it
there. `tool_pre` (actuating, pre-execution) is likewise never a read.

`intent_resolver` is consulted only at `tool_post`; it must return `read`,
`action`, `unknown`, or `None`. Never blanket `intent="read"` onto an actuating
tool — resolve it from the single audited taxonomy above. See the
[wire contract](../tenet-client/docs/integration_contract.md) for the field
semantics and the `X-Tenet-Api-Version` header.

### What the judge sees — `context_keys` / `context_builder` (0.6.0)

The judge reasons over the call's `context`: the facts it weighs, such as
`role`, `job_description`, `stage` or `consent_on_file`. Facts move verdicts;
tool names and claims don't (see the engine's "passing tool context" guide).

tenet-client 0.7.1 replaced the old behaviour, where a dict of tool args was
splatted into `context` key-by-key, with an explicit `context=` argument
(the splat warns in 0.7.1, errors in 0.8.0 and is removed in a later release). Both
middlewares now pass `context=` for you, so you see no warning, and **by
default the judge sees exactly what it saw before**: every tool arg, minus
the names the SDK reserves (`tool_output`, `tool_input`, `recruiter_prompt`,
`candidate_content`, `tool_name`, `surface`, `phase`, `intent`, `workflow`).
`recruiter_prompt` / `candidate_content` still reach the judge, because the SDK
reads them from the tool args itself. The only change is for a tool arg whose
*name* collides with one of the others: it is no longer forwarded, so an arg
called `tool_name` can't overwrite the real tool name and an arg called
`intent` can't assert a caller signal through `context`.

To choose what the judge sees, pass one of:

```python
from tenet_langchain import TenetJudgeMiddleware  # or CloudJudgeMiddleware

# An allowlist of tool arg names:
mw = TenetJudgeMiddleware(judge, policy=policy, context_keys={"role", "job_description"})


# Or a function (tool name, a copy of the args) -> context dict:
def judge_context(tool_name: str, args: dict) -> dict:
    return {"role": args.get("role"), "job_description": lookup_posting(args["job_id"])}


mw = TenetJudgeMiddleware(judge, policy=policy, context_builder=judge_context)
```

`context_keys` and `context_builder` are mutually exclusive. A builder that
returns a reserved key raises `ValueError` before anything is sent. Tool
*output* never enters `context`: it travels as a tool-role message.

### Tell the judge what the tool does — request shaping

The judge sees a tool call as its arguments and little else. These options add
facts it can reason over, without subclassing the client:

```python
from tenet_langchain import JudgeCall, RequestShape, TenetJudgeMiddleware

def shaper(call: JudgeCall) -> RequestShape | None:
    # Runs for every judged call, including agent_input; non-None fields win.
    return RequestShape(context={"role": current_page.job_title})

mw = TenetJudgeMiddleware(
    judge,
    policy=policy,
    surface_for_tool={"rank_candidates": "resume_triage_rank"},  # per-call surface
    tool_descriptions={"rank_candidates": "Ranks applicants for the open role."},
    send_user_prompt_on_tool_phases=True,  # the user's own words, not a dump of the args
    request_shaper=shaper,
)
```

- `surface_for_tool`: the `surface` for a listed tool at `tool_pre` / `tool_post`;
  other tools use the client's surface.
- `tool_descriptions`: sent as `context["tool_description"]` for a listed tool.
- `send_user_prompt_on_tool_phases`: the latest user message goes out as
  `user_prompt=` (the judge's `recruiter_prompt`) on tool phases, unless the tool's
  own arguments already carry a `recruiter_prompt`.
- `request_shaper`: gets a `JudgeCall` (phase, tool name, input, output, latest user
  message, graph state, runtime) and returns a `RequestShape` (`surface`, `context`,
  `user_prompt`, `candidate_content`) or `None`. `context` is merged over the default
  context; `candidate_content=` is how the output of a tool is judged as candidate
  text. A shaper that raises propagates, so a bug is never silently sent unshaped.

Reserved context keys (`tool_name`, `recruiter_prompt`, ...) are still rejected by the
client with `ValueError`; use `user_prompt` / `candidate_content` for those. The
verdict cache key includes whatever was shaped. If you also call the client directly,
`default_judge_context(tool_name, tool_input)` returns the same default `context` the
middleware builds for that call, and `RESERVED_CONTEXT_KEYS` lists the names to keep out.

`max_tool_output_chars` (default `None`, no cap) cuts the tool output sent to the
judge at `tool_post` to that many characters, because large outputs drive judge
latency. The cut applies to the judge's copy only: the `tool_output` a
`request_shaper` sees and the verdict cache key use the cut text, while the tool's
real result returned to the agent and the `JudgeContext.tool_output` your policy
callbacks receive stay whole. Must be `>= 1`.

`send_user_prompt_on_tool_phases` is silently a no-op for a call whose arguments
already carry `recruiter_prompt`: the judge reads the arguments' own ask.

These options change what the judge reads, so they can change verdicts. Turn them
on in a test environment and compare before production.

### Record every decision — `on_decision`

`on_decision` takes a sink, or a list of sinks, and gets one `DecisionRecord` per
judged call after the policy has chosen an action. `outcome` is that action's kind
(`allow`, `block`, `tool_error`, `retry_nudge`, ...), `turn_approved` when turn
approval passed the call, `interrupted` when a review callback paused the run, or `policy_error` (with
`extra={"error": "<ExceptionName>"}`) when a policy callback raised any other
exception; that exception is then re-raised unchanged. A cache hit carries `extra={"cached": True}`; with the judge unavailable
`decision` is `"unavailable"` and `outcome` is what the policy did. A failing sink
is logged and never affects the run.

```python
import logging
from tenet_client.observability import langfuse_score_sink, logging_sink
from opentelemetry import trace

def app_trace_id() -> str | None:
    ctx = trace.get_current_span().get_span_context()
    return format(ctx.trace_id, "032x") if ctx.is_valid else None

mw = TenetJudgeMiddleware(
    judge,
    policy=policy,
    on_decision=[
        logging_sink(logging.getLogger("tenet")),
        langfuse_score_sink(langfuse),
    ],
    trace_id_provider=app_trace_id,
)
```

`trace_id_provider` returns the run's trace id (32 hex characters), so
`record.trace_id` is your own trace and `langfuse_score_sink` scores it. `None` or an
invalid value falls back to a generated id. Trace ids do not reach Tenet; they live
on the client call, `JudgeContext` and the record.

A human-review pause writes an `interrupted` record, and the resumed pass writes
another (marked `cached` when `cache_verdicts` is on), so a paused review yields two.

### Try it before you enforce it — `mode="shadow"`

"What would the judge do to my traffic?" should not need enforcement to answer.
With `mode="shadow"` every phase the middleware would judge is judged without
acting: the policy is never dispatched, the hooks return as if the call were
allowed, and each check ends in one `DecisionRecord` with `mode="shadow"` and
`outcome` set to the verdict (`allow`, `caveat`, `review`, `block`, `degraded`,
`unavailable`, or `skipped`). Nothing is cached, approved or written to review
state.

```python
import logging
from tenet_client.observability import logging_sink
from tenet_langchain import TenetJudgeMiddleware

mw = TenetJudgeMiddleware(
    judge,
    mode="shadow",
    check_user_messages=True,
    on_decision=logging_sink(logging.getLogger("tenet")),
)
agent = create_agent(model=model, tools=tools, middleware=mw.middlewares())
```

Async hooks (`ainvoke` / `astream`) judge in a background task and never wait for
the answer. Sync hooks judge inline under `shadow_timeout_s` (default 15 seconds),
which adds that latency to the turn, so prefer async. A judge that fails or misses
the deadline is recorded as `unavailable`; a shadow check never raises into the turn.
`stream=True` is ignored in shadow mode. `shadow_timeout_s` must be a finite number above
zero. If your `is_user_message` raises in shadow mode, the error is logged and that check is
skipped. `with_human_review(..., mode="shadow")` raises `ValueError`: it would build a review
recipe that never reviews.

A consumer of the records should filter on `outcome`: a skipped check is recorded with
`decision="unavailable"` like a judge outage, and only `outcome` tells them apart.

Shadow checks share the judge's capacity with checks that block, and a burst of them
once tripped the engine's circuit breaker. A `ShadowRunner` therefore allows only
`max_in_flight=2` checks at a time and skips the rest (recorded with
`outcome="skipped"`, `extra={"reason": "in_flight_limit"}`); a skipped check is
never queued. The default runner is one per process, so apps that build the
middleware per request share a single cap. Pass `shadow_runner=ShadowRunner(...)`
to use your own, and call `await default_shadow_runner().drain()` at application
shutdown so checks in flight finish.

Shadow checks never open or close the client's circuit breaker (they are sent with
`record_breaker=False`), so a fault only the shadow checks see cannot fail a real turn,
and their successes do not reset the enforcing checks' failure count. They are skipped,
with no network call, while the breaker is open.

The cap applies to the async hooks only: sync shadow hooks run inline and are not capped.
The records of checks still in flight are lost if the event loop closes without a
`drain()` (a script that ends right after `asyncio.run(...)` sees none), and `drain()`
waits only for the checks of the loop that calls it.

To record a verdict on the agent's final reply (`phase="agent_output"`), add the
reply check:

```python
agent = create_agent(
    model=model,
    tools=tools,
    middleware=mw.middlewares(check_agent_output="shadow"),
)
```

`middlewares()` returns `[mw, RefusedExchangeFilter?, AgentOutputCheck(...)]` (the
filter only when `refusal_marker` is set), sharing the sinks, request shaper and
runner. The check's middleware name derives from the parent's `name=`, so two named
judges can share one agent. `AgentOutputCheck` is a separate class so users who do not turn
it on pay no extra graph node per model call. It checks only a model message with
text and no tool calls (not the canned text of a block), sends it as `agent_reply=`
with the user's latest message as `user_prompt=`, and only observes: `mode="enforce"`
is not supported, since holding or retracting a streamed reply is a product decision
for your app. A `request_shaper` receives a `JudgeCall` with `phase="agent_output"`,
the reply as `tool_input`, and the user's ask as `user_message`.

### Make sure every tool is classified

The middleware judges by tool name, so with `judge_tools_pre` / `judge_tools_post` set, a
tool added later and listed nowhere runs with no check and no warning. Classify every tool:
judged (`judge_tools_pre`, `judge_tools_post`), a read (`read_tools`), or deliberately not
judged (`unjudged_tools`, a mapping from tool name to the reason, or just names). Leaving a
phase list unset (`None`) means every tool is judged at that phase, so name both lists.

```python
mw = TenetJudgeMiddleware(
    judge,
    judge_tools_pre=["send_email"],
    judge_tools_post=["send_email"],
    read_tools=["search_candidates"],
    unjudged_tools={"move_stage": "ids and a stage name only; the ask behind it is judged"},
    strict_tools=True,
)
```

With `strict_tools=True`, a call to a tool that no enabled phase judges, and that is neither in
`read_tools` nor in `unjudged_tools`, does not run: the tool wrapper raises
`UnclassifiedToolError` naming the tool. "Judged" is what the wrapper itself decides: the
phase's `check_pre` / `check_post` is on and its list is unset (every tool) or names the tool.
A disabled phase covers nothing, and an unset list covers every tool only at an enabled phase.
So with `judge_tools_pre=["a"]`, the post list unset and `check_post` on, an unlisted tool is
judged at post and runs; with `check_post=False` it raises. It applies in `mode="shadow"` too,
since the point is to find the tool before you enforce. A tool both judged and in
`unjudged_tools` raises `ValueError` at construction.

The error is a deploy-time guard, not a recovery path. Raised in the middle of a turn it leaves
the thread with an assistant tool call that has no result (the tool did not run), which a
provider rejects on the next turn. Use `assert_tools_classified` in a test so it fires before
production.

Catch it in CI rather than in production, with one line in your test suite:

```python
def test_every_tool_is_classified():
    mw.assert_tools_classified(all_tools)
```

It raises `UnclassifiedToolError` listing every unclassified tool, and every name in a list
that no tool carries (a stale entry after a rename). `mw.tool_classification(all_tools)`
returns the label per tool: `pre`, `post`, `pre+post` (enabled phases only), `read`, `unjudged` or
`unclassified`. Both accept anything `create_agent` does as a tool: a `BaseTool`, a plain
function, a provider dict tool (skipped when it has no `name`) or a name.

### Recursion limit

`create_agent` turns each node hook a middleware overrides into a graph node, and each node
run uses one LangGraph recursion step. `TenetJudgeMiddleware` costs one step per run
(`before_agent`) plus one per model call (`before_model`), whether or not
`check_user_messages` is on; tool judging costs none. `AgentOutputCheck` costs one more per
model call. `RefusedExchangeFilter` costs none (`recursion_steps` returns 0), and
`judge_unanswered_messages` adds none: it is the same node judging more messages. A turn
near your `recursion_limit` can fail with `GraphRecursionError` unless you add the cost:

```python
max_model_calls = 16
middleware = mw.middlewares(check_agent_output="shadow")
limit = 50 + sum(m.recursion_steps(model_calls=max_model_calls) for m in middleware)
agent.invoke(inputs, {"recursion_limit": limit})
```

### Recipes

**Block hard.** Default. Returns a `ToolMessage(status="error")` to the agent.

```python
from tenet_client import JudgeAction, JudgePolicy

policy = JudgePolicy(
    on_block=lambda ctx, v: JudgeAction.tool_error(v.safe_message or "blocked"),
)
```

**Review only — never block, just tag for audit.**

```python
from tenet_client import JudgeAction, JudgePolicy

policy = JudgePolicy(
    on_block=lambda ctx, v: JudgeAction.allow(metadata={"flagged": True}),
    on_review=lambda ctx, v: JudgeAction.allow(metadata={"flagged": True}),
)
```

**Fail-open dev mode.** When the cloud is flaky in dev.

```python
from tenet_client import JudgeAction, JudgePolicy

dev_policy = JudgePolicy(
    on_unavailable=lambda ctx, err: JudgeAction.allow(),
    on_timeout=lambda ctx, err: JudgeAction.allow(),
)
```

**Human review handoff.**

```python
from tenet_client import JudgeAction, JudgePolicy

def queue_for_review(ctx, verdict):
    queue.push({
        "session_id": ctx.session_id,
        "tool_name": ctx.tool_name,
        "verdict": verdict.model_dump(),
    })
    return JudgeAction.tool_error("Waiting on human review.")

policy = JudgePolicy(on_block=queue_for_review)
```

**Human review.** `TenetJudgeMiddleware.with_human_review(...)` pauses the agent on a
`review` or `block` verdict, with a LangGraph interrupt, and decides from the answer whether the
flagged message or tool call goes on. It needs a checkpointer on `create_agent` and a stable
`thread_id`.

```python
from langchain.agents import create_agent
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command

from tenet_client import TenetCloudJudgeClient
from tenet_langchain import APPROVE, TenetJudgeMiddleware, interrupt_policy

judge = TenetJudgeMiddleware.with_human_review(
    TenetCloudJudgeClient.from_env(),
    policy=interrupt_policy(strict_approve=True),  # only an explicit approve approves a message
)
agent = create_agent(
    model="claude-sonnet-4-5-20250514",
    tools=[send_claim_to_payer],
    middleware=judge.middlewares(),
    checkpointer=InMemorySaver(),
)
config = {"configurable": {"thread_id": "case-123"}}

result = agent.invoke({"messages": [{"role": "user", "content": "Submit the packet."}]}, config=config, version="v2")
if result.interrupts:
    prompt = result.interrupts[0].value  # show prompt["display_message"] and prompt["choices"]
    agent.invoke(
        Command(resume={**APPROVE, "review_id": prompt["review_id"]}),
        config=config,
        version="v2",
    )
```

The prompt is `format_review_event(...).to_dict()` plus `phase`, `review_id` and, for a message,
`user_message`. Ways to answer:

- `{"action": "approve", "review_id": ...}` approves (`APPROVE` is the first part).
- `{"selection": "<text>"}` at a message replaces it with that text, which is judged in turn. It is
  not an approval and leaves no approval behind. Anything else at a tool asks again.
- A block can only be dismissed; no answer lets it through.
- A message the judge reports as an attack on the agent (a `SAFETY-` label) gets no prompt: the turn
  ends with `DEFAULT_REFUSAL_MESSAGE`, and that exchange is hidden from later judge calls and the
  model. Set `refuse_label_prefixes=()` to turn that off.

Echo `review_id`. Without it, a resume that lands where the judge reports a different finding for
the same call approves the one the person never saw. A client that does not echo it still works.
At a message, any non-approve answer approves by default (what existing clients rely on); the recipe
above passes `interrupt_policy(strict_approve=True)`, which you should do in a new integration so
only `approve` does. Do not use `{"action": "approve"}` as a tool's own confirm answer: LangGraph
hands recorded answers back in order on a re-run, and that shape is taken as approving a flag.
`review_id` binds an answer to the kind of finding (phase, tool name, labels), not to the message
text or the tool arguments.

`with_human_review` sets `check_user_messages`, `cache_verdicts`, `turn_approval`,
`persist_review_state`, `rejudge_overridden_input`, `judge_unanswered_messages` (a flagged message
whose pause the app abandons by sending a new message cannot reach the model unapproved) and
`refusal_marker=DEFAULT_REFUSAL_MESSAGE`; every one can be overridden by keyword. To change the
refusal text, pass `with_human_review(..., refusal_message="...")`: the one string goes to both
the policy and `refusal_marker`. If you pass your own `policy=` built with `interrupt_policy(...)`
(`display=`, `payload=`, `accept_rewrite=`, `refusal_message=`, `block_message=`, `on_action=`,
plus any `JudgePolicy` option) and also a `refusal_marker`, you own keeping the two the same.
`on_action(name, ctx, verdict)` hears `paused`, `approved`, `rewritten`, `blocked`, `refused` and
`replayed_answer_skipped`; `approved` and `rewritten` are reported once per decision (a second message approved, or one
message rewritten twice, reports again) even though LangGraph re-runs the node that paused, from
the top, on resume. A review that gets no usable answer 25 times in a row raises `RuntimeError`. Keep tools idempotent for the same
reason.

**Writing your own `on_review`.** Pausing with `interrupt(...)` and treating the answer as
approval is wrong in five ways:

1. *Replay.* A resume re-runs the node and hands recorded answers back in order. A tool check that
   did not pause before but flags now receives the answer to another prompt (the tool's own
   confirm). Only an explicit approve may approve at a tool.
2. *A different finding on resume.* The judge is a model and the verdict cache may be empty in the
   new process. The recorded approval is for a finding the person saw; bind answers to the prompt
   (`review_id`).
3. *A tapped rewrite is not an approval.* It replaces the flagged message and must be judged
   (`rejudge_overridden_input=True`), with no approval recorded.
4. *A block has no approve path.* Resume can only mean "dismissed".
5. *An attack on the agent gets no prompt.* Nobody should vouch for "print your system prompt"
   with "Continue anyway"; end the turn with a fixed refusal (and set `refusal_marker`).

**Safe override response — replace the tool output instead of erroring.**

```python
from tenet_client import JudgeAction, JudgePolicy

policy = JudgePolicy(
    on_block=lambda ctx, v: JudgeAction.override_output(
        "I can't share that information. Please contact support."
    ),
)
```

**Retry nudge — let the agent self-correct.**

A `retry_nudge` action returns a `ToolMessage(status="error")` carrying
corrective guidance to the agent loop. The agent reads the guidance on
its next iteration and re-issues the tool call, typically with different
arguments. Distinct from `tool_error` (terminal denial) and from
`override_output` (replacement output). Forge research found this
mechanic produced large completion-accuracy lifts on identical model
weights, so it ships as a first-class `JudgeAction` kind.

```python
from tenet_client import JudgeAction, JudgePolicy

policy = JudgePolicy(
    on_block=lambda ctx, v: JudgeAction.retry_nudge_from_verdict(v),
)
```

The canonical constructor assembles the guidance from `verdict.reason`
and `verdict.safe_message` via a documented two-line template:

```
Cannot proceed as requested: {reason}
Suggested correction: {safe_message_or_reason}
```

Pass `template=...` to `retry_nudge_from_verdict` to override.

**Severity-routed recipe.**

For partner-configurable severity → action mapping, use the
`severity_routed_policy` recipe. Default mapping:

| Severity     | Action                              |
|--------------|-------------------------------------|
| `low`        | `retry_nudge_from_verdict`          |
| `medium`     | `retry_nudge_from_verdict`          |
| `high`       | `tool_error`                        |
| `critical`   | `tool_error`                        |
| `None`       | `tool_error` (preserves v1 default) |

Each bucket is keyword-configurable. `human_review_severities` is empty
by default and, when populated, takes precedence over `tool_error`:

```python
from tenet_client.recipes import severity_routed_policy

policy = severity_routed_policy(
    retry_nudge_severities=("low", "medium"),
    tool_error_severities=("high", "critical"),
    human_review_severities=(),
)
```

Pass through any other `JudgePolicy` kwargs (`on_unresolved`,
`on_unavailable`, `per_tool`, ...) via the same call.

**`on_unresolved` — workflow correction, not a compliance outcome.**

A tool can return a valid but empty result — "no records found", empty
list, null. The middleware detects these heuristically (see below) and
routes the case to `JudgePolicy.on_unresolved` independently of the
verdict's `allow|review|block`. The default callback returns
`retry_nudge_from_verdict(v)` so the agent gets a workflow correction
prompt; override to taste:

```python
from tenet_client import JudgeAction, JudgePolicy

policy = JudgePolicy(
    on_unresolved=lambda ctx, v: JudgeAction.retry_nudge(
        "No matches. Broaden the query or try a synonym."
    ),
)
```

### Resolution-status detection

After every tool call, `TenetJudgeMiddleware` classifies the return as
`resolved` / `unresolved` / (`error` — reserved for a future wave) and
threads the value to the judge so server-side rules can branch on it.
The default heuristics (case-insensitive substring match on the
stringified output):

- empty list `[]`, empty dict `{}`, empty string, or literal `"None"` → `unresolved`
- `"not found"`, `"no results"`, `"no match"`, `"0 results"` → `unresolved`
- anything else → `resolved`

Opt out per tool or globally on the middleware constructor:

```python
mw = TenetJudgeMiddleware(
    judge,
    policy=policy,
    resolution_detection=True,                              # default
    resolution_detection_excluded_tools={"send_email"},     # skip these tools
)
```

When opted out, the middleware threads `resolution_status=None`, which
preserves the pre-Phase-4.5 wire envelope and dispatch byte-for-byte.

### Retry-nudge budget + telemetry

To prevent runaway loops where the agent keeps re-issuing the same
broken call, the middleware tracks consecutive retry-nudges per tool
and escalates to `tool_error` once the budget is hit:

```python
mw = TenetJudgeMiddleware(
    judge,
    policy=policy,
    retry_nudge_max_consecutive=3,   # default; escalate on the 4th
)
```

Three counters live on `mw.telemetry`, each keyed by `(surface, tool)`:

- `mw.telemetry.emitted` — every retry-nudge synthesized
- `mw.telemetry.succeeded` — every chain that self-corrected (a non-nudge
  tool call followed a nudge on the same tool)
- `mw.telemetry.exhausted` — every chain that hit the budget and was
  escalated to `tool_error`

Read these directly to wire into whatever observability stack you have;
the middleware ships no external dependency.

### Verdict-first streaming

The judge exposes an SSE surface (`POST /eeo/decide/stream`) that emits the
verdict ~4× sooner than the full response. Opt in with `stream=True` and run
the agent with an **async** invocation (`ainvoke` / `astream`) — the sync
hooks have no streaming variant and ignore the flag.

```python
mw = TenetJudgeMiddleware(judge, policy=policy, stream=True)
```

The middleware branches on the stream's `route` event:

- `act_at_verdict` (route_to_human): the policy is dispatched the instant the
  `verdict` event lands — before the safe-message / explanation / rewrite body
  streams in — so a routing decision is available at ~TTV. The body is still
  drained and folded onto the verdict context for the HITL payload.
- `wait_for_done` (include / exclude / block): the rewrite or explanation *is*
  the actionable payload, so the stream drains fully and the policy is
  dispatched once on the complete verdict.

Behaviour and return types are otherwise identical to the non-streaming path —
it is a drop-in, A/B-able latency optimization. (For the raw client, the
equivalent toggles are `use_stream=True`, plus `evaluate_stream(...)` for a
verdict-first event iterator.)

### Multi-turn conversation history

The judge is stateless per call. On multi-turn BFOQ flows, sending only the
latest turn can read as discriminatory out of context. Set `send_history=True`
to send the **prior recruiter turns** (every prior `HumanMessage`, oldest
first) as additional `{"role": "user"}` messages ahead of the latest turn:

```python
mw = TenetJudgeMiddleware(judge, policy=policy, send_history=True)
```

Assistant turns are **never** sent — they carry no recruiter intent. Off by
default, in which case the wire envelope is byte-for-byte the single-turn shape.

### Reviews that survive a restart

By default the middleware remembers "this message was judged" and "the user
approved this finding for this turn" in memory on the instance. Turn on
`persist_review_state=True` when you run with a checkpointer and more than one
process, or rebuild the agent for every request: a resume that lands on a new
instance would otherwise judge the approved message again, and a tool that
raises the same finding would pause the user a second time.

```python
mw = TenetJudgeMiddleware(
    judge,
    policy=policy,
    check_user_messages=True,
    turn_approval=True,
    send_history=True,
    persist_review_state=True,
)
```

What is stored, in four private graph-state channels (they never reach the
caller's output), named `<review_state_prefix>_...` (`"tenet"` by default):

- `..._allowed_message_ids`: ids of user messages a real verdict let through.
  They are not judged again. A fail-open after `on_unavailable` / `on_timeout`,
  or a degraded answer, is not recorded, so that message is judged again. So is
  an allow the policy gave to a `block` verdict: only `allow`, `caveat` and
  `review` verdicts count as the judge clearing the message.
- `..._reviewed_message_ids`: the subset the policy approved on a `review`.
- `..._turn_approval`: the latest approval, `{"message_id", "risk_labels",
  "text_sha"}`. Before a judged tool call it is restored into the turn approval,
  so only the labels the user was shown are covered, and only for the message
  (and text) they approved.
- `..._allowed_text_digests`: message id to the sha256 of the text that was judged.
  An id is a name, not a promise about content, so a message is skipped (and an
  approval restored, and a reviewed message left out of history) only while its
  text still matches: an edited message that reuses its id, or a new message under
  the id of a removed one, is judged again. A record with no digest is legacy
  state (written before this channel existed, or by code that never wrote one) and
  is trusted by id alone.

Messages without an id are judged every time. Two middleware instances that
should not share state need different prefixes, and, because `create_agent`
rejects two middleware with the same name, different `name=` values
(`TenetJudgeMiddleware(judge, name="eeo_judge", review_state_prefix="eeo", ...)`).
Pass `review_state_prefix="judge"` to keep reading channels that already exist
under those names in your checkpoints.

History. With `exclude_reviewed_from_history=True` (the default, effective only
with `persist_review_state`) approved messages are left out of the prior user
turns sent to the judge: it reads every history turn as part of the current
request, so an approved finding otherwise comes back on every later message with
the old turn as its evidence. The model still sees them. Two hooks work with or
without persisted state:

- `is_user_message(msg) -> bool` says which `HumanMessage` are the user's own
  turns. Others (for example an answer your app echoes back as a
  `HumanMessage`) are never judged as the ask and never sent as history.
- `history_filter(candidates, state) -> list` receives the prior user messages
  (oldest first, after the exclusion above) and returns the ones to send. It
  runs last, and its output is sent as is: it may return messages outside its
  candidates, including the current one.

The default policy (no `on_review`) allows a `review`, so with persisted state that
allow is recorded as a reviewed id and a turn approval, with no human involved:
the message is then left out of later history. Pass an `on_review` that pauses if
that is not what you want.

Once `persist_review_state` or either hook is on, the judge path reads the user's
turns through the options above. A subclass that overrides the old static
`_prior_human_texts` or `_latest_human_text` is bypassed.

#### Rewrites and refusals

Two options for a human-review flow, whatever policy drives it.

`rejudge_overridden_input=True`. When the policy answers `override_input` at the
model boundary (for example the user picked a suggested rewrite), the default is
to swap in the new text and go straight to the model: the new text is never
judged, and the replacement drops the original message's id and kwargs, so the
thread no longer shows which message was replaced. With the option on, the
replacement keeps the original's `id` and `additional_kwargs` (plus
`additional_kwargs["tenet_rewrite"] = True`) and is judged as the new
`agent_input` before the model runs, again through your policy. A rewrite may be
overridden again; after three replacements the next `override_input` ends the turn
with "The rewritten message could not be approved." An `override_input` never
records a turn approval, and with `persist_review_state` the message id is
recorded as allowed only after the final allow. The replacement must itself be
the message that is judged: if `is_user_message` would not accept the replacement
text, the turn ends with the same "could not be approved" message instead of
judging some other message.

`judge_unanswered_messages=True` (needs `persist_review_state=True`). A flagged
message pauses the graph. If the app then sends a new message on the same thread
instead of resuming, the default is to judge only the latest message, and the
model receives the flagged one as history without an approval ever given. With the
option on, every user message after the last assistant message (per
`is_user_message`, refused exchanges excluded) that is not already recorded as
allowed is judged, oldest first, as `agent_input`. The first whose action is not
an allow decides the turn, and a pause is about that message; the model runs only
when all are allowed. A rewrite replaces whichever message was being judged. The block, refusal and
cap messages the middleware writes carry `additional_kwargs["tenet_answers"]` (the
id of the message they answer), so a message that sat before such a reply is still
judged on the next turn, and one the reply already answers is not judged again. The
tag is written only when `judge_unanswered_messages` is on or a `refusal_marker` is
set; with neither, the stored messages are what earlier releases wrote.

The option covers the messages after the last model reply. An in-place edit of a
message that was already answered (same id, new text, before the last reply) is not
re-judged, the same as without the option. Cost is one judge call per unanswered
message, so a thread restored with many unanswered messages is judged that many times
on its first turn. When several flagged messages are queued, each resume re-judges the
earlier ones (the node's record of them is lost at every pause) unless the verdict
cache is on (`cache_verdicts`).

`refusal_marker="..."`. When a message is an attack on the agent and the turn ends
with a fixed refusal, that exchange would otherwise stay in the conversation: with
`send_history` the judge flags every later message with the old turn as evidence,
and the refused instruction reaches the model on the next allowed turn. Set the
marker to the exact refusal text (`DEFAULT_REFUSAL_MESSAGE` is a ready one) and
return it from your block action. An `AIMessage` equal to the marker, with the
user message it refused, is a refused exchange (the message named by its
`tenet_answers` tag, or, for a reply with no tag, the user message right before it): it is left out of the history
sent to the judge, is never "the latest user message", and is removed from every
model request. The checkpoint keeps it, so the transcript still shows it. The
marker is matched against stored transcripts: never reword it once it is in
production, or old refusals come back into the conversation.

The policy-authored refusal (a block or tool-error message equal to the marker, and
the "could not be approved" message after a rewrite cap) is also tagged
`additional_kwargs["tenet_refusal"] = True`. An exchange counts as refused when its
reply carries the tag or equals the marker exactly, so threads stored before this
option, which have only the text, still match. A model reply that happens to equal
the marker hides the user message before it too; that is known and low
consequence.

The model request is cleaned by a separate middleware, `RefusedExchangeFilter`.
Hand `create_agent` `mw.middlewares()` rather than `[mw]`: it returns `[mw]` when
no marker is set, and `[mw, RefusedExchangeFilter(mw)]` when one is. The filter adds
a model-call wrapper (an edge and a trace span per model call) only when you opt in;
its name derives from the judge's `name=`, so two named judges can share an agent.
With a marker set and only `[mw]` passed, the first model call raises a
`RuntimeError` rather than letting refused text reach the model silently. The
filter changes the model request only: the checkpoint still holds the refused
exchange, so other middleware that reads state (a summarizer, say) still sees it.
If every message left is a refused exchange, the turn ends without calling the
model.

```python
from tenet_langchain import DEFAULT_REFUSAL_MESSAGE, TenetJudgeMiddleware

middleware = TenetJudgeMiddleware(
    judge,
    policy=JudgePolicy(
        on_block=lambda ctx, v: JudgeAction.tool_error(DEFAULT_REFUSAL_MESSAGE),
    ),
    check_user_messages=True,
    send_history=True,
    rejudge_overridden_input=True,
    refusal_marker=DEFAULT_REFUSAL_MESSAGE,
)
# create_agent(model=model, tools=tools, middleware=middleware.middlewares())
```

### Session grouping

Every judge call carries a conversation `session_id` so the server groups a
conversation's decision traces into one session. The
middleware uses your LangGraph `thread_id` when a checkpointer is configured
(so each conversation groups on its own), falling back to the middleware's
`session_id` constructor arg otherwise — the same conversation identity the
verdict cache and turn-approval features scope on. No configuration required;
to pin a fixed id for an out-of-graph deployment, pass
`TenetJudgeMiddleware(judge, session_id="…")`.

`ctx.session_id` in your policy callbacks is that same id, so a log line can be
joined to the judge's trace.

### Sharing one instance across conversations

When a thread id is configured (a checkpointer plus
`{"configurable": {"thread_id": ...}}`), one middleware instance is safe to
share across concurrent conversations: trace ids, retry-nudge budgets, the
verdict cache and turn approvals are all scoped to the thread. Without a thread
id every run shares one scope, as a single-conversation instance does.

Per-thread state is bounded: `TenetJudgeMiddleware(judge, max_threads=1024)`
keeps the 1024 most recently used threads and evicts the least recently used
beyond that. Evicting a thread drops its cache, approval, trace and retry-nudge
counters. A thread's trace id is constant within a run while the thread stays
among the `max_threads` most recently used; an evicted thread starts a new
trace on its next tool call.

### Support correlation — `X-Tenet-Canonical-Id`

Every judge call is tagged with a 32-hex `canonical_id` — the same value as the
`/decide` body's `decision_id`, and the key Tenet uses to find a decision in
its traces. It is returned on the `X-Tenet-Canonical-Id` response
header and the `request_accepted` / `done` stream events, surfaced on
`CloudJudgeResponse.canonical_id`, and folded onto the verdict context as
`ctx.metadata["tenet_canonical_id"]`.

**Runbook:** log the `canonical_id` on every judge call and quote it when you
report a decision to Tenet support. The middleware
emits it at `DEBUG` (`logging.getLogger("tenet_langchain.tenet_judge_middleware")`).
**Never** show it to the end user — it is an internal correlation key, not a
user-facing reference.

## Level 1 — raw client, no LangChain

For custom agents, FastAPI middleware, queue workers — anywhere you
don't want LangChain in the call path:

```python
from tenet_client import (
    JudgeAction,
    JudgePolicy,
    TenetCloudJudgeClient,
)

judge = TenetCloudJudgeClient.from_env()
policy = JudgePolicy()

verdict, action = judge.evaluate_phase(
    policy=policy,
    phase="tool_pre",
    tool_name="search",
    tool_input={"q": "patient lookup"},
)

if action.kind == "allow":
    result = run_search()
elif action.kind == "tool_error":
    result = action.message
elif action.kind == "raise_error":
    raise action.error
```

`evaluate_phase_async` is the async sibling.

## Level 1 — `@judged` for standalone tools

```python
from tenet_client import (
    JudgeAction,
    JudgePolicy,
    JudgeBlocked,
    TenetCloudJudgeClient,
    judged,
)

judge = TenetCloudJudgeClient.from_env()
policy = JudgePolicy(
    on_block=lambda ctx, v: JudgeAction.override_output(
        "I cannot share that data."
    ),
)

@judged(judge, policy=policy)
def get_patient_chart(patient_id: str) -> str:
    return _fetch_chart(patient_id)

# When the judge blocks, the override_output replaces the return value.
chart = get_patient_chart("MRN12345")
```

## Cold-start avoidance

The first `evaluate()` call from a fresh `TenetCloudJudgeClient` pays a
TLS handshake to Auth0, the Auth0 token mint, and a TLS handshake to
the cloud judge — typically 600–900 ms vs. ~50–150 ms once warm. Call
`warmup()` (or `warmup_async()`) at process start:

```python
from tenet_client import TenetCloudJudgeClient

judge = TenetCloudJudgeClient.from_env()
judge.warmup()
```

`warmup()` is idempotent and doubles as a credential smoke test.

## Local server — `TenetMiddleware`

If you're running the Tenet desktop app or an on-prem server (default
`http://127.0.0.1:19990`) instead of the cloud judge:

```python
from langchain.agents import create_agent
from tenet_langchain import TenetMiddleware

agent = create_agent(
    model="claude-sonnet-4-5-20250514",
    tools=[],
    middleware=[TenetMiddleware(tenet_ids=["hipaa-safe-harbor"])],
)
```

Right surface for self-hosted deployments where data must not leave
your network.

## Migration from `wrap()`

`wrap()` still works but emits a `DeprecationWarning`. The translation
is mechanical:

```python
# Before
from tenet_langchain import wrap

agent = wrap(
    model=model,
    tools=tools,
    judge=judge,
    fail_open=False,
)

# After
from langchain.agents import create_agent
from tenet_client import JudgePolicy
from tenet_langchain import TenetJudgeMiddleware

agent = create_agent(
    model=model,
    tools=tools,
    middleware=[TenetJudgeMiddleware(judge, policy=JudgePolicy())],
)
```

The default `JudgePolicy()` is fail-closed — same as the old
`fail_open=False`. To restore the old `fail_open=True` behavior, set
`on_unavailable=lambda ctx, err: JudgeAction.allow()`.

## Examples

- [`examples/healthcare_agent/`](examples/healthcare_agent/) — end-to-end
  LangChain healthcare agent gated by the `healthcare-1` cloud judge.
- [`examples/human_review_interrupt.py`](examples/human_review_interrupt.py) —
  `with_human_review` pausing the agent on a `review` verdict and resuming
  with `APPROVE` and the prompt's `review_id`.

## License

Apache-2.0.
