agentengine-sdk-python 0.8.7__py3-none-any.whl → 0.8.9__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 (285) hide show
  1. {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.9.dist-info}/METADATA +22 -20
  2. {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.9.dist-info}/RECORD +259 -221
  3. ksadk/__init__.py +2 -1
  4. ksadk/_build_provenance.json +1 -1
  5. ksadk/_mcp_compat.py +305 -0
  6. ksadk/agent.py +29 -0
  7. ksadk/agui/_agent_kernel.py +176 -142
  8. ksadk/agui/agent.py +75 -6
  9. ksadk/agui/hosted.py +343 -0
  10. ksadk/agui/request_identity.py +11 -0
  11. ksadk/agui/routes.py +77 -2
  12. ksadk/builders/code_builder.py +30 -23
  13. ksadk/builders/container_builder.py +5 -5
  14. ksadk/builders/framework_requirements.py +1 -1
  15. ksadk/builders/mcp_builder.py +142 -0
  16. ksadk/builders/project_imports.py +66 -0
  17. ksadk/cli/cmd_mcp.py +1 -1
  18. ksadk/cli/cmd_run.py +6 -4
  19. ksadk/cli/cmd_web.py +12 -0
  20. ksadk/cli/runtime_bootstrap.py +4 -1
  21. ksadk/cli/runtime_logging.py +30 -0
  22. ksadk/common/cloud_headers.py +33 -6
  23. ksadk/compat/adk_compat.py +2 -0
  24. ksadk/compat/adk_stream.py +35 -0
  25. ksadk/configs/env_registry.py +31 -0
  26. ksadk/context_engine/capabilities.py +13 -9
  27. ksadk/conversations/context.py +5 -0
  28. ksadk/conversations/message_projection.py +28 -19
  29. ksadk/conversations/projector.py +6 -0
  30. ksadk/conversations/runtime_compaction.py +6 -2
  31. ksadk/conversations/runtime_input.py +4 -0
  32. ksadk/conversations/runtime_invocation.py +5 -1
  33. ksadk/conversations/runtime_metadata.py +6 -7
  34. ksadk/conversations/runtime_observability.py +1 -0
  35. ksadk/conversations/runtime_payloads.py +5 -1
  36. ksadk/conversations/runtime_persistence.py +23 -0
  37. ksadk/conversations/runtime_preparation.py +128 -5
  38. ksadk/detection/mcp_detector.py +80 -22
  39. ksadk/events/adapters/langgraph.py +53 -1
  40. ksadk/harness/__init__.py +3 -0
  41. ksadk/harness/service_presentation.py +44 -0
  42. ksadk/harness/service_runtime.py +1038 -0
  43. ksadk/interaction/providers/harness.py +9 -4
  44. ksadk/kernel/control.py +16 -22
  45. ksadk/kernel/history_projection.py +191 -58
  46. ksadk/kernel/ingress.py +50 -26
  47. ksadk/kernel/postgres_event_log.py +10 -2
  48. ksadk/kernel/postgres_store.py +81 -2
  49. ksadk/kernel/run_references.py +38 -0
  50. ksadk/kernel/worker.py +2 -2
  51. ksadk/kernel/worker_controls.py +11 -1
  52. ksadk/kernel/worker_identity.py +15 -8
  53. ksadk/knowledge_base/client.py +10 -3
  54. ksadk/mcp_runtime/oauth/_agent.py +77 -9
  55. ksadk/mcp_runtime/oauth/kernel.py +5 -0
  56. ksadk/mcp_runtime/oauth/langgraph.py +47 -15
  57. ksadk/mcp_runtime/oauth/local/broker.py +41 -9
  58. ksadk/mcp_runtime/oauth/local/protocol.py +3 -11
  59. ksadk/mcp_runtime/oauth/local/transport.py +9 -2
  60. ksadk/mcp_runtime/oauth/tools.py +46 -8
  61. ksadk/mcp_runtime/oauth/transport.py +19 -2
  62. ksadk/memory/adk/backends/sdk_ltm_backend.py +21 -12
  63. ksadk/memory/scope_ids.py +49 -0
  64. ksadk/plugins/providers/harness.py +65 -28
  65. ksadk/plugins/providers/harness_service.py +198 -0
  66. ksadk/plugins/providers/harness_service_context.py +175 -0
  67. ksadk/plugins/providers/harness_service_hooks.py +168 -0
  68. ksadk/plugins/providers/harness_service_memory.py +479 -0
  69. ksadk/plugins/providers/platform_resources.py +2 -2
  70. ksadk/resource_runtime/contracts.py +39 -1
  71. ksadk/resource_runtime/langgraph.py +7 -3
  72. ksadk/resource_runtime/managed_projection.py +8 -6
  73. ksadk/resource_runtime/mcp_server.py +3 -3
  74. ksadk/resource_runtime/worker.py +27 -5
  75. ksadk/runners/_adk_canonical_stream.py +53 -24
  76. ksadk/runners/_adk_tunnel_history.py +96 -0
  77. ksadk/runners/_langgraph_answer_contract.py +1 -7
  78. ksadk/runners/_langgraph_canonical_stream.py +29 -6
  79. ksadk/runners/_langgraph_context.py +265 -0
  80. ksadk/runners/_langgraph_factory.py +79 -0
  81. ksadk/runners/_langgraph_model_budget.py +397 -0
  82. ksadk/runners/_langgraph_runner_streams.py +13 -6
  83. ksadk/runners/_session_identity.py +8 -3
  84. ksadk/runners/adk_runner.py +104 -36
  85. ksadk/runners/langgraph_runner.py +145 -29
  86. ksadk/runners/usage_accumulator.py +40 -0
  87. ksadk/runtime/conversation_execution.py +26 -4
  88. ksadk/runtime/factory.py +17 -5
  89. ksadk/runtime/framework_adapters.py +10 -0
  90. ksadk/runtime/langgraph_checkpoint_view.py +28 -7
  91. ksadk/runtime/launch.py +2 -0
  92. ksadk/server/factory.py +58 -1
  93. ksadk/server/routes/common.py +2 -0
  94. ksadk/server/routes/control.py +24 -8
  95. ksadk/server/routes/harness_service_view.py +38 -0
  96. ksadk/server/routes/history_items.py +157 -0
  97. ksadk/server/routes/kernel_ingress.py +51 -12
  98. ksadk/server/routes/local_kernel_control.py +16 -0
  99. ksadk/server/routes/models.py +26 -0
  100. ksadk/server/routes/openai_compat.py +10 -3
  101. ksadk/server/routes/projection.py +4 -0
  102. ksadk/server/routes/run.py +4 -2
  103. ksadk/server/routes/sessions.py +20 -1
  104. ksadk/server/routes/ui_bootstrap.py +16 -2
  105. ksadk/server/static/assets/{ArtifactsPanel-Cdr5C_vM.js → ArtifactsPanel-iZ_6CAQ2.js} +1 -1
  106. ksadk/server/static/assets/{CodeBlock-BWRafud9.js → CodeBlock-D6uglm5n.js} +1 -1
  107. ksadk/server/static/assets/{MathMessageMarkdown-CFKeJIvy.js → MathMessageMarkdown-D6ojdxCG.js} +1 -1
  108. ksadk/server/static/assets/{MermaidBlock-BneAGUOd.js → MermaidBlock-Csk2ivT7.js} +6 -6
  109. ksadk/server/static/assets/{NativeTerminalPanel-BHI85zDO.js → NativeTerminalPanel-CCJA1XSH.js} +1 -1
  110. ksadk/server/static/assets/{OfficialA2uiRenderer-BOmT36lJ.js → OfficialA2uiRenderer-C06jus9N.js} +1 -1
  111. ksadk/server/static/assets/{abnfDiagram-VCTEODGH-DQvlOsBI.js → abnfDiagram-VCTEODGH-BhrF5tmL.js} +1 -1
  112. ksadk/server/static/assets/{arc-CGx0e4pN.js → arc-Btsh3kfy.js} +1 -1
  113. ksadk/server/static/assets/architecture-7GRP2DOG-BSXho3cq.js +1 -0
  114. ksadk/server/static/assets/{architectureDiagram-5GKGNRK7-WyybcNKX.js → architectureDiagram-5GKGNRK7-Cl8MfAmp.js} +1 -1
  115. ksadk/server/static/assets/{blockDiagram-NRAW4CY4-C9Cx_GVs.js → blockDiagram-NRAW4CY4-CeHSr8E_.js} +1 -1
  116. ksadk/server/static/assets/{c4Diagram-UCG6FXSJ-Bh7X3bGr.js → c4Diagram-UCG6FXSJ-BSD7RUKo.js} +1 -1
  117. ksadk/server/static/assets/channel-BpyDVKis.js +1 -0
  118. ksadk/server/static/assets/chunk-2Q5K7J3B-HLcpmPI2.js +1 -0
  119. ksadk/server/static/assets/{chunk-5VM5RSS4-cP9XupZj.js → chunk-5VM5RSS4-wz0pkBjp.js} +1 -1
  120. ksadk/server/static/assets/{chunk-F27PBJKO-Bm77fvR9.js → chunk-F27PBJKO-shjQ7cPM.js} +1 -1
  121. ksadk/server/static/assets/{chunk-G27WJ6UU-DDKNPesQ.js → chunk-G27WJ6UU-DL_MfUsu.js} +1 -1
  122. ksadk/server/static/assets/{chunk-JWPE2WC7-BqiUDB7s.js → chunk-JWPE2WC7-moUdwYpb.js} +1 -1
  123. ksadk/server/static/assets/{chunk-LCL6LL3I-C528mMZy.js → chunk-LCL6LL3I-B3QcDsZM.js} +1 -1
  124. ksadk/server/static/assets/{chunk-POPQ4Y6H-CzZ9g_Uf.js → chunk-POPQ4Y6H-BLBKb48A.js} +1 -1
  125. ksadk/server/static/assets/{chunk-RHFEMEQ7-CXj4tUZ-.js → chunk-RHFEMEQ7-CXR6ZzOx.js} +1 -1
  126. ksadk/server/static/assets/{chunk-SVP7TREG-BHyd85pS.js → chunk-SVP7TREG-DoR8BxkO.js} +1 -1
  127. ksadk/server/static/assets/{chunk-XXDRQBXY-Qe29PHGe.js → chunk-XXDRQBXY-8HJaIq0q.js} +1 -1
  128. ksadk/server/static/assets/classDiagram-DTDB5LWJ-DlNiRtSN.js +1 -0
  129. ksadk/server/static/assets/classDiagram-v2-JRS7N3AN-DlNiRtSN.js +1 -0
  130. ksadk/server/static/assets/{cose-bilkent-JH36ORCC-maRKgeec.js → cose-bilkent-JH36ORCC-DnSSHHqS.js} +1 -1
  131. ksadk/server/static/assets/cynefin-OW5HDTMX-DxNym3qg.js +1 -0
  132. ksadk/server/static/assets/{cynefinDiagram-5FMLGOSQ-CoD0bEvn.js → cynefinDiagram-5FMLGOSQ-4eCi_Rw5.js} +1 -1
  133. ksadk/server/static/assets/{dagre-3AP2YEHR-BkpgQqyW.js → dagre-3AP2YEHR-DpPk9jsh.js} +1 -1
  134. ksadk/server/static/assets/{dagre-BUaTFrYa.js → dagre-G789Mawt.js} +1 -1
  135. ksadk/server/static/assets/{diagram-S7CK7UJ4-25HdTbjE.js → diagram-S7CK7UJ4-7x2FScRJ.js} +1 -1
  136. ksadk/server/static/assets/{diagram-UQ7AKVKN-KO-WqOIg.js → diagram-UQ7AKVKN-DGvliWDD.js} +1 -1
  137. ksadk/server/static/assets/{diagram-VSXAHHWV-B360BkDQ.js → diagram-VSXAHHWV-C0i4uEyS.js} +1 -1
  138. ksadk/server/static/assets/{diagram-VX7I27RA-COr1Oqsg.js → diagram-VX7I27RA-C7SmgIl5.js} +1 -1
  139. ksadk/server/static/assets/{diagram-Z3DM3KII-CgaKrIwB.js → diagram-Z3DM3KII-Xca7TB4U.js} +1 -1
  140. ksadk/server/static/assets/{dist-By-MVndb.js → dist-B3rsrE8r.js} +1 -1
  141. ksadk/server/static/assets/{dist-Bsuusoi0.js → dist-BM6KIyhr.js} +1 -1
  142. ksadk/server/static/assets/{dist-DzdXSBJb.js → dist-BMZKBrmN.js} +1 -1
  143. ksadk/server/static/assets/{dist-DmWw0IXB.js → dist-BUGNcOx8.js} +1 -1
  144. ksadk/server/static/assets/{dist-DXOlCAay.js → dist-BbIN_x76.js} +1 -1
  145. ksadk/server/static/assets/{dist--HftQyp9.js → dist-CGB89Aru.js} +1 -1
  146. ksadk/server/static/assets/{dist-DKG0OYnk.js → dist-CGIWL8mC.js} +1 -1
  147. ksadk/server/static/assets/{dist-DgJ57sRe.js → dist-CHeuPGXZ.js} +1 -1
  148. ksadk/server/static/assets/{dist-_0Xgu_07.js → dist-CMJq3QL-.js} +1 -1
  149. ksadk/server/static/assets/{dist-CwnkOyDn.js → dist-CiUeIDKz.js} +1 -1
  150. ksadk/server/static/assets/{dist-BoRn8a_t.js → dist-CmaZEf5M.js} +1 -1
  151. ksadk/server/static/assets/{dist-BQ116UdZ.js → dist-Cq4qlsg3.js} +1 -1
  152. ksadk/server/static/assets/{dist-CBo9AHUv.js → dist-DDVDyH7h.js} +1 -1
  153. ksadk/server/static/assets/{dist-DSw5Ju6-.js → dist-DDi9q5bO.js} +1 -1
  154. ksadk/server/static/assets/{dist-CxIl4t92.js → dist-DJ8mj6p4.js} +1 -1
  155. ksadk/server/static/assets/{dist-Brbrdmff.js → dist-DRGym1nc.js} +1 -1
  156. ksadk/server/static/assets/{dist-BEbS8Bag.js → dist-DcrTYAeW.js} +1 -1
  157. ksadk/server/static/assets/{dist-C9BTMVwS.js → dist-DpuxDDLa.js} +1 -1
  158. ksadk/server/static/assets/{dist-B3Jp5r1e.js → dist-EFGQ7G_k.js} +1 -1
  159. ksadk/server/static/assets/{dist-HHvdjADB.js → dist-IyCF0NNA.js} +1 -1
  160. ksadk/server/static/assets/{dist-Bxcu8Ca0.js → dist-Ny95vkRV.js} +1 -1
  161. ksadk/server/static/assets/{dist-CR61WJFC.js → dist-s5cohO5C.js} +1 -1
  162. ksadk/server/static/assets/{ebnfDiagram-PWID7BFC-DogDP2db.js → ebnfDiagram-PWID7BFC-DNwVczAJ.js} +1 -1
  163. ksadk/server/static/assets/{erDiagram-SSCWMZ5O-CeBDnUjR.js → erDiagram-SSCWMZ5O-OxFlhx6v.js} +1 -1
  164. ksadk/server/static/assets/eventmodeling-NTZA5JFV-C-gXDupK.js +1 -0
  165. ksadk/server/static/assets/flowDiagram-A5DVABFB-CkpCYD4e.js +1 -0
  166. ksadk/server/static/assets/{ganttDiagram-EL5Y4UJY-oIQL3MCp.js → ganttDiagram-EL5Y4UJY-D4krNgUz.js} +1 -1
  167. ksadk/server/static/assets/gitGraph-4MIJSDKK-0RSkEgC5.js +1 -0
  168. ksadk/server/static/assets/{gitGraphDiagram-WWUBYQGX-B7qz0cmZ.js → gitGraphDiagram-WWUBYQGX-BUSVPN1s.js} +1 -1
  169. ksadk/server/static/assets/index-B9UP7He9.css +2 -0
  170. ksadk/server/static/assets/index-COn4kn-G.js +1135 -0
  171. ksadk/server/static/assets/info-A6RAGUB7-C6KX7WO4.js +1 -0
  172. ksadk/server/static/assets/{infoDiagram-RXCK75RN-yQRC41Ya.js → infoDiagram-RXCK75RN-b6w3u3-O.js} +1 -1
  173. ksadk/server/static/assets/{ishikawaDiagram-5VMMS53U-BCu4HiwL.js → ishikawaDiagram-5VMMS53U-CsC7gzRt.js} +1 -1
  174. ksadk/server/static/assets/{journeyDiagram-EYS64GPL-JaqmO73K.js → journeyDiagram-EYS64GPL-BATLNoy1.js} +1 -1
  175. ksadk/server/static/assets/{kanban-definition-3QL26DDD-DQo4X8NO.js → kanban-definition-3QL26DDD-C49zL_s0.js} +1 -1
  176. ksadk/server/static/assets/{katex-t_DWylQw.js → katex-CDVgGGy2.js} +1 -1
  177. ksadk/server/static/assets/{linear-DWdnI35B.js → linear-DkyDumSy.js} +1 -1
  178. ksadk/server/static/assets/{mermaid-parser.core-BHrT2Pfe.js → mermaid-parser.core-BDX-LqSy.js} +2 -2
  179. ksadk/server/static/assets/{mindmap-definition-FBJOCRG2-PBVAhZYV.js → mindmap-definition-FBJOCRG2-DRPnzL2n.js} +1 -1
  180. ksadk/server/static/assets/packet-AYTQ26CC-CMMupxPW.js +1 -0
  181. ksadk/server/static/assets/{pegDiagram-XKGWAZYB-CU_cLfow.js → pegDiagram-XKGWAZYB-Zm-xrNrr.js} +1 -1
  182. ksadk/server/static/assets/pie-WAS4IAKB-Bfo0pa9v.js +1 -0
  183. ksadk/server/static/assets/{pieDiagram-E7YTZNPT-B1h0-_pW.js → pieDiagram-E7YTZNPT-a8C1Jxo4.js} +1 -1
  184. ksadk/server/static/assets/{quadrantDiagram-AXDQQJYC-DEMoGo5a.js → quadrantDiagram-AXDQQJYC-ihH8znBv.js} +1 -1
  185. ksadk/server/static/assets/radar-RG4KPBEZ-PRBiHoJx.js +1 -0
  186. ksadk/server/static/assets/railroad-74A4TZTK-BCJ-XMRJ.js +1 -0
  187. ksadk/server/static/assets/railroad-abnf-HS5TGJTU-Bbttj0Jz.js +1 -0
  188. ksadk/server/static/assets/railroad-ebnf-LZEXJU2U-Bo18264J.js +1 -0
  189. ksadk/server/static/assets/railroad-peg-WCYAUIDC-xZDJTFLD.js +1 -0
  190. ksadk/server/static/assets/{railroadDiagram-O6MQD6OU-BTAob2wg.js → railroadDiagram-O6MQD6OU-DD9lFfXo.js} +1 -1
  191. ksadk/server/static/assets/{requirementDiagram-EFPCY7ZU-Dl0Q2SuO.js → requirementDiagram-EFPCY7ZU-CGn93Iyb.js} +1 -1
  192. ksadk/server/static/assets/{sankeyDiagram-P5KCCOFB-DeaTWkur.js → sankeyDiagram-P5KCCOFB-BuyjrHuW.js} +1 -1
  193. ksadk/server/static/assets/{sequenceDiagram-WJ2MYXX4-gFQYrsOd.js → sequenceDiagram-WJ2MYXX4-D-Iw-30A.js} +1 -1
  194. ksadk/server/static/assets/{sizeCapture-X5ZJPWSS-pGQzddMB.js → sizeCapture-X5ZJPWSS-B0EHLwrD.js} +1 -1
  195. ksadk/server/static/assets/{stateDiagram-HBIQ2CUA-DmpYOZt1.js → stateDiagram-HBIQ2CUA-k9Zyg69R.js} +1 -1
  196. ksadk/server/static/assets/stateDiagram-v2-4QOOHH4V-tUEVnq9-.js +1 -0
  197. ksadk/server/static/assets/{swimlanes-XN3QIQJK-BfuSAsrr.js → swimlanes-XN3QIQJK-D2BewKmp.js} +1 -1
  198. ksadk/server/static/assets/swimlanesDiagram-VK2B7HYN-CGBmsrCQ.js +8 -0
  199. ksadk/server/static/assets/{timeline-definition-24CTP7MA-CgJwrrxf.js → timeline-definition-24CTP7MA-czSzsYbz.js} +1 -1
  200. ksadk/server/static/assets/treeView-Q6P3EWNA-CrEvfC8M.js +1 -0
  201. ksadk/server/static/assets/treemap-WGGIJYW6-D1TmShtn.js +1 -0
  202. ksadk/server/static/assets/{vennDiagram-4TSXK5OY-CBSAgXDd.js → vennDiagram-4TSXK5OY-BJF_qZLF.js} +1 -1
  203. ksadk/server/static/assets/wardley-WFR3VGLG-0gZiSyL0.js +1 -0
  204. ksadk/server/static/assets/{wardleyDiagram-VM6X3IG4-013TZ2JZ.js → wardleyDiagram-VM6X3IG4-BfwUuJpr.js} +1 -1
  205. ksadk/server/static/assets/{xychartDiagram-S5SC5T6Z-u6Frp8xp.js → xychartDiagram-S5SC5T6Z-Ci6Nsp4p.js} +1 -1
  206. ksadk/server/static/index.html +2 -2
  207. ksadk/server/static/ui-source.json +6 -6
  208. ksadk/sessions/_postgres_history_backfill.py +80 -0
  209. ksadk/sessions/_postgres_schema.py +117 -0
  210. ksadk/sessions/_postgres_tables.py +6 -0
  211. ksadk/sessions/base.py +24 -0
  212. ksadk/sessions/history_tool_refs.py +244 -0
  213. ksadk/sessions/in_memory.py +42 -0
  214. ksadk/sessions/local_service.py +78 -0
  215. ksadk/sessions/model_history.py +20 -0
  216. ksadk/sessions/postgres_service.py +215 -19
  217. ksadk/sessions/resilient.py +24 -0
  218. ksadk/skills/mcp_server/server.py +239 -217
  219. ksadk/studio/contracts.py +8 -0
  220. ksadk/studio/mcp_runtime.py +23 -8
  221. ksadk/studio/native_mcp_disclosure.py +8 -6
  222. ksadk/studio/native_mcp_tool_port.py +3 -1
  223. ksadk/studio/native_memory_context.py +10 -8
  224. ksadk/studio/native_product.py +3 -4
  225. ksadk/studio/plugin_composition.py +8 -1
  226. ksadk/studio/plugin_native_activation.py +4 -2
  227. ksadk/studio/plugin_runtime.py +9 -0
  228. ksadk/studio/service.py +2 -0
  229. ksadk/studio/static/assets/{ChannelsPage-Do_mRmVu.js → ChannelsPage-Ot9iV_QP.js} +1 -1
  230. ksadk/studio/static/assets/{CodeBlock-DMIf4h33-CsO7rJKv.js → CodeBlock-DMIf4h33-Cfs6se0v.js} +1 -1
  231. ksadk/studio/static/assets/{MathMessageMarkdown-BesSeCYl-CiB60plG.js → MathMessageMarkdown-BesSeCYl-BIBDiQAl.js} +1 -1
  232. ksadk/studio/static/assets/{MessageMarkdown-CwMTvgFj-BzEmQkHH.js → MessageMarkdown-CwMTvgFj-CWM4n-9K.js} +2 -2
  233. ksadk/studio/static/assets/{OfficialA2uiRenderer-DI49Kpxu-BBxfdj3P.js → OfficialA2uiRenderer-DI49Kpxu-BZSumE9D.js} +1 -1
  234. ksadk/studio/static/assets/{TeamsPage-qNVYpcox.js → TeamsPage-CVOpMIMf.js} +2 -2
  235. ksadk/studio/static/assets/index-CW1D-Kqg.css +2 -0
  236. ksadk/studio/static/assets/index-DMexeQ1-.js +1155 -0
  237. ksadk/studio/static/index.html +3 -3
  238. ksadk/studio/static/ui-source.json +6 -6
  239. ksadk/tracing/setup.py +53 -3
  240. ksadk/tunnel/__init__.py +37 -0
  241. ksadk/tunnel/connector.py +384 -0
  242. ksadk/tunnel/discovery.py +107 -0
  243. ksadk/tunnel/failure.py +168 -0
  244. ksadk/tunnel/http_tools.py +100 -0
  245. ksadk/tunnel/langgraph.py +125 -0
  246. ksadk/tunnel/middleware.py +28 -0
  247. ksadk/tunnel/peers.py +872 -0
  248. ksadk/tunnel/protocol.py +97 -0
  249. ksadk/tunnel/registry.py +306 -0
  250. ksadk/tunnel/runtime.py +147 -0
  251. ksadk/tunnel/server.py +201 -0
  252. ksadk/tunnel/services.py +366 -0
  253. ksadk/tunnel/toolset.py +78 -0
  254. ksadk/version.py +1 -1
  255. ksadk_runtime_common/memory_backend/providers/mem0.py +20 -0
  256. ksadk/server/static/assets/architecture-7GRP2DOG-CFWjFkDL.js +0 -1
  257. ksadk/server/static/assets/channel-D6Dp_l74.js +0 -1
  258. ksadk/server/static/assets/chunk-2Q5K7J3B-CwmjhFYK.js +0 -1
  259. ksadk/server/static/assets/classDiagram-DTDB5LWJ-DsbvkCAV.js +0 -1
  260. ksadk/server/static/assets/classDiagram-v2-JRS7N3AN-DsbvkCAV.js +0 -1
  261. ksadk/server/static/assets/cynefin-OW5HDTMX-CBZRVuc4.js +0 -1
  262. ksadk/server/static/assets/eventmodeling-NTZA5JFV-vXZWMkpn.js +0 -1
  263. ksadk/server/static/assets/flowDiagram-A5DVABFB-5LRgzKLv.js +0 -1
  264. ksadk/server/static/assets/gitGraph-4MIJSDKK-BUWSkncI.js +0 -1
  265. ksadk/server/static/assets/index-4g1ndaxW.js +0 -1132
  266. ksadk/server/static/assets/index-DEVfafsU.css +0 -2
  267. ksadk/server/static/assets/info-A6RAGUB7-CzJ_YrOs.js +0 -1
  268. ksadk/server/static/assets/packet-AYTQ26CC-CXoos6fx.js +0 -1
  269. ksadk/server/static/assets/pie-WAS4IAKB-CjF9NoIt.js +0 -1
  270. ksadk/server/static/assets/radar-RG4KPBEZ-BQGWs9nw.js +0 -1
  271. ksadk/server/static/assets/railroad-74A4TZTK-B6znvLUK.js +0 -1
  272. ksadk/server/static/assets/railroad-abnf-HS5TGJTU-Bzquz0As.js +0 -1
  273. ksadk/server/static/assets/railroad-ebnf-LZEXJU2U-1IikGkb5.js +0 -1
  274. ksadk/server/static/assets/railroad-peg-WCYAUIDC-BKKgHzdc.js +0 -1
  275. ksadk/server/static/assets/stateDiagram-v2-4QOOHH4V-Dolxgkw3.js +0 -1
  276. ksadk/server/static/assets/swimlanesDiagram-VK2B7HYN-BuI1erYj.js +0 -8
  277. ksadk/server/static/assets/treeView-Q6P3EWNA-DtMdDH8N.js +0 -1
  278. ksadk/server/static/assets/treemap-WGGIJYW6-VoU8QtLZ.js +0 -1
  279. ksadk/server/static/assets/wardley-WFR3VGLG-YWSRB0Zm.js +0 -1
  280. ksadk/studio/static/assets/index-Cp9Unfkn.css +0 -2
  281. ksadk/studio/static/assets/index-HepnaEeR.js +0 -1152
  282. {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.9.dist-info}/WHEEL +0 -0
  283. {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.9.dist-info}/entry_points.txt +0 -0
  284. {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.9.dist-info}/licenses/LICENSE +0 -0
  285. {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.9.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,1038 @@
1
+ """KSADK's RuntimeAdapter for a separately deployed Harness engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import hashlib
7
+ import json
8
+ import logging
9
+ import os
10
+ import time
11
+ from collections.abc import AsyncIterator, Awaitable, Callable
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+ from ssl import create_default_context
15
+ from typing import Any
16
+ from uuid import uuid4
17
+
18
+ import httpx
19
+
20
+ from ksadk.conversations.normalize import canonical_input_content_from_message_content
21
+ from ksadk.events.canonical import (
22
+ ApprovalRequest,
23
+ ErrorInfo,
24
+ InteractionRequested,
25
+ ItemCompleted,
26
+ ItemStarted,
27
+ OutputRef,
28
+ RunCanceled,
29
+ RunCompleted,
30
+ RunFailed,
31
+ RunInterrupted,
32
+ RunProgress,
33
+ RunStarted,
34
+ RuntimeEvent,
35
+ SourceRef,
36
+ UsageReported,
37
+ )
38
+ from ksadk.events.content import ContentSnapshot, TextContent
39
+ from ksadk.harness.service_presentation import VIEW_HASH, engine_presentation, engine_view_hash
40
+ from ksadk.kernel.contracts import RuntimeCapability, RuntimeCapabilityMatrix
41
+ from ksadk.kernel.errors import UnsupportedControlError
42
+ from ksadk.runtime.adapter import (
43
+ BaseRuntime,
44
+ CancelResult,
45
+ CheckpointDescriptor,
46
+ ResumePayload,
47
+ ResumeTarget,
48
+ RunHandle,
49
+ RuntimeAdapter,
50
+ StartRequest,
51
+ )
52
+
53
+ _PROTOCOL = "agentkit.engine/v1"
54
+ _BINDING = "agentkit.engine-service/v1"
55
+ _APPROVAL = "agentkit.engine-approval/v1"
56
+ _POLICY = "agentkit.native-agent-policy/v1"
57
+ _EXECUTION_POLICY = "agentkit.engine-execution-policy/v1"
58
+ _CONTEXT = "agentkit.engine-context/v1"
59
+ _HOOKS = "agentkit.engine-hooks/v1"
60
+ _TOOL_EFFECT = "agentkit.engine-host-tool-effect/v1"
61
+ _VERIFICATION = "agentkit.engine-verification/v1"
62
+ _HOST_OBSERVATIONS = "run/host-observations"
63
+ _RETRYABLE_RPC = {
64
+ "initialize", "run/start", "run/status", "run/events", "run/approve", _HOST_OBSERVATIONS,
65
+ }
66
+ _LOG = logging.getLogger(__name__)
67
+ TurnContext = Callable[[StartRequest, list[dict[str, Any]]], Awaitable[list[str]]]
68
+
69
+
70
+ class _ServiceRestarted(RuntimeError):
71
+ pass
72
+
73
+
74
+ class _ServiceUnavailable(RuntimeError):
75
+ pass
76
+
77
+
78
+ def _session_key(agent_id: str, user_id: str, session_id: str) -> str:
79
+ identity = json.dumps([agent_id, user_id, session_id], ensure_ascii=True)
80
+ return hashlib.sha256(identity.encode("ascii")).hexdigest()
81
+
82
+
83
+ class _ServiceRuntime(BaseRuntime):
84
+ runtime_type = "harness"
85
+
86
+ def native_capabilities(self) -> dict[str, Any]:
87
+ return {"cancel": True, "attach": True, "resume": True, "durable_restore": True}
88
+
89
+
90
+ @dataclass(frozen=True)
91
+ class ServiceHostTool:
92
+ name: str
93
+ description: str
94
+ parameters: dict[str, Any]
95
+ call: Callable[[dict[str, Any]], Awaitable[Any]] | None
96
+ read_only: bool = False
97
+ deferred: bool = False
98
+ source_name: str | None = None
99
+ effect: Callable[[RunHandle, dict[str, Any]], Awaitable[dict[str, Any]]] | None = None
100
+
101
+ def definition(self) -> dict[str, Any]:
102
+ return {
103
+ "name": self.name, "description": self.description[:4000],
104
+ "parameters": self.parameters, "readOnly": self.read_only, "deferred": self.deferred,
105
+ **({"effectProtocol": _TOOL_EFFECT} if self.effect is not None else {}),
106
+ }
107
+
108
+
109
+ @dataclass(frozen=True)
110
+ class ServiceContextSource:
111
+ definition: dict[str, Any]
112
+ read: Callable[[RunHandle, dict[str, Any]], Awaitable[list[dict[str, Any]]]]
113
+
114
+
115
+ @dataclass(frozen=True)
116
+ class ServiceHook:
117
+ definition: dict[str, Any]
118
+ invoke: Callable[[RunHandle, dict[str, Any]], Awaitable[dict[str, Any]]]
119
+
120
+
121
+ @dataclass(frozen=True)
122
+ class ServiceGoalVerifier:
123
+ definition: dict[str, Any]
124
+ applies: Callable[[str], bool]
125
+ verify: Callable[[RunHandle, dict[str, Any]], Awaitable[dict[str, Any]]]
126
+
127
+
128
+ class HarnessServiceRuntimeAdapter(RuntimeAdapter):
129
+ """The service owns the ledger, tools and model binding for this deployment."""
130
+
131
+ def __init__(
132
+ self,
133
+ *,
134
+ endpoint: str,
135
+ token: str,
136
+ instructions: str = "",
137
+ model: str | None = None,
138
+ ca_file: str | None = None,
139
+ durable_approvals: bool = False,
140
+ ) -> None:
141
+ super().__init__(_ServiceRuntime())
142
+ url = httpx.URL(endpoint)
143
+ if (
144
+ not url.host
145
+ or url.userinfo
146
+ or url.query
147
+ or url.fragment
148
+ or (
149
+ url.scheme != "https"
150
+ and (url.scheme != "http" or url.host not in {"localhost", "127.0.0.1", "::1"})
151
+ )
152
+ or len(token) < 24
153
+ ):
154
+ raise ValueError("invalid Harness service endpoint or credential")
155
+ self._endpoint = str(url).rstrip("/")
156
+ self._token = token
157
+ self._instructions = instructions
158
+ self._durable_approvals = durable_approvals
159
+ self._verify = create_default_context(cafile=ca_file) if ca_file else True
160
+ self._resource_binding: str | None = None
161
+ self._bound_scope: dict[str, str] = {}
162
+ self._bound_model = model
163
+ self._load_tools: Callable[[], Awaitable[tuple[ServiceHostTool, ...]]] | None = None
164
+ self._context: TurnContext | None = None
165
+ self._context_sources: dict[str, ServiceContextSource] = {}
166
+ self._hooks: dict[str, ServiceHook] = {}
167
+ self._stop_hook_limit: int | None = None
168
+ self._tool_effects = False
169
+ self._complete: Callable[[RunHandle, dict[str, Any]], Awaitable[None]] | None = None
170
+ self._execution_policy: dict[str, Any] | None = None
171
+ self._verifier: ServiceGoalVerifier | None = None
172
+ self._tool_catalog: dict[str, ServiceHostTool] | None = None
173
+ self._tool_catalog_lock = asyncio.Lock()
174
+
175
+ def bind_read_only_workspace(
176
+ self,
177
+ *,
178
+ binding: str,
179
+ model: str,
180
+ load_tools: Callable[[], Awaitable[tuple[ServiceHostTool, ...]]],
181
+ context: TurnContext,
182
+ scope: dict[str, str] | None = None,
183
+ context_sources: tuple[ServiceContextSource, ...] = (),
184
+ hooks: tuple[ServiceHook, ...] = (),
185
+ stop_hook_limit: int | None = None,
186
+ tool_effects: bool = False,
187
+ complete: Callable[[RunHandle, dict[str, Any]], Awaitable[None]] | None = None,
188
+ execution_policy: dict[str, Any] | None = None,
189
+ verifier: ServiceGoalVerifier | None = None,
190
+ ) -> None:
191
+ if self._resource_binding is not None:
192
+ raise RuntimeError("Harness service resources are already bound")
193
+ self._resource_binding = binding
194
+ self._bound_scope = dict(scope or {})
195
+ self._bound_model = model
196
+ self._load_tools = load_tools
197
+ self._context = context
198
+ self._context_sources = {
199
+ source.definition["sourceId"]: source for source in context_sources
200
+ }
201
+ if len(self._context_sources) != len(context_sources):
202
+ raise ValueError("Duplicate Harness context source")
203
+ self._hooks = {hook.definition["hookId"]: hook for hook in hooks}
204
+ if len(self._hooks) != len(hooks):
205
+ raise ValueError("Duplicate Harness hook")
206
+ self._stop_hook_limit = stop_hook_limit
207
+ self._tool_effects = tool_effects
208
+ self._complete = complete
209
+ self._verifier = verifier
210
+ if execution_policy is not None:
211
+ self._execution_policy = {**execution_policy, "contract": _EXECUTION_POLICY}
212
+
213
+ def _hook_definitions(self, tools: dict[str, ServiceHostTool]) -> dict[str, dict[str, Any]]:
214
+ aliases: dict[str, list[str]] = {}
215
+ for name, tool in tools.items():
216
+ if tool.source_name is not None:
217
+ aliases.setdefault(tool.source_name, []).append(name)
218
+ result = {}
219
+ for key, hook in self._hooks.items():
220
+ definition = hook.definition
221
+ selected = definition.get("toolNames")
222
+ if selected is not None:
223
+ names = []
224
+ for name in selected:
225
+ candidates = aliases.get(name, [])
226
+ if len(candidates) > 1:
227
+ raise ValueError("Ambiguous Harness Hook tool name")
228
+ names.append(candidates[0] if candidates else name)
229
+ definition = {**definition, "toolNames": names}
230
+ result[key] = definition
231
+ return result
232
+
233
+ async def _tools(self) -> dict[str, ServiceHostTool]:
234
+ async with self._tool_catalog_lock:
235
+ if self._tool_catalog is None:
236
+ tools = await self._load_tools() if self._load_tools is not None else ()
237
+ self._tool_catalog = {tool.name: tool for tool in tools}
238
+ if len(self._tool_catalog) != len(tools):
239
+ self._tool_catalog = None
240
+ raise ValueError("duplicate Harness service resource name")
241
+ return self._tool_catalog
242
+
243
+ def _http(self, *, timeout: float) -> httpx.AsyncClient:
244
+ return httpx.AsyncClient(
245
+ headers={"Authorization": "Bearer " + self._token},
246
+ timeout=timeout, trust_env=False, verify=self._verify, follow_redirects=False,
247
+ )
248
+
249
+ async def _rpc(self, session: str, method: str, **params: Any) -> dict[str, Any]:
250
+ try:
251
+ return await self._exchange(session, method, params)
252
+ except _ServiceRestarted:
253
+ if method == "initialize":
254
+ raise
255
+ await self._initialize(session)
256
+ return await self._exchange(session, method, params)
257
+
258
+ async def _exchange(self, session: str, method: str, params: dict[str, Any]) -> dict[str, Any]:
259
+ delay = 0.125
260
+ clock = asyncio.get_running_loop().time
261
+ deadline = clock() + 15
262
+ while True:
263
+ try:
264
+ return await self._request(session, method, params)
265
+ except (
266
+ httpx.NetworkError,
267
+ httpx.RemoteProtocolError,
268
+ _ServiceUnavailable,
269
+ ):
270
+ if method not in _RETRYABLE_RPC or clock() + delay >= deadline:
271
+ raise
272
+ await asyncio.sleep(delay)
273
+ delay = min(delay * 2, 2)
274
+
275
+ async def _request(self, session: str, method: str, params: dict[str, Any]) -> dict[str, Any]:
276
+ request_id = uuid4().hex
277
+ async with self._http(timeout=35) as client:
278
+ response = await client.post(
279
+ f"{self._endpoint}/v1/sessions/{session}/rpc",
280
+ json={"jsonrpc": "2.0", "id": request_id, "method": method, "params": params},
281
+ )
282
+ if response.status_code in {502, 503, 504}:
283
+ raise _ServiceUnavailable(f"Harness service HTTP {response.status_code}")
284
+ if response.status_code in {404, 409}:
285
+ try:
286
+ error_body = response.json()
287
+ except ValueError:
288
+ error_body = None
289
+ if isinstance(error_body, dict) and error_body.get("error") == "session_not_found":
290
+ raise _ServiceRestarted("Harness service session must be reattached")
291
+ if isinstance(error_body, dict) and error_body.get("error") == "request_unavailable":
292
+ raise _ServiceUnavailable("Harness service request was interrupted")
293
+ if not response.is_success:
294
+ raise RuntimeError(f"Harness service HTTP {response.status_code}")
295
+ body = response.json()
296
+ if (
297
+ not isinstance(body, dict)
298
+ or body.get("jsonrpc") != "2.0"
299
+ or body.get("id") != request_id
300
+ ):
301
+ raise RuntimeError("Invalid Harness service response")
302
+ if "error" in body:
303
+ # Remote diagnostics may include provider data. Report only the protocol code.
304
+ error = body["error"]
305
+ code = error.get("code") if isinstance(error, dict) else None
306
+ if code == -32010:
307
+ raise _ServiceRestarted("Harness service session must be reattached")
308
+ raise RuntimeError(f"Harness service RPC {code if isinstance(code, int) else 'error'}")
309
+ if not isinstance(body.get("result"), dict):
310
+ raise RuntimeError("Invalid Harness service result")
311
+ return body["result"]
312
+
313
+ async def view_html(self, sha256: str) -> bytes | None:
314
+ if not VIEW_HASH.fullmatch(sha256):
315
+ return None
316
+ headers = {"Authorization": "Bearer " + self._token}
317
+ async with (
318
+ httpx.AsyncClient(
319
+ headers=headers,
320
+ timeout=5,
321
+ trust_env=False,
322
+ verify=self._verify,
323
+ ) as client,
324
+ client.stream("GET", f"{self._endpoint}/v1/views/{sha256}") as response,
325
+ ):
326
+ if response.status_code == 404:
327
+ return None
328
+ response.raise_for_status()
329
+ content = bytearray()
330
+ async for chunk in response.aiter_bytes():
331
+ content.extend(chunk)
332
+ if len(content) > 1024 * 1024:
333
+ raise RuntimeError("Harness view exceeded the size limit")
334
+ if hashlib.sha256(content).hexdigest() != sha256:
335
+ raise RuntimeError("Harness view hash mismatch")
336
+ return bytes(content)
337
+
338
+ async def _initialize(self, session: str) -> dict[str, Any]:
339
+ hello = await self._rpc(
340
+ session,
341
+ "initialize",
342
+ protocolVersions=[_PROTOCOL],
343
+ host={"name": "ksadk-python"},
344
+ services={
345
+ "durableApprovals": self._durable_approvals,
346
+ "tools": self._load_tools is not None,
347
+ **({"context": _CONTEXT} if self._context_sources else {}),
348
+ **({"hooks": _HOOKS} if self._hooks else {}),
349
+ **({"toolEffects": _TOOL_EFFECT} if self._tool_effects else {}),
350
+ **({"verification": _VERIFICATION} if self._verifier else {}),
351
+ },
352
+ )
353
+ if hello.get("protocolVersion") != _PROTOCOL:
354
+ raise RuntimeError("Incompatible Harness service protocol")
355
+ if (
356
+ self._durable_approvals
357
+ and (hello.get("capabilities") or {}).get("approvals") != "durable"
358
+ ):
359
+ raise RuntimeError("Harness service does not support durable approvals")
360
+ capabilities = hello.get("capabilities") or {}
361
+ if self._load_tools is not None and (
362
+ capabilities.get("toolPolicy") != _POLICY
363
+ or capabilities.get("hostTools") is not True
364
+ or capabilities.get("scopedHostRequests") is not True
365
+ ):
366
+ raise RuntimeError("Harness service does not support bound KSADK resources")
367
+ if self._context_sources and capabilities.get("hostContext") != _CONTEXT:
368
+ raise RuntimeError("Harness service does not support bound KSADK context")
369
+ if self._hooks and capabilities.get("hostHooks") != _HOOKS:
370
+ raise RuntimeError("Harness service does not support bound KSADK hooks")
371
+ if self._tool_effects and capabilities.get("hostToolEffects") != _TOOL_EFFECT:
372
+ raise RuntimeError("Harness service does not support bound KSADK effects")
373
+ if self._verifier and capabilities.get("hostVerification") != _VERIFICATION:
374
+ raise RuntimeError("Harness service does not support bound KSADK goal verification")
375
+ if self._complete is not None and _HOST_OBSERVATIONS not in capabilities.get("methods", []):
376
+ raise RuntimeError("Harness service does not support completed-Turn host observations")
377
+ if (
378
+ self._execution_policy is not None
379
+ and capabilities.get("executionPolicy") != _EXECUTION_POLICY
380
+ ):
381
+ raise RuntimeError("Harness service does not support bound KSADK execution policy")
382
+ return hello
383
+
384
+ async def preflight(self) -> None:
385
+ async with httpx.AsyncClient(timeout=5, trust_env=False, verify=self._verify) as client:
386
+ response = await client.get(f"{self._endpoint}/healthz")
387
+ health = response.json() if response.status_code == 200 else {}
388
+ if not isinstance(health, dict) or health.get("contract") != _BINDING:
389
+ raise RuntimeError("Harness service is unavailable or incompatible")
390
+ if self._resource_binding is not None:
391
+ capabilities = health.get("capabilities") or {}
392
+ if (
393
+ not isinstance(capabilities, dict)
394
+ or capabilities.get("scopedHostRequests") is not True
395
+ or capabilities.get("toolPolicy") != _POLICY
396
+ ):
397
+ raise RuntimeError("Harness service does not support bound KSADK resources")
398
+ if self._context_sources and capabilities.get("hostContext") != _CONTEXT:
399
+ raise RuntimeError("Harness service does not support bound KSADK context")
400
+ if self._hooks and capabilities.get("hostHooks") != _HOOKS:
401
+ raise RuntimeError("Harness service does not support bound KSADK hooks")
402
+ if self._tool_effects and capabilities.get("hostToolEffects") != _TOOL_EFFECT:
403
+ raise RuntimeError("Harness service does not support bound KSADK effects")
404
+ if self._verifier and capabilities.get("hostVerification") != _VERIFICATION:
405
+ raise RuntimeError("Harness service does not support bound KSADK goal verification")
406
+ if (
407
+ self._execution_policy is not None
408
+ and capabilities.get("executionPolicy") != _EXECUTION_POLICY
409
+ ):
410
+ raise RuntimeError("Harness service does not support bound KSADK execution policy")
411
+
412
+ def _check_scope(self, *, agent_id: str, user_id: str, session_id: str) -> None:
413
+ if any(
414
+ self._bound_scope.get(key, actual) != actual
415
+ for key, actual in (
416
+ ("agent_id", agent_id), ("user_id", user_id), ("session_id", session_id),
417
+ )
418
+ ):
419
+ raise ValueError("Harness request does not match the bound activation scope")
420
+
421
+ def _session(self, handle: RunHandle) -> str:
422
+ ref = handle.native_ref
423
+ agent_id, user_id = ref.get("agent_id"), ref.get("user_id")
424
+ if (
425
+ handle.runtime_type != "harness"
426
+ or ref.get("binding") != _BINDING
427
+ or not all(
428
+ isinstance(value, str) and value for value in (agent_id, user_id, handle.session_id)
429
+ )
430
+ ):
431
+ raise ValueError("Invalid Harness service handle")
432
+ self._check_scope(agent_id=agent_id, user_id=user_id, session_id=handle.session_id)
433
+ return _session_key(agent_id, user_id, handle.session_id)
434
+
435
+ async def start(self, request: StartRequest) -> RunHandle:
436
+ conversation = request.conversation_preprocessing()
437
+ rows = list(conversation.messages if conversation else [])
438
+ objective = request.input if isinstance(request.input, str) else ""
439
+ if isinstance(request.input, list):
440
+ if all(isinstance(item, dict) and "role" in item for item in request.input):
441
+ rows = request.input
442
+ else:
443
+ rows = [{"role": "user", "content": request.input}]
444
+ elif not isinstance(request.input, str):
445
+ raise ValueError("Harness service requires text or image input")
446
+ current = next((row for row in reversed(rows) if row.get("role") == "user"), {})
447
+ parts = canonical_input_content_from_message_content(
448
+ current.get("input_content") or current.get("content")
449
+ )
450
+ images = [
451
+ {
452
+ "type": "image_url",
453
+ "image_url": {"url": part["image_url"], "detail": part.get("detail") or "auto"},
454
+ }
455
+ for part in parts
456
+ if part["type"] == "input_image"
457
+ ]
458
+ if not objective.strip():
459
+ objective = "".join(part["text"] for part in parts if part["type"] == "input_text")
460
+ if not objective.strip():
461
+ if not images:
462
+ raise ValueError("Harness service requires text or image input")
463
+ objective = "请查看用户提供的图片并说明其中的内容。"
464
+ if any(not image["image_url"]["url"].startswith("data:image/") for image in images):
465
+ raise ValueError("Harness service requires inline image content")
466
+ if not request.user_id.strip() or not request.session_id.strip():
467
+ raise ValueError("Harness service requires an admitted user and session")
468
+ agent_id = request.agent_id or self._bound_scope.get("agent_id") or "deployment"
469
+ run_id = request.metadata.get("invocation_id") or request.metadata.get("run_id")
470
+ handle = RunHandle(
471
+ run_id=str(run_id or uuid4().hex),
472
+ session_id=request.session_id,
473
+ runtime_type="harness",
474
+ native_ref={"binding": _BINDING, "agent_id": agent_id, "user_id": request.user_id},
475
+ )
476
+ session = self._session(handle)
477
+ hello = await self._initialize(session)
478
+ engine = hello.get("engine") or {}
479
+ selected_model = request.model or self._bound_model
480
+ if selected_model and (engine.get("model") or {}).get("name") != selected_model:
481
+ raise ValueError("Selected model does not match the bound Harness service")
482
+ tool_params: dict[str, Any] = {}
483
+ instructions = self._instructions
484
+ if self._resource_binding is not None:
485
+ handle.native_ref["resource_binding"] = self._resource_binding
486
+ if self._context is not None:
487
+ history = rows or [{"role": "user", "content": objective}]
488
+ sections = await self._context(request, history)
489
+ instructions = "\n\n".join(filter(None, (instructions, *sections)))
490
+ tools = await self._tools()
491
+ reserved = engine.get("reservedToolNames")
492
+ if not isinstance(reserved, list) or any(tool in reserved for tool in tools):
493
+ raise RuntimeError("Harness service resource catalog conflicts with the engine")
494
+ tool_params = {
495
+ "hostTools": [tool.definition() for tool in tools.values()],
496
+ # Only the workspace is read-only. The locked connector's tool
497
+ # allowlist authorizes its own operations independently.
498
+ "toolPolicy": {"contract": _POLICY, "mode": "custom", "rules": {
499
+ name: "inherit" for name in tools
500
+ }},
501
+ }
502
+ if self._execution_policy is not None:
503
+ tool_params["executionPolicy"] = self._execution_policy
504
+ if self._verifier and self._verifier.applies(objective):
505
+ tool_params["hostVerification"] = {
506
+ "contract": _VERIFICATION, **self._verifier.definition,
507
+ }
508
+ if self._context_sources:
509
+ tool_params["hostContext"] = {
510
+ "contract": _CONTEXT,
511
+ "sources": [item.definition for item in self._context_sources.values()],
512
+ }
513
+ if self._hooks:
514
+ filtered = {
515
+ name for hook in self._hooks.values()
516
+ for name in hook.definition.get("toolNames", ())
517
+ }
518
+ if any(
519
+ tool.source_name in filtered and tool.source_name in reserved
520
+ for tool in tools.values()
521
+ ):
522
+ raise ValueError("Harness Hook tool name overlaps an engine tool")
523
+ tool_params["hostHooks"] = {
524
+ "contract": _HOOKS, "hooks": list(self._hook_definitions(tools).values()),
525
+ **({"stopContinuationLimit": self._stop_hook_limit}
526
+ if self._stop_hook_limit is not None else {}),
527
+ }
528
+ if images:
529
+ limits = (hello.get("capabilities") or {}).get("inputImages")
530
+ if (
531
+ not isinstance(limits, dict)
532
+ or type(limits.get("maxCount")) is not int
533
+ or type(limits.get("maxEncodedBytes")) is not int
534
+ ):
535
+ raise ValueError("Harness service or its model does not support image input")
536
+ if (
537
+ len(images) > limits["maxCount"]
538
+ or sum(len(image["image_url"]["url"].encode("utf-8")) for image in images)
539
+ > limits["maxEncodedBytes"]
540
+ ):
541
+ raise ValueError("Harness service image input exceeded its limits")
542
+ earlier = [
543
+ {"role": row["role"], "text": row["content"]}
544
+ for row in rows
545
+ if row.get("role") in {"user", "assistant"} and isinstance(row.get("content"), str)
546
+ ]
547
+ if earlier and earlier[-1] == {"role": "user", "text": objective}:
548
+ earlier.pop()
549
+ started = await self._rpc(
550
+ session,
551
+ "run/start",
552
+ runId=handle.run_id,
553
+ objective=objective,
554
+ conversation=earlier,
555
+ hostInstructions=instructions,
556
+ **tool_params,
557
+ **({"inputImages": images} if images else {}),
558
+ )
559
+ view_hash = engine_view_hash(started.get("view"))
560
+ if view_hash:
561
+ handle.native_ref["view_sha256"] = view_hash
562
+ return handle
563
+
564
+ async def attach(self, handle: RunHandle) -> RunHandle:
565
+ session = self._session(handle)
566
+ await self._initialize(session)
567
+ await self._rpc(session, "run/status", runId=handle.run_id)
568
+ return handle
569
+
570
+ async def durable_restore(self, handle: RunHandle) -> RunHandle:
571
+ return await self.attach(handle)
572
+
573
+ async def resume(
574
+ self,
575
+ handle: RunHandle,
576
+ target: ResumeTarget,
577
+ payload: ResumePayload | None,
578
+ ) -> RunHandle:
579
+ if target.kind != "invocation_id" or target.id != handle.run_id:
580
+ raise UnsupportedControlError("Harness service can resume only the original Run")
581
+ session = self._session(await self.attach(handle))
582
+ if payload is not None and payload.kind == "approval_decision":
583
+ data = payload.data
584
+ decision = data.get("decision") if isinstance(data, dict) else None
585
+ if (
586
+ not self._durable_approvals
587
+ or not payload.call_id
588
+ or decision not in {"approve", "reject"}
589
+ ):
590
+ raise UnsupportedControlError(
591
+ "Harness service requires an explicit approval decision"
592
+ )
593
+ receipt = await self._rpc(
594
+ session,
595
+ "run/approve",
596
+ runId=handle.run_id,
597
+ interactionId=payload.call_id,
598
+ decision="allow" if decision == "approve" else "deny",
599
+ )
600
+ if receipt.get("status") not in {"accepted", "duplicate"}:
601
+ raise UnsupportedControlError("Harness service did not accept the approval")
602
+ return handle
603
+ if payload is not None and (payload.kind != "free_text" or payload.data is not None):
604
+ raise UnsupportedControlError(
605
+ "Harness service cannot append input while resuming a Run"
606
+ )
607
+ state = await self._rpc(session, "run/status", runId=handle.run_id)
608
+ if (
609
+ not state.get("running")
610
+ and not state.get("terminal")
611
+ and not state.get("pendingApproval")
612
+ ):
613
+ await self._rpc(session, "run/resume", runId=handle.run_id)
614
+ return handle
615
+
616
+ async def cancel(self, handle: RunHandle) -> CancelResult:
617
+ session = self._session(await self.attach(handle))
618
+ status = await self._rpc(session, "run/status", runId=handle.run_id)
619
+ if status["terminal"]:
620
+ return CancelResult.NOT_RUNNING
621
+ state = await self._rpc(session, "run/cancel", runId=handle.run_id)
622
+ if state.get("phase") == "canceled":
623
+ return CancelResult.INTERRUPTED_ACTIVE_TURN
624
+ return CancelResult.PENDING_CANCEL_RECORDED
625
+
626
+ def capabilities(self) -> RuntimeCapabilityMatrix:
627
+ native = RuntimeCapability(supported=True, mode="native")
628
+ controls = {name: native for name in self.runtime.native_capabilities()}
629
+ if self._durable_approvals:
630
+ controls.update(submit_interaction=native, interaction_mode="durable_resume")
631
+ return super().capabilities().model_copy(update=controls)
632
+
633
+ async def checkpoint(self, handle: RunHandle) -> CheckpointDescriptor:
634
+ raise UnsupportedControlError("Harness service resumes its own journal")
635
+
636
+ async def close(self, handle: RunHandle) -> None:
637
+ # Stream subscriptions own their HTTP requests. Releasing a handle
638
+ # must not cancel the service's independently owned Run.
639
+ self._session(handle)
640
+
641
+ async def close_all(self) -> None:
642
+ # The PluginHost activation owns connectors and their cleanup.
643
+ return None
644
+
645
+ async def stream(self, handle: RunHandle) -> AsyncIterator[RuntimeEvent]:
646
+ session = self._session(await self.attach(handle))
647
+ pump = (
648
+ asyncio.create_task(self._serve_host_callbacks(session, handle))
649
+ if self._load_tools is not None else None
650
+ )
651
+ try:
652
+ async for event in self._stream_events(session, handle):
653
+ yield event
654
+ finally:
655
+ if pump is not None:
656
+ pump.cancel()
657
+ await asyncio.gather(pump, return_exceptions=True)
658
+
659
+ async def _serve_host_callbacks(self, session: str, handle: RunHandle) -> None:
660
+ base = f"{self._endpoint}/v1/sessions/{session}"
661
+ clock = asyncio.get_running_loop().time
662
+ async with self._http(timeout=10) as client:
663
+ while True:
664
+ try:
665
+ started = clock()
666
+ response = await client.get(
667
+ base + "/host-requests", params={"runId": handle.run_id, "waitMs": 5000}
668
+ )
669
+ requests = []
670
+ if response.is_success:
671
+ requests = response.json().get("requests", [])
672
+ for frame in requests:
673
+ if not isinstance(frame, dict) or not isinstance(frame.get("id"), str):
674
+ continue
675
+ if frame.get("method") == "host/readContext":
676
+ result = await self._execute_host_context(handle, frame)
677
+ elif frame.get("method") == "host/invokeHook":
678
+ result = await self._execute_host_hook(handle, frame)
679
+ elif frame.get("method") == "host/verifyGoal":
680
+ result = await self._execute_host_verification(handle, frame)
681
+ else:
682
+ result = await self._execute_host_tool(handle, frame)
683
+ await client.post(base + "/host-reply", json={
684
+ "jsonrpc": "2.0", "id": frame["id"], "result": result,
685
+ })
686
+ except (httpx.HTTPError, ValueError, AttributeError, TypeError):
687
+ # The ledger retains the outcome of an interrupted call as
688
+ # uncertain. Never repeat a claimed callback after a lost reply.
689
+ pass
690
+ await asyncio.sleep(0.15)
691
+ continue
692
+ if not response.is_success or (not requests and clock() - started < 0.15):
693
+ await asyncio.sleep(0.15)
694
+
695
+ async def _execute_host_verification(
696
+ self, handle: RunHandle, frame: dict[str, Any],
697
+ ) -> dict[str, Any]:
698
+ params, expires, verifier = frame.get("params"), frame.get("expiresAt"), self._verifier
699
+ unavailable = {"code": "ksadk_verifier_unavailable"}
700
+ if (
701
+ verifier is None or not isinstance(params, dict)
702
+ or params.get("contract") != _VERIFICATION
703
+ or params.get("definition") != verifier.definition
704
+ or params.get("runId") != handle.run_id
705
+ or not isinstance(params.get("goal"), str)
706
+ or not verifier.applies(params["goal"])
707
+ or not isinstance(params.get("operationKey"), str)
708
+ or not isinstance(params.get("inputDigest"), str)
709
+ or handle.native_ref.get("resource_binding") != self._resource_binding
710
+ or type(expires) is not int or expires <= time.time() * 1000
711
+ ):
712
+ return unavailable
713
+ try:
714
+ async with asyncio.timeout_at(
715
+ asyncio.get_running_loop().time() + (expires / 1000 - time.time())
716
+ ):
717
+ result = await verifier.verify(handle, params)
718
+ except Exception:
719
+ return unavailable
720
+ return {
721
+ **result, "contract": _VERIFICATION, "operationKey": params["operationKey"],
722
+ "inputDigest": params["inputDigest"],
723
+ }
724
+
725
+ async def _execute_host_hook(self, handle: RunHandle, frame: dict[str, Any]) -> dict[str, Any]:
726
+ params = frame.get("params")
727
+ expires = frame.get("expiresAt")
728
+ unavailable = {"code": "ksadk_hook_unavailable"}
729
+ if (
730
+ not isinstance(params, dict)
731
+ or params.get("contract") != _HOOKS
732
+ or params.get("runId") != handle.run_id
733
+ or not isinstance(params.get("definition"), dict)
734
+ or not isinstance(params["definition"].get("hookId"), str)
735
+ or not isinstance(params.get("operationKey"), str)
736
+ or not isinstance(params.get("inputDigest"), str)
737
+ or type(expires) is not int
738
+ or expires <= time.time() * 1000
739
+ or handle.native_ref.get("resource_binding") != self._resource_binding
740
+ ):
741
+ return unavailable
742
+ identifier = params["definition"]["hookId"]
743
+ try:
744
+ async with asyncio.timeout_at(
745
+ asyncio.get_running_loop().time() + (expires / 1000 - time.time())
746
+ ):
747
+ tools = await self._tools()
748
+ hook = self._hooks.get(identifier)
749
+ if hook is None:
750
+ return unavailable
751
+ if self._hook_definitions(tools)[identifier] != params["definition"]:
752
+ return unavailable
753
+ if expires <= time.time() * 1000:
754
+ return unavailable
755
+ subject = params["input"]
756
+ call = subject.get("call")
757
+ if call is not None and (tool := tools.get(call["name"])) and tool.source_name:
758
+ subject = {**subject, "call": {**call, "name": tool.source_name}}
759
+ result = await hook.invoke(handle, {**params, "input": subject})
760
+ except Exception:
761
+ return unavailable
762
+ return {
763
+ "contract": _HOOKS, "operationKey": params["operationKey"],
764
+ "inputDigest": params["inputDigest"], **result,
765
+ }
766
+
767
+ async def _execute_host_context(
768
+ self, handle: RunHandle, frame: dict[str, Any],
769
+ ) -> dict[str, Any]:
770
+ params = frame.get("params")
771
+ expires = frame.get("expiresAt")
772
+ unavailable = {"code": "ksadk_context_unavailable"}
773
+ if (
774
+ not isinstance(params, dict)
775
+ or params.get("contract") != _CONTEXT
776
+ or params.get("runId") != handle.run_id
777
+ or not isinstance(params.get("sourceId"), str)
778
+ or type(expires) is not int
779
+ or handle.native_ref.get("resource_binding") != self._resource_binding
780
+ ):
781
+ return unavailable
782
+ source = self._context_sources.get(params["sourceId"])
783
+ if (
784
+ source is None
785
+ or source.definition["bindingDigest"] != params.get("bindingDigest")
786
+ or expires <= time.time() * 1000
787
+ ):
788
+ return unavailable
789
+ try:
790
+ async with asyncio.timeout_at(
791
+ asyncio.get_running_loop().time() + (expires / 1000 - time.time())
792
+ ):
793
+ items = await source.read(handle, params)
794
+ except Exception:
795
+ return unavailable
796
+ return {
797
+ "contract": _CONTEXT, "sourceId": params["sourceId"],
798
+ "bindingDigest": params["bindingDigest"], "items": items,
799
+ }
800
+
801
+ async def _execute_host_tool(self, handle: RunHandle, frame: dict[str, Any]) -> dict[str, Any]:
802
+ params = frame.get("params")
803
+ expires = frame.get("expiresAt")
804
+ unavailable = {"status": "error", "content": {"code": "ksadk_resource_unavailable"}}
805
+ if (
806
+ frame.get("method") != "host/callTool"
807
+ or not isinstance(params, dict)
808
+ or params.get("runId") != handle.run_id
809
+ or not isinstance(params.get("callId"), str)
810
+ or not isinstance(params.get("arguments"), dict)
811
+ or not isinstance(params.get("name"), str)
812
+ or type(expires) is not int
813
+ or handle.native_ref.get("resource_binding") != self._resource_binding
814
+ ):
815
+ return unavailable
816
+ try:
817
+ tool = (await self._tools()).get(params["name"])
818
+ if tool is None or expires <= time.time() * 1000:
819
+ return unavailable
820
+ if tool.effect is not None:
821
+ return await self._execute_tool_effect(handle, params, tool, expires)
822
+ if tool.call is None:
823
+ return unavailable
824
+ async with asyncio.timeout_at(
825
+ asyncio.get_running_loop().time() + (expires / 1000 - time.time())
826
+ ):
827
+ content = await tool.call(params["arguments"])
828
+ if len(json.dumps(content, ensure_ascii=False, allow_nan=False).encode()) > 1024 * 1024:
829
+ return {"status": "error", "content": {"code": "ksadk_resource_result_too_large"}}
830
+ except Exception:
831
+ return {"status": "error", "content": {"code": "ksadk_resource_execution_failed"}}
832
+ failed = isinstance(content, dict) and (
833
+ content.get("isError") is True or content.get("ok") is False
834
+ )
835
+ return {"status": "error" if failed else "ok", "content": content}
836
+
837
+ async def _execute_tool_effect(
838
+ self, handle: RunHandle, params: dict[str, Any], tool: ServiceHostTool, expires: int,
839
+ ) -> dict[str, Any]:
840
+ effect = params.get("effect")
841
+ if (
842
+ tool.effect is None
843
+ or not isinstance(effect, dict)
844
+ or effect.get("contract") != _TOOL_EFFECT
845
+ or not isinstance(effect.get("operationKey"), str)
846
+ or type(effect.get("approved")) is not bool
847
+ or type(effect.get("canRequestApproval")) is not bool
848
+ ):
849
+ return {"status": "error", "content": {"code": "ksadk_effect_unavailable"}}
850
+ try:
851
+ async with asyncio.timeout_at(
852
+ asyncio.get_running_loop().time() + (expires / 1000 - time.time())
853
+ ):
854
+ result = await tool.effect(handle, params)
855
+ if (
856
+ result.get("status") in {"ok", "error", "approval_required", "uncertain"}
857
+ and len(json.dumps(result, ensure_ascii=False, allow_nan=False).encode()) <= 1048576
858
+ ):
859
+ return result
860
+ except Exception:
861
+ pass
862
+ return {"status": "uncertain", "content": {"code": "ksadk_effect_outcome_unknown"}}
863
+
864
+ async def _stream_events(self, session: str, handle: RunHandle) -> AsyncIterator[RuntimeEvent]:
865
+ cursor = 0
866
+ while True:
867
+ page = await self._rpc(
868
+ session, "run/events", runId=handle.run_id, cursor=cursor, waitMs=5000, follow=True
869
+ )
870
+ for event in page["events"]:
871
+ if event.get("approvalContract") == _APPROVAL:
872
+ if not self._durable_approvals:
873
+ continue
874
+ state = await self._rpc(session, "run/status", runId=handle.run_id)
875
+ pending = state.get("pendingApproval") or {}
876
+ if pending.get("interactionId") != event.get("interactionId"):
877
+ continue
878
+ for item in _project(handle.run_id, event, handle.native_ref.get("view_sha256")):
879
+ if self._complete is not None and isinstance(item, RunCompleted):
880
+ try:
881
+ async with asyncio.timeout(10):
882
+ observed = await self._rpc(
883
+ session, _HOST_OBSERVATIONS, runId=handle.run_id,
884
+ )
885
+ if (
886
+ observed.get("contract") == _TOOL_EFFECT
887
+ and observed.get("runId") == handle.run_id
888
+ and handle.native_ref.get("resource_binding")
889
+ == self._resource_binding
890
+ ):
891
+ await self._complete(handle, observed)
892
+ except Exception:
893
+ _LOG.warning(
894
+ "Harness completed-Turn host outcome unknown",
895
+ extra={"run_id": handle.run_id},
896
+ )
897
+ yield item
898
+ if not page["events"] and not page["running"]:
899
+ state = await self._rpc(session, "run/status", runId=handle.run_id)
900
+ if state.get("terminal") or state.get("pendingApproval"):
901
+ return
902
+ if not state.get("running"):
903
+ raise RuntimeError("Harness Run stopped before delivering an outcome")
904
+ cursor = page["cursor"]
905
+
906
+
907
+ def harness_service_configured() -> bool:
908
+ return any(
909
+ key in os.environ for key in (
910
+ "KSADK_HARNESS_SERVICE_URL", "KSADK_HARNESS_SERVICE_TOKEN",
911
+ "KSADK_HARNESS_SERVICE_WORKSPACE",
912
+ )
913
+ )
914
+
915
+
916
+ def harness_service_from_env(
917
+ *, instructions: str = "", model: str | None = None,
918
+ ) -> HarnessServiceRuntimeAdapter | None:
919
+ if not harness_service_configured():
920
+ return None
921
+ endpoint = os.environ.get("KSADK_HARNESS_SERVICE_URL")
922
+ token = os.environ.get("KSADK_HARNESS_SERVICE_TOKEN")
923
+ workspace = os.environ.get("KSADK_HARNESS_SERVICE_WORKSPACE")
924
+ if workspace is not None:
925
+ mount = Path(workspace)
926
+ if not mount.is_absolute() or not mount.is_dir():
927
+ raise ValueError("invalid Harness service workspace mount")
928
+ return HarnessServiceRuntimeAdapter(
929
+ endpoint=endpoint or "",
930
+ token=token or "",
931
+ instructions=instructions,
932
+ model=model,
933
+ ca_file=os.environ.get("KSADK_HARNESS_SERVICE_CA_FILE"),
934
+ durable_approvals=os.environ.get("KSADK_HARNESS_SERVICE_DURABLE_APPROVALS") == "1",
935
+ )
936
+
937
+
938
+ def _project(
939
+ run_id: str,
940
+ event: dict[str, Any],
941
+ view_hash: str | None = None,
942
+ ) -> list[RuntimeEvent]:
943
+ seq = event["seq"] * 4
944
+ kind = event["kind"]
945
+ scope = run_id
946
+ presentation = engine_presentation(view_hash, event)
947
+ base: dict[str, Any] = {
948
+ # v1 journal frames have no clock. A stable sentinel keeps replay identical.
949
+ "schema_version": 2,
950
+ "seq": seq,
951
+ "timestamp": 0.0,
952
+ "run_id": run_id,
953
+ "scope_id": scope,
954
+ "source": SourceRef(
955
+ framework="ksadk",
956
+ native_run_id=run_id,
957
+ native_cursor=str(event["seq"]),
958
+ metadata={"harness_service_presentation": presentation} if presentation else {},
959
+ ),
960
+ }
961
+
962
+ def envelope(offset: int = 0) -> dict[str, Any]:
963
+ return {**base, "seq": seq + offset, "event_id": f"{run_id}:harness:{seq + offset}"}
964
+
965
+ if kind == "run.started":
966
+ return [RunStarted(**envelope(), status="running")]
967
+ if kind == "approval.requested" and event.get("approvalContract") == _APPROVAL:
968
+ interaction_id = event["interactionId"]
969
+ tool = event["title"]
970
+ return [
971
+ InteractionRequested(
972
+ **envelope(),
973
+ interaction_id=interaction_id,
974
+ interaction_kind="approval",
975
+ request=ApprovalRequest(
976
+ call_id=interaction_id,
977
+ kind=tool,
978
+ detail={"reason": event["detail"]} if event.get("detail") else None,
979
+ ),
980
+ )
981
+ ]
982
+ if kind == "model.completed" and isinstance(event.get("usage"), dict):
983
+ count = event["usage"]
984
+ input_tokens = count.get("inputTokens") or 0
985
+ output_tokens = count.get("outputTokens") or 0
986
+ events: list[RuntimeEvent] = [
987
+ UsageReported(
988
+ **envelope(),
989
+ input_tokens=input_tokens,
990
+ output_tokens=output_tokens,
991
+ total_tokens=input_tokens + output_tokens,
992
+ )
993
+ ]
994
+ if event.get("title") == "initial_plan" and isinstance(event.get("detail"), str):
995
+ events.append(RunProgress(**envelope(1), status="running", message=event["detail"]))
996
+ return events
997
+ if kind != "run.terminal":
998
+ if presentation or kind in {"tool.completed", "model.failure_observed"}:
999
+ return [RunProgress(**envelope(), status="running", message=event.get("title"))]
1000
+ return []
1001
+ phase, outcome, reason = event.get("title"), event.get("status"), event.get("reason")
1002
+ if phase == "canceled":
1003
+ return [RunCanceled(**envelope(), status="canceled", reason=reason)]
1004
+ if phase == "interrupted":
1005
+ return [RunInterrupted(**envelope(), status="interrupted", reason=reason)]
1006
+ if (
1007
+ phase != "completed" or outcome in {"failed", "budget_exhausted"}
1008
+ or event.get("requiredVerification") is True and outcome != "verified"
1009
+ ):
1010
+ return [
1011
+ RunFailed(
1012
+ **envelope(),
1013
+ status="failed",
1014
+ error=ErrorInfo(
1015
+ code=reason or "harness_run_failed", source="runtime", scope_id=scope
1016
+ ),
1017
+ )
1018
+ ]
1019
+ text = event.get("detail")
1020
+ if not text:
1021
+ return [RunCompleted(**envelope(), status="completed", output_refs=())]
1022
+ item_id = f"{run_id}:answer"
1023
+ snapshot = ContentSnapshot(parts=(TextContent(part_id=f"{item_id}:text", text=text),))
1024
+ return [
1025
+ ItemStarted(
1026
+ **envelope(),
1027
+ item_id=item_id,
1028
+ item_kind="message",
1029
+ phase="final_answer",
1030
+ initial=snapshot,
1031
+ ),
1032
+ ItemCompleted(**envelope(1), item_id=item_id, item_kind="message", snapshot=snapshot),
1033
+ RunCompleted(
1034
+ **envelope(2),
1035
+ status="completed",
1036
+ output_refs=(OutputRef(scope_id=scope, item_id=item_id),),
1037
+ ),
1038
+ ]