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
langgraph_api/__init__.py CHANGED
@@ -1 +1 @@
1
- __version__ = "0.19.0.dev3"
1
+ __version__ = "0.19.0.dev5"
langgraph_api/api/a2a.py CHANGED
@@ -18,7 +18,7 @@ import os
18
18
  import uuid
19
19
  from dataclasses import dataclass, replace
20
20
  from datetime import UTC, datetime
21
- from typing import Any, Literal, NotRequired, Self, cast
21
+ from typing import TYPE_CHECKING, Any, Literal, NotRequired, Self, cast
22
22
 
23
23
  import orjson
24
24
  import structlog
@@ -42,6 +42,7 @@ from langgraph_api.config import (
42
42
  A2A_A2UI_TOOL_CALL_RESULTS,
43
43
  A2A_ALLOWED_TOOL_CALL_RESULTS,
44
44
  )
45
+ from langgraph_api.errors import UserInterrupt, UserRollback
45
46
  from langgraph_api.metadata import USER_API_URL
46
47
  from langgraph_api.route import ApiRequest, ApiRoute
47
48
  from langgraph_api.schema import RunCommand
@@ -50,6 +51,9 @@ from langgraph_api.sse import EventSourceResponse
50
51
  from langgraph_api.utils.cache import LRUCache
51
52
  from langgraph_api.utils.uuids import uuid7
52
53
 
54
+ if TYPE_CHECKING:
55
+ from langgraph_sdk.schema import RunCreateMetadata
56
+
53
57
  logger = structlog.stdlib.get_logger(__name__)
54
58
 
55
59
  # Cache for assistant schemas (assistant_id -> schemas dict)
@@ -553,6 +557,13 @@ def _lg_status_to_a2a_state(lg_status: str) -> str:
553
557
  return mapping.get(lg_status, "TASK_STATE_SUBMITTED")
554
558
 
555
559
 
560
+ _CANCEL_ERROR_NAMES = frozenset({UserInterrupt.__name__, UserRollback.__name__})
561
+
562
+
563
+ def _is_cancel_error(error: object) -> bool:
564
+ return isinstance(error, dict) and error.get("error") in _CANCEL_ERROR_NAMES
565
+
566
+
556
567
  def _task_state_for_run(
557
568
  run: dict[str, Any], thread: dict[str, Any] | None = None
558
569
  ) -> str:
@@ -1716,7 +1727,12 @@ async def _create_task_response(
1716
1727
  if history_length != 0:
1717
1728
  base_task["history"] = thread_history
1718
1729
 
1719
- if "__error__" in result:
1730
+ if _is_cancel_error(result.get("__error__")):
1731
+ base_task["status"] = {
1732
+ "state": "TASK_STATE_CANCELED",
1733
+ "timestamp": datetime.now(UTC).isoformat(),
1734
+ }
1735
+ elif "__error__" in result:
1720
1736
  base_task["status"] = {
1721
1737
  "state": "TASK_STATE_FAILED",
1722
1738
  "message": {
@@ -2296,32 +2312,37 @@ async def handle_message_send(
2296
2312
  task_id=existing_task_id,
2297
2313
  )
2298
2314
 
2299
- try:
2300
- run = await client.runs.create(
2301
- thread_id=context_id,
2302
- assistant_id=assistant_id,
2303
- input=input_content,
2304
- command=command,
2305
- context=run_context,
2306
- metadata=_a2a_run_metadata(
2307
- assistant,
2308
- a2ui,
2309
- task_id=task_id,
2310
- task_start_id=task_start_id,
2311
- ),
2312
- if_not_exists="create",
2313
- headers=request.headers,
2314
- )
2315
- except Exception as e:
2316
- error_response = _map_runs_create_error_to_rpc(e, assistant_id, context_id)
2317
- if error_response.get("error", {}).get("code") == ERROR_CODE_INTERNAL_ERROR:
2318
- raise
2319
- return error_response
2320
-
2321
- context_id = str(run["thread_id"])
2322
- if task_id is None:
2323
- task_id = _make_task_id(context_id, str(run["run_id"]))
2315
+ run_metadata = _a2a_run_metadata(
2316
+ assistant,
2317
+ a2ui,
2318
+ task_id=task_id,
2319
+ task_start_id=task_start_id,
2320
+ )
2324
2321
  if return_immediately:
2322
+ try:
2323
+ run = await client.runs.create(
2324
+ thread_id=context_id,
2325
+ assistant_id=assistant_id,
2326
+ input=input_content,
2327
+ command=command,
2328
+ context=run_context,
2329
+ metadata=run_metadata,
2330
+ if_not_exists="create",
2331
+ headers=request.headers,
2332
+ )
2333
+ except Exception as e:
2334
+ error_response = _map_runs_create_error_to_rpc(
2335
+ e, assistant_id, context_id
2336
+ )
2337
+ if (
2338
+ error_response.get("error", {}).get("code")
2339
+ == ERROR_CODE_INTERNAL_ERROR
2340
+ ):
2341
+ raise
2342
+ return error_response
2343
+ context_id = str(run["thread_id"])
2344
+ if task_id is None:
2345
+ task_id = _make_task_id(context_id, str(run["run_id"]))
2325
2346
  immediate_task: dict[str, Any] = {
2326
2347
  "kind": "task",
2327
2348
  "id": task_id,
@@ -2350,6 +2371,35 @@ async def handle_message_send(
2350
2371
  )
2351
2372
  return {"result": {"task": immediate_task}}
2352
2373
 
2374
+ # runs.wait subscribes to the run before creating it, so a cancel that lands
2375
+ # right after the run starts still reaches this call; a create followed by a
2376
+ # join starts listening too late and misses it.
2377
+ created: list[RunCreateMetadata] = []
2378
+ try:
2379
+ result = cast(
2380
+ "dict[str, Any]",
2381
+ await client.runs.wait(
2382
+ thread_id=context_id,
2383
+ assistant_id=assistant_id,
2384
+ input=input_content,
2385
+ command=command,
2386
+ context=run_context,
2387
+ metadata=run_metadata,
2388
+ if_not_exists="create",
2389
+ raise_error=False,
2390
+ on_run_created=created.append,
2391
+ headers=request.headers,
2392
+ ),
2393
+ )
2394
+ except Exception as e:
2395
+ error_response = _map_runs_create_error_to_rpc(e, assistant_id, context_id)
2396
+ if error_response.get("error", {}).get("code") == ERROR_CODE_INTERNAL_ERROR:
2397
+ raise
2398
+ return error_response
2399
+ run_id = str(created[0]["run_id"])
2400
+ if task_id is None:
2401
+ task_id = _make_task_id(context_id, run_id)
2402
+
2353
2403
  if existing_task_id is None:
2354
2404
  try:
2355
2405
  runs = await _list_context_runs(
@@ -2367,11 +2417,6 @@ async def handle_message_send(
2367
2417
  if task_start_id:
2368
2418
  task_ids_by_start_id.setdefault(task_start_id, task_id)
2369
2419
 
2370
- result = await client.runs.join(
2371
- thread_id=run["thread_id"],
2372
- run_id=run["run_id"],
2373
- headers=request.headers,
2374
- )
2375
2420
  data_only_input = command is None and "messages" not in input_content
2376
2421
  turn = None
2377
2422
  if data_only_input or (
@@ -2379,9 +2424,7 @@ async def handle_message_send(
2379
2424
  and history_length != 0
2380
2425
  and "messages" not in input_content
2381
2426
  ):
2382
- run_messages = await _load_run_messages(
2383
- context_id, str(run["run_id"]), request.headers
2384
- )
2427
+ run_messages = await _load_run_messages(context_id, run_id, request.headers)
2385
2428
  result = {**result, "messages": run_messages.stamped(task_id)}
2386
2429
  if data_only_input:
2387
2430
  turn = run_messages.added
@@ -3913,7 +3956,7 @@ async def handle_message_stream(
3913
3956
  "result": update,
3914
3957
  },
3915
3958
  )
3916
- else:
3959
+ elif chunk.event != "end":
3917
3960
  await logger.awarning(
3918
3961
  "Ignoring unknown event type: " + chunk.event
3919
3962
  )
@@ -3923,9 +3966,14 @@ async def handle_message_stream(
3923
3966
  err = {"error": type(e).__name__, "message": str(e)}
3924
3967
  continue
3925
3968
 
3926
- # If we exit unexpectedly, send a final status based on error presence
3969
+ # The stream ended: report the final state from the last error or result.
3970
+ canceled = _is_cancel_error(err)
3927
3971
  final_message = None
3928
- if isinstance(err, dict) and ("__error__" in err or "error" in err):
3972
+ if (
3973
+ not canceled
3974
+ and isinstance(err, dict)
3975
+ and ("__error__" in err or "error" in err)
3976
+ ):
3929
3977
  msg = (
3930
3978
  err.get("__error__", {}).get("error")
3931
3979
  if isinstance(err.get("__error__"), dict)
@@ -3940,8 +3988,10 @@ async def handle_message_stream(
3940
3988
  "taskId": task_id,
3941
3989
  "contextId": context_id,
3942
3990
  }
3943
- # Determine final state: failed > input-required > completed
3944
- if err:
3991
+ # Determine final state: canceled > failed > input-required > completed
3992
+ if canceled:
3993
+ fallback_state = "TASK_STATE_CANCELED"
3994
+ elif err:
3945
3995
  fallback_state = "TASK_STATE_FAILED"
3946
3996
  elif isinstance(result, dict) and "__interrupt__" in result:
3947
3997
  fallback_state = "TASK_STATE_INPUT_REQUIRED"
langgraph_api/api/meta.py CHANGED
@@ -9,6 +9,7 @@ from langgraph_api.feature_flags import IS_POSTGRES_OR_GRPC_BACKEND
9
9
  from langgraph_api.http_metrics import HTTP_METRICS_COLLECTOR
10
10
  from langgraph_api.route import ApiRequest
11
11
  from langgraph_api.schema import PoolStats, PostgresPoolStats, RedisPoolStats
12
+ from langgraph_api.tracing_session import ADDRESS_SUPPORT
12
13
  from langgraph_runtime.database import connect, pool_stats
13
14
  from langgraph_runtime.metrics import get_metrics
14
15
 
@@ -38,13 +39,18 @@ def _merge_pool_stats(local: PoolStats, remote: PoolStats) -> PoolStats:
38
39
  if "redis" in local or "redis" in remote:
39
40
  lr = local.get("redis") or {}
40
41
  rr = remote.get("redis") or {}
41
- merged["redis"] = RedisPoolStats(
42
+ redis_stats = RedisPoolStats(
42
43
  idle_connections=lr.get("idle_connections", 0)
43
44
  + rr.get("idle_connections", 0),
44
45
  in_use_connections=lr.get("in_use_connections", 0)
45
46
  + rr.get("in_use_connections", 0),
46
- max_connections=lr.get("max_connections", 0) + rr.get("max_connections", 0),
47
47
  )
48
+ # Cluster Go path omits max; only sum when at least one side reported it.
49
+ if "max_connections" in lr or "max_connections" in rr:
50
+ redis_stats["max_connections"] = lr.get("max_connections", 0) + rr.get(
51
+ "max_connections", 0
52
+ )
53
+ merged["redis"] = redis_stats
48
54
  return merged
49
55
 
50
56
 
@@ -81,7 +87,10 @@ async def meta_info(request: ApiRequest):
81
87
  and bool(config.TRACING),
82
88
  "langsmith_tracing_replicas": True,
83
89
  "langsmith_tracing_session_on_runs": True,
90
+ "langsmith_tracing_address": ADDRESS_SUPPORT,
84
91
  "mcp": MCP_SERVED,
92
+ "stream_namespaces": IS_POSTGRES_OR_GRPC_BACKEND,
93
+ "stream_lifecycle": True,
85
94
  },
86
95
  "host": {
87
96
  "kind": metadata.HOST,
langgraph_api/api/runs.py CHANGED
@@ -1,14 +1,17 @@
1
1
  import asyncio
2
2
  from collections.abc import AsyncIterator, Awaitable, Callable
3
3
  from typing import Any, Literal, cast
4
+ from urllib.parse import urlencode
4
5
  from uuid import UUID
5
6
 
6
7
  import orjson
7
8
  import structlog
9
+ from starlette.datastructures import QueryParams
8
10
  from starlette.exceptions import HTTPException
9
11
  from starlette.responses import Response, StreamingResponse
10
12
 
11
13
  from langgraph_api.asyncio import ValueEvent
14
+ from langgraph_api.errors import UserInterrupt
12
15
  from langgraph_api.feature_flags import IS_POSTGRES_OR_GRPC_BACKEND
13
16
  from langgraph_api.graph import _validate_assistant_id
14
17
  from langgraph_api.models.run import create_valid_run
@@ -16,6 +19,7 @@ from langgraph_api.route import ApiRequest, ApiResponse, ApiRoute
16
19
  from langgraph_api.schema import (
17
20
  CRON_FIELDS,
18
21
  RUN_FIELDS,
22
+ Run,
19
23
  )
20
24
  from langgraph_api.serde import json_dumpb, json_loads
21
25
  from langgraph_api.sse import EventSourceResponse
@@ -75,6 +79,53 @@ def parse_stream_mode_param(stream_mode_param: str | None) -> list[str]:
75
79
  return [stream_mode_param]
76
80
 
77
81
 
82
+ # 32 `tools:<uuid>` values keep the query near 1.8 KB, under the 8 KB many
83
+ # proxies allow, and the Go core's per-event check, which tries each value,
84
+ # under 100 ns.
85
+ MAX_STREAM_NAMESPACES = 32
86
+
87
+
88
+ def parse_stream_namespaces(params: QueryParams) -> list[str]:
89
+ """The ``namespace`` params: the conversations a run stream keeps.
90
+
91
+ Each is a "|"-joined namespace ("" is the root graph), kept without the
92
+ subagents it starts.
93
+ """
94
+ namespaces = list(dict.fromkeys(params.getlist("namespace")))
95
+ if len(namespaces) > MAX_STREAM_NAMESPACES:
96
+ raise HTTPException(
97
+ status_code=422,
98
+ detail=f"At most {MAX_STREAM_NAMESPACES} namespace values are allowed",
99
+ )
100
+ if any(ns and "" in ns.split("|") for ns in namespaces):
101
+ raise HTTPException(
102
+ status_code=422, detail="Invalid namespace: it has an empty segment"
103
+ )
104
+ return namespaces
105
+
106
+
107
+ def stream_namespace_query(params: QueryParams) -> str:
108
+ """The ``namespace`` params as the query of a run stream's reconnect ``Location``.
109
+
110
+ A run-creating request ignores its other query params, so they must not
111
+ reach the join a reconnect makes.
112
+ """
113
+ query = urlencode([("namespace", ns) for ns in params.getlist("namespace")])
114
+ return f"?{query}" if query else ""
115
+
116
+
117
+ def stream_namespace_kwargs(params: QueryParams) -> dict[str, list[str]]:
118
+ """``Runs.Stream.join`` kwargs for the request's ``namespace`` params.
119
+
120
+ Every runtime rejects a bad value, but only the Go core filters by
121
+ namespace, so the Python in-memory runtime gets none and streams everything.
122
+ """
123
+ namespaces = parse_stream_namespaces(params)
124
+ if not namespaces or not IS_POSTGRES_OR_GRPC_BACKEND:
125
+ return {}
126
+ return {"namespaces": namespaces}
127
+
128
+
78
129
  # Type alias for stream handlers (GrpcStreamHandler or ContextQueue).
79
130
  # Runs is selected at runtime, and the implementations have different
80
131
  # type signatures, so we use Any for compatibility.
@@ -203,6 +254,102 @@ class _RunResult:
203
254
  return self._interrupt_chunks[-1]
204
255
 
205
256
 
257
+ async def _read_ended_run(run_id: UUID, thread_id: UUID) -> Run | None:
258
+ async with connect() as conn:
259
+ try:
260
+ return await fetchone(
261
+ await Runs.get(
262
+ conn,
263
+ run_id,
264
+ thread_id=thread_id,
265
+ read_mask_paths=["status", "cancel_reason"],
266
+ )
267
+ )
268
+ except HTTPException as e:
269
+ # A rolled-back or deleted run has no ending left to report.
270
+ if e.status_code == 404:
271
+ return None
272
+ raise
273
+
274
+
275
+ async def _ended_run_error(run: Run) -> bytes | None:
276
+ # Only a cancel leaves a run interrupted: a graph interrupt ends the
277
+ # run as success and interrupts its thread instead.
278
+ if run["status"] == "interrupted":
279
+ reason = run.get("cancel_reason")
280
+ return json_dumpb(UserInterrupt(reason) if reason else UserInterrupt())
281
+ if run["status"] not in ("error", "timeout"):
282
+ return None
283
+ async with connect() as conn:
284
+ try:
285
+ # The run row has no error field, and the thread keeps only its latest
286
+ # failure: it's this run's only while no later run exists.
287
+ latest = await fetchone(
288
+ await Runs.search(conn, run["thread_id"], limit=1, select=["run_id"])
289
+ )
290
+ if latest["run_id"] != run["run_id"]:
291
+ return None
292
+ thread = await fetchone(
293
+ await Threads.get(
294
+ conn, run["thread_id"], read_mask_paths=["status", "error"]
295
+ )
296
+ )
297
+ except HTTPException as e:
298
+ # A deleted run has no ending left to report, and a user who may not
299
+ # list the thread's runs can't be told which failure is this run's.
300
+ if e.status_code in (403, 404):
301
+ return None
302
+ raise
303
+ if thread["status"] != "error":
304
+ return None
305
+ return json_dumpb(json_loads(thread["error"]))
306
+
307
+
308
+ async def _join_with_outcome(
309
+ run_id: UUID, *, thread_id: UUID, end: bool = False, **join_kwargs: Any
310
+ ) -> AsyncIterator[tuple[bytes, bytes, bytes | None]]:
311
+ """`Runs.Stream.join`, ending with how the run ended when the join didn't say.
312
+
313
+ A join gets no events from a run cancelled before it started, or from a run
314
+ that ended before the join: without Last-Event-ID it replays nothing, and a
315
+ replay has nothing left once the run's events expire. Such a join ends with
316
+ the run's error. With `end`, a join also ends with an `end` event carrying
317
+ the run's final status whenever that status can be read.
318
+ """
319
+ joined_any = ended = False
320
+ async for event in Runs.Stream.join(run_id, thread_id=thread_id, **join_kwargs):
321
+ if ended:
322
+ # A resume can replay `end` after the run's row is gone, and the
323
+ # core then reports the missing run. Keep reading instead of
324
+ # closing: closing early would cancel an on_disconnect=cancel run
325
+ # whose row still says running.
326
+ continue
327
+ ended = event[0] == b"end"
328
+ # `metadata` only starts an attempt, so a join that saw just that still
329
+ # needs the run's ending.
330
+ joined_any = joined_any or event[0] != b"metadata"
331
+ yield event
332
+ if ended or (joined_any and not end):
333
+ return
334
+ try:
335
+ run = await _read_ended_run(run_id, thread_id)
336
+ error = None if joined_any or run is None else await _ended_run_error(run)
337
+ except Exception:
338
+ if not end:
339
+ raise
340
+ # Raising would end the stream with an error event, which reads as a
341
+ # failed run; without an ending, the client asks the run instead.
342
+ await logger.awarning(
343
+ "Could not read how a run ended", run_id=str(run_id), exc_info=True
344
+ )
345
+ return
346
+ if error:
347
+ yield b"error", error, None
348
+ if end and run is not None and run["status"] not in ("pending", "running"):
349
+ end_data = {"run_id": run["run_id"], "status": run["status"]}
350
+ yield b"end", json_dumpb(end_data), None
351
+
352
+
206
353
  def _run_result_body(
207
354
  *,
208
355
  run_id: UUID,
@@ -218,7 +365,7 @@ def _run_result_body(
218
365
  async def consume() -> None:
219
366
  result = _RunResult(fallback)
220
367
  try:
221
- async for mode, chunk, _ in Runs.Stream.join(
368
+ async for mode, chunk, _ in _join_with_outcome(
222
369
  run_id,
223
370
  stream_channel=sub,
224
371
  cancel_on_disconnect=cancel_on_disconnect,
@@ -327,6 +474,7 @@ async def stream_run(
327
474
  """Create a run."""
328
475
  thread_id = request.path_params["thread_id"]
329
476
  payload = await request.json(RunCreateStreamingStateful)
477
+ namespace_kwargs = stream_namespace_kwargs(request.query_params)
330
478
  on_disconnect = payload.get("on_disconnect", "continue")
331
479
  run_id = uuid7()
332
480
 
@@ -350,11 +498,13 @@ async def stream_run(
350
498
 
351
499
  async def body():
352
500
  try:
353
- async for event, message, stream_id in Runs.Stream.join(
501
+ async for event, message, stream_id in _join_with_outcome(
354
502
  run["run_id"],
355
503
  thread_id=thread_id,
504
+ end=True,
356
505
  cancel_on_disconnect=on_disconnect == "cancel",
357
506
  stream_channel=cast("_StreamHandler", sub),
507
+ **namespace_kwargs,
358
508
  ):
359
509
  yield event, message, stream_id
360
510
  finally:
@@ -364,7 +514,8 @@ async def stream_run(
364
514
  return EventSourceResponse(
365
515
  body(),
366
516
  headers={
367
- "Location": f"/threads/{thread_id}/runs/{run['run_id']}/stream",
517
+ "Location": f"/threads/{thread_id}/runs/{run['run_id']}/stream"
518
+ + stream_namespace_query(request.query_params),
368
519
  "Content-Location": f"/threads/{thread_id}/runs/{run['run_id']}",
369
520
  },
370
521
  on_close=lambda: sub.__aexit__(None, None, None),
@@ -376,6 +527,7 @@ async def stream_run_stateless(
376
527
  ):
377
528
  """Create a stateless run."""
378
529
  payload = await request.json(RunCreateStreamingStateless)
530
+ namespace_kwargs = stream_namespace_kwargs(request.query_params)
379
531
  payload["if_not_exists"] = "create"
380
532
  on_disconnect = payload.get("on_disconnect", "continue")
381
533
  run_id = uuid7()
@@ -402,12 +554,14 @@ async def stream_run_stateless(
402
554
 
403
555
  async def body():
404
556
  try:
405
- async for event, message, stream_id in Runs.Stream.join(
557
+ async for event, message, stream_id in _join_with_outcome(
406
558
  run["run_id"],
407
559
  thread_id=run["thread_id"],
560
+ end=True,
408
561
  ignore_404=True,
409
562
  cancel_on_disconnect=on_disconnect == "cancel",
410
563
  stream_channel=cast("_StreamHandler", sub),
564
+ **namespace_kwargs,
411
565
  ):
412
566
  yield event, message, stream_id
413
567
  finally:
@@ -417,7 +571,8 @@ async def stream_run_stateless(
417
571
  return EventSourceResponse(
418
572
  body(),
419
573
  headers={
420
- "Location": f"/threads/{run['thread_id']}/runs/{run['run_id']}/stream",
574
+ "Location": f"/threads/{run['thread_id']}/runs/{run['run_id']}/stream"
575
+ + stream_namespace_query(request.query_params),
421
576
  "Content-Location": f"/threads/{run['thread_id']}/runs/{run['run_id']}",
422
577
  },
423
578
  on_close=lambda: sub.__aexit__(None, None, None),
@@ -630,18 +785,26 @@ async def join_run_stream(request: ApiRequest):
630
785
  for mode in parse_stream_mode_param(value)
631
786
  ]
632
787
 
788
+ namespace_kwargs = stream_namespace_kwargs(request.query_params)
633
789
  last_event_id = request.headers.get("last-event-id") or None
790
+ # A resume replays what the client missed from the stream's cache, which
791
+ # outlives a run deleted as it ends (a stateless run), so it skips this
792
+ # check; the join still applies the auth filters before it replays.
793
+ if last_event_id is None:
794
+ await Runs.Stream.check_run_stream_auth(run_id, thread_id)
795
+ sub = await Runs.Stream.subscribe(run_id, thread_id)
634
796
 
635
797
  async def body():
636
- sub = await Runs.Stream.subscribe(run_id, thread_id)
637
798
  try:
638
- async for event, message, stream_id in Runs.Stream.join(
799
+ async for event, message, stream_id in _join_with_outcome(
639
800
  run_id,
640
801
  thread_id=thread_id,
802
+ end=True,
641
803
  cancel_on_disconnect=cancel_on_disconnect,
642
804
  stream_channel=cast("_StreamHandler", sub),
643
805
  stream_mode=stream_mode,
644
806
  last_event_id=last_event_id,
807
+ **namespace_kwargs,
645
808
  ):
646
809
  yield event, message, stream_id
647
810
  finally:
@@ -658,9 +821,30 @@ async def join_run_stream(request: ApiRequest):
658
821
  "Location": location,
659
822
  "Content-Location": f"/threads/{thread_id}/runs/{run_id}",
660
823
  },
824
+ on_close=lambda: sub.__aexit__(None, None, None),
661
825
  )
662
826
 
663
827
 
828
+ def _cancel_reason(
829
+ request: ApiRequest, action: Literal["interrupt", "rollback"]
830
+ ) -> str:
831
+ path = "/threads/{thread_id}/runs/{run_id}/cancel"
832
+ reason = request.query_params.get("reason")
833
+ if reason is None:
834
+ return f"{action} requested via POST {path}"
835
+ if reason != "taken":
836
+ raise HTTPException(
837
+ status_code=422,
838
+ detail="Invalid cancellation reason: must be 'taken'",
839
+ )
840
+ if action != "interrupt":
841
+ raise HTTPException(
842
+ status_code=422,
843
+ detail="Cancellation reason 'taken' requires action 'interrupt'",
844
+ )
845
+ return f"taken: input absorbed for steering via POST {path}"
846
+
847
+
664
848
  @retry_db
665
849
  async def cancel_run(
666
850
  request: ApiRequest,
@@ -678,6 +862,7 @@ async def cancel_run(
678
862
  action_str if action_str in {"interrupt", "rollback"} else "interrupt",
679
863
  )
680
864
 
865
+ reason = _cancel_reason(request, action)
681
866
  sub = await Runs.Stream.subscribe(run_id, thread_id) if wait else None
682
867
  try:
683
868
  async with connect() as conn:
@@ -686,7 +871,7 @@ async def cancel_run(
686
871
  [run_id],
687
872
  action=action,
688
873
  thread_id=thread_id,
689
- reason=f"{action} requested via POST /threads/{{thread_id}}/runs/{{run_id}}/cancel",
874
+ reason=reason,
690
875
  )
691
876
  except Exception:
692
877
  if sub is not None:
@@ -716,6 +901,12 @@ async def cancel_runs(
716
901
  request: ApiRequest,
717
902
  ):
718
903
  """Cancel a run."""
904
+ if "reason" in request.query_params:
905
+ # A batch can partly fail without reporting which runs it cancelled.
906
+ raise HTTPException(
907
+ status_code=422,
908
+ detail="Cancellation reason is only supported when cancelling a single run",
909
+ )
719
910
  body = await request.json(RunsCancel)
720
911
  status = body.get("status")
721
912
  if status:
@@ -78,12 +78,16 @@ async def put_item(request: ApiRequest):
78
78
  namespace = tuple(payload["namespace"]) if payload.get("namespace") else ()
79
79
  if err := _validate_namespace(namespace):
80
80
  return err
81
+ ttl = payload.get("ttl")
82
+ if "ttl" not in payload:
83
+ store = await get_store()
84
+ ttl = (store.ttl_config or {}).get("default_ttl")
81
85
  handler_payload: dict[str, Any] = {
82
86
  "namespace": namespace,
83
87
  "key": payload["key"],
84
88
  "value": payload["value"],
85
89
  "index": payload.get("index"),
86
- "ttl": payload.get("ttl"),
90
+ "ttl": ttl,
87
91
  }
88
92
  await handle_event("put", handler_payload)
89
93
  if err := _validate_namespace(handler_payload["namespace"]):