agentengine-sdk-python 0.7.0__py3-none-any.whl → 0.8.1__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 (450) hide show
  1. {agentengine_sdk_python-0.7.0.dist-info → agentengine_sdk_python-0.8.1.dist-info}/METADATA +52 -20
  2. agentengine_sdk_python-0.8.1.dist-info/RECORD +644 -0
  3. {agentengine_sdk_python-0.7.0.dist-info → agentengine_sdk_python-0.8.1.dist-info}/WHEEL +1 -1
  4. ksadk/a2a/__init__.py +180 -11
  5. ksadk/a2a/bootstrap.py +332 -0
  6. ksadk/a2a/card.py +15 -0
  7. ksadk/a2a/context_store.py +203 -0
  8. ksadk/a2a/control_plane.py +1056 -0
  9. ksadk/a2a/credential.py +99 -0
  10. ksadk/a2a/event_adapter.py +149 -0
  11. ksadk/a2a/executor.py +361 -137
  12. ksadk/a2a/external_transport.py +516 -0
  13. ksadk/a2a/identity.py +304 -0
  14. ksadk/a2a/ids.py +22 -0
  15. ksadk/a2a/langgraph.py +285 -0
  16. ksadk/a2a/resume_store.py +201 -0
  17. ksadk/a2a/routes.py +112 -0
  18. ksadk/a2a/server.py +102 -62
  19. ksadk/a2a/service_env.py +33 -0
  20. ksadk/a2a/space_client.py +1122 -0
  21. ksadk/a2a/task_adapter.py +423 -0
  22. ksadk/a2a/task_event_dispatcher.py +167 -0
  23. ksadk/a2a/task_event_outbox.py +326 -0
  24. ksadk/a2a/task_store.py +206 -0
  25. ksadk/a2a_card.py +101 -0
  26. ksadk/a2ui/__init__.py +27 -0
  27. ksadk/a2ui/core.py +186 -0
  28. ksadk/a2ui/models.py +166 -0
  29. ksadk/a2ui/renderer.py +198 -0
  30. ksadk/agui/__init__.py +9 -0
  31. ksadk/agui/a2ui_projection.py +92 -0
  32. ksadk/agui/agent.py +872 -0
  33. ksadk/agui/config.py +92 -0
  34. ksadk/agui/routes.py +47 -0
  35. ksadk/api/client.py +238 -204
  36. ksadk/api/environment.py +27 -0
  37. ksadk/builders/__init__.py +2 -0
  38. ksadk/builders/base.py +16 -14
  39. ksadk/builders/code_builder.py +375 -270
  40. ksadk/builders/container_builder.py +240 -200
  41. ksadk/builders/framework_requirements.py +31 -12
  42. ksadk/builders/ks3_uploader.py +60 -29
  43. ksadk/builders/managed_runtime_builder.py +173 -0
  44. ksadk/builders/mcp_builder.py +91 -92
  45. ksadk/builders/requirements_utils.py +1 -5
  46. ksadk/cli/__init__.py +97 -171
  47. ksadk/cli/cmd_a2a.py +255 -84
  48. ksadk/cli/cmd_agent.py +19 -5
  49. ksadk/cli/cmd_build.py +158 -29
  50. ksadk/cli/cmd_completion.py +47 -35
  51. ksadk/cli/cmd_config.py +267 -198
  52. ksadk/cli/cmd_create.py +507 -740
  53. ksadk/cli/cmd_dashboard.py +120 -45
  54. ksadk/cli/cmd_deploy.py +135 -59
  55. ksadk/cli/cmd_destroy.py +44 -14
  56. ksadk/cli/cmd_eval.py +386 -0
  57. ksadk/cli/cmd_files.py +63 -24
  58. ksadk/cli/cmd_hermes.py +313 -135
  59. ksadk/cli/cmd_invoke.py +184 -122
  60. ksadk/cli/cmd_launch.py +76 -28
  61. ksadk/cli/cmd_mcp.py +98 -64
  62. ksadk/cli/cmd_model.py +14 -5
  63. ksadk/cli/cmd_openclaw.py +564 -268
  64. ksadk/cli/cmd_replay.py +71 -0
  65. ksadk/cli/cmd_run.py +58 -73
  66. ksadk/cli/cmd_status.py +80 -31
  67. ksadk/cli/cmd_studio.py +110 -0
  68. ksadk/cli/cmd_version.py +20 -13
  69. ksadk/cli/cmd_web.py +95 -18
  70. ksadk/cli/deploy_utils.py +20 -20
  71. ksadk/cli/dry_run.py +7 -4
  72. ksadk/cli/env_options.py +83 -0
  73. ksadk/cli/error_utils.py +37 -12
  74. ksadk/cli/global_options.py +4 -3
  75. ksadk/cli/local_runtime.py +1 -2
  76. ksadk/cli/model_catalog.py +6 -2
  77. ksadk/cli/network_options.py +41 -19
  78. ksadk/cli/resource_common.py +6 -2
  79. ksadk/cli/runtime_bootstrap.py +51 -0
  80. ksadk/cli/storage.py +0 -1
  81. ksadk/cli/ui.py +11 -3
  82. ksadk/cli/workflow_common.py +52 -18
  83. ksadk/codex/__init__.py +12 -0
  84. ksadk/codex/client.py +1042 -0
  85. ksadk/codex/phase.py +143 -0
  86. ksadk/codex/runtime.py +940 -0
  87. ksadk/common/aicp_env.py +0 -1
  88. ksadk/common/auth.py +2 -2
  89. ksadk/common/constants.py +1 -3
  90. ksadk/common/kop_client.py +232 -0
  91. ksadk/common/llm_utils.py +17 -13
  92. ksadk/compat/__init__.py +5 -0
  93. ksadk/compat/adk_compat.py +200 -0
  94. ksadk/compat/copilotkit_a2ui.py +330 -0
  95. ksadk/configs/__init__.py +12 -14
  96. ksadk/configs/env_registry.py +661 -116
  97. ksadk/configs/global_config.py +3 -2
  98. ksadk/configs/settings.py +133 -209
  99. ksadk/conversations/__init__.py +85 -92
  100. ksadk/conversations/attachment_storage.py +16 -11
  101. ksadk/conversations/attachments.py +44 -36
  102. ksadk/conversations/compaction_pipeline.py +12 -12
  103. ksadk/conversations/compaction_prompt.py +9 -5
  104. ksadk/conversations/context.py +221 -6
  105. ksadk/conversations/message_projection.py +438 -51
  106. ksadk/conversations/model_context.py +12 -6
  107. ksadk/conversations/model_options.py +0 -1
  108. ksadk/conversations/normalize.py +20 -16
  109. ksadk/conversations/reasoning_markup.py +1 -1
  110. ksadk/conversations/runtime.py +339 -5255
  111. ksadk/conversations/runtime_compaction.py +333 -0
  112. ksadk/conversations/runtime_constants.py +27 -0
  113. ksadk/conversations/runtime_governance.py +185 -0
  114. ksadk/conversations/runtime_input.py +660 -0
  115. ksadk/conversations/runtime_invocation.py +395 -0
  116. ksadk/conversations/runtime_metadata.py +475 -0
  117. ksadk/conversations/runtime_observability.py +367 -0
  118. ksadk/conversations/runtime_payloads.py +272 -0
  119. ksadk/conversations/runtime_persistence.py +440 -0
  120. ksadk/conversations/runtime_preparation.py +426 -0
  121. ksadk/conversations/runtime_resume.py +836 -0
  122. ksadk/conversations/runtime_stream_events.py +902 -0
  123. ksadk/conversations/runtime_streaming.py +700 -0
  124. ksadk/conversations/semantic_summary.py +17 -5
  125. ksadk/conversations/session_title.py +6 -3
  126. ksadk/deployment/__init__.py +15 -16
  127. ksadk/deployment/agent_access.py +12 -23
  128. ksadk/deployment/base.py +51 -38
  129. ksadk/deployment/managed_runtime.py +33 -0
  130. ksadk/deployment/manager.py +85 -71
  131. ksadk/deployment/providers/serverless.py +379 -210
  132. ksadk/deployment/registry.py +38 -32
  133. ksadk/deployment/state.py +11 -11
  134. ksadk/deployment/ui_config.py +1 -1
  135. ksadk/detection/__init__.py +1 -1
  136. ksadk/detection/detector.py +146 -83
  137. ksadk/detection/mcp_detector.py +9 -6
  138. ksadk/evaluation/__init__.py +84 -0
  139. ksadk/evaluation/a2a_adapter.py +444 -0
  140. ksadk/evaluation/adapters.py +54 -0
  141. ksadk/evaluation/contracts.py +409 -0
  142. ksadk/evaluation/evalset.py +351 -0
  143. ksadk/evaluation/evaluators.py +461 -0
  144. ksadk/evaluation/executor.py +118 -0
  145. ksadk/evaluation/storage.py +68 -0
  146. ksadk/evaluation/target.py +73 -0
  147. ksadk/events/__init__.py +25 -0
  148. ksadk/events/parser.py +191 -0
  149. ksadk/events/replay.py +37 -0
  150. ksadk/events/runtime_event.py +273 -0
  151. ksadk/events/store.py +317 -0
  152. ksadk/harness/__init__.py +35 -0
  153. ksadk/harness/app.py +269 -0
  154. ksadk/harness/config.py +181 -0
  155. ksadk/harness/reasoner.py +105 -0
  156. ksadk/harness/runtime.py +364 -0
  157. ksadk/harness/sandbox.py +141 -0
  158. ksadk/harness/tools.py +222 -0
  159. ksadk/hermes_terminal.py +28 -12
  160. ksadk/identity/resolver.py +15 -9
  161. ksadk/ids.py +32 -0
  162. ksadk/knowledge_base/adk_tool.py +1 -1
  163. ksadk/knowledge_base/client.py +38 -33
  164. ksadk/managed_a2a_card.py +160 -0
  165. ksadk/managed_runtime.py +195 -0
  166. ksadk/markdown.py +5 -2
  167. ksadk/mcp_runtime/__init__.py +9 -6
  168. ksadk/memory/__init__.py +1 -1
  169. ksadk/memory/adk/__init__.py +2 -0
  170. ksadk/memory/adk/backends/base_ltm_backend.py +2 -6
  171. ksadk/memory/adk/backends/http_ltm_backend.py +13 -21
  172. ksadk/memory/adk/backends/inmemory_ltm_backend.py +7 -13
  173. ksadk/memory/adk/backends/sdk_ltm_backend.py +36 -36
  174. ksadk/memory/adk/long_term_memory.py +34 -37
  175. ksadk/memory/adk/resilient_session_service.py +4 -5
  176. ksadk/memory/adk/short_term_memory.py +12 -21
  177. ksadk/memory/adk_tool.py +3 -2
  178. ksadk/memory/backends/base.py +19 -19
  179. ksadk/memory/backends/memory.py +24 -25
  180. ksadk/memory/backends/redis.py +31 -30
  181. ksadk/memory/langchain_tool.py +2 -1
  182. ksadk/memory/manager.py +52 -47
  183. ksadk/memory/service.py +16 -6
  184. ksadk/memory/tool.py +4 -0
  185. ksadk/model_policy.py +15 -7
  186. ksadk/model_proxy/__init__.py +51 -0
  187. ksadk/model_proxy/bootstrap.py +80 -0
  188. ksadk/model_proxy/cache.py +165 -0
  189. ksadk/model_proxy/config.py +66 -0
  190. ksadk/model_proxy/demo_webui.py +115 -0
  191. ksadk/model_proxy/detect.py +145 -0
  192. ksadk/model_proxy/gate.py +68 -0
  193. ksadk/model_proxy/namespace.py +201 -0
  194. ksadk/model_proxy/protocol_proxy.py +22 -0
  195. ksadk/model_proxy/server.py +443 -0
  196. ksadk/model_proxy/transform.py +735 -0
  197. ksadk/openclaw_gateway.py +29 -14
  198. ksadk/runners/adk_runner.py +354 -146
  199. ksadk/runners/base_runner.py +71 -29
  200. ksadk/runners/deepagents_runner.py +0 -1
  201. ksadk/runners/factory.py +18 -5
  202. ksadk/runners/langchain_runner.py +29 -742
  203. ksadk/runners/langgraph_runner.py +417 -97
  204. ksadk/runners/patch_langchain.py +16 -16
  205. ksadk/runners/remote_runner.py +134 -33
  206. ksadk/runners/usage_accumulator.py +1 -0
  207. ksadk/runners/utils/__init__.py +0 -10
  208. ksadk/runners/utils/loader.py +23 -7
  209. ksadk/runtime/__init__.py +67 -0
  210. ksadk/runtime/adapter.py +412 -0
  211. ksadk/runtime/conversation_execution.py +553 -0
  212. ksadk/runtime/executor.py +251 -0
  213. ksadk/runtime/factory.py +156 -0
  214. ksadk/runtime/framework_adapters.py +118 -0
  215. ksadk/runtime/launch.py +48 -0
  216. ksadk/runtime/preprocessing.py +131 -0
  217. ksadk/runtime/runner_adapter.py +1032 -0
  218. ksadk/runtime/runner_loading.py +36 -0
  219. ksadk/runtime_context.py +18 -3
  220. ksadk/runtime_state.py +0 -1
  221. ksadk/sandbox/__init__.py +4 -1
  222. ksadk/sandbox/backends/__init__.py +4 -1
  223. ksadk/sandbox/backends/e2b.py +13 -5
  224. ksadk/sandbox/backends/local_process.py +11 -3
  225. ksadk/sandbox/base.py +10 -15
  226. ksadk/sandbox/factory.py +14 -4
  227. ksadk/sandbox/registry.py +57 -6
  228. ksadk/server/__init__.py +39 -4
  229. ksadk/server/api_models.py +15 -5
  230. ksadk/server/app.py +24 -3928
  231. ksadk/server/composition.py +47 -0
  232. ksadk/server/factory.py +622 -0
  233. ksadk/server/routes/__init__.py +1 -0
  234. ksadk/server/routes/checkpoint_resolution.py +116 -0
  235. ksadk/server/routes/common.py +682 -0
  236. ksadk/server/routes/control.py +331 -0
  237. ksadk/server/routes/dependencies.py +98 -0
  238. ksadk/server/routes/misc.py +425 -0
  239. ksadk/server/routes/models.py +451 -0
  240. ksadk/server/routes/openai_compat.py +229 -0
  241. ksadk/server/routes/projection.py +848 -0
  242. ksadk/server/routes/routers.py +52 -0
  243. ksadk/server/routes/run.py +519 -0
  244. ksadk/server/routes/sessions.py +644 -0
  245. ksadk/server/routes/streaming.py +265 -0
  246. ksadk/server/routes/workspace.py +414 -0
  247. ksadk/server/static/assets/{ArtifactsPanel-D-SSn2ee.js → ArtifactsPanel-CakCqxEN.js} +1 -1
  248. ksadk/server/static/assets/CodeBlock-CynLknyO.js +9 -0
  249. ksadk/server/static/assets/MathMessageMarkdown-3sQdOysS.js +8 -0
  250. ksadk/server/static/assets/MermaidBlock-NERD_ef7.js +303 -0
  251. ksadk/server/static/assets/NativeTerminalPanel-CiHWf82q.js +1 -0
  252. ksadk/server/static/assets/{arc-BA13sHc9.js → arc-DrgjcKhl.js} +1 -1
  253. ksadk/server/static/assets/architecture-7EHR7CIX-CpZLRCcY.js +1 -0
  254. ksadk/server/static/assets/{architectureDiagram-3BPJPVTR-DzJzgVoL.js → architectureDiagram-3BPJPVTR-BXoVRbQ6.js} +1 -1
  255. ksadk/server/static/assets/{blockDiagram-GPEHLZMM-UTdVcZhn.js → blockDiagram-GPEHLZMM-BnaB3Ywv.js} +1 -1
  256. ksadk/server/static/assets/{c4Diagram-AAUBKEIU-Dix0GD4m.js → c4Diagram-AAUBKEIU-Dw4weZcp.js} +1 -1
  257. ksadk/server/static/assets/channel-Dt3rQTFI.js +1 -0
  258. ksadk/server/static/assets/{chunk-2J33WTMH-C2JxuZ42.js → chunk-2J33WTMH-ChjpLK7j.js} +1 -1
  259. ksadk/server/static/assets/{chunk-4BX2VUAB-Be57QPgD.js → chunk-4BX2VUAB-B9drTgOW.js} +1 -1
  260. ksadk/server/static/assets/{chunk-55IACEB6-WjSuy4nv.js → chunk-55IACEB6-CK4ROATy.js} +1 -1
  261. ksadk/server/static/assets/{chunk-727SXJPM-BOovP-b5.js → chunk-727SXJPM-B9KtTTgw.js} +1 -1
  262. ksadk/server/static/assets/{chunk-AQP2D5EJ-DOmZNmWj.js → chunk-AQP2D5EJ-1O1mki3m.js} +1 -1
  263. ksadk/server/static/assets/{chunk-FMBD7UC4-DzwlodkU.js → chunk-FMBD7UC4-B_fH2YuH.js} +1 -1
  264. ksadk/server/static/assets/{chunk-ND2GUHAM-DMqAikEU.js → chunk-ND2GUHAM-D6rFLaVV.js} +1 -1
  265. ksadk/server/static/assets/chunk-QZHKN3VN-iXEZtKQc.js +1 -0
  266. ksadk/server/static/assets/classDiagram-4FO5ZUOK-DIveV17Q.js +1 -0
  267. ksadk/server/static/assets/classDiagram-v2-Q7XG4LA2-DIveV17Q.js +1 -0
  268. ksadk/server/static/assets/{cose-bilkent-S5V4N54A-Zhy2GBnP.js → cose-bilkent-S5V4N54A-ChNs_Mdk.js} +1 -1
  269. ksadk/server/static/assets/{dagre-BM42HDAG-CbKrtIUz.js → dagre-BM42HDAG-D0QXg_MQ.js} +1 -1
  270. ksadk/server/static/assets/{diagram-2AECGRRQ-BRApgQRK.js → diagram-2AECGRRQ-DBDDKwBQ.js} +1 -1
  271. ksadk/server/static/assets/{diagram-5GNKFQAL-D0xbnDiK.js → diagram-5GNKFQAL-BkwDOxmO.js} +1 -1
  272. ksadk/server/static/assets/{diagram-KO2AKTUF-CVugVI9L.js → diagram-KO2AKTUF-Bv8waYvY.js} +1 -1
  273. ksadk/server/static/assets/{diagram-LMA3HP47-DozUGgee.js → diagram-LMA3HP47-e1VECDdu.js} +1 -1
  274. ksadk/server/static/assets/{diagram-OG6HWLK6-ZOYsKlru.js → diagram-OG6HWLK6-Ds9adfRl.js} +1 -1
  275. ksadk/server/static/assets/{dist-DpKtt4Bo.js → dist-4N2NMVYg.js} +1 -1
  276. ksadk/server/static/assets/{dist-CkEKJFtk.js → dist-B-jNR6Vn.js} +1 -1
  277. ksadk/server/static/assets/{dist-D57wnGWd.js → dist-B5J2uhNk.js} +1 -1
  278. ksadk/server/static/assets/{dist-8_SfK1IP.js → dist-B5oS1zcj.js} +1 -1
  279. ksadk/server/static/assets/{dist-DMezvBGJ.js → dist-BB3-OwTQ.js} +1 -1
  280. ksadk/server/static/assets/{dist-2hInLS_J.js → dist-BIlKoW0k.js} +1 -1
  281. ksadk/server/static/assets/{dist-BrCcQ47T.js → dist-BjOdlDjj.js} +1 -1
  282. ksadk/server/static/assets/{dist-BmlMPsCc.js → dist-C1sz5Eo3.js} +1 -1
  283. ksadk/server/static/assets/{dist-B0NP_Z0z.js → dist-CWV4lDr1.js} +1 -1
  284. ksadk/server/static/assets/{dist-D-xOD048.js → dist-CmZHzlwZ.js} +1 -1
  285. ksadk/server/static/assets/{dist-DL_NKc_z.js → dist-D6MpCZtz.js} +1 -1
  286. ksadk/server/static/assets/{dist-DyOkZmze.js → dist-DJN_6Y39.js} +1 -1
  287. ksadk/server/static/assets/{dist-DmFaq_Iy.js → dist-DQU9EWw-.js} +1 -1
  288. ksadk/server/static/assets/{dist-gX6GOLKq.js → dist-DWKByxWV.js} +1 -1
  289. ksadk/server/static/assets/{dist-DyWsb78Q.js → dist-Dli7qW-B.js} +1 -1
  290. ksadk/server/static/assets/{dist-BIJVDMuB.js → dist-DsHPdk3W.js} +1 -1
  291. ksadk/server/static/assets/{dist-Dp0k7bWI.js → dist-X4TnqwOK.js} +1 -1
  292. ksadk/server/static/assets/{dist-8EEyGgDx.js → dist-_pHPTyZ-.js} +1 -1
  293. ksadk/server/static/assets/{dist-CPBtqRTW.js → dist-fhOuWds5.js} +1 -1
  294. ksadk/server/static/assets/{dist-D-JMdWPQ.js → dist-gLnrGsoU.js} +1 -1
  295. ksadk/server/static/assets/{dist-BssVmjIo.js → dist-j6Dxmf_j.js} +1 -1
  296. ksadk/server/static/assets/{dist-C3HIIaN5.js → dist-o2OVmKvt.js} +1 -1
  297. ksadk/server/static/assets/{erDiagram-TEJ5UH35-Bk-9bgE5.js → erDiagram-TEJ5UH35-BPItFKH6.js} +1 -1
  298. ksadk/server/static/assets/eventmodeling-FCH6USID-DYFSxbqr.js +1 -0
  299. ksadk/server/static/assets/{flowDiagram-I6XJVG4X-Dn9kZVuZ.js → flowDiagram-I6XJVG4X-BbYB9w5Y.js} +1 -1
  300. ksadk/server/static/assets/{ganttDiagram-6RSMTGT7-BGxXlJqm.js → ganttDiagram-6RSMTGT7-TQXa0KXv.js} +1 -1
  301. ksadk/server/static/assets/gitGraph-WXDBUCRP-DyNYp6BN.js +1 -0
  302. ksadk/server/static/assets/{gitGraphDiagram-PVQCEYII-C7Q0X-wi.js → gitGraphDiagram-PVQCEYII-bKblCnpa.js} +1 -1
  303. ksadk/server/static/assets/index-R52pJJvg.js +177 -0
  304. ksadk/server/static/assets/index-jJr3_955.css +2 -0
  305. ksadk/server/static/assets/info-J43DQDTF-WUx7qTde.js +1 -0
  306. ksadk/server/static/assets/{infoDiagram-5YYISTIA-BO_CSqq5.js → infoDiagram-5YYISTIA-BGVT7J_i.js} +1 -1
  307. ksadk/server/static/assets/{ishikawaDiagram-YF4QCWOH-eYLPLd46.js → ishikawaDiagram-YF4QCWOH-K0OOfVna.js} +1 -1
  308. ksadk/server/static/assets/{journeyDiagram-JHISSGLW-De9geSb0.js → journeyDiagram-JHISSGLW-8LeOJaZp.js} +1 -1
  309. ksadk/server/static/assets/{kanban-definition-UN3LZRKU-Cs80kQto.js → kanban-definition-UN3LZRKU-C6uCgZrW.js} +1 -1
  310. ksadk/server/static/assets/{katex-DSrCFD8n.js → katex-CYWseY5E.js} +1 -1
  311. ksadk/server/static/assets/{linear-CN9sbKTF.js → linear-hdBcYzM8.js} +1 -1
  312. ksadk/server/static/assets/{mermaid-parser.core-DlgSBU8l.js → mermaid-parser.core-BWrDjSZM.js} +2 -2
  313. ksadk/server/static/assets/{mindmap-definition-RKZ34NQL-9afz7Oug.js → mindmap-definition-RKZ34NQL-Bjy_2v4_.js} +1 -1
  314. ksadk/server/static/assets/packet-YPE3B663-BN13y_xl.js +1 -0
  315. ksadk/server/static/assets/pie-LRSECV5Y-ftSLXhhc.js +1 -0
  316. ksadk/server/static/assets/{pieDiagram-4H26LBE5-DPv_VstN.js → pieDiagram-4H26LBE5-GmmqNiVH.js} +1 -1
  317. ksadk/server/static/assets/{quadrantDiagram-W4KKPZXB-o77wZ1XK.js → quadrantDiagram-W4KKPZXB-BmkRbwCg.js} +1 -1
  318. ksadk/server/static/assets/radar-GUYGQ44K-jaICkIeO.js +1 -0
  319. ksadk/server/static/assets/{requirementDiagram-4Y6WPE33-BYVw81VC.js → requirementDiagram-4Y6WPE33-DSWFqL7c.js} +1 -1
  320. ksadk/server/static/assets/{sankeyDiagram-5OEKKPKP-B7nZFMKT.js → sankeyDiagram-5OEKKPKP-l6iXmU65.js} +1 -1
  321. ksadk/server/static/assets/{sequenceDiagram-3UESZ5HK-BGRRrFw5.js → sequenceDiagram-3UESZ5HK-Cq6UBeQB.js} +1 -1
  322. ksadk/server/static/assets/{stateDiagram-AJRCARHV-BUfHCoPs.js → stateDiagram-AJRCARHV-qzTQpg3Y.js} +1 -1
  323. ksadk/server/static/assets/stateDiagram-v2-BHNVJYJU-BYCoYGAN.js +1 -0
  324. ksadk/server/static/assets/{timeline-definition-PNZ67QCA-FbCTGrf9.js → timeline-definition-PNZ67QCA-DEz24vV0.js} +1 -1
  325. ksadk/server/static/assets/treeView-BLDUP644-Cpib_vlz.js +1 -0
  326. ksadk/server/static/assets/treemap-LRROVOQU-DQxfmVHK.js +1 -0
  327. ksadk/server/static/assets/{vennDiagram-CIIHVFJN-DWgwtPsJ.js → vennDiagram-CIIHVFJN-CMCixki2.js} +1 -1
  328. ksadk/server/static/assets/wardley-L42UT6IY-BQYHnnkU.js +1 -0
  329. ksadk/server/static/assets/{wardleyDiagram-YWT4CUSO-2x8G-tTM.js → wardleyDiagram-YWT4CUSO-CVzB8F9K.js} +1 -1
  330. ksadk/server/static/assets/{xychartDiagram-2RQKCTM6-Drma3AYl.js → xychartDiagram-2RQKCTM6-BFBqBLc1.js} +1 -1
  331. ksadk/server/static/index.html +2 -2
  332. ksadk/server/terminal_sessions.py +111 -58
  333. ksadk/sessions/__init__.py +69 -19
  334. ksadk/sessions/base.py +31 -11
  335. ksadk/sessions/continuity.py +2 -3
  336. ksadk/sessions/in_memory.py +46 -2
  337. ksadk/sessions/local_service.py +148 -17
  338. ksadk/sessions/postgres_service.py +143 -25
  339. ksadk/sessions/resilient.py +36 -8
  340. ksadk/skills/models.py +17 -5
  341. ksadk/skills/package_store.py +5 -2
  342. ksadk/skills/runtime/agent.py +20 -5
  343. ksadk/skills/runtime/artifacts.py +1 -5
  344. ksadk/skills/runtime/backends/e2b.py +10 -4
  345. ksadk/skills/runtime/backends/local.py +15 -3
  346. ksadk/skills/runtime/base.py +1 -2
  347. ksadk/skills/runtime/executor.py +10 -3
  348. ksadk/skills/runtime/factory.py +4 -2
  349. ksadk/skills/runtime/loader.py +1 -2
  350. ksadk/skills/runtime/registry.py +15 -10
  351. ksadk/skills/runtime/request.py +3 -1
  352. ksadk/skills/service_client.py +47 -16
  353. ksadk/skills/tool_defs.py +15 -10
  354. ksadk/studio/__init__.py +5 -0
  355. ksadk/studio/agent_avatar_assets.py +120 -0
  356. ksadk/studio/agent_lifecycle.py +51 -0
  357. ksadk/studio/api.py +1046 -0
  358. ksadk/studio/api_catalog_routes.py +324 -0
  359. ksadk/studio/api_contracts.py +177 -0
  360. ksadk/studio/api_helpers.py +132 -0
  361. ksadk/studio/authoring.py +524 -0
  362. ksadk/studio/authoring_coordinator.py +285 -0
  363. ksadk/studio/builder.py +320 -0
  364. ksadk/studio/capabilities.py +351 -0
  365. ksadk/studio/cloud.py +278 -0
  366. ksadk/studio/codex_agent_service.py +583 -0
  367. ksadk/studio/codex_builder.py +324 -0
  368. ksadk/studio/codex_manifest.py +278 -0
  369. ksadk/studio/codex_run.py +352 -0
  370. ksadk/studio/compiler.py +189 -0
  371. ksadk/studio/contracts.py +644 -0
  372. ksadk/studio/errors.py +47 -0
  373. ksadk/studio/evaluation.py +192 -0
  374. ksadk/studio/event_store.py +284 -0
  375. ksadk/studio/framework_run.py +114 -0
  376. ksadk/studio/identifiers.py +33 -0
  377. ksadk/studio/mcp_runtime.py +229 -0
  378. ksadk/studio/model_client.py +543 -0
  379. ksadk/studio/model_profile_service.py +214 -0
  380. ksadk/studio/operations.py +243 -0
  381. ksadk/studio/otel_trace.py +754 -0
  382. ksadk/studio/pagination.py +182 -0
  383. ksadk/studio/python_tool_inspection.py +183 -0
  384. ksadk/studio/repository.py +306 -0
  385. ksadk/studio/resource_catalog.py +1217 -0
  386. ksadk/studio/run_service.py +707 -0
  387. ksadk/studio/runtime_catalog.py +74 -0
  388. ksadk/studio/runtime_source.py +339 -0
  389. ksadk/studio/service.py +1141 -0
  390. ksadk/studio/shared_web.py +994 -0
  391. ksadk/studio/skill_discovery.py +628 -0
  392. ksadk/studio/static/assets/PrismRenderer-IYN-ffww.js +3 -0
  393. ksadk/studio/static/assets/index-CaEN0eTR.css +1 -0
  394. ksadk/studio/static/assets/index-DI2eY_NH.js +252 -0
  395. ksadk/studio/static/assets/react-vendor-BNmTiJ-I.js +9 -0
  396. ksadk/studio/static/assets/rolldown-runtime-hePW80VL.js +1 -0
  397. ksadk/studio/static/index.html +15 -0
  398. ksadk/studio/templates.py +630 -0
  399. ksadk/studio/validator.py +246 -0
  400. ksadk/studio/workspace.py +137 -0
  401. ksadk/terminal_exec_policy.py +3 -4
  402. ksadk/tools/gateway.py +101 -15
  403. ksadk/tools/result_budget.py +12 -4
  404. ksadk/toolsets/__init__.py +161 -37
  405. ksadk/toolsets/a2a.py +426 -0
  406. ksadk/toolsets/platform.py +21 -5
  407. ksadk/toolsets/sandbox.py +82 -16
  408. ksadk/toolsets/skills.py +200 -39
  409. ksadk/toolsets/web.py +123 -26
  410. ksadk/toolsets/workspace.py +212 -101
  411. ksadk/tracing/__init__.py +19 -21
  412. ksadk/tracing/exporters/inmemory_exporter.py +62 -51
  413. ksadk/tracing/setup.py +135 -506
  414. ksadk/tracing/span_utils.py +0 -41
  415. ksadk/tui/loop.py +78 -30
  416. ksadk/tui/stream_render.py +1 -0
  417. ksadk/ui_config.py +5 -3
  418. ksadk/version.py +1 -1
  419. ksadk_runtime_common/memory_backend/registry.py +56 -56
  420. ksadk_runtime_common/schemas/runtime_event_v1.json +95 -0
  421. ksadk_runtime_common/workspace_files/router.py +8 -2
  422. agentengine_sdk_python-0.7.0.dist-info/RECORD +0 -482
  423. ksadk/a2a/card_builder.py +0 -64
  424. ksadk/a2a/client.py +0 -309
  425. ksadk/runners/utils/langfuse.py +0 -230
  426. ksadk/server/static/assets/CodeBlock-P16VOLYi.js +0 -9
  427. ksadk/server/static/assets/MathMessageMarkdown-CdGiQWHR.js +0 -8
  428. ksadk/server/static/assets/MermaidBlock-IOcal8cm.js +0 -303
  429. ksadk/server/static/assets/NativeTerminalPanel-DGSDWsei.js +0 -1
  430. ksadk/server/static/assets/architecture-7EHR7CIX-BvUlsA6l.js +0 -1
  431. ksadk/server/static/assets/channel-CTuydARX.js +0 -1
  432. ksadk/server/static/assets/chunk-QZHKN3VN-BnCydivS.js +0 -1
  433. ksadk/server/static/assets/classDiagram-4FO5ZUOK-BNHg45Be.js +0 -1
  434. ksadk/server/static/assets/classDiagram-v2-Q7XG4LA2-BNHg45Be.js +0 -1
  435. ksadk/server/static/assets/eventmodeling-FCH6USID-DsAgWnlf.js +0 -1
  436. ksadk/server/static/assets/gitGraph-WXDBUCRP-BIao9Yjg.js +0 -1
  437. ksadk/server/static/assets/index-C00Lwg3L.js +0 -165
  438. ksadk/server/static/assets/index-DAURbCsP.css +0 -1
  439. ksadk/server/static/assets/info-J43DQDTF-CyipqGxU.js +0 -1
  440. ksadk/server/static/assets/packet-YPE3B663-CGkyRxlg.js +0 -1
  441. ksadk/server/static/assets/pie-LRSECV5Y-M0uWAf4n.js +0 -1
  442. ksadk/server/static/assets/radar-GUYGQ44K-Bdbm24-x.js +0 -1
  443. ksadk/server/static/assets/stateDiagram-v2-BHNVJYJU-8xBN_gLM.js +0 -1
  444. ksadk/server/static/assets/treeView-BLDUP644-npMo0ak1.js +0 -1
  445. ksadk/server/static/assets/treemap-LRROVOQU-CHdzrrdo.js +0 -1
  446. ksadk/server/static/assets/wardley-L42UT6IY-BEQz7wyy.js +0 -1
  447. ksadk/tracing/exporters/langfuse_exporter.py +0 -445
  448. {agentengine_sdk_python-0.7.0.dist-info → agentengine_sdk_python-0.8.1.dist-info}/entry_points.txt +0 -0
  449. {agentengine_sdk_python-0.7.0.dist-info → agentengine_sdk_python-0.8.1.dist-info}/licenses/LICENSE +0 -0
  450. {agentengine_sdk_python-0.7.0.dist-info → agentengine_sdk_python-0.8.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,848 @@
1
+ """Session event projection, pagination, and checkpoint policy helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import logging
7
+ from collections.abc import AsyncIterator, Mapping
8
+ from datetime import datetime, timezone
9
+ from typing import Any, Optional, cast
10
+
11
+ from fastapi import HTTPException
12
+
13
+ from ksadk.conversations.session_title import (
14
+ HEURISTIC_SESSION_TITLE_SOURCE,
15
+ build_fallback_title,
16
+ build_heuristic_title,
17
+ )
18
+ from ksadk.events.runtime_event import EventType
19
+ from ksadk.server.factory import get_runtime_execution, get_state
20
+ from ksadk.sessions import Session, SessionEvent
21
+
22
+ from . import dependencies as deps
23
+ from .common import _sanitize_session_state_for_action
24
+ from .models import (
25
+ _EVENT_SCAN_PAGE_SIZE,
26
+ _latest_session_run_metadata,
27
+ _parse_iso_datetime,
28
+ _session_topic_from_events,
29
+ _session_user_prompt_from_event,
30
+ _truncate_session_text,
31
+ )
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+
36
+ async def _require_action_session(
37
+ service,
38
+ *,
39
+ session_id: str,
40
+ agent_id: Optional[str] = None,
41
+ user_id: Optional[str] = None,
42
+ ) -> Session:
43
+ """Resolve one runtime session while enforcing every supplied scope."""
44
+
45
+ session = await service.get_session_metadata(str(session_id or "").strip())
46
+ if (
47
+ session is None
48
+ or (agent_id is not None and session.agent_id != agent_id)
49
+ or (user_id is not None and session.user_id != user_id)
50
+ ):
51
+ raise HTTPException(status_code=404, detail="Session not found")
52
+ return cast(Session, session)
53
+
54
+
55
+ async def _session_to_action_payload(session: Session) -> dict[str, Any]:
56
+ events = list(session.events or [])
57
+ if not events:
58
+ try:
59
+ events = await deps.resolve_session_service().get_events(session.id)
60
+ except Exception as exc:
61
+ logger.debug("Failed to hydrate events for session %s: %s", session.id, exc)
62
+ events = []
63
+ event_prompts = [
64
+ _session_user_prompt_from_event(event)
65
+ for event in events
66
+ if event.event_type == "user_message"
67
+ ]
68
+ event_prompts = [prompt for prompt in event_prompts if prompt]
69
+ first_prompt = session.first_prompt or (event_prompts[0] if event_prompts else "")
70
+ last_prompt = session.last_prompt or (event_prompts[-1] if event_prompts else "")
71
+ (
72
+ active_invocation_id,
73
+ active_run_status,
74
+ active_run_mode,
75
+ active_run_trigger,
76
+ ) = _latest_session_run_metadata(events)
77
+ title = session.title
78
+ title_source = session.title_source
79
+ if not title:
80
+ title_seed = _session_topic_from_events(events) or first_prompt
81
+ if title_seed:
82
+ title = build_fallback_title(title_seed)
83
+ title_source = "fallback_first_prompt"
84
+ if title_source == "fallback_first_prompt":
85
+ heuristic = build_heuristic_title(
86
+ first_prompt=first_prompt or title,
87
+ assistant_text=session.summary or "",
88
+ )
89
+ if heuristic and heuristic != title:
90
+ title = heuristic
91
+ title_source = HEURISTIC_SESSION_TITLE_SOURCE
92
+ payload = {
93
+ "SessionId": session.id,
94
+ "AgentId": session.agent_id,
95
+ "UserId": session.user_id,
96
+ "Title": title,
97
+ "TitleSource": title_source,
98
+ "Summary": session.summary,
99
+ "FirstPrompt": _truncate_session_text(first_prompt),
100
+ "LastPrompt": _truncate_session_text(last_prompt),
101
+ "ActiveInvocationId": active_invocation_id,
102
+ "ActiveRunStatus": active_run_status,
103
+ "ActiveRunMode": active_run_mode,
104
+ "ActiveRunTrigger": active_run_trigger,
105
+ "State": _sanitize_session_state_for_action(session.state),
106
+ "CreatedAt": session.created_at,
107
+ "UpdatedAt": session.updated_at,
108
+ "Version": session.version,
109
+ "Continuity": _runtime_continuity_payload(),
110
+ }
111
+ return payload
112
+
113
+
114
+ def _runtime_continuity_payload() -> dict[str, Any]:
115
+ """Describe continuity from the active RuntimeAdapter capability contract."""
116
+
117
+ state = get_state()
118
+ if state.executor is None or state.launch_context is None:
119
+ # Session storage is independently useful in route-manifest and
120
+ # control-plane-only apps. Do not make a metadata projection require a
121
+ # live runtime execution binding.
122
+ return {
123
+ "Level": "semantic",
124
+ "Path": "replay",
125
+ "Runtime": "unbound",
126
+ "Details": {
127
+ "CheckpointSupported": False,
128
+ "Reason": "RuntimeAdapter is not bound to this app",
129
+ },
130
+ }
131
+ executor, launch_context = get_runtime_execution()
132
+ capabilities = executor.native_capabilities(launch_context)
133
+ continuity = capabilities.get("SessionContinuity")
134
+ continuity = continuity if isinstance(continuity, Mapping) else {}
135
+ checkpoint = capabilities.get("Checkpoint")
136
+ checkpoint = checkpoint if isinstance(checkpoint, Mapping) else {}
137
+ level = str(continuity.get("Level") or "semantic").strip().lower()
138
+ if level not in {"ui_only", "semantic", "runtime", "exact"}:
139
+ level = "semantic"
140
+ return {
141
+ "Level": level,
142
+ "Path": "checkpoint" if checkpoint.get("Supported") else "replay",
143
+ "Runtime": launch_context.runtime_type,
144
+ "Details": {
145
+ "CheckpointSupported": bool(checkpoint.get("Supported")),
146
+ "Reason": str(continuity.get("Reason") or ""),
147
+ },
148
+ }
149
+
150
+
151
+ def _event_to_action_payload(event: SessionEvent) -> dict[str, Any]:
152
+ payload = {
153
+ "EventId": event.id,
154
+ "SessionId": event.session_id,
155
+ "Author": event.author,
156
+ "EventType": event.event_type,
157
+ "Content": event.content,
158
+ "Timestamp": event.timestamp,
159
+ "SeqId": event.seq_id,
160
+ "Metadata": event.metadata,
161
+ }
162
+ if event.invocation_id:
163
+ payload["InvocationId"] = event.invocation_id
164
+ return payload
165
+
166
+
167
+ async def _iter_with_idle_heartbeat(source: AsyncIterator[Any]):
168
+ """转发 source 的 chunk,空闲超时发 ``: ping`` 而不取消 source 迭代器。
169
+
170
+ 直接用 ``asyncio.wait_for(source.__anext__(), timeout=...)`` 会在超时时 cancel
171
+ 掉正在进行的 ``__anext__()``;若 source 是原生 async generator,cancel 会触发
172
+ GeneratorExit 把它关闭,下一轮 ``__anext__`` 抛 StopAsyncIteration → 流提前断。
173
+ 用 pump task + queue 隔离:pump 独立消费 source,主循环只对 queue.get() 计时,
174
+ 超时时发心跳而不碰 source。
175
+ """
176
+ queue: asyncio.Queue[Any] = asyncio.Queue(maxsize=1)
177
+
178
+ async def pump() -> None:
179
+ async for chunk in source:
180
+ await queue.put(chunk)
181
+
182
+ pump_task = asyncio.create_task(pump())
183
+ get_task: asyncio.Task[Any] | None = None
184
+ try:
185
+ while True:
186
+ # Drain queued data before observing producer completion so a final
187
+ # chunk is never lost when the producer exits immediately after it.
188
+ if not queue.empty():
189
+ yield ("chunk", queue.get_nowait())
190
+ continue
191
+ if pump_task.done():
192
+ pump_task.result()
193
+ return
194
+
195
+ get_task = asyncio.create_task(queue.get())
196
+ done, _ = await asyncio.wait(
197
+ {get_task, pump_task},
198
+ timeout=deps.heartbeat_interval(),
199
+ return_when=asyncio.FIRST_COMPLETED,
200
+ )
201
+ if get_task in done:
202
+ chunk = get_task.result()
203
+ get_task = None
204
+ yield ("chunk", chunk)
205
+ continue
206
+ if pump_task in done:
207
+ # The final queue.put() may have completed in the same loop turn
208
+ # as the producer. Let the pending getter consume it first.
209
+ if not queue.empty():
210
+ chunk = await get_task
211
+ get_task = None
212
+ yield ("chunk", chunk)
213
+ continue
214
+ get_task.cancel()
215
+ await asyncio.gather(get_task, return_exceptions=True)
216
+ get_task = None
217
+ pump_task.result()
218
+ return
219
+
220
+ get_task.cancel()
221
+ await asyncio.gather(get_task, return_exceptions=True)
222
+ get_task = None
223
+ yield ("heartbeat", None)
224
+ finally:
225
+ if get_task is not None and not get_task.done():
226
+ get_task.cancel()
227
+ await asyncio.gather(get_task, return_exceptions=True)
228
+ if not pump_task.done():
229
+ pump_task.cancel()
230
+ await asyncio.gather(pump_task, return_exceptions=True)
231
+
232
+
233
+ def _checkpoint_event_to_action_payload(event: SessionEvent) -> dict[str, Any] | None:
234
+ if event.event_type == "run_checkpoint":
235
+ metadata = event.metadata or {}
236
+ elif event.event_type == EventType.CHECKPOINT_CREATED:
237
+ content = event.content or {}
238
+ payload = content.get("payload") if isinstance(content, Mapping) else {}
239
+ if not isinstance(payload, Mapping):
240
+ return None
241
+ framework_ref = payload.get("framework_ref") or payload.get("resume_target") or {}
242
+ if not isinstance(framework_ref, Mapping):
243
+ framework_ref = {}
244
+ framework = str(payload.get("framework") or "").strip()
245
+ if not framework and len(framework_ref) == 1:
246
+ framework = str(next(iter(framework_ref)))
247
+ capability = payload.get("capability")
248
+ capability = capability if isinstance(capability, Mapping) else {}
249
+ metadata = {
250
+ **dict(event.metadata or {}),
251
+ "run_id": str(payload.get("run_id") or event.invocation_id or ""),
252
+ "checkpoint_id": str(payload.get("checkpoint_id") or ""),
253
+ "framework": framework,
254
+ "framework_ref": dict(framework_ref),
255
+ "backend": str(payload.get("backend") or capability.get("backend") or "unknown"),
256
+ "scope": str(payload.get("scope") or capability.get("scope") or "unknown"),
257
+ "durable": bool(payload.get("durable", capability.get("durable", False))),
258
+ "is_resumable": bool(payload.get("is_resumable", True)),
259
+ }
260
+ else:
261
+ return None
262
+ run_id = str(metadata.get("run_id") or "").strip()
263
+ checkpoint_id = str(metadata.get("checkpoint_id") or "").strip()
264
+ framework = str(metadata.get("framework") or "").strip()
265
+ framework_ref = metadata.get("framework_ref")
266
+ if not run_id or not checkpoint_id or not framework or not isinstance(framework_ref, Mapping):
267
+ return None
268
+ next_node = str(metadata.get("next_node") or "").strip()
269
+ if not next_node:
270
+ langgraph_ref = framework_ref.get("langgraph")
271
+ if isinstance(langgraph_ref, Mapping):
272
+ next_node = str(langgraph_ref.get("next_node") or "").strip()
273
+ is_terminal = bool(metadata.get("is_terminal", False))
274
+ is_resumable_raw = metadata.get("is_resumable")
275
+ is_resumable = is_resumable_raw if isinstance(is_resumable_raw, bool) else None
276
+ backend = str(metadata.get("backend") or "unknown").strip() or "unknown"
277
+ scope = str(metadata.get("scope") or "unknown").strip() or "unknown"
278
+ durable = bool(metadata.get("durable", False))
279
+ disabled_reason = str(metadata.get("resume_disabled_reason") or "").strip()
280
+ if is_terminal:
281
+ is_resumable = False
282
+ disabled_reason = disabled_reason or "该 checkpoint 已是终态;可选择更早恢复点重跑"
283
+ if backend == "memory" or scope == "process_local":
284
+ is_resumable = False
285
+ disabled_reason = disabled_reason or "进程内 checkpoint 不能跨实例恢复"
286
+ resume_status = str(metadata.get("resume_status") or "").strip()
287
+ if not resume_status:
288
+ if is_resumable is True:
289
+ resume_status = "resumable"
290
+ elif is_resumable is False:
291
+ resume_status = "disabled"
292
+ else:
293
+ resume_status = "unknown"
294
+ if resume_status == "disabled" and not disabled_reason:
295
+ disabled_reason = "该 checkpoint 不可恢复"
296
+ artifact_preview = metadata.get("artifact_preview")
297
+ if not isinstance(artifact_preview, Mapping):
298
+ artifact_preview = {}
299
+ resume_count_raw = metadata.get("resume_count")
300
+ try:
301
+ resume_count = int(resume_count_raw) if resume_count_raw is not None else 0
302
+ except (TypeError, ValueError):
303
+ resume_count = 0
304
+ last_resumed_at = metadata.get("last_resumed_at")
305
+ replay_allowed_raw = metadata.get("replay_allowed")
306
+ replay_allowed = replay_allowed_raw if isinstance(replay_allowed_raw, bool) else True
307
+ expires_at = metadata.get("expires_at")
308
+ checkpoint_status = str(metadata.get("checkpoint_status") or "").strip()
309
+ if not checkpoint_status:
310
+ if is_terminal:
311
+ checkpoint_status = "resumed" if resume_count else "terminal"
312
+ elif is_resumable is False:
313
+ checkpoint_status = "disabled"
314
+ else:
315
+ checkpoint_status = "active"
316
+ payload = {
317
+ "EventId": event.id,
318
+ "SessionId": event.session_id,
319
+ "InvocationId": event.invocation_id,
320
+ "SeqId": event.seq_id,
321
+ "Timestamp": event.timestamp,
322
+ "RunId": run_id,
323
+ "CheckpointId": checkpoint_id,
324
+ "Framework": framework,
325
+ "FrameworkRef": dict(framework_ref),
326
+ "Phase": str(metadata.get("phase") or ""),
327
+ "Metadata": metadata,
328
+ "IsResumable": is_resumable,
329
+ "ResumeStatus": resume_status,
330
+ "IsTerminal": is_terminal,
331
+ "ResumeDisabledReason": disabled_reason,
332
+ "NextNode": next_node,
333
+ "StageKey": str(metadata.get("stage_key") or ""),
334
+ "StageName": str(
335
+ metadata.get("stage_name") or metadata.get("stage") or metadata.get("title") or ""
336
+ ),
337
+ "StageIndex": metadata.get("stage_index"),
338
+ "TotalStages": metadata.get("total_stages"),
339
+ "Backend": backend,
340
+ "Scope": scope,
341
+ "Durable": durable,
342
+ "CreatedAt": event.timestamp,
343
+ "ArtifactPreview": dict(artifact_preview),
344
+ "LastResumedAt": last_resumed_at,
345
+ "ResumeCount": resume_count,
346
+ "ReplayAllowed": replay_allowed,
347
+ "ExpiresAt": expires_at,
348
+ "CheckpointStatus": checkpoint_status,
349
+ }
350
+ stage = str(metadata.get("stage") or metadata.get("title") or "").strip()
351
+ summary = str(metadata.get("summary") or metadata.get("description") or "").strip()
352
+ next_action = str(metadata.get("next_action") or metadata.get("nextAction") or "").strip()
353
+ status = str(metadata.get("status") or "").strip()
354
+ if stage:
355
+ payload["Stage"] = stage
356
+ if summary:
357
+ payload["Summary"] = summary
358
+ if next_action:
359
+ payload["NextAction"] = next_action
360
+ if status:
361
+ payload["Status"] = status
362
+ return payload
363
+
364
+
365
+ def _resume_audit_by_checkpoint(
366
+ events: list[SessionEvent],
367
+ ) -> dict[tuple[str, str], dict[str, Any]]:
368
+ audit: dict[tuple[str, str], dict[str, Any]] = {}
369
+ for event in events:
370
+ if event.event_type != "run_resume":
371
+ continue
372
+ metadata = event.metadata or {}
373
+ run_id = str(metadata.get("run_id") or "").strip()
374
+ checkpoint_id = str(metadata.get("checkpoint_id") or "").strip()
375
+ if not run_id or not checkpoint_id:
376
+ continue
377
+ key = (run_id, checkpoint_id)
378
+ item = audit.setdefault(key, {"resume_count": 0, "last_resumed_at": None})
379
+ item["resume_count"] = int(item["resume_count"]) + 1
380
+ item["last_resumed_at"] = event.timestamp
381
+ return audit
382
+
383
+
384
+ def _apply_checkpoint_resume_audit(
385
+ checkpoint: dict[str, Any],
386
+ audit_by_checkpoint: Mapping[tuple[str, str], Mapping[str, Any]],
387
+ ) -> dict[str, Any]:
388
+ audit = audit_by_checkpoint.get(
389
+ (
390
+ str(checkpoint.get("RunId") or ""),
391
+ str(checkpoint.get("CheckpointId") or ""),
392
+ ),
393
+ {},
394
+ )
395
+ metadata = dict(checkpoint.get("Metadata") or {})
396
+ resume_count = int(audit.get("resume_count") or checkpoint.get("ResumeCount") or 0)
397
+ last_resumed_at = audit.get("last_resumed_at") or checkpoint.get("LastResumedAt")
398
+ checkpoint["ResumeCount"] = resume_count
399
+ checkpoint["LastResumedAt"] = last_resumed_at
400
+ metadata["resume_count"] = resume_count
401
+ metadata["last_resumed_at"] = last_resumed_at
402
+ if resume_count and checkpoint.get("CheckpointStatus") in {"", "active"}:
403
+ checkpoint["CheckpointStatus"] = "resumed"
404
+ expires_at = checkpoint.get("ExpiresAt")
405
+ expires_at_dt = _parse_iso_datetime(expires_at)
406
+ if expires_at_dt is not None and expires_at_dt <= datetime.now(timezone.utc):
407
+ checkpoint["IsResumable"] = False
408
+ checkpoint["ResumeStatus"] = "disabled"
409
+ checkpoint["CheckpointStatus"] = "expired"
410
+ checkpoint["ResumeDisabledReason"] = "该 checkpoint 已过期"
411
+ elif resume_count and checkpoint.get("ReplayAllowed") is False:
412
+ checkpoint["IsResumable"] = False
413
+ checkpoint["ResumeStatus"] = "disabled"
414
+ checkpoint["ResumeDisabledReason"] = "该 checkpoint 已恢复过,当前策略不允许重复恢复"
415
+ metadata["checkpoint_status"] = checkpoint.get("CheckpointStatus")
416
+ metadata["resume_status"] = checkpoint.get("ResumeStatus")
417
+ metadata["resume_disabled_reason"] = checkpoint.get("ResumeDisabledReason")
418
+ checkpoint["Metadata"] = metadata
419
+ return checkpoint
420
+
421
+
422
+ def _apply_adk_only_latest_resumable(
423
+ checkpoints: list[dict[str, Any]],
424
+ ) -> list[dict[str, Any]]:
425
+ """P1.4: For ADK invocation_id resume mode, only the latest checkpoint per
426
+ RunId is independently resumable. Older checkpoints get IsResumable=False."""
427
+ latest_by_run: dict[str, int] = {}
428
+ for cp in checkpoints:
429
+ metadata = cp.get("Metadata") or {}
430
+ if not metadata.get("only_latest_resumable"):
431
+ continue
432
+ run_id = str(cp.get("RunId") or "")
433
+ seq_id = int(cp.get("SeqId") or 0)
434
+ if run_id not in latest_by_run or seq_id > latest_by_run[run_id]:
435
+ latest_by_run[run_id] = seq_id
436
+
437
+ for cp in checkpoints:
438
+ metadata = cp.get("Metadata") or {}
439
+ if not metadata.get("only_latest_resumable"):
440
+ continue
441
+ run_id = str(cp.get("RunId") or "")
442
+ seq_id = int(cp.get("SeqId") or 0)
443
+ if seq_id < latest_by_run.get(run_id, 0):
444
+ if cp.get("IsResumable") is True:
445
+ cp["IsResumable"] = False
446
+ cp["ResumeStatus"] = "disabled"
447
+ cp["ResumeDisabledReason"] = "新的恢复点已生成,此恢复点暂停恢复能力"
448
+ metadata["resume_disabled_reason"] = "新的恢复点已生成,此恢复点暂停恢复能力"
449
+ metadata["resume_status"] = "disabled"
450
+ cp["Metadata"] = metadata
451
+
452
+ return checkpoints
453
+
454
+
455
+ def _check_adk_latest_resumable(
456
+ checkpoint: dict[str, Any],
457
+ events: list,
458
+ ) -> dict[str, Any]:
459
+ """P1.4: For a single ADK only_latest_resumable checkpoint, verify it is
460
+ the latest for its RunId. If not, mark IsResumable=False."""
461
+ metadata = checkpoint.get("Metadata") or {}
462
+ if not metadata.get("only_latest_resumable"):
463
+ return checkpoint
464
+
465
+ run_id = str(checkpoint.get("RunId") or "")
466
+ my_seq_id = int(checkpoint.get("SeqId") or 0)
467
+
468
+ max_seq_id = my_seq_id
469
+ for event in events:
470
+ if event.event_type != "run_checkpoint":
471
+ continue
472
+ ev_meta = event.metadata or {}
473
+ if str(ev_meta.get("run_id") or "") != run_id:
474
+ continue
475
+ seq_id = int(event.seq_id or 0)
476
+ if seq_id > max_seq_id:
477
+ max_seq_id = seq_id
478
+
479
+ if my_seq_id < max_seq_id and checkpoint.get("IsResumable") is True:
480
+ checkpoint["IsResumable"] = False
481
+ checkpoint["ResumeStatus"] = "disabled"
482
+ checkpoint["ResumeDisabledReason"] = "新的恢复点已生成,此恢复点暂停恢复能力"
483
+ metadata["resume_disabled_reason"] = "新的恢复点已生成,此恢复点暂停恢复能力"
484
+ metadata["resume_status"] = "disabled"
485
+ checkpoint["Metadata"] = metadata
486
+
487
+ return checkpoint
488
+
489
+
490
+ _SIDE_EFFECT_TOOL_NAMES = {
491
+ "write_workspace_file",
492
+ "write_workspace_files",
493
+ "delete_workspace_file",
494
+ "execute_skills",
495
+ "run_command",
496
+ "run_code",
497
+ }
498
+
499
+
500
+ def _tool_receipt_event_to_action_payload(event: SessionEvent) -> dict[str, Any] | None:
501
+ if event.event_type != "tool_result":
502
+ return None
503
+ metadata = event.metadata or {}
504
+ receipt = metadata.get("tool_receipt")
505
+ if not isinstance(receipt, Mapping):
506
+ return None
507
+ tool_name = str(receipt.get("tool_name") or metadata.get("tool_name") or "").strip()
508
+ if not tool_name:
509
+ return None
510
+ return {
511
+ "EventId": event.id,
512
+ "SessionId": event.session_id,
513
+ "InvocationId": event.invocation_id,
514
+ "SeqId": event.seq_id,
515
+ "Timestamp": event.timestamp,
516
+ "ReceiptId": str(receipt.get("receipt_id") or ""),
517
+ "IdempotencyKey": str(receipt.get("idempotency_key") or ""),
518
+ "ToolName": tool_name,
519
+ "ToolCallId": str(receipt.get("tool_call_id") or ""),
520
+ "RunId": str(receipt.get("run_id") or metadata.get("run_id") or ""),
521
+ "CheckpointId": str(receipt.get("checkpoint_id") or ""),
522
+ "Status": str(receipt.get("status") or ""),
523
+ "Replayed": bool(receipt.get("replayed") or metadata.get("replayed")),
524
+ "Metadata": dict(metadata),
525
+ }
526
+
527
+
528
+ def _build_checkpoint_resume_preview(
529
+ *,
530
+ checkpoint: Mapping[str, Any],
531
+ receipts: list[dict[str, Any]],
532
+ receipt_total: int,
533
+ side_effect_receipt_count: int,
534
+ failed_receipt_count: int,
535
+ ) -> dict[str, Any]:
536
+ run_id = str(checkpoint.get("RunId") or "")
537
+ risk_level = "low"
538
+ if side_effect_receipt_count:
539
+ risk_level = "medium"
540
+ if failed_receipt_count:
541
+ risk_level = "high"
542
+
543
+ return {
544
+ "Checkpoint": dict(checkpoint),
545
+ "Capabilities": {
546
+ "Checkpoints": True,
547
+ "CheckpointResume": checkpoint.get("IsResumable") is not False,
548
+ "ToolReceipts": True,
549
+ "IdempotentToolReplay": True,
550
+ },
551
+ "CanResume": checkpoint.get("IsResumable") is not False,
552
+ "Reason": str(checkpoint.get("ResumeDisabledReason") or ""),
553
+ "NextNode": str(checkpoint.get("NextNode") or ""),
554
+ "ExpectedAction": (
555
+ "resume_from_checkpoint"
556
+ if checkpoint.get("IsResumable") is True
557
+ else ("preview_required" if checkpoint.get("ResumeStatus") == "unknown" else "disabled")
558
+ ),
559
+ "ToolReceipts": receipts,
560
+ "ToolReceiptsTruncated": receipt_total > len(receipts),
561
+ "Risk": {
562
+ "Level": risk_level,
563
+ "DuplicateSideEffectRisk": side_effect_receipt_count > 0,
564
+ "SideEffectReceiptCount": side_effect_receipt_count,
565
+ "FailedReceiptCount": failed_receipt_count,
566
+ },
567
+ "Summary": {
568
+ "RunId": run_id,
569
+ "CheckpointId": str(checkpoint.get("CheckpointId") or ""),
570
+ "Phase": str(checkpoint.get("Phase") or ""),
571
+ "ToolReceiptCount": receipt_total,
572
+ },
573
+ }
574
+
575
+
576
+ def _checkpoint_resume_disabled_detail(checkpoint: Mapping[str, Any]) -> dict[str, Any] | None:
577
+ if checkpoint.get("IsResumable") is not False:
578
+ return None
579
+ reason = (
580
+ str(checkpoint.get("ResumeDisabledReason") or "").strip() or "Checkpoint is not resumable"
581
+ )
582
+ return {
583
+ "code": "checkpoint_not_resumable",
584
+ "reason": reason,
585
+ "checkpoint_id": str(checkpoint.get("CheckpointId") or ""),
586
+ "run_id": str(checkpoint.get("RunId") or ""),
587
+ "resume_status": str(checkpoint.get("ResumeStatus") or "disabled"),
588
+ "is_terminal": bool(checkpoint.get("IsTerminal")),
589
+ }
590
+
591
+
592
+ async def _iter_session_event_pages(
593
+ service: Any,
594
+ session_id: str,
595
+ *,
596
+ after_seq_id: int | None = None,
597
+ before_seq_id: int | None = None,
598
+ ) -> AsyncIterator[list[SessionEvent]]:
599
+ remaining = await service.count_events(
600
+ session_id,
601
+ after_seq_id=after_seq_id,
602
+ before_seq_id=before_seq_id,
603
+ )
604
+ while remaining > 0:
605
+ page_size = min(_EVENT_SCAN_PAGE_SIZE, remaining)
606
+ page = await service.get_events(
607
+ session_id,
608
+ offset=remaining - page_size,
609
+ limit=page_size,
610
+ after_seq_id=after_seq_id,
611
+ before_seq_id=before_seq_id,
612
+ )
613
+ if not page:
614
+ return
615
+ yield page
616
+ remaining -= len(page)
617
+
618
+
619
+ def _event_invocation_id(event: SessionEvent) -> str:
620
+ return str(event.invocation_id or "").strip()
621
+
622
+
623
+ async def _extend_invocation_before_window(
624
+ service: Any,
625
+ session_id: str,
626
+ events: list[SessionEvent],
627
+ *,
628
+ after_seq_id: int | None,
629
+ ) -> list[SessionEvent]:
630
+ if not events:
631
+ return events
632
+ invocation_id = _event_invocation_id(events[0])
633
+ if not invocation_id:
634
+ return events
635
+ cursor = int(events[0].seq_id or 0)
636
+ prefix: list[SessionEvent] = []
637
+ while cursor > 0:
638
+ page = await service.get_events(
639
+ session_id,
640
+ limit=_EVENT_SCAN_PAGE_SIZE,
641
+ after_seq_id=after_seq_id,
642
+ before_seq_id=cursor,
643
+ )
644
+ if not page:
645
+ break
646
+ matching_suffix: list[SessionEvent] = []
647
+ for event in reversed(page):
648
+ if _event_invocation_id(event) != invocation_id:
649
+ break
650
+ matching_suffix.append(event)
651
+ if not matching_suffix:
652
+ break
653
+ matching_suffix.reverse()
654
+ prefix[0:0] = matching_suffix
655
+ cursor = int(matching_suffix[0].seq_id or 0)
656
+ if len(matching_suffix) < len(page):
657
+ break
658
+ return [*prefix, *events]
659
+
660
+
661
+ async def _extend_invocation_after_window(
662
+ service: Any,
663
+ session_id: str,
664
+ events: list[SessionEvent],
665
+ *,
666
+ before_seq_id: int | None,
667
+ ) -> list[SessionEvent]:
668
+ if not events:
669
+ return events
670
+ invocation_id = _event_invocation_id(events[-1])
671
+ if not invocation_id:
672
+ return events
673
+ cursor = int(events[-1].seq_id or 0)
674
+ suffix: list[SessionEvent] = []
675
+ while True:
676
+ remaining = await service.count_events(
677
+ session_id,
678
+ after_seq_id=cursor,
679
+ before_seq_id=before_seq_id,
680
+ )
681
+ if remaining <= 0:
682
+ break
683
+ page_size = min(_EVENT_SCAN_PAGE_SIZE, remaining)
684
+ page = await service.get_events(
685
+ session_id,
686
+ offset=remaining - page_size,
687
+ limit=page_size,
688
+ after_seq_id=cursor,
689
+ before_seq_id=before_seq_id,
690
+ )
691
+ if not page:
692
+ break
693
+ matching_prefix: list[SessionEvent] = []
694
+ for event in page:
695
+ if _event_invocation_id(event) != invocation_id:
696
+ break
697
+ matching_prefix.append(event)
698
+ if not matching_prefix:
699
+ break
700
+ suffix.extend(matching_prefix)
701
+ cursor = int(matching_prefix[-1].seq_id or 0)
702
+ if len(matching_prefix) < len(page):
703
+ break
704
+ return [*events, *suffix]
705
+
706
+
707
+ async def _iter_agent_event_pages(
708
+ service: Any,
709
+ agent_id: str,
710
+ *,
711
+ user_id: str | None = None,
712
+ ) -> AsyncIterator[list[SessionEvent]]:
713
+ remaining = await service.count_events_for_agent(agent_id, user_id=user_id)
714
+ while remaining > 0:
715
+ page_size = min(_EVENT_SCAN_PAGE_SIZE, remaining)
716
+ page = await service.get_events_for_agent(
717
+ agent_id,
718
+ user_id=user_id,
719
+ offset=remaining - page_size,
720
+ limit=page_size,
721
+ )
722
+ if not page:
723
+ return
724
+ yield page
725
+ remaining -= len(page)
726
+
727
+
728
+ async def _iter_scoped_event_pages(
729
+ service: Any,
730
+ *,
731
+ session_id: str | None,
732
+ agent_id: str,
733
+ user_id: str | None,
734
+ ) -> AsyncIterator[list[SessionEvent]]:
735
+ if session_id:
736
+ async for page in _iter_session_event_pages(service, session_id):
737
+ yield page
738
+ return
739
+ async for page in _iter_agent_event_pages(service, agent_id, user_id=user_id):
740
+ yield page
741
+
742
+
743
+ async def _session_contains_invocation(
744
+ service: Any,
745
+ session_id: str,
746
+ invocation_id: str,
747
+ ) -> bool:
748
+ async for page in _iter_session_event_pages(service, session_id):
749
+ if any(event.invocation_id == invocation_id for event in page):
750
+ return True
751
+ return False
752
+
753
+
754
+ async def _agent_contains_invocation(
755
+ service: Any,
756
+ agent_id: str,
757
+ invocation_id: str,
758
+ *,
759
+ user_id: str | None,
760
+ ) -> bool:
761
+ async for page in _iter_agent_event_pages(service, agent_id, user_id=user_id):
762
+ if any(event.invocation_id == invocation_id for event in page):
763
+ return True
764
+ return False
765
+
766
+
767
+ async def _latest_invocation_status(
768
+ service: Any,
769
+ session_id: str,
770
+ invocation_id: str,
771
+ ) -> str:
772
+ offset = 0
773
+ total = await service.count_events(session_id)
774
+ while offset < total:
775
+ page = await service.get_events(
776
+ session_id,
777
+ offset=offset,
778
+ limit=min(_EVENT_SCAN_PAGE_SIZE, total - offset),
779
+ )
780
+ if not page:
781
+ break
782
+ for event in reversed(page):
783
+ if event.invocation_id != invocation_id or event.event_type != "run_status":
784
+ continue
785
+ return str((event.content or {}).get("status") or "").strip().lower()
786
+ offset += len(page)
787
+ return ""
788
+
789
+
790
+ async def _oldest_unconsumed_session_events(
791
+ service: Any,
792
+ session_id: str,
793
+ *,
794
+ after_seq_id: int,
795
+ ) -> list[SessionEvent]:
796
+ remaining = await service.count_events(session_id, after_seq_id=after_seq_id)
797
+ if remaining <= 0:
798
+ return []
799
+ page_size = min(_EVENT_SCAN_PAGE_SIZE, remaining)
800
+ events = await service.get_events(
801
+ session_id,
802
+ offset=remaining - page_size,
803
+ limit=page_size,
804
+ after_seq_id=after_seq_id,
805
+ )
806
+ return list(events)
807
+
808
+
809
+ def _record_resume_audit(
810
+ audit_by_session: dict[str, dict[tuple[str, str], dict[str, Any]]],
811
+ event: SessionEvent,
812
+ ) -> None:
813
+ if event.event_type != "run_resume":
814
+ return
815
+ metadata = event.metadata or {}
816
+ run_id = str(metadata.get("run_id") or "").strip()
817
+ checkpoint_id = str(metadata.get("checkpoint_id") or "").strip()
818
+ if not run_id or not checkpoint_id:
819
+ return
820
+ session_audit = audit_by_session.setdefault(event.session_id, {})
821
+ item = session_audit.setdefault(
822
+ (run_id, checkpoint_id),
823
+ {"resume_count": 0, "last_resumed_at": None},
824
+ )
825
+ item["resume_count"] = int(item["resume_count"]) + 1
826
+ item["last_resumed_at"] = event.timestamp
827
+
828
+
829
+ def _apply_latest_checkpoint_policy(
830
+ checkpoint: dict[str, Any],
831
+ latest_by_session_run: Mapping[tuple[str, str], int],
832
+ *,
833
+ session_id: str,
834
+ ) -> dict[str, Any]:
835
+ metadata = checkpoint.get("Metadata") or {}
836
+ if not metadata.get("only_latest_resumable"):
837
+ return checkpoint
838
+ run_id = str(checkpoint.get("RunId") or "")
839
+ if int(checkpoint.get("SeqId") or 0) >= latest_by_session_run.get((session_id, run_id), 0):
840
+ return checkpoint
841
+ if checkpoint.get("IsResumable") is True:
842
+ checkpoint["IsResumable"] = False
843
+ checkpoint["ResumeStatus"] = "disabled"
844
+ checkpoint["ResumeDisabledReason"] = "新的恢复点已生成,此恢复点暂停恢复能力"
845
+ metadata["resume_disabled_reason"] = checkpoint["ResumeDisabledReason"]
846
+ metadata["resume_status"] = "disabled"
847
+ checkpoint["Metadata"] = metadata
848
+ return checkpoint