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
ksadk/api/client.py CHANGED
@@ -4,22 +4,23 @@ AgentEngine Server API 客户端
4
4
  支持 AWS V4 签名认证,用于通过 KOP 网关访问 AgentEngine Server。
5
5
  """
6
6
 
7
- import os
8
- import re
9
7
  import json
10
- import uuid
11
- import socket
12
8
  import logging
13
9
  import mimetypes
10
+ import os
11
+ import re
12
+ import socket
13
+ import uuid
14
14
  from contextlib import contextmanager
15
15
  from dataclasses import dataclass
16
16
  from pathlib import Path
17
- from typing import Optional, Dict, Any, Sequence, Callable, Iterator
17
+ from typing import Any, Callable, Dict, Iterator, Optional, Sequence
18
18
  from urllib.parse import quote, unquote, urlparse, urlsplit
19
19
 
20
20
  import requests
21
21
  import urllib3
22
22
 
23
+ from ksadk.api.environment import environment_variables_payload
23
24
  from ksadk.common.auth import AWSV4Auth
24
25
 
25
26
  logger = logging.getLogger(__name__)
@@ -38,7 +39,9 @@ class AttachmentContent:
38
39
  class DryRunExit(Exception):
39
40
  """DryRun 模式退出异常。"""
40
41
 
41
- def __init__(self, message: str = "Dry Run finished.", *, payload: Optional[Dict[str, Any]] = None):
42
+ def __init__(
43
+ self, message: str = "Dry Run finished.", *, payload: Optional[Dict[str, Any]] = None
44
+ ):
42
45
  self.payload = payload or {}
43
46
  super().__init__(message)
44
47
 
@@ -54,6 +57,7 @@ class AgentEngineAPIError(Exception):
54
57
  details: Optional[Dict[str, Any]] = None,
55
58
  ):
56
59
  self.raw_code = code
60
+ self.code: Optional[int]
57
61
  try:
58
62
  self.code = int(code)
59
63
  except (TypeError, ValueError):
@@ -69,9 +73,9 @@ class AgentEngineAPIError(Exception):
69
73
 
70
74
  class AgentEngineClient:
71
75
  """AgentEngine Server API 客户端
72
-
76
+
73
77
  使用 AWS V4 签名认证访问 KOP 网关后的 AgentEngine Server。
74
-
78
+
75
79
  凭证来源 (优先级从高到低):
76
80
  1. 构造函数参数
77
81
  2. 环境变量 KSYUN_ACCESS_KEY / KSYUN_SECRET_KEY
@@ -85,8 +89,8 @@ class AgentEngineClient:
85
89
  _permission_probe_cache: dict[tuple[str, str, str], bool] = {}
86
90
 
87
91
  def __init__(
88
- self,
89
- base_url: Optional[str] = None,
92
+ self,
93
+ base_url: Optional[str] = None,
90
94
  access_key: Optional[str] = None,
91
95
  secret_key: Optional[str] = None,
92
96
  region: str = "cn-beijing-6",
@@ -95,13 +99,9 @@ class AgentEngineClient:
95
99
  dry_run: bool = False,
96
100
  extra_headers: Optional[Dict[str, str]] = None,
97
101
  ):
98
- self.base_url = (
99
- base_url
100
- or os.getenv("AGENTENGINE_SERVER_URL")
101
- )
102
- if not self.base_url:
103
- self.base_url = self._detect_default_base_url()
104
-
102
+ resolved_base_url = base_url or os.getenv("AGENTENGINE_SERVER_URL")
103
+ self.base_url: str = resolved_base_url or self._detect_default_base_url()
104
+
105
105
  # 本地调试覆盖 (如果需要)
106
106
  # self.base_url = "http://localhost:8081"
107
107
  self.timeout = timeout
@@ -111,8 +111,8 @@ class AgentEngineClient:
111
111
  self.dry_run = bool(dry_run or self._is_global_dry_run_enabled())
112
112
  self.extra_headers = extra_headers or {}
113
113
  # 签名 service 可通过环境变量覆盖(例如 aicp)
114
- self.service = service or os.getenv("AGENTENGINE_SIGN_SERVICE", "aicp")
115
-
114
+ self.service: str = service or os.getenv("AGENTENGINE_SIGN_SERVICE") or "aicp"
115
+
116
116
  # AWS V4 签名
117
117
  self._auth = AWSV4Auth(
118
118
  access_key_id=access_key or "",
@@ -120,12 +120,12 @@ class AgentEngineClient:
120
120
  region=self.region,
121
121
  service=self.service,
122
122
  )
123
-
123
+
124
124
  if self._auth.is_enabled:
125
125
  logger.debug(f"AgentEngineClient initialized with V4Auth: {self.base_url}")
126
126
  else:
127
127
  logger.debug("AgentEngineClient: No credentials, signing disabled")
128
-
128
+
129
129
  self._session: Optional[requests.Session] = None
130
130
  self._http_error_log_suppressors: list[HttpErrorLogSuppressor] = []
131
131
  # 反查身份的实例缓存(避免同会话重复调 IAM);None=未尝试,ResolvedIdentity|None=已反查
@@ -135,10 +135,10 @@ class AgentEngineClient:
135
135
  @staticmethod
136
136
  def _ssl_verify_enabled() -> bool:
137
137
  insecure = (
138
- os.getenv("AGENTENGINE_SSL_INSECURE")
139
- or os.getenv("CURL_SSL_INSECURE")
140
- or ""
141
- ).strip().lower()
138
+ (os.getenv("AGENTENGINE_SSL_INSECURE") or os.getenv("CURL_SSL_INSECURE") or "")
139
+ .strip()
140
+ .lower()
141
+ )
142
142
  if insecure in {"1", "true", "yes", "on"}:
143
143
  urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
144
144
  return False
@@ -303,7 +303,9 @@ class AgentEngineClient:
303
303
  @staticmethod
304
304
  def _is_auth_related_error_details(details: Dict[str, Any]) -> bool:
305
305
  remote_code = str(details.get("remote_error_code") or "").strip().lower()
306
- remote_message = str(details.get("remote_error_message") or details.get("message") or "").strip().lower()
306
+ remote_message = (
307
+ str(details.get("remote_error_message") or details.get("message") or "").strip().lower()
308
+ )
307
309
  if remote_code in {
308
310
  "missingaccesskey",
309
311
  "missingsecretkey",
@@ -336,7 +338,9 @@ class AgentEngineClient:
336
338
  @staticmethod
337
339
  def _is_inner_account_intranet_error(details: Dict[str, Any]) -> bool:
338
340
  remote_code = str(details.get("remote_error_code") or "").strip().lower()
339
- remote_message = str(details.get("remote_error_message") or details.get("message") or "").strip().lower()
341
+ remote_message = (
342
+ str(details.get("remote_error_message") or details.get("message") or "").strip().lower()
343
+ )
340
344
  return (
341
345
  remote_code == "inneraccountcanonlyaccessthroughintranet"
342
346
  or "inner account can only access through intranet" in remote_message
@@ -356,7 +360,9 @@ class AgentEngineClient:
356
360
  )
357
361
  self.base_url = self._INNER_AICP_BASE_URL
358
362
 
359
- def _build_action_request_target(self, path: str, action: str) -> tuple[bool, Dict[str, str], str]:
363
+ def _build_action_request_target(
364
+ self, path: str, action: str
365
+ ) -> tuple[bool, Dict[str, str], str]:
360
366
  kop_mode = self._is_kop_mode()
361
367
  headers = self._build_headers(action=action, kop_mode=kop_mode)
362
368
  if kop_mode:
@@ -366,14 +372,17 @@ class AgentEngineClient:
366
372
  full_url = f"{self.base_url}{path}"
367
373
  return kop_mode, headers, full_url
368
374
 
369
- def _build_raw_action_request_target(self, action: str, accept: str, has_files: bool) -> tuple[bool, Dict[str, str], str]:
375
+ def _build_raw_action_request_target(
376
+ self, action: str, accept: str, has_files: bool
377
+ ) -> tuple[bool, Dict[str, str], str]:
370
378
  kop_mode = self._is_kop_mode()
371
379
  headers = self._build_headers(action=action, kop_mode=kop_mode)
372
380
  headers["Accept"] = accept
373
381
  if has_files:
374
382
  headers.pop("Content-Type", None)
383
+ version = os.getenv("AGENTENGINE_API_VERSION", "2024-06-12")
375
384
  full_url = (
376
- f"{self.base_url.rstrip('/')}/?Action={action}&Version={os.getenv('AGENTENGINE_API_VERSION', '2024-06-12')}"
385
+ f"{self.base_url.rstrip('/')}/?Action={action}&Version={version}"
377
386
  if kop_mode
378
387
  else f"{self.base_url}/agentengine/api/v1/{action}"
379
388
  )
@@ -394,7 +403,9 @@ class AgentEngineClient:
394
403
  if self._http_error_log_suppressors:
395
404
  self._http_error_log_suppressors.pop()
396
405
 
397
- def _log_http_error(self, *, method: str, full_url: str, status_code: int, details: Dict[str, Any]) -> None:
406
+ def _log_http_error(
407
+ self, *, method: str, full_url: str, status_code: int, details: Dict[str, Any]
408
+ ) -> None:
398
409
  for suppressor in reversed(self._http_error_log_suppressors):
399
410
  try:
400
411
  if suppressor(
@@ -433,7 +444,9 @@ class AgentEngineClient:
433
444
  message = " ".join(message.split())[:200]
434
445
  return f"{code}: {message}" if code else message
435
446
 
436
- def _build_headers(self, request_id: str = "", action: str = "", kop_mode: bool = False) -> Dict[str, str]:
447
+ def _build_headers(
448
+ self, request_id: str = "", action: str = "", kop_mode: bool = False
449
+ ) -> Dict[str, str]:
437
450
  if not request_id:
438
451
  request_id = str(uuid.uuid4())
439
452
  headers = {
@@ -508,9 +521,7 @@ class AgentEngineClient:
508
521
  # dry-run 不联网,只读缓存
509
522
  self._resolved_identity = get_cached_identity(ak)
510
523
  else:
511
- self._resolved_identity = resolve_identity(
512
- access_key=ak, secret_key=sk
513
- )
524
+ self._resolved_identity = resolve_identity(access_key=ak, secret_key=sk)
514
525
  except Exception as e:
515
526
  logger.warning("反查子账号身份失败: %s", e)
516
527
  self._resolved_identity = None
@@ -536,9 +547,7 @@ class AgentEngineClient:
536
547
  access = params.get("Access") if isinstance(params, dict) else None
537
548
  if isinstance(access, dict):
538
549
  explicit_role = (
539
- access.get("IamRole")
540
- or access.get("iamRole")
541
- or access.get("iam_role")
550
+ access.get("IamRole") or access.get("iamRole") or access.get("iam_role")
542
551
  )
543
552
  if str(explicit_role or "").strip():
544
553
  return str(explicit_role).strip()
@@ -597,9 +606,9 @@ class AgentEngineClient:
597
606
  self._permission_probe_cache[cache_key] = True
598
607
 
599
608
  def _request(
600
- self,
609
+ self,
601
610
  method: str,
602
- path: str,
611
+ path: str,
603
612
  body: Optional[Dict[str, Any]] = None,
604
613
  *,
605
614
  ignore_dry_run: bool = False,
@@ -608,7 +617,7 @@ class AgentEngineClient:
608
617
  action = path.rstrip("/").split("/")[-1] if path else ""
609
618
  _kop_mode, headers, full_url = self._build_action_request_target(path, action)
610
619
  body_str = json.dumps(body, ensure_ascii=False) if body else ""
611
-
620
+
612
621
  # DryRun 模式
613
622
  if self.dry_run and not ignore_dry_run:
614
623
  signed_headers = headers
@@ -622,9 +631,9 @@ class AgentEngineClient:
622
631
  )
623
632
 
624
633
  # 生成 Curl 命令
625
- curl_cmd = f"curl -X {method} \"{full_url}\" \\\n"
634
+ curl_cmd = f'curl -X {method} "{full_url}" \\\n'
626
635
  for k, v in signed_headers.items():
627
- curl_cmd += f" -H \"{k}: {v}\" \\\n"
636
+ curl_cmd += f' -H "{k}: {v}" \\\n'
628
637
  if body_str:
629
638
  curl_cmd += f" -d '{body_str}'"
630
639
 
@@ -639,7 +648,7 @@ class AgentEngineClient:
639
648
  "curl": curl_cmd,
640
649
  },
641
650
  )
642
-
651
+
643
652
  session = self._get_session()
644
653
 
645
654
  retried_inner_endpoint = False
@@ -685,31 +694,36 @@ class AgentEngineClient:
685
694
 
686
695
  if response.text:
687
696
  try:
688
- return response.json()
697
+ payload = response.json()
689
698
  except Exception as e:
690
699
  raise Exception(f"Invalid JSON response from {full_url}: {response.text}") from e
700
+ if not isinstance(payload, dict):
701
+ raise Exception(f"Invalid JSON response from {full_url}: expected an object")
702
+ return payload
691
703
  return {}
692
-
704
+
693
705
  # Async 包装 (保持兼容性)
694
706
  async def close(self):
695
707
  if self._session:
696
708
  self._session.close()
697
709
  self._session = None
698
-
710
+
699
711
  async def __aenter__(self):
700
712
  return self
701
-
713
+
702
714
  async def __aexit__(self, exc_type, exc_val, exc_tb):
703
715
  await self.close()
704
716
 
705
717
  # ===== Action API (推荐使用) =====
706
-
718
+
707
719
  @staticmethod
708
720
  def _pascal_key(key: str) -> str:
709
721
  """PascalCase/camelCase 键名转 snake_case"""
710
722
  # "MCPs" -> "mcps", "AgentId" -> "agent_id", "QuickAccess" -> "quick_access"
711
- s1 = re.sub('([A-Z]+)([A-Z][a-z])', r'\1_\2', key)
712
- s2 = re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1)
723
+ if re.fullmatch(r"[A-Z]+s", key):
724
+ return key.lower()
725
+ s1 = re.sub("([A-Z]+)([A-Z][a-z])", r"\1_\2", key)
726
+ s2 = re.sub("([a-z0-9])([A-Z])", r"\1_\2", s1)
713
727
  return s2.lower()
714
728
 
715
729
  @classmethod
@@ -747,7 +761,7 @@ class AgentEngineClient:
747
761
  image = raw
748
762
  for prefix in ("http://", "https://"):
749
763
  if image.startswith(prefix):
750
- image = image[len(prefix):]
764
+ image = image[len(prefix) :]
751
765
  break
752
766
 
753
767
  image_no_tag = image
@@ -798,9 +812,8 @@ class AgentEngineClient:
798
812
  img_ns, img_repo, img_ver = cls._parse_container_image_ref(artifact)
799
813
 
800
814
  inferred_enterprise_instance = cls._enterprise_instance_from_image_ref(artifact)
801
- image_type = (
802
- container.get("image_type")
803
- or ("Enterprise" if inferred_enterprise_instance else "Personal")
815
+ image_type = container.get("image_type") or (
816
+ "Enterprise" if inferred_enterprise_instance else "Personal"
804
817
  )
805
818
  params: Dict[str, Any] = {
806
819
  "ImageType": image_type,
@@ -860,14 +873,13 @@ class AgentEngineClient:
860
873
  if not isinstance(detail, dict):
861
874
  return {}
862
875
 
863
- basic = detail.get("basic") if isinstance(detail.get("basic"), dict) else {}
864
- quick = detail.get("quick_access") if isinstance(detail.get("quick_access"), dict) else {}
865
- deployment = detail.get("deployment") if isinstance(detail.get("deployment"), dict) else {}
866
- framework = (
867
- deployment.get("framework")
868
- or basic.get("framework")
869
- or detail.get("framework")
870
- )
876
+ basic_value = detail.get("basic")
877
+ quick_value = detail.get("quick_access")
878
+ deployment_value = detail.get("deployment")
879
+ basic: Dict[str, Any] = basic_value if isinstance(basic_value, dict) else {}
880
+ quick: Dict[str, Any] = quick_value if isinstance(quick_value, dict) else {}
881
+ deployment: Dict[str, Any] = deployment_value if isinstance(deployment_value, dict) else {}
882
+ framework = deployment.get("framework") or basic.get("framework") or detail.get("framework")
871
883
  return {
872
884
  "agent_id": basic.get("agent_id") or detail.get("agent_id"),
873
885
  "name": basic.get("name") or detail.get("name"),
@@ -896,18 +908,13 @@ class AgentEngineClient:
896
908
  payload = None
897
909
  if isinstance(payload, dict):
898
910
  message = (
899
- str(payload.get("detail") or payload.get("Message") or message).strip()
900
- or message
911
+ str(payload.get("detail") or payload.get("Message") or message).strip() or message
901
912
  )
902
913
  return AgentEngineAPIError(response.status_code, message)
903
914
 
904
915
  @staticmethod
905
916
  def _compact_params(params: Dict[str, Any] | None) -> Dict[str, Any]:
906
- return {
907
- key: value
908
- for key, value in (params or {}).items()
909
- if value is not None
910
- }
917
+ return {key: value for key, value in (params or {}).items() if value is not None}
911
918
 
912
919
  @staticmethod
913
920
  def _workspace_prefers_action_proxy(detail: Dict[str, Any] | None) -> bool:
@@ -938,13 +945,15 @@ class AgentEngineClient:
938
945
  },
939
946
  }
940
947
 
941
- detail = await self.get_agent(agent_id=agent_id, name=name, include_api_key=True)
948
+ detail = await self.get_agent(
949
+ agent_id=agent_id,
950
+ name=name,
951
+ include_api_key=True,
952
+ )
942
953
  access = self._extract_runtime_access(detail)
943
954
  resolved_agent_id = str(access.get("agent_id") or agent_id or "").strip() or None
944
955
  resolved_name = str(access.get("name") or name or "").strip() or None
945
- resolved_api_key = api_key_value or (
946
- str(access.get("api_key") or "").strip() or None
947
- )
956
+ resolved_api_key = api_key_value or (str(access.get("api_key") or "").strip() or None)
948
957
  if self._workspace_prefers_action_proxy(detail):
949
958
  return {
950
959
  "mode": "action",
@@ -1039,8 +1048,13 @@ class AgentEngineClient:
1039
1048
  api_key=api_key,
1040
1049
  )
1041
1050
  if transport["mode"] != "runtime":
1042
- raise AgentEngineAPIError(400, "Workspace runtime direct access is unavailable for this agent")
1043
- return transport["access"]
1051
+ raise AgentEngineAPIError(
1052
+ 400, "Workspace runtime direct access is unavailable for this agent"
1053
+ )
1054
+ access = transport.get("access")
1055
+ if not isinstance(access, dict):
1056
+ raise AgentEngineAPIError(502, "Workspace runtime access payload is invalid")
1057
+ return access
1044
1058
 
1045
1059
  def _workspace_runtime_request(
1046
1060
  self,
@@ -1075,8 +1089,7 @@ class AgentEngineClient:
1075
1089
  payload = response.json()
1076
1090
  except Exception as exc:
1077
1091
  url = str(
1078
- getattr(response, "_ksadk_workspace_url", "")
1079
- or getattr(response, "url", "")
1092
+ getattr(response, "_ksadk_workspace_url", "") or getattr(response, "url", "")
1080
1093
  ).strip()
1081
1094
  body = (response.text or "").strip()
1082
1095
  body_preview = body[:200] if body else "<empty response body>"
@@ -1093,10 +1106,15 @@ class AgentEngineClient:
1093
1106
  "workspace_runtime_body_preview": body_preview,
1094
1107
  },
1095
1108
  ) from exc
1096
- return self._to_snake_case(payload)
1109
+ normalized = self._to_snake_case(payload)
1110
+ if not isinstance(normalized, dict):
1111
+ raise AgentEngineAPIError(502, "workspace runtime returned a non-object JSON payload")
1112
+ return normalized
1097
1113
 
1098
1114
  @staticmethod
1099
- def _annotate_workspace_payload(payload: Dict[str, Any], *, transport_mode: str) -> Dict[str, Any]:
1115
+ def _annotate_workspace_payload(
1116
+ payload: Dict[str, Any], *, transport_mode: str
1117
+ ) -> Dict[str, Any]:
1100
1118
  annotated = dict(payload or {})
1101
1119
  annotated["transport_mode"] = transport_mode
1102
1120
  return annotated
@@ -1117,7 +1135,7 @@ class AgentEngineClient:
1117
1135
  def _action(
1118
1136
  self,
1119
1137
  action: str,
1120
- params: Dict[str, Any] = None,
1138
+ params: Optional[Dict[str, Any]] = None,
1121
1139
  *,
1122
1140
  ignore_dry_run: bool = False,
1123
1141
  ) -> Dict[str, Any]:
@@ -1126,24 +1144,31 @@ class AgentEngineClient:
1126
1144
  self._maybe_precheck_permission(action, body)
1127
1145
  request_kwargs = {"ignore_dry_run": True} if ignore_dry_run else {}
1128
1146
  result = self._request("POST", f"/agentengine/api/v1/{action}", body, **request_kwargs)
1129
-
1147
+
1130
1148
  # 检查错误 (统一返回格式 {"Code": 0, ...})
1131
1149
  code = result.get("Code", 0)
1132
1150
  if code != 0:
1133
1151
  msg = result.get("Message", "Unknown API error")
1134
- raise AgentEngineAPIError(code=code, message=msg)
1135
-
1152
+ details = {}
1153
+ if result.get("RequestId"):
1154
+ details["request_id"] = str(result["RequestId"])
1155
+ if result.get("Action"):
1156
+ details["action"] = str(result["Action"])
1157
+ raise AgentEngineAPIError(code=code, message=msg, details=details)
1158
+
1136
1159
  if result.get("Error"):
1137
1160
  raise Exception(result["Error"].get("Message", "Unknown error"))
1138
-
1161
+
1139
1162
  # 提取 Data 并统一转换为 snake_case
1140
1163
  data = result.get("Data") if result.get("Data") is not None else result
1141
1164
  data = self._to_snake_case(data)
1142
-
1165
+
1143
1166
  # 预发环境 endpoint 协议归一化: https -> http
1144
1167
  if self.logical_region and self.logical_region.strip().lower() == "pre-online":
1145
1168
  data = self._fix_endpoints_protocol(data)
1146
-
1169
+
1170
+ if not isinstance(data, dict):
1171
+ raise AgentEngineAPIError(502, "Action API returned a non-object payload")
1147
1172
  return data
1148
1173
 
1149
1174
  def download_attachment_content(self, file_uri: str) -> AttachmentContent:
@@ -1182,7 +1207,12 @@ class AgentEngineClient:
1182
1207
 
1183
1208
  payload: Dict[str, Any] = {
1184
1209
  "EnablePublicAccess": bool(
1185
- _pick("enable_public_access", "enablePublicAccess", "EnablePublicAccess", default=False)
1210
+ _pick(
1211
+ "enable_public_access",
1212
+ "enablePublicAccess",
1213
+ "EnablePublicAccess",
1214
+ default=False,
1215
+ )
1186
1216
  ),
1187
1217
  "EnableVpcAccess": bool(
1188
1218
  _pick("enable_vpc_access", "enableVpcAccess", "EnableVpcAccess", default=False)
@@ -1203,7 +1233,9 @@ class AgentEngineClient:
1203
1233
  return payload
1204
1234
 
1205
1235
  @staticmethod
1206
- def _normalize_ui_config_payload(ui_config: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
1236
+ def _normalize_ui_config_payload(
1237
+ ui_config: Optional[Dict[str, Any]],
1238
+ ) -> Optional[Dict[str, Any]]:
1207
1239
  if not isinstance(ui_config, dict):
1208
1240
  return None
1209
1241
 
@@ -1234,10 +1266,7 @@ class AgentEngineClient:
1234
1266
  return None
1235
1267
 
1236
1268
  mount_path = str(
1237
- storage.get("mount_path")
1238
- or storage.get("mountPath")
1239
- or storage.get("MountPath")
1240
- or ""
1269
+ storage.get("mount_path") or storage.get("mountPath") or storage.get("MountPath") or ""
1241
1270
  ).strip()
1242
1271
  size_gi = storage.get("size_gi", storage.get("sizeGi", storage.get("SizeGi")))
1243
1272
  if not mount_path and size_gi is None:
@@ -1251,14 +1280,14 @@ class AgentEngineClient:
1251
1280
  return payload
1252
1281
 
1253
1282
  @staticmethod
1254
- def _normalize_memory_config_payload(memory_config: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
1283
+ def _normalize_memory_config_payload(
1284
+ memory_config: Optional[Dict[str, Any]],
1285
+ ) -> Optional[Dict[str, Any]]:
1255
1286
  if not isinstance(memory_config, dict):
1256
1287
  return None
1257
1288
 
1258
1289
  memory_system = str(
1259
- memory_config.get("memory_system")
1260
- or memory_config.get("MemorySystem")
1261
- or ""
1290
+ memory_config.get("memory_system") or memory_config.get("MemorySystem") or ""
1262
1291
  ).strip()
1263
1292
  if not memory_system:
1264
1293
  return None
@@ -1268,17 +1297,12 @@ class AgentEngineClient:
1268
1297
  }
1269
1298
  field_mapping = {
1270
1299
  "Mem0InstanceId": (
1271
- memory_config.get("mem0_instance_id")
1272
- or memory_config.get("Mem0InstanceId")
1300
+ memory_config.get("mem0_instance_id") or memory_config.get("Mem0InstanceId")
1273
1301
  ),
1274
1302
  "Mem0InstanceName": (
1275
- memory_config.get("mem0_instance_name")
1276
- or memory_config.get("Mem0InstanceName")
1277
- ),
1278
- "Mem0Region": (
1279
- memory_config.get("mem0_region")
1280
- or memory_config.get("Mem0Region")
1303
+ memory_config.get("mem0_instance_name") or memory_config.get("Mem0InstanceName")
1281
1304
  ),
1305
+ "Mem0Region": (memory_config.get("mem0_region") or memory_config.get("Mem0Region")),
1282
1306
  }
1283
1307
  for key, value in field_mapping.items():
1284
1308
  text = str(value or "").strip()
@@ -1297,7 +1321,9 @@ class AgentEngineClient:
1297
1321
  "Region": self._normalize_payload_region(data.get("region", "cn-beijing-6")),
1298
1322
  "Resource": {
1299
1323
  "Cpu": int(float(data.get("resources", {}).get("cpu", 2))),
1300
- "Memory": int(str(data.get("resources", {}).get("memory", "4Gi")).replace("Gi", ""))
1324
+ "Memory": int(
1325
+ str(data.get("resources", {}).get("memory", "4Gi")).replace("Gi", "")
1326
+ ),
1301
1327
  },
1302
1328
  "Scaling": {
1303
1329
  "MinReplicas": int(data.get("scaling", {}).get("min_replicas", 1)),
@@ -1331,7 +1357,7 @@ class AgentEngineClient:
1331
1357
  "IamRole": data.get("iam_role", "KsyunAgentEngineDefaultRole"),
1332
1358
  }
1333
1359
 
1334
- if params["DeploymentType"] == "Code":
1360
+ if params["DeploymentType"] in {"Code", "ManagedRuntime"}:
1335
1361
  ks3 = data.get("ks3", {})
1336
1362
  params["CodeConfig"] = {
1337
1363
  "Path": data.get("artifact_path", ""),
@@ -1340,6 +1366,13 @@ class AgentEngineClient:
1340
1366
  "Region": self._normalize_payload_region(ks3.get("region", "cn-beijing-6")),
1341
1367
  "Bucket": ks3.get("bucket"),
1342
1368
  }
1369
+ if params["DeploymentType"] == "ManagedRuntime":
1370
+ runtime_config = data.get("runtime_config") or {}
1371
+ params["RuntimeConfig"] = {
1372
+ "Name": runtime_config.get("name"),
1373
+ "Version": runtime_config.get("version"),
1374
+ "ManifestSha256": runtime_config.get("manifest_sha256"),
1375
+ }
1343
1376
  else:
1344
1377
  ic = data.get("image_credential", {}) or {}
1345
1378
  artifact = (data.get("artifact_path", "") or "").strip()
@@ -1348,14 +1381,11 @@ class AgentEngineClient:
1348
1381
  image_credential=ic,
1349
1382
  )
1350
1383
 
1351
- env_vars = []
1352
1384
  envs = data.get("env_vars") or data.get("environment_variables")
1353
1385
  if envs:
1354
- if isinstance(envs, dict):
1355
- for k, v in envs.items():
1356
- env_vars.append({"Key": k, "Value": str(v), "IsSensitive": False})
1357
- elif isinstance(envs, list):
1358
- env_vars = envs
1386
+ env_vars = environment_variables_payload(envs)
1387
+ else:
1388
+ env_vars = []
1359
1389
 
1360
1390
  advanced = {
1361
1391
  "EnableObservability": True,
@@ -1371,7 +1401,12 @@ class AgentEngineClient:
1371
1401
 
1372
1402
  return self._action("CreateAgentProduct", params)
1373
1403
 
1374
- async def get_agent(self, agent_id: str = None, name: str = None, include_api_key: bool = False) -> Dict[str, Any]:
1404
+ async def get_agent(
1405
+ self,
1406
+ agent_id: Optional[str] = None,
1407
+ name: Optional[str] = None,
1408
+ include_api_key: bool = False,
1409
+ ) -> Dict[str, Any]:
1375
1410
  """获取 Agent 详情(支持 AgentId 或 Name 查询)"""
1376
1411
  if agent_id:
1377
1412
  params: Dict[str, Any] = {"AgentId": agent_id}
@@ -1382,7 +1417,7 @@ class AgentEngineClient:
1382
1417
  except Exception as e:
1383
1418
  # 兼容旧控制面:极少数版本仍使用 Id 字段
1384
1419
  if self._should_fallback_get_agent_with_legacy_id(e):
1385
- fallback = {"Id": agent_id}
1420
+ fallback: Dict[str, Any] = {"Id": agent_id}
1386
1421
  if include_api_key:
1387
1422
  fallback["IncludeApiKey"] = True
1388
1423
  return self._action("GetAgent", fallback)
@@ -1512,7 +1547,7 @@ class AgentEngineClient:
1512
1547
  async def delete_dashboard_access_link(self, *, link_id: str) -> Dict[str, Any]:
1513
1548
  """删除 Dashboard 短链接。"""
1514
1549
  return self._action("DeleteDashboardAccessLink", {"LinkId": link_id})
1515
-
1550
+
1516
1551
  async def list_agents(
1517
1552
  self,
1518
1553
  region: Optional[str] = None,
@@ -1595,17 +1630,18 @@ class AgentEngineClient:
1595
1630
  self._action("DeleteAgent", {"AgentId": agent_id})
1596
1631
  return True
1597
1632
 
1598
-
1599
-
1600
1633
  async def update_agent(self, agent_id: str, data: Dict[str, Any]) -> Dict[str, Any]:
1601
1634
  """更新 Agent (热更新)"""
1602
- params = {"AgentId": agent_id}
1635
+ params: Dict[str, Any] = {"AgentId": agent_id}
1636
+ artifact_type = data.get("artifact_type")
1637
+ if artifact_type:
1638
+ params["DeploymentType"] = artifact_type
1603
1639
  if data.get("description"):
1604
1640
  params["Description"] = data["description"]
1605
-
1641
+
1606
1642
  if data.get("artifact_path"):
1607
1643
  artifact = (data.get("artifact_path", "") or "").strip()
1608
- if (data.get("artifact_type") or "").lower() == "container":
1644
+ if (artifact_type or "").lower() == "container":
1609
1645
  ic = data.get("image_credential", {}) or {}
1610
1646
  params["ContainerConfig"] = self._build_container_config_payload(
1611
1647
  artifact=artifact,
@@ -1620,29 +1656,30 @@ class AgentEngineClient:
1620
1656
  "Region": self._normalize_payload_region(ks3.get("region", "cn-beijing-6")),
1621
1657
  "Bucket": ks3.get("bucket"),
1622
1658
  }
1623
-
1659
+ if artifact_type == "ManagedRuntime":
1660
+ runtime_config = data.get("runtime_config") or {}
1661
+ params["RuntimeConfig"] = {
1662
+ "Name": runtime_config.get("name"),
1663
+ "Version": runtime_config.get("version"),
1664
+ "ManifestSha256": runtime_config.get("manifest_sha256"),
1665
+ }
1666
+
1624
1667
  if data.get("resources"):
1625
1668
  params["Resource"] = {
1626
1669
  "Cpu": int(float(data["resources"].get("cpu", 2))),
1627
- "Memory": int(str(data["resources"].get("memory", "4Gi")).replace("Gi", ""))
1670
+ "Memory": int(str(data["resources"].get("memory", "4Gi")).replace("Gi", "")),
1628
1671
  }
1629
-
1672
+
1630
1673
  if data.get("scaling"):
1631
1674
  params["Scaling"] = {
1632
1675
  "MinReplicas": int(data["scaling"].get("min_replicas", 1)),
1633
1676
  "MaxReplicas": int(data["scaling"].get("max_replicas", 10)),
1634
1677
  "Concurrency": int(data["scaling"].get("concurrency", 20)),
1635
1678
  }
1636
-
1679
+
1637
1680
  envs = data.get("env_vars") or data.get("environment_variables")
1638
1681
  if envs:
1639
- env_vars = []
1640
- if isinstance(envs, dict):
1641
- for k, v in envs.items():
1642
- env_vars.append({"Key": k, "Value": str(v), "IsSensitive": False})
1643
- elif isinstance(envs, list):
1644
- env_vars = envs
1645
- params["EnvironmentVariables"] = env_vars
1682
+ params["EnvironmentVariables"] = environment_variables_payload(envs)
1646
1683
 
1647
1684
  network_payload = self._normalize_network_payload(data.get("network"))
1648
1685
  if network_payload:
@@ -1683,27 +1720,27 @@ class AgentEngineClient:
1683
1720
  advanced["ProjectId"] = project_id
1684
1721
  if advanced:
1685
1722
  params["Advanced"] = advanced
1686
-
1723
+
1687
1724
  return self._action("UpdateAgent", params)
1688
1725
 
1689
1726
  # ===== Session Actions =====
1690
-
1691
- async def create_session(self, agent_id: str, user_id: Optional[str] = None, expires_hours: int = 24) -> Dict[str, Any]:
1727
+
1728
+ async def create_session(
1729
+ self, agent_id: str, user_id: Optional[str] = None, expires_hours: int = 24
1730
+ ) -> Dict[str, Any]:
1692
1731
  """创建会话"""
1693
- return self._action("CreateSession", {
1694
- "AgentId": agent_id,
1695
- "UserId": user_id,
1696
- "ExpiresHours": expires_hours
1697
- })
1698
-
1732
+ return self._action(
1733
+ "CreateSession", {"AgentId": agent_id, "UserId": user_id, "ExpiresHours": expires_hours}
1734
+ )
1735
+
1699
1736
  async def get_session(self, session_id: str) -> Dict[str, Any]:
1700
1737
  """获取会话详情"""
1701
1738
  return self._action("GetSession", {"Id": session_id})
1702
-
1739
+
1703
1740
  async def list_sessions(self, agent_id: str, page: int = 1, size: int = 20) -> Dict[str, Any]:
1704
1741
  """列出会话"""
1705
1742
  return self._action("ListSessions", {"AgentId": agent_id, "Page": page, "PageSize": size})
1706
-
1743
+
1707
1744
  async def delete_session(self, session_id: str) -> bool:
1708
1745
  """删除会话"""
1709
1746
  try:
@@ -1866,14 +1903,14 @@ class AgentEngineClient:
1866
1903
  },
1867
1904
  accept="application/octet-stream",
1868
1905
  )
1869
- return response.content
1906
+ return bytes(response.content)
1870
1907
  access = transport["access"]
1871
1908
  response = self._workspace_runtime_request(
1872
1909
  access=access,
1873
1910
  method="GET",
1874
1911
  path=f"files/{self._encode_workspace_runtime_path(remote_path)}",
1875
1912
  )
1876
- return response.content
1913
+ return bytes(response.content)
1877
1914
 
1878
1915
  async def delete_workspace_file(
1879
1916
  self,
@@ -1944,13 +1981,17 @@ class AgentEngineClient:
1944
1981
  return int(float(raw))
1945
1982
 
1946
1983
  @staticmethod
1947
- def _normalize_mcp_deployment_type(value: Optional[str], default: Optional[str] = None) -> Optional[str]:
1984
+ def _normalize_mcp_deployment_type(
1985
+ value: Optional[str], default: Optional[str] = None
1986
+ ) -> Optional[str]:
1948
1987
  raw = str(value or default or "").strip()
1949
1988
  if not raw:
1950
1989
  return None
1951
1990
  return "Container" if raw.lower() == "container" else "Code"
1952
1991
 
1953
- def _infer_mcp_deployment_type(self, data: Dict[str, Any], default: Optional[str] = None) -> Optional[str]:
1992
+ def _infer_mcp_deployment_type(
1993
+ self, data: Dict[str, Any], default: Optional[str] = None
1994
+ ) -> Optional[str]:
1954
1995
  explicit = self._normalize_mcp_deployment_type(
1955
1996
  data.get("deployment_type") or data.get("artifact_type"),
1956
1997
  default=default,
@@ -2018,11 +2059,14 @@ class AgentEngineClient:
2018
2059
  async def create_mcp(self, data: Dict[str, Any]) -> Dict[str, Any]:
2019
2060
  """创建 MCP"""
2020
2061
  if self._looks_like_nested_mcp_payload(data):
2021
- params = dict(data)
2022
- params["Region"] = self._normalize_payload_region(
2023
- params.get("Region") or data.get("region") or self.logical_region or "cn-beijing-6"
2062
+ nested_params = dict(data)
2063
+ nested_params["Region"] = self._normalize_payload_region(
2064
+ nested_params.get("Region")
2065
+ or data.get("region")
2066
+ or self.logical_region
2067
+ or "cn-beijing-6"
2024
2068
  )
2025
- return self._action("CreateMCP", params)
2069
+ return self._action("CreateMCP", nested_params)
2026
2070
 
2027
2071
  deployment_type = self._infer_mcp_deployment_type(data, default="Code") or "Code"
2028
2072
  params: Dict[str, Any] = {
@@ -2043,11 +2087,11 @@ class AgentEngineClient:
2043
2087
  if network_payload:
2044
2088
  params["Network"] = network_payload
2045
2089
  return self._action("CreateMCP", params)
2046
-
2090
+
2047
2091
  async def get_mcp(self, mcp_id: str) -> Dict[str, Any]:
2048
2092
  """获取 MCP 详情"""
2049
2093
  return self._action("GetMCP", {"Id": mcp_id})
2050
-
2094
+
2051
2095
  async def list_mcps(
2052
2096
  self,
2053
2097
  region: Optional[str] = None,
@@ -2055,24 +2099,23 @@ class AgentEngineClient:
2055
2099
  page_size: int = 20,
2056
2100
  ) -> Dict[str, Any]:
2057
2101
  """列出 MCP (注册中心)"""
2058
- params = {"Page": int(page), "PageSize": int(page_size)}
2102
+ params: Dict[str, Any] = {"Page": int(page), "PageSize": int(page_size)}
2059
2103
  if region:
2060
2104
  params["Region"] = self._normalize_payload_region(region)
2061
2105
  result = self._action("ListMCPs", params)
2062
- # _action 已统一转 snake_case: "MCPs" -> "m_c_ps"...
2063
- # 实际上 MCPs -> mcps, Total -> total
2106
+ # _action 已统一转 snake_case: MCPs -> mcps, Total -> total
2064
2107
  return {"mcps": result.get("mcps", []), "total": result.get("total", 0)}
2065
-
2108
+
2066
2109
  async def update_mcp(self, mcp_id: str, data: Dict[str, Any]) -> Dict[str, Any]:
2067
2110
  """更新 MCP (热更新)"""
2068
2111
  if self._looks_like_nested_mcp_payload(data):
2069
- params = dict(data)
2070
- params.setdefault("Id", mcp_id)
2071
- if "Region" in params or data.get("region") or self.logical_region:
2072
- params["Region"] = self._normalize_payload_region(
2073
- params.get("Region") or data.get("region") or self.logical_region
2112
+ nested_params = dict(data)
2113
+ nested_params.setdefault("Id", mcp_id)
2114
+ if "Region" in nested_params or data.get("region") or self.logical_region:
2115
+ nested_params["Region"] = self._normalize_payload_region(
2116
+ nested_params.get("Region") or data.get("region") or self.logical_region
2074
2117
  )
2075
- return self._action("UpdateMCP", params)
2118
+ return self._action("UpdateMCP", nested_params)
2076
2119
 
2077
2120
  params: Dict[str, Any] = {"Id": mcp_id}
2078
2121
  deployment_type = self._infer_mcp_deployment_type(data)
@@ -2096,7 +2139,9 @@ class AgentEngineClient:
2096
2139
  }
2097
2140
 
2098
2141
  scaling = data.get("scaling", {}) or {}
2099
- if any(scaling.get(key) is not None for key in ("min_replicas", "max_replicas", "concurrency")):
2142
+ if any(
2143
+ scaling.get(key) is not None for key in ("min_replicas", "max_replicas", "concurrency")
2144
+ ):
2100
2145
  params["Scaling"] = {
2101
2146
  "MinReplicas": int(scaling.get("min_replicas", 1)),
2102
2147
  "MaxReplicas": int(scaling.get("max_replicas", 5)),
@@ -2119,16 +2164,15 @@ class AgentEngineClient:
2119
2164
  if data.get("region") is not None:
2120
2165
  params["Region"] = self._normalize_payload_region(data.get("region"))
2121
2166
  return self._action("UpdateMCP", params)
2122
-
2167
+
2123
2168
  async def delete_mcp(self, mcp_id: str) -> bool:
2124
2169
  """删除 MCP"""
2125
- try:
2126
- self._action("DeleteMCP", {"Id": mcp_id})
2127
- return True
2128
- except Exception:
2129
- return False
2130
-
2131
- async def get_mcp_by_name(self, name: str, region: Optional[str] = None) -> Optional[Dict[str, Any]]:
2170
+ result = self._action("DeleteMCP", {"Id": mcp_id})
2171
+ return bool(result.get("deleted"))
2172
+
2173
+ async def get_mcp_by_name(
2174
+ self, name: str, region: Optional[str] = None
2175
+ ) -> Optional[Dict[str, Any]]:
2132
2176
  """按名称查询 MCP"""
2133
2177
  # 使用 ListMCPs 然后过滤 (Action API 暂不支持 by-name)
2134
2178
  try:
@@ -2138,7 +2182,7 @@ class AgentEngineClient:
2138
2182
  result = await self.list_mcps(region=region, page=page, page_size=page_size)
2139
2183
  mcps = result.get("mcps", [])
2140
2184
  for mcp in mcps:
2141
- if mcp.get("name") == name:
2185
+ if isinstance(mcp, dict) and mcp.get("name") == name:
2142
2186
  return mcp
2143
2187
  if len(mcps) < page_size:
2144
2188
  break
@@ -2148,39 +2192,38 @@ class AgentEngineClient:
2148
2192
  return None
2149
2193
 
2150
2194
  # ===== Upload Actions =====
2151
-
2195
+
2152
2196
  async def get_presigned_url(self, filename: str) -> Dict[str, Any]:
2153
2197
  """获取 KS3 预签名上传 URL"""
2154
2198
  return self._action("GetPresignedUrl", {"Filename": filename})
2155
2199
 
2156
2200
  # ===== Chat Actions =====
2157
-
2158
- async def chat(self, agent_id: str, message: str, session_id: Optional[str] = None) -> Dict[str, Any]:
2201
+
2202
+ async def chat(
2203
+ self, agent_id: str, message: str, session_id: Optional[str] = None
2204
+ ) -> Dict[str, Any]:
2159
2205
  """调用 Agent"""
2160
2206
  params = {
2161
2207
  "AgentId": agent_id,
2162
2208
  "Messages": [{"role": "user", "content": message}],
2163
- "Stream": False
2209
+ "Stream": False,
2164
2210
  }
2165
2211
  if session_id:
2166
2212
  params["SessionId"] = session_id
2167
2213
  return self._action("RunAgent", params)
2168
2214
 
2169
2215
  # ===== Version Actions =====
2170
-
2216
+
2171
2217
  async def release_version(
2172
- self,
2173
- agent_id: str,
2174
- tag: Optional[str] = None,
2175
- description: Optional[str] = None
2218
+ self, agent_id: str, tag: Optional[str] = None, description: Optional[str] = None
2176
2219
  ) -> Dict[str, Any]:
2177
2220
  """发布新版本
2178
-
2221
+
2179
2222
  Args:
2180
2223
  agent_id: Agent ID
2181
2224
  tag: 版本标签,不填则自动生成
2182
2225
  description: 版本描述
2183
-
2226
+
2184
2227
  Returns:
2185
2228
  版本信息
2186
2229
  """
@@ -2190,46 +2233,37 @@ class AgentEngineClient:
2190
2233
  if description:
2191
2234
  params["Description"] = description
2192
2235
  return self._action("CreateVersion", params)
2193
-
2194
- async def list_versions(
2195
- self,
2196
- agent_id: str,
2197
- page: int = 1,
2198
- size: int = 10
2199
- ) -> Dict[str, Any]:
2236
+
2237
+ async def list_versions(self, agent_id: str, page: int = 1, size: int = 10) -> Dict[str, Any]:
2200
2238
  """列出版本历史
2201
-
2239
+
2202
2240
  Args:
2203
2241
  agent_id: Agent ID
2204
2242
  page: 页码
2205
2243
  size: 每页数量
2206
-
2244
+
2207
2245
  Returns:
2208
2246
  版本列表和分页信息
2209
2247
  """
2210
- return self._action("ListVersions", {
2211
- "AgentId": agent_id,
2212
- "Page": page,
2213
- "PageSize": size
2214
- })
2215
-
2248
+ return self._action("ListVersions", {"AgentId": agent_id, "Page": page, "PageSize": size})
2249
+
2216
2250
  async def rollback_version(
2217
- self,
2218
- agent_id: str,
2251
+ self,
2252
+ agent_id: str,
2219
2253
  target_version_id: Optional[str] = None,
2220
2254
  target_tag: Optional[str] = None,
2221
2255
  ks3_access_key: Optional[str] = None,
2222
2256
  ks3_secret_key: Optional[str] = None,
2223
2257
  ) -> Dict[str, Any]:
2224
2258
  """回滚到指定版本
2225
-
2259
+
2226
2260
  Args:
2227
2261
  agent_id: Agent ID
2228
2262
  target_version_id: 目标版本 ID(与 target_tag 二选一)
2229
2263
  target_tag: 目标版本标签(与 target_version_id 二选一)
2230
2264
  ks3_access_key: KS3 Access Key (可选)
2231
2265
  ks3_secret_key: KS3 Secret Key (可选)
2232
-
2266
+
2233
2267
  Returns:
2234
2268
  回滚结果
2235
2269
  """
@@ -2242,5 +2276,5 @@ class AgentEngineClient:
2242
2276
  params["KS3AccessKey"] = ks3_access_key
2243
2277
  if ks3_secret_key:
2244
2278
  params["KS3SecretKey"] = ks3_secret_key
2245
-
2279
+
2246
2280
  return self._action("RollbackVersion", params)