langgraph-api 0.19.0.dev4__py3-none-any.whl → 0.19.0.dev6__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 (65) hide show
  1. langgraph_api/__init__.py +1 -1
  2. langgraph_api/api/a2a.py +90 -40
  3. langgraph_api/api/meta.py +20 -4
  4. langgraph_api/api/runs.py +217 -8
  5. langgraph_api/api/threads.py +38 -17
  6. langgraph_api/asgi_transport.py +5 -3
  7. langgraph_api/command.py +16 -1
  8. langgraph_api/config/__init__.py +26 -1
  9. langgraph_api/encryption/context.py +11 -4
  10. langgraph_api/errors.py +37 -0
  11. langgraph_api/event_streaming/capabilities.py +1 -1
  12. langgraph_api/event_streaming/service.py +12 -23
  13. langgraph_api/event_streaming/session.py +33 -2
  14. langgraph_api/executor/__main__.py +18 -4
  15. langgraph_api/feature_flags.py +5 -0
  16. langgraph_api/go_prometheus_metrics.py +52 -0
  17. langgraph_api/grpc/ops/__init__.py +3 -0
  18. langgraph_api/grpc/ops/runs.py +64 -28
  19. langgraph_api/grpc/ops/threads.py +60 -23
  20. langgraph_api/js/client.mts +45 -13
  21. langgraph_api/js/errors.py +9 -2
  22. langgraph_api/js/package.json +2 -2
  23. langgraph_api/js/remote.py +9 -1
  24. langgraph_api/js/src/lifecycle.mts +153 -0
  25. langgraph_api/js/src/utils/serde.mts +21 -0
  26. langgraph_api/js/yarn.lock +113 -113
  27. langgraph_api/lifecycle.py +276 -0
  28. langgraph_api/metadata.py +4 -11
  29. langgraph_api/metrics_collector.py +3 -1
  30. langgraph_api/metrics_otlp.py +13 -1
  31. langgraph_api/middleware/private_network.py +17 -15
  32. langgraph_api/models/run.py +1 -16
  33. langgraph_api/queue_entrypoint.py +5 -1
  34. langgraph_api/runtime/__init__.py +1 -0
  35. langgraph_api/runtime/lifespan.py +335 -0
  36. langgraph_api/runtime/metrics.py +26 -0
  37. langgraph_api/runtime/queue.py +457 -0
  38. langgraph_api/runtime/retry.py +87 -0
  39. langgraph_api/self_hosted_metrics.py +9 -3
  40. langgraph_api/serde.py +6 -2
  41. langgraph_api/server.py +14 -0
  42. langgraph_api/sse.py +45 -16
  43. langgraph_api/state.py +82 -5
  44. langgraph_api/stream.py +215 -43
  45. langgraph_api/utils/__init__.py +7 -3
  46. langgraph_api/validation.py +1 -0
  47. langgraph_api/web_identity.py +287 -0
  48. langgraph_api/worker.py +59 -11
  49. langgraph_api/worker_runtime.py +28 -0
  50. {langgraph_api-0.19.0.dev4.dist-info → langgraph_api-0.19.0.dev6.dist-info}/METADATA +1 -1
  51. {langgraph_api-0.19.0.dev4.dist-info → langgraph_api-0.19.0.dev6.dist-info}/RECORD +65 -56
  52. langgraph_grpc_common/checkpointer.py +7 -5
  53. langgraph_grpc_common/proto/checkpointer_pb2.py +18 -18
  54. langgraph_grpc_common/proto/checkpointer_pb2.pyi +9 -1
  55. langgraph_grpc_common/proto/core_api_pb2.py +150 -148
  56. langgraph_grpc_common/proto/core_api_pb2.pyi +75 -8
  57. langgraph_grpc_common/proto/core_api_pb2_grpc.py +44 -0
  58. langgraph_grpc_common/proto/core_api_pb2_grpc.pyi +12 -0
  59. langgraph_grpc_common/proto/orchestrator_pb2.py +4 -4
  60. langgraph_grpc_common/proto/orchestrator_pb2.pyi +5 -1
  61. langgraph_runtime/__init__.py +3 -0
  62. openapi.json +180 -14
  63. {langgraph_api-0.19.0.dev4.dist-info → langgraph_api-0.19.0.dev6.dist-info}/WHEEL +0 -0
  64. {langgraph_api-0.19.0.dev4.dist-info → langgraph_api-0.19.0.dev6.dist-info}/entry_points.txt +0 -0
  65. {langgraph_api-0.19.0.dev4.dist-info → langgraph_api-0.19.0.dev6.dist-info}/licenses/LICENSE +0 -0
@@ -106,6 +106,11 @@ async def create_thread(
106
106
  return ApiResponse(thread)
107
107
 
108
108
 
109
+ def _raw_values_kwargs(raw_values: bool = True) -> dict[str, bool]:
110
+ """Have the gRPC ops relay thread values undecoded; in-memory ops always decode."""
111
+ return {"raw_values": raw_values} if IS_POSTGRES_OR_GRPC_BACKEND else {}
112
+
113
+
109
114
  def _exclude_metadata_kwargs(payload: dict) -> dict:
110
115
  """Normalize `exclude_metadata` (object or list of objects) into ops kwargs."""
111
116
  exclude_metadata = payload.get("exclude_metadata")
@@ -167,6 +172,8 @@ async def search_threads(
167
172
  sort_order=payload.get("sort_order"),
168
173
  select=storage_select,
169
174
  extract=storage_extract,
175
+ # Python-side extraction reads the values, so it needs them decoded.
176
+ **_raw_values_kwargs(not (extract and needs_python_extract)),
170
177
  **exclude_kwargs,
171
178
  )
172
179
  threads, response_headers = await get_pagination_headers(
@@ -215,6 +222,7 @@ async def get_thread_state(
215
222
  thread_id = request.path_params["thread_id"]
216
223
  validate_uuid(thread_id, "Invalid thread ID: must be a UUID")
217
224
  subgraphs = request.query_params.get("subgraphs") in ("true", "True")
225
+ select = _validate_history_select(request.query_params.getlist("select"))
218
226
  async with connect(supports_core_api=PREFER_GRPC_CHECKPOINTER) as conn:
219
227
  config = {
220
228
  "configurable": {
@@ -222,9 +230,7 @@ async def get_thread_state(
222
230
  "thread_id": thread_id,
223
231
  }
224
232
  }
225
- state = state_snapshot_to_thread_state(
226
- await Threads.State.get(conn, config=config, subgraphs=subgraphs)
227
- )
233
+ state = await _thread_state(conn, select, config=config, subgraphs=subgraphs)
228
234
  return ApiResponse(state)
229
235
 
230
236
 
@@ -236,6 +242,7 @@ async def get_thread_state_at_checkpoint(
236
242
  thread_id = request.path_params["thread_id"]
237
243
  validate_uuid(thread_id, "Invalid thread ID: must be a UUID")
238
244
  checkpoint_id = request.path_params["checkpoint_id"]
245
+ select = _validate_history_select(request.query_params.getlist("select"))
239
246
  async with connect(supports_core_api=PREFER_GRPC_CHECKPOINTER) as conn:
240
247
  config = {
241
248
  "configurable": {
@@ -244,12 +251,11 @@ async def get_thread_state_at_checkpoint(
244
251
  "checkpoint_id": checkpoint_id,
245
252
  }
246
253
  }
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
- )
254
+ state = await _thread_state(
255
+ conn,
256
+ select,
257
+ config=config,
258
+ subgraphs=request.query_params.get("subgraphs") in ("true", "True"),
253
259
  )
254
260
  return ApiResponse(state)
255
261
 
@@ -262,6 +268,7 @@ async def get_thread_state_at_checkpoint_post(
262
268
  thread_id = request.path_params["thread_id"]
263
269
  validate_uuid(thread_id, "Invalid thread ID: must be a UUID")
264
270
  payload = await request.json(ThreadStateCheckpointRequest)
271
+ select = _validate_history_select(payload.get("select"))
265
272
  async with connect(supports_core_api=PREFER_GRPC_CHECKPOINTER) as conn:
266
273
  config = {
267
274
  "configurable": {
@@ -270,16 +277,25 @@ async def get_thread_state_at_checkpoint_post(
270
277
  "thread_id": thread_id,
271
278
  }
272
279
  }
273
- state = state_snapshot_to_thread_state(
274
- await Threads.State.get(
275
- conn,
276
- config=config,
277
- subgraphs=payload.get("subgraphs", False),
278
- )
280
+ state = await _thread_state(
281
+ conn,
282
+ select,
283
+ config=config,
284
+ subgraphs=payload.get("subgraphs", False),
279
285
  )
280
286
  return ApiResponse(state)
281
287
 
282
288
 
289
+ async def _thread_state(
290
+ conn: Any, select: list[str] | None, **kwargs: Any
291
+ ) -> "Mapping[str, Any]":
292
+ value_keys = _selected_value_keys(select)
293
+ if value_keys is not None:
294
+ kwargs["channels"] = value_keys
295
+ state = state_snapshot_to_thread_state(await Threads.State.get(conn, **kwargs))
296
+ return _project_thread_state(state, select, value_keys) if select else state
297
+
298
+
283
299
  @retry_db
284
300
  async def update_thread_state(
285
301
  request: ApiRequest,
@@ -407,7 +423,7 @@ def _validate_history_select(select: list[str] | None) -> list[str] | None:
407
423
 
408
424
 
409
425
  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."""
426
+ """State keys a state or history read returns, or None when it returns all."""
411
427
  if not select or "values" in select:
412
428
  return None
413
429
  return [f.removeprefix("values.") for f in select if f.startswith("values.")]
@@ -495,7 +511,9 @@ async def get_thread(
495
511
  include_ttl = "ttl" in include_fields
496
512
 
497
513
  async with connect() as conn:
498
- thread = await Threads.get(conn, thread_id, include_ttl=include_ttl)
514
+ thread = await Threads.get(
515
+ conn, thread_id, include_ttl=include_ttl, **_raw_values_kwargs()
516
+ )
499
517
 
500
518
  thread_data = await fetchone(thread)
501
519
  return ApiResponse(thread_data)
@@ -611,12 +629,15 @@ async def join_thread_stream(request: ApiRequest):
611
629
  if mode not in get_args(ThreadStreamMode):
612
630
  raise HTTPException(status_code=422, detail=f"Invalid stream mode: {mode}")
613
631
 
632
+ # Clients reconnect to Location as-is, so it keeps the request's query.
633
+ query = f"?{request.url.query}" if request.url.query else ""
614
634
  return EventSourceResponse(
615
635
  Threads.Stream.join(
616
636
  thread_id,
617
637
  last_event_id=last_event_id,
618
638
  stream_modes=stream_modes,
619
639
  ),
640
+ headers={"Location": f"/threads/{thread_id}/stream{query}"},
620
641
  )
621
642
 
622
643
 
@@ -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")
@@ -3,6 +3,7 @@ from collections.abc import Sequence
3
3
  from enum import StrEnum
4
4
  from os import environ, getenv
5
5
  from typing import TYPE_CHECKING, Annotated, Literal, TypeVar, cast
6
+ from urllib.parse import urlsplit
6
7
 
7
8
  import structlog
8
9
  from langgraph.version import __version__ as langgraph_version
@@ -205,7 +206,7 @@ LANGGRAPH_CLOUD_LICENSE_KEY = env("LANGGRAPH_CLOUD_LICENSE_KEY", cast=str, defau
205
206
 
206
207
  # When true, the Go core-server owns Postgres schema setup (DB migrations +
207
208
  # vector index)
208
- DB_MIGRATION_BY_CORE_API = env("DB_MIGRATION_BY_CORE_API", cast=bool, default=False)
209
+ DB_MIGRATION_BY_CORE_API = env("DB_MIGRATION_BY_CORE_API", cast=bool, default=True)
209
210
 
210
211
  # redis
211
212
  # Not in public docs: infrastructure, set by platform
@@ -653,6 +654,13 @@ else:
653
654
  ),
654
655
  )
655
656
 
657
+
658
+ def langsmith_api_url(path: str) -> str:
659
+ """Return the LangSmith API URL for a /v1 path, since self-hosted endpoints already end in /api/v1."""
660
+ base = (LANGSMITH_AUTH_ENDPOINT or "").rstrip("/")
661
+ return base + ("" if urlsplit(base).path.endswith("/api/v1") else "/v1") + path
662
+
663
+
656
664
  # Webhooks
657
665
 
658
666
 
@@ -691,6 +699,18 @@ LANGSMITH_API_KEY = env(
691
699
  LANGSMITH_CONTROL_PLANE_API_KEY = env(
692
700
  "LANGSMITH_CONTROL_PLANE_API_KEY", cast=str, default=LANGSMITH_API_KEY
693
701
  )
702
+ # IAM role assumed through the AWS SDK's web identity variables; the API key must be bound to an agent.
703
+ LANGSMITH_AWS_ROLE_ARN = env("LANGSMITH_AWS_ROLE_ARN", cast=str, default=None)
704
+ # Entra app or managed identity reached through azure-identity's workload identity variables; both must be set.
705
+ LANGSMITH_AZURE_CLIENT_ID = env("LANGSMITH_AZURE_CLIENT_ID", cast=str, default=None)
706
+ LANGSMITH_AZURE_TENANT_ID = env("LANGSMITH_AZURE_TENANT_ID", cast=str, default=None)
707
+ # Google workload identity provider (//iam.googleapis.com/... resource name), and an optional service account to impersonate.
708
+ LANGSMITH_GCP_WORKLOAD_IDENTITY_PROVIDER = env(
709
+ "LANGSMITH_GCP_WORKLOAD_IDENTITY_PROVIDER", cast=str, default=None
710
+ )
711
+ LANGSMITH_GCP_SERVICE_ACCOUNT = env(
712
+ "LANGSMITH_GCP_SERVICE_ACCOUNT", cast=str, default=None
713
+ )
694
714
 
695
715
 
696
716
  # if langsmith api key is set, enable tracing unless explicitly disabled
@@ -900,7 +920,12 @@ __all__ = [
900
920
  "LANGSMITH_API_KEY",
901
921
  "LANGSMITH_AUTH_ENDPOINT",
902
922
  "LANGSMITH_AUTH_VERIFY_TENANT_ID",
923
+ "LANGSMITH_AWS_ROLE_ARN",
924
+ "LANGSMITH_AZURE_CLIENT_ID",
925
+ "LANGSMITH_AZURE_TENANT_ID",
903
926
  "LANGSMITH_CONTROL_PLANE_API_KEY",
927
+ "LANGSMITH_GCP_SERVICE_ACCOUNT",
928
+ "LANGSMITH_GCP_WORKLOAD_IDENTITY_PROVIDER",
904
929
  "LANGSMITH_TENANT_ID",
905
930
  "LSD_DD_API_KEY",
906
931
  "LSD_DD_ENDPOINT",
@@ -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
@@ -1,5 +1,8 @@
1
+ from typing import Any
2
+
1
3
  import jsonschema_rs
2
4
  import structlog
5
+ from langgraph import errors as langgraph_errors
3
6
  from langgraph.errors import EmptyInputError, InvalidUpdateError
4
7
  from starlette.exceptions import HTTPException
5
8
  from starlette.requests import Request
@@ -9,6 +12,30 @@ from langgraph_api.js.errors import RemoteException
9
12
 
10
13
  logger = structlog.stdlib.get_logger(__name__)
11
14
 
15
+ UNKNOWN_INTERRUPT_ERROR = "UnknownInterruptError"
16
+
17
+
18
+ def unknown_interrupt_error(exc: BaseException) -> dict[str, Any] | None:
19
+ """The error payload when strict resume refused an answer, else None.
20
+
21
+ Its message and ids describe the answer the client sent, so they reach
22
+ the client in full. A JS graph's error arrives as a RemoteException, which
23
+ carries only the class name.
24
+ """
25
+ if isinstance(exc, RemoteException):
26
+ return exc.dict() if exc.error == UNKNOWN_INTERRUPT_ERROR else None
27
+ # Absent before langgraph 1.2.20, which has no strict resume to raise it.
28
+ error_class = getattr(langgraph_errors, UNKNOWN_INTERRUPT_ERROR, None)
29
+ if error_class is None or not isinstance(exc, error_class):
30
+ return None
31
+ return {
32
+ "error": UNKNOWN_INTERRUPT_ERROR,
33
+ "message": str(exc),
34
+ "reason": getattr(exc, "reason", None),
35
+ "interrupt_ids": list(getattr(exc, "interrupt_ids", ())),
36
+ "pending_ids": list(getattr(exc, "pending_ids", ())),
37
+ }
38
+
12
39
 
13
40
  def is_body_allowed_for_status_code(status_code: int | None) -> bool:
14
41
  if status_code is None:
@@ -93,3 +120,13 @@ class UserTimeout(Exception):
93
120
  def __init__(self, timeout_error: TimeoutError):
94
121
  super().__init__(timeout_error)
95
122
  self.timeout_error = timeout_error
123
+
124
+
125
+ class StreamCutError(Exception):
126
+ """The event stream behind a response ended before its run did.
127
+
128
+ The SSE response aborts instead of sending an ``error`` event, so the SDKs
129
+ reconnect run and thread streams with ``Last-Event-ID``. Behind a custom
130
+ ``BaseHTTPMiddleware``, which would end an aborted response cleanly, the
131
+ response sends an ``error`` event instead.
132
+ """
@@ -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,
@@ -130,16 +130,16 @@ DEFAULT_MULTITASK_STRATEGY = "enqueue"
130
130
 
131
131
 
132
132
  def _multitask_strategy_from_run_start(params: dict[str, Any]) -> str:
133
- """Resolve the per-run ``multitaskStrategy`` from ``run.start`` params.
133
+ """Resolve the per-run multitask strategy from ``run.start`` params.
134
134
 
135
- The SDK forwards the caller's ``multitaskStrategy`` on every
136
- ``run.start`` (one of ``reject`` | ``rollback`` | ``interrupt`` |
137
- ``enqueue``). Honor it when it is one of the recognized strategies,
138
- otherwise fall back to ``DEFAULT_MULTITASK_STRATEGY`` (the legacy
139
- stream-endpoint default). This mirrors the JS reference server's
135
+ ``multitask_strategy`` is the protocol's spelling; older JS SDKs send only
136
+ ``multitaskStrategy``, so that name still works. Honor one of the
137
+ recognized strategies (``reject`` | ``rollback`` | ``interrupt`` |
138
+ ``enqueue``), otherwise fall back to ``DEFAULT_MULTITASK_STRATEGY`` (the
139
+ legacy stream-endpoint default). This mirrors the JS reference server's
140
140
  lenient normalization so both behave identically.
141
141
  """
142
- strategy = params.get("multitaskStrategy")
142
+ strategy = params.get("multitask_strategy", params.get("multitaskStrategy"))
143
143
  if isinstance(strategy, str) and strategy in VALID_MULTITASK_STRATEGIES:
144
144
  return strategy
145
145
  return DEFAULT_MULTITASK_STRATEGY
@@ -152,25 +152,12 @@ EventSink = Callable[[dict[str, Any]], Awaitable[None] | None]
152
152
  _IN_FLIGHT_THREAD_STATUS = "busy"
153
153
  _INTERRUPT_SETTLE_TIMEOUT_SECONDS = 5.0
154
154
  _INTERRUPT_SETTLE_POLL_INTERVAL_SECONDS = 0.05
155
- # langgraph resumes interrupts by id only when every key of the resume map has
156
- # this shape; any other key turns the whole map into one value for whichever
157
- # interrupt is pending.
158
- _INTERRUPT_ID_RE = re.compile(r"[0-9a-f]{32}")
159
155
 
160
156
 
161
157
  class _AmbiguousResumeError(Exception):
162
158
  """``run.start`` input would resume several pending interrupts at once."""
163
159
 
164
160
 
165
- def _keyed_by_interrupt_id(value: Any) -> bool:
166
- """Whether langgraph resumes ``value`` per interrupt rather than as one answer."""
167
- return (
168
- _is_record(value)
169
- and bool(value)
170
- and all(_INTERRUPT_ID_RE.fullmatch(key) for key in value)
171
- )
172
-
173
-
174
161
  # Protocol v2 commands this server implements. Anything outside this
175
162
  # set returns ``unknown_command`` up front from ``handle_command`` so
176
163
  # pre-session dispatch does not mislabel typos (or removed methods
@@ -709,7 +696,7 @@ class ThreadRunManager:
709
696
  # open for any id shaped like an interrupt id: the resume below is
710
697
  # authoritative, so neither must masquerade as a missing interrupt.
711
698
  if thread_state_ids is None:
712
- rejected = not _INTERRUPT_ID_RE.fullmatch(interrupt_id)
699
+ rejected = not INTERRUPT_ID_RE.fullmatch(interrupt_id)
713
700
  else:
714
701
  rejected = interrupt_id not in thread_state_ids
715
702
  if rejected:
@@ -753,6 +740,7 @@ class ThreadRunManager:
753
740
  "goto": params.get("goto"),
754
741
  "config": params.get("config"),
755
742
  "metadata": params.get("metadata"),
743
+ "strict_resume": params.get("strict_resume"),
756
744
  },
757
745
  )
758
746
  except ProtocolV2UnsupportedError as exc:
@@ -816,7 +804,7 @@ class ThreadRunManager:
816
804
  has_interrupts = False
817
805
  if params.get("input") is not None and not force_resume:
818
806
  has_interrupts = await self._has_pending_interrupts()
819
- if has_interrupts and not _keyed_by_interrupt_id(params["input"]):
807
+ if has_interrupts and not keyed_by_interrupt_id(params["input"]):
820
808
  # One answer can't say which of several pending interrupts it is
821
809
  # for: langgraph fails the run, or picks one when they share a
822
810
  # subgraph task. Only a paused thread's row is current, so a run in
@@ -905,6 +893,7 @@ class ThreadRunManager:
905
893
  "multitask_strategy": _multitask_strategy_from_run_start(params),
906
894
  "langsmith_tracer": _langsmith_tracer_from_run_start(params),
907
895
  "durability": None,
896
+ "strict_resume": params.get("strict_resume") is True,
908
897
  }
909
898
 
910
899
  run_id = make_uuid7()
@@ -502,6 +502,7 @@ class EventStreamingSession:
502
502
  return
503
503
  if event_name == "error":
504
504
  self._terminal_lifecycle_emitted = True
505
+ details: dict[str, Any] | None = None
505
506
  try:
506
507
  error_data = orjson.loads(message_bytes)
507
508
  if _is_record(error_data) and error_data.get("error") == "UserRollback":
@@ -519,10 +520,23 @@ class EventStreamingSession:
519
520
  if _is_record(error_data)
520
521
  else str(error_data)
521
522
  )
523
+ if (
524
+ _is_record(error_data)
525
+ and error_data.get("error") == "UnknownInterruptError"
526
+ ):
527
+ details = {
528
+ key: error_data[key]
529
+ for key in ("reason", "interrupt_ids", "pending_ids")
530
+ if key in error_data
531
+ }
522
532
  except Exception:
523
533
  error_msg = message_bytes.decode("utf-8", errors="replace")
524
534
  await self._emit_namespace_lifecycle(
525
- [], "failed", graph_name=self._root_graph_name, error=error_msg
535
+ [],
536
+ "failed",
537
+ graph_name=self._root_graph_name,
538
+ error=error_msg,
539
+ details=details,
526
540
  )
527
541
  return
528
542
 
@@ -567,6 +581,10 @@ class EventStreamingSession:
567
581
  scope cleanly wraps every push triggered by this source event.
568
582
  """
569
583
 
584
+ if method == "interrupts":
585
+ await self._emit_input_answered(data)
586
+ return
587
+
570
588
  # Core ``langgraph.stream`` already emits canonical ProtocolEvent
571
589
  # objects. Re-envelope them with this session's seq/event_id so
572
590
  # transport replay remains API-owned.
@@ -1118,7 +1136,7 @@ class EventStreamingSession:
1118
1136
  self, subscription: Subscription, event: dict[str, Any]
1119
1137
  ) -> bool:
1120
1138
  raw_method = event.get("method", "")
1121
- channel = "input" if raw_method == "input.requested" else raw_method
1139
+ channel = "input" if raw_method.startswith("input.") else raw_method
1122
1140
  if not _is_supported_channel(channel):
1123
1141
  return False
1124
1142
  if channel == "custom":
@@ -1479,6 +1497,7 @@ class EventStreamingSession:
1479
1497
  graph_name: str | None = None,
1480
1498
  error: str | None = None,
1481
1499
  cause: dict[str, Any] | None = None,
1500
+ details: dict[str, Any] | None = None,
1482
1501
  ) -> None:
1483
1502
  key = to_namespace_key(namespace)
1484
1503
  if namespace and key not in self._namespaces:
@@ -1517,6 +1536,8 @@ class EventStreamingSession:
1517
1536
  lifecycle_data["error"] = error
1518
1537
  if cause is not None:
1519
1538
  lifecycle_data["cause"] = cause
1539
+ if details:
1540
+ lifecycle_data.update(details)
1520
1541
  await self._push_event(
1521
1542
  self._create_event(
1522
1543
  "lifecycle",
@@ -1576,6 +1597,16 @@ class EventStreamingSession:
1576
1597
  """
1577
1598
  return self._pending_interrupts.get(interrupt_id)
1578
1599
 
1600
+ async def _emit_input_answered(self, data: Any) -> None:
1601
+ answered = data.get("answered") if _is_record(data) else None
1602
+ if not isinstance(answered, list) or not answered:
1603
+ return
1604
+ for interrupt_id in answered:
1605
+ self.clear_pending_interrupt(interrupt_id)
1606
+ await self._push_event(
1607
+ self._create_event("input.answered", [], {"interrupt_ids": answered})
1608
+ )
1609
+
1579
1610
  def clear_pending_interrupt(self, interrupt_id: str) -> None:
1580
1611
  """Remove *interrupt_id* from the pending set after a successful resume."""
1581
1612
  self._pending_interrupts.pop(interrupt_id, None)
@@ -15,9 +15,10 @@ os.environ.setdefault("DISABLE_TRUSTSTORE", "true")
15
15
  import grpc.aio as grpc_aio
16
16
  from langgraph_grpc_common.proto import orchestrator_pb2, orchestrator_pb2_grpc
17
17
 
18
+ from langgraph_api import config, web_identity
18
19
  from langgraph_api.asyncio import ValueEvent
19
20
  from langgraph_api.encryption.context import set_encryption_context
20
- from langgraph_api.errors import UserInterrupt, UserRollback
21
+ from langgraph_api.errors import UserInterrupt, UserRollback, unknown_interrupt_error
21
22
  from langgraph_api.graph import collect_graphs_from_env
22
23
  from langgraph_api.grpc.ops import encryption_context_from_proto
23
24
  from langgraph_api.grpc.ops.runs import proto_to_run
@@ -29,6 +30,7 @@ from langgraph_api.worker_runtime import (
29
30
  cleanup_custom_checkpointer_for_run,
30
31
  fetch_checkpoint_after_failure,
31
32
  fetch_missing_checkpoint,
33
+ resumes_strictly,
32
34
  stream_run,
33
35
  )
34
36
 
@@ -76,6 +78,7 @@ def _done_msg(
76
78
  message: str = "",
77
79
  checkpoint: dict[str, Any] | None = None,
78
80
  exception: dict[str, Any] | None = None,
81
+ refused_resume: bool = False,
79
82
  ) -> orchestrator_pb2.ExecutorMessage:
80
83
  return orchestrator_pb2.ExecutorMessage(
81
84
  done=orchestrator_pb2.Done(
@@ -83,6 +86,7 @@ def _done_msg(
83
86
  message=message,
84
87
  checkpoint_json=json_dumpb(checkpoint) if checkpoint is not None else b"",
85
88
  exception_json=json_dumpb(exception) if exception is not None else b"",
89
+ refused_resume=refused_resume,
86
90
  )
87
91
  )
88
92
 
@@ -122,8 +126,12 @@ async def _run_graph(
122
126
  set_encryption_context(encryption_context or {})
123
127
  tracker = RunCheckpointTracker()
124
128
  temporary = run["kwargs"].get("temporary", False)
129
+ strict = False
125
130
  try:
126
- async for mode, payload in stream_run(run, attempt, cancel, tracker=tracker):
131
+ strict = await resumes_strictly(run, attempt)
132
+ async for mode, payload in stream_run(
133
+ run, attempt, cancel, tracker=tracker, strict_resume=strict
134
+ ):
127
135
  packet = await asyncio.to_thread(json_dumpb, payload)
128
136
  yield orchestrator_pb2.ExecutorMessage(
129
137
  chunk=orchestrator_pb2.Chunk(mode=mode, packet=packet)
@@ -159,10 +167,14 @@ async def _run_graph(
159
167
  exception=_exception_dict(exc),
160
168
  )
161
169
  return
170
+ refusal = unknown_interrupt_error(exc) if strict else None
162
171
  yield _done_msg(
163
172
  status=STATUS_ERROR,
164
173
  message=str(exc),
165
- exception=_exception_dict(exc),
174
+ # The core publishes this as the run's error event, so a refusal
175
+ # carries its reason and ids.
176
+ exception=_exception_dict(exc) if refusal is None else refusal,
177
+ refused_resume=refusal is not None,
166
178
  checkpoint=await _failure_checkpoint(
167
179
  run, failed_attempts, tracker, temporary
168
180
  ),
@@ -281,6 +293,9 @@ async def _bootstrap() -> None:
281
293
  # get_client() with no URL imports langgraph_api.server itself.
282
294
  set_event_loop(asyncio.get_running_loop())
283
295
 
296
+ # Executors skip API lifespan, so they need their own token files before graphs use a cloud SDK.
297
+ await web_identity.start()
298
+
284
299
  from langgraph_runtime import database # noqa: PLC0415
285
300
 
286
301
  await database.start_pool()
@@ -319,7 +334,6 @@ def _configure_logging() -> None:
319
334
 
320
335
  async def amain() -> None:
321
336
  _configure_logging()
322
- from langgraph_api import config # noqa: PLC0415
323
337
 
324
338
  # Role flag before bootstrap so graph registration / other shared code
325
339
  # can skip API-only work (mirrors queue_entrypoint + IS_QUEUE_ENTRYPOINT).
@@ -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)