langgraph-api 0.19.0.dev3__py3-none-any.whl → 0.19.0.dev5__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.
Files changed (51) hide show
  1. langgraph_api/__init__.py +1 -1
  2. langgraph_api/api/a2a.py +90 -40
  3. langgraph_api/api/meta.py +11 -2
  4. langgraph_api/api/runs.py +199 -8
  5. langgraph_api/api/store.py +5 -1
  6. langgraph_api/api/threads.py +35 -17
  7. langgraph_api/asgi_transport.py +5 -3
  8. langgraph_api/command.py +16 -1
  9. langgraph_api/config/__init__.py +1 -1
  10. langgraph_api/encryption/context.py +11 -4
  11. langgraph_api/errors.py +10 -0
  12. langgraph_api/event_streaming/capabilities.py +1 -1
  13. langgraph_api/event_streaming/service.py +8 -19
  14. langgraph_api/event_streaming/session.py +15 -1
  15. langgraph_api/feature_flags.py +5 -0
  16. langgraph_api/graph.py +10 -1
  17. langgraph_api/grpc/ops/__init__.py +3 -0
  18. langgraph_api/grpc/ops/runs.py +81 -10
  19. langgraph_api/grpc/ops/threads.py +35 -17
  20. langgraph_api/js/client.mts +28 -8
  21. langgraph_api/js/remote.py +20 -2
  22. langgraph_api/js/src/lifecycle.mts +153 -0
  23. langgraph_api/lifecycle.py +276 -0
  24. langgraph_api/metadata.py +8 -2
  25. langgraph_api/metrics_collector.py +3 -1
  26. langgraph_api/middleware/ensure_store.py +4 -0
  27. langgraph_api/middleware/private_network.py +17 -15
  28. langgraph_api/models/run.py +11 -18
  29. langgraph_api/priority_settings.py +12 -1
  30. langgraph_api/self_hosted_metrics.py +5 -2
  31. langgraph_api/serde.py +13 -2
  32. langgraph_api/server.py +14 -0
  33. langgraph_api/sse.py +45 -16
  34. langgraph_api/state.py +82 -5
  35. langgraph_api/stream.py +208 -67
  36. langgraph_api/tracing_session.py +95 -10
  37. langgraph_api/validation.py +1 -0
  38. langgraph_api/worker.py +62 -33
  39. langgraph_api/worker_runtime.py +7 -0
  40. {langgraph_api-0.19.0.dev3.dist-info → langgraph_api-0.19.0.dev5.dist-info}/METADATA +2 -2
  41. {langgraph_api-0.19.0.dev3.dist-info → langgraph_api-0.19.0.dev5.dist-info}/RECORD +51 -49
  42. langgraph_grpc_common/checkpointer.py +7 -5
  43. langgraph_grpc_common/proto/checkpointer_pb2.py +22 -22
  44. langgraph_grpc_common/proto/checkpointer_pb2.pyi +14 -2
  45. langgraph_grpc_common/proto/core_api_pb2.py +162 -162
  46. langgraph_grpc_common/proto/core_api_pb2.pyi +51 -7
  47. langgraph_grpc_common/serde.py +10 -1
  48. openapi.json +178 -12
  49. {langgraph_api-0.19.0.dev3.dist-info → langgraph_api-0.19.0.dev5.dist-info}/WHEEL +0 -0
  50. {langgraph_api-0.19.0.dev3.dist-info → langgraph_api-0.19.0.dev5.dist-info}/entry_points.txt +0 -0
  51. {langgraph_api-0.19.0.dev3.dist-info → langgraph_api-0.19.0.dev5.dist-info}/licenses/LICENSE +0 -0
@@ -215,6 +215,7 @@ async def get_thread_state(
215
215
  thread_id = request.path_params["thread_id"]
216
216
  validate_uuid(thread_id, "Invalid thread ID: must be a UUID")
217
217
  subgraphs = request.query_params.get("subgraphs") in ("true", "True")
218
+ select = _validate_history_select(request.query_params.getlist("select"))
218
219
  async with connect(supports_core_api=PREFER_GRPC_CHECKPOINTER) as conn:
219
220
  config = {
220
221
  "configurable": {
@@ -222,9 +223,7 @@ async def get_thread_state(
222
223
  "thread_id": thread_id,
223
224
  }
224
225
  }
225
- state = state_snapshot_to_thread_state(
226
- await Threads.State.get(conn, config=config, subgraphs=subgraphs)
227
- )
226
+ state = await _thread_state(conn, select, config=config, subgraphs=subgraphs)
228
227
  return ApiResponse(state)
229
228
 
230
229
 
@@ -236,6 +235,7 @@ async def get_thread_state_at_checkpoint(
236
235
  thread_id = request.path_params["thread_id"]
237
236
  validate_uuid(thread_id, "Invalid thread ID: must be a UUID")
238
237
  checkpoint_id = request.path_params["checkpoint_id"]
238
+ select = _validate_history_select(request.query_params.getlist("select"))
239
239
  async with connect(supports_core_api=PREFER_GRPC_CHECKPOINTER) as conn:
240
240
  config = {
241
241
  "configurable": {
@@ -244,12 +244,11 @@ async def get_thread_state_at_checkpoint(
244
244
  "checkpoint_id": checkpoint_id,
245
245
  }
246
246
  }
247
- state = state_snapshot_to_thread_state(
248
- await Threads.State.get(
249
- conn,
250
- config=config,
251
- subgraphs=request.query_params.get("subgraphs") in ("true", "True"),
252
- )
247
+ state = await _thread_state(
248
+ conn,
249
+ select,
250
+ config=config,
251
+ subgraphs=request.query_params.get("subgraphs") in ("true", "True"),
253
252
  )
254
253
  return ApiResponse(state)
255
254
 
@@ -262,6 +261,7 @@ async def get_thread_state_at_checkpoint_post(
262
261
  thread_id = request.path_params["thread_id"]
263
262
  validate_uuid(thread_id, "Invalid thread ID: must be a UUID")
264
263
  payload = await request.json(ThreadStateCheckpointRequest)
264
+ select = _validate_history_select(payload.get("select"))
265
265
  async with connect(supports_core_api=PREFER_GRPC_CHECKPOINTER) as conn:
266
266
  config = {
267
267
  "configurable": {
@@ -270,16 +270,25 @@ async def get_thread_state_at_checkpoint_post(
270
270
  "thread_id": thread_id,
271
271
  }
272
272
  }
273
- state = state_snapshot_to_thread_state(
274
- await Threads.State.get(
275
- conn,
276
- config=config,
277
- subgraphs=payload.get("subgraphs", False),
278
- )
273
+ state = await _thread_state(
274
+ conn,
275
+ select,
276
+ config=config,
277
+ subgraphs=payload.get("subgraphs", False),
279
278
  )
280
279
  return ApiResponse(state)
281
280
 
282
281
 
282
+ async def _thread_state(
283
+ conn: Any, select: list[str] | None, **kwargs: Any
284
+ ) -> "Mapping[str, Any]":
285
+ value_keys = _selected_value_keys(select)
286
+ if value_keys is not None:
287
+ kwargs["channels"] = value_keys
288
+ state = state_snapshot_to_thread_state(await Threads.State.get(conn, **kwargs))
289
+ return _project_thread_state(state, select, value_keys) if select else state
290
+
291
+
283
292
  @retry_db
284
293
  async def update_thread_state(
285
294
  request: ApiRequest,
@@ -407,7 +416,7 @@ def _validate_history_select(select: list[str] | None) -> list[str] | None:
407
416
 
408
417
 
409
418
  def _selected_value_keys(select: list[str] | None) -> list[str] | None:
410
- """State keys history entries return, or None when they return all of them."""
419
+ """State keys a state or history read returns, or None when it returns all."""
411
420
  if not select or "values" in select:
412
421
  return None
413
422
  return [f.removeprefix("values.") for f in select if f.startswith("values.")]
@@ -534,8 +543,13 @@ async def delete_thread(request: ApiRequest):
534
543
  """Delete a thread by ID."""
535
544
  thread_id = request.path_params["thread_id"]
536
545
  validate_uuid(thread_id, "Invalid thread ID: must be a UUID")
546
+ sync_checkpoint_delete = (
547
+ request.query_params.get("sync_checkpoint_delete", "").lower() == "true"
548
+ )
537
549
  async with connect() as conn:
538
- tid = await Threads.delete(conn, thread_id)
550
+ tid = await Threads.delete(
551
+ conn, thread_id, sync_checkpoint_delete=sync_checkpoint_delete
552
+ )
539
553
  await fetchone(tid)
540
554
  return Response(status_code=204)
541
555
 
@@ -565,6 +579,7 @@ async def prune_threads(request: ApiRequest):
565
579
  pruned_count = await Threads.prune(
566
580
  thread_ids=thread_ids,
567
581
  strategy=strategy,
582
+ sync_checkpoint_delete=payload.get("sync_checkpoint_delete", False),
568
583
  )
569
584
 
570
585
  return ApiResponse({"pruned_count": pruned_count})
@@ -605,12 +620,15 @@ async def join_thread_stream(request: ApiRequest):
605
620
  if mode not in get_args(ThreadStreamMode):
606
621
  raise HTTPException(status_code=422, detail=f"Invalid stream mode: {mode}")
607
622
 
623
+ # Clients reconnect to Location as-is, so it keeps the request's query.
624
+ query = f"?{request.url.query}" if request.url.query else ""
608
625
  return EventSourceResponse(
609
626
  Threads.Stream.join(
610
627
  thread_id,
611
628
  last_event_id=last_event_id,
612
629
  stream_modes=stream_modes,
613
630
  ),
631
+ headers={"Location": f"/threads/{thread_id}/stream{query}"},
614
632
  )
615
633
 
616
634
 
@@ -9,7 +9,7 @@ import asyncio
9
9
  import typing
10
10
 
11
11
  from httpx import ASGITransport as ASGITransportBase
12
- from httpx import AsyncByteStream, Request, Response
12
+ from httpx import AsyncByteStream, RemoteProtocolError, Request, Response
13
13
 
14
14
  if typing.TYPE_CHECKING: # pragma: no cover
15
15
  import trio # type: ignore[unresolved-import]
@@ -272,10 +272,12 @@ class ASGITransport(ASGITransportBase):
272
272
  # The consumer drains queued chunks then sees the
273
273
  # error. Bound unconditionally — this is an ASGI
274
274
  # protocol error, not an app error, so it's not
275
- # gated on raise_app_exceptions.
275
+ # gated on raise_app_exceptions. A socket raises
276
+ # RemoteProtocolError for a truncated body, and the SDK
277
+ # reconnects a stream only on httpx errors.
276
278
  if not app_complete.done():
277
279
  app_complete.set_exception(
278
- RuntimeError("Response not complete")
280
+ RemoteProtocolError("Response not complete")
279
281
  )
280
282
  else:
281
283
  # 3. Clean completion (send saw more_body=False).
langgraph_api/command.py CHANGED
@@ -1,9 +1,24 @@
1
- from typing import cast
1
+ import re
2
+ from typing import Any, cast
2
3
 
3
4
  from langgraph.types import Command, Send
4
5
 
5
6
  from langgraph_api.schema import RunCommand
6
7
 
8
+ # langgraph resumes interrupts by id only when every key of the resume map has
9
+ # this shape; any other key turns the whole map into one value for whichever
10
+ # interrupt is pending.
11
+ INTERRUPT_ID_RE = re.compile(r"[0-9a-f]{32}")
12
+
13
+
14
+ def keyed_by_interrupt_id(value: Any) -> bool:
15
+ """Whether langgraph resumes ``value`` per interrupt rather than as one answer."""
16
+ return (
17
+ isinstance(value, dict)
18
+ and bool(value)
19
+ and all(INTERRUPT_ID_RE.fullmatch(key) for key in value)
20
+ )
21
+
7
22
 
8
23
  def map_cmd(cmd: RunCommand) -> Command:
9
24
  goto = cmd.get("goto")
@@ -205,7 +205,7 @@ LANGGRAPH_CLOUD_LICENSE_KEY = env("LANGGRAPH_CLOUD_LICENSE_KEY", cast=str, defau
205
205
 
206
206
  # When true, the Go core-server owns Postgres schema setup (DB migrations +
207
207
  # vector index)
208
- DB_MIGRATION_BY_CORE_API = env("DB_MIGRATION_BY_CORE_API", cast=bool, default=False)
208
+ DB_MIGRATION_BY_CORE_API = env("DB_MIGRATION_BY_CORE_API", cast=bool, default=True)
209
209
 
210
210
  # redis
211
211
  # Not in public docs: infrastructure, set by platform
@@ -7,8 +7,8 @@ from typing import Any
7
7
  import orjson
8
8
  import structlog
9
9
  from starlette.exceptions import HTTPException
10
- from starlette.middleware.base import BaseHTTPMiddleware
11
10
  from starlette.requests import Request
11
+ from starlette.types import ASGIApp, Receive, Scope, Send
12
12
 
13
13
  from langgraph_api.config import LANGGRAPH_ENCRYPTION
14
14
  from langgraph_api.encryption.custom import get_custom_encryption_instance
@@ -68,10 +68,17 @@ def extract_encryption_context(request: Request) -> dict[str, Any]:
68
68
  ) from e
69
69
 
70
70
 
71
- class EncryptionContextMiddleware(BaseHTTPMiddleware):
71
+ class EncryptionContextMiddleware:
72
72
  """Set request encryption context from headers and the configured handler."""
73
73
 
74
- async def dispatch(self, request: Request, call_next):
74
+ def __init__(self, app: ASGIApp) -> None:
75
+ self.app = app
76
+
77
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
78
+ if scope["type"] != "http":
79
+ await self.app(scope, receive, send)
80
+ return
81
+ request = Request(scope)
75
82
  context_dict = extract_encryption_context(request)
76
83
 
77
84
  encryption_instance = get_custom_encryption_instance()
@@ -92,4 +99,4 @@ class EncryptionContextMiddleware(BaseHTTPMiddleware):
92
99
 
93
100
  set_encryption_context(context_dict)
94
101
  request.state.encryption_context = context_dict
95
- return await call_next(request)
102
+ await self.app(scope, receive, send)
langgraph_api/errors.py CHANGED
@@ -93,3 +93,13 @@ class UserTimeout(Exception):
93
93
  def __init__(self, timeout_error: TimeoutError):
94
94
  super().__init__(timeout_error)
95
95
  self.timeout_error = timeout_error
96
+
97
+
98
+ class StreamCutError(Exception):
99
+ """The event stream behind a response ended before its run did.
100
+
101
+ The SSE response aborts instead of sending an ``error`` event, so the SDKs
102
+ reconnect run and thread streams with ``Last-Event-ID``. Behind a custom
103
+ ``BaseHTTPMiddleware``, which would end an aborted response cleanly, the
104
+ response sends an ``error`` event instead.
105
+ """
@@ -37,7 +37,7 @@ the runtime cannot emit native protocol-shaped message events.
37
37
  ``messages/partial`` events, which v2 no longer supports.
38
38
 
39
39
  Remote (JS) pregels bypass every code path that needs these symbols
40
- (``stream.py`` drops ``tools`` / ``lifecycle`` and skips the
40
+ (on protocol v2 runs ``stream.py`` drops ``tools`` / ``lifecycle`` and skips the
41
41
  content-block dispatch for remote graphs), so a ``BaseRemotePregel``-only
42
42
  deployment could in theory run on an older Python ``langgraph``. The
43
43
  probe is still applied — the DX of a clear "upgrade your dependencies"
@@ -21,7 +21,6 @@ from __future__ import annotations
21
21
  import asyncio
22
22
  import contextlib
23
23
  import inspect
24
- import re
25
24
  import time
26
25
  from collections.abc import Awaitable, Callable, Mapping
27
26
  from typing import Any, cast, get_args
@@ -30,6 +29,7 @@ from uuid import UUID, uuid4
30
29
  import orjson
31
30
  import structlog
32
31
 
32
+ from langgraph_api.command import INTERRUPT_ID_RE, keyed_by_interrupt_id
33
33
  from langgraph_api.event_streaming.capabilities import (
34
34
  ProtocolV2Capabilities,
35
35
  ProtocolV2UnsupportedError,
@@ -46,6 +46,7 @@ from langgraph_api.event_streaming.session import (
46
46
  from langgraph_api.event_streaming.types import Subscription
47
47
  from langgraph_api.feature_flags import FF_V2_EVENT_STREAMING, PREFER_GRPC_CHECKPOINTER
48
48
  from langgraph_api.schema import MultitaskStrategy
49
+ from langgraph_api.tracing_session import tracer_destination
49
50
  from langgraph_api.validation import sanitize_reserved_keys
50
51
 
51
52
  logger = structlog.stdlib.get_logger(__name__)
@@ -101,20 +102,21 @@ def validate_checkpoint_id_from_runnable_config(params: dict[str, Any]) -> str |
101
102
 
102
103
  def _langsmith_tracer_from_run_start(
103
104
  params: dict[str, Any],
104
- ) -> dict[str, str] | None:
105
+ ) -> dict[str, Any] | None:
105
106
  tracer = params.get("langsmith_tracer")
106
107
  if tracer is None:
107
108
  return None
108
109
  if not _is_record(tracer):
109
110
  raise ValueError("langsmith_tracer must be an object.")
110
- unknown = tracer.keys() - {"project_name", "example_id"}
111
+ unknown = tracer.keys() - {"project_name", "example_id", "address"}
111
112
  if unknown:
112
113
  raise ValueError(
113
114
  f"langsmith_tracer has unsupported fields: {sorted(unknown)!r}."
114
115
  )
115
116
  for key, value in tracer.items():
116
- if not isinstance(value, str):
117
+ if key != "address" and not isinstance(value, str):
117
118
  raise ValueError(f"langsmith_tracer.{key} must be a string.")
119
+ tracer_destination({"langsmith_tracer": tracer})
118
120
  return dict(tracer)
119
121
 
120
122
 
@@ -150,25 +152,12 @@ EventSink = Callable[[dict[str, Any]], Awaitable[None] | None]
150
152
  _IN_FLIGHT_THREAD_STATUS = "busy"
151
153
  _INTERRUPT_SETTLE_TIMEOUT_SECONDS = 5.0
152
154
  _INTERRUPT_SETTLE_POLL_INTERVAL_SECONDS = 0.05
153
- # langgraph resumes interrupts by id only when every key of the resume map has
154
- # this shape; any other key turns the whole map into one value for whichever
155
- # interrupt is pending.
156
- _INTERRUPT_ID_RE = re.compile(r"[0-9a-f]{32}")
157
155
 
158
156
 
159
157
  class _AmbiguousResumeError(Exception):
160
158
  """``run.start`` input would resume several pending interrupts at once."""
161
159
 
162
160
 
163
- def _keyed_by_interrupt_id(value: Any) -> bool:
164
- """Whether langgraph resumes ``value`` per interrupt rather than as one answer."""
165
- return (
166
- _is_record(value)
167
- and bool(value)
168
- and all(_INTERRUPT_ID_RE.fullmatch(key) for key in value)
169
- )
170
-
171
-
172
161
  # Protocol v2 commands this server implements. Anything outside this
173
162
  # set returns ``unknown_command`` up front from ``handle_command`` so
174
163
  # pre-session dispatch does not mislabel typos (or removed methods
@@ -707,7 +696,7 @@ class ThreadRunManager:
707
696
  # open for any id shaped like an interrupt id: the resume below is
708
697
  # authoritative, so neither must masquerade as a missing interrupt.
709
698
  if thread_state_ids is None:
710
- rejected = not _INTERRUPT_ID_RE.fullmatch(interrupt_id)
699
+ rejected = not INTERRUPT_ID_RE.fullmatch(interrupt_id)
711
700
  else:
712
701
  rejected = interrupt_id not in thread_state_ids
713
702
  if rejected:
@@ -814,7 +803,7 @@ class ThreadRunManager:
814
803
  has_interrupts = False
815
804
  if params.get("input") is not None and not force_resume:
816
805
  has_interrupts = await self._has_pending_interrupts()
817
- if has_interrupts and not _keyed_by_interrupt_id(params["input"]):
806
+ if has_interrupts and not keyed_by_interrupt_id(params["input"]):
818
807
  # One answer can't say which of several pending interrupts it is
819
808
  # for: langgraph fails the run, or picks one when they share a
820
809
  # subgraph task. Only a paused thread's row is current, so a run in
@@ -567,6 +567,10 @@ class EventStreamingSession:
567
567
  scope cleanly wraps every push triggered by this source event.
568
568
  """
569
569
 
570
+ if method == "interrupts":
571
+ await self._emit_input_answered(data)
572
+ return
573
+
570
574
  # Core ``langgraph.stream`` already emits canonical ProtocolEvent
571
575
  # objects. Re-envelope them with this session's seq/event_id so
572
576
  # transport replay remains API-owned.
@@ -1118,7 +1122,7 @@ class EventStreamingSession:
1118
1122
  self, subscription: Subscription, event: dict[str, Any]
1119
1123
  ) -> bool:
1120
1124
  raw_method = event.get("method", "")
1121
- channel = "input" if raw_method == "input.requested" else raw_method
1125
+ channel = "input" if raw_method.startswith("input.") else raw_method
1122
1126
  if not _is_supported_channel(channel):
1123
1127
  return False
1124
1128
  if channel == "custom":
@@ -1576,6 +1580,16 @@ class EventStreamingSession:
1576
1580
  """
1577
1581
  return self._pending_interrupts.get(interrupt_id)
1578
1582
 
1583
+ async def _emit_input_answered(self, data: Any) -> None:
1584
+ answered = data.get("answered") if _is_record(data) else None
1585
+ if not isinstance(answered, list) or not answered:
1586
+ return
1587
+ for interrupt_id in answered:
1588
+ self.clear_pending_interrupt(interrupt_id)
1589
+ await self._push_event(
1590
+ self._create_event("input.answered", [], {"interrupt_ids": answered})
1591
+ )
1592
+
1579
1593
  def clear_pending_interrupt(self, interrupt_id: str) -> None:
1580
1594
  """Remove *interrupt_id* from the pending set after a successful resume."""
1581
1595
  self._pending_interrupts.pop(interrupt_id, None)
@@ -91,3 +91,8 @@ DELTA_CHANNEL_SUPPORT = LANGGRAPH_PY_MINOR >= (1, 2)
91
91
  # (langchain-ai/langgraph#9281). Earlier versions drain in front of a
92
92
  # breakpoint, and the resume then runs past it.
93
93
  DRAIN_RESUME_SUPPORT = LANGGRAPH_PY_PATCH >= (1, 2, 15)
94
+
95
+ # v1 runs stream `tools` events from langgraph 1.2.19. Before it, a tool that
96
+ # pauses on `interrupt()` is reported as failed, and an awaited `@task` in a
97
+ # subgraph returns None while the tools handler runs.
98
+ TOOLS_STREAM_SUPPORT = LANGGRAPH_PY_PATCH >= (1, 2, 19)
langgraph_api/graph.py CHANGED
@@ -424,7 +424,16 @@ async def get_graph(
424
424
  if graph_obj.name == "LangGraph":
425
425
  update["name"] = graph_id
426
426
  if isinstance(graph_obj, BaseRemotePregel):
427
- update["config"] = config
427
+ # JS factories run in the sidecar and only see this config, so they
428
+ # get the same read-vs-run signal as Python factories here.
429
+ config = config or {}
430
+ update["config"] = {
431
+ **config,
432
+ "configurable": {
433
+ **(config.get("configurable") or {}),
434
+ "__is_for_execution__": is_for_execution(access_context),
435
+ },
436
+ }
428
437
  yield graph_obj.copy(update=update)
429
438
  finally:
430
439
  var_child_runnable_config.set(None)
@@ -21,6 +21,7 @@ from starlette.exceptions import HTTPException
21
21
  from langgraph_api.auth.custom import handle_event as auth_handle_event
22
22
  from langgraph_api.encryption.context import get_encryption_context
23
23
  from langgraph_api.encryption.shared import using_encryption
24
+ from langgraph_api.errors import StreamCutError
24
25
  from langgraph_api.serde import json_dumpb
25
26
  from langgraph_api.utils import get_auth_ctx
26
27
 
@@ -186,6 +187,8 @@ def _handle_grpc_error(error: AioRpcError) -> None:
186
187
  - A string. This we can return verbatim.
187
188
  Always return detail as a string here.
188
189
  """
190
+ if error.code() == StatusCode.ABORTED:
191
+ raise StreamCutError(error.details()) from error
189
192
  error_details = error.details()
190
193
  retry_after_seconds = None
191
194
  if error_details is not None:
@@ -39,7 +39,7 @@ from langgraph_grpc_common.proto import (
39
39
  from langgraph_sdk import Auth
40
40
  from starlette.exceptions import HTTPException
41
41
 
42
- from langgraph_api.asyncio import ValueEvent
42
+ from langgraph_api.asyncio import ValueEvent, create_task
43
43
  from langgraph_api.auth.custom import handle_event as auth_handle_event
44
44
  from langgraph_api.config import (
45
45
  STREAM_PUBLISH_RETRY_BACKOFF_FACTOR,
@@ -229,6 +229,7 @@ class GrpcStreamHandler:
229
229
  def __init__(self, run_id: UUID, thread_id: UUID):
230
230
  self.run_id = run_id
231
231
  self.thread_id = thread_id
232
+ self.join_requested = False
232
233
  self._stream = None
233
234
  self._closed = False
234
235
 
@@ -281,6 +282,7 @@ class GrpcStreamHandler:
281
282
  ignore_run_not_found: bool = False,
282
283
  cancel_on_disconnect: bool = False,
283
284
  last_event_id: str | None = None,
285
+ namespaces: list[str] | None = None,
284
286
  ):
285
287
  """Send JoinRunRequest and yield events.
286
288
 
@@ -300,10 +302,14 @@ class GrpcStreamHandler:
300
302
  join_kwargs["stream_modes"] = stream_modes
301
303
  if last_event_id is not None:
302
304
  join_kwargs["last_event_id"] = last_event_id
305
+ if namespaces:
306
+ join_kwargs["namespaces"] = namespaces
303
307
 
304
308
  # Send JoinRunRequest
305
309
  join_msg = pb.StreamRunClientMessage(join=pb.JoinRunRequest(**join_kwargs))
306
310
  await self._stream.write(join_msg)
311
+ # Only after the write: a write cancelled midway may never reach the core.
312
+ self.join_requested = True
307
313
 
308
314
  # Half-close: signal we're done sending client messages.
309
315
  # Required for bidirectional streaming so the server knows to stop
@@ -348,6 +354,36 @@ class GrpcStreamHandler:
348
354
  await self.close()
349
355
 
350
356
 
357
+ async def _cancel_dropped_join(
358
+ run_id: UUID,
359
+ thread_id: UUID,
360
+ ctx: Any,
361
+ filters: list[pb.AuthFilter] | None,
362
+ ) -> None:
363
+ # Same filters and reason as the core's own cancel when a joined stream drops.
364
+ # No filters means the drop interrupted the stream's own read check.
365
+ if filters is None:
366
+ filters = await Runs.Stream.handle_event(
367
+ ctx, "read", Auth.types.ThreadsRead(run_id=run_id, thread_id=thread_id)
368
+ )
369
+ client = await get_shared_client()
370
+ try:
371
+ await client.runs.Cancel(
372
+ pb.CancelRunRequest(
373
+ filters=filters,
374
+ action=enum_cancel_run_action.interrupt,
375
+ reason="client disconnected from the run stream (on_disconnect=cancel)",
376
+ run_ids=pb.CancelRunIdsTarget(
377
+ thread_id=pb.UUID(value=str(thread_id)),
378
+ run_ids=[pb.UUID(value=str(run_id))],
379
+ ),
380
+ )
381
+ )
382
+ except AioRpcError as e:
383
+ if e.code() != StatusCode.NOT_FOUND:
384
+ raise
385
+
386
+
351
387
  def _map_multitask_strategy(
352
388
  strategy: MultitaskStrategy | None,
353
389
  ) -> enum_multitask_strategy.MultitaskStrategy | None:
@@ -644,18 +680,31 @@ class Runs(Authenticated):
644
680
  *,
645
681
  thread_id: UUID,
646
682
  ctx: Any = None,
683
+ read_mask_paths: list[str] | None = None,
647
684
  ) -> AsyncIterator[Run]:
648
- """Get a run by ID."""
685
+ """Get a run by ID.
686
+
687
+ Args:
688
+ read_mask_paths: When set, "metadata" and "kwargs" are read only if
689
+ listed, and every other field always is; omitting "kwargs" skips
690
+ the run's input. None reads every field.
691
+ """
649
692
  auth_filters = await Runs.handle_event(
650
693
  ctx,
651
694
  "read",
652
695
  Auth.types.ThreadsRead(run_id=run_id, thread_id=thread_id),
653
696
  )
654
697
 
698
+ read_mask = (
699
+ field_mask_pb2.FieldMask(paths=read_mask_paths)
700
+ if read_mask_paths is not None
701
+ else None
702
+ )
655
703
  request = pb.GetRunRequest(
656
704
  run_id=pb.UUID(value=str(run_id)),
657
705
  thread_id=pb.UUID(value=str(thread_id)),
658
706
  filters=auth_filters,
707
+ read_mask=read_mask,
659
708
  )
660
709
 
661
710
  client = await get_shared_client()
@@ -987,11 +1036,14 @@ class Runs(Authenticated):
987
1036
  }
988
1037
  if response.HasField("redis"):
989
1038
  r = response.redis
990
- out["redis"] = {
1039
+ redis_stats: dict[str, int] = {
991
1040
  "idle_connections": r.idle_connections,
992
1041
  "in_use_connections": r.in_use_connections,
993
- "max_connections": r.max_connections,
994
1042
  }
1043
+ # Cluster omits max — proto3 zero is indistinguishable from unset.
1044
+ if r.max_connections:
1045
+ redis_stats["max_connections"] = r.max_connections
1046
+ out["redis"] = redis_stats
995
1047
  return out
996
1048
 
997
1049
  @staticmethod
@@ -1126,6 +1178,7 @@ class Runs(Authenticated):
1126
1178
  cancel_on_disconnect: bool = False,
1127
1179
  stream_mode: list[str] | None = None,
1128
1180
  last_event_id: str | None = None,
1181
+ namespaces: list[str] | None = None,
1129
1182
  ctx: Any = None,
1130
1183
  ):
1131
1184
  """Join the run stream and start receiving events.
@@ -1135,21 +1188,22 @@ class Runs(Authenticated):
1135
1188
  Yields tuples of (event_bytes, message_bytes, stream_id_bytes|None).
1136
1189
  """
1137
1190
  handler: GrpcStreamHandler = stream_channel
1138
- auth_filters = await Runs.Stream.handle_event(
1139
- ctx,
1140
- "read",
1141
- Auth.types.ThreadsRead(run_id=run_id, thread_id=thread_id),
1142
- )
1143
-
1144
1191
  stream_modes_pb = _map_stream_modes(stream_mode)
1192
+ auth_filters: list[pb.AuthFilter] | None = None
1145
1193
 
1146
1194
  try:
1195
+ auth_filters = await Runs.Stream.handle_event(
1196
+ ctx,
1197
+ "read",
1198
+ Auth.types.ThreadsRead(run_id=run_id, thread_id=thread_id),
1199
+ )
1147
1200
  async for event_bytes, message_bytes, stream_id_bytes in handler.join(
1148
1201
  auth_filters=auth_filters,
1149
1202
  stream_modes=stream_modes_pb or None,
1150
1203
  ignore_run_not_found=ignore_404,
1151
1204
  cancel_on_disconnect=cancel_on_disconnect,
1152
1205
  last_event_id=last_event_id,
1206
+ namespaces=namespaces,
1153
1207
  ):
1154
1208
  yield (event_bytes, message_bytes, stream_id_bytes)
1155
1209
  except AioRpcError as e:
@@ -1158,6 +1212,14 @@ class Runs(Authenticated):
1158
1212
  return # Return empty stream
1159
1213
  # Convert all other gRPC errors to HTTP exceptions
1160
1214
  _handle_grpc_error(e)
1215
+ except asyncio.CancelledError:
1216
+ # The core can cancel on disconnect only after it receives the join request.
1217
+ if cancel_on_disconnect and not handler.join_requested:
1218
+ create_task(
1219
+ _cancel_dropped_join(run_id, thread_id, ctx, auth_filters),
1220
+ ignore_exceptions=(HTTPException,),
1221
+ )
1222
+ raise
1161
1223
  finally:
1162
1224
  await handler.close()
1163
1225
 
@@ -1198,6 +1260,8 @@ class Runs(Authenticated):
1198
1260
  thread_id: UUID | str,
1199
1261
  *,
1200
1262
  resumable: bool = False,
1263
+ publisher_id: str | None = None,
1264
+ seq: int | None = None,
1201
1265
  ) -> None:
1202
1266
  """Publish a message to the run stream via gRPC.
1203
1267
 
@@ -1207,6 +1271,11 @@ class Runs(Authenticated):
1207
1271
  message: Event payload (serialized JSON or raw bytes)
1208
1272
  thread_id: The thread ID
1209
1273
  resumable: If true, message will be cached with TTL for resumable streaming
1274
+ publisher_id: With `seq`, lets the Lua publish scripts drop a
1275
+ retried publish instead of adding it twice; publishes outside
1276
+ those scripts, such as a plain Pub/Sub publish, ignore both.
1277
+ Pass both or neither.
1278
+ seq: The event's number within the publisher; retries resend it
1210
1279
  """
1211
1280
  run_id_pb = (
1212
1281
  None if run_id is None or run_id == "*" else pb.UUID(value=str(run_id))
@@ -1218,6 +1287,8 @@ class Runs(Authenticated):
1218
1287
  event_type=event,
1219
1288
  message=message,
1220
1289
  resumable=resumable,
1290
+ publisher_id=publisher_id,
1291
+ seq=seq,
1221
1292
  )
1222
1293
  max_duration_secs = max(0.0, STREAM_PUBLISH_RETRY_MAX_DURATION_SECS)
1223
1294
  initial_interval_secs = max(