tallwright-langgraph 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,34 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """tallwright_langgraph — Cloud Proof for a LangChain/LangGraph v1 agent, as one middleware.
3
+
4
+ from tallwright_langgraph import TallwrightMiddleware
5
+
6
+ agent = create_agent(model, tools, middleware=[TallwrightMiddleware(client)]) # last in the list
7
+
8
+ - :class:`TallwrightMiddleware` hands a ``tallwright_cloud.Tallwright`` client the agent's context and
9
+ actions (``middleware.py``);
10
+ - :mod:`tallwright_langgraph.projection` is what those events become as content, the one decision an
11
+ adapter makes; a self-hosted recorder commits to the same projection.
12
+
13
+ The middleware is loaded when it is first named, so a reader of the projection alone does not load the
14
+ Cloud client.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import TYPE_CHECKING, Any
20
+
21
+ if TYPE_CHECKING: # pragma: no cover - names for the type checker only
22
+ from .middleware import TallwrightMiddleware
23
+
24
+ __version__ = "0.1.0"
25
+
26
+ __all__ = ["TallwrightMiddleware"]
27
+
28
+
29
+ def __getattr__(name: str) -> Any:
30
+ if name == "TallwrightMiddleware":
31
+ from .middleware import TallwrightMiddleware
32
+
33
+ return TallwrightMiddleware
34
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,170 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """Cloud Proof for a LangChain/LangGraph v1 agent: one middleware, handed the client you already built.
3
+
4
+ from tallwright_cloud import Tallwright
5
+ from tallwright_langgraph import TallwrightMiddleware
6
+
7
+ client = Tallwright(ingest_url, archive_key, "./tallwright-evidence")
8
+ agent = create_agent(model, tools, middleware=[TallwrightMiddleware(client)])
9
+
10
+ It decides when to hand the client an event and what content to hand it, and nothing else
11
+ (https://docs.tallwright.com/adapters). The commitment, the evidence, sending, sending again and the
12
+ receipt are the client's; the projection is :mod:`tallwright_langgraph.projection`.
13
+
14
+ - ``wrap_model_call``: what the model received, as context (``CONTEXT_RECEIVED``).
15
+ - ``wrap_tool_call``: the tool and its arguments BEFORE it runs, as an action (``ACTION_TRIGGERED``,
16
+ ``action_type`` = the tool's name); then what it returned, or the type of what it raised, as context.
17
+ - The agent's reasoning or intent is never recorded: LangChain has no hook for intent, and a
18
+ provider's reasoning blocks are left out of the projection.
19
+
20
+ **Best effort by default, fail-closed when asked.** By default every event is handed to
21
+ ``client.submit``, which returns once the evidence is safe and sends in the background, so the agent
22
+ never waits on the network; a failure is logged by its type, never with content, and the agent keeps
23
+ serving. With ``fail_closed=True`` an action is handed to ``client.capture`` before the tool runs, and a
24
+ capture the door did not confirm raises before the tool runs; any other failure raises too.
25
+
26
+ **Install it LAST in** ``middleware=[...]``. LangChain composes middleware outermost first, and this one
27
+ records the tool call before calling the handler. A middleware listed after it runs inside it and may
28
+ rewrite the call afterwards (context editing, PII, summarization, tool selection, human-in-the-loop), and
29
+ the record would describe the call as it was before that rewrite. No middleware can see what an inner
30
+ one does, so this is a requirement on the deployment that the library cannot enforce.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import logging
36
+ from collections.abc import Awaitable, Callable
37
+ from typing import Any
38
+
39
+ from langchain.agents.middleware import AgentMiddleware, ModelRequest, ModelResponse, ToolCallRequest
40
+ from tallwright_cloud import Flushed, Tallwright
41
+ from tallwright_core.redact import CREDENTIAL_KEYS
42
+
43
+ from .projection import action_payload, error_payload, model_payload, result_payload
44
+
45
+ LOG = logging.getLogger("tallwright_langgraph")
46
+
47
+ #: Gives the client of the Environment a run records into, from that run's LangGraph ``runtime``: its
48
+ #: ``context`` is what your code passed as ``invoke(..., context=...)``.
49
+ ClientFor = Callable[[Any], Tallwright]
50
+
51
+
52
+ class TallwrightMiddleware(AgentMiddleware): # type: ignore[misc] # AgentMiddleware is untyped
53
+ """Records a LangChain/LangGraph v1 agent's context and actions into Cloud Proof.
54
+
55
+ Hand it ``client``, a :class:`~tallwright_cloud.Tallwright` built by you, or ``client_for``, which
56
+ gives one per run when one agent process serves many end customers (``Environments.client``). It
57
+ never builds a client and never reads a key: the key and where evidence lives are yours.
58
+
59
+ ``actor_authority`` is the role or rule the agent's actions run under (``role:payments-agent``), never
60
+ a person; it is set on actions only. ``redact_keys`` names the keys whose values are withheld from
61
+ tool arguments, messages and results, with the path of each recorded.
62
+ """
63
+
64
+ def __init__(
65
+ self,
66
+ client: Tallwright | None = None,
67
+ *,
68
+ client_for: ClientFor | None = None,
69
+ fail_closed: bool = False,
70
+ actor_authority: str | None = None,
71
+ redact_keys: frozenset[str] = CREDENTIAL_KEYS,
72
+ ) -> None:
73
+ super().__init__()
74
+ if (client is None) == (client_for is None):
75
+ raise TypeError("hand the middleware a client or a client_for, and not both")
76
+ self._client = client
77
+ self._client_for = client_for
78
+ self._fail_closed = fail_closed
79
+ self._authority = actor_authority
80
+ self._keys = redact_keys
81
+ #: The clients this middleware has handed events to, so ``pending`` and ``flush`` reach each.
82
+ self._used: dict[int, Tallwright] = {} if client is None else {id(client): client}
83
+
84
+ # -- what the adapter adds to the client's surface ---------------------------------------
85
+
86
+ def pending(self) -> list[str]:
87
+ """Records handed to a client here and never confirmed or refused (``client.pending()``)."""
88
+ return [name for client in self._used.values() for name in client.pending()]
89
+
90
+ def flush(self, timeout: float | None = 30.0) -> list[Flushed]:
91
+ """Wait for what was submitted, client by client (``client.flush()``), at the end of a run."""
92
+ return [client.flush(timeout) for client in self._used.values()]
93
+
94
+ # -- one event ------------------------------------------------------------------------------
95
+
96
+ def _of(self, runtime: Any) -> Tallwright:
97
+ if self._client is not None:
98
+ return self._client
99
+ assert self._client_for is not None
100
+ client = self._client_for(runtime)
101
+ self._used.setdefault(id(client), client)
102
+ return client
103
+
104
+ def _failed(self, what: str, failed: Exception, *, stops: bool) -> None:
105
+ """A capture that failed: raised when it must stop the agent, logged by its type otherwise."""
106
+ if stops:
107
+ raise failed
108
+ LOG.warning("%s was not recorded: %s; the agent goes on (best effort)", what, type(failed).__name__)
109
+
110
+ def _record(self, runtime: Any, what: str, build: Callable[[], tuple[Any, str | None]]) -> None:
111
+ try:
112
+ content, action_type = build()
113
+ client = self._of(runtime)
114
+ if action_type is not None and self._fail_closed:
115
+ client.capture(content, action_type=action_type, actor_authority=self._authority)
116
+ elif action_type is not None:
117
+ client.submit(content, action_type=action_type, actor_authority=self._authority)
118
+ else:
119
+ client.submit(content)
120
+ except Exception as failed: # noqa: BLE001 - best effort must not stop the agent, and says so
121
+ self._failed(what, failed, stops=self._fail_closed)
122
+
123
+ async def _arecord(self, runtime: Any, what: str, build: Callable[[], tuple[Any, str | None]]) -> None:
124
+ try:
125
+ content, action_type = build()
126
+ client = self._of(runtime)
127
+ if action_type is not None and self._fail_closed:
128
+ await client.acapture(content, action_type=action_type, actor_authority=self._authority)
129
+ elif action_type is not None:
130
+ await client.asubmit(content, action_type=action_type, actor_authority=self._authority)
131
+ else:
132
+ await client.asubmit(content)
133
+ except Exception as failed: # noqa: BLE001 - best effort must not stop the agent, and says so
134
+ self._failed(what, failed, stops=self._fail_closed)
135
+
136
+ # -- the hooks ----------------------------------------------------------------------------
137
+
138
+ def wrap_model_call(self, request: ModelRequest, handler: Callable[[ModelRequest], ModelResponse]) -> ModelResponse:
139
+ self._record(request.runtime, "the model's context", lambda: (model_payload(request, self._keys), None))
140
+ return handler(request)
141
+
142
+ def wrap_tool_call(self, request: ToolCallRequest, handler: Callable[[ToolCallRequest], Any]) -> Any:
143
+ self._record(request.runtime, "a tool call", lambda: action_payload(request, self._keys))
144
+ try:
145
+ result = handler(request)
146
+ except Exception as exc:
147
+ kind = type(exc).__name__
148
+ self._record(request.runtime, "a tool's error", lambda: (error_payload(request, kind), None))
149
+ raise
150
+ self._record(request.runtime, "a tool's result", lambda: (result_payload(request, result, self._keys), None))
151
+ return result
152
+
153
+ async def awrap_model_call(
154
+ self, request: ModelRequest, handler: Callable[[ModelRequest], Awaitable[ModelResponse]]
155
+ ) -> ModelResponse:
156
+ await self._arecord(request.runtime, "the model's context", lambda: (model_payload(request, self._keys), None))
157
+ return await handler(request)
158
+
159
+ async def awrap_tool_call(self, request: ToolCallRequest, handler: Callable[[ToolCallRequest], Awaitable[Any]]) -> Any:
160
+ await self._arecord(request.runtime, "a tool call", lambda: action_payload(request, self._keys))
161
+ try:
162
+ result = await handler(request)
163
+ except Exception as exc:
164
+ kind = type(exc).__name__
165
+ await self._arecord(request.runtime, "a tool's error", lambda: (error_payload(request, kind), None))
166
+ raise
167
+ await self._arecord(
168
+ request.runtime, "a tool's result", lambda: (result_payload(request, result, self._keys), None)
169
+ )
170
+ return result
@@ -0,0 +1,247 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ """What a LangChain/LangGraph v1 agent's events become as content: the projection, and only that.
3
+
4
+ This is the one real decision an adapter makes (https://docs.tallwright.com/adapters, section 4):
5
+ which fields of what the framework hands it are committed to, and which are left out. Everything
6
+ after that, the commitment, the salt, the evidence and the sending, belongs to the recorder the
7
+ middleware hands the content to. The functions here build plain JSON values and nothing else, so the
8
+ Cloud Proof middleware and a self-hosted one commit to the same projection of the same event.
9
+
10
+ **Two contracts, two functions.** A framework MESSAGE is an object whose schema this module names,
11
+ and from which a provider's reasoning must be excluded; a tool RESULT is arbitrary business data,
12
+ and is kept whole. One shared "dump, then subtract" helper for both applied every rule written for
13
+ messages, by key name and at every depth, to data whose shape nobody here can know: it deleted
14
+ evidence, and two different approvals encoded to the same value. So the message is an ALLOWLIST
15
+ projection, closed against any field a provider adds later, and the result encoder filters nothing
16
+ but the named credential keys every adapter withholds (``tallwright_core.redact``).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from collections.abc import Mapping, Sequence
22
+ from typing import Any
23
+
24
+ from langchain.agents.middleware import ModelRequest, ToolCallRequest
25
+ from langchain_core.messages import BaseMessage
26
+ from tallwright_core.redact import CREDENTIAL_KEYS, scrub
27
+
28
+ #: The fields of a message that are committed to. Anything else (``additional_kwargs``,
29
+ #: ``response_metadata``, ``usage_metadata`` and whatever a provider adds tomorrow) is absent by
30
+ #: construction, and named in ``omitted_message_fields``.
31
+ MESSAGE_FIELDS = (
32
+ "type",
33
+ "id",
34
+ "name",
35
+ "content",
36
+ "tool_calls",
37
+ "invalid_tool_calls",
38
+ "tool_call_id",
39
+ "status",
40
+ "artifact",
41
+ )
42
+
43
+ #: The content blocks that are committed to. Anything else, a provider's thinking block or a block
44
+ #: type that does not exist yet, is replaced by a marker: the unknown fails closed, and visibly.
45
+ CONTENT_BLOCK_TYPES = frozenset(
46
+ {
47
+ "text",
48
+ "tool_use",
49
+ "tool_result",
50
+ "image",
51
+ "document",
52
+ "server_tool_use",
53
+ "web_search_tool_result",
54
+ "citation",
55
+ }
56
+ )
57
+
58
+ #: What stands where a block of another type was.
59
+ OMITTED = "[omitted: not a recorded content-block type]"
60
+
61
+
62
+ def model_id(model: Any) -> str:
63
+ """The model's name, from a string or the attribute a chat model keeps it in."""
64
+ if isinstance(model, str):
65
+ return model
66
+ for attr in ("model", "model_name"):
67
+ value = getattr(model, attr, None)
68
+ if isinstance(value, str):
69
+ return value
70
+ return type(model).__name__
71
+
72
+
73
+ def project_block(block: Any, keys: frozenset[str] = CREDENTIAL_KEYS, *, path: str = "") -> tuple[Any, list[str]]:
74
+ """One content block, with named credential values replaced wherever they sit.
75
+
76
+ A ``tool_use`` block carries the same arguments the tool call does, so withholding a credential
77
+ from the action alone would leave it in the context by a second door. Returns what it took as well
78
+ as what is left: a redaction nobody can see cannot be told from a block that never carried one.
79
+ """
80
+ if isinstance(block, Mapping):
81
+ kind = block.get("type")
82
+ if kind not in CONTENT_BLOCK_TYPES:
83
+ return {"type": kind, "omitted": OMITTED}, []
84
+ # With the path: `token` alone does not tell a reader which of five blocks was cut.
85
+ return scrub(dict(block), keys, path=path)
86
+ return block, []
87
+
88
+
89
+ def names_dropped(full: Mapping[str, Any]) -> list[str]:
90
+ """The NAMES the allowlist dropped from a message, never their values.
91
+
92
+ The complement of the allowlist, so it deletes nothing and names a carrier a provider invents
93
+ tomorrow. Without it, a message carrying a provider's reasoning under ``additional_kwargs`` or
94
+ ``response_metadata`` projected to the same bytes as one carrying none: the omission was not only
95
+ unmarked, it was undetectable. One level deep, because those carriers sit under a container whose
96
+ name alone says nothing; empty values are skipped, so it reports what was dropped.
97
+ """
98
+ names: list[str] = []
99
+ for key in sorted(set(full) - set(MESSAGE_FIELDS)):
100
+ value = full[key]
101
+ if value is None or value is False or value == {} or value == [] or value == "":
102
+ continue
103
+ if isinstance(value, Mapping):
104
+ names += [f"{key}.{inner}" for inner in sorted(value)]
105
+ else:
106
+ names.append(key)
107
+ return names
108
+
109
+
110
+ def project_message(message: Any, keys: frozenset[str] = CREDENTIAL_KEYS) -> tuple[Any, list[str], list[str]]:
111
+ """A framework message, projected onto the fields named above; the paths withheld; the names dropped.
112
+
113
+ ``tool_calls`` and ``invalid_tool_calls`` are named fields, and they carry the arguments a tool was
114
+ called with, for most "call this API for me" tools somebody else's credential. So the same keys are
115
+ replaced here as in the action: the arguments appear twice, and withholding one of them is not
116
+ withholding.
117
+ """
118
+ dump = getattr(message, "model_dump", None)
119
+ if not callable(dump):
120
+ return str(message), [], []
121
+ full = dump(mode="json")
122
+ out = {k: full[k] for k in MESSAGE_FIELDS if k in full}
123
+ omitted = names_dropped(full)
124
+ withheld: list[str] = []
125
+ content = out.get("content")
126
+ if isinstance(content, list):
127
+ projected = [project_block(b, keys, path=f"content[{i}]") for i, b in enumerate(content)]
128
+ out["content"] = [b for b, _ in projected]
129
+ withheld += [p for _, paths in projected for p in paths]
130
+ for field in ("tool_calls", "invalid_tool_calls"):
131
+ if field in out:
132
+ out[field], taken = scrub(out[field], keys)
133
+ withheld += taken
134
+ return out, withheld, omitted
135
+
136
+
137
+ def encode_result(value: Any, keys: frozenset[str] = CREDENTIAL_KEYS, *, path: str = "") -> tuple[Any, list[str]]:
138
+ """A tool RESULT as a JSON value, kept whole but for the named credential keys; the paths withheld.
139
+
140
+ A result's ``signature``, ``reasoning`` or ``thought`` are evidence, and stay. The one special case
141
+ is a framework message a tool returned, which is projected like any other message.
142
+ """
143
+ if isinstance(value, BaseMessage):
144
+ projected, withheld, _omitted = project_message(value, keys)
145
+ return projected, withheld
146
+ if isinstance(value, Mapping):
147
+ out: dict[Any, Any] = {}
148
+ taken: list[str] = []
149
+ for k, v in value.items():
150
+ here = f"{path}.{k}" if path else str(k)
151
+ out[k], paths = encode_result(v, keys, path=here)
152
+ taken += paths
153
+ return out, taken
154
+ if isinstance(value, (str, int, float, bool)) or value is None:
155
+ return value, []
156
+ if isinstance(value, (list, tuple)):
157
+ items = [encode_result(v, keys, path=f"{path}[{i}]") for i, v in enumerate(value)]
158
+ return [v for v, _ in items], [p for _, paths in items for p in paths]
159
+ dump = getattr(value, "model_dump", None)
160
+ if callable(dump):
161
+ return encode_result(dump(mode="json"), keys, path=path)
162
+ return str(value), []
163
+
164
+
165
+ def dump_messages(messages: Sequence[Any], keys: frozenset[str]) -> tuple[list[Any], list[str], list[str]]:
166
+ """Every message projected; every path withheld; every name dropped, under ``messages[i]``."""
167
+ projected = [project_message(m, keys) for m in messages]
168
+ return (
169
+ [m for m, _, _ in projected],
170
+ [p for _, paths, _ in projected for p in paths],
171
+ [f"messages[{i}].{name}" for i, (_, _, names) in enumerate(projected) for name in names],
172
+ )
173
+
174
+
175
+ def dump_tools(tools: Sequence[Any]) -> list[Any]:
176
+ """The tools the model was offered: name and description, or the mapping it was given as."""
177
+ out: list[Any] = []
178
+ for tool in tools:
179
+ name = getattr(tool, "name", None)
180
+ if name is not None:
181
+ out.append({"name": name, "description": getattr(tool, "description", "")})
182
+ elif isinstance(tool, Mapping):
183
+ out.append(dict(tool))
184
+ else:
185
+ out.append(str(tool))
186
+ return out
187
+
188
+
189
+ def model_payload(request: ModelRequest, keys: frozenset[str] = CREDENTIAL_KEYS) -> dict[str, Any]:
190
+ """What went to the model, and which named credentials were taken out of it.
191
+
192
+ ``withheld_argument_keys`` and ``omitted_message_fields`` are present even when empty: "nothing was
193
+ found to withhold" and "nothing was looked for" are opposite statements about whether a credential
194
+ or a provider's reasoning could be sitting in this prompt, and only these fields carry the
195
+ difference.
196
+ """
197
+ system, taken, dropped = (
198
+ project_message(request.system_message, keys) if request.system_message is not None else (None, [], [])
199
+ )
200
+ messages, more, also = dump_messages(request.messages, keys)
201
+ return {
202
+ "model": model_id(request.model),
203
+ "system_message": system,
204
+ "messages": messages,
205
+ "tools": dump_tools(request.tools),
206
+ "withheld_argument_keys": sorted(set(taken + more)),
207
+ "omitted_message_fields": sorted(set([f"system_message.{n}" for n in dropped] + also)),
208
+ }
209
+
210
+
211
+ def action_payload(request: ToolCallRequest, keys: frozenset[str] = CREDENTIAL_KEYS) -> tuple[dict[str, Any], str]:
212
+ """The call, with named credential arguments replaced and the paths where they were; the tool's name."""
213
+ call = request.tool_call
214
+ name = getattr(request.tool, "name", None) or call.get("name")
215
+ args, withheld = scrub(call.get("args"), keys)
216
+ return (
217
+ {
218
+ "tool": name,
219
+ "args": args,
220
+ "tool_call_id": call.get("id"),
221
+ "withheld_argument_keys": sorted(set(withheld)),
222
+ },
223
+ str(name),
224
+ )
225
+
226
+
227
+ def result_payload(request: ToolCallRequest, result: Any, keys: frozenset[str] = CREDENTIAL_KEYS) -> dict[str, Any]:
228
+ """The tool's outcome, kept whole, and the paths the credential keys took out of it.
229
+
230
+ ``withheld_result_keys`` is present even when empty. A business field whose NAME collides with a
231
+ credential key is replaced, and silently that would read as the tool's own answer.
232
+ """
233
+ encoded, withheld = encode_result(result, keys)
234
+ return {
235
+ "tool_call_id": request.tool_call.get("id"),
236
+ "result": encoded,
237
+ "withheld_result_keys": sorted(set(withheld)),
238
+ }
239
+
240
+
241
+ def error_payload(request: ToolCallRequest, error: str) -> dict[str, Any]:
242
+ """The outcome when the tool RAISED: the exception's type only, never its message.
243
+
244
+ A message can carry provider or third-party detail nothing here has projected; the fact the record
245
+ needs is that the action did not complete normally.
246
+ """
247
+ return {"tool_call_id": request.tool_call.get("id"), "error": error}
File without changes
@@ -0,0 +1,119 @@
1
+ Metadata-Version: 2.5
2
+ Name: tallwright-langgraph
3
+ Version: 0.1.0
4
+ Summary: Tallwright - Cloud Proof for LangChain/LangGraph v1 agents, as one middleware
5
+ Project-URL: Homepage, https://www.tallwright.com
6
+ Project-URL: Documentation, https://docs.tallwright.com/adapters
7
+ Project-URL: Source, https://github.com/tallwright-hq/tallwright-python
8
+ Project-URL: Issues, https://github.com/tallwright-hq/tallwright-python/issues
9
+ Author: Tallwright
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ License-File: NOTICE
13
+ Keywords: ai-agents,audit,evidence,langchain,langgraph,middleware,tamper-evident
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Intended Audience :: Legal Industry
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Typing :: Typed
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: langchain<2,>=1.3
23
+ Requires-Dist: langgraph<2,>=1.2
24
+ Requires-Dist: tallwright-cloud<2,>=1.0.0rc1
25
+ Requires-Dist: tallwright-core==0.1.*,>=0.1.1
26
+ Description-Content-Type: text/markdown
27
+
28
+ # tallwright-langgraph
29
+
30
+ Cloud Proof for a LangChain/LangGraph v1 agent, as one middleware. The agent's context and the actions
31
+ it triggers become records that somebody else can check offline, while the content stays on your
32
+ machine.
33
+
34
+ It is a thin adapter on the Python SDK, [`tallwright-cloud`](https://docs.tallwright.com/python): it
35
+ decides when to hand the client an event and what content to hand it, and nothing else. The commitment,
36
+ the evidence, sending, sending again and the receipt are the SDK's
37
+ ([the adapter contract](https://docs.tallwright.com/adapters)).
38
+
39
+ ## Use it
40
+
41
+ ```python
42
+ import os
43
+
44
+ from langchain.agents import create_agent
45
+ from tallwright_cloud import Tallwright
46
+ from tallwright_langgraph import TallwrightMiddleware
47
+
48
+ client = Tallwright(os.environ["TALLWRIGHT_INGEST"], os.environ["TALLWRIGHT_KEY"], "./tallwright-evidence")
49
+ agent = create_agent(model, tools, middleware=[TallwrightMiddleware(client)]) # last in the list
50
+
51
+ agent.invoke({"messages": [{"role": "user", "content": "Refund ticket 8812"}]})
52
+ client.flush() # at the end of a run: wait for what was sent in the background
53
+ ```
54
+
55
+ The ingest address and the key are the ones the backoffice shows for an Environment, as in the
56
+ [quickstart](https://docs.tallwright.com/quickstart). The middleware never reads a key and never chooses
57
+ where evidence lives: you build the client, and you hand it over.
58
+
59
+ ## What becomes a record
60
+
61
+ - **Each model call**: what the model received (system message, messages, the tools offered, the model's
62
+ name), as context the agent received.
63
+ - **Each tool call, before the tool runs**: the tool's name and its arguments, as an action, with the
64
+ tool's name as its `action_type`.
65
+ - **What the tool returned**, or the type of the exception it raised, as context.
66
+
67
+ Never recorded: the agent's reasoning or intent. LangChain has no hook for intent, and a provider's
68
+ reasoning blocks are left out of what is committed. Messages are projected onto named fields; what was
69
+ left out is named in `omitted_message_fields`, and named credential keys (`api_key`, `token`,
70
+ `authorization`, …) are replaced in arguments, messages and results, with each path in
71
+ `withheld_argument_keys` or `withheld_result_keys`. Pass `redact_keys=` to name more.
72
+
73
+ ## Best effort or fail-closed
74
+
75
+ By default each event is handed to `client.submit`: it returns once the evidence is safe on your machine
76
+ and sends in the background, so the agent never waits on the network. A capture that fails is logged by
77
+ its type, never with content, the agent keeps serving, and the record stays in `pending()` until it is
78
+ sent again.
79
+
80
+ ```python
81
+ TallwrightMiddleware(client, fail_closed=True, actor_authority="role:payments-agent")
82
+ ```
83
+
84
+ With `fail_closed=True`, each tool call is handed to `client.capture` before the tool runs, and a capture
85
+ Tallwright did not confirm raises before the tool runs. A regulated deployment sets it.
86
+ `actor_authority` names the role or rule the agent's actions run under, never a person.
87
+
88
+ ## Many end customers
89
+
90
+ One agent process that serves many end customers records each run into that customer's Environment:
91
+
92
+ ```python
93
+ from tallwright_cloud import Environments
94
+
95
+ environments = Environments(ingest_url, key_for, "./tallwright-evidence")
96
+ middleware = TallwrightMiddleware(client_for=lambda runtime: environments.client(runtime.context["customer"]))
97
+ agent.invoke(inputs, context={"customer": "customer-42"})
98
+ ```
99
+
100
+ `client_for` is called with the run's LangGraph `runtime`; its `context` is what your code passed to
101
+ `invoke`. `middleware.pending()` and `middleware.flush()` reach every client the middleware used.
102
+
103
+ ## What is outside the record
104
+
105
+ - **A middleware listed after this one.** LangChain composes middleware outermost first, and this one
106
+ records the tool call before calling the handler. A middleware listed after it runs inside it and may
107
+ rewrite the call afterwards (context editing, PII, summarization, tool selection, human-in-the-loop),
108
+ and the record then describes the call as it was before. Install it last.
109
+ - **Anything that does not pass through the agent's model and tool hooks**: a model or an API your code
110
+ calls directly, and what a tool does inside itself.
111
+ - **A credential inside free text.** Keys are replaced where they are keys; a secret written into a
112
+ string, such as a tool result the framework turned into text for the model, is not recognised.
113
+ - **Whether what the agent was told was true.** A record commits to what was received, not to whether it
114
+ was right.
115
+
116
+ ## License
117
+
118
+ Copyright 2026 David Jöbstl. Licensed under the Apache License, Version 2.0: the package carries the
119
+ license text and the NOTICE.
@@ -0,0 +1,9 @@
1
+ tallwright_langgraph/__init__.py,sha256=INSeQepmaMF-0_ipfcjV8MfU3iIsYODdQTm6rlAutLg,1223
2
+ tallwright_langgraph/middleware.py,sha256=cai2XmcWY5hHbiPP89vNSCR83WdYSXrpSfN7X82nurg,9060
3
+ tallwright_langgraph/projection.py,sha256=9yXC3HUrsjOHKuVWyEsA4b3W6JXoZoq6aFEh3QDksCQ,10986
4
+ tallwright_langgraph/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ tallwright_langgraph-0.1.0.dist-info/METADATA,sha256=S9dekn337dVJj1cBtJs4pEGNWOGy5Gwv-ZT9Ca5FNFQ,5773
6
+ tallwright_langgraph-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
7
+ tallwright_langgraph-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
8
+ tallwright_langgraph-0.1.0.dist-info/licenses/NOTICE,sha256=T-SmpcHkzKt9r6bSl8E_dh1Ii9WVDOvBeUDESBTAgCw,279
9
+ tallwright_langgraph-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,6 @@
1
+ Tallwright LangGraph adapter
2
+ Copyright 2026 David Jöbstl
3
+
4
+ Licensed under the Apache License, Version 2.0: tallwright-langgraph. The license text is in the
5
+ LICENSE file beside this one. The adapter requires tallwright-cloud and tallwright-core, which are under
6
+ the same license.