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,198 @@
1
+ """Expose PluginHost-owned MCP and Skills to the independent engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ksadk._mcp_compat import tool_input_schema
6
+
7
+ import hashlib
8
+ import json
9
+ import re
10
+ from contextlib import AsyncExitStack
11
+ from typing import TYPE_CHECKING, Any
12
+
13
+ from ksadk.harness.native.hook_executor import HookAuthorizer
14
+ from ksadk.harness.service_runtime import HarnessServiceRuntimeAdapter, ServiceHostTool
15
+ from ksadk.plugins.host import PluginExecutionContext, PluginHostError
16
+ from ksadk.plugins.providers.harness_contributions import McpToolSpecTransport, ProviderSkillSource
17
+ from ksadk.plugins.providers.harness_service_context import service_context_sources
18
+ from ksadk.plugins.providers.harness_service_hooks import service_hooks
19
+ from ksadk.plugins.providers.harness_service_memory import (
20
+ service_local_memory,
21
+ service_memory_verifier,
22
+ )
23
+ from ksadk.plugins.providers.platform_resources import (
24
+ PLATFORM_RESOURCE_MCP_NAME,
25
+ PLATFORM_RESOURCE_MCP_PLUGIN_ID,
26
+ PLATFORM_RESOURCE_MCP_PLUGIN_VERSION,
27
+ )
28
+ from ksadk.runtime import StartRequest
29
+ from ksadk.studio.contracts import ExecutionSpec, MemorySpec
30
+
31
+ if TYPE_CHECKING:
32
+ from ksadk.plugins.providers.harness import HarnessEngineActivationContext
33
+
34
+
35
+ def admit_service_memory(
36
+ context: HarnessEngineActivationContext, capabilities: PluginExecutionContext,
37
+ ) -> None:
38
+ """Platform memory uses its locked connector and existing worker write gate."""
39
+ policy = MemorySpec.model_validate(context.bundle.resolved_agent_spec.get("memory") or {})
40
+ if not policy.enabled or not policy.scopes or policy.provider_ref == "local-default":
41
+ return
42
+ connectors = capabilities.all("mcp.connector/v1", slot="mcp.platform-resources")
43
+ if (
44
+ policy.provider_ref.startswith("binding://")
45
+ and len(context.memory_sources) == 1 and len(connectors) == 1
46
+ ):
47
+ memory = context.memory_sources[0]
48
+ connector = connectors[0]
49
+ if (
50
+ memory.slot == "memory.primary"
51
+ and memory.plugin_id == connector.plugin_id == PLATFORM_RESOURCE_MCP_PLUGIN_ID
52
+ and memory.plugin_version == connector.plugin_version
53
+ and memory.plugin_version == PLATFORM_RESOURCE_MCP_PLUGIN_VERSION
54
+ and memory.runtime is connector.runtime
55
+ and any(spec.name == PLATFORM_RESOURCE_MCP_NAME for spec in context.config.mcp_tools)
56
+ ):
57
+ return
58
+ raise PluginHostError(
59
+ "harness_service_memory_unsupported",
60
+ "Independent Harness requires the locked platform memory connector for this activation",
61
+ )
62
+
63
+
64
+ def bind_service_resources(
65
+ adapter: HarnessServiceRuntimeAdapter,
66
+ context: HarnessEngineActivationContext,
67
+ cleanup: AsyncExitStack,
68
+ *,
69
+ hook_authorizer: HookAuthorizer | None = None,
70
+ hook_authorization_version: str | None = None,
71
+ ) -> None:
72
+ credentials = {item.name: item for item in context.mcp_runtime_credentials}
73
+ transports = []
74
+ for spec in context.config.mcp_tools:
75
+ transport = McpToolSpecTransport(spec, credential=credentials.get(spec.name))
76
+ cleanup.push_async_callback(transport.close)
77
+ transports.append((spec.name, transport))
78
+ skills = ProviderSkillSource(context.skills)
79
+ memory = service_local_memory(context)
80
+
81
+ async def check_activation() -> None:
82
+ if context.activation_available is not None and not context.activation_available():
83
+ raise RuntimeError("Harness activation is no longer available")
84
+
85
+ async def check_mcp() -> None:
86
+ await check_activation()
87
+ if context.mcp_available is not None and not await context.mcp_available():
88
+ raise RuntimeError("Harness MCP binding is no longer available")
89
+
90
+ async def list_skills(_: dict[str, Any]) -> Any:
91
+ await check_activation()
92
+ manifests = []
93
+ for ref in skills.refs:
94
+ manifest = skills.manifest(ref)
95
+ manifests.append({"ref": ref, "name": manifest.name, "summary": manifest.summary})
96
+ return manifests
97
+
98
+ async def read_skill(arguments: dict[str, Any]) -> Any:
99
+ await check_activation()
100
+ ref = arguments["ref"]
101
+ path = arguments.get("path")
102
+ if not isinstance(ref, str) or (path is not None and not isinstance(path, str)):
103
+ raise ValueError("invalid Skill resource request")
104
+ if path is None:
105
+ return skills.full_text(ref)
106
+ return skills.resource(ref, path).decode("utf-8")
107
+
108
+ async def load_tools() -> tuple[ServiceHostTool, ...]:
109
+ await check_activation()
110
+ result = memory.tools() if memory is not None else []
111
+ if skills.refs:
112
+ result.extend((
113
+ ServiceHostTool(
114
+ "ksadk_skill_list", "List Skills bound to this Agent.",
115
+ {"type": "object", "properties": {}, "additionalProperties": False},
116
+ list_skills, read_only=True,
117
+ ),
118
+ ServiceHostTool(
119
+ "ksadk_skill_read", "Read a bound Skill or one of its UTF-8 text resources.",
120
+ {"type": "object", "properties": {
121
+ "ref": {"type": "string"}, "path": {"type": "string"},
122
+ }, "required": ["ref"], "additionalProperties": False},
123
+ read_skill, read_only=True,
124
+ ),
125
+ ))
126
+ for server, transport in transports:
127
+ await check_mcp()
128
+ for definition in await transport.list_tools():
129
+ original_name = definition["name"]
130
+ canonical = json.dumps([server, definition], sort_keys=True, allow_nan=False)
131
+ digest = hashlib.sha256(canonical.encode()).hexdigest()[:20]
132
+ label = re.sub(r"[^A-Za-z0-9_]", "_", original_name)[:30]
133
+
134
+ async def call(arguments, *, bound=transport, name=original_name):
135
+ await check_mcp()
136
+ return await bound.call_tool(name, arguments)
137
+
138
+ result.append(ServiceHostTool(
139
+ f"ksadk_mcp_{label}_{digest}", definition["description"],
140
+ tool_input_schema(definition), call, deferred=True, source_name=original_name,
141
+ ))
142
+ return tuple(result)
143
+
144
+ claims = dict(context.activation_claims)
145
+ scope = {"agent_id": context.agent_name}
146
+ scope.update({key: claims[key] for key in ("user_id", "session_id") if key in claims})
147
+ if claims.get("agent_id", context.agent_name) != context.agent_name or (
148
+ "session_id" in scope and scope["session_id"] != context.activation_key
149
+ ):
150
+ raise PluginHostError(
151
+ "harness_service_activation_unbound", "Invalid Harness activation scope",
152
+ )
153
+ identity = json.dumps([
154
+ context.agent_name, context.activation_key, context.profile_digest,
155
+ context.plugin_lock_digest, context.bundle.bundle_digest, claims,
156
+ ], sort_keys=True)
157
+
158
+ async def turn_context(request: StartRequest, rows: list[dict[str, Any]]) -> list[str]:
159
+ from ksadk.plugins.providers.harness import HarnessTurnRequest
160
+
161
+ await check_activation()
162
+ turn = HarnessTurnRequest(
163
+ user_id=request.user_id, session_id=request.session_id, messages=tuple(rows),
164
+ model=request.model, request_metadata=request.metadata,
165
+ invocation_id=request.metadata.get("invocation_id") or request.metadata.get("run_id"),
166
+ )
167
+ return [
168
+ text.strip()
169
+ for binding in context.context_sources
170
+ if not binding.contributor
171
+ and (text := await binding.runtime.harness_context(context.bundle, turn)).strip()
172
+ ]
173
+
174
+ hooks, stop_limit = service_hooks(
175
+ context, cleanup, authorize=hook_authorizer,
176
+ authorization_version=hook_authorization_version,
177
+ )
178
+ execution = ExecutionSpec.model_validate(
179
+ context.bundle.resolved_agent_spec.get("execution") or {},
180
+ )
181
+ limits = execution.native_call_limits()
182
+ adapter.bind_read_only_workspace(
183
+ binding=hashlib.sha256(identity.encode()).hexdigest(),
184
+ model=context.config.model, load_tools=load_tools, context=turn_context,
185
+ scope=scope,
186
+ context_sources=(*service_context_sources(context),
187
+ *(memory.context_sources() if memory else ())),
188
+ hooks=(*hooks, *(memory.hooks() if memory else ())), stop_hook_limit=stop_limit,
189
+ tool_effects=memory.writes if memory is not None else False,
190
+ complete=memory.complete if memory and memory.flush_after else None,
191
+ verifier=service_memory_verifier(context, memory),
192
+ execution_policy={
193
+ "strategy": execution.strategy,
194
+ "maxWallMs": execution.timeout_seconds * 1000 or None,
195
+ "maxModelCalls": limits.max_model_calls,
196
+ "maxToolCalls": limits.max_tool_calls,
197
+ },
198
+ )
@@ -0,0 +1,175 @@
1
+ """Project authenticated, frozen Context Contributors into the service protocol."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import time
8
+ from dataclasses import dataclass
9
+ from typing import TYPE_CHECKING, Any
10
+
11
+ from ksadk.harness.service_runtime import ServiceContextSource
12
+ from ksadk.plugins.context_contributor import (
13
+ AuthenticatedContextScope,
14
+ ContextContributorExchange,
15
+ ContextContributorRequest,
16
+ ContextContributorResponse,
17
+ )
18
+ from ksadk.plugins.contracts import plugin_lock_digest
19
+ from ksadk.plugins.host import PluginHostError
20
+ from ksadk.plugins.providers.harness_context import (
21
+ HarnessContextContributorConfiguration,
22
+ HarnessContextContributorSource,
23
+ )
24
+ from ksadk.plugins.resolver import composition_profile_digest
25
+ from ksadk.runtime import RunHandle
26
+
27
+ if TYPE_CHECKING:
28
+ from ksadk.plugins.providers.harness import HarnessEngineActivationContext
29
+
30
+
31
+ def _locked_graph(context: HarnessEngineActivationContext) -> None:
32
+ graph = context.bundle.composition
33
+ if (
34
+ context.profile_digest != graph.profile_digest
35
+ or context.profile_digest != composition_profile_digest(graph.profile)
36
+ or context.profile_digest != context.bundle.manifest.composition_profile_digest
37
+ or context.plugin_lock_digest != graph.plugin_lock_digest
38
+ or context.plugin_lock_digest != plugin_lock_digest(graph.plugin_lock)
39
+ or context.plugin_lock_digest != context.bundle.manifest.plugin_lock_digest
40
+ ):
41
+ raise PluginHostError(
42
+ "harness_service_context_unbound", "Context differs from the locked plugin graph",
43
+ )
44
+
45
+
46
+ @dataclass
47
+ class _Contributor:
48
+ context: HarnessEngineActivationContext
49
+ runtime: HarnessContextContributorSource
50
+ config: HarnessContextContributorConfiguration
51
+ scope: dict[str, str]
52
+ cached: tuple[tuple[str, int, int], float, list[dict[str, Any]]] | None = None
53
+
54
+ def check_available(self) -> None:
55
+ available = self.context.activation_available
56
+ if available is not None and not available():
57
+ raise ValueError("Harness context activation is unavailable")
58
+ _locked_graph(self.context)
59
+
60
+ async def read(self, handle: RunHandle, params: dict[str, Any]) -> list[dict[str, Any]]:
61
+ self.check_available()
62
+ remaining = params["remainingTokens"]
63
+ revision = params["goalRevision"]
64
+ if type(remaining) is not int or remaining < 0 or type(revision) is not int or revision < 0:
65
+ raise ValueError("Invalid Harness context budget or goal revision")
66
+ if handle.session_id != self.scope["session_id"]:
67
+ raise ValueError("Harness context session differs from activation")
68
+ budget = min(remaining, self.config.capabilities.max_tokens)
69
+ cache_key = (handle.run_id, revision, budget)
70
+ cache = self.cached
71
+ if cache is not None and cache[0] == cache_key and cache[1] > time.time():
72
+ return cache[2]
73
+ workspace = self.context.user_workspace_root or self.context.workspace_root
74
+ request = ContextContributorRequest(
75
+ request_format="ksadk.context-request/v1",
76
+ scope=AuthenticatedContextScope(
77
+ authenticated=True,
78
+ actor_id=self.scope["user_id"],
79
+ agent_id=self.scope["agent_id"],
80
+ session_id=handle.session_id,
81
+ turn_id=params["turnId"],
82
+ ),
83
+ invocation_id=params["operationKey"],
84
+ user_input=params["goal"],
85
+ workspace_root=str(workspace),
86
+ policy_ref=self.config.policy_ref,
87
+ remaining_budget=budget,
88
+ allowed_classifications=self.config.allowed_classifications,
89
+ metadata={
90
+ "tenant_id": self.scope["tenant_id"], "workspace_id": self.scope["workspace_id"],
91
+ "run_id": handle.run_id, "goal_revision": revision,
92
+ },
93
+ )
94
+ response = await self.runtime.harness_context_contribution(self.context.bundle, request)
95
+ if not isinstance(response, ContextContributorResponse):
96
+ raise ValueError("Invalid Harness context response")
97
+ exchange = ContextContributorExchange(
98
+ contract_format="ksadk.context-contributor/v1", capabilities=self.config.capabilities,
99
+ request=request, response=response,
100
+ )
101
+ exchange.project()
102
+ self.check_available()
103
+ if len(response.fragments) > 64 or len(response.model_dump_json()) > self.config.max_chars:
104
+ raise ValueError("Harness context response exceeded its grant")
105
+ items = []
106
+ expires = float("inf")
107
+ for fragment in response.fragments:
108
+ role = fragment.metadata.get("role")
109
+ privileged = fragment.kind == "compiled_prompt" or (
110
+ isinstance(role, str) and role in {"system", "developer"}
111
+ )
112
+ items.append({
113
+ "projection": "instructions" if privileged else "data",
114
+ "fragment": fragment.model_dump(mode="json", by_alias=True),
115
+ **({"expiresAt": int(fragment.expires_at.timestamp() * 1000)}
116
+ if fragment.expires_at else {}),
117
+ })
118
+ if fragment.expires_at is not None:
119
+ expires = min(expires, fragment.expires_at.timestamp())
120
+ if self.config.capabilities.cacheability != "none":
121
+ self.cached = (cache_key, expires, items)
122
+ return items
123
+
124
+
125
+ def service_context_sources(
126
+ context: HarnessEngineActivationContext,
127
+ ) -> tuple[ServiceContextSource, ...]:
128
+ bindings = tuple(binding for binding in context.context_sources if binding.contributor)
129
+ if not bindings:
130
+ return ()
131
+ claims = dict(context.activation_claims)
132
+ if (
133
+ any(not claims.get(key, "").strip() for key in ("tenant_id", "workspace_id", "user_id"))
134
+ or claims.get("agent_id") != context.agent_name
135
+ or claims.get("session_id") != context.activation_key
136
+ or not context.activation_key
137
+ ):
138
+ raise PluginHostError(
139
+ "harness_service_context_unbound", "Context requires authenticated activation claims",
140
+ )
141
+ _locked_graph(context)
142
+ graph = context.bundle.composition
143
+ result = []
144
+ for binding in bindings:
145
+ ref = f"plugin://{binding.plugin_id}@{binding.plugin_version}"
146
+ declarations = [item for item in graph.profile.capabilities if item.ref == ref]
147
+ offers = [
148
+ offer for entry in graph.plugin_lock.plugins for offer in entry.provides
149
+ if entry.id == binding.plugin_id and entry.version == binding.plugin_version
150
+ and offer.owner == binding.plugin_id and offer.definition == "context.contributor/v1"
151
+ and offer.slot == binding.slot
152
+ ]
153
+ if len(declarations) != 1 or len(offers) != 1 or not isinstance(
154
+ binding.runtime, HarnessContextContributorSource
155
+ ):
156
+ raise PluginHostError(
157
+ "harness_service_context_unbound", "Context source differs from the locked offer",
158
+ )
159
+ config = HarnessContextContributorConfiguration.model_validate(declarations[0].config)
160
+ caps = config.capabilities
161
+ if not caps.max_tokens:
162
+ continue
163
+ identity = json.dumps([
164
+ context.bundle.bundle_digest, context.profile_digest, context.plugin_lock_digest,
165
+ ref, binding.slot, config.model_dump(mode="json"), claims,
166
+ ], ensure_ascii=False, sort_keys=True)
167
+ source = _Contributor(context, binding.runtime, config, claims)
168
+ result.append(ServiceContextSource({
169
+ "sourceId": "ksadk-context-" + hashlib.sha256(ref.encode()).hexdigest()[:24],
170
+ "bindingDigest": "sha256:" + hashlib.sha256(identity.encode()).hexdigest(),
171
+ "maxTokens": caps.max_tokens, "maxBytes": config.max_chars,
172
+ "timeoutMs": caps.timeout_ms, "failureMode": caps.failure_mode,
173
+ "allowInstructions": caps.trust_level in {"developer", "platform"},
174
+ }, source.read))
175
+ return tuple(result)
@@ -0,0 +1,168 @@
1
+ """Bind Python Hook producers and host authorization to independent Runs."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from contextlib import AsyncExitStack
8
+ from typing import TYPE_CHECKING, Any
9
+
10
+ from ksadk.harness.native.hook_executor import HookAuthorizer, HookBinding, ScopedHookExecutor
11
+ from ksadk.harness.native.hook_runtime_contract import HookInvocationRequest, PreCompactSubject
12
+ from ksadk.harness.native.model import ModelToolCall
13
+ from ksadk.harness.service_runtime import ServiceHook
14
+ from ksadk.plugins.providers.harness_hooks import hook_configuration
15
+ from ksadk.runtime import RunHandle
16
+ from ksadk.studio.native_hook_registration import validate_hook_authorization_policy
17
+ from ksadk.studio.native_scope import native_scope_from_activation
18
+
19
+ if TYPE_CHECKING:
20
+ from ksadk.harness.native.hook_runtime_contract import HookDefinition
21
+ from ksadk.plugins.providers.harness import HarnessEngineActivationContext
22
+
23
+
24
+ def _tool_result(result: dict[str, Any] | None) -> dict[str, Any] | None:
25
+ if result is None:
26
+ return None
27
+ usage = result.get("resourceUsage") or {}
28
+ counters = {
29
+ "modelCalls": "model_calls", "toolCalls": "tool_calls",
30
+ "inputTokens": "input_tokens", "outputTokens": "output_tokens",
31
+ "cachedInputTokens": "cached_input_tokens", "reasoningTokens": "reasoning_tokens",
32
+ }
33
+ artifacts = []
34
+ for item in result.get("artifactRefs", []):
35
+ digest = item["digest"]
36
+ artifacts.append({
37
+ "uri": item["uri"], "content_hash": digest if ":" in digest else "sha256:" + digest,
38
+ "mime_type": item["mediaType"], "size_bytes": item["sizeBytes"],
39
+ })
40
+ return {
41
+ "status": result["status"], "content": result["content"],
42
+ "workspace_changed_paths": result.get("workspaceChangedPaths") or [],
43
+ "artifact_refs": artifacts,
44
+ "resource_usage": {
45
+ **{target: usage[key] for key, target in counters.items() if key in usage},
46
+ "child_run_ids": result.get("childRunIds") or [],
47
+ },
48
+ }
49
+
50
+
51
+ def _compaction(value: dict[str, Any] | None) -> PreCompactSubject | None:
52
+ if value is None:
53
+ return None
54
+ return PreCompactSubject.model_validate({
55
+ "source_revision": value["sourceRevision"],
56
+ "source_context_digest": value["sourceContextDigest"],
57
+ "source_message_count": value["sourceMessageCount"],
58
+ "message_refs": value["messageRefs"], "messages": value["messages"],
59
+ "retained_message_refs": value["retainedMessageRefs"],
60
+ **({"source_projection": "canonical_user"}
61
+ if value.get("sourceProjection") == "canonical_user" else {}),
62
+ })
63
+
64
+
65
+ def service_hooks(
66
+ context: HarnessEngineActivationContext,
67
+ cleanup: AsyncExitStack,
68
+ *,
69
+ authorize: HookAuthorizer | None,
70
+ authorization_version: str | None,
71
+ ) -> tuple[tuple[ServiceHook, ...], int | None]:
72
+ if not context.hook_sources:
73
+ return (), None
74
+ scope = native_scope_from_activation(context)
75
+ validate_hook_authorization_policy(authorize, authorization_version)
76
+ if context.activation_available is None or not context.activation_generation:
77
+ raise ValueError("Harness hooks require an owned PluginHost activation")
78
+ bundle = context.bundle
79
+ manifest_json = bundle.manifest.model_dump_json()
80
+ profile_json = bundle.composition.profile.model_dump_json()
81
+ lock_json = bundle.composition.plugin_lock.model_dump_json()
82
+
83
+ def available() -> bool:
84
+ return (
85
+ context.activation_available() is True
86
+ and bundle.manifest.model_dump_json() == manifest_json
87
+ and bundle.composition.profile.model_dump_json() == profile_json
88
+ and bundle.composition.plugin_lock.model_dump_json() == lock_json
89
+ )
90
+
91
+ async def admitted(request: HookInvocationRequest) -> str:
92
+ if authorize is None or not available():
93
+ return "deny"
94
+ return await authorize(request)
95
+
96
+ bindings = []
97
+ stop_limits = set()
98
+ for source in context.hook_sources:
99
+ config = hook_configuration(bundle, source)
100
+ ref = f"plugin://{source.plugin_id}@{source.plugin_version}"
101
+ identity = json.dumps([
102
+ bundle.bundle_digest, context.profile_digest, context.plugin_lock_digest,
103
+ ref, source.slot, config.model_dump(mode="json"), authorization_version,
104
+ "engine-hooks/v1",
105
+ ], sort_keys=True)
106
+ binding_digest = "sha256:" + hashlib.sha256(identity.encode()).hexdigest()
107
+ definitions = config.definitions(source_ref=ref, binding_digest=binding_digest)
108
+ if config.stop_continuation_limit is not None:
109
+ stop_limits.add(config.stop_continuation_limit)
110
+
111
+ async def callback(request, *, read=source.runtime.harness_hook):
112
+ return await read(bundle, request)
113
+
114
+ executor = ScopedHookExecutor(
115
+ scope=scope, bindings=tuple(HookBinding(item, callback, available)
116
+ for item in definitions),
117
+ authorize=admitted if authorize is not None else None,
118
+ cleanup_timeout_seconds=config.cleanup_timeout_seconds,
119
+ )
120
+ cleanup.push_async_callback(executor.aclose)
121
+
122
+ for item in definitions:
123
+ async def invoke(
124
+ handle: RunHandle, params: dict[str, Any],
125
+ *, hook: HookDefinition = item, owner: ScopedHookExecutor = executor,
126
+ ) -> dict[str, Any]:
127
+ if handle.session_id != context.activation_key:
128
+ raise ValueError("Harness Hook session differs from activation")
129
+ payload = params["input"]
130
+ call, candidate = payload["call"], payload["candidate"]
131
+ request = HookInvocationRequest(
132
+ scope=scope, run_id=handle.run_id, session_id=handle.session_id,
133
+ turn_id=params["turnId"], operation_key=params["operationKey"],
134
+ goal_revision=params["goalRevision"], goal=payload["goal"],
135
+ tool_call_count=payload["toolCallCount"],
136
+ stop_continuation_count=payload["stopContinuationCount"],
137
+ event=params["event"], definition=hook,
138
+ call=ModelToolCall(
139
+ call_id=call["callId"], name=call["name"], arguments=call["arguments"],
140
+ ) if call else None,
141
+ tool_result=_tool_result(payload["toolResult"]),
142
+ candidate_id=candidate["candidateId"] if candidate else None,
143
+ candidate_text=candidate["text"] if candidate else None,
144
+ compaction=_compaction(payload["compaction"]),
145
+ )
146
+ result = await owner.invoke(request)
147
+ output = result.output
148
+ return {
149
+ "status": result.status, "reason": result.reason,
150
+ "output": {"action": output.action,
151
+ "additionalContext": list(output.additional_context),
152
+ "updatedArguments": output.updated_arguments} if output else None,
153
+ }
154
+
155
+ bindings.append(ServiceHook({
156
+ "hookId": item.hook_id, "sourceRef": item.source_ref,
157
+ "bindingDigest": item.binding_digest,
158
+ "executionPolicyDigest": item.execution_policy_digest,
159
+ "readOnly": item.read_only, "events": list(item.events),
160
+ "timeoutMs": item.timeout_seconds * 1000, "maxInputBytes": item.max_input_bytes,
161
+ "maxOutputBytes": item.max_output_bytes, "failureMode": item.failure_mode,
162
+ **({"toolNames": list(item.tool_names)} if item.tool_names else {}),
163
+ **({"compactionSourceProjection": item.compaction_source_projection}
164
+ if item.compaction_source_projection else {}),
165
+ }, invoke))
166
+ if len(stop_limits) > 1:
167
+ raise ValueError("Conflicting Harness Stop continuation limits")
168
+ return tuple(bindings), next(iter(stop_limits), None)