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
|
@@ -14,6 +14,7 @@ from langgraph.types import Command
|
|
|
14
14
|
|
|
15
15
|
from ksadk.conversations.reasoning_markup import ReasoningMarkupParser, strip_reasoning_markup
|
|
16
16
|
from ksadk.runners._langgraph_canonical_stream import _LangGraphCanonicalStreamMixin
|
|
17
|
+
from ksadk.runners._langgraph_model_budget import model_budget_scope
|
|
17
18
|
from ksadk.runners._langgraph_fresh_turn import fresh_memory_input, fresh_user_checkpoint
|
|
18
19
|
from ksadk.runners.usage_accumulator import accumulate_usage
|
|
19
20
|
from ksadk.runtime.skill_eval_result import skill_eval_response_fields
|
|
@@ -25,6 +26,7 @@ logger = logging.getLogger(__name__)
|
|
|
25
26
|
|
|
26
27
|
class _LangGraphStreamMixin(_LangGraphCanonicalStreamMixin):
|
|
27
28
|
@fresh_user_checkpoint
|
|
29
|
+
@model_budget_scope
|
|
28
30
|
async def stream(self, input_data: Dict[str, Any]) -> AsyncIterator[Dict[str, Any]]:
|
|
29
31
|
"""流式调用 LangGraph 图"""
|
|
30
32
|
await self.prepare_runtime_capabilities()
|
|
@@ -76,15 +78,14 @@ class _LangGraphStreamMixin(_LangGraphCanonicalStreamMixin):
|
|
|
76
78
|
# Keep the interrupt value intact for ``Command(resume=...)``;
|
|
77
79
|
# prepare-state hooks only shape fresh user turns.
|
|
78
80
|
state = self._unwrap_resume_value(resume_value)
|
|
79
|
-
|
|
80
|
-
state = self.
|
|
81
|
+
else:
|
|
82
|
+
state = await self._prepare_new_turn_state(
|
|
81
83
|
payload,
|
|
82
84
|
session_id,
|
|
83
85
|
history,
|
|
86
|
+
config=config,
|
|
84
87
|
is_resume=is_gateway_approval_resume,
|
|
85
88
|
)
|
|
86
|
-
else:
|
|
87
|
-
state = self._to_state(payload, history)
|
|
88
89
|
|
|
89
90
|
if not is_resume and not is_checkpoint_resume:
|
|
90
91
|
state = await fresh_memory_input(self._agent, config, state)
|
|
@@ -446,8 +447,8 @@ class _LangGraphStreamMixin(_LangGraphCanonicalStreamMixin):
|
|
|
446
447
|
if state is None:
|
|
447
448
|
agent = getattr(self, "_agent", None)
|
|
448
449
|
has_checkpointer = (
|
|
449
|
-
getattr(agent, "checkpointer", None)
|
|
450
|
-
or getattr(agent, "_checkpointer", None)
|
|
450
|
+
bool(getattr(agent, "checkpointer", None))
|
|
451
|
+
or bool(getattr(agent, "_checkpointer", None))
|
|
451
452
|
)
|
|
452
453
|
if has_checkpointer:
|
|
453
454
|
raise RuntimeError(
|
ksadk/runners/adk_runner.py
CHANGED
|
@@ -27,7 +27,7 @@ from ksadk.conversations.attachments import classify_attachment_kind, read_attac
|
|
|
27
27
|
from ksadk.conversations.model_context import supports_native_image_input
|
|
28
28
|
from ksadk.runners._session_identity import ADKSessionIdentityMixin
|
|
29
29
|
from ksadk.runners.base_runner import BaseRunner
|
|
30
|
-
from ksadk.runners.usage_accumulator import
|
|
30
|
+
from ksadk.runners.usage_accumulator import ADKUsageAccumulator
|
|
31
31
|
from ksadk.runners.utils import load_agent_module
|
|
32
32
|
from ksadk.sessions.continuity import ADKSessionAdapter
|
|
33
33
|
|
|
@@ -1414,10 +1414,11 @@ class ADKRunner(ADKSessionIdentityMixin, BaseRunner):
|
|
|
1414
1414
|
except (TypeError, ValueError):
|
|
1415
1415
|
pass
|
|
1416
1416
|
|
|
1417
|
-
if
|
|
1417
|
+
if any(usage_metadata.get(key) is not None for key in ("input_tokens", "output_tokens", "total_tokens")):
|
|
1418
1418
|
input_tokens = int(usage_metadata.get("input_tokens") or 0)
|
|
1419
1419
|
output_tokens = int(usage_metadata.get("output_tokens") or 0)
|
|
1420
|
-
|
|
1420
|
+
total = usage_metadata.get("total_tokens")
|
|
1421
|
+
total_tokens = int(total) if total is not None else input_tokens + output_tokens
|
|
1421
1422
|
direct_input_details = usage_metadata.get("input_token_details")
|
|
1422
1423
|
if isinstance(direct_input_details, Mapping):
|
|
1423
1424
|
input_token_details.update(dict(direct_input_details))
|
|
@@ -1435,16 +1436,11 @@ class ADKRunner(ADKSessionIdentityMixin, BaseRunner):
|
|
|
1435
1436
|
|
|
1436
1437
|
input_tokens = int(usage_metadata.get("prompt_token_count") or 0)
|
|
1437
1438
|
output_tokens = int(usage_metadata.get("candidates_token_count") or 0)
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
)
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
or output_tokens
|
|
1444
|
-
or total_tokens
|
|
1445
|
-
or input_token_details
|
|
1446
|
-
or output_token_details
|
|
1447
|
-
):
|
|
1439
|
+
total = usage_metadata.get("total_token_count")
|
|
1440
|
+
total_tokens = int(total) if total is not None else input_tokens + output_tokens
|
|
1441
|
+
if not any(usage_metadata.get(key) is not None for key in (
|
|
1442
|
+
"prompt_token_count", "candidates_token_count", "total_token_count",
|
|
1443
|
+
)):
|
|
1448
1444
|
return {}
|
|
1449
1445
|
return {
|
|
1450
1446
|
"input_tokens": input_tokens,
|
|
@@ -2129,17 +2125,13 @@ class ADKRunner(ADKSessionIdentityMixin, BaseRunner):
|
|
|
2129
2125
|
# P1.4: Track last_event to avoid UnboundLocalError when ADK returns
|
|
2130
2126
|
# zero events (e.g. resuming a completed invocation).
|
|
2131
2127
|
last_event = None
|
|
2132
|
-
|
|
2133
|
-
last_usage: dict[str, Any] = {}
|
|
2128
|
+
usage_accumulator = ADKUsageAccumulator()
|
|
2134
2129
|
tunnel_outcome = None
|
|
2135
2130
|
try:
|
|
2136
2131
|
async for event in wrapped_async:
|
|
2137
2132
|
events_list.append(event)
|
|
2138
2133
|
last_event = event
|
|
2139
|
-
|
|
2140
|
-
if event_usage:
|
|
2141
|
-
usage = accumulate_usage(usage, event_usage)
|
|
2142
|
-
last_usage = event_usage # 保留最后一个非空(窗口占用=最后一次 input)
|
|
2134
|
+
usage_accumulator.observe(event, self._extract_event_usage(event))
|
|
2143
2135
|
if hasattr(event, "content") and event.content:
|
|
2144
2136
|
if hasattr(event.content, "parts"):
|
|
2145
2137
|
for part in event.content.parts:
|
|
@@ -2183,10 +2175,10 @@ class ADKRunner(ADKSessionIdentityMixin, BaseRunner):
|
|
|
2183
2175
|
}
|
|
2184
2176
|
if tunnel_outcome is not None:
|
|
2185
2177
|
result["metadata"] = tunnel_outcome.metadata
|
|
2186
|
-
if usage:
|
|
2178
|
+
if usage := usage_accumulator.total():
|
|
2187
2179
|
result["usage"] = usage
|
|
2188
2180
|
# last_usage = 最后一次 LLM 调用快照(input_tokens = 当前上下文窗口占用)
|
|
2189
|
-
result.setdefault("metadata", {})["last_usage"] = last_usage
|
|
2181
|
+
result.setdefault("metadata", {})["last_usage"] = usage_accumulator.last_usage
|
|
2190
2182
|
return result
|
|
2191
2183
|
|
|
2192
2184
|
async def stream_canonical_events(
|
|
@@ -20,6 +20,7 @@ from ksadk.runners._langgraph_checkpoint_binding import (
|
|
|
20
20
|
bind_native_checkpointer,
|
|
21
21
|
)
|
|
22
22
|
from ksadk.runners._langgraph_factory import LangGraphFactoryMixin
|
|
23
|
+
from ksadk.runners._langgraph_model_budget import model_budget_scope
|
|
23
24
|
from ksadk.runners._langgraph_fresh_turn import fresh_memory_input, fresh_user_checkpoint
|
|
24
25
|
from ksadk.runners._langgraph_output import extract_output
|
|
25
26
|
from ksadk.runners._langgraph_runner_streams import _LangGraphStreamMixin
|
|
@@ -638,12 +639,12 @@ class LangGraphRunner(
|
|
|
638
639
|
self._managed_checkpoint_state = "terminal_failure"
|
|
639
640
|
return
|
|
640
641
|
|
|
641
|
-
#
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
# 提供 hook,否则 fail-closed,避免生产 auto checkpoint 下静默双重注入。
|
|
642
|
+
# 标准消息图由 Runner 统一处理历史;非标准业务状态继续使用原 hook。
|
|
643
|
+
from ksadk.runners._langgraph_context import framework_summary, standard_messages
|
|
644
|
+
|
|
645
645
|
prepare_state_hook = getattr(self._module, "ksadk_prepare_state", None)
|
|
646
|
-
if not callable(prepare_state_hook) and self._sdk_mcp_agent() is None
|
|
646
|
+
if (not callable(prepare_state_hook) and self._sdk_mcp_agent() is None
|
|
647
|
+
and not standard_messages(self._agent) and not framework_summary(self._agent)):
|
|
647
648
|
self._managed_checkpoint_error = (
|
|
648
649
|
"PREPARE_STATE_HOOK_REQUIRED",
|
|
649
650
|
"Managed PostgreSQL checkpoint requires ksadk_prepare_state hook to "
|
|
@@ -1015,6 +1016,128 @@ class LangGraphRunner(
|
|
|
1015
1016
|
or self._sdk_mcp_agent() is not None
|
|
1016
1017
|
)
|
|
1017
1018
|
|
|
1019
|
+
def uses_ksadk_model_context(self) -> bool:
|
|
1020
|
+
from ksadk.runners._langgraph_context import framework_summary, standard_messages
|
|
1021
|
+
|
|
1022
|
+
return standard_messages(self._agent) and not framework_summary(self._agent)
|
|
1023
|
+
|
|
1024
|
+
async def _prepare_new_turn_state(
|
|
1025
|
+
self,
|
|
1026
|
+
payload: Dict[str, Any],
|
|
1027
|
+
session_id: str,
|
|
1028
|
+
history: list,
|
|
1029
|
+
*,
|
|
1030
|
+
config: dict | None = None,
|
|
1031
|
+
is_resume: bool = False,
|
|
1032
|
+
) -> Dict[str, Any]:
|
|
1033
|
+
from copy import deepcopy
|
|
1034
|
+
|
|
1035
|
+
from langchain_core.messages import SystemMessage, convert_to_messages
|
|
1036
|
+
from langgraph.types import Overwrite
|
|
1037
|
+
|
|
1038
|
+
from ksadk.runners._langgraph_context import (
|
|
1039
|
+
TURN_KEY,
|
|
1040
|
+
checkpoint_messages,
|
|
1041
|
+
current_hook_messages,
|
|
1042
|
+
effective_history,
|
|
1043
|
+
framework_summary,
|
|
1044
|
+
merge_hook_current,
|
|
1045
|
+
standard_messages,
|
|
1046
|
+
)
|
|
1047
|
+
|
|
1048
|
+
payload = dict(payload)
|
|
1049
|
+
projection = payload.pop("langgraph_model_context", None)
|
|
1050
|
+
standard = standard_messages(self._agent)
|
|
1051
|
+
native_summary = framework_summary(self._agent)
|
|
1052
|
+
append_messages = bool(
|
|
1053
|
+
getattr(getattr(self._agent, "channels", {}).get("messages"), "operator", None)
|
|
1054
|
+
)
|
|
1055
|
+
projected = (
|
|
1056
|
+
self.uses_ksadk_model_context() and isinstance(projection, dict) and not is_resume
|
|
1057
|
+
)
|
|
1058
|
+
saver = getattr(self._agent, "checkpointer", None)
|
|
1059
|
+
saved = []
|
|
1060
|
+
if (standard or native_summary) and saver and not is_resume:
|
|
1061
|
+
saved = await checkpoint_messages(
|
|
1062
|
+
self._agent, config or await self._get_session_config(session_id)
|
|
1063
|
+
)
|
|
1064
|
+
sdk_messages = (
|
|
1065
|
+
deepcopy(self._to_state(payload, []).get("messages", [])) if projected else None
|
|
1066
|
+
)
|
|
1067
|
+
prepare_history = history
|
|
1068
|
+
owns_history = projected or (
|
|
1069
|
+
((standard and append_messages) or native_summary) and saved and not is_resume
|
|
1070
|
+
)
|
|
1071
|
+
has_hook = self._has_prepare_state_hook()
|
|
1072
|
+
if owns_history and not has_hook:
|
|
1073
|
+
history = []
|
|
1074
|
+
payload["history"] = []
|
|
1075
|
+
state = (
|
|
1076
|
+
self._prepare_state_with_hook(payload, session_id, history, is_resume=is_resume)
|
|
1077
|
+
if has_hook
|
|
1078
|
+
else self._to_state(payload, history)
|
|
1079
|
+
)
|
|
1080
|
+
if projected:
|
|
1081
|
+
# History remains SDK-owned. Preserve legacy hook policies and
|
|
1082
|
+
# custom current input without accepting its history.
|
|
1083
|
+
state["messages"] = merge_hook_current(
|
|
1084
|
+
sdk_messages,
|
|
1085
|
+
state.get("messages"),
|
|
1086
|
+
payload.get("input"),
|
|
1087
|
+
[prepare_history, projection.get("history", [])],
|
|
1088
|
+
)
|
|
1089
|
+
elif owns_history and has_hook and isinstance(state.get("messages"), list):
|
|
1090
|
+
state["messages"] = current_hook_messages(
|
|
1091
|
+
state["messages"],
|
|
1092
|
+
[prepare_history, projection.get("history", []) if projected else []],
|
|
1093
|
+
payload.get("input"),
|
|
1094
|
+
)
|
|
1095
|
+
if not projected or not isinstance(state.get("messages"), list):
|
|
1096
|
+
return state
|
|
1097
|
+
|
|
1098
|
+
current = convert_to_messages(state["messages"])
|
|
1099
|
+
invocation = str(
|
|
1100
|
+
projection.get("invocation_id") or payload.get("invocation_id") or uuid.uuid4()
|
|
1101
|
+
)
|
|
1102
|
+
current = [
|
|
1103
|
+
message.model_copy(
|
|
1104
|
+
update={
|
|
1105
|
+
"id": message.id
|
|
1106
|
+
or str(
|
|
1107
|
+
uuid.uuid5(uuid.NAMESPACE_URL, f"ksadk:{session_id}:{invocation}:{index}")
|
|
1108
|
+
),
|
|
1109
|
+
"response_metadata": {**message.response_metadata, TURN_KEY: invocation},
|
|
1110
|
+
}
|
|
1111
|
+
)
|
|
1112
|
+
for index, message in enumerate(current)
|
|
1113
|
+
]
|
|
1114
|
+
if not getattr(self._agent.channels["messages"], "operator", None):
|
|
1115
|
+
# LastValue nodes may return only their answer. Session history is
|
|
1116
|
+
# needed on the next turn even when that answer was checkpointed.
|
|
1117
|
+
projection = {**projection, "uncompacted": False}
|
|
1118
|
+
policies = [m for m in current if isinstance(m, SystemMessage)]
|
|
1119
|
+
previous = effective_history(projection, saved)
|
|
1120
|
+
messages = [
|
|
1121
|
+
*policies,
|
|
1122
|
+
*(m for m in previous if not (
|
|
1123
|
+
isinstance(m, SystemMessage)
|
|
1124
|
+
and any(p.content == m.content for p in policies)
|
|
1125
|
+
)),
|
|
1126
|
+
*(m for m in current if not isinstance(m, SystemMessage)),
|
|
1127
|
+
]
|
|
1128
|
+
# Public LangGraph reducer bypass: replace this turn's messages only.
|
|
1129
|
+
# Other state channels and historical checkpoints are not rewritten.
|
|
1130
|
+
state["messages"] = (
|
|
1131
|
+
Overwrite(messages)
|
|
1132
|
+
if (
|
|
1133
|
+
saver
|
|
1134
|
+
and not getattr(saver, "_ksadk_resume_only", False)
|
|
1135
|
+
and getattr(self._agent.channels["messages"], "operator", None)
|
|
1136
|
+
)
|
|
1137
|
+
else messages
|
|
1138
|
+
)
|
|
1139
|
+
return state
|
|
1140
|
+
|
|
1018
1141
|
def _prepare_state_with_hook(
|
|
1019
1142
|
self,
|
|
1020
1143
|
payload: Dict[str, Any],
|
|
@@ -1272,6 +1395,7 @@ class LangGraphRunner(
|
|
|
1272
1395
|
return {"output": accumulated_text, "raw": {"chunks": chunks}}
|
|
1273
1396
|
|
|
1274
1397
|
@fresh_user_checkpoint
|
|
1398
|
+
@model_budget_scope
|
|
1275
1399
|
async def invoke(self, input_data: Dict[str, Any]) -> Dict[str, Any]:
|
|
1276
1400
|
"""调用 LangGraph 图
|
|
1277
1401
|
|
|
@@ -1315,10 +1439,8 @@ class LangGraphRunner(
|
|
|
1315
1439
|
# applying it here can rewrite an approval decision into ordinary
|
|
1316
1440
|
# graph state and turn an approved HITL action into a rejection.
|
|
1317
1441
|
state = self._unwrap_resume_value(resume_value)
|
|
1318
|
-
elif self._has_prepare_state_hook():
|
|
1319
|
-
state = self._prepare_state_with_hook(payload, session_id, history)
|
|
1320
1442
|
else:
|
|
1321
|
-
state = self.
|
|
1443
|
+
state = await self._prepare_new_turn_state(payload, session_id, history, config=config)
|
|
1322
1444
|
|
|
1323
1445
|
if not is_resume and not is_checkpoint_resume:
|
|
1324
1446
|
state = await fresh_memory_input(self._agent, config, state)
|
|
@@ -9,6 +9,7 @@ cache_creation),逐键求和作诊断明细。
|
|
|
9
9
|
|
|
10
10
|
from __future__ import annotations
|
|
11
11
|
|
|
12
|
+
from dataclasses import dataclass
|
|
12
13
|
from typing import Any
|
|
13
14
|
|
|
14
15
|
_SCALAR_FIELDS = (
|
|
@@ -45,3 +46,42 @@ def accumulate_usage(acc: dict[str, Any], delta: dict[str, Any]) -> dict[str, An
|
|
|
45
46
|
if merged:
|
|
46
47
|
result[detail_key] = merged
|
|
47
48
|
return result
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass(frozen=True)
|
|
52
|
+
class ADKUsageSnapshot:
|
|
53
|
+
invocation_id: str
|
|
54
|
+
response_id: str
|
|
55
|
+
timestamp: float | None
|
|
56
|
+
partial: bool
|
|
57
|
+
usage: dict[str, Any]
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class ADKUsageAccumulator:
|
|
61
|
+
"""Fold ADK partial and final observations of the same native response."""
|
|
62
|
+
|
|
63
|
+
def __init__(self) -> None:
|
|
64
|
+
self.snapshots: dict[tuple[str, str], ADKUsageSnapshot] = {}
|
|
65
|
+
self.last_usage: dict[str, Any] = {}
|
|
66
|
+
|
|
67
|
+
def observe(self, event: Any, usage: dict[str, Any]) -> None:
|
|
68
|
+
if not usage:
|
|
69
|
+
return
|
|
70
|
+
invocation_id = str(getattr(event, "invocation_id", None) or "")
|
|
71
|
+
response_id = str(getattr(event, "id", None) or f"unidentified:{len(self.snapshots)}")
|
|
72
|
+
key = invocation_id, response_id
|
|
73
|
+
partial = bool(getattr(event, "partial", False))
|
|
74
|
+
previous = self.snapshots.get(key)
|
|
75
|
+
if previous is not None and not previous.partial and partial:
|
|
76
|
+
return
|
|
77
|
+
timestamp = getattr(event, "timestamp", None)
|
|
78
|
+
self.snapshots[key] = ADKUsageSnapshot(
|
|
79
|
+
invocation_id, response_id, timestamp, partial, usage,
|
|
80
|
+
)
|
|
81
|
+
self.last_usage = usage
|
|
82
|
+
|
|
83
|
+
def total(self) -> dict[str, Any]:
|
|
84
|
+
total: dict[str, Any] = {}
|
|
85
|
+
for snapshot in self.snapshots.values():
|
|
86
|
+
total = accumulate_usage(total, snapshot.usage)
|
|
87
|
+
return total
|
|
@@ -100,6 +100,14 @@ async def iter_runtime_conversation_events(
|
|
|
100
100
|
|
|
101
101
|
turn_started_monotonic = time.monotonic()
|
|
102
102
|
provider = session_service_provider or resolve_session_service
|
|
103
|
+
context_runner = None
|
|
104
|
+
if launch_context.runtime_type == "langgraph" and resume_input is None:
|
|
105
|
+
if runtime_preparation is None:
|
|
106
|
+
runtime_preparation = await executor.prepare_start(launch_context)
|
|
107
|
+
candidate = getattr(getattr(runtime_preparation.adapter, "runtime", None), "runner", None)
|
|
108
|
+
uses_model_context = getattr(candidate, "uses_ksadk_model_context", None)
|
|
109
|
+
if callable(uses_model_context) and uses_model_context():
|
|
110
|
+
context_runner = candidate
|
|
103
111
|
compaction_preview = await preview_auto_compaction(
|
|
104
112
|
agent_id=agent_id,
|
|
105
113
|
user_id=user_id,
|
|
@@ -108,6 +116,7 @@ async def iter_runtime_conversation_events(
|
|
|
108
116
|
model=model,
|
|
109
117
|
model_metadata=model_metadata,
|
|
110
118
|
session_service_provider=provider,
|
|
119
|
+
compaction_owner="ksadk" if context_runner is not None else "",
|
|
111
120
|
)
|
|
112
121
|
prepared = await build_run_input(
|
|
113
122
|
agent_id=agent_id,
|
|
@@ -126,6 +135,7 @@ async def iter_runtime_conversation_events(
|
|
|
126
135
|
session_service_provider=provider,
|
|
127
136
|
run_mode=run_mode,
|
|
128
137
|
runtime_type=launch_context.runtime_type,
|
|
138
|
+
runner=context_runner,
|
|
129
139
|
)
|
|
130
140
|
if _execution_context is not None:
|
|
131
141
|
_execution_context["session_id"] = prepared.session_id
|
|
@@ -206,6 +216,7 @@ async def iter_runtime_conversation_events(
|
|
|
206
216
|
),
|
|
207
217
|
)
|
|
208
218
|
for persisted in await pipeline.ingest(event):
|
|
219
|
+
terminal = persisted.event_type in _TERMINAL_EVENTS
|
|
209
220
|
await _project_runtime_run_status(
|
|
210
221
|
persisted,
|
|
211
222
|
session_id=prepared.session_id,
|
|
@@ -216,8 +227,12 @@ async def iter_runtime_conversation_events(
|
|
|
216
227
|
run_mode=prepared.run_mode,
|
|
217
228
|
run_trigger=prepared.run_trigger,
|
|
218
229
|
session_service_provider=provider,
|
|
230
|
+
terminal_usage=(
|
|
231
|
+
snapshot.model_dump()
|
|
232
|
+
if terminal and (snapshot := pipeline.reducer.usage_snapshot()) is not None
|
|
233
|
+
else None
|
|
234
|
+
),
|
|
219
235
|
)
|
|
220
|
-
terminal = persisted.event_type in _TERMINAL_EVENTS
|
|
221
236
|
interrupted = persisted.event_type == "run.interrupted"
|
|
222
237
|
if terminal and _execution_context is not None:
|
|
223
238
|
# HTTP may attach mid-run. Its live reducer only saw this
|
|
@@ -250,6 +265,7 @@ async def iter_runtime_conversation_events(
|
|
|
250
265
|
reason=cancel_result.value,
|
|
251
266
|
)
|
|
252
267
|
persisted_cancelled = (await pipeline.ingest(cancelled_event))[-1]
|
|
268
|
+
snapshot = pipeline.reducer.usage_snapshot()
|
|
253
269
|
await _project_runtime_run_status(
|
|
254
270
|
persisted_cancelled,
|
|
255
271
|
session_id=prepared.session_id,
|
|
@@ -260,6 +276,7 @@ async def iter_runtime_conversation_events(
|
|
|
260
276
|
run_mode=prepared.run_mode,
|
|
261
277
|
run_trigger=prepared.run_trigger,
|
|
262
278
|
session_service_provider=provider,
|
|
279
|
+
terminal_usage=snapshot.model_dump() if snapshot is not None else None,
|
|
263
280
|
)
|
|
264
281
|
await executor.close(handle)
|
|
265
282
|
raise
|
|
@@ -396,6 +413,7 @@ async def _project_runtime_run_status(
|
|
|
396
413
|
run_mode: str,
|
|
397
414
|
run_trigger: str,
|
|
398
415
|
session_service_provider: Callable[[], Any],
|
|
416
|
+
terminal_usage: dict[str, Any] | None = None,
|
|
399
417
|
) -> None:
|
|
400
418
|
"""Project canonical lifecycle events into the session's active-run state."""
|
|
401
419
|
|
|
@@ -412,6 +430,7 @@ async def _project_runtime_run_status(
|
|
|
412
430
|
metadata={
|
|
413
431
|
"runtime_event_id": event.event_id,
|
|
414
432
|
"runtime_event_type": event.event_type,
|
|
433
|
+
**({"token_usage": terminal_usage} if event.event_type in _TERMINAL_EVENTS else {}),
|
|
415
434
|
},
|
|
416
435
|
session_service_provider=session_service_provider,
|
|
417
436
|
run_mode=run_mode,
|
|
@@ -679,27 +698,30 @@ async def iter_runtime_conversation_semantic_events(
|
|
|
679
698
|
"session_id": execution_context.get("session_id", ""),
|
|
680
699
|
}
|
|
681
700
|
elif isinstance(event, RunFailed):
|
|
701
|
+
usage = execution_context.get("terminal_usage") or reducer.usage_snapshot()
|
|
682
702
|
metrics = event.source.metadata.get("metrics")
|
|
683
703
|
timing = normalize_timing(metrics.get("timing")) if isinstance(metrics, Mapping) else {}
|
|
684
704
|
yield {
|
|
685
705
|
"type": "error",
|
|
686
706
|
"message": event.error.message or "Agent 运行失败",
|
|
687
707
|
"session_id": execution_context.get("session_id", ""),
|
|
688
|
-
"usage":
|
|
708
|
+
"usage": usage.model_dump() if usage is not None else None,
|
|
689
709
|
**({"timing": timing} if timing else {}),
|
|
690
710
|
**skill_eval_response_fields(metrics),
|
|
691
711
|
}
|
|
692
712
|
elif isinstance(event, RunCanceled):
|
|
713
|
+
usage = execution_context.get("terminal_usage") or reducer.usage_snapshot()
|
|
693
714
|
metrics = event.source.metadata.get("metrics")
|
|
694
715
|
timing = normalize_timing(metrics.get("timing")) if isinstance(metrics, Mapping) else {}
|
|
695
716
|
yield {
|
|
696
717
|
"type": "cancelled",
|
|
697
718
|
"session_id": execution_context.get("session_id", ""),
|
|
698
|
-
"usage":
|
|
719
|
+
"usage": usage.model_dump() if usage is not None else None,
|
|
699
720
|
**({"timing": timing} if timing else {}),
|
|
700
721
|
**skill_eval_response_fields(metrics),
|
|
701
722
|
}
|
|
702
723
|
elif isinstance(event, RunCompleted):
|
|
724
|
+
usage = execution_context.get("terminal_usage") or reducer.usage_snapshot()
|
|
703
725
|
completion_metadata = dict(event.source.metadata)
|
|
704
726
|
metrics = completion_metadata.get("metrics")
|
|
705
727
|
metrics = metrics if isinstance(metrics, Mapping) else {}
|
|
@@ -727,7 +749,7 @@ async def iter_runtime_conversation_semantic_events(
|
|
|
727
749
|
"type": "completed",
|
|
728
750
|
"output_text": _selected_output_text(projection, event),
|
|
729
751
|
"session_id": execution_context.get("session_id", ""),
|
|
730
|
-
"usage":
|
|
752
|
+
"usage": usage.model_dump() if usage is not None else None,
|
|
731
753
|
"metadata": completion_metadata,
|
|
732
754
|
**({"timing": timing} if timing else {}),
|
|
733
755
|
**skill_eval_response_fields(metrics),
|
ksadk/server/factory.py
CHANGED
|
@@ -964,7 +964,9 @@ def _wire_agui_if_enabled(app: FastAPI, state: RuntimeAppState, config: RuntimeA
|
|
|
964
964
|
if config.kernel_adapter_provider is not None or config.a2a_runtime_adapter is not None
|
|
965
965
|
else lambda: state.executor.capability_adapter(state.launch_context)
|
|
966
966
|
), launch_context=state.launch_context,
|
|
967
|
-
|
|
967
|
+
# Startup/recovery may run outside an HTTP request, or while a
|
|
968
|
+
# different app is bound. This runtime owns this app's storage.
|
|
969
|
+
session_service=state.resolve_session_service,
|
|
968
970
|
agent_name=agui_cfg.agent_name,
|
|
969
971
|
on_ready=state.persistence_capability.invalidate,
|
|
970
972
|
adapter_owned=(config.kernel_adapter_provider is not None
|
ksadk/server/routes/control.py
CHANGED
|
@@ -4,7 +4,6 @@ from __future__ import annotations
|
|
|
4
4
|
|
|
5
5
|
import asyncio
|
|
6
6
|
import json
|
|
7
|
-
import os
|
|
8
7
|
import time
|
|
9
8
|
import uuid
|
|
10
9
|
from collections.abc import AsyncIterator, Mapping
|
|
@@ -37,6 +36,7 @@ from ..invocation_identity import (
|
|
|
37
36
|
from . import dependencies as deps
|
|
38
37
|
from .checkpoint_resolution import _find_session_checkpoint
|
|
39
38
|
from .common import _action_response
|
|
39
|
+
from .local_kernel_control import resolve_local_responses_run_id
|
|
40
40
|
from .models import (
|
|
41
41
|
_MAX_PREVIEW_TOOL_RECEIPTS,
|
|
42
42
|
_RUN_TERMINAL_STATUSES,
|
|
@@ -539,11 +539,16 @@ async def subscribe_run_events_action(
|
|
|
539
539
|
invocation_identity=invocation_identity,
|
|
540
540
|
history_only=True,
|
|
541
541
|
)
|
|
542
|
+
stored_run_id = invocation_id
|
|
542
543
|
if not await _session_contains_invocation(service, session_id, invocation_id):
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
544
|
+
# The accepted Inbox command can identify the Run even before the
|
|
545
|
+
# worker writes its first event. Reconnect must not submit it again.
|
|
546
|
+
stored_run_id = await resolve_local_responses_run_id(session_id, invocation_id)
|
|
547
|
+
if stored_run_id is None:
|
|
548
|
+
raise HTTPException(
|
|
549
|
+
status_code=409,
|
|
550
|
+
detail="InvocationId does not belong to SessionId",
|
|
551
|
+
)
|
|
547
552
|
|
|
548
553
|
async def event_generator() -> AsyncIterator[str]:
|
|
549
554
|
last_seq_id = int(AfterSeqId or 0)
|
|
@@ -561,19 +566,30 @@ async def subscribe_run_events_action(
|
|
|
561
566
|
service,
|
|
562
567
|
session_id,
|
|
563
568
|
after_seq_id=last_seq_id,
|
|
564
|
-
invocation_id=
|
|
569
|
+
invocation_id=stored_run_id,
|
|
565
570
|
)
|
|
566
571
|
for event in events:
|
|
567
572
|
last_seq_id = max(last_seq_id, event.seq_id)
|
|
568
|
-
if event.invocation_id !=
|
|
573
|
+
if event.invocation_id != stored_run_id:
|
|
569
574
|
continue
|
|
570
575
|
payload = _event_to_action_payload(event)
|
|
576
|
+
if stored_run_id != invocation_id:
|
|
577
|
+
# Only the compatibility envelope uses the request ID.
|
|
578
|
+
# Canonical event content retains the Kernel Run ID.
|
|
579
|
+
payload["InvocationId"] = invocation_id
|
|
571
580
|
yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
|
|
572
581
|
last_heartbeat_at = time.monotonic()
|
|
582
|
+
runtime_event = (event.content or {}).get("runtime_event")
|
|
573
583
|
if (
|
|
574
584
|
event.event_type == "run_status"
|
|
575
585
|
and str((event.content or {}).get("status") or "").strip().lower()
|
|
576
586
|
in _RUN_TERMINAL_STATUSES
|
|
587
|
+
) or (
|
|
588
|
+
event.event_type in {
|
|
589
|
+
"run.completed", "run.failed", "run.canceled", "run.interrupted",
|
|
590
|
+
}
|
|
591
|
+
and isinstance(runtime_event, Mapping)
|
|
592
|
+
and not runtime_event.get("parent_scope_id")
|
|
577
593
|
):
|
|
578
594
|
yield "data: [DONE]\n\n"
|
|
579
595
|
return
|
|
@@ -583,7 +599,7 @@ async def subscribe_run_events_action(
|
|
|
583
599
|
latest_status = await _latest_invocation_status(
|
|
584
600
|
service,
|
|
585
601
|
session_id,
|
|
586
|
-
|
|
602
|
+
stored_run_id,
|
|
587
603
|
)
|
|
588
604
|
last_terminal_check_at = now
|
|
589
605
|
if latest_status in _RUN_TERMINAL_STATUSES:
|