> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tenetlabs.com/llms.txt
> Use this file to discover all available pages before exploring further.

# tenet-langchain

> LangChain integration reference — TenetJudgeMiddleware, read intent, HITL display helpers, and adjacent classes.

**`tenet-langchain`**: LangChain adapters over `tenet-client`. Requires `langchain>=1.2.13` (the `AgentMiddleware` API), Python 3.11–3.13. Version 0.7.0 needs `tenet-client>=0.7.7`.

```bash theme={null}
pip install tenet-langchain
```

## TenetJudgeMiddleware

The primary integration — policy-first middleware for `create_agent`. Usage, options, and recipes live in the [LangChain guide](https://docs.tenetlabs.com/guides/langchain.md); the full constructor:

```python theme={null}
TenetJudgeMiddleware(
    client: TenetCloudJudgeClient,
    *,
    policy: JudgePolicy | None = None,            # defaults: fail-closed
    check_pre: bool = True,
    check_post: bool = True,
    check_user_messages: bool = False,            # gate agent_input
    judge_tools_pre: Iterable[str] | None = None, # None = all tools
    judge_tools_post: Iterable[str] | None = None,
    cache_verdicts: bool = False,
    turn_approval: bool = False,
    stream: bool = False,                         # verdict-first SSE
    send_history: bool = False,                   # prior user turns
    session_id: str | None = None,                # auto: checkpointer thread_id
    resolution_detection: bool = True,
    resolution_detection_excluded_tools: Iterable[str] | None = None,
    retry_nudge_max_consecutive: int = 3,
    read_tools: Iterable[str] | None = None,        # declare read tools
    intent_resolver: Callable[[str], str | None] | None = None,
)
```

Implements `before_agent` / `abefore_agent` (per-invocation trace setup) and `wrap_tool_call` / `awrap_tool_call` (the tool-boundary gate). Sync and async agent runs both work.

## Read intent

The service reads a top-level [`intent`](https://docs.tenetlabs.com/concepts/read-intent) field on the `/decide` body as its **highest-precedence** intent signal and records the classification on the decision trace. The current judge doesn't change verdicts on it, so declaring reads doesn't fast-pass anything today — it puts your read/write taxonomy on every trace, scoped by the `tool_post`-only rule below. Declaring which tools are reads lets the middleware assert `intent="read"` on exactly those calls.

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

```python theme={null}
from tenet_langchain import TenetJudgeMiddleware

mw = TenetJudgeMiddleware(
    judge,
    policy=policy,
    judge_tools_pre={"schedule_interview", "send_phone_screen"},   # mutating → pre
    judge_tools_post={"list_candidates", "get_application"},        # reads → post
    read_tools={"list_candidates", "get_application"},              # ← stamps intent="read"
    # or, for a computed taxonomy (wins over read_tools):
    # intent_resolver=lambda tool_name: "read" if tool_name.startswith("get_") 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 the field. An `intent_resolver` must return one of those strings or `None`; an out-of-vocab value raises `ValueError`.

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

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

The middleware applies the phase gate **before** it consults `read_tools` / `intent_resolver`. It stamps `intent="read"` only at `tool_post`; the field is never sent at `agent_input` or `tool_pre`, whatever `read_tools` contains.

Full field semantics and the wire header: [Read-intent contract](https://docs.tenetlabs.com/concepts/read-intent.md).

Every call the middleware makes is judged under the **client's** [`surface`](https://docs.tenetlabs.com/concepts/surfaces) — there is no per-tool surface option. For agents whose tools span recruiting-action kinds, scope one middleware per action family via `judge_tools_pre` / `judge_tools_post` (one client per surface), or gate mixed tools with `tenet_client`'s `evaluate(surface=...)`.

An `include_with_caveats` verdict rides through as a **non-blocking allow**: the judge's advisory note is folded onto `ctx.metadata` and annotated onto the proceeding tool result's `response_metadata` (status preserved, never an error). It never reaches `on_review` and never interrupts. On streaming runs (`stream=True`), severity-routed dispatch waits for the final severity, not the provisional verdict event — see [Verdict-first streaming](https://docs.tenetlabs.com/guides/streaming.md#provisional-verdicts).

## Tell the judge what the tool does

The judge sees a tool call as its arguments and little else, so it can misread a call whose meaning sits in the user's words or in the tool's purpose. The request-shaping options add those facts without subclassing the client.

```python theme={null}
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.

> [!WARNING]
>
> 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

You can't tune a policy you can't see. `on_decision` hands you one record per judged call.

`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 theme={null}
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

"What would the judge do to my traffic?" should not need enforcement to answer. Shadow mode judges every phase without acting on it.

"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 theme={null}
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 theme={null}
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

A tool added later and listed nowhere would run with no check and no warning. `strict_tools` turns that into a deploy-time error.

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 theme={null}
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 theme={null}
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 theme={null}
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})
```

## Human review

A `review` or `block` verdict can pause the agent for a person and resume from the answer, which needs a checkpointer and a stable `thread_id`.

```python theme={null}
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. `review_id` binds an answer to the kind of finding (phase, tool name, labels), not to the message
text or the tool arguments. Keep tools idempotent: LangGraph re-runs the node that paused, from the top, on resume.

`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.

## 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 theme={null}
mw = TenetJudgeMiddleware(
    judge,
    policy=policy,
    check_user_messages=True,
    turn_approval=True,
    send_history=True,
    persist_review_state=True,
)
```

Four private graph-state channels hold the state; they never reach the caller's output. Messages without an id are judged every time. Two middleware instances that should not share state need different `review_state_prefix` and `name=` values.

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.

### 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 theme={null}
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())
```

## Per-thread state

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.

## Timeouts

A timeout reaches `on_timeout`; if you leave it unset, a timeout falls back to `on_unavailable`, so setting only `on_unavailable` covers both.

## ToolGuardMiddleware

Constructor-injected tool **allowlist** — structural defence-in-depth that stops the model from calling tools the application never registered, at the agent layer, instead of scanning model output for leaked tool names after the fact.

```python theme={null}
from langchain.agents import create_agent
from tenet_langchain import ToolGuardMiddleware

TOOLS = [search_tool, send_email_tool, delete_db_tool]
TOOL_NAMES = frozenset(t.name for t in TOOLS)   # one source of truth

agent = create_agent(
    model="...",
    tools=TOOLS,
    middleware=[ToolGuardMiddleware(allowed=TOOL_NAMES)],
    context_schema=RequestContext,   # optional — a `scopes: frozenset[str]` field
)
```

Two layers enforce independently:

* **Layer 1 — `wrap_model_call`:** per-request scoping. Narrows the tools the model sees to the subset permitted by `runtime.context.scopes`. No-ops cleanly when context or `scopes` is absent, so Layer 2 stays the unconditional enforcement point.
* **Layer 2 — `wrap_tool_call`:** hard enforcement. Any call whose name is not in the constructor `allowed` set short-circuits with `ToolMessage(status="error")` — the handler is never invoked, regardless of how the call surfaced. Comparison is by tool name (string), not object identity.

The allowlist lives on the instance (constructor), never written to messages or `AgentState`, so it is never serialized into the prompt or captured in checkpoints/traces. Both sync and async (`awrap_tool_call`) are implemented. It does **not** validate tool *arguments* (an allowed tool with poisoned args passes) — compose with argument validation or `HumanInTheLoopMiddleware` on high-impact tools.

## Adjacent classes

| Class | Status | Use when |
| - | - | - |
| `TenetJudgeMiddleware` | **Current** | `create_agent` integrations — always start here |
| `TenetMiddleware` | Separate product | Local Tenet server for PII detect/redact — not the cloud judge |
| `TenetCallbackHandler` / `AsyncTenetCallbackHandler` | Adjacent | Non-middleware LangChain chains; hooks `on_tool_start` / `on_tool_end` against the local server |
| `TenetGuard` | Adjacent | Standalone PII detection on arbitrary text (`detect_pii`) |

## HITL display helpers

For harnesses that surface `review` verdicts to humans:

* `RiskLabelDisplay` + `DEFAULT_EEO_TOPIC_MAPPING` — render risk codes (`EEO-AGE-PROXY-01` → "age-discrimination") as reviewer-friendly topics; operator-only codes map to `None` and drop out.
* `ReviewEvent` + `format_review_event` — a transport-ready review record with `to_sse()` / `to_dict()` renderers. The middleware never calls these; your app does, from its HITL handler.

Full usage — callbacks, SSE rendering, resume semantics — in the [HITL guide](https://docs.tenetlabs.com/guides/hitl.md).

These pair with an `interrupt()`-based `on_review` callback ([Human in the loop](https://docs.tenetlabs.com/guides/policies.md#human-in-the-loop)) and `turn_approval=True`: the human approves once, and approved risk labels don't re-trigger for the rest of the turn.

## Re-exports

`JudgePolicy`, `JudgeVerdict`, `JudgeContext`, `JudgeAction`, and `judged` re-export from `tenet_client` — import from either package.

## Links

* [LangChain guide — setup and recipes](https://docs.tenetlabs.com/guides/langchain.md)
* [Policies](https://docs.tenetlabs.com/guides/policies.md)
* [tenet-client reference](https://docs.tenetlabs.com/sdk/tenet-client.md)
* [`tenet-langchain` on PyPI](https://pypi.org/project/tenet-langchain/)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.