kitaru-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,37 @@
1
+ # Copyright (c) ZenML GmbH 2026. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ """LangGraph recording and replay adapter."""
6
+
7
+ from .agent import KitaruGraphRunner
8
+ from .capability import (
9
+ CapabilityOperation,
10
+ CapabilityTarget,
11
+ CapabilityTargetKind,
12
+ LangGraphAdapterError,
13
+ LangGraphCapabilityView,
14
+ LocalSubagentFactorySpec,
15
+ ToolPolicyError,
16
+ ToolPolicyMissError,
17
+ UnsupportedCapabilityError,
18
+ UnsupportedInvocationError,
19
+ UnsupportedWorkerInterruptError,
20
+ )
21
+ from .capture import CapturePolicy
22
+
23
+ __all__ = [
24
+ "CapabilityOperation",
25
+ "CapabilityTarget",
26
+ "CapabilityTargetKind",
27
+ "CapturePolicy",
28
+ "KitaruGraphRunner",
29
+ "LangGraphAdapterError",
30
+ "LangGraphCapabilityView",
31
+ "LocalSubagentFactorySpec",
32
+ "ToolPolicyError",
33
+ "ToolPolicyMissError",
34
+ "UnsupportedCapabilityError",
35
+ "UnsupportedInvocationError",
36
+ "UnsupportedWorkerInterruptError",
37
+ ]
@@ -0,0 +1,526 @@
1
+ # Copyright (c) ZenML GmbH 2026. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ """Transparent public runner for compiled LangGraph runnables."""
6
+
7
+ import asyncio
8
+ import os
9
+ import threading
10
+ import uuid
11
+ from collections.abc import Callable, Coroutine, Mapping, Sequence
12
+ from concurrent.futures import TimeoutError as FutureTimeoutError
13
+ from contextlib import suppress
14
+ from typing import Any, Generic, TypeVar, cast
15
+
16
+ from langchain_core.runnables import Runnable
17
+ from langchain_core.runnables.config import RunnableConfig, merge_configs
18
+ from langgraph.types import Command
19
+
20
+ from .capability import (
21
+ CapabilityOperation,
22
+ LangGraphCapabilityView,
23
+ LocalSubagentFactorySpec,
24
+ ToolPolicyError,
25
+ UnsupportedCapabilityError,
26
+ UnsupportedInvocationError,
27
+ UnsupportedWorkerInterruptError,
28
+ _make_capability_manifest,
29
+ _require_operation,
30
+ _validate_manifest,
31
+ )
32
+ from .capture import CapturePolicy
33
+ from .recording import _ACTIVE_INVOCATION, InvocationRecorder, _has_interrupt
34
+
35
+ InputT = TypeVar("InputT")
36
+ OutputT = TypeVar("OutputT")
37
+ ResultT = TypeVar("ResultT")
38
+
39
+ _FINALIZATION_TIMEOUT_SECONDS = 5.0
40
+ _FINALIZATION_CLEANUP_TIMEOUT_SECONDS = 0.5
41
+
42
+
43
+ def _import_supported_factories() -> tuple[
44
+ Callable[..., Runnable[Any, Any]],
45
+ Callable[..., Runnable[Any, Any]] | None,
46
+ ]:
47
+ """Return create_agent and, when deepagents is installed, create_deep_agent."""
48
+ from langchain.agents import create_agent
49
+
50
+ try:
51
+ from deepagents import create_deep_agent
52
+ except ImportError:
53
+ return create_agent, None
54
+ return create_agent, create_deep_agent
55
+
56
+
57
+ class _LoopThreadBridge:
58
+ """Run one invocation's async Kitaru client on a dedicated loop thread."""
59
+
60
+ def __init__(self) -> None:
61
+ self._loop = asyncio.new_event_loop()
62
+ self._started = threading.Event()
63
+ self._thread = threading.Thread(
64
+ target=self._run,
65
+ name="kitaru-langgraph-recording",
66
+ daemon=True,
67
+ )
68
+ self._thread.start()
69
+ self._started.wait()
70
+
71
+ def _run(self) -> None:
72
+ asyncio.set_event_loop(self._loop)
73
+ self._started.set()
74
+ self._loop.run_forever()
75
+ self._loop.close()
76
+
77
+ def run(
78
+ self,
79
+ coroutine: Coroutine[Any, Any, ResultT],
80
+ *,
81
+ timeout: float | None = None,
82
+ ) -> ResultT:
83
+ """Submit one coroutine and wait for its result."""
84
+ future = asyncio.run_coroutine_threadsafe(coroutine, self._loop)
85
+ try:
86
+ return future.result(timeout=timeout)
87
+ except FutureTimeoutError:
88
+ future.cancel()
89
+ raise
90
+
91
+ def close(self) -> None:
92
+ """Stop and join the invocation loop thread."""
93
+ self._loop.call_soon_threadsafe(self._loop.stop)
94
+ self._thread.join(timeout=5)
95
+
96
+
97
+ class KitaruGraphRunner(Generic[InputT, OutputT]):
98
+ """Record supported invocations of one existing compiled graph."""
99
+
100
+ def __init__(
101
+ self,
102
+ graph: Runnable[InputT, OutputT],
103
+ *,
104
+ agent_id: uuid.UUID | None = None,
105
+ agent_version_id: uuid.UUID | None = None,
106
+ session_name: str | None = None,
107
+ batch_size: int = 20,
108
+ capture_policy: CapturePolicy | None = None,
109
+ ) -> None:
110
+ """Initialize a wrapper without changing graph persistence.
111
+
112
+ Args:
113
+ graph: Existing compiled LangGraph or compatible public runnable.
114
+ agent_id: Optional Kitaru agent identifier.
115
+ agent_version_id: Optional Kitaru agent-version identifier.
116
+ session_name: Recorded name, falling back to KITARU_SESSION_NAME.
117
+ batch_size: Number of completed child nodes per ingest batch.
118
+ capture_policy: Redaction and resource limits for stored copies.
119
+
120
+ Raises:
121
+ TypeError: If graph is not a public Runnable.
122
+ ValueError: If batch_size is invalid.
123
+ """
124
+ if not isinstance(graph, Runnable):
125
+ raise TypeError("graph must implement langchain_core.runnables.Runnable")
126
+ if batch_size < 1:
127
+ raise ValueError("batch_size must be at least 1")
128
+ self._graph = graph
129
+ self._agent_id = agent_id
130
+ self._agent_version_id = agent_version_id
131
+ self._session_name = session_name or os.environ.get("KITARU_SESSION_NAME")
132
+ self._batch_size = batch_size
133
+ self._capture_policy = capture_policy or CapturePolicy()
134
+ self._middleware: object | None = None
135
+ self._manifest = None
136
+
137
+ @classmethod
138
+ def from_agent_factory(
139
+ cls,
140
+ factory: Callable[..., Runnable[InputT, OutputT]],
141
+ *,
142
+ factory_kwargs: Mapping[str, Any],
143
+ local_subagents: Sequence[LocalSubagentFactorySpec] = (),
144
+ agent_id: uuid.UUID | None = None,
145
+ agent_version_id: uuid.UUID | None = None,
146
+ session_name: str | None = None,
147
+ batch_size: int = 20,
148
+ capture_policy: CapturePolicy | None = None,
149
+ ) -> "KitaruGraphRunner[InputT, OutputT]":
150
+ """Construct a supported agent with Kitaru middleware outermost."""
151
+ create_agent, create_deep_agent = _import_supported_factories()
152
+
153
+ if factory is not create_agent and factory is not create_deep_agent:
154
+ message = (
155
+ "factory must be langchain.agents.create_agent or "
156
+ "deepagents.create_deep_agent"
157
+ )
158
+ if create_deep_agent is None:
159
+ message += "; Deep Agents support requires kitaru-langgraph[deepagents]"
160
+ raise ValueError(message)
161
+ if local_subagents and factory is not create_deep_agent:
162
+ raise ValueError("local_subagents require deepagents.create_deep_agent")
163
+
164
+ built_subagents: list[dict[str, Any]] = []
165
+ for spec in local_subagents:
166
+ subgraph, _ = cls._call_supported_factory(
167
+ spec.factory, spec.copied_kwargs()
168
+ )
169
+ built_subagents.append(
170
+ {
171
+ "name": spec.name,
172
+ "description": spec.description,
173
+ "runnable": subgraph,
174
+ }
175
+ )
176
+
177
+ kwargs = dict(factory_kwargs)
178
+ existing_subagents = list(kwargs.get("subagents") or ())
179
+ if built_subagents:
180
+ kwargs["subagents"] = [*built_subagents, *existing_subagents]
181
+ graph, middleware = cls._call_supported_factory(factory, kwargs)
182
+ runner = cls(
183
+ graph,
184
+ agent_id=agent_id,
185
+ agent_version_id=agent_version_id,
186
+ session_name=session_name,
187
+ batch_size=batch_size,
188
+ capture_policy=capture_policy,
189
+ )
190
+ runner._middleware = middleware
191
+ runner._manifest = _make_capability_manifest(
192
+ middleware,
193
+ local_subagents=tuple(spec.name for spec in local_subagents),
194
+ opaque_targets=("opaque_subagents",) if existing_subagents else (),
195
+ )
196
+ return runner
197
+
198
+ @staticmethod
199
+ def _call_supported_factory(
200
+ factory: Callable[..., Runnable[Any, Any]], kwargs: dict[str, Any]
201
+ ) -> tuple[Runnable[Any, Any], object]:
202
+ """Inject one middleware and call one known factory exactly once."""
203
+ create_agent, create_deep_agent = _import_supported_factories()
204
+
205
+ from .langchain import KitaruLangGraphMiddleware
206
+
207
+ if factory is not create_agent and factory is not create_deep_agent:
208
+ raise ValueError("local subagent factory is unsupported")
209
+ caller_middleware = list(kwargs.get("middleware") or ())
210
+ if any(
211
+ isinstance(item, KitaruLangGraphMiddleware) for item in caller_middleware
212
+ ):
213
+ raise ValueError("factory middleware already contains Kitaru middleware")
214
+ requested_model = kwargs.get("model")
215
+ middleware = KitaruLangGraphMiddleware(
216
+ requested_model=requested_model
217
+ if isinstance(requested_model, str)
218
+ else None
219
+ )
220
+ kwargs["middleware"] = [middleware, *caller_middleware]
221
+ return factory(**kwargs), middleware
222
+
223
+ @property
224
+ def graph(self) -> Runnable[InputT, OutputT]:
225
+ """Return the exact wrapped runnable."""
226
+ return self._graph
227
+
228
+ @property
229
+ def capabilities(self) -> LangGraphCapabilityView:
230
+ """Return immutable operations available through this construction."""
231
+ return _validate_manifest(self._manifest, self._middleware)
232
+
233
+ def invoke(
234
+ self,
235
+ input: InputT,
236
+ config: RunnableConfig | None = None,
237
+ **kwargs: Any,
238
+ ) -> OutputT:
239
+ """Record one synchronous graph invocation."""
240
+ bridge = _LoopThreadBridge()
241
+ recorder: InvocationRecorder | None = None
242
+ try:
243
+ recorder = bridge.run(
244
+ InvocationRecorder.setup(
245
+ input,
246
+ cast(dict[str, Any] | None, config),
247
+ agent_id=self._agent_id,
248
+ agent_version_id=self._agent_version_id,
249
+ session_name=self._session_name,
250
+ batch_size=self._batch_size,
251
+ policy=self._capture_policy,
252
+ )
253
+ )
254
+ recorder.sync_bridge = bridge
255
+ try:
256
+ self._preflight(recorder)
257
+ effective_input = self._effective_input(input, recorder)
258
+ merged = self._merge_config(config, recorder, bridge=bridge)
259
+ token = _ACTIVE_INVOCATION.set(recorder)
260
+ try:
261
+ result = self._graph.invoke(effective_input, merged, **kwargs)
262
+ finally:
263
+ _ACTIVE_INVOCATION.reset(token)
264
+ except BaseException as graph_error:
265
+ self._finalize_sync(
266
+ bridge, recorder, error=graph_error, graph_succeeded=False
267
+ )
268
+ raise
269
+ self._finalize_sync(bridge, recorder, result=result, graph_succeeded=True)
270
+ if recorder.task_id is not None and _has_interrupt(result):
271
+ raise UnsupportedWorkerInterruptError(
272
+ "LangGraph worker interrupt and resume are not supported"
273
+ )
274
+ return result
275
+ finally:
276
+ bridge.close()
277
+
278
+ async def ainvoke(
279
+ self,
280
+ input: InputT,
281
+ config: RunnableConfig | None = None,
282
+ **kwargs: Any,
283
+ ) -> OutputT:
284
+ """Record one asynchronous graph invocation."""
285
+ recorder = await InvocationRecorder.setup(
286
+ input,
287
+ cast(dict[str, Any] | None, config),
288
+ agent_id=self._agent_id,
289
+ agent_version_id=self._agent_version_id,
290
+ session_name=self._session_name,
291
+ batch_size=self._batch_size,
292
+ policy=self._capture_policy,
293
+ )
294
+ try:
295
+ self._preflight(recorder)
296
+ effective_input = self._effective_input(input, recorder)
297
+ merged = self._merge_config(config, recorder, bridge=None)
298
+ token = _ACTIVE_INVOCATION.set(recorder)
299
+ try:
300
+ result = await self._graph.ainvoke(effective_input, merged, **kwargs)
301
+ finally:
302
+ _ACTIVE_INVOCATION.reset(token)
303
+ except BaseException as graph_error:
304
+ await self._finalize_async(
305
+ recorder, error=graph_error, graph_succeeded=False
306
+ )
307
+ raise
308
+ await self._finalize_async(recorder, result=result, graph_succeeded=True)
309
+ if recorder.task_id is not None and _has_interrupt(result):
310
+ raise UnsupportedWorkerInterruptError(
311
+ "LangGraph worker interrupt and resume are not supported"
312
+ )
313
+ return result
314
+
315
+ def _preflight(self, recorder: InvocationRecorder) -> None:
316
+ """Reject unavailable replay work before the graph executes."""
317
+ override = recorder.override
318
+ if override is None and recorder.replay is None:
319
+ return
320
+ view = self.capabilities
321
+ if override is not None:
322
+ if isinstance(override.model, dict):
323
+ from .langchain import KitaruLangGraphMiddleware
324
+
325
+ if (
326
+ not isinstance(self._middleware, KitaruLangGraphMiddleware)
327
+ or self._middleware.requested_model is None
328
+ ):
329
+ raise UnsupportedCapabilityError(
330
+ "Mapped model override requires a string model at construction"
331
+ )
332
+ operations = (
333
+ (override.model, CapabilityOperation.OVERRIDE_MODEL),
334
+ (override.prompt, CapabilityOperation.OVERRIDE_PROMPT),
335
+ (override.system_prompt, CapabilityOperation.OVERRIDE_SYSTEM_PROMPT),
336
+ (override.model_params, CapabilityOperation.OVERRIDE_MODEL_PARAMS),
337
+ )
338
+ for value, operation in operations:
339
+ if value is not None:
340
+ _require_operation(view, operation)
341
+ if recorder.replay is None:
342
+ return
343
+ policies = [
344
+ recorder.replay.tool_policy.default,
345
+ *recorder.replay.tool_policy.tools.values(),
346
+ ]
347
+ from kitaru.api_models.v1.replay_config import LLMConfig, PassthroughConfig
348
+
349
+ if any(isinstance(policy, LLMConfig) for policy in policies):
350
+ raise ToolPolicyError("Tool policy 'llm' is not supported")
351
+ if any(not isinstance(policy, PassthroughConfig) for policy in policies):
352
+ for target in view.targets:
353
+ _require_operation(
354
+ view,
355
+ CapabilityOperation.SUBSTITUTE_TOOL_RESULT,
356
+ target=target.name,
357
+ )
358
+
359
+ @staticmethod
360
+ async def _finalize_async(
361
+ recorder: InvocationRecorder,
362
+ *,
363
+ result: Any = None,
364
+ error: BaseException | None = None,
365
+ graph_succeeded: bool,
366
+ ) -> None:
367
+ """Finish recording within the adapter's post-delegation deadline."""
368
+ task = asyncio.create_task(recorder.finalize(result=result, error=error))
369
+ try:
370
+ done, _ = await asyncio.wait({task}, timeout=_FINALIZATION_TIMEOUT_SECONDS)
371
+ except asyncio.CancelledError:
372
+ task.cancel()
373
+ stopped = await KitaruGraphRunner._drain_finalization_task(task)
374
+ if stopped:
375
+ await KitaruGraphRunner._close_after_finalization_abort(recorder)
376
+ raise
377
+ if task not in done:
378
+ task.cancel()
379
+ stopped = await KitaruGraphRunner._drain_finalization_task(task)
380
+ recorder.latch("finalize_timeout", TimeoutError())
381
+ if stopped:
382
+ await KitaruGraphRunner._close_after_finalization_abort(recorder)
383
+ recorder.warn(graph_succeeded=graph_succeeded)
384
+ return
385
+ try:
386
+ task.result()
387
+ except asyncio.CancelledError:
388
+ raise
389
+ except BaseException as finalization_error:
390
+ recorder.latch("finalize", finalization_error)
391
+ await KitaruGraphRunner._close_after_finalization_abort(recorder)
392
+ recorder.warn(graph_succeeded=graph_succeeded)
393
+
394
+ @staticmethod
395
+ def _finalize_sync(
396
+ bridge: _LoopThreadBridge,
397
+ recorder: InvocationRecorder,
398
+ *,
399
+ result: Any = None,
400
+ error: BaseException | None = None,
401
+ graph_succeeded: bool,
402
+ ) -> None:
403
+ """Finish synchronous recording without blocking the caller forever."""
404
+ hard_timeout = (
405
+ _FINALIZATION_TIMEOUT_SECONDS + 3 * _FINALIZATION_CLEANUP_TIMEOUT_SECONDS
406
+ )
407
+ try:
408
+ bridge.run(
409
+ KitaruGraphRunner._finalize_async(
410
+ recorder,
411
+ result=result,
412
+ error=error,
413
+ graph_succeeded=graph_succeeded,
414
+ ),
415
+ timeout=hard_timeout,
416
+ )
417
+ except BaseException as finalization_error:
418
+ stage = (
419
+ "finalize_timeout"
420
+ if isinstance(finalization_error, TimeoutError)
421
+ else "finalize"
422
+ )
423
+ recorder.latch(stage, finalization_error)
424
+ with suppress(BaseException):
425
+ bridge.run(
426
+ KitaruGraphRunner._close_after_finalization_abort(recorder),
427
+ timeout=_FINALIZATION_CLEANUP_TIMEOUT_SECONDS,
428
+ )
429
+ recorder.warn(graph_succeeded=graph_succeeded)
430
+
431
+ @staticmethod
432
+ async def _drain_finalization_task(task: asyncio.Task[Any]) -> bool:
433
+ """Give cancellation one bounded event-loop turn to finish."""
434
+ done, _ = await asyncio.wait(
435
+ {task}, timeout=_FINALIZATION_CLEANUP_TIMEOUT_SECONDS
436
+ )
437
+ if task not in done:
438
+ return False
439
+ with suppress(BaseException):
440
+ task.result()
441
+ return True
442
+
443
+ @staticmethod
444
+ async def _close_after_finalization_abort(
445
+ recorder: InvocationRecorder,
446
+ ) -> None:
447
+ """Close the client after an aborted finalizer within a short deadline."""
448
+ close_task = asyncio.create_task(recorder._close())
449
+ done, _ = await asyncio.wait(
450
+ {close_task}, timeout=_FINALIZATION_CLEANUP_TIMEOUT_SECONDS
451
+ )
452
+ if close_task in done:
453
+ with suppress(BaseException):
454
+ close_task.result()
455
+ return
456
+ close_task.cancel()
457
+ await KitaruGraphRunner._drain_finalization_task(close_task)
458
+
459
+ def _effective_input(
460
+ self, caller_input: InputT, recorder: InvocationRecorder
461
+ ) -> InputT:
462
+ """Apply whole-input replacement while preserving any Command."""
463
+ if isinstance(caller_input, Command):
464
+ return caller_input
465
+ return cast(InputT, recorder.effective_input)
466
+
467
+ def _merge_config(
468
+ self,
469
+ config: RunnableConfig | None,
470
+ recorder: InvocationRecorder,
471
+ *,
472
+ bridge: _LoopThreadBridge | None,
473
+ ) -> RunnableConfig:
474
+ """Copy caller config and append the invocation callback."""
475
+ from .callbacks import AsyncKitaruCallback, SyncKitaruCallback
476
+
477
+ callback = (
478
+ SyncKitaruCallback(recorder, bridge)
479
+ if bridge is not None
480
+ else AsyncKitaruCallback(recorder)
481
+ )
482
+ return merge_configs(config, {"callbacks": [callback]})
483
+
484
+ def stream(self, *_: Any, **__: Any) -> Any:
485
+ """Reject unrecorded streaming."""
486
+ self._unsupported("stream")
487
+
488
+ async def astream(self, *_: Any, **__: Any) -> Any:
489
+ """Reject unrecorded asynchronous streaming."""
490
+ self._unsupported("astream")
491
+ if False: # pragma: no cover - preserves async-generator shape
492
+ yield None
493
+
494
+ async def astream_events(self, *_: Any, **__: Any) -> Any:
495
+ """Reject unrecorded event streaming."""
496
+ self._unsupported("astream_events")
497
+ if False: # pragma: no cover
498
+ yield None
499
+
500
+ async def astream_log(self, *_: Any, **__: Any) -> Any:
501
+ """Reject unrecorded log streaming."""
502
+ self._unsupported("astream_log")
503
+ if False: # pragma: no cover
504
+ yield None
505
+
506
+ def batch(self, *_: Any, **__: Any) -> Any:
507
+ """Reject unrecorded batching."""
508
+ self._unsupported("batch")
509
+
510
+ async def abatch(self, *_: Any, **__: Any) -> Any:
511
+ """Reject unrecorded asynchronous batching."""
512
+ self._unsupported("abatch")
513
+
514
+ def batch_as_completed(self, *_: Any, **__: Any) -> Any:
515
+ """Reject unrecorded completed-order batching."""
516
+ self._unsupported("batch_as_completed")
517
+
518
+ async def abatch_as_completed(self, *_: Any, **__: Any) -> Any:
519
+ """Reject unrecorded asynchronous completed-order batching."""
520
+ self._unsupported("abatch_as_completed")
521
+
522
+ @staticmethod
523
+ def _unsupported(name: str) -> None:
524
+ raise UnsupportedInvocationError(
525
+ f"KitaruGraphRunner does not support {name}(); use invoke() or ainvoke()"
526
+ )