genkit 0.9.0__tar.gz → 0.10.0__tar.gz

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 (146) hide show
  1. {genkit-0.9.0 → genkit-0.10.0}/PKG-INFO +14 -2
  2. {genkit-0.9.0 → genkit-0.10.0}/pyproject.toml +17 -3
  3. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_agents/_base.py +16 -2
  4. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_agents/_client.py +123 -50
  5. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_agents/_runtime.py +82 -27
  6. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_agents/_session.py +62 -20
  7. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_agents/_session_stores/_file_store.py +27 -5
  8. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_agents/_session_stores/_inmemory_store.py +28 -6
  9. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_agents/_session_stores/_util.py +130 -21
  10. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_agents/_snapshot.py +48 -26
  11. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_aio.py +12 -11
  12. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_generate.py +59 -22
  13. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_model.py +13 -5
  14. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_prompt.py +3 -2
  15. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_runtime.py +3 -8
  16. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_tools.py +24 -5
  17. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_background.py +16 -38
  18. genkit-0.10.0/src/genkit/_core/_logger.py +138 -0
  19. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_model.py +55 -5
  20. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_reflection.py +5 -2
  21. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_reflection_v2.py +5 -3
  22. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_typing.py +2 -6
  23. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/agent/__init__.py +2 -0
  24. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/_tools_test.py +33 -0
  25. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/agent_chat_client_test.py +25 -4
  26. genkit-0.10.0/tests/genkit/ai/agent_conformance_test.py +995 -0
  27. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/agent_detach_test.py +45 -1
  28. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/agent_init_funnel_test.py +17 -0
  29. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/agent_load_session_test.py +31 -1
  30. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/agent_session_stores_test.py +160 -4
  31. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/agent_snapshot_test.py +70 -16
  32. genkit-0.10.0/tests/genkit/ai/generate_logging_test.py +207 -0
  33. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/generate_test.py +66 -2
  34. genkit-0.10.0/tests/genkit/ai/model_ref_test.py +170 -0
  35. genkit-0.10.0/tests/genkit/ai/resolve_model_error_test.py +46 -0
  36. genkit-0.10.0/tests/genkit/core/logger_test.py +299 -0
  37. genkit-0.10.0/tests/genkit/core/output_config_test.py +55 -0
  38. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/veneer/veneer_test.py +58 -1
  39. genkit-0.9.0/src/genkit/_core/_logger.py +0 -63
  40. genkit-0.9.0/tests/genkit/core/logger_test.py +0 -97
  41. {genkit-0.9.0 → genkit-0.10.0}/.gitignore +0 -0
  42. {genkit-0.9.0 → genkit-0.10.0}/LICENSE +0 -0
  43. {genkit-0.9.0 → genkit-0.10.0}/README.md +0 -0
  44. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/__init__.py +0 -0
  45. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_agents/_preamble.py +0 -0
  46. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_agents/_transports/_http.py +0 -0
  47. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_agents/_transports/_inprocess.py +0 -0
  48. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_agents/_types.py +0 -0
  49. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_decorators.py +0 -0
  50. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_embedding.py +0 -0
  51. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_evaluator.py +0 -0
  52. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_formats/__init__.py +0 -0
  53. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_formats/_array.py +0 -0
  54. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_formats/_enum.py +0 -0
  55. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_formats/_json.py +0 -0
  56. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_formats/_jsonl.py +0 -0
  57. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_formats/_schema.py +0 -0
  58. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_formats/_text.py +0 -0
  59. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_formats/_types.py +0 -0
  60. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_json_patch.py +0 -0
  61. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_messages.py +0 -0
  62. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_resource.py +0 -0
  63. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_ai/_testing.py +0 -0
  64. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_action.py +0 -0
  65. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_base.py +0 -0
  66. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_channel.py +0 -0
  67. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_compat.py +0 -0
  68. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_constants.py +0 -0
  69. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_context.py +0 -0
  70. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_dap.py +0 -0
  71. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_environment.py +0 -0
  72. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_error.py +0 -0
  73. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_extract_json.py +0 -0
  74. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_flow.py +0 -0
  75. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_http_client.py +0 -0
  76. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_loop_cache.py +0 -0
  77. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_middleware.py +0 -0
  78. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_plugin.py +0 -0
  79. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_protocols.py +0 -0
  80. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_registry.py +0 -0
  81. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_schema.py +0 -0
  82. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_trace/_adjusting_exporter.py +0 -0
  83. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_trace/_attrs.py +0 -0
  84. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_trace/_default_exporter.py +0 -0
  85. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_trace/_path.py +0 -0
  86. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_trace/_realtime_processor.py +0 -0
  87. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_trace/_suppress.py +0 -0
  88. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/_core/_tracing.py +0 -0
  89. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/embedder/__init__.py +0 -0
  90. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/evaluator/__init__.py +0 -0
  91. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/middleware/__init__.py +0 -0
  92. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/model/__init__.py +0 -0
  93. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/plugin_api/__init__.py +0 -0
  94. {genkit-0.9.0 → genkit-0.10.0}/src/genkit/py.typed +0 -0
  95. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/agent_http_transport_test.py +0 -0
  96. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/agent_http_wire_test.py +0 -0
  97. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/agent_preamble_test.py +0 -0
  98. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/agent_resume_validation_test.py +0 -0
  99. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/agent_state_schema_server_test.py +0 -0
  100. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/agent_transports_test.py +0 -0
  101. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/agent_turn_context_test.py +0 -0
  102. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/agent_turn_span_test.py +0 -0
  103. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/ai_plugin_test.py +0 -0
  104. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/ai_registry_test.py +0 -0
  105. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/dap_test.py +0 -0
  106. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/document_test.py +0 -0
  107. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/dynamic_tools_generate_test.py +0 -0
  108. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/embedding_test.py +0 -0
  109. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/formats/array_test.py +0 -0
  110. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/formats/enum_test.py +0 -0
  111. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/formats/formats_test.py +0 -0
  112. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/formats/json_test.py +0 -0
  113. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/formats/jsonl_test.py +0 -0
  114. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/formats/text_test.py +0 -0
  115. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/generate_helpers_test.py +0 -0
  116. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/generate_interrupt_resume_test.py +0 -0
  117. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/generate_operation_test.py +0 -0
  118. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/genkit_api_test.py +0 -0
  119. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/json_patch_test.py +0 -0
  120. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/message_utils_test.py +0 -0
  121. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/model_test.py +0 -0
  122. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/prompt_test.py +0 -0
  123. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/resource_integration_test.py +0 -0
  124. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/resource_test.py +0 -0
  125. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/ai/session_context_test.py +0 -0
  126. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/core/action_test.py +0 -0
  127. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/core/channel_test.py +0 -0
  128. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/core/endpoints/reflection_test.py +0 -0
  129. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/core/environment_test.py +0 -0
  130. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/core/error_test.py +0 -0
  131. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/core/extract_test.py +0 -0
  132. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/core/http_client_test.py +0 -0
  133. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/core/latency_test.py +0 -0
  134. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/core/reflection_v2_test.py +0 -0
  135. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/core/registry_test.py +0 -0
  136. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/core/run_in_new_span_test.py +0 -0
  137. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/core/schema_test.py +0 -0
  138. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/core/status_types_test.py +0 -0
  139. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/core/trace/__init__.py +0 -0
  140. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/core/trace/adjusting_exporter_test.py +0 -0
  141. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/core/trace/default_exporter_test.py +0 -0
  142. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/core/trace/realtime_processor_test.py +0 -0
  143. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/testing_test.py +0 -0
  144. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/veneer/reflection_server_test.py +0 -0
  145. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/veneer/server_test.py +0 -0
  146. {genkit-0.9.0 → genkit-0.10.0}/tests/genkit/veneer/veneer_resource_test.py +0 -0
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: genkit
3
- Version: 0.9.0
3
+ Version: 0.10.0
4
4
  Summary: Genkit AI Framework
5
5
  Project-URL: Bug Tracker, https://github.com/genkit-ai/genkit/issues
6
6
  Project-URL: Documentation, https://firebase.google.com/docs/genkit
@@ -52,12 +52,24 @@ Requires-Dist: typing-extensions>=4.0
52
52
  Requires-Dist: uvicorn>=0.34.0
53
53
  Requires-Dist: uvloop>=0.21.0; sys_platform != 'win32'
54
54
  Requires-Dist: websockets>=13.0.0
55
+ Provides-Extra: amazon-bedrock
56
+ Requires-Dist: genkit-amazon-bedrock; extra == 'amazon-bedrock'
57
+ Provides-Extra: anthropic
58
+ Requires-Dist: genkit-anthropic; extra == 'anthropic'
59
+ Provides-Extra: django
60
+ Requires-Dist: genkit-django; extra == 'django'
61
+ Provides-Extra: evaluators
62
+ Requires-Dist: genkit-evaluators; extra == 'evaluators'
63
+ Provides-Extra: fastapi
64
+ Requires-Dist: genkit-fastapi; extra == 'fastapi'
55
65
  Provides-Extra: flask
56
66
  Requires-Dist: genkit-flask; extra == 'flask'
57
67
  Provides-Extra: google-cloud
58
68
  Requires-Dist: genkit-google-cloud; extra == 'google-cloud'
59
69
  Provides-Extra: google-genai
60
70
  Requires-Dist: genkit-google-genai; extra == 'google-genai'
71
+ Provides-Extra: middleware
72
+ Requires-Dist: genkit-middleware; extra == 'middleware'
61
73
  Provides-Extra: ollama
62
74
  Requires-Dist: genkit-ollama; extra == 'ollama'
63
75
  Provides-Extra: openai
@@ -77,12 +77,18 @@ license = "Apache-2.0"
77
77
  name = "genkit"
78
78
  readme = "README.md"
79
79
  requires-python = ">=3.10"
80
- version = "0.9.0"
80
+ version = "0.10.0"
81
81
 
82
82
  [project.optional-dependencies]
83
+ amazon-bedrock = ["genkit-amazon-bedrock"]
84
+ anthropic = ["genkit-anthropic"]
85
+ django = ["genkit-django"]
86
+ evaluators = ["genkit-evaluators"]
87
+ fastapi = ["genkit-fastapi"]
83
88
  flask = ["genkit-flask"]
84
89
  google-cloud = ["genkit-google-cloud"]
85
90
  google-genai = ["genkit-google-genai"]
91
+ middleware = ["genkit-middleware"]
86
92
  ollama = ["genkit-ollama"]
87
93
  openai = ["genkit-openai"]
88
94
  vertex-ai = ["genkit-vertexai"]
@@ -105,7 +111,15 @@ pythonpath = [".", "src", "tests", "packages/genkit/src"]
105
111
  testpaths = ["tests"]
106
112
 
107
113
  [tool.uv.sources]
108
- genkit-openai = { workspace = true }
114
+ genkit-amazon-bedrock = { workspace = true }
115
+ genkit-anthropic = { workspace = true }
116
+ genkit-django = { workspace = true }
117
+ genkit-evaluators = { workspace = true }
118
+ genkit-fastapi = { workspace = true }
109
119
  genkit-flask = { workspace = true }
110
- genkit-google-genai = { workspace = true }
120
+ genkit-google-cloud = { workspace = true }
121
+ genkit-google-genai = { workspace = true }
122
+ genkit-middleware = { workspace = true }
111
123
  genkit-ollama = { workspace = true }
124
+ genkit-openai = { workspace = true }
125
+ genkit-vertexai = { workspace = true }
@@ -176,7 +176,13 @@ class Agent(
176
176
  snapshot_id: str | None = None,
177
177
  session_id: str | None = None,
178
178
  ) -> SessionSnapshot | None:
179
- """Read a snapshot by id or latest session leaf (client-visible form)."""
179
+ """Read a stored snapshot without starting a session.
180
+
181
+ Pass exactly one of ``snapshot_id`` or ``session_id``. A session
182
+ lookup returns the newest row even when that turn failed or was
183
+ aborted. ``chat(session_id=)`` is how you continue from the last
184
+ good turn.
185
+ """
180
186
  if self.store is None:
181
187
  return None
182
188
  return await resolve_snapshot(
@@ -188,7 +194,15 @@ class Agent(
188
194
  )
189
195
 
190
196
  async def abort_snapshot_data(self, snapshot_id: str) -> SnapshotStatus | None:
191
- """Abort a running snapshot."""
197
+ """Abort a running snapshot.
198
+
199
+ The return is the snapshot's status from *before* this call, not after.
200
+ ``pending`` means the turn was still running and this call cancelled it
201
+ (the row is now ``aborted``). A terminal status means the turn had
202
+ already finished — this call did not rewrite it. ``None`` means
203
+ nothing was observed (no store, no row, or the store never ran the
204
+ abort write). This Python server always returns the previous status.
205
+ """
192
206
  if self.store is None:
193
207
  return None
194
208
  return await abort_snapshot_in_store(
@@ -527,11 +527,18 @@ class AgentAPI(Protocol, Generic[StateT]):
527
527
  artifacts: list[Artifact] | None = None,
528
528
  state: StateT | None = None,
529
529
  ) -> AgentChat[StateT]:
530
- """Starts a new session, or attaches to one via a snapshot/session id or saved conversation state.
531
-
532
- ``messages`` / ``artifacts`` / ``state`` are only for client-managed agents
533
- (no store). Store-backed agents take ``snapshot_id`` or ``session_id``;
534
- passing a state blob raises :class:`AgentInitError`.
530
+ """Starts a new session, or resumes one.
531
+
532
+ Store-backed agents take ``snapshot_id`` and/or ``session_id``.
533
+ ``snapshot_id`` resumes that exact row (it must be completed).
534
+ ``session_id`` continues the conversation: skip a failed / aborted /
535
+ pending leaf, or start fresh if there isn't a completed turn yet.
536
+ Passing both is fine: the snapshot picks the row, the session id
537
+ checks it belongs to that session.
538
+
539
+ ``messages`` / ``artifacts`` / ``state`` are only for client-managed
540
+ agents (no store). Mixing those with a resume id, or sending a state
541
+ blob to a store-backed agent, raises :class:`AgentInitError`.
535
542
  """
536
543
  ...
537
544
 
@@ -541,7 +548,13 @@ class AgentAPI(Protocol, Generic[StateT]):
541
548
  snapshot_id: str | None = None,
542
549
  session_id: str | None = None,
543
550
  ) -> AgentChat[StateT]:
544
- """Loads a server snapshot and returns a session with history restored."""
551
+ """Loads a stored snapshot onto a new chat.
552
+
553
+ Pass exactly one of ``snapshot_id`` or ``session_id``. The chat is
554
+ pointed at that row as stored — including a failed, aborted, or
555
+ still-pending turn. ``send()`` resumes that row, so a non-completed
556
+ leaf is rejected. To continue the conversation, use ``chat(session_id=)``.
557
+ """
545
558
  ...
546
559
 
547
560
  async def get_snapshot(
@@ -550,11 +563,25 @@ class AgentAPI(Protocol, Generic[StateT]):
550
563
  snapshot_id: str | None = None,
551
564
  session_id: str | None = None,
552
565
  ) -> SessionSnapshotSchema | None:
553
- """Reads a snapshot without starting a session."""
566
+ """Reads a stored snapshot without starting a session.
567
+
568
+ Pass exactly one of ``snapshot_id`` or ``session_id``. A session
569
+ lookup returns the newest row even when that turn failed or was
570
+ aborted. ``chat(session_id=)`` is how you continue from the last
571
+ good turn.
572
+ """
554
573
  ...
555
574
 
556
575
  async def abort(self, snapshot_id: str) -> SnapshotStatus | None:
557
- """Aborts a running snapshot."""
576
+ """Aborts a running snapshot.
577
+
578
+ The return is the snapshot's status from *before* this call, not after.
579
+ ``pending`` means the turn was still running and this call cancelled it
580
+ (the row is now ``aborted``). A terminal status (``completed``,
581
+ ``failed``, ``aborted``) means the turn had already finished — this
582
+ call did not rewrite it. ``None`` means nothing was observed (no row,
583
+ or the store never ran the abort write).
584
+ """
558
585
  ...
559
586
 
560
587
 
@@ -563,8 +590,8 @@ class AgentClient(Generic[StateT]):
563
590
 
564
591
  This is the one ergonomic surface (``chat``/``load_chat``/``get_snapshot``/
565
592
  ``abort``) for talking to an agent, whether it's remote (HTTP transport) or
566
- in-process (the local agent action). Point it at a transport and you get the
567
- same client either way.
593
+ in-process (the local agent action). ``get_snapshot`` and ``load_chat``
594
+ read the store; ``chat()`` is how you start or continue a conversation.
568
595
 
569
596
  ``state_schema`` types the custom session state so the resulting chat hands
570
597
  back a validated model instead of a bare dict; leave it None for untyped state.
@@ -588,11 +615,18 @@ class AgentClient(Generic[StateT]):
588
615
  artifacts: list[Artifact] | None = None,
589
616
  state: StateT | None = None,
590
617
  ) -> AgentChat[StateT]:
591
- """Starts a new session, or attaches to one via a snapshot/session id or saved conversation state.
592
-
593
- ``messages`` / ``artifacts`` / ``state`` are only for client-managed agents
594
- (no store). Store-backed agents take ``snapshot_id`` or ``session_id``;
595
- passing a state blob raises :class:`AgentInitError`.
618
+ """Starts a new session, or resumes one.
619
+
620
+ Store-backed agents take ``snapshot_id`` and/or ``session_id``.
621
+ ``snapshot_id`` resumes that exact row (it must be completed).
622
+ ``session_id`` continues the conversation: skip a failed / aborted /
623
+ pending leaf, or start fresh if there isn't a completed turn yet.
624
+ Passing both is fine: the snapshot picks the row, the session id
625
+ checks it belongs to that session.
626
+
627
+ ``messages`` / ``artifacts`` / ``state`` are only for client-managed
628
+ agents (no store). Mixing those with a resume id, or sending a state
629
+ blob to a store-backed agent, raises :class:`AgentInitError`.
596
630
  """
597
631
  session_transport = copy.copy(self._transport)
598
632
  return AgentChat(
@@ -613,7 +647,13 @@ class AgentClient(Generic[StateT]):
613
647
  snapshot_id: str | None = None,
614
648
  session_id: str | None = None,
615
649
  ) -> AgentChat[StateT]:
616
- """Loads a server snapshot and returns a chat with history restored."""
650
+ """Loads a stored snapshot onto a new chat.
651
+
652
+ Pass exactly one of ``snapshot_id`` or ``session_id``. The chat is
653
+ pointed at that row as stored — including a failed, aborted, or
654
+ still-pending turn. ``send()`` resumes that row, so a non-completed
655
+ leaf is rejected. To continue the conversation, use ``chat(session_id=)``.
656
+ """
617
657
  snapshot = await self._transport.get_snapshot(snapshot_id=snapshot_id, session_id=session_id)
618
658
  if snapshot is None:
619
659
  raise ValueError(f'Snapshot {lookup_label(snapshot_id=snapshot_id, session_id=session_id)!r} not found.')
@@ -629,11 +669,25 @@ class AgentClient(Generic[StateT]):
629
669
  snapshot_id: str | None = None,
630
670
  session_id: str | None = None,
631
671
  ) -> SessionSnapshotSchema | None:
632
- """Reads a snapshot without starting a session."""
672
+ """Reads a stored snapshot without starting a session.
673
+
674
+ Pass exactly one of ``snapshot_id`` or ``session_id``. A session
675
+ lookup returns the newest row even when that turn failed or was
676
+ aborted. ``chat(session_id=)`` is how you continue from the last
677
+ good turn.
678
+ """
633
679
  return await self._transport.get_snapshot(snapshot_id=snapshot_id, session_id=session_id)
634
680
 
635
681
  async def abort(self, snapshot_id: str) -> SnapshotStatus | None:
636
- """Aborts a running snapshot on the server."""
682
+ """Aborts a running snapshot on the server.
683
+
684
+ The return is the snapshot's status from *before* this call, not after.
685
+ ``pending`` means the turn was still running and this call cancelled it
686
+ (the row is now ``aborted``). A terminal status (``completed``,
687
+ ``failed``, ``aborted``) means the turn had already finished — this
688
+ call did not rewrite it. ``None`` means nothing was observed (no row,
689
+ or the store never ran the abort write).
690
+ """
637
691
  return await self._transport.abort_snapshot(snapshot_id)
638
692
 
639
693
 
@@ -665,19 +719,23 @@ def init_from(
665
719
 
666
720
 
667
721
  def validate_init(init: AgentInit) -> None:
668
- """Ensures init specifies at most one resume handle."""
669
- provided = [
670
- name
671
- for name, present in (
672
- ('state', init.state is not None),
673
- ('snapshot_id', bool(init.snapshot_id)),
674
- ('session_id', bool(init.session_id)),
675
- )
676
- if present
677
- ]
678
- if len(provided) > 1:
679
- raise ValueError(
680
- f'AgentInit may specify at most one of state, snapshot_id, or session_id; got {", ".join(provided)}.'
722
+ """Rejects mixing a state blob with a resume id.
723
+
724
+ Passing both ``snapshot_id`` and ``session_id`` is fine: the snapshot id
725
+ picks the row, and the session id checks that the row belongs to that
726
+ session. What is not allowed is sending ``messages`` / ``artifacts`` /
727
+ custom state alongside either id — resume from the store, or seed a new
728
+ conversation, not both.
729
+ """
730
+ has_resume = bool(init.snapshot_id) or bool(init.session_id)
731
+ if init.state is not None and has_resume:
732
+ fields = seeded_init_fields(init.state)
733
+ raise AgentInitError(
734
+ status='FAILED_PRECONDITION',
735
+ message=(
736
+ f'Cannot send {fields} together with snapshot_id/session_id. '
737
+ 'Resume with snapshot_id and/or session_id, or send a state blob, not both.'
738
+ ),
681
739
  )
682
740
 
683
741
 
@@ -973,10 +1031,10 @@ class AgentChat(Generic[StateT]):
973
1031
  )
974
1032
  if init.state is not None:
975
1033
  self._set_state(init.state)
976
- elif init.snapshot_id:
1034
+ if init.snapshot_id:
977
1035
  self._snapshot_id = init.snapshot_id
978
1036
  self._resume_snapshot_id = init.snapshot_id
979
- elif init.session_id:
1037
+ if init.session_id:
980
1038
  self._session_id = init.session_id
981
1039
 
982
1040
  @property
@@ -1016,7 +1074,7 @@ class AgentChat(Generic[StateT]):
1016
1074
  metadata a resume needs). The chunks are identical whether state is server-
1017
1075
  or client-managed, so there's one path here. For server-managed sessions
1018
1076
  the durable snapshot in the store stays the source of truth — use
1019
- ``get_snapshot()`` / ``load_chat`` when you need it (e.g. after a detached
1077
+ ``get_snapshot()`` / ``load_chat`` to read it (e.g. after a detached
1020
1078
  turn, whose chunks this session never saw).
1021
1079
  """
1022
1080
  return self._messages
@@ -1150,10 +1208,11 @@ class AgentChat(Generic[StateT]):
1150
1208
  # reads the stream. For detach we only care about the resulting handle.
1151
1209
  _stream, output_awaitable = await self._transport.run_turn(agent_input=inp, init=init)
1152
1210
  raw_output = await output_awaitable
1153
- # Point the chat at the pending detached snapshot (same as JS applyOutput).
1154
- # A send() while it is still pending is rejected; after it completes, send
1155
- # continues from that snapshot. Abort rolls back the optimistic prompt —
1156
- # reload via load_chat(session_id=...) to resume from the last completed turn.
1211
+ # Point the chat at the pending detached snapshot. A send() while it is
1212
+ # still pending is rejected; after it completes, send continues from
1213
+ # that snapshot. Abort stops the server turn but keeps the prompt —
1214
+ # it was still asked. Use chat(session_id=...) to resume from the last
1215
+ # completed turn.
1157
1216
  self._update_from_output(raw=raw_output, message_count_before=message_count_before)
1158
1217
 
1159
1218
  if not raw_output.snapshot_id:
@@ -1162,12 +1221,21 @@ class AgentChat(Generic[StateT]):
1162
1221
  snapshot_id=raw_output.snapshot_id,
1163
1222
  transport=self._transport,
1164
1223
  state_schema=self._state_schema,
1165
- on_abort_rollback=lambda: self._rollback_optimistic(message_count_before),
1166
1224
  )
1167
1225
 
1168
1226
  async def abort(self) -> SnapshotStatus | None:
1169
1227
  """Stops the session's server-side work by aborting its current snapshot.
1170
1228
 
1229
+ The return is the snapshot's status from *before* this call, not after.
1230
+ ``pending`` means the turn was still running and this call cancelled it
1231
+ (the row is now ``aborted``). A terminal status means the turn had
1232
+ already finished. ``None`` means nothing was observed.
1233
+
1234
+ Against this SDK the return is always the previous status. After abort
1235
+ the chat still points at the aborted leaf — ``chat(session_id=…)``
1236
+ before the next ``send()``. The local transcript keeps the prompt;
1237
+ it was still asked.
1238
+
1171
1239
  Raises:
1172
1240
  ValueError: if there's no snapshot to abort — the agent is
1173
1241
  client-managed (no store) or no turn has produced a snapshot yet.
@@ -1220,8 +1288,10 @@ class AgentChat(Generic[StateT]):
1220
1288
  # full live state every turn.
1221
1289
  return AgentInit(state=self._session_state())
1222
1290
 
1223
- # Server store owns the state; point it at what to load. Prefer the
1224
- # current resume snapshot, fall back to the session id, else start fresh.
1291
+ # A snapshot id already names the row. Sending session_id too would
1292
+ # re-check ownership every turn, and a mismatched id on the snapshot
1293
+ # vs its state would reject a row the caller already chose. Session
1294
+ # id is only the resume handle when there isn't a snapshot yet.
1225
1295
  if self._resume_snapshot_id:
1226
1296
  return AgentInit(snapshot_id=self._resume_snapshot_id)
1227
1297
  if self._session_id:
@@ -1350,6 +1420,9 @@ class AgentChat(Generic[StateT]):
1350
1420
  self._merge_artifacts(raw.artifacts)
1351
1421
 
1352
1422
 
1423
+ # Settled statuses for client poll/wait loops. Includes ``expired`` because
1424
+ # resolve/get overlays a stale pending heartbeat as expired even though stores
1425
+ # never persist that status.
1353
1426
  TERMINAL_SNAPSHOT_STATUSES = frozenset({
1354
1427
  SnapshotStatus.COMPLETED,
1355
1428
  SnapshotStatus.FAILED,
@@ -1367,12 +1440,10 @@ class DetachedTask(Generic[StateT]):
1367
1440
  snapshot_id: str,
1368
1441
  transport: AgentTransport[StateT],
1369
1442
  state_schema: type[StateT] | None = None,
1370
- on_abort_rollback: Callable[[], None] | None = None,
1371
1443
  ) -> None:
1372
1444
  self.snapshot_id = snapshot_id
1373
1445
  self._transport = transport
1374
1446
  self._state_schema = state_schema
1375
- self._on_abort_rollback = on_abort_rollback
1376
1447
 
1377
1448
  def _parse_snapshot(self, raw: SessionSnapshotSchema | None) -> SessionSnapshot[StateT] | None:
1378
1449
  if raw is None:
@@ -1415,14 +1486,16 @@ class DetachedTask(Generic[StateT]):
1415
1486
  async def abort(self) -> SnapshotStatus | None:
1416
1487
  """Aborts the detached task on the server.
1417
1488
 
1418
- If the turn was actually aborted (and not already finished by the time the
1419
- abort lands), the originating chat drops the prompt it optimistically held
1420
- for this turn, so its view doesn't strand an unanswered message.
1489
+ The return is the snapshot's status from *before* this call, not after.
1490
+ ``pending`` means this call cancelled a still-running turn (the row is
1491
+ now ``aborted``). A terminal status means the turn had already
1492
+ finished. ``None`` means nothing was observed.
1493
+
1494
+ This does not edit the originating chat's transcript. The prompt was
1495
+ still asked; reload via ``chat(session_id=...)`` before the next send
1496
+ so you are not still pointed at the aborted leaf.
1421
1497
  """
1422
- status = await self._transport.abort_snapshot(self.snapshot_id)
1423
- if status == SnapshotStatus.ABORTED and self._on_abort_rollback is not None:
1424
- self._on_abort_rollback()
1425
- return status
1498
+ return await self._transport.abort_snapshot(self.snapshot_id)
1426
1499
 
1427
1500
 
1428
1501
  # ===========================================================================
@@ -37,6 +37,7 @@ from genkit._ai._agents._session import (
37
37
  reserve_snapshot_id,
38
38
  run_with_session,
39
39
  )
40
+ from genkit._ai._agents._session_stores._util import session_id_of
40
41
  from genkit._ai._agents._snapshot import walk_back_to_resumable
41
42
  from genkit._ai._agents._types import ChunkTransform, StateTransform, TurnContext, TurnResult
42
43
  from genkit._ai._generate import generate_action
@@ -316,7 +317,9 @@ def assert_init_matches_state_management(
316
317
  ) -> None:
317
318
  """Raise ``AgentInitError`` when init does not match the agent's store mode."""
318
319
  if (init.snapshot_id or init.session_id) and store is None:
319
- field = 'snapshot_id' if init.snapshot_id else 'session_id'
320
+ # Wire-facing errors use the wire (camelCase) field names so a
321
+ # client talking over HTTP sees the same identifiers it sent.
322
+ field = 'snapshotId' if init.snapshot_id else 'sessionId'
320
323
  raise AgentInitError(
321
324
  status='FAILED_PRECONDITION',
322
325
  message=(
@@ -325,12 +328,11 @@ def assert_init_matches_state_management(
325
328
  ),
326
329
  )
327
330
  if init.state is not None and store is not None:
328
- fields = seeded_init_fields(init.state)
329
331
  raise AgentInitError(
330
332
  status='FAILED_PRECONDITION',
331
333
  message=(
332
- f"Cannot send {fields} to agent '{agent_name}': this agent uses a "
333
- "server-managed store. Send 'snapshot_id' or 'session_id' instead."
334
+ f"Cannot send 'state' to agent '{agent_name}': this agent uses a "
335
+ "server-managed store. Send 'snapshotId' or 'sessionId' instead."
334
336
  ),
335
337
  )
336
338
 
@@ -345,6 +347,8 @@ async def load_session(
345
347
  """Construct a Session from AgentInit payload.
346
348
 
347
349
  Server-managed (store set): resume via snapshot_id or session_id.
350
+ snapshot_id is that exact row (must be completed). session_id continues
351
+ the conversation: skip a dead leaf, or start fresh if none is completed.
348
352
  Client-managed (no store): use init.state or start fresh.
349
353
 
350
354
  When ``state_schema`` is set the custom state loaded from a snapshot or the
@@ -356,11 +360,6 @@ async def load_session(
356
360
  """
357
361
  name = agent_name or 'agent'
358
362
 
359
- if init.snapshot_id and init.session_id:
360
- raise AgentInitError(
361
- status='INVALID_ARGUMENT',
362
- message=(f"Cannot send both 'snapshot_id' and 'session_id' to agent '{name}'. Provide exactly one."),
363
- )
364
363
  assert_init_matches_state_management(init=init, store=store, agent_name=name)
365
364
 
366
365
  ctx = get_current_context()
@@ -372,6 +371,20 @@ async def load_session(
372
371
  status='NOT_FOUND',
373
372
  message=f'Snapshot {init.snapshot_id!r} not found',
374
373
  )
374
+ # When init carries both ids, the snapshot id picks the row and the
375
+ # session id is an ownership check: the snapshot must belong to that
376
+ # session. Wrong pairing is a client error, not a silent load.
377
+ if init.session_id:
378
+ snap_session_id = session_id_of(snap)
379
+ if snap_session_id != init.session_id:
380
+ owner = snap_session_id if snap_session_id is not None else 'an unknown session'
381
+ raise AgentInitError(
382
+ status='INVALID_ARGUMENT',
383
+ message=(
384
+ f'Snapshot {init.snapshot_id!r} does not belong to session '
385
+ f'{init.session_id!r} (it belongs to {owner!r}).'
386
+ ),
387
+ )
375
388
  # A failed/aborted/pending snapshot is kept for inspection but isn't a
376
389
  # valid place to continue a conversation from.
377
390
  if snap.status != SnapshotStatus.COMPLETED:
@@ -657,19 +670,28 @@ class AgentRuntime:
657
670
  out.snapshot_id = await self.ensure_recovery_snapshot()
658
671
  return out
659
672
 
660
- async def watch_snapshot_abort(self, *, snapshot_id: str, abort_signal: asyncio.Event) -> None:
673
+ async def watch_snapshot_abort(
674
+ self,
675
+ *,
676
+ snapshot_id: str,
677
+ abort_signal: asyncio.Event,
678
+ context: dict[str, Any] | None = None,
679
+ ) -> None:
661
680
  if self.store is None or not isinstance(self.store, SnapshotSubscriber):
662
681
  return
663
- q = await self.store.on_snapshot_status_change(snapshot_id)
664
- while True:
665
- status = await q.get()
666
- if status is None:
667
- return
682
+ # Prefer the detach-time context from the caller so the subscription
683
+ # stays on the request's tenant even if this task starts after ambient
684
+ # context has moved on.
685
+ statuses = await self.store.on_snapshot_status_change(
686
+ snapshot_id, context=context if context is not None else get_current_context()
687
+ )
688
+ # Aborted is terminal, so the stream ends right after that yield and
689
+ # unsubscribes. Returning early would skip that teardown.
690
+ async for status in statuses:
668
691
  if status == SnapshotStatus.ABORTED:
669
692
  abort_signal.set()
670
- return
671
693
 
672
- async def refresh_heartbeat(self, snapshot_id: str) -> None:
694
+ async def refresh_heartbeat(self, snapshot_id: str, *, context: dict[str, Any] | None = None) -> None:
673
695
  """Keep a detached turn's pending snapshot fresh so readers don't flag it dead.
674
696
 
675
697
  A reader treats a pending snapshot whose heartbeat has gone stale as
@@ -677,13 +699,14 @@ class AgentRuntime:
677
699
  detached turn is genuinely still running we bump the beat on an interval.
678
700
  The mutator only touches a still-pending snapshot, so a beat never
679
701
  resurrects a terminal snapshot or races a concurrent abort/finalize.
702
+
703
+ ``context`` should be the detach-time tenant context (same as abort-watch
704
+ and finalize). Falls back to ambient context if the caller omitted it.
680
705
  """
681
706
  if self.store is None:
682
707
  return
683
708
  interval_s = DEFAULT_HEARTBEAT_INTERVAL_MS / 1000
684
- # Capture at start (detach time) so beats keep using the request's
685
- # tenant context even if ambient context later changes.
686
- beat_context = get_current_context()
709
+ beat_context = context if context is not None else get_current_context()
687
710
 
688
711
  def beat(existing: SessionSnapshot | None) -> SessionSnapshot | None:
689
712
  if existing is None or existing.status != SnapshotStatus.PENDING:
@@ -708,8 +731,14 @@ class AgentRuntime:
708
731
  err_holder: list[Exception],
709
732
  result_holder: list[AgentResult],
710
733
  heartbeat_task: asyncio.Task,
734
+ context: dict[str, Any] | None = None,
711
735
  ) -> None:
712
- """Background task: wait for fn, then rewrite pending snapshot with final state."""
736
+ """Background task: wait for fn, then rewrite pending snapshot with final state.
737
+
738
+ ``context`` should be captured at detach time (same as heartbeats) so a
739
+ multi-tenant store still writes the terminal status under the request's
740
+ tenant after the original call has returned.
741
+ """
713
742
  await fn_task
714
743
  await forward_task
715
744
 
@@ -722,7 +751,17 @@ class AgentRuntime:
722
751
  state = await self.session.state()
723
752
  now = datetime.now(timezone.utc).isoformat()
724
753
  fn_err = err_holder[0] if err_holder else None
725
- if fn_err:
754
+ # SessionRunner.run swallows turn exceptions into last_turn_error and
755
+ # still returns. The attached path consults that field; detached
756
+ # finalize used to look only at err_holder, so a graceful turn failure
757
+ # wrote status=completed / error=None. Same rule as emit_turn_end.
758
+ turn_err = self.session_runner.last_turn_error
759
+ is_failed = (
760
+ fn_err is not None
761
+ or turn_err is not None
762
+ or self.session_runner.last_turn_finish_reason == AgentFinishReason.FAILED
763
+ )
764
+ if is_failed:
726
765
  finish_reason = AgentFinishReason.FAILED
727
766
  else:
728
767
  result = result_holder[0] if result_holder else None
@@ -737,9 +776,9 @@ class AgentRuntime:
737
776
  return SessionSnapshot(
738
777
  snapshot_id=existing.snapshot_id if existing else '',
739
778
  parent_id=pending_snap.parent_id or '',
740
- status=SnapshotStatus.FAILED if fn_err else SnapshotStatus.COMPLETED,
779
+ status=SnapshotStatus.FAILED if is_failed else SnapshotStatus.COMPLETED,
741
780
  state=state,
742
- error=(to_error_details(fn_err) if fn_err else None),
781
+ error=(to_error_details(fn_err) if fn_err else turn_err),
743
782
  finish_reason=finish_reason,
744
783
  created_at=existing.created_at if existing else now,
745
784
  )
@@ -748,7 +787,7 @@ class AgentRuntime:
748
787
  await self.store.save_snapshot( # type: ignore[union-attr]
749
788
  pending_snap.snapshot_id,
750
789
  finalize,
751
- context=get_current_context(),
790
+ context=context,
752
791
  )
753
792
  except Exception: # noqa: BLE001
754
793
  # Best-effort: the snapshot stays pending, but its heartbeat stopped
@@ -780,6 +819,12 @@ class AgentRuntime:
780
819
  async for item in client_inputs:
781
820
  if item.detach:
782
821
  is_detached = True
822
+ # Stop chunk emission immediately: a detached run must
823
+ # not stream chunks back on this connection. Setting the
824
+ # flag here — before the payload is queued — closes the
825
+ # race where the background turn starts streaming before
826
+ # the detach branch of run() marks the runtime detached.
827
+ self.detached = True
783
828
  # Forward the detach input's payload (if any) into the turn
784
829
  # loop and close it *before* signaling detach. Doing it in
785
830
  # this order means the turn is deterministically queued for
@@ -884,10 +929,19 @@ class AgentRuntime:
884
929
  # emitting chunks to it. The turn keeps running; a background task
885
930
  # finalizes the snapshot when fn finishes.
886
931
  self.detached = True
932
+ # Pin tenant context for background abort-watch / heartbeat / finalize
933
+ # — ambient context may be gone by the time those tasks run or settle.
934
+ detach_context = get_current_context()
887
935
  t1 = asyncio.create_task(
888
- self.watch_snapshot_abort(snapshot_id=pending_snap.snapshot_id, abort_signal=abort_signal)
936
+ self.watch_snapshot_abort(
937
+ snapshot_id=pending_snap.snapshot_id,
938
+ abort_signal=abort_signal,
939
+ context=detach_context,
940
+ )
941
+ )
942
+ heartbeat_task = asyncio.create_task(
943
+ self.refresh_heartbeat(pending_snap.snapshot_id, context=detach_context)
889
944
  )
890
- heartbeat_task = asyncio.create_task(self.refresh_heartbeat(pending_snap.snapshot_id))
891
945
  t2 = asyncio.create_task(
892
946
  self.finalize_detach(
893
947
  pending_snap=pending_snap,
@@ -896,6 +950,7 @@ class AgentRuntime:
896
950
  err_holder=err_holder,
897
951
  result_holder=result_holder,
898
952
  heartbeat_task=heartbeat_task,
953
+ context=detach_context,
899
954
  )
900
955
  )
901
956
  self.background_tasks.add(t1)