agentengine-sdk-python 0.7.0__py3-none-any.whl → 0.8.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (450) hide show
  1. {agentengine_sdk_python-0.7.0.dist-info → agentengine_sdk_python-0.8.1.dist-info}/METADATA +52 -20
  2. agentengine_sdk_python-0.8.1.dist-info/RECORD +644 -0
  3. {agentengine_sdk_python-0.7.0.dist-info → agentengine_sdk_python-0.8.1.dist-info}/WHEEL +1 -1
  4. ksadk/a2a/__init__.py +180 -11
  5. ksadk/a2a/bootstrap.py +332 -0
  6. ksadk/a2a/card.py +15 -0
  7. ksadk/a2a/context_store.py +203 -0
  8. ksadk/a2a/control_plane.py +1056 -0
  9. ksadk/a2a/credential.py +99 -0
  10. ksadk/a2a/event_adapter.py +149 -0
  11. ksadk/a2a/executor.py +361 -137
  12. ksadk/a2a/external_transport.py +516 -0
  13. ksadk/a2a/identity.py +304 -0
  14. ksadk/a2a/ids.py +22 -0
  15. ksadk/a2a/langgraph.py +285 -0
  16. ksadk/a2a/resume_store.py +201 -0
  17. ksadk/a2a/routes.py +112 -0
  18. ksadk/a2a/server.py +102 -62
  19. ksadk/a2a/service_env.py +33 -0
  20. ksadk/a2a/space_client.py +1122 -0
  21. ksadk/a2a/task_adapter.py +423 -0
  22. ksadk/a2a/task_event_dispatcher.py +167 -0
  23. ksadk/a2a/task_event_outbox.py +326 -0
  24. ksadk/a2a/task_store.py +206 -0
  25. ksadk/a2a_card.py +101 -0
  26. ksadk/a2ui/__init__.py +27 -0
  27. ksadk/a2ui/core.py +186 -0
  28. ksadk/a2ui/models.py +166 -0
  29. ksadk/a2ui/renderer.py +198 -0
  30. ksadk/agui/__init__.py +9 -0
  31. ksadk/agui/a2ui_projection.py +92 -0
  32. ksadk/agui/agent.py +872 -0
  33. ksadk/agui/config.py +92 -0
  34. ksadk/agui/routes.py +47 -0
  35. ksadk/api/client.py +238 -204
  36. ksadk/api/environment.py +27 -0
  37. ksadk/builders/__init__.py +2 -0
  38. ksadk/builders/base.py +16 -14
  39. ksadk/builders/code_builder.py +375 -270
  40. ksadk/builders/container_builder.py +240 -200
  41. ksadk/builders/framework_requirements.py +31 -12
  42. ksadk/builders/ks3_uploader.py +60 -29
  43. ksadk/builders/managed_runtime_builder.py +173 -0
  44. ksadk/builders/mcp_builder.py +91 -92
  45. ksadk/builders/requirements_utils.py +1 -5
  46. ksadk/cli/__init__.py +97 -171
  47. ksadk/cli/cmd_a2a.py +255 -84
  48. ksadk/cli/cmd_agent.py +19 -5
  49. ksadk/cli/cmd_build.py +158 -29
  50. ksadk/cli/cmd_completion.py +47 -35
  51. ksadk/cli/cmd_config.py +267 -198
  52. ksadk/cli/cmd_create.py +507 -740
  53. ksadk/cli/cmd_dashboard.py +120 -45
  54. ksadk/cli/cmd_deploy.py +135 -59
  55. ksadk/cli/cmd_destroy.py +44 -14
  56. ksadk/cli/cmd_eval.py +386 -0
  57. ksadk/cli/cmd_files.py +63 -24
  58. ksadk/cli/cmd_hermes.py +313 -135
  59. ksadk/cli/cmd_invoke.py +184 -122
  60. ksadk/cli/cmd_launch.py +76 -28
  61. ksadk/cli/cmd_mcp.py +98 -64
  62. ksadk/cli/cmd_model.py +14 -5
  63. ksadk/cli/cmd_openclaw.py +564 -268
  64. ksadk/cli/cmd_replay.py +71 -0
  65. ksadk/cli/cmd_run.py +58 -73
  66. ksadk/cli/cmd_status.py +80 -31
  67. ksadk/cli/cmd_studio.py +110 -0
  68. ksadk/cli/cmd_version.py +20 -13
  69. ksadk/cli/cmd_web.py +95 -18
  70. ksadk/cli/deploy_utils.py +20 -20
  71. ksadk/cli/dry_run.py +7 -4
  72. ksadk/cli/env_options.py +83 -0
  73. ksadk/cli/error_utils.py +37 -12
  74. ksadk/cli/global_options.py +4 -3
  75. ksadk/cli/local_runtime.py +1 -2
  76. ksadk/cli/model_catalog.py +6 -2
  77. ksadk/cli/network_options.py +41 -19
  78. ksadk/cli/resource_common.py +6 -2
  79. ksadk/cli/runtime_bootstrap.py +51 -0
  80. ksadk/cli/storage.py +0 -1
  81. ksadk/cli/ui.py +11 -3
  82. ksadk/cli/workflow_common.py +52 -18
  83. ksadk/codex/__init__.py +12 -0
  84. ksadk/codex/client.py +1042 -0
  85. ksadk/codex/phase.py +143 -0
  86. ksadk/codex/runtime.py +940 -0
  87. ksadk/common/aicp_env.py +0 -1
  88. ksadk/common/auth.py +2 -2
  89. ksadk/common/constants.py +1 -3
  90. ksadk/common/kop_client.py +232 -0
  91. ksadk/common/llm_utils.py +17 -13
  92. ksadk/compat/__init__.py +5 -0
  93. ksadk/compat/adk_compat.py +200 -0
  94. ksadk/compat/copilotkit_a2ui.py +330 -0
  95. ksadk/configs/__init__.py +12 -14
  96. ksadk/configs/env_registry.py +661 -116
  97. ksadk/configs/global_config.py +3 -2
  98. ksadk/configs/settings.py +133 -209
  99. ksadk/conversations/__init__.py +85 -92
  100. ksadk/conversations/attachment_storage.py +16 -11
  101. ksadk/conversations/attachments.py +44 -36
  102. ksadk/conversations/compaction_pipeline.py +12 -12
  103. ksadk/conversations/compaction_prompt.py +9 -5
  104. ksadk/conversations/context.py +221 -6
  105. ksadk/conversations/message_projection.py +438 -51
  106. ksadk/conversations/model_context.py +12 -6
  107. ksadk/conversations/model_options.py +0 -1
  108. ksadk/conversations/normalize.py +20 -16
  109. ksadk/conversations/reasoning_markup.py +1 -1
  110. ksadk/conversations/runtime.py +339 -5255
  111. ksadk/conversations/runtime_compaction.py +333 -0
  112. ksadk/conversations/runtime_constants.py +27 -0
  113. ksadk/conversations/runtime_governance.py +185 -0
  114. ksadk/conversations/runtime_input.py +660 -0
  115. ksadk/conversations/runtime_invocation.py +395 -0
  116. ksadk/conversations/runtime_metadata.py +475 -0
  117. ksadk/conversations/runtime_observability.py +367 -0
  118. ksadk/conversations/runtime_payloads.py +272 -0
  119. ksadk/conversations/runtime_persistence.py +440 -0
  120. ksadk/conversations/runtime_preparation.py +426 -0
  121. ksadk/conversations/runtime_resume.py +836 -0
  122. ksadk/conversations/runtime_stream_events.py +902 -0
  123. ksadk/conversations/runtime_streaming.py +700 -0
  124. ksadk/conversations/semantic_summary.py +17 -5
  125. ksadk/conversations/session_title.py +6 -3
  126. ksadk/deployment/__init__.py +15 -16
  127. ksadk/deployment/agent_access.py +12 -23
  128. ksadk/deployment/base.py +51 -38
  129. ksadk/deployment/managed_runtime.py +33 -0
  130. ksadk/deployment/manager.py +85 -71
  131. ksadk/deployment/providers/serverless.py +379 -210
  132. ksadk/deployment/registry.py +38 -32
  133. ksadk/deployment/state.py +11 -11
  134. ksadk/deployment/ui_config.py +1 -1
  135. ksadk/detection/__init__.py +1 -1
  136. ksadk/detection/detector.py +146 -83
  137. ksadk/detection/mcp_detector.py +9 -6
  138. ksadk/evaluation/__init__.py +84 -0
  139. ksadk/evaluation/a2a_adapter.py +444 -0
  140. ksadk/evaluation/adapters.py +54 -0
  141. ksadk/evaluation/contracts.py +409 -0
  142. ksadk/evaluation/evalset.py +351 -0
  143. ksadk/evaluation/evaluators.py +461 -0
  144. ksadk/evaluation/executor.py +118 -0
  145. ksadk/evaluation/storage.py +68 -0
  146. ksadk/evaluation/target.py +73 -0
  147. ksadk/events/__init__.py +25 -0
  148. ksadk/events/parser.py +191 -0
  149. ksadk/events/replay.py +37 -0
  150. ksadk/events/runtime_event.py +273 -0
  151. ksadk/events/store.py +317 -0
  152. ksadk/harness/__init__.py +35 -0
  153. ksadk/harness/app.py +269 -0
  154. ksadk/harness/config.py +181 -0
  155. ksadk/harness/reasoner.py +105 -0
  156. ksadk/harness/runtime.py +364 -0
  157. ksadk/harness/sandbox.py +141 -0
  158. ksadk/harness/tools.py +222 -0
  159. ksadk/hermes_terminal.py +28 -12
  160. ksadk/identity/resolver.py +15 -9
  161. ksadk/ids.py +32 -0
  162. ksadk/knowledge_base/adk_tool.py +1 -1
  163. ksadk/knowledge_base/client.py +38 -33
  164. ksadk/managed_a2a_card.py +160 -0
  165. ksadk/managed_runtime.py +195 -0
  166. ksadk/markdown.py +5 -2
  167. ksadk/mcp_runtime/__init__.py +9 -6
  168. ksadk/memory/__init__.py +1 -1
  169. ksadk/memory/adk/__init__.py +2 -0
  170. ksadk/memory/adk/backends/base_ltm_backend.py +2 -6
  171. ksadk/memory/adk/backends/http_ltm_backend.py +13 -21
  172. ksadk/memory/adk/backends/inmemory_ltm_backend.py +7 -13
  173. ksadk/memory/adk/backends/sdk_ltm_backend.py +36 -36
  174. ksadk/memory/adk/long_term_memory.py +34 -37
  175. ksadk/memory/adk/resilient_session_service.py +4 -5
  176. ksadk/memory/adk/short_term_memory.py +12 -21
  177. ksadk/memory/adk_tool.py +3 -2
  178. ksadk/memory/backends/base.py +19 -19
  179. ksadk/memory/backends/memory.py +24 -25
  180. ksadk/memory/backends/redis.py +31 -30
  181. ksadk/memory/langchain_tool.py +2 -1
  182. ksadk/memory/manager.py +52 -47
  183. ksadk/memory/service.py +16 -6
  184. ksadk/memory/tool.py +4 -0
  185. ksadk/model_policy.py +15 -7
  186. ksadk/model_proxy/__init__.py +51 -0
  187. ksadk/model_proxy/bootstrap.py +80 -0
  188. ksadk/model_proxy/cache.py +165 -0
  189. ksadk/model_proxy/config.py +66 -0
  190. ksadk/model_proxy/demo_webui.py +115 -0
  191. ksadk/model_proxy/detect.py +145 -0
  192. ksadk/model_proxy/gate.py +68 -0
  193. ksadk/model_proxy/namespace.py +201 -0
  194. ksadk/model_proxy/protocol_proxy.py +22 -0
  195. ksadk/model_proxy/server.py +443 -0
  196. ksadk/model_proxy/transform.py +735 -0
  197. ksadk/openclaw_gateway.py +29 -14
  198. ksadk/runners/adk_runner.py +354 -146
  199. ksadk/runners/base_runner.py +71 -29
  200. ksadk/runners/deepagents_runner.py +0 -1
  201. ksadk/runners/factory.py +18 -5
  202. ksadk/runners/langchain_runner.py +29 -742
  203. ksadk/runners/langgraph_runner.py +417 -97
  204. ksadk/runners/patch_langchain.py +16 -16
  205. ksadk/runners/remote_runner.py +134 -33
  206. ksadk/runners/usage_accumulator.py +1 -0
  207. ksadk/runners/utils/__init__.py +0 -10
  208. ksadk/runners/utils/loader.py +23 -7
  209. ksadk/runtime/__init__.py +67 -0
  210. ksadk/runtime/adapter.py +412 -0
  211. ksadk/runtime/conversation_execution.py +553 -0
  212. ksadk/runtime/executor.py +251 -0
  213. ksadk/runtime/factory.py +156 -0
  214. ksadk/runtime/framework_adapters.py +118 -0
  215. ksadk/runtime/launch.py +48 -0
  216. ksadk/runtime/preprocessing.py +131 -0
  217. ksadk/runtime/runner_adapter.py +1032 -0
  218. ksadk/runtime/runner_loading.py +36 -0
  219. ksadk/runtime_context.py +18 -3
  220. ksadk/runtime_state.py +0 -1
  221. ksadk/sandbox/__init__.py +4 -1
  222. ksadk/sandbox/backends/__init__.py +4 -1
  223. ksadk/sandbox/backends/e2b.py +13 -5
  224. ksadk/sandbox/backends/local_process.py +11 -3
  225. ksadk/sandbox/base.py +10 -15
  226. ksadk/sandbox/factory.py +14 -4
  227. ksadk/sandbox/registry.py +57 -6
  228. ksadk/server/__init__.py +39 -4
  229. ksadk/server/api_models.py +15 -5
  230. ksadk/server/app.py +24 -3928
  231. ksadk/server/composition.py +47 -0
  232. ksadk/server/factory.py +622 -0
  233. ksadk/server/routes/__init__.py +1 -0
  234. ksadk/server/routes/checkpoint_resolution.py +116 -0
  235. ksadk/server/routes/common.py +682 -0
  236. ksadk/server/routes/control.py +331 -0
  237. ksadk/server/routes/dependencies.py +98 -0
  238. ksadk/server/routes/misc.py +425 -0
  239. ksadk/server/routes/models.py +451 -0
  240. ksadk/server/routes/openai_compat.py +229 -0
  241. ksadk/server/routes/projection.py +848 -0
  242. ksadk/server/routes/routers.py +52 -0
  243. ksadk/server/routes/run.py +519 -0
  244. ksadk/server/routes/sessions.py +644 -0
  245. ksadk/server/routes/streaming.py +265 -0
  246. ksadk/server/routes/workspace.py +414 -0
  247. ksadk/server/static/assets/{ArtifactsPanel-D-SSn2ee.js → ArtifactsPanel-CakCqxEN.js} +1 -1
  248. ksadk/server/static/assets/CodeBlock-CynLknyO.js +9 -0
  249. ksadk/server/static/assets/MathMessageMarkdown-3sQdOysS.js +8 -0
  250. ksadk/server/static/assets/MermaidBlock-NERD_ef7.js +303 -0
  251. ksadk/server/static/assets/NativeTerminalPanel-CiHWf82q.js +1 -0
  252. ksadk/server/static/assets/{arc-BA13sHc9.js → arc-DrgjcKhl.js} +1 -1
  253. ksadk/server/static/assets/architecture-7EHR7CIX-CpZLRCcY.js +1 -0
  254. ksadk/server/static/assets/{architectureDiagram-3BPJPVTR-DzJzgVoL.js → architectureDiagram-3BPJPVTR-BXoVRbQ6.js} +1 -1
  255. ksadk/server/static/assets/{blockDiagram-GPEHLZMM-UTdVcZhn.js → blockDiagram-GPEHLZMM-BnaB3Ywv.js} +1 -1
  256. ksadk/server/static/assets/{c4Diagram-AAUBKEIU-Dix0GD4m.js → c4Diagram-AAUBKEIU-Dw4weZcp.js} +1 -1
  257. ksadk/server/static/assets/channel-Dt3rQTFI.js +1 -0
  258. ksadk/server/static/assets/{chunk-2J33WTMH-C2JxuZ42.js → chunk-2J33WTMH-ChjpLK7j.js} +1 -1
  259. ksadk/server/static/assets/{chunk-4BX2VUAB-Be57QPgD.js → chunk-4BX2VUAB-B9drTgOW.js} +1 -1
  260. ksadk/server/static/assets/{chunk-55IACEB6-WjSuy4nv.js → chunk-55IACEB6-CK4ROATy.js} +1 -1
  261. ksadk/server/static/assets/{chunk-727SXJPM-BOovP-b5.js → chunk-727SXJPM-B9KtTTgw.js} +1 -1
  262. ksadk/server/static/assets/{chunk-AQP2D5EJ-DOmZNmWj.js → chunk-AQP2D5EJ-1O1mki3m.js} +1 -1
  263. ksadk/server/static/assets/{chunk-FMBD7UC4-DzwlodkU.js → chunk-FMBD7UC4-B_fH2YuH.js} +1 -1
  264. ksadk/server/static/assets/{chunk-ND2GUHAM-DMqAikEU.js → chunk-ND2GUHAM-D6rFLaVV.js} +1 -1
  265. ksadk/server/static/assets/chunk-QZHKN3VN-iXEZtKQc.js +1 -0
  266. ksadk/server/static/assets/classDiagram-4FO5ZUOK-DIveV17Q.js +1 -0
  267. ksadk/server/static/assets/classDiagram-v2-Q7XG4LA2-DIveV17Q.js +1 -0
  268. ksadk/server/static/assets/{cose-bilkent-S5V4N54A-Zhy2GBnP.js → cose-bilkent-S5V4N54A-ChNs_Mdk.js} +1 -1
  269. ksadk/server/static/assets/{dagre-BM42HDAG-CbKrtIUz.js → dagre-BM42HDAG-D0QXg_MQ.js} +1 -1
  270. ksadk/server/static/assets/{diagram-2AECGRRQ-BRApgQRK.js → diagram-2AECGRRQ-DBDDKwBQ.js} +1 -1
  271. ksadk/server/static/assets/{diagram-5GNKFQAL-D0xbnDiK.js → diagram-5GNKFQAL-BkwDOxmO.js} +1 -1
  272. ksadk/server/static/assets/{diagram-KO2AKTUF-CVugVI9L.js → diagram-KO2AKTUF-Bv8waYvY.js} +1 -1
  273. ksadk/server/static/assets/{diagram-LMA3HP47-DozUGgee.js → diagram-LMA3HP47-e1VECDdu.js} +1 -1
  274. ksadk/server/static/assets/{diagram-OG6HWLK6-ZOYsKlru.js → diagram-OG6HWLK6-Ds9adfRl.js} +1 -1
  275. ksadk/server/static/assets/{dist-DpKtt4Bo.js → dist-4N2NMVYg.js} +1 -1
  276. ksadk/server/static/assets/{dist-CkEKJFtk.js → dist-B-jNR6Vn.js} +1 -1
  277. ksadk/server/static/assets/{dist-D57wnGWd.js → dist-B5J2uhNk.js} +1 -1
  278. ksadk/server/static/assets/{dist-8_SfK1IP.js → dist-B5oS1zcj.js} +1 -1
  279. ksadk/server/static/assets/{dist-DMezvBGJ.js → dist-BB3-OwTQ.js} +1 -1
  280. ksadk/server/static/assets/{dist-2hInLS_J.js → dist-BIlKoW0k.js} +1 -1
  281. ksadk/server/static/assets/{dist-BrCcQ47T.js → dist-BjOdlDjj.js} +1 -1
  282. ksadk/server/static/assets/{dist-BmlMPsCc.js → dist-C1sz5Eo3.js} +1 -1
  283. ksadk/server/static/assets/{dist-B0NP_Z0z.js → dist-CWV4lDr1.js} +1 -1
  284. ksadk/server/static/assets/{dist-D-xOD048.js → dist-CmZHzlwZ.js} +1 -1
  285. ksadk/server/static/assets/{dist-DL_NKc_z.js → dist-D6MpCZtz.js} +1 -1
  286. ksadk/server/static/assets/{dist-DyOkZmze.js → dist-DJN_6Y39.js} +1 -1
  287. ksadk/server/static/assets/{dist-DmFaq_Iy.js → dist-DQU9EWw-.js} +1 -1
  288. ksadk/server/static/assets/{dist-gX6GOLKq.js → dist-DWKByxWV.js} +1 -1
  289. ksadk/server/static/assets/{dist-DyWsb78Q.js → dist-Dli7qW-B.js} +1 -1
  290. ksadk/server/static/assets/{dist-BIJVDMuB.js → dist-DsHPdk3W.js} +1 -1
  291. ksadk/server/static/assets/{dist-Dp0k7bWI.js → dist-X4TnqwOK.js} +1 -1
  292. ksadk/server/static/assets/{dist-8EEyGgDx.js → dist-_pHPTyZ-.js} +1 -1
  293. ksadk/server/static/assets/{dist-CPBtqRTW.js → dist-fhOuWds5.js} +1 -1
  294. ksadk/server/static/assets/{dist-D-JMdWPQ.js → dist-gLnrGsoU.js} +1 -1
  295. ksadk/server/static/assets/{dist-BssVmjIo.js → dist-j6Dxmf_j.js} +1 -1
  296. ksadk/server/static/assets/{dist-C3HIIaN5.js → dist-o2OVmKvt.js} +1 -1
  297. ksadk/server/static/assets/{erDiagram-TEJ5UH35-Bk-9bgE5.js → erDiagram-TEJ5UH35-BPItFKH6.js} +1 -1
  298. ksadk/server/static/assets/eventmodeling-FCH6USID-DYFSxbqr.js +1 -0
  299. ksadk/server/static/assets/{flowDiagram-I6XJVG4X-Dn9kZVuZ.js → flowDiagram-I6XJVG4X-BbYB9w5Y.js} +1 -1
  300. ksadk/server/static/assets/{ganttDiagram-6RSMTGT7-BGxXlJqm.js → ganttDiagram-6RSMTGT7-TQXa0KXv.js} +1 -1
  301. ksadk/server/static/assets/gitGraph-WXDBUCRP-DyNYp6BN.js +1 -0
  302. ksadk/server/static/assets/{gitGraphDiagram-PVQCEYII-C7Q0X-wi.js → gitGraphDiagram-PVQCEYII-bKblCnpa.js} +1 -1
  303. ksadk/server/static/assets/index-R52pJJvg.js +177 -0
  304. ksadk/server/static/assets/index-jJr3_955.css +2 -0
  305. ksadk/server/static/assets/info-J43DQDTF-WUx7qTde.js +1 -0
  306. ksadk/server/static/assets/{infoDiagram-5YYISTIA-BO_CSqq5.js → infoDiagram-5YYISTIA-BGVT7J_i.js} +1 -1
  307. ksadk/server/static/assets/{ishikawaDiagram-YF4QCWOH-eYLPLd46.js → ishikawaDiagram-YF4QCWOH-K0OOfVna.js} +1 -1
  308. ksadk/server/static/assets/{journeyDiagram-JHISSGLW-De9geSb0.js → journeyDiagram-JHISSGLW-8LeOJaZp.js} +1 -1
  309. ksadk/server/static/assets/{kanban-definition-UN3LZRKU-Cs80kQto.js → kanban-definition-UN3LZRKU-C6uCgZrW.js} +1 -1
  310. ksadk/server/static/assets/{katex-DSrCFD8n.js → katex-CYWseY5E.js} +1 -1
  311. ksadk/server/static/assets/{linear-CN9sbKTF.js → linear-hdBcYzM8.js} +1 -1
  312. ksadk/server/static/assets/{mermaid-parser.core-DlgSBU8l.js → mermaid-parser.core-BWrDjSZM.js} +2 -2
  313. ksadk/server/static/assets/{mindmap-definition-RKZ34NQL-9afz7Oug.js → mindmap-definition-RKZ34NQL-Bjy_2v4_.js} +1 -1
  314. ksadk/server/static/assets/packet-YPE3B663-BN13y_xl.js +1 -0
  315. ksadk/server/static/assets/pie-LRSECV5Y-ftSLXhhc.js +1 -0
  316. ksadk/server/static/assets/{pieDiagram-4H26LBE5-DPv_VstN.js → pieDiagram-4H26LBE5-GmmqNiVH.js} +1 -1
  317. ksadk/server/static/assets/{quadrantDiagram-W4KKPZXB-o77wZ1XK.js → quadrantDiagram-W4KKPZXB-BmkRbwCg.js} +1 -1
  318. ksadk/server/static/assets/radar-GUYGQ44K-jaICkIeO.js +1 -0
  319. ksadk/server/static/assets/{requirementDiagram-4Y6WPE33-BYVw81VC.js → requirementDiagram-4Y6WPE33-DSWFqL7c.js} +1 -1
  320. ksadk/server/static/assets/{sankeyDiagram-5OEKKPKP-B7nZFMKT.js → sankeyDiagram-5OEKKPKP-l6iXmU65.js} +1 -1
  321. ksadk/server/static/assets/{sequenceDiagram-3UESZ5HK-BGRRrFw5.js → sequenceDiagram-3UESZ5HK-Cq6UBeQB.js} +1 -1
  322. ksadk/server/static/assets/{stateDiagram-AJRCARHV-BUfHCoPs.js → stateDiagram-AJRCARHV-qzTQpg3Y.js} +1 -1
  323. ksadk/server/static/assets/stateDiagram-v2-BHNVJYJU-BYCoYGAN.js +1 -0
  324. ksadk/server/static/assets/{timeline-definition-PNZ67QCA-FbCTGrf9.js → timeline-definition-PNZ67QCA-DEz24vV0.js} +1 -1
  325. ksadk/server/static/assets/treeView-BLDUP644-Cpib_vlz.js +1 -0
  326. ksadk/server/static/assets/treemap-LRROVOQU-DQxfmVHK.js +1 -0
  327. ksadk/server/static/assets/{vennDiagram-CIIHVFJN-DWgwtPsJ.js → vennDiagram-CIIHVFJN-CMCixki2.js} +1 -1
  328. ksadk/server/static/assets/wardley-L42UT6IY-BQYHnnkU.js +1 -0
  329. ksadk/server/static/assets/{wardleyDiagram-YWT4CUSO-2x8G-tTM.js → wardleyDiagram-YWT4CUSO-CVzB8F9K.js} +1 -1
  330. ksadk/server/static/assets/{xychartDiagram-2RQKCTM6-Drma3AYl.js → xychartDiagram-2RQKCTM6-BFBqBLc1.js} +1 -1
  331. ksadk/server/static/index.html +2 -2
  332. ksadk/server/terminal_sessions.py +111 -58
  333. ksadk/sessions/__init__.py +69 -19
  334. ksadk/sessions/base.py +31 -11
  335. ksadk/sessions/continuity.py +2 -3
  336. ksadk/sessions/in_memory.py +46 -2
  337. ksadk/sessions/local_service.py +148 -17
  338. ksadk/sessions/postgres_service.py +143 -25
  339. ksadk/sessions/resilient.py +36 -8
  340. ksadk/skills/models.py +17 -5
  341. ksadk/skills/package_store.py +5 -2
  342. ksadk/skills/runtime/agent.py +20 -5
  343. ksadk/skills/runtime/artifacts.py +1 -5
  344. ksadk/skills/runtime/backends/e2b.py +10 -4
  345. ksadk/skills/runtime/backends/local.py +15 -3
  346. ksadk/skills/runtime/base.py +1 -2
  347. ksadk/skills/runtime/executor.py +10 -3
  348. ksadk/skills/runtime/factory.py +4 -2
  349. ksadk/skills/runtime/loader.py +1 -2
  350. ksadk/skills/runtime/registry.py +15 -10
  351. ksadk/skills/runtime/request.py +3 -1
  352. ksadk/skills/service_client.py +47 -16
  353. ksadk/skills/tool_defs.py +15 -10
  354. ksadk/studio/__init__.py +5 -0
  355. ksadk/studio/agent_avatar_assets.py +120 -0
  356. ksadk/studio/agent_lifecycle.py +51 -0
  357. ksadk/studio/api.py +1046 -0
  358. ksadk/studio/api_catalog_routes.py +324 -0
  359. ksadk/studio/api_contracts.py +177 -0
  360. ksadk/studio/api_helpers.py +132 -0
  361. ksadk/studio/authoring.py +524 -0
  362. ksadk/studio/authoring_coordinator.py +285 -0
  363. ksadk/studio/builder.py +320 -0
  364. ksadk/studio/capabilities.py +351 -0
  365. ksadk/studio/cloud.py +278 -0
  366. ksadk/studio/codex_agent_service.py +583 -0
  367. ksadk/studio/codex_builder.py +324 -0
  368. ksadk/studio/codex_manifest.py +278 -0
  369. ksadk/studio/codex_run.py +352 -0
  370. ksadk/studio/compiler.py +189 -0
  371. ksadk/studio/contracts.py +644 -0
  372. ksadk/studio/errors.py +47 -0
  373. ksadk/studio/evaluation.py +192 -0
  374. ksadk/studio/event_store.py +284 -0
  375. ksadk/studio/framework_run.py +114 -0
  376. ksadk/studio/identifiers.py +33 -0
  377. ksadk/studio/mcp_runtime.py +229 -0
  378. ksadk/studio/model_client.py +543 -0
  379. ksadk/studio/model_profile_service.py +214 -0
  380. ksadk/studio/operations.py +243 -0
  381. ksadk/studio/otel_trace.py +754 -0
  382. ksadk/studio/pagination.py +182 -0
  383. ksadk/studio/python_tool_inspection.py +183 -0
  384. ksadk/studio/repository.py +306 -0
  385. ksadk/studio/resource_catalog.py +1217 -0
  386. ksadk/studio/run_service.py +707 -0
  387. ksadk/studio/runtime_catalog.py +74 -0
  388. ksadk/studio/runtime_source.py +339 -0
  389. ksadk/studio/service.py +1141 -0
  390. ksadk/studio/shared_web.py +994 -0
  391. ksadk/studio/skill_discovery.py +628 -0
  392. ksadk/studio/static/assets/PrismRenderer-IYN-ffww.js +3 -0
  393. ksadk/studio/static/assets/index-CaEN0eTR.css +1 -0
  394. ksadk/studio/static/assets/index-DI2eY_NH.js +252 -0
  395. ksadk/studio/static/assets/react-vendor-BNmTiJ-I.js +9 -0
  396. ksadk/studio/static/assets/rolldown-runtime-hePW80VL.js +1 -0
  397. ksadk/studio/static/index.html +15 -0
  398. ksadk/studio/templates.py +630 -0
  399. ksadk/studio/validator.py +246 -0
  400. ksadk/studio/workspace.py +137 -0
  401. ksadk/terminal_exec_policy.py +3 -4
  402. ksadk/tools/gateway.py +101 -15
  403. ksadk/tools/result_budget.py +12 -4
  404. ksadk/toolsets/__init__.py +161 -37
  405. ksadk/toolsets/a2a.py +426 -0
  406. ksadk/toolsets/platform.py +21 -5
  407. ksadk/toolsets/sandbox.py +82 -16
  408. ksadk/toolsets/skills.py +200 -39
  409. ksadk/toolsets/web.py +123 -26
  410. ksadk/toolsets/workspace.py +212 -101
  411. ksadk/tracing/__init__.py +19 -21
  412. ksadk/tracing/exporters/inmemory_exporter.py +62 -51
  413. ksadk/tracing/setup.py +135 -506
  414. ksadk/tracing/span_utils.py +0 -41
  415. ksadk/tui/loop.py +78 -30
  416. ksadk/tui/stream_render.py +1 -0
  417. ksadk/ui_config.py +5 -3
  418. ksadk/version.py +1 -1
  419. ksadk_runtime_common/memory_backend/registry.py +56 -56
  420. ksadk_runtime_common/schemas/runtime_event_v1.json +95 -0
  421. ksadk_runtime_common/workspace_files/router.py +8 -2
  422. agentengine_sdk_python-0.7.0.dist-info/RECORD +0 -482
  423. ksadk/a2a/card_builder.py +0 -64
  424. ksadk/a2a/client.py +0 -309
  425. ksadk/runners/utils/langfuse.py +0 -230
  426. ksadk/server/static/assets/CodeBlock-P16VOLYi.js +0 -9
  427. ksadk/server/static/assets/MathMessageMarkdown-CdGiQWHR.js +0 -8
  428. ksadk/server/static/assets/MermaidBlock-IOcal8cm.js +0 -303
  429. ksadk/server/static/assets/NativeTerminalPanel-DGSDWsei.js +0 -1
  430. ksadk/server/static/assets/architecture-7EHR7CIX-BvUlsA6l.js +0 -1
  431. ksadk/server/static/assets/channel-CTuydARX.js +0 -1
  432. ksadk/server/static/assets/chunk-QZHKN3VN-BnCydivS.js +0 -1
  433. ksadk/server/static/assets/classDiagram-4FO5ZUOK-BNHg45Be.js +0 -1
  434. ksadk/server/static/assets/classDiagram-v2-Q7XG4LA2-BNHg45Be.js +0 -1
  435. ksadk/server/static/assets/eventmodeling-FCH6USID-DsAgWnlf.js +0 -1
  436. ksadk/server/static/assets/gitGraph-WXDBUCRP-BIao9Yjg.js +0 -1
  437. ksadk/server/static/assets/index-C00Lwg3L.js +0 -165
  438. ksadk/server/static/assets/index-DAURbCsP.css +0 -1
  439. ksadk/server/static/assets/info-J43DQDTF-CyipqGxU.js +0 -1
  440. ksadk/server/static/assets/packet-YPE3B663-CGkyRxlg.js +0 -1
  441. ksadk/server/static/assets/pie-LRSECV5Y-M0uWAf4n.js +0 -1
  442. ksadk/server/static/assets/radar-GUYGQ44K-Bdbm24-x.js +0 -1
  443. ksadk/server/static/assets/stateDiagram-v2-BHNVJYJU-8xBN_gLM.js +0 -1
  444. ksadk/server/static/assets/treeView-BLDUP644-npMo0ak1.js +0 -1
  445. ksadk/server/static/assets/treemap-LRROVOQU-CHdzrrdo.js +0 -1
  446. ksadk/server/static/assets/wardley-L42UT6IY-BEQz7wyy.js +0 -1
  447. ksadk/tracing/exporters/langfuse_exporter.py +0 -445
  448. {agentengine_sdk_python-0.7.0.dist-info → agentengine_sdk_python-0.8.1.dist-info}/entry_points.txt +0 -0
  449. {agentengine_sdk_python-0.7.0.dist-info → agentengine_sdk_python-0.8.1.dist-info}/licenses/LICENSE +0 -0
  450. {agentengine_sdk_python-0.7.0.dist-info → agentengine_sdk_python-0.8.1.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,735 @@
1
+ """OpenAI Responses API <-> Chat Completions API 纯转换器(无环境依赖).
2
+
3
+ 映射逻辑参照 cc-switch transform_codex_chat.rs / streaming_codex_chat.rs /
4
+ codex_responses_sse.rs,用 Python 重写。本模块只做纯函数/纯状态机转换,
5
+ 不读环境变量、不持有网络/配置 —— 配置由 config.py 注入,便于内化与测试。
6
+ """
7
+
8
+ import json
9
+ import time
10
+
11
+
12
+ class UnsupportedToolsError(ValueError):
13
+ """codex 请求携带了当前不支持转换的工具类型(namespace/MCP/web_search 等)。
14
+
15
+ 应 fail-fast 返回明确错误,而不是静默丢弃工具降级请求;根治靠 namespace 拍平。
16
+ """
17
+
18
+
19
+ # ---------------------------------------------------------------------------
20
+ # 文本 / role / system 处理
21
+ # ---------------------------------------------------------------------------
22
+
23
+
24
+ def extract_text(content):
25
+ """content: str | [{type,text}] -> str"""
26
+ if isinstance(content, str):
27
+ return content
28
+ parts = []
29
+ for p in content or []:
30
+ if isinstance(p, dict) and p.get("text"):
31
+ parts.append(p["text"])
32
+ return "".join(parts)
33
+
34
+
35
+ def _chat_role(role):
36
+ """responses role -> chat role(developer->system; latest_reminder/未知->user)。
37
+
38
+ kimi-k3 等严格网关对 developer role 报 tokenization failed,必须映射。
39
+ """
40
+ if role in ("system", "developer"):
41
+ return "system"
42
+ if role == "assistant":
43
+ return "assistant"
44
+ if role == "tool":
45
+ return "tool"
46
+ return "user"
47
+
48
+
49
+ def collapse_system(msgs):
50
+ """把所有 system 消息合并到头部一条(cc-switch collapse_system_messages_to_head)。"""
51
+ chunks, rest = [], []
52
+ for m in msgs:
53
+ if m.get("role") == "system" and isinstance(m.get("content"), str) and m["content"].strip():
54
+ chunks.append(m["content"])
55
+ else:
56
+ rest.append(m)
57
+ return ([{"role": "system", "content": "\n\n".join(chunks)}] if chunks else []) + rest
58
+
59
+
60
+ # ---------------------------------------------------------------------------
61
+ # 请求: responses -> chat
62
+ # ---------------------------------------------------------------------------
63
+
64
+ # 除 messages/tools 外原样透传的字段(cc-switch EXTRA_CHAT_PASSTHROUGH_FIELDS 子集)
65
+ _PASSTHROUGH = (
66
+ "temperature",
67
+ "top_p",
68
+ "top_logprobs",
69
+ "logprobs",
70
+ "stop",
71
+ "seed",
72
+ "frequency_penalty",
73
+ "presence_penalty",
74
+ "logit_bias",
75
+ "response_format",
76
+ "user",
77
+ "metadata",
78
+ "n",
79
+ "service_tier",
80
+ )
81
+
82
+
83
+ def input_to_messages(inp):
84
+ """responses 的 input(str | [items]) -> chat messages[]。
85
+
86
+ 处理 message / function_call / function_call_output;reasoning 历史不转发。
87
+ """
88
+ if inp is None:
89
+ return []
90
+ if isinstance(inp, str):
91
+ return [{"role": "user", "content": inp}]
92
+ if isinstance(inp, dict):
93
+ inp = [inp]
94
+ messages = []
95
+ pending_tc = []
96
+
97
+ def flush():
98
+ if pending_tc:
99
+ messages.append({"role": "assistant", "content": None, "tool_calls": list(pending_tc)})
100
+ pending_tc.clear()
101
+
102
+ for item in inp:
103
+ if not isinstance(item, dict):
104
+ continue
105
+ t = item.get("type")
106
+ if t in (None, "message"):
107
+ flush()
108
+ messages.append(
109
+ {
110
+ "role": _chat_role(item.get("role", "user")),
111
+ "content": extract_text(item.get("content")),
112
+ }
113
+ )
114
+ elif t == "function_call":
115
+ pending_tc.append(
116
+ {
117
+ "id": item.get("call_id") or f"call_{len(pending_tc)}",
118
+ "type": "function",
119
+ "function": {
120
+ "name": item.get("name"),
121
+ "arguments": item.get("arguments") or "",
122
+ },
123
+ }
124
+ )
125
+ elif t == "custom_tool_call":
126
+ # 历史里的 custom_tool_call:还原为 function 调用(input 包进 JSON)
127
+ pending_tc.append(
128
+ {
129
+ "id": item.get("call_id") or f"call_{len(pending_tc)}",
130
+ "type": "function",
131
+ "function": {
132
+ "name": item.get("name"),
133
+ "arguments": json.dumps(
134
+ {"input": item.get("input") or ""}, ensure_ascii=False
135
+ ),
136
+ },
137
+ }
138
+ )
139
+ elif t == "custom_tool_call_output":
140
+ flush()
141
+ out = item.get("output")
142
+ messages.append(
143
+ {
144
+ "role": "tool",
145
+ "tool_call_id": item.get("call_id") or "",
146
+ "content": out if isinstance(out, str) else json.dumps(out, ensure_ascii=False),
147
+ }
148
+ )
149
+ elif t == "function_call_output":
150
+ flush()
151
+ out = item.get("output")
152
+ messages.append(
153
+ {
154
+ "role": "tool",
155
+ "tool_call_id": item.get("call_id") or "",
156
+ "content": out if isinstance(out, str) else json.dumps(out, ensure_ascii=False),
157
+ }
158
+ )
159
+ # reasoning / 其他类型: 跳过
160
+ flush()
161
+ return messages
162
+
163
+
164
+ def convert_tools(tools):
165
+ """codex 扁平 function tool -> chat 嵌套 function tool,保留 strict。
166
+
167
+ 遇非 function 工具(namespace/MCP/web_search 等)fail-fast 抛 UnsupportedToolsError,
168
+ 不静默丢弃降级请求(codex 端禁用配置注入前的安全网)。
169
+ """
170
+ out = []
171
+ unsupported = []
172
+ for t in tools or []:
173
+ if isinstance(t, dict) and t.get("type") == "function":
174
+ fn = {
175
+ "name": t.get("name"),
176
+ "description": t.get("description", ""),
177
+ "parameters": t.get("parameters", {"type": "object", "properties": {}}),
178
+ }
179
+ if "strict" in t:
180
+ fn["strict"] = t["strict"]
181
+ out.append({"type": "function", "function": fn})
182
+ elif isinstance(t, dict) and t.get("type") == "custom" and t.get("name"):
183
+ # custom 工具(apply_patch 等 freeform 输入)转为单 input 字符串参数的 function
184
+ out.append(
185
+ {
186
+ "type": "function",
187
+ "function": {
188
+ "name": t.get("name"),
189
+ "description": t.get("description", ""),
190
+ "parameters": {
191
+ "type": "object",
192
+ "properties": {"input": {"type": "string"}},
193
+ "required": ["input"],
194
+ },
195
+ },
196
+ }
197
+ )
198
+ else:
199
+ t = t or {}
200
+ import json as _json
201
+ try:
202
+ unsupported.append(_json.dumps(t, ensure_ascii=False)[:300])
203
+ except Exception:
204
+ unsupported.append(str(t.get("type") or t.get("name") or "unknown"))
205
+ if unsupported:
206
+ raise UnsupportedToolsError(
207
+ f"不支持转换的 codex 工具类型: {unsupported};"
208
+ "请在 codex 端禁用 multi_agent/web_search(v2 优先),或实现 namespace 拍平"
209
+ )
210
+ return out
211
+
212
+
213
+ def convert_tool_choice(tc):
214
+ """responses tool_choice -> chat tool_choice。
215
+
216
+ named 形式 {"type":"function","name":"x"} 必须嵌套为
217
+ {"type":"function","function":{"name":"x"}}(chat 要求 function.name 嵌套)。
218
+ """
219
+ if tc is None or isinstance(tc, str):
220
+ return tc # auto / none / required
221
+ if isinstance(tc, dict) and tc.get("type") == "function":
222
+ name = tc.get("name") or (tc.get("function") or {}).get("name")
223
+ return {"type": "function", "function": {"name": name}}
224
+ return tc
225
+
226
+
227
+ def _convert_text_format(fmt):
228
+ """responses text.format -> chat response_format(structured output 结构重组)。
229
+
230
+ responses: {"type":"json_schema","name":...,"schema":...,"strict":...}
231
+ chat: {"type":"json_schema","json_schema":{"name":...,"schema":...,"strict":...}}
232
+ """
233
+ if not isinstance(fmt, dict):
234
+ return None
235
+ t = fmt.get("type")
236
+ if t == "json_schema":
237
+ js = {"name": fmt.get("name"), "schema": fmt.get("schema")}
238
+ if "strict" in fmt:
239
+ js["strict"] = fmt["strict"]
240
+ return {"type": "json_schema", "json_schema": js}
241
+ if t in ("json_object", "text"):
242
+ return {"type": t}
243
+ return None
244
+
245
+
246
+ def responses_to_chat(body):
247
+ """responses 请求 -> chat 请求;返回 (chat_req, restore_map)。
248
+
249
+ 先拍平 namespace 工具(namespace.py),再用 convert_tools 转 chat 嵌套 function。
250
+ restore_map 供响应侧把 flat function_call 名字还原回 {name, namespace}。
251
+ """
252
+ from .namespace import flatten_request_namespaces
253
+
254
+ restore_map = flatten_request_namespaces(body)
255
+ out = {"model": body.get("model")}
256
+ msgs = []
257
+ if body.get("instructions"):
258
+ msgs.append({"role": "system", "content": extract_text(body["instructions"])})
259
+ msgs += input_to_messages(body.get("input"))
260
+ out["messages"] = collapse_system(msgs)
261
+ if body.get("max_output_tokens") is not None:
262
+ out["max_tokens"] = body["max_output_tokens"]
263
+ for k in _PASSTHROUGH:
264
+ if k in body:
265
+ out[k] = body[k]
266
+ # codex 特有字段(client.rs:862 固定发送):
267
+ # reasoning effort / structured output(在 text.format,非顶层 response_format) / 显式缓存 key
268
+ reasoning = body.get("reasoning")
269
+ if isinstance(reasoning, dict) and reasoning.get("effort"):
270
+ out["reasoning_effort"] = reasoning["effort"]
271
+ text = body.get("text")
272
+ if isinstance(text, dict):
273
+ rf = _convert_text_format(text.get("format"))
274
+ if rf is not None:
275
+ out["response_format"] = rf
276
+ if text.get("verbosity"):
277
+ out["verbosity"] = text["verbosity"]
278
+ if body.get("prompt_cache_key"):
279
+ out["prompt_cache_key"] = body["prompt_cache_key"]
280
+ tools = convert_tools(body.get("tools"))
281
+ if tools:
282
+ out["tools"] = tools
283
+ if "tool_choice" in body:
284
+ out["tool_choice"] = convert_tool_choice(body["tool_choice"])
285
+ if "parallel_tool_calls" in body:
286
+ out["parallel_tool_calls"] = body["parallel_tool_calls"]
287
+ return out, restore_map
288
+
289
+
290
+ # ---------------------------------------------------------------------------
291
+ # 响应(非流式): chat -> responses
292
+ # ---------------------------------------------------------------------------
293
+
294
+
295
+ def convert_usage(u):
296
+ """chat usage -> responses usage;透传前缀缓存命中数(否则 codex 看到 cached 恒 0)。"""
297
+ u = u or {}
298
+ ct = u.get("completion_tokens_details") or {}
299
+ pt = u.get("prompt_tokens_details") or {} # 平台有时返回 None
300
+ return {
301
+ "input_tokens": u.get("prompt_tokens", 0),
302
+ "input_tokens_details": {"cached_tokens": pt.get("cached_tokens", 0)},
303
+ "output_tokens": u.get("completion_tokens", 0),
304
+ "total_tokens": u.get("total_tokens", 0),
305
+ "output_tokens_details": {"reasoning_tokens": ct.get("reasoning_tokens", 0)},
306
+ }
307
+
308
+
309
+ def _status_and_incomplete(finish_reason):
310
+ """finish_reason -> (status, incomplete_reason)。
311
+
312
+ length/content_filter 都不是 completed。
313
+ """
314
+ if finish_reason == "length":
315
+ return "incomplete", "max_output_tokens"
316
+ if finish_reason == "content_filter":
317
+ return "incomplete", "content_filter"
318
+ return "completed", None
319
+
320
+
321
+ def chat_to_response(chat, rid, restore_map=None):
322
+ choice = (chat.get("choices") or [{}])[0]
323
+ msg = choice.get("message") or {}
324
+ output = []
325
+ rc = msg.get("reasoning_content")
326
+ if rc:
327
+ output.append(
328
+ {
329
+ "id": f"rs_{rid}",
330
+ "type": "reasoning",
331
+ "summary": [{"type": "summary_text", "text": rc}],
332
+ }
333
+ )
334
+ if msg.get("content"):
335
+ output.append(
336
+ {
337
+ "id": f"{rid}_msg",
338
+ "type": "message",
339
+ "status": "completed",
340
+ "role": "assistant",
341
+ "content": [{"type": "output_text", "text": msg["content"], "annotations": []}],
342
+ }
343
+ )
344
+ from .namespace import restore_function_call
345
+
346
+ for i, tc in enumerate(msg.get("tool_calls") or []):
347
+ fn = tc.get("function") or {}
348
+ cid = tc.get("id") or f"call_{i}"
349
+ item = restore_function_call(
350
+ {
351
+ "id": f"fc_{cid}",
352
+ "type": "function_call",
353
+ "status": "completed",
354
+ "call_id": cid,
355
+ "name": fn.get("name"),
356
+ "arguments": fn.get("arguments") or "",
357
+ },
358
+ restore_map or {},
359
+ )
360
+ output.append(item)
361
+ status, incomplete = _status_and_incomplete(choice.get("finish_reason"))
362
+ resp = {
363
+ "id": rid,
364
+ "object": "response",
365
+ "created_at": chat.get("created", int(time.time())),
366
+ "status": status,
367
+ "model": chat.get("model"),
368
+ "output": output,
369
+ "usage": convert_usage(chat.get("usage")),
370
+ }
371
+ if incomplete:
372
+ resp["incomplete_details"] = {"reason": incomplete}
373
+ return resp
374
+
375
+
376
+ # ---------------------------------------------------------------------------
377
+ # 流式: chat SSE -> responses SSE(每个 tool call 独立状态,修复并行截断)
378
+ # ---------------------------------------------------------------------------
379
+
380
+
381
+ class Streamer:
382
+ """把 chat completions 流式 chunk 转成 responses SSE 事件。
383
+
384
+ 关键不变量:每个 tool call(按 index)独立维护 open/output_index/arguments,
385
+ **index 切换时不互相关闭**,统一在 finalize 关闭 —— 修复并行 tool call 参数被截断。
386
+ """
387
+
388
+ def __init__(self, rid, model, restore_map=None):
389
+ self.rid = rid
390
+ self.model = model
391
+ self.restore_map = restore_map or {}
392
+ self.created = int(time.time())
393
+ self._next_oi = 0
394
+ self._reasoning = None # {"oi","id","text"}
395
+ self._message = None # {"oi","id","text"}
396
+ self._tool_calls = {} # index -> {"oi","item_id","call_id","name","args"}
397
+ self._completed = [] # [(oi, item)] 完成顺序
398
+ self.usage = None
399
+ self.finish = None
400
+
401
+ # ---- SSE 信封(格式照 codex_responses_sse.rs) ----
402
+ @staticmethod
403
+ def ev(event, data):
404
+ return f"event: {event}\ndata: {json.dumps(data, ensure_ascii=False)}\n\n"
405
+
406
+ def _resp(self, status, output=None, usage=None):
407
+ r = {
408
+ "id": self.rid,
409
+ "object": "response",
410
+ "created_at": self.created,
411
+ "status": status,
412
+ "model": self.model,
413
+ "output": output or [],
414
+ }
415
+ if usage is not None:
416
+ r["usage"] = usage
417
+ return r
418
+
419
+ def _alloc_oi(self):
420
+ oi = self._next_oi
421
+ self._next_oi += 1
422
+ return oi
423
+
424
+ def start(self):
425
+ return [
426
+ self.ev(
427
+ "response.created",
428
+ {"type": "response.created", "response": self._resp("in_progress")},
429
+ ),
430
+ self.ev(
431
+ "response.in_progress",
432
+ {"type": "response.in_progress", "response": self._resp("in_progress")},
433
+ ),
434
+ ]
435
+
436
+ # ---- reasoning ----
437
+ def _open_reasoning(self):
438
+ oi = self._alloc_oi()
439
+ rid = f"rs_{self.rid}"
440
+ self._reasoning = {"oi": oi, "id": rid, "text": ""}
441
+ return [
442
+ self.ev(
443
+ "response.output_item.added",
444
+ {
445
+ "type": "response.output_item.added",
446
+ "output_index": oi,
447
+ "item": {
448
+ "id": rid,
449
+ "type": "reasoning",
450
+ "status": "in_progress",
451
+ "summary": [],
452
+ },
453
+ },
454
+ ),
455
+ self.ev(
456
+ "response.reasoning_summary_part.added",
457
+ {
458
+ "type": "response.reasoning_summary_part.added",
459
+ "item_id": rid,
460
+ "output_index": oi,
461
+ "summary_index": 0,
462
+ "part": {"type": "summary_text", "text": ""},
463
+ },
464
+ ),
465
+ ]
466
+
467
+ def _close_reasoning(self):
468
+ r = self._reasoning
469
+ self._reasoning = None
470
+ item = {
471
+ "id": r["id"],
472
+ "type": "reasoning",
473
+ "summary": [{"type": "summary_text", "text": r["text"]}],
474
+ }
475
+ self._completed.append((r["oi"], item))
476
+ return [
477
+ self.ev(
478
+ "response.reasoning_summary_text.done",
479
+ {
480
+ "type": "response.reasoning_summary_text.done",
481
+ "item_id": r["id"],
482
+ "output_index": r["oi"],
483
+ "summary_index": 0,
484
+ "text": r["text"],
485
+ },
486
+ ),
487
+ self.ev(
488
+ "response.reasoning_summary_part.done",
489
+ {
490
+ "type": "response.reasoning_summary_part.done",
491
+ "item_id": r["id"],
492
+ "output_index": r["oi"],
493
+ "summary_index": 0,
494
+ "part": {"type": "summary_text", "text": r["text"]},
495
+ },
496
+ ),
497
+ self.ev(
498
+ "response.output_item.done",
499
+ {"type": "response.output_item.done", "output_index": r["oi"], "item": item},
500
+ ),
501
+ ]
502
+
503
+ # ---- message ----
504
+ def _open_message(self):
505
+ oi = self._alloc_oi()
506
+ mid = f"{self.rid}_msg"
507
+ self._message = {"oi": oi, "id": mid, "text": ""}
508
+ return [
509
+ self.ev(
510
+ "response.output_item.added",
511
+ {
512
+ "type": "response.output_item.added",
513
+ "output_index": oi,
514
+ "item": {
515
+ "id": mid,
516
+ "type": "message",
517
+ "status": "in_progress",
518
+ "role": "assistant",
519
+ "content": [],
520
+ },
521
+ },
522
+ ),
523
+ self.ev(
524
+ "response.content_part.added",
525
+ {
526
+ "type": "response.content_part.added",
527
+ "item_id": mid,
528
+ "output_index": oi,
529
+ "content_index": 0,
530
+ "part": {"type": "output_text", "text": "", "annotations": []},
531
+ },
532
+ ),
533
+ ]
534
+
535
+ def _close_message(self):
536
+ m = self._message
537
+ self._message = None
538
+ item = {
539
+ "id": m["id"],
540
+ "type": "message",
541
+ "status": "completed",
542
+ "role": "assistant",
543
+ "content": [{"type": "output_text", "text": m["text"], "annotations": []}],
544
+ }
545
+ self._completed.append((m["oi"], item))
546
+ return [
547
+ self.ev(
548
+ "response.output_text.done",
549
+ {
550
+ "type": "response.output_text.done",
551
+ "item_id": m["id"],
552
+ "output_index": m["oi"],
553
+ "content_index": 0,
554
+ "text": m["text"],
555
+ },
556
+ ),
557
+ self.ev(
558
+ "response.content_part.done",
559
+ {
560
+ "type": "response.content_part.done",
561
+ "item_id": m["id"],
562
+ "output_index": m["oi"],
563
+ "content_index": 0,
564
+ "part": {"type": "output_text", "text": m["text"], "annotations": []},
565
+ },
566
+ ),
567
+ self.ev(
568
+ "response.output_item.done",
569
+ {"type": "response.output_item.done", "output_index": m["oi"], "item": item},
570
+ ),
571
+ ]
572
+
573
+ # ---- function_call(每个 index 独立) ----
574
+ def _open_tool_call(self, idx, call_id, name):
575
+ oi = self._alloc_oi()
576
+ item_id = f"fc_{call_id}"
577
+ self._tool_calls[idx] = {
578
+ "oi": oi,
579
+ "item_id": item_id,
580
+ "call_id": call_id,
581
+ "name": name,
582
+ "args": "",
583
+ }
584
+ return [
585
+ self.ev(
586
+ "response.output_item.added",
587
+ {
588
+ "type": "response.output_item.added",
589
+ "output_index": oi,
590
+ "item": {
591
+ "id": item_id,
592
+ "type": "function_call",
593
+ "status": "in_progress",
594
+ "call_id": call_id,
595
+ "name": name,
596
+ "arguments": "",
597
+ },
598
+ },
599
+ )
600
+ ]
601
+
602
+ def _close_tool_call(self, idx):
603
+ from .namespace import restore_function_call
604
+
605
+ tc = self._tool_calls.pop(idx)
606
+ item = restore_function_call(
607
+ {
608
+ "id": tc["item_id"],
609
+ "type": "function_call",
610
+ "status": "completed",
611
+ "call_id": tc["call_id"],
612
+ "name": tc["name"],
613
+ "arguments": tc["args"],
614
+ },
615
+ self.restore_map,
616
+ )
617
+ self._completed.append((tc["oi"], item))
618
+ return [
619
+ self.ev(
620
+ "response.function_call_arguments.done",
621
+ {
622
+ "type": "response.function_call_arguments.done",
623
+ "item_id": tc["item_id"],
624
+ "output_index": tc["oi"],
625
+ "arguments": tc["args"],
626
+ },
627
+ ),
628
+ self.ev(
629
+ "response.output_item.done",
630
+ {"type": "response.output_item.done", "output_index": tc["oi"], "item": item},
631
+ ),
632
+ ]
633
+
634
+ def handle(self, chunk):
635
+ evts = []
636
+ if chunk.get("usage"):
637
+ self.usage = chunk["usage"]
638
+ for choice in chunk.get("choices") or []:
639
+ delta = choice.get("delta") or {}
640
+
641
+ rt = delta.get("reasoning_content") or delta.get("reasoning")
642
+ if rt:
643
+ if self._reasoning is None:
644
+ evts += self._open_reasoning()
645
+ self._reasoning["text"] += rt
646
+ evts.append(
647
+ self.ev(
648
+ "response.reasoning_summary_text.delta",
649
+ {
650
+ "type": "response.reasoning_summary_text.delta",
651
+ "item_id": self._reasoning["id"],
652
+ "output_index": self._reasoning["oi"],
653
+ "summary_index": 0,
654
+ "delta": rt,
655
+ },
656
+ )
657
+ )
658
+
659
+ ct = delta.get("content")
660
+ if ct:
661
+ if self._reasoning is not None:
662
+ evts += self._close_reasoning()
663
+ if self._message is None:
664
+ evts += self._open_message()
665
+ self._message["text"] += ct
666
+ evts.append(
667
+ self.ev(
668
+ "response.output_text.delta",
669
+ {
670
+ "type": "response.output_text.delta",
671
+ "item_id": self._message["id"],
672
+ "output_index": self._message["oi"],
673
+ "content_index": 0,
674
+ "delta": ct,
675
+ },
676
+ )
677
+ )
678
+
679
+ tcs = delta.get("tool_calls")
680
+ if tcs:
681
+ # 进入工具调用阶段:reasoning/message 与 tool call 不并行,先关掉
682
+ if self._reasoning is not None:
683
+ evts += self._close_reasoning()
684
+ if self._message is not None:
685
+ evts += self._close_message()
686
+ for tc in tcs:
687
+ idx = tc.get("index", 0)
688
+ fn = tc.get("function") or {}
689
+ if idx not in self._tool_calls:
690
+ evts += self._open_tool_call(
691
+ idx, tc.get("id") or f"call_{idx}", fn.get("name") or ""
692
+ )
693
+ elif fn.get("name") and not self._tool_calls[idx]["name"]:
694
+ self._tool_calls[idx]["name"] = fn["name"]
695
+ if fn.get("arguments"):
696
+ self._tool_calls[idx]["args"] += fn["arguments"]
697
+ evts.append(
698
+ self.ev(
699
+ "response.function_call_arguments.delta",
700
+ {
701
+ "type": "response.function_call_arguments.delta",
702
+ "item_id": self._tool_calls[idx]["item_id"],
703
+ "output_index": self._tool_calls[idx]["oi"],
704
+ "delta": fn["arguments"],
705
+ },
706
+ )
707
+ )
708
+
709
+ if choice.get("finish_reason"):
710
+ self.finish = choice["finish_reason"]
711
+ return evts
712
+
713
+ def finalize(self):
714
+ evts = []
715
+ if self._reasoning is not None:
716
+ evts += self._close_reasoning()
717
+ if self._message is not None:
718
+ evts += self._close_message()
719
+ for idx in sorted(self._tool_calls):
720
+ evts += self._close_tool_call(idx)
721
+ items = [item for _, item in sorted(self._completed, key=lambda x: x[0])]
722
+ if self.finish is None:
723
+ # 断流:无合法 incomplete reason(官方仅 max_output_tokens/content_filter),发 failed
724
+ resp = self._resp("failed", output=items, usage=convert_usage(self.usage))
725
+ resp["error"] = {"message": "上游流中断(未收到 finish_reason)"}
726
+ evts.append(self.ev("response.failed", {"type": "response.failed", "response": resp}))
727
+ return evts
728
+ status, incomplete = _status_and_incomplete(self.finish)
729
+ resp = self._resp(status, output=items, usage=convert_usage(self.usage))
730
+ if incomplete:
731
+ resp["incomplete_details"] = {"reason": incomplete}
732
+ # codex 仅在收到 response.incomplete 时才报错;incomplete 不能误发 completed
733
+ event = "response.completed" if status == "completed" else "response.incomplete"
734
+ evts.append(self.ev(event, {"type": event, "response": resp}))
735
+ return evts