agentengine-sdk-python 0.8.8__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.
- {agentengine_sdk_python-0.8.8.dist-info → agentengine_sdk_python-0.8.9.dist-info}/METADATA +12 -15
- {agentengine_sdk_python-0.8.8.dist-info → agentengine_sdk_python-0.8.9.dist-info}/RECORD +181 -173
- ksadk/_build_provenance.json +1 -1
- ksadk/agui/agent.py +1 -1
- ksadk/builders/framework_requirements.py +1 -1
- ksadk/cli/cmd_run.py +4 -0
- ksadk/cli/cmd_web.py +4 -0
- ksadk/cli/runtime_logging.py +30 -0
- ksadk/context_engine/capabilities.py +13 -9
- ksadk/conversations/context.py +5 -0
- ksadk/conversations/message_projection.py +28 -19
- ksadk/conversations/runtime_compaction.py +6 -2
- ksadk/conversations/runtime_input.py +4 -0
- ksadk/conversations/runtime_invocation.py +5 -1
- ksadk/conversations/runtime_metadata.py +6 -7
- ksadk/conversations/runtime_payloads.py +5 -1
- ksadk/conversations/runtime_persistence.py +23 -0
- ksadk/conversations/runtime_preparation.py +128 -5
- ksadk/events/adapters/langgraph.py +53 -1
- ksadk/kernel/control.py +16 -22
- ksadk/kernel/history_projection.py +191 -58
- ksadk/kernel/ingress.py +16 -2
- ksadk/kernel/postgres_event_log.py +10 -2
- ksadk/kernel/postgres_store.py +81 -2
- ksadk/kernel/run_references.py +38 -0
- ksadk/kernel/worker_controls.py +11 -1
- ksadk/mcp_runtime/oauth/kernel.py +5 -0
- ksadk/mcp_runtime/oauth/local/broker.py +18 -8
- ksadk/mcp_runtime/oauth/local/protocol.py +3 -11
- ksadk/mcp_runtime/oauth/local/transport.py +9 -2
- ksadk/resource_runtime/contracts.py +39 -1
- ksadk/resource_runtime/managed_projection.py +8 -6
- ksadk/resource_runtime/worker.py +8 -1
- ksadk/runners/_adk_canonical_stream.py +16 -15
- ksadk/runners/_langgraph_answer_contract.py +1 -7
- ksadk/runners/_langgraph_canonical_stream.py +13 -6
- ksadk/runners/_langgraph_context.py +265 -0
- ksadk/runners/_langgraph_model_budget.py +397 -0
- ksadk/runners/_langgraph_runner_streams.py +7 -6
- ksadk/runners/adk_runner.py +13 -21
- ksadk/runners/langgraph_runner.py +130 -8
- ksadk/runners/usage_accumulator.py +40 -0
- ksadk/runtime/conversation_execution.py +26 -4
- ksadk/server/factory.py +3 -1
- ksadk/server/routes/control.py +24 -8
- ksadk/server/routes/history_items.py +157 -0
- ksadk/server/routes/kernel_ingress.py +51 -12
- ksadk/server/routes/local_kernel_control.py +16 -0
- ksadk/server/routes/models.py +26 -0
- ksadk/server/routes/openai_compat.py +10 -3
- ksadk/server/routes/projection.py +4 -0
- ksadk/server/routes/run.py +4 -2
- ksadk/server/routes/sessions.py +20 -1
- ksadk/server/static/assets/{ArtifactsPanel-Cdr5C_vM.js → ArtifactsPanel-iZ_6CAQ2.js} +1 -1
- ksadk/server/static/assets/{CodeBlock-BWRafud9.js → CodeBlock-D6uglm5n.js} +1 -1
- ksadk/server/static/assets/{MathMessageMarkdown-CFKeJIvy.js → MathMessageMarkdown-D6ojdxCG.js} +1 -1
- ksadk/server/static/assets/{MermaidBlock-BneAGUOd.js → MermaidBlock-Csk2ivT7.js} +6 -6
- ksadk/server/static/assets/{NativeTerminalPanel-BHI85zDO.js → NativeTerminalPanel-CCJA1XSH.js} +1 -1
- ksadk/server/static/assets/{OfficialA2uiRenderer-BOmT36lJ.js → OfficialA2uiRenderer-C06jus9N.js} +1 -1
- ksadk/server/static/assets/{abnfDiagram-VCTEODGH-DQvlOsBI.js → abnfDiagram-VCTEODGH-BhrF5tmL.js} +1 -1
- ksadk/server/static/assets/{arc-CGx0e4pN.js → arc-Btsh3kfy.js} +1 -1
- ksadk/server/static/assets/architecture-7GRP2DOG-BSXho3cq.js +1 -0
- ksadk/server/static/assets/{architectureDiagram-5GKGNRK7-WyybcNKX.js → architectureDiagram-5GKGNRK7-Cl8MfAmp.js} +1 -1
- ksadk/server/static/assets/{blockDiagram-NRAW4CY4-C9Cx_GVs.js → blockDiagram-NRAW4CY4-CeHSr8E_.js} +1 -1
- ksadk/server/static/assets/{c4Diagram-UCG6FXSJ-Bh7X3bGr.js → c4Diagram-UCG6FXSJ-BSD7RUKo.js} +1 -1
- ksadk/server/static/assets/channel-BpyDVKis.js +1 -0
- ksadk/server/static/assets/chunk-2Q5K7J3B-HLcpmPI2.js +1 -0
- ksadk/server/static/assets/{chunk-5VM5RSS4-cP9XupZj.js → chunk-5VM5RSS4-wz0pkBjp.js} +1 -1
- ksadk/server/static/assets/{chunk-F27PBJKO-Bm77fvR9.js → chunk-F27PBJKO-shjQ7cPM.js} +1 -1
- ksadk/server/static/assets/{chunk-G27WJ6UU-DDKNPesQ.js → chunk-G27WJ6UU-DL_MfUsu.js} +1 -1
- ksadk/server/static/assets/{chunk-JWPE2WC7-BqiUDB7s.js → chunk-JWPE2WC7-moUdwYpb.js} +1 -1
- ksadk/server/static/assets/{chunk-LCL6LL3I-C528mMZy.js → chunk-LCL6LL3I-B3QcDsZM.js} +1 -1
- ksadk/server/static/assets/{chunk-POPQ4Y6H-CzZ9g_Uf.js → chunk-POPQ4Y6H-BLBKb48A.js} +1 -1
- ksadk/server/static/assets/{chunk-RHFEMEQ7-CXj4tUZ-.js → chunk-RHFEMEQ7-CXR6ZzOx.js} +1 -1
- ksadk/server/static/assets/{chunk-SVP7TREG-BHyd85pS.js → chunk-SVP7TREG-DoR8BxkO.js} +1 -1
- ksadk/server/static/assets/{chunk-XXDRQBXY-Qe29PHGe.js → chunk-XXDRQBXY-8HJaIq0q.js} +1 -1
- ksadk/server/static/assets/classDiagram-DTDB5LWJ-DlNiRtSN.js +1 -0
- ksadk/server/static/assets/classDiagram-v2-JRS7N3AN-DlNiRtSN.js +1 -0
- ksadk/server/static/assets/{cose-bilkent-JH36ORCC-maRKgeec.js → cose-bilkent-JH36ORCC-DnSSHHqS.js} +1 -1
- ksadk/server/static/assets/cynefin-OW5HDTMX-DxNym3qg.js +1 -0
- ksadk/server/static/assets/{cynefinDiagram-5FMLGOSQ-CoD0bEvn.js → cynefinDiagram-5FMLGOSQ-4eCi_Rw5.js} +1 -1
- ksadk/server/static/assets/{dagre-3AP2YEHR-BkpgQqyW.js → dagre-3AP2YEHR-DpPk9jsh.js} +1 -1
- ksadk/server/static/assets/{dagre-BUaTFrYa.js → dagre-G789Mawt.js} +1 -1
- ksadk/server/static/assets/{diagram-S7CK7UJ4-25HdTbjE.js → diagram-S7CK7UJ4-7x2FScRJ.js} +1 -1
- ksadk/server/static/assets/{diagram-UQ7AKVKN-KO-WqOIg.js → diagram-UQ7AKVKN-DGvliWDD.js} +1 -1
- ksadk/server/static/assets/{diagram-VSXAHHWV-B360BkDQ.js → diagram-VSXAHHWV-C0i4uEyS.js} +1 -1
- ksadk/server/static/assets/{diagram-VX7I27RA-COr1Oqsg.js → diagram-VX7I27RA-C7SmgIl5.js} +1 -1
- ksadk/server/static/assets/{diagram-Z3DM3KII-CgaKrIwB.js → diagram-Z3DM3KII-Xca7TB4U.js} +1 -1
- ksadk/server/static/assets/{dist-By-MVndb.js → dist-B3rsrE8r.js} +1 -1
- ksadk/server/static/assets/{dist-Bsuusoi0.js → dist-BM6KIyhr.js} +1 -1
- ksadk/server/static/assets/{dist-DzdXSBJb.js → dist-BMZKBrmN.js} +1 -1
- ksadk/server/static/assets/{dist-DmWw0IXB.js → dist-BUGNcOx8.js} +1 -1
- ksadk/server/static/assets/{dist-DXOlCAay.js → dist-BbIN_x76.js} +1 -1
- ksadk/server/static/assets/{dist--HftQyp9.js → dist-CGB89Aru.js} +1 -1
- ksadk/server/static/assets/{dist-DKG0OYnk.js → dist-CGIWL8mC.js} +1 -1
- ksadk/server/static/assets/{dist-DgJ57sRe.js → dist-CHeuPGXZ.js} +1 -1
- ksadk/server/static/assets/{dist-_0Xgu_07.js → dist-CMJq3QL-.js} +1 -1
- ksadk/server/static/assets/{dist-CwnkOyDn.js → dist-CiUeIDKz.js} +1 -1
- ksadk/server/static/assets/{dist-BoRn8a_t.js → dist-CmaZEf5M.js} +1 -1
- ksadk/server/static/assets/{dist-BQ116UdZ.js → dist-Cq4qlsg3.js} +1 -1
- ksadk/server/static/assets/{dist-CBo9AHUv.js → dist-DDVDyH7h.js} +1 -1
- ksadk/server/static/assets/{dist-DSw5Ju6-.js → dist-DDi9q5bO.js} +1 -1
- ksadk/server/static/assets/{dist-CxIl4t92.js → dist-DJ8mj6p4.js} +1 -1
- ksadk/server/static/assets/{dist-Brbrdmff.js → dist-DRGym1nc.js} +1 -1
- ksadk/server/static/assets/{dist-BEbS8Bag.js → dist-DcrTYAeW.js} +1 -1
- ksadk/server/static/assets/{dist-C9BTMVwS.js → dist-DpuxDDLa.js} +1 -1
- ksadk/server/static/assets/{dist-B3Jp5r1e.js → dist-EFGQ7G_k.js} +1 -1
- ksadk/server/static/assets/{dist-HHvdjADB.js → dist-IyCF0NNA.js} +1 -1
- ksadk/server/static/assets/{dist-Bxcu8Ca0.js → dist-Ny95vkRV.js} +1 -1
- ksadk/server/static/assets/{dist-CR61WJFC.js → dist-s5cohO5C.js} +1 -1
- ksadk/server/static/assets/{ebnfDiagram-PWID7BFC-DogDP2db.js → ebnfDiagram-PWID7BFC-DNwVczAJ.js} +1 -1
- ksadk/server/static/assets/{erDiagram-SSCWMZ5O-CeBDnUjR.js → erDiagram-SSCWMZ5O-OxFlhx6v.js} +1 -1
- ksadk/server/static/assets/eventmodeling-NTZA5JFV-C-gXDupK.js +1 -0
- ksadk/server/static/assets/flowDiagram-A5DVABFB-CkpCYD4e.js +1 -0
- ksadk/server/static/assets/{ganttDiagram-EL5Y4UJY-oIQL3MCp.js → ganttDiagram-EL5Y4UJY-D4krNgUz.js} +1 -1
- ksadk/server/static/assets/gitGraph-4MIJSDKK-0RSkEgC5.js +1 -0
- ksadk/server/static/assets/{gitGraphDiagram-WWUBYQGX-B7qz0cmZ.js → gitGraphDiagram-WWUBYQGX-BUSVPN1s.js} +1 -1
- ksadk/server/static/assets/index-B9UP7He9.css +2 -0
- ksadk/server/static/assets/index-COn4kn-G.js +1135 -0
- ksadk/server/static/assets/info-A6RAGUB7-C6KX7WO4.js +1 -0
- ksadk/server/static/assets/{infoDiagram-RXCK75RN-yQRC41Ya.js → infoDiagram-RXCK75RN-b6w3u3-O.js} +1 -1
- ksadk/server/static/assets/{ishikawaDiagram-5VMMS53U-BCu4HiwL.js → ishikawaDiagram-5VMMS53U-CsC7gzRt.js} +1 -1
- ksadk/server/static/assets/{journeyDiagram-EYS64GPL-JaqmO73K.js → journeyDiagram-EYS64GPL-BATLNoy1.js} +1 -1
- ksadk/server/static/assets/{kanban-definition-3QL26DDD-DQo4X8NO.js → kanban-definition-3QL26DDD-C49zL_s0.js} +1 -1
- ksadk/server/static/assets/{katex-t_DWylQw.js → katex-CDVgGGy2.js} +1 -1
- ksadk/server/static/assets/{linear-DWdnI35B.js → linear-DkyDumSy.js} +1 -1
- ksadk/server/static/assets/{mermaid-parser.core-BHrT2Pfe.js → mermaid-parser.core-BDX-LqSy.js} +2 -2
- ksadk/server/static/assets/{mindmap-definition-FBJOCRG2-PBVAhZYV.js → mindmap-definition-FBJOCRG2-DRPnzL2n.js} +1 -1
- ksadk/server/static/assets/packet-AYTQ26CC-CMMupxPW.js +1 -0
- ksadk/server/static/assets/{pegDiagram-XKGWAZYB-CU_cLfow.js → pegDiagram-XKGWAZYB-Zm-xrNrr.js} +1 -1
- ksadk/server/static/assets/pie-WAS4IAKB-Bfo0pa9v.js +1 -0
- ksadk/server/static/assets/{pieDiagram-E7YTZNPT-B1h0-_pW.js → pieDiagram-E7YTZNPT-a8C1Jxo4.js} +1 -1
- ksadk/server/static/assets/{quadrantDiagram-AXDQQJYC-DEMoGo5a.js → quadrantDiagram-AXDQQJYC-ihH8znBv.js} +1 -1
- ksadk/server/static/assets/radar-RG4KPBEZ-PRBiHoJx.js +1 -0
- ksadk/server/static/assets/railroad-74A4TZTK-BCJ-XMRJ.js +1 -0
- ksadk/server/static/assets/railroad-abnf-HS5TGJTU-Bbttj0Jz.js +1 -0
- ksadk/server/static/assets/railroad-ebnf-LZEXJU2U-Bo18264J.js +1 -0
- ksadk/server/static/assets/railroad-peg-WCYAUIDC-xZDJTFLD.js +1 -0
- ksadk/server/static/assets/{railroadDiagram-O6MQD6OU-BTAob2wg.js → railroadDiagram-O6MQD6OU-DD9lFfXo.js} +1 -1
- ksadk/server/static/assets/{requirementDiagram-EFPCY7ZU-Dl0Q2SuO.js → requirementDiagram-EFPCY7ZU-CGn93Iyb.js} +1 -1
- ksadk/server/static/assets/{sankeyDiagram-P5KCCOFB-DeaTWkur.js → sankeyDiagram-P5KCCOFB-BuyjrHuW.js} +1 -1
- ksadk/server/static/assets/{sequenceDiagram-WJ2MYXX4-gFQYrsOd.js → sequenceDiagram-WJ2MYXX4-D-Iw-30A.js} +1 -1
- ksadk/server/static/assets/{sizeCapture-X5ZJPWSS-pGQzddMB.js → sizeCapture-X5ZJPWSS-B0EHLwrD.js} +1 -1
- ksadk/server/static/assets/{stateDiagram-HBIQ2CUA-DmpYOZt1.js → stateDiagram-HBIQ2CUA-k9Zyg69R.js} +1 -1
- ksadk/server/static/assets/stateDiagram-v2-4QOOHH4V-tUEVnq9-.js +1 -0
- ksadk/server/static/assets/{swimlanes-XN3QIQJK-BfuSAsrr.js → swimlanes-XN3QIQJK-D2BewKmp.js} +1 -1
- ksadk/server/static/assets/swimlanesDiagram-VK2B7HYN-CGBmsrCQ.js +8 -0
- ksadk/server/static/assets/{timeline-definition-24CTP7MA-CgJwrrxf.js → timeline-definition-24CTP7MA-czSzsYbz.js} +1 -1
- ksadk/server/static/assets/treeView-Q6P3EWNA-CrEvfC8M.js +1 -0
- ksadk/server/static/assets/treemap-WGGIJYW6-D1TmShtn.js +1 -0
- ksadk/server/static/assets/{vennDiagram-4TSXK5OY-CBSAgXDd.js → vennDiagram-4TSXK5OY-BJF_qZLF.js} +1 -1
- ksadk/server/static/assets/wardley-WFR3VGLG-0gZiSyL0.js +1 -0
- ksadk/server/static/assets/{wardleyDiagram-VM6X3IG4-013TZ2JZ.js → wardleyDiagram-VM6X3IG4-BfwUuJpr.js} +1 -1
- ksadk/server/static/assets/{xychartDiagram-S5SC5T6Z-u6Frp8xp.js → xychartDiagram-S5SC5T6Z-Ci6Nsp4p.js} +1 -1
- ksadk/server/static/index.html +2 -2
- ksadk/server/static/ui-source.json +6 -6
- ksadk/sessions/_postgres_history_backfill.py +80 -0
- ksadk/sessions/_postgres_schema.py +117 -0
- ksadk/sessions/_postgres_tables.py +6 -0
- ksadk/sessions/base.py +24 -0
- ksadk/sessions/history_tool_refs.py +244 -0
- ksadk/sessions/in_memory.py +42 -0
- ksadk/sessions/local_service.py +78 -0
- ksadk/sessions/model_history.py +20 -0
- ksadk/sessions/postgres_service.py +215 -19
- ksadk/sessions/resilient.py +24 -0
- ksadk/studio/static/assets/{ChannelsPage-Do_mRmVu.js → ChannelsPage-Ot9iV_QP.js} +1 -1
- ksadk/studio/static/assets/{CodeBlock-DMIf4h33-CsO7rJKv.js → CodeBlock-DMIf4h33-Cfs6se0v.js} +1 -1
- ksadk/studio/static/assets/{MathMessageMarkdown-BesSeCYl-CiB60plG.js → MathMessageMarkdown-BesSeCYl-BIBDiQAl.js} +1 -1
- ksadk/studio/static/assets/{MessageMarkdown-CwMTvgFj-BzEmQkHH.js → MessageMarkdown-CwMTvgFj-CWM4n-9K.js} +2 -2
- ksadk/studio/static/assets/{OfficialA2uiRenderer-DI49Kpxu-BBxfdj3P.js → OfficialA2uiRenderer-DI49Kpxu-BZSumE9D.js} +1 -1
- ksadk/studio/static/assets/{TeamsPage-qNVYpcox.js → TeamsPage-CVOpMIMf.js} +2 -2
- ksadk/studio/static/assets/index-CW1D-Kqg.css +2 -0
- ksadk/studio/static/assets/index-DMexeQ1-.js +1155 -0
- ksadk/studio/static/index.html +3 -3
- ksadk/studio/static/ui-source.json +6 -6
- ksadk/version.py +1 -1
- ksadk/server/static/assets/architecture-7GRP2DOG-CFWjFkDL.js +0 -1
- ksadk/server/static/assets/channel-D6Dp_l74.js +0 -1
- ksadk/server/static/assets/chunk-2Q5K7J3B-CwmjhFYK.js +0 -1
- ksadk/server/static/assets/classDiagram-DTDB5LWJ-DsbvkCAV.js +0 -1
- ksadk/server/static/assets/classDiagram-v2-JRS7N3AN-DsbvkCAV.js +0 -1
- ksadk/server/static/assets/cynefin-OW5HDTMX-CBZRVuc4.js +0 -1
- ksadk/server/static/assets/eventmodeling-NTZA5JFV-vXZWMkpn.js +0 -1
- ksadk/server/static/assets/flowDiagram-A5DVABFB-5LRgzKLv.js +0 -1
- ksadk/server/static/assets/gitGraph-4MIJSDKK-BUWSkncI.js +0 -1
- ksadk/server/static/assets/index-4g1ndaxW.js +0 -1132
- ksadk/server/static/assets/index-DEVfafsU.css +0 -2
- ksadk/server/static/assets/info-A6RAGUB7-CzJ_YrOs.js +0 -1
- ksadk/server/static/assets/packet-AYTQ26CC-CXoos6fx.js +0 -1
- ksadk/server/static/assets/pie-WAS4IAKB-CjF9NoIt.js +0 -1
- ksadk/server/static/assets/radar-RG4KPBEZ-BQGWs9nw.js +0 -1
- ksadk/server/static/assets/railroad-74A4TZTK-B6znvLUK.js +0 -1
- ksadk/server/static/assets/railroad-abnf-HS5TGJTU-Bzquz0As.js +0 -1
- ksadk/server/static/assets/railroad-ebnf-LZEXJU2U-1IikGkb5.js +0 -1
- ksadk/server/static/assets/railroad-peg-WCYAUIDC-BKKgHzdc.js +0 -1
- ksadk/server/static/assets/stateDiagram-v2-4QOOHH4V-Dolxgkw3.js +0 -1
- ksadk/server/static/assets/swimlanesDiagram-VK2B7HYN-BuI1erYj.js +0 -8
- ksadk/server/static/assets/treeView-Q6P3EWNA-DtMdDH8N.js +0 -1
- ksadk/server/static/assets/treemap-WGGIJYW6-VoU8QtLZ.js +0 -1
- ksadk/server/static/assets/wardley-WFR3VGLG-YWSRB0Zm.js +0 -1
- ksadk/studio/static/assets/index-Cp9Unfkn.css +0 -2
- ksadk/studio/static/assets/index-HepnaEeR.js +0 -1152
- {agentengine_sdk_python-0.8.8.dist-info → agentengine_sdk_python-0.8.9.dist-info}/WHEEL +0 -0
- {agentengine_sdk_python-0.8.8.dist-info → agentengine_sdk_python-0.8.9.dist-info}/entry_points.txt +0 -0
- {agentengine_sdk_python-0.8.8.dist-info → agentengine_sdk_python-0.8.9.dist-info}/licenses/LICENSE +0 -0
- {agentengine_sdk_python-0.8.8.dist-info → agentengine_sdk_python-0.8.9.dist-info}/top_level.txt +0 -0
|
@@ -8,6 +8,7 @@ from typing import Any
|
|
|
8
8
|
|
|
9
9
|
from langchain_core.messages import AIMessage, HumanMessage, SystemMessage, ToolMessage
|
|
10
10
|
from langgraph.stream import AsyncGraphRunStream
|
|
11
|
+
from langgraph.types import Command
|
|
11
12
|
|
|
12
13
|
from ksadk.events.adapters._langgraph_custom import CustomOutputMapper
|
|
13
14
|
from ksadk.events.adapters._langgraph_model_tasks import NativeModelTasks
|
|
@@ -93,6 +94,50 @@ _TOOL_DELTA_TYPES = frozenset(
|
|
|
93
94
|
)
|
|
94
95
|
|
|
95
96
|
|
|
97
|
+
def _tool_output(output: Any, call_id: str) -> Any:
|
|
98
|
+
"""Project a Command's tool reply without exposing graph state or routing data."""
|
|
99
|
+
if isinstance(output, Command):
|
|
100
|
+
items = [output]
|
|
101
|
+
elif isinstance(output, (list, tuple)) and any(
|
|
102
|
+
isinstance(item, (Command, ToolMessage)) for item in output
|
|
103
|
+
):
|
|
104
|
+
items = output
|
|
105
|
+
else:
|
|
106
|
+
return output
|
|
107
|
+
|
|
108
|
+
for item in items:
|
|
109
|
+
if isinstance(item, Command):
|
|
110
|
+
update = item.update
|
|
111
|
+
messages = update.get("messages") if isinstance(update, Mapping) else update
|
|
112
|
+
else:
|
|
113
|
+
messages = item
|
|
114
|
+
reply = _command_reply(messages, call_id)
|
|
115
|
+
if reply is not None:
|
|
116
|
+
return reply
|
|
117
|
+
# Routing and parent-graph Commands can finish without a user-facing reply.
|
|
118
|
+
return None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _command_reply(messages: Any, call_id: str) -> ToolMessage | None:
|
|
122
|
+
# LangGraph accepts message lists and (channel, value) updates. Traverse
|
|
123
|
+
# only the messages channel. Other state can be sensitive or non-JSON.
|
|
124
|
+
candidates = messages if isinstance(messages, (list, tuple)) else (messages,)
|
|
125
|
+
for candidate in candidates:
|
|
126
|
+
if isinstance(candidate, ToolMessage) and candidate.tool_call_id == call_id:
|
|
127
|
+
return candidate
|
|
128
|
+
if (
|
|
129
|
+
isinstance(candidate, Mapping)
|
|
130
|
+
and candidate.get("tool_call_id") == call_id
|
|
131
|
+
and candidate.get("role", candidate.get("type")) == "tool"
|
|
132
|
+
):
|
|
133
|
+
return ToolMessage.model_validate(candidate)
|
|
134
|
+
if isinstance(candidate, tuple) and len(candidate) == 2 and candidate[0] == "messages":
|
|
135
|
+
reply = _command_reply(candidate[1], call_id)
|
|
136
|
+
if reply is not None:
|
|
137
|
+
return reply
|
|
138
|
+
return None
|
|
139
|
+
|
|
140
|
+
|
|
96
141
|
class LangGraphEventAdapter:
|
|
97
142
|
"""Consume the lossless raw log exposed by ``AsyncGraphRunStream``."""
|
|
98
143
|
|
|
@@ -415,6 +460,9 @@ class LangGraphEventAdapter:
|
|
|
415
460
|
f"LangGraph tool call {call_id!r} started twice",
|
|
416
461
|
)
|
|
417
462
|
name = _required_string(payload.get("tool_name"), "tools tool_name")
|
|
463
|
+
source = source.model_copy(update={"metadata": {
|
|
464
|
+
**source.metadata, "tool_name": name,
|
|
465
|
+
}})
|
|
418
466
|
occurrence = self._tool_occurrences.get(state_key, 0)
|
|
419
467
|
self._tool_occurrences[state_key] = occurrence + 1
|
|
420
468
|
item_id = (
|
|
@@ -459,6 +507,10 @@ class LangGraphEventAdapter:
|
|
|
459
507
|
"tools tool_call_id",
|
|
460
508
|
f"LangGraph tool call {call_id!r} mutated before tool-started",
|
|
461
509
|
)
|
|
510
|
+
# Finish frames need not repeat the name; retain this execution's name.
|
|
511
|
+
source = source.model_copy(update={"metadata": {
|
|
512
|
+
**source.metadata, "tool_name": state.name,
|
|
513
|
+
}})
|
|
462
514
|
envelope = lambda event_type, part_id: env( # noqa: E731
|
|
463
515
|
frame.scope_id, frame.parent_scope_id, state.item_id, event_type, part_id, source
|
|
464
516
|
)
|
|
@@ -480,7 +532,7 @@ class LangGraphEventAdapter:
|
|
|
480
532
|
if native_type == "tool-finished":
|
|
481
533
|
if self._tool_outcomes is not None:
|
|
482
534
|
self._tool_outcomes.consume(frame.namespace, call_id, native_type)
|
|
483
|
-
output = payload.get("output")
|
|
535
|
+
output = _tool_output(payload.get("output"), call_id)
|
|
484
536
|
result_value = output.content if isinstance(output, ToolMessage) else output
|
|
485
537
|
is_error = isinstance(output, ToolMessage) and output.status == "error"
|
|
486
538
|
result = ToolResultContent(
|
ksadk/kernel/control.py
CHANGED
|
@@ -324,27 +324,13 @@ class AgentKernel:
|
|
|
324
324
|
async def public_run_id(self, query, public_ref: str, *, permit) -> str | None:
|
|
325
325
|
"""Resolve an authorized logical Run or its admitted wire attempt ID."""
|
|
326
326
|
await self._permit_verifier.verify(permit, query, "get_status", self._clock())
|
|
327
|
-
|
|
328
|
-
return None
|
|
329
|
-
run = await self._store.load_run(public_ref)
|
|
330
|
-
if (run is not None and run.session_id == query.session_id
|
|
331
|
-
and run.agent_instance_id == query.agent_instance_id
|
|
332
|
-
and run.metadata.get("tenant_id") == query.tenant_id):
|
|
333
|
-
return run.run_id
|
|
334
|
-
message = await self._store.load_by_idempotency(query.session_id, public_ref)
|
|
335
|
-
command = message.command if message is not None else None
|
|
336
|
-
if (command is None or command.command_type != "enqueue"
|
|
337
|
-
or command.tenant_id != query.tenant_id
|
|
338
|
-
or command.agent_instance_id != query.agent_instance_id):
|
|
339
|
-
return None
|
|
340
|
-
prior = await self._store.find_command_run(
|
|
341
|
-
query.agent_instance_id, query.session_id, str(command.command_id),
|
|
342
|
-
)
|
|
343
|
-
if prior is not None:
|
|
344
|
-
return prior.run_id
|
|
345
|
-
from ksadk.kernel.execution_grants import execution_grant_run_id
|
|
327
|
+
from ksadk.kernel.run_references import resolve_public_run_id
|
|
346
328
|
|
|
347
|
-
return
|
|
329
|
+
return await resolve_public_run_id(
|
|
330
|
+
self._store, tenant_id=query.tenant_id,
|
|
331
|
+
agent_instance_id=query.agent_instance_id, session_id=query.session_id,
|
|
332
|
+
public_ref=public_ref,
|
|
333
|
+
)
|
|
348
334
|
|
|
349
335
|
async def pending_interactions(
|
|
350
336
|
self, query: AgentStatusQuery, *, permit: AgentControlPermit
|
|
@@ -386,6 +372,14 @@ class AgentKernel:
|
|
|
386
372
|
)
|
|
387
373
|
active = await self._store.find_active_run(query.agent_instance_id, query.session_id)
|
|
388
374
|
lease = await self._store.current_lease(query.agent_instance_id, query.session_id)
|
|
375
|
+
inbox_depth = await self._store.inbox_depth(query.agent_instance_id, query.session_id)
|
|
376
|
+
claimed = getattr(self._store, "has_claimed_work", None)
|
|
377
|
+
has_claimed_work = (
|
|
378
|
+
active is None and bool(query.session_id) and callable(claimed)
|
|
379
|
+
and await claimed(query.agent_instance_id, query.session_id)
|
|
380
|
+
)
|
|
381
|
+
# Observe the watermark last. If a claim became an active or terminal
|
|
382
|
+
# Run during these reads, its newer fact still keeps consumers following.
|
|
389
383
|
watermark = None
|
|
390
384
|
read_watermark = getattr(self._events, "get_max_seq_id", None)
|
|
391
385
|
if query.session_id and callable(read_watermark):
|
|
@@ -396,8 +390,8 @@ class AgentKernel:
|
|
|
396
390
|
session_id=query.session_id or (active.session_id if active else None),
|
|
397
391
|
session_event_seq=watermark,
|
|
398
392
|
active_run_id=active.run_id if active else None,
|
|
399
|
-
active_run_state=active.state.value if active else None,
|
|
400
|
-
inbox_depth=
|
|
393
|
+
active_run_state=active.state.value if active else ("pending" if has_claimed_work else None),
|
|
394
|
+
inbox_depth=inbox_depth,
|
|
401
395
|
activation_id=lease.activation_id if lease else None,
|
|
402
396
|
lease_expires_at=lease.lease_expires_at if lease else None,
|
|
403
397
|
capability=self._capabilities(),
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
from __future__ import annotations
|
|
4
4
|
|
|
5
|
+
import json
|
|
5
6
|
from typing import Any
|
|
6
7
|
|
|
7
8
|
from ksadk.conversations.message_projection import project_session_messages
|
|
@@ -31,6 +32,55 @@ def _accepted_input(event: dict[str, Any], session_id: str) -> dict[str, Any] |
|
|
|
31
32
|
return None
|
|
32
33
|
|
|
33
34
|
|
|
35
|
+
async def _load_history_runs(runtime, session_id, storage_tenant, run_ids, runs):
|
|
36
|
+
missing_runs = sorted(run_ids - runs.keys())
|
|
37
|
+
batch_runs = getattr(runtime.kernel_store, "load_runs_for_history", None)
|
|
38
|
+
if callable(batch_runs) and missing_runs:
|
|
39
|
+
runs.update(await batch_runs(
|
|
40
|
+
missing_runs, tenant_id=storage_tenant,
|
|
41
|
+
agent_instance_id=runtime.config.agent_instance_id, session_id=session_id,
|
|
42
|
+
))
|
|
43
|
+
else:
|
|
44
|
+
for run_id in missing_runs:
|
|
45
|
+
runs[run_id] = await runtime.kernel_store.load_run(run_id)
|
|
46
|
+
for run_id in missing_runs:
|
|
47
|
+
runs.setdefault(run_id, None)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _verified_run_commands(runtime, session_id, effective_tenant, run_ids, runs):
|
|
51
|
+
batch_runs = getattr(runtime.kernel_store, "load_runs_for_history", None)
|
|
52
|
+
run_by_command: dict[str, str] = {}
|
|
53
|
+
for run_id in run_ids:
|
|
54
|
+
run = runs.get(run_id)
|
|
55
|
+
run_tenant = getattr(run, "tenant_id", None)
|
|
56
|
+
store_tenant = getattr(runtime.kernel_store, "tenant_id", None)
|
|
57
|
+
if run_tenant is not None and run_tenant != effective_tenant:
|
|
58
|
+
continue
|
|
59
|
+
if (not callable(batch_runs) and store_tenant is not None
|
|
60
|
+
and store_tenant != effective_tenant):
|
|
61
|
+
continue
|
|
62
|
+
if (run is not None and run.session_id == session_id
|
|
63
|
+
and run.agent_instance_id == runtime.config.agent_instance_id):
|
|
64
|
+
run_by_command[str(run.metadata.get("command_id") or "")] = run_id
|
|
65
|
+
|
|
66
|
+
return run_by_command
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
async def _history_command_ids(runtime, session_id, run_ids, cache):
|
|
70
|
+
"""Use the store's scoped command IDs without transferring run checkpoints."""
|
|
71
|
+
lookup = getattr(runtime.kernel_store, "history_input_command_ids", None)
|
|
72
|
+
if not callable(lookup):
|
|
73
|
+
return None
|
|
74
|
+
commands = cache.setdefault("command_ids", {})
|
|
75
|
+
missing = sorted(run_ids - commands.keys())
|
|
76
|
+
if missing:
|
|
77
|
+
found = await lookup(
|
|
78
|
+
missing, agent_instance_id=runtime.config.agent_instance_id, session_id=session_id,
|
|
79
|
+
)
|
|
80
|
+
commands.update((run_id, found.get(run_id)) for run_id in missing)
|
|
81
|
+
return {run_id: commands[run_id] for run_id in run_ids if commands[run_id]}
|
|
82
|
+
|
|
83
|
+
|
|
34
84
|
async def project_inbox_inputs(
|
|
35
85
|
events: list[dict[str, Any]], *, runtime: Any, session_id: str,
|
|
36
86
|
tenant_id: str | None = None,
|
|
@@ -49,7 +99,6 @@ async def project_inbox_inputs(
|
|
|
49
99
|
if message.get("Role") == "user" and message.get("InvocationId")
|
|
50
100
|
}
|
|
51
101
|
cache = request_cache if request_cache is not None else {}
|
|
52
|
-
runs = cache.setdefault("runs", {})
|
|
53
102
|
messages = cache.setdefault("messages", {})
|
|
54
103
|
effective_tenant = tenant_id or runtime.config.tenant_id
|
|
55
104
|
# Kernel table tenant_id is the configured storage partition, not the
|
|
@@ -57,18 +106,15 @@ async def project_inbox_inputs(
|
|
|
57
106
|
# partition; validate the command principal below before exposing input.
|
|
58
107
|
storage_tenant = getattr(runtime.kernel_store, "tenant_id", effective_tenant)
|
|
59
108
|
run_ids = {str(event.get("InvocationId") or "") for event in events} - {""}
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
)
|
|
109
|
+
command_ids = await _history_command_ids(runtime, session_id, run_ids, cache)
|
|
110
|
+
if command_ids is None:
|
|
111
|
+
runs = cache.setdefault("runs", {})
|
|
112
|
+
await _load_history_runs(runtime, session_id, storage_tenant, run_ids, runs)
|
|
113
|
+
run_by_command = _verified_run_commands(
|
|
114
|
+
runtime, session_id, effective_tenant, run_ids, runs,
|
|
115
|
+
)
|
|
67
116
|
else:
|
|
68
|
-
for run_id in
|
|
69
|
-
runs[run_id] = await runtime.kernel_store.load_run(run_id)
|
|
70
|
-
for run_id in missing_runs:
|
|
71
|
-
runs.setdefault(run_id, None)
|
|
117
|
+
run_by_command = {command: run_id for run_id, command in command_ids.items()}
|
|
72
118
|
accepted = [payload for event in events
|
|
73
119
|
if (payload := _accepted_input(event, session_id)) is not None]
|
|
74
120
|
message_ids = {str(payload.get("message_id") or "") for payload in accepted} - {""}
|
|
@@ -84,20 +130,6 @@ async def project_inbox_inputs(
|
|
|
84
130
|
messages[message_id] = await runtime.kernel_store.load_message(message_id)
|
|
85
131
|
for message_id in missing_messages:
|
|
86
132
|
messages.setdefault(message_id, None)
|
|
87
|
-
run_by_command: dict[str, str] = {}
|
|
88
|
-
for run_id in run_ids:
|
|
89
|
-
run = runs.get(run_id)
|
|
90
|
-
run_tenant = getattr(run, "tenant_id", None)
|
|
91
|
-
store_tenant = getattr(runtime.kernel_store, "tenant_id", None)
|
|
92
|
-
if run_tenant is not None and run_tenant != effective_tenant:
|
|
93
|
-
continue
|
|
94
|
-
if (not callable(batch_runs) and store_tenant is not None
|
|
95
|
-
and store_tenant != effective_tenant):
|
|
96
|
-
continue
|
|
97
|
-
if (run is not None and run.session_id == session_id
|
|
98
|
-
and run.agent_instance_id == runtime.config.agent_instance_id):
|
|
99
|
-
run_by_command[str(run.metadata.get("command_id") or "")] = run_id
|
|
100
|
-
|
|
101
133
|
projected = []
|
|
102
134
|
for event in events:
|
|
103
135
|
payload = _accepted_input(event, session_id)
|
|
@@ -129,6 +161,85 @@ async def project_inbox_inputs(
|
|
|
129
161
|
return projected
|
|
130
162
|
|
|
131
163
|
|
|
164
|
+
async def item_inbox_chunks(events, *, runtime, session_id, tenant_id, offset, limit):
|
|
165
|
+
if runtime is None:
|
|
166
|
+
return {}
|
|
167
|
+
accepted = {
|
|
168
|
+
event["SeqId"]: fact for event in events
|
|
169
|
+
if (fact := _accepted_input(event, session_id)) and fact.get("message_id")
|
|
170
|
+
and fact.get("command_id")
|
|
171
|
+
}
|
|
172
|
+
if not accepted:
|
|
173
|
+
return {}
|
|
174
|
+
reader = getattr(runtime.kernel_store, "history_input_chunks", None)
|
|
175
|
+
if callable(reader):
|
|
176
|
+
commands = {str(fact["message_id"]): str(fact["command_id"]) for fact in accepted.values()}
|
|
177
|
+
chunks = await reader(
|
|
178
|
+
commands,
|
|
179
|
+
tenant_id=tenant_id or runtime.config.tenant_id,
|
|
180
|
+
agent_instance_id=runtime.config.agent_instance_id,
|
|
181
|
+
session_id=session_id, offset=offset, limit=limit,
|
|
182
|
+
)
|
|
183
|
+
return {seq: chunks[str(fact["message_id"])] for seq, fact in accepted.items()
|
|
184
|
+
if str(fact["message_id"]) in chunks
|
|
185
|
+
and commands[str(fact["message_id"])] == str(fact["command_id"])}
|
|
186
|
+
# Embedded/third-party Kernel stores may only support record reads. Reuse
|
|
187
|
+
# their established identity checks and serialize just the visible text.
|
|
188
|
+
projected = await project_inbox_inputs(
|
|
189
|
+
[event for event in events if event["SeqId"] in accepted], runtime=runtime,
|
|
190
|
+
session_id=session_id, tenant_id=tenant_id,
|
|
191
|
+
)
|
|
192
|
+
chunks = {}
|
|
193
|
+
for event in projected:
|
|
194
|
+
if event.get("EventType") == "user_message":
|
|
195
|
+
value = json.dumps(_input_text(event["Content"]), ensure_ascii=False)
|
|
196
|
+
end = offset + limit
|
|
197
|
+
chunks[event["SeqId"]] = (value[offset:end], end if end < len(value) else None)
|
|
198
|
+
return chunks
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
async def item_input_annotations(
|
|
202
|
+
events: list[dict[str, Any]], *, runtime: Any, session_id: str, tenant_id: str | None,
|
|
203
|
+
) -> dict[int, dict[str, Any]]:
|
|
204
|
+
"""Bind accepted inputs and native user items by verified command, across item pages."""
|
|
205
|
+
if runtime is None or not events:
|
|
206
|
+
return {}
|
|
207
|
+
accepted = [event for event in events if _accepted_input(event, session_id)]
|
|
208
|
+
chunks = await item_inbox_chunks(
|
|
209
|
+
accepted, runtime=runtime, session_id=session_id, tenant_id=tenant_id, offset=0, limit=2048,
|
|
210
|
+
)
|
|
211
|
+
annotations = {}
|
|
212
|
+
for original in accepted:
|
|
213
|
+
seq = original["SeqId"]
|
|
214
|
+
if seq in chunks:
|
|
215
|
+
value, next_offset = chunks[seq]
|
|
216
|
+
command_id = _accepted_input(original, session_id)["command_id"]
|
|
217
|
+
input_data = ({"ContentRef": {"SeqId": seq}} if next_offset is not None
|
|
218
|
+
else {"Text": _input_text(json.loads(value))})
|
|
219
|
+
annotations[seq] = {"InboxInput": {"CommandId": str(command_id), **input_data}}
|
|
220
|
+
effective_tenant = tenant_id or runtime.config.tenant_id
|
|
221
|
+
storage_tenant = getattr(runtime.kernel_store, "tenant_id", effective_tenant)
|
|
222
|
+
run_ids = {str(event["InvocationId"]) for event in events if event.get("InvocationId")}
|
|
223
|
+
lookup = getattr(runtime.kernel_store, "history_input_command_ids", None)
|
|
224
|
+
if not run_ids:
|
|
225
|
+
return annotations
|
|
226
|
+
if callable(lookup):
|
|
227
|
+
by_run = await lookup(
|
|
228
|
+
sorted(run_ids), agent_instance_id=runtime.config.agent_instance_id,
|
|
229
|
+
session_id=session_id,
|
|
230
|
+
)
|
|
231
|
+
else:
|
|
232
|
+
runs = {}
|
|
233
|
+
await _load_history_runs(runtime, session_id, storage_tenant, run_ids, runs)
|
|
234
|
+
by_command = _verified_run_commands(runtime, session_id, effective_tenant, run_ids, runs)
|
|
235
|
+
by_run = {run_id: command for command, run_id in by_command.items() if command}
|
|
236
|
+
for event in events:
|
|
237
|
+
command = by_run.get(event.get("InvocationId"))
|
|
238
|
+
if command:
|
|
239
|
+
annotations.setdefault(event["SeqId"], {})["InputCommandId"] = command
|
|
240
|
+
return annotations
|
|
241
|
+
|
|
242
|
+
|
|
132
243
|
async def complete_history_input_boundary(
|
|
133
244
|
events, *, service, runtime, session_id, budget, after_seq_id=None, request_cache=None
|
|
134
245
|
):
|
|
@@ -144,48 +255,44 @@ async def complete_history_input_boundary(
|
|
|
144
255
|
if not run_id:
|
|
145
256
|
return events
|
|
146
257
|
store = runtime.kernel_store
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
if
|
|
150
|
-
|
|
151
|
-
elif callable(batch):
|
|
152
|
-
runs = await batch(
|
|
153
|
-
[run_id],
|
|
154
|
-
tenant_id=getattr(store, "tenant_id", runtime.config.tenant_id),
|
|
155
|
-
agent_instance_id=runtime.config.agent_instance_id,
|
|
156
|
-
session_id=session_id,
|
|
157
|
-
)
|
|
158
|
-
run = runs.get(run_id)
|
|
258
|
+
cache = request_cache if request_cache is not None else {}
|
|
259
|
+
commands = await _history_command_ids(runtime, session_id, {run_id}, cache)
|
|
260
|
+
if commands is not None:
|
|
261
|
+
command_id = commands.get(run_id)
|
|
159
262
|
else:
|
|
160
|
-
|
|
161
|
-
run_cache[run_id] = run
|
|
162
|
-
if (
|
|
163
|
-
run is None
|
|
164
|
-
or run.session_id != session_id
|
|
165
|
-
or run.agent_instance_id != runtime.config.agent_instance_id
|
|
166
|
-
):
|
|
167
|
-
return events
|
|
168
|
-
command_id = str(run.metadata.get("command_id") or "")
|
|
263
|
+
command_id = await _history_run_command(runtime, session_id, run_id, cache)
|
|
169
264
|
if not command_id:
|
|
170
265
|
return events
|
|
171
266
|
|
|
172
267
|
def is_acceptance(event):
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
payload = envelope.get("payload") if isinstance(envelope, dict) else None
|
|
176
|
-
return (
|
|
177
|
-
event.session_id == session_id
|
|
178
|
-
and isinstance(payload, dict)
|
|
179
|
-
and envelope.get("family") == "control"
|
|
180
|
-
and envelope.get("event_type") == "control.command_accepted"
|
|
181
|
-
and payload.get("command_type") == "enqueue"
|
|
182
|
-
and str(payload.get("command_id") or "") == command_id
|
|
268
|
+
accepted = _accepted_input(
|
|
269
|
+
{"Content": event.content, "SessionId": event.session_id}, session_id
|
|
183
270
|
)
|
|
271
|
+
return accepted is not None and str(accepted.get("command_id") or "") == command_id
|
|
184
272
|
|
|
185
273
|
if any(is_acceptance(e) for e in events):
|
|
186
274
|
return events
|
|
187
|
-
|
|
275
|
+
|
|
188
276
|
cursor = events[0].seq_id
|
|
277
|
+
locate = getattr(store, "history_input_start_seq", None)
|
|
278
|
+
if callable(locate):
|
|
279
|
+
start = await locate(
|
|
280
|
+
command_id, agent_instance_id=runtime.config.agent_instance_id,
|
|
281
|
+
session_id=session_id, after_seq_id=after_seq_id or 0, before_seq_id=cursor,
|
|
282
|
+
)
|
|
283
|
+
if start is not None:
|
|
284
|
+
# The fallback scans backwards in fixed batches to find this
|
|
285
|
+
# same acceptance. Once known, read its exact bounded prefix.
|
|
286
|
+
prefix = await service.get_events(
|
|
287
|
+
session_id, limit=budget.remaining_events + 1, before_seq_id=cursor,
|
|
288
|
+
after_seq_id=start - 1,
|
|
289
|
+
)
|
|
290
|
+
budget.account(prefix)
|
|
291
|
+
if prefix and is_acceptance(prefix[0]):
|
|
292
|
+
return [*prefix, *events]
|
|
293
|
+
|
|
294
|
+
# Older rows and embedded stores can lack a canonical Inbox position.
|
|
295
|
+
prefix = []
|
|
189
296
|
while cursor and cursor > (after_seq_id or 0) + 1:
|
|
190
297
|
page = await service.get_events(
|
|
191
298
|
session_id, limit=64, before_seq_id=cursor, after_seq_id=after_seq_id
|
|
@@ -199,3 +306,29 @@ async def complete_history_input_boundary(
|
|
|
199
306
|
break
|
|
200
307
|
cursor = page[0].seq_id
|
|
201
308
|
return [*prefix, *events]
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
async def _history_run_command(runtime, session_id, run_id, cache):
|
|
312
|
+
store = runtime.kernel_store
|
|
313
|
+
run_cache = cache.setdefault("runs", {})
|
|
314
|
+
batch = getattr(store, "load_runs_for_history", None)
|
|
315
|
+
if run_id in run_cache:
|
|
316
|
+
run = run_cache[run_id]
|
|
317
|
+
elif callable(batch):
|
|
318
|
+
runs = await batch(
|
|
319
|
+
[run_id],
|
|
320
|
+
tenant_id=getattr(store, "tenant_id", runtime.config.tenant_id),
|
|
321
|
+
agent_instance_id=runtime.config.agent_instance_id,
|
|
322
|
+
session_id=session_id,
|
|
323
|
+
)
|
|
324
|
+
run = runs.get(run_id)
|
|
325
|
+
else:
|
|
326
|
+
run = await store.load_run(run_id)
|
|
327
|
+
run_cache[run_id] = run
|
|
328
|
+
if (
|
|
329
|
+
run is None
|
|
330
|
+
or run.session_id != session_id
|
|
331
|
+
or run.agent_instance_id != runtime.config.agent_instance_id
|
|
332
|
+
):
|
|
333
|
+
return None
|
|
334
|
+
return str(run.metadata.get("command_id") or "")
|
ksadk/kernel/ingress.py
CHANGED
|
@@ -964,7 +964,14 @@ def _build_kernel_router() -> Any:
|
|
|
964
964
|
"Code": "session_not_found", "Message": "session not found",
|
|
965
965
|
}})
|
|
966
966
|
epoch, _ = history_identity(session_service, metadata)
|
|
967
|
-
response_headers = {
|
|
967
|
+
response_headers = {
|
|
968
|
+
"X-AgentEngine-History-Epoch": epoch,
|
|
969
|
+
"X-Ksadk-Run-Causation": "1",
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
chained_cursor = bool(getattr(getattr(kernel, "_events", None), "subscription_cursor_chain", False))
|
|
973
|
+
if chained_cursor:
|
|
974
|
+
response_headers["X-Ksadk-Session-Cursor-Chain"] = "1"
|
|
968
975
|
|
|
969
976
|
async def _client_disconnected() -> bool:
|
|
970
977
|
# 客户端断开后及时收口 SSE,而不是轮询到订阅 timeout。
|
|
@@ -979,6 +986,7 @@ def _build_kernel_router() -> Any:
|
|
|
979
986
|
response_headers.update({"Cache-Control": "no-cache", "X-Accel-Buffering": "no"})
|
|
980
987
|
|
|
981
988
|
async def generator():
|
|
989
|
+
previous_seq = after_seq
|
|
982
990
|
source = subscribe_projected(
|
|
983
991
|
session_id, trusted=trusted, after_seq=after_seq,
|
|
984
992
|
should_stop=_client_disconnected, timeout=subscribe_timeout,
|
|
@@ -1016,7 +1024,13 @@ def _build_kernel_router() -> Any:
|
|
|
1016
1024
|
frame.setdefault("event_type", getattr(envelope, "event_type", None))
|
|
1017
1025
|
if getattr(envelope, "run_id", None):
|
|
1018
1026
|
frame.setdefault("run_id", envelope.run_id)
|
|
1019
|
-
|
|
1027
|
+
if frame.get("event_type") == "control.run_transition":
|
|
1028
|
+
causation_id = getattr(envelope, "causation_id", None)
|
|
1029
|
+
if causation_id:
|
|
1030
|
+
frame["causation_id"] = causation_id
|
|
1031
|
+
link = f": ksadk-previous-seq={previous_seq}\n" if chained_cursor else ""
|
|
1032
|
+
previous_seq = seq
|
|
1033
|
+
yield f"{link}id: {seq}\ndata: {json.dumps(frame, ensure_ascii=False)}\n\n"
|
|
1020
1034
|
finally:
|
|
1021
1035
|
await frames.aclose()
|
|
1022
1036
|
|
|
@@ -35,6 +35,7 @@ class PostgresKernelEventLog:
|
|
|
35
35
|
workspace_id: str = "default",
|
|
36
36
|
) -> None:
|
|
37
37
|
self._pool = pool
|
|
38
|
+
self._history_insert_fields = None
|
|
38
39
|
self._namespace = namespace.strip() or "default"
|
|
39
40
|
self._tenant_id = tenant_id.strip() or "default"
|
|
40
41
|
self._workspace_id = workspace_id.strip() or "default"
|
|
@@ -78,15 +79,22 @@ class PostgresKernelEventLog:
|
|
|
78
79
|
)
|
|
79
80
|
seq = int(next_seq or 1)
|
|
80
81
|
packed.bind_seq_id(seq) # 把物理 seq 绑定回 runtime/session envelope 内容
|
|
82
|
+
# Standalone ingress may connect to a previous Session schema during rollout.
|
|
83
|
+
# Decide once per writer; legacy INSERTs keep working until its next restart.
|
|
84
|
+
if self._history_insert_fields is None:
|
|
85
|
+
from ksadk.sessions._postgres_schema import history_item_insert_fields
|
|
86
|
+
|
|
87
|
+
self._history_insert_fields = await history_item_insert_fields(connection)
|
|
88
|
+
history_column, history_value = self._history_insert_fields
|
|
81
89
|
await connection.execute(
|
|
82
90
|
f"""
|
|
83
91
|
INSERT INTO {KSADK_PG_EVENTS_TABLE} (
|
|
84
92
|
namespace, tenant_id, workspace_id, id, session_id, author,
|
|
85
93
|
event_type, content_json, timestamp, state_delta_json,
|
|
86
|
-
seq_id, invocation_id, metadata_json
|
|
94
|
+
seq_id, invocation_id, metadata_json{history_column}
|
|
87
95
|
) VALUES (
|
|
88
96
|
$1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9,
|
|
89
|
-
'{{}}'::jsonb, $10, $11, $12::jsonb
|
|
97
|
+
'{{}}'::jsonb, $10, $11, $12::jsonb{history_value}
|
|
90
98
|
)
|
|
91
99
|
ON CONFLICT (namespace, id) DO NOTHING
|
|
92
100
|
""",
|
ksadk/kernel/postgres_store.py
CHANGED
|
@@ -108,6 +108,7 @@ class PostgresKernelEventLog:
|
|
|
108
108
|
workspace_id: str = "default",
|
|
109
109
|
) -> None:
|
|
110
110
|
self._pool = pool
|
|
111
|
+
self._history_insert_fields = None
|
|
111
112
|
self._namespace = namespace.strip() or "default"
|
|
112
113
|
self._tenant_id = tenant_id.strip() or "default"
|
|
113
114
|
self._workspace_id = workspace_id.strip() or "default"
|
|
@@ -149,15 +150,22 @@ class PostgresKernelEventLog:
|
|
|
149
150
|
)
|
|
150
151
|
seq = int(next_seq or 1)
|
|
151
152
|
packed.bind_seq_id(seq) # 把物理 seq 绑定回 runtime/session envelope 内容
|
|
153
|
+
# Standalone ingress may connect to a previous Session schema during rollout.
|
|
154
|
+
# Decide once per writer; legacy INSERTs keep working until its next restart.
|
|
155
|
+
if self._history_insert_fields is None:
|
|
156
|
+
from ksadk.sessions._postgres_schema import history_item_insert_fields
|
|
157
|
+
|
|
158
|
+
self._history_insert_fields = await history_item_insert_fields(connection)
|
|
159
|
+
history_column, history_value = self._history_insert_fields
|
|
152
160
|
inserted = await connection.fetchrow(
|
|
153
161
|
f"""
|
|
154
162
|
INSERT INTO {KSADK_PG_EVENTS_TABLE} (
|
|
155
163
|
namespace, tenant_id, workspace_id, id, session_id, author,
|
|
156
164
|
event_type, content_json, timestamp, state_delta_json,
|
|
157
|
-
seq_id, invocation_id, metadata_json
|
|
165
|
+
seq_id, invocation_id, metadata_json{history_column}
|
|
158
166
|
) VALUES (
|
|
159
167
|
$1, $2, $3, $4, $5, $6, $7, $8::jsonb, $9,
|
|
160
|
-
'{{}}'::jsonb, $10, $11, $12::jsonb
|
|
168
|
+
'{{}}'::jsonb, $10, $11, $12::jsonb{history_value}
|
|
161
169
|
)
|
|
162
170
|
ON CONFLICT (namespace, id) DO NOTHING
|
|
163
171
|
RETURNING seq_id, timestamp
|
|
@@ -337,6 +345,7 @@ class PostgresKernelEventLog:
|
|
|
337
345
|
COALESCE(octet_length(metadata_json::text),0) + 1024 AS bytes
|
|
338
346
|
FROM {KSADK_PG_EVENTS_TABLE}
|
|
339
347
|
WHERE namespace=$1 AND session_id=$2 AND seq_id>$3
|
|
348
|
+
AND metadata_json @> '{{"ksadk_session_event_envelope": true}}'::jsonb
|
|
340
349
|
ORDER BY seq_id LIMIT $4
|
|
341
350
|
), measured AS (
|
|
342
351
|
SELECT *,ROW_NUMBER() OVER (ORDER BY seq_id) AS position,
|
|
@@ -763,6 +772,28 @@ class PostgresAgentKernelStore(PostgresInteractionStoreMixin, PostgresExecutionG
|
|
|
763
772
|
)
|
|
764
773
|
return self._row_to_message(row)
|
|
765
774
|
|
|
775
|
+
async def history_input_chunks(
|
|
776
|
+
self, accepted: dict[str, str], *, tenant_id: str, agent_instance_id: str,
|
|
777
|
+
session_id: str, offset: int, limit: int,
|
|
778
|
+
) -> dict[str, tuple[str, int | None]]:
|
|
779
|
+
"""Read only the caller-visible content from verified enqueue commands."""
|
|
780
|
+
async with self._connection() as connection:
|
|
781
|
+
rows = await connection.fetch("""
|
|
782
|
+
SELECT message_id::text AS id,
|
|
783
|
+
substring((payload->'payload'->'content')::text FROM $7::integer FOR $8::integer) AS part
|
|
784
|
+
FROM kernel_inbox
|
|
785
|
+
JOIN unnest($1::uuid[], $2::text[]) AS accepted(id, cmd)
|
|
786
|
+
ON message_id=accepted.id AND payload->>'command_id'=accepted.cmd
|
|
787
|
+
WHERE tenant_id=$3 AND agent_instance_id=$4 AND session_id=$5
|
|
788
|
+
AND payload->>'command_type'='enqueue' AND payload->>'tenant_id'=$6
|
|
789
|
+
AND payload->>'agent_instance_id'=$4 AND payload->>'session_id'=$5
|
|
790
|
+
""", list(accepted), list(accepted.values()), self.tenant_id, agent_instance_id,
|
|
791
|
+
session_id, tenant_id, offset + 1, limit + 1)
|
|
792
|
+
return {
|
|
793
|
+
row["id"]: (row["part"][:limit], offset + limit if len(row["part"]) > limit else None)
|
|
794
|
+
for row in rows if row["part"] is not None
|
|
795
|
+
}
|
|
796
|
+
|
|
766
797
|
async def load_messages_for_history(
|
|
767
798
|
self, message_ids: list[str], *, tenant_id: str, agent_instance_id: str,
|
|
768
799
|
session_id: str,
|
|
@@ -1141,6 +1172,16 @@ class PostgresAgentKernelStore(PostgresInteractionStoreMixin, PostgresExecutionG
|
|
|
1141
1172
|
)
|
|
1142
1173
|
)
|
|
1143
1174
|
|
|
1175
|
+
async def has_claimed_work(self, agent_instance_id: str, session_id: str) -> bool:
|
|
1176
|
+
"""Observe a Worker claim before its Run reaches the active query."""
|
|
1177
|
+
async with self._connection() as connection:
|
|
1178
|
+
return bool(await connection.fetchval(
|
|
1179
|
+
"SELECT EXISTS(SELECT 1 FROM kernel_inbox WHERE agent_instance_id=$1"
|
|
1180
|
+
" AND tenant_id=$2 AND (session_namespace=$3 OR session_namespace IS NULL)"
|
|
1181
|
+
" AND session_id=$4 AND status='claimed')",
|
|
1182
|
+
agent_instance_id, self.tenant_id, self._events._namespace, session_id,
|
|
1183
|
+
))
|
|
1184
|
+
|
|
1144
1185
|
async def find_active_run(
|
|
1145
1186
|
self, agent_instance_id: str, session_id: str | None = None
|
|
1146
1187
|
) -> RunRecord | None:
|
|
@@ -1509,6 +1550,42 @@ class PostgresAgentKernelStore(PostgresInteractionStoreMixin, PostgresExecutionG
|
|
|
1509
1550
|
metadata=json.loads(row["metadata"]),
|
|
1510
1551
|
)
|
|
1511
1552
|
|
|
1553
|
+
async def history_input_command_ids(
|
|
1554
|
+
self, run_ids: list[str], *, agent_instance_id: str, session_id: str,
|
|
1555
|
+
) -> dict[str, str]:
|
|
1556
|
+
"""Return only the stable command identity, without loading run metadata blobs."""
|
|
1557
|
+
async with self._connection() as connection:
|
|
1558
|
+
rows = await connection.fetch("""
|
|
1559
|
+
SELECT run_id, metadata->>'command_id' AS cmd FROM kernel_runs
|
|
1560
|
+
WHERE run_id=ANY($1::text[]) AND tenant_id=$2
|
|
1561
|
+
AND agent_instance_id=$3 AND session_id=$4
|
|
1562
|
+
AND length(metadata->>'command_id') BETWEEN 1 AND 128
|
|
1563
|
+
""", run_ids, self.tenant_id, agent_instance_id, session_id)
|
|
1564
|
+
return {row["run_id"]: row["cmd"] for row in rows}
|
|
1565
|
+
|
|
1566
|
+
async def history_input_start_seq(
|
|
1567
|
+
self, command_id: str, *, agent_instance_id: str, session_id: str,
|
|
1568
|
+
after_seq_id: int, before_seq_id: int,
|
|
1569
|
+
) -> int | None:
|
|
1570
|
+
"""Locate the durable acceptance in its Session sequence space."""
|
|
1571
|
+
async with self._connection() as connection:
|
|
1572
|
+
return await connection.fetchval(f"""
|
|
1573
|
+
SELECT e.seq_id
|
|
1574
|
+
FROM kernel_inbox AS i
|
|
1575
|
+
JOIN {KSADK_PG_EVENTS_TABLE} AS e
|
|
1576
|
+
ON e.namespace=$1 AND e.session_id=i.session_id AND e.seq_id=i.accepted_seq
|
|
1577
|
+
WHERE i.tenant_id=$2 AND i.agent_instance_id=$3 AND i.session_id=$4
|
|
1578
|
+
AND i.session_namespace=$1 AND i.payload->>'command_id'=$5
|
|
1579
|
+
AND i.accepted_seq>$6 AND i.accepted_seq<$7
|
|
1580
|
+
AND e.event_type='control.command_accepted'
|
|
1581
|
+
AND e.content_json#>>'{{session_event,family}}'='control'
|
|
1582
|
+
AND e.content_json#>>'{{session_event,payload,command_id}}'=$5
|
|
1583
|
+
AND e.content_json#>>'{{session_event,payload,message_id}}'=i.message_id::text
|
|
1584
|
+
AND e.content_json#>>'{{session_event,payload,command_type}}'='enqueue'
|
|
1585
|
+
ORDER BY e.seq_id DESC LIMIT 1
|
|
1586
|
+
""", self._events._namespace, self.tenant_id, agent_instance_id, session_id,
|
|
1587
|
+
command_id, after_seq_id, before_seq_id)
|
|
1588
|
+
|
|
1512
1589
|
async def load_runs_for_history(
|
|
1513
1590
|
self, run_ids: list[str], *, tenant_id: str, agent_instance_id: str,
|
|
1514
1591
|
session_id: str,
|
|
@@ -1671,6 +1748,8 @@ class PostgresFencedSessionEventStore:
|
|
|
1671
1748
|
走 event log 自开事务。
|
|
1672
1749
|
"""
|
|
1673
1750
|
|
|
1751
|
+
subscription_cursor_chain = True
|
|
1752
|
+
|
|
1674
1753
|
def __init__(self, store: "PostgresAgentKernelStore") -> None:
|
|
1675
1754
|
self._store = store
|
|
1676
1755
|
self._log = store._events
|