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/cli/cmd_create.py CHANGED
@@ -7,11 +7,12 @@ import platform
7
7
  import re
8
8
  import shlex
9
9
  import shutil
10
-
11
10
  from pathlib import Path
12
11
 
13
12
  import click
14
13
  import questionary
14
+ from rich.markup import escape
15
+
15
16
  from ksadk.cli.cmd_config import custom_style
16
17
  from ksadk.cli.ui import (
17
18
  print_error,
@@ -112,10 +113,10 @@ model = LiteLlm(
112
113
 
113
114
  def hello(name: str) -> dict:
114
115
  """问候工具
115
-
116
+
116
117
  Args:
117
118
  name: 名字
118
-
119
+
119
120
  Returns:
120
121
  问候语
121
122
  """
@@ -133,7 +134,7 @@ root_agent = Agent(
133
134
  },
134
135
  "langchain": {
135
136
  "agent.py": '''"""
136
- {package_name} - LangChain Agent
137
+ {package_name} - LangChain Agent (create_agent)
137
138
  """
138
139
 
139
140
  import os
@@ -142,9 +143,8 @@ from dotenv import load_dotenv
142
143
 
143
144
  load_dotenv(Path(__file__).parent.parent / ".env")
144
145
 
146
+ from langchain.agents import create_agent
145
147
  from langchain_openai import ChatOpenAI
146
- from langchain_core.prompts import ChatPromptTemplate
147
- from langchain_core.output_parsers import StrOutputParser
148
148
 
149
149
  llm = ChatOpenAI(
150
150
  model=os.getenv("OPENAI_MODEL_NAME", "glm-5.2"),
@@ -153,12 +153,28 @@ llm = ChatOpenAI(
153
153
  streaming=True,
154
154
  )
155
155
 
156
- prompt = ChatPromptTemplate.from_messages([
157
- ("system", "你是一个友好的助手。请用中文回复。"),
158
- ("human", "{{input}}")
159
- ])
160
156
 
161
- root_agent = prompt | llm | StrOutputParser()
157
+ def hello(name: str) -> str:
158
+ """问候工具
159
+
160
+ Args:
161
+ name: 名字
162
+
163
+ Returns:
164
+ 问候语
165
+ """
166
+ return f"你好, {{name}}!"
167
+
168
+
169
+ # create_agent 是新版 LangChain 定义 agent 的推荐方式,自带工具调用;
170
+ # 可选 middleware=[HumanInTheLoopMiddleware(...)](人工审批 HITL)与
171
+ # checkpointer(会话持久化)。detector 将本项目判为 LANGCHAIN,
172
+ # 经 LangChainRunner 运行。
173
+ root_agent = create_agent(
174
+ model=llm,
175
+ tools=[hello],
176
+ system_prompt="你是一个友好的助手。请用中文回复。",
177
+ )
162
178
  ''',
163
179
  },
164
180
  "langgraph": {
@@ -243,42 +259,46 @@ root_agent = None
243
259
 
244
260
  def _detect_framework(content: str) -> str:
245
261
  """检测 Agent 文件使用的框架"""
246
- if 'from deepagents' in content or 'import deepagents' in content or 'create_deep_agent(' in content:
247
- return 'deepagents'
248
- elif 'from langgraph' in content or 'import langgraph' in content:
249
- return 'langgraph'
250
- elif 'from google.adk' in content or 'import google.adk' in content:
251
- return 'adk'
252
- elif 'from langchain' in content or 'import langchain' in content:
253
- return 'langchain'
254
- return 'unknown'
262
+ if (
263
+ "from deepagents" in content
264
+ or "import deepagents" in content
265
+ or "create_deep_agent(" in content
266
+ ):
267
+ return "deepagents"
268
+ elif "from langgraph" in content or "import langgraph" in content:
269
+ return "langgraph"
270
+ elif "from google.adk" in content or "import google.adk" in content:
271
+ return "adk"
272
+ elif "from langchain" in content or "import langchain" in content:
273
+ return "langchain"
274
+ return "unknown"
255
275
 
256
276
 
257
277
  def _detect_agent_variable(content: str) -> str | None:
258
278
  """检测 Agent 变量名"""
259
279
  import re
260
-
280
+
261
281
  # 优先级匹配: root_agent > compiled graph > StateGraph > Agent()
262
282
  # Only module-level exports are valid entry variables. Service-style
263
283
  # projects often build a local `graph` inside init_agent_resources(), which
264
284
  # must not be treated as importable module state.
265
285
  patterns = [
266
- (r'^(root_agent)\s*=', 'root_agent'),
267
- (r'^(root_agent)\s*:\s*[^=]+\s*=', 'root_agent'), # type annotated root_agent
268
- (r'^(\w+)\s*=\s*\w*graph\w*\.compile\(', None), # e.g., agent = graph.compile()
269
- (r'^(\w+)\s*=\s*StateGraph', None), # e.g., graph = StateGraph(...)
270
- (r'^(\w+)\s*=\s*Agent\(', None), # ADK: agent = Agent(...)
271
- (r'^(\w+)\s*=\s*create_react_agent\(', None), # create_react_agent
272
- (r'^(\w+)\s*=\s*create_deep_agent\(', None), # deepagents create_deep_agent
273
- (r'^(\w+)\s*=\s*create_agent\(', None), # langchain create_agent
274
- (r'^(\w+)\s*=\s*build_agent\(', None), # adapter style build_agent
286
+ (r"^(root_agent)\s*=", "root_agent"),
287
+ (r"^(root_agent)\s*:\s*[^=]+\s*=", "root_agent"), # type annotated root_agent
288
+ (r"^(\w+)\s*=\s*\w*graph\w*\.compile\(", None), # e.g., agent = graph.compile()
289
+ (r"^(\w+)\s*=\s*StateGraph", None), # e.g., graph = StateGraph(...)
290
+ (r"^(\w+)\s*=\s*Agent\(", None), # ADK: agent = Agent(...)
291
+ (r"^(\w+)\s*=\s*create_react_agent\(", None), # create_react_agent
292
+ (r"^(\w+)\s*=\s*create_deep_agent\(", None), # deepagents create_deep_agent
293
+ (r"^(\w+)\s*=\s*create_agent\(", None), # langchain create_agent
294
+ (r"^(\w+)\s*=\s*build_agent\(", None), # adapter style build_agent
275
295
  ]
276
-
296
+
277
297
  for pattern, fixed_name in patterns:
278
298
  match = re.search(pattern, content, re.MULTILINE | re.IGNORECASE)
279
299
  if match:
280
300
  return fixed_name if fixed_name else match.group(1)
281
-
301
+
282
302
  return None
283
303
 
284
304
 
@@ -367,7 +387,11 @@ def _load_entry_from_langgraph_json(directory: Path) -> tuple[Path, str] | None:
367
387
  path_part = path_part.strip().removeprefix("./")
368
388
  agent_var = agent_var.strip() or "root_agent"
369
389
  entry_path = directory / Path(path_part.replace("\\", "/"))
370
- if entry_path.exists() and entry_path.is_file() and _entry_exposes_variable(entry_path, agent_var):
390
+ if (
391
+ entry_path.exists()
392
+ and entry_path.is_file()
393
+ and _entry_exposes_variable(entry_path, agent_var)
394
+ ):
371
395
  return entry_path, agent_var
372
396
  return None
373
397
 
@@ -389,7 +413,7 @@ def _load_framework_from_agentengine_yaml(directory: Path) -> str | None:
389
413
  if not isinstance(framework, str):
390
414
  return None
391
415
  framework = framework.strip().lower()
392
- if framework in {"adk", "langchain", "langgraph", "deepagents", "openclaw", "hermes"}:
416
+ if framework in {"adk", "langchain", "langgraph", "deepagents", "openclaw", "hermes", "codex"}:
393
417
  return framework
394
418
  return None
395
419
 
@@ -501,35 +525,37 @@ def _fix_dotenv_paths_in_file(file_path: Path, depth: int = 1) -> bool:
501
525
  返回是否修改了文件
502
526
  """
503
527
  import re
504
-
528
+
505
529
  try:
506
- content = file_path.read_text(encoding='utf-8')
530
+ content = file_path.read_text(encoding="utf-8")
507
531
  except Exception:
508
532
  return False
509
-
533
+
510
534
  # 构建替换的 parent 链
511
- parent_chain = '.parent' * depth
512
-
535
+ parent_chain = ".parent" * depth
536
+
513
537
  # 匹配各种 load_dotenv 模式
514
538
  patterns = [
515
539
  # load_dotenv(Path(__file__).parent / ".env")
516
- (r'(load_dotenv\s*\(\s*Path\s*\(\s*__file__\s*\)\s*)\.parent(\s*/\s*["\']\.env["\'])',
517
- rf'\1{parent_chain}\2'),
540
+ (
541
+ r'(load_dotenv\s*\(\s*Path\s*\(\s*__file__\s*\)\s*)\.parent(\s*/\s*["\']\.env["\'])',
542
+ rf"\1{parent_chain}\2",
543
+ ),
518
544
  # load_dotenv(Path(__file__).parent.parent / ".env") -> 根据 depth 调整
519
545
  ]
520
-
546
+
521
547
  modified = False
522
548
  new_content = content
523
-
549
+
524
550
  for pattern, replacement in patterns:
525
551
  new_content_temp = re.sub(pattern, replacement, new_content)
526
552
  if new_content_temp != new_content:
527
553
  new_content = new_content_temp
528
554
  modified = True
529
-
555
+
530
556
  if modified:
531
- file_path.write_text(new_content, encoding='utf-8')
532
-
557
+ file_path.write_text(new_content, encoding="utf-8")
558
+
533
559
  return modified
534
560
 
535
561
 
@@ -539,76 +565,76 @@ def _fix_dotenv_paths_recursive(directory: Path, depth: int = 1) -> int:
539
565
  返回修复的文件数量
540
566
  """
541
567
  fixed_count = 0
542
-
543
- for py_file in directory.rglob('*.py'):
568
+
569
+ for py_file in directory.rglob("*.py"):
544
570
  # 计算相对深度
545
571
  rel_path = py_file.relative_to(directory)
546
572
  file_depth = len(rel_path.parts) + depth - 1 # 相对于项目根目录
547
-
573
+
548
574
  if _fix_dotenv_paths_in_file(py_file, file_depth):
549
575
  fixed_count += 1
550
-
576
+
551
577
  return fixed_count
552
578
 
553
579
 
554
580
  def _fix_nested_imports(file_path: Path, subdirs: list[str]) -> bool:
555
581
  """
556
582
  修复文件中的嵌套目录导入
557
-
583
+
558
584
  当源目录包含子包目录(如 my_agent/)时,
559
585
  入口文件中的 `from my_agent import xxx` 需要改为 `from .my_agent import xxx`
560
-
586
+
561
587
  Args:
562
588
  file_path: 需要修复的文件
563
589
  subdirs: 同级子目录名列表
564
-
590
+
565
591
  Returns:
566
592
  是否修改了文件
567
593
  """
568
594
  import re
569
-
595
+
570
596
  if not subdirs:
571
597
  return False
572
-
598
+
573
599
  try:
574
- content = file_path.read_text(encoding='utf-8')
600
+ content = file_path.read_text(encoding="utf-8")
575
601
  except Exception:
576
602
  return False
577
-
603
+
578
604
  original = content
579
-
605
+
580
606
  # 为每个子目录生成修复规则
581
607
  for subdir in subdirs:
582
608
  # from my_agent import xxx -> from .my_agent import xxx
583
- pattern = rf'^(from\s+)({re.escape(subdir)})(\s+import\s+)'
584
- replacement = rf'\1.\2\3'
609
+ pattern = rf"^(from\s+)({re.escape(subdir)})(\s+import\s+)"
610
+ replacement = r"\1.\2\3"
585
611
  content = re.sub(pattern, replacement, content, flags=re.MULTILINE)
586
-
612
+
587
613
  # import my_agent -> from . import my_agent
588
614
  # 只处理独立的 import 语句
589
- pattern_import = rf'^import\s+({re.escape(subdir)})\s*$'
590
- replacement_import = rf'from . import \1'
615
+ pattern_import = rf"^import\s+({re.escape(subdir)})\s*$"
616
+ replacement_import = r"from . import \1"
591
617
  content = re.sub(pattern_import, replacement_import, content, flags=re.MULTILINE)
592
-
618
+
593
619
  if content != original:
594
- file_path.write_text(content, encoding='utf-8')
620
+ file_path.write_text(content, encoding="utf-8")
595
621
  return True
596
-
622
+
597
623
  return False
598
624
 
599
625
 
600
626
  def _generate_env_content(global_env: dict) -> str:
601
- """生成 .env 文件内容"""
602
- api_key = global_env.get("OPENAI_API_KEY", "")
627
+ """Generate project-local configuration without copying credentials.
628
+
629
+ ``init`` may read a global profile to retain non-secret endpoint defaults, but
630
+ it must not persist the caller's credentials in a newly created directory.
631
+ """
603
632
  base_url = global_env.get("OPENAI_BASE_URL", "")
604
633
  model_name = global_env.get("OPENAI_MODEL_NAME", "")
605
- ks_ak = global_env.get("KSYUN_ACCESS_KEY", "")
606
- ks_sk = global_env.get("KSYUN_SECRET_KEY", "")
607
634
  ks_region = global_env.get("KSYUN_REGION", "cn-beijing-6")
608
- ks_account = global_env.get("KSYUN_ACCOUNT_ID", "")
609
-
610
- env_content = f"""# 模型配置
611
- OPENAI_API_KEY={api_key}
635
+
636
+ env_content = """# 模型配置
637
+ # OPENAI_API_KEY=
612
638
  """
613
639
  if base_url:
614
640
  env_content += f"OPENAI_BASE_URL={base_url}\n"
@@ -618,110 +644,131 @@ OPENAI_API_KEY={api_key}
618
644
  env_content += f"OPENAI_MODEL_NAME={model_name}\n"
619
645
  else:
620
646
  env_content += "# OPENAI_MODEL_NAME=\n"
621
-
622
- env_content += f"""
647
+
648
+ env_content += """
623
649
  # 金山云配置
624
650
  """
625
- if ks_ak:
626
- env_content += f"KSYUN_ACCESS_KEY={ks_ak}\n"
627
- else:
628
- env_content += "# KSYUN_ACCESS_KEY=\n"
629
- if ks_sk:
630
- env_content += f"KSYUN_SECRET_KEY={ks_sk}\n"
631
- else:
632
- env_content += "# KSYUN_SECRET_KEY=\n"
651
+ env_content += "# KSYUN_ACCESS_KEY=\n"
652
+ env_content += "# KSYUN_SECRET_KEY=\n"
633
653
  env_content += f"KSYUN_REGION={ks_region}\n"
634
- if ks_account:
635
- env_content += f"KSYUN_ACCOUNT_ID={ks_account}\n"
636
- else:
637
- env_content += "# KSYUN_ACCOUNT_ID=\n"
638
-
654
+ env_content += "# KSYUN_ACCOUNT_ID=\n"
655
+
639
656
  return env_content
640
657
 
641
658
 
659
+ def _generate_codex_env_content(global_env: dict) -> str:
660
+ """Generate the intentionally small local-only environment for a Codex project.
661
+
662
+ A ManagedRuntime manifest is declarative and must never acquire cloud, storage or
663
+ observability credentials merely because the developer ran ``init``. The three
664
+ OpenAI-compatible values are enough for native ``ksadk web`` debugging. The
665
+ optional proxy knobs are documented rather than copied from the global profile,
666
+ because their upstream key can be different from the model key.
667
+ """
668
+ base_url = global_env.get("OPENAI_BASE_URL", "")
669
+ model_name = global_env.get("OPENAI_MODEL_NAME", "")
670
+ lines = [
671
+ "# 本地 Codex 模型配置(仅用于 ksadk web,不会进入 ManagedRuntime bundle)",
672
+ "# OPENAI_API_KEY=",
673
+ f"OPENAI_BASE_URL={base_url}" if base_url else "# OPENAI_BASE_URL=",
674
+ f"OPENAI_MODEL_NAME={model_name}" if model_name else "# OPENAI_MODEL_NAME=glm-5.2",
675
+ "",
676
+ "# 可选:自定义上游仅支持 Chat Completions 时,强制启用协议转换代理",
677
+ "# KSADK_CODEX_USE_PROXY=1",
678
+ "# KSADK_PROXY_UPSTREAM_BASE=",
679
+ "# KSADK_PROXY_UPSTREAM_KEY=",
680
+ "",
681
+ ]
682
+ return "\n".join(lines)
683
+
684
+
642
685
  def _generate_requirements_from_imports(directory: Path, framework: str) -> str:
643
686
  """
644
687
  扫描目录中的 Python 文件,从 import 语句生成 requirements.txt
645
688
  """
646
689
  import re
647
-
690
+
648
691
  # 常用包名到 PyPI 包名的映射
649
692
  import_to_package = {
650
- 'langchain': 'langchain',
651
- 'langchain_openai': 'langchain-openai',
652
- 'langchain_anthropic': 'langchain-anthropic',
653
- 'langchain_core': 'langchain-core',
654
- 'langchain_community': 'langchain-community',
655
- 'langgraph': 'langgraph',
656
- 'deepagents': 'deepagents',
657
- 'openai': 'openai',
658
- 'anthropic': 'anthropic',
659
- 'dotenv': 'python-dotenv',
660
- 'pydantic': 'pydantic',
661
- 'httpx': 'httpx',
662
- 'requests': 'requests',
663
- 'google.adk': 'google-adk',
664
- 'google.genai': 'google-genai',
665
- 'tiktoken': 'tiktoken',
666
- 'faiss': 'faiss-cpu',
667
- 'chromadb': 'chromadb',
668
- 'tavily': 'tavily-python',
693
+ "langchain": "langchain",
694
+ "langchain_openai": "langchain-openai",
695
+ "langchain_anthropic": "langchain-anthropic",
696
+ "langchain_core": "langchain-core",
697
+ "langchain_community": "langchain-community",
698
+ "langgraph": "langgraph",
699
+ "deepagents": "deepagents",
700
+ "openai": "openai",
701
+ "anthropic": "anthropic",
702
+ "dotenv": "python-dotenv",
703
+ "pydantic": "pydantic",
704
+ "httpx": "httpx",
705
+ "requests": "requests",
706
+ "google.adk": "google-adk",
707
+ "google.genai": "google-genai",
708
+ "tiktoken": "tiktoken",
709
+ "faiss": "faiss-cpu",
710
+ "chromadb": "chromadb",
711
+ "tavily": "tavily-python",
669
712
  }
670
-
713
+
671
714
  found_packages = set()
672
-
715
+
673
716
  # 扫描所有 .py 文件
674
- for py_file in directory.rglob('*.py'):
717
+ for py_file in directory.rglob("*.py"):
675
718
  try:
676
- content = py_file.read_text(encoding='utf-8')
719
+ content = py_file.read_text(encoding="utf-8")
677
720
  except Exception:
678
721
  continue
679
-
722
+
680
723
  # 匹配 import 语句
681
724
  # from xxx import yyy
682
725
  # import xxx
683
726
  import_patterns = [
684
- r'^from\s+([\w\.]+)',
685
- r'^import\s+([\w\.]+)',
727
+ r"^from\s+([\w\.]+)",
728
+ r"^import\s+([\w\.]+)",
686
729
  ]
687
-
730
+
688
731
  for pattern in import_patterns:
689
732
  for match in re.finditer(pattern, content, re.MULTILINE):
690
- module = match.group(1).split('.')[0] # 取顶级模块
733
+ module = match.group(1).split(".")[0] # 取顶级模块
691
734
  full_module = match.group(1)
692
-
735
+
693
736
  # 检查是否在映射中
694
737
  if full_module in import_to_package:
695
738
  found_packages.add(import_to_package[full_module])
696
739
  elif module in import_to_package:
697
740
  found_packages.add(import_to_package[module])
698
741
  # 检查常见的下划线包名
699
- elif module.replace('_', '-') in ['langchain-openai', 'langchain-anthropic',
700
- 'langchain-core', 'langchain-community']:
701
- found_packages.add(module.replace('_', '-'))
702
-
742
+ elif module.replace("_", "-") in [
743
+ "langchain-openai",
744
+ "langchain-anthropic",
745
+ "langchain-core",
746
+ "langchain-community",
747
+ ]:
748
+ found_packages.add(module.replace("_", "-"))
749
+
703
750
  # 确保框架相关的核心依赖在列表中
704
- if framework == 'langgraph':
705
- found_packages.add('langgraph')
706
- found_packages.add('langchain')
707
- found_packages.add('langchain-openai')
708
- elif framework == 'deepagents':
709
- found_packages.add('deepagents')
710
- found_packages.add('langgraph')
711
- found_packages.add('langchain')
712
- found_packages.add('langchain-openai')
713
- elif framework == 'langchain':
714
- found_packages.add('langchain')
715
- found_packages.add('langchain-openai')
716
- elif framework == 'adk':
717
- found_packages.add('google-adk')
718
-
751
+ if framework == "langgraph":
752
+ found_packages.add("langgraph")
753
+ found_packages.add("langchain")
754
+ found_packages.add("langchain-openai")
755
+ elif framework == "deepagents":
756
+ found_packages.add("deepagents")
757
+ found_packages.add("langgraph")
758
+ found_packages.add("langchain")
759
+ found_packages.add("langchain-openai")
760
+ elif framework == "langchain":
761
+ found_packages.add("langchain")
762
+ found_packages.add("langchain-openai")
763
+ elif framework == "adk":
764
+ found_packages.add("google-adk")
765
+
719
766
  # 总是添加 python-dotenv
720
- found_packages.add('python-dotenv')
721
-
767
+ found_packages.add("python-dotenv")
768
+
722
769
  # 按字母顺序排序
723
770
  sorted_packages = sorted(found_packages)
724
- return '\n'.join(sorted_packages) + '\n'
771
+ return "\n".join(sorted_packages) + "\n"
725
772
 
726
773
 
727
774
  def _analyze_langgraph_state(content: str) -> dict:
@@ -752,7 +799,9 @@ def _analyze_langgraph_state(content: str) -> dict:
752
799
  preferred = ("query", "question", "prompt", "user_input", "input")
753
800
  input_field = next((field for field in preferred if field in candidates), None)
754
801
 
755
- if candidates and ("TypedDict" in content or "StateGraph(" in content or "langgraph" in content):
802
+ if candidates and (
803
+ "TypedDict" in content or "StateGraph(" in content or "langgraph" in content
804
+ ):
756
805
  return {"kind": "custom", "input_field": input_field}
757
806
  if "StateGraph(" in content or "from langgraph" in content or "import langgraph" in content:
758
807
  return {"kind": "ambiguous", "input_field": input_field}
@@ -789,15 +838,15 @@ def _generate_langgraph_adapter_content(
789
838
  ) -> str:
790
839
  input_field = analysis.get("input_field")
791
840
  if input_field:
792
- return_body = f''' return {{
841
+ return_body = f""" return {{
793
842
  "{input_field}": payload.get("input", ""),
794
- }}'''
843
+ }}"""
795
844
  else:
796
- return_body = ''' # TODO: Map AgentEngine's chat payload to your LangGraph State.
845
+ return_body = """ # TODO: Map AgentEngine's chat payload to your LangGraph State.
797
846
  # Common examples:
798
847
  # return {"query": payload.get("input", "")}
799
848
  # return {"question": payload.get("input", ""), "context": []}
800
- return dict(payload)'''
849
+ return dict(payload)"""
801
850
 
802
851
  return f'''"""
803
852
  AgentEngine adapter generated for a LangGraph project.
@@ -919,13 +968,15 @@ def _detect_deepagents_service_project(
919
968
  def _generate_deepagents_service_adapter_content(analysis: dict) -> str:
920
969
  init_module = analysis["init_module"]
921
970
  runnable_module = analysis.get("runnable_module")
922
- runnable_module_constant = f'RUNNABLE_MODULE = "{runnable_module}"' if runnable_module else "RUNNABLE_MODULE = None"
971
+ runnable_module_constant = (
972
+ f'RUNNABLE_MODULE = "{runnable_module}"' if runnable_module else "RUNNABLE_MODULE = None"
973
+ )
923
974
  runnable_build = " return None\n"
924
975
  if runnable_module:
925
976
  runnable_build = """ try:
926
977
  runnable_module = importlib.import_module(RUNNABLE_MODULE, __package__)
927
978
  deep_agent_runnable = getattr(runnable_module, "DeepAgentRunnable")
928
- return deep_agent_runnable(agent, _NullLangfuseManager())
979
+ return deep_agent_runnable(agent, _NullObservabilityManager())
929
980
  except Exception:
930
981
  return None
931
982
  """
@@ -941,20 +992,11 @@ import asyncio
941
992
  import importlib
942
993
  from typing import Any
943
994
 
944
- try:
945
- from langchain_core.callbacks import BaseCallbackHandler
946
- except Exception: # pragma: no cover - dependency may be absent during static checks
947
- BaseCallbackHandler = object
948
-
949
995
  INIT_MODULE = "{init_module}"
950
996
  {runnable_module_constant}
951
997
 
952
- class _NoopCallbackHandler(BaseCallbackHandler):
953
- pass
954
-
955
-
956
- class _NullLangfuseManager:
957
- callback_handler = _NoopCallbackHandler()
998
+ class _NullObservabilityManager:
999
+ callback_handler = None
958
1000
 
959
1001
 
960
1002
  class AgentEngineDeepAgentsServiceAdapter:
@@ -1040,7 +1082,14 @@ class AgentEngineDeepAgentsServiceAdapter:
1040
1082
  return self._normalize_result(result)
1041
1083
 
1042
1084
  if hasattr(self._agent, "ainvoke"):
1043
- result = await self._agent.ainvoke({{"messages": payload.get("messages", [])}} if isinstance(payload, dict) and payload.get("messages") else payload, config=config, **kwargs)
1085
+ agent_payload = (
1086
+ {{"messages": payload.get("messages", [])}}
1087
+ if isinstance(payload, dict) and payload.get("messages")
1088
+ else payload
1089
+ )
1090
+ result = await self._agent.ainvoke(
1091
+ agent_payload, config=config, **kwargs
1092
+ )
1044
1093
  return self._normalize_result(result)
1045
1094
  result = self._agent.invoke(payload, config=config, **kwargs)
1046
1095
  return self._normalize_result(result)
@@ -1050,7 +1099,10 @@ class AgentEngineDeepAgentsServiceAdapter:
1050
1099
  loop = asyncio.get_running_loop()
1051
1100
  except RuntimeError:
1052
1101
  return asyncio.run(self.ainvoke(payload, config=config, **kwargs))
1053
- raise RuntimeError("Synchronous invoke cannot run while an event loop is already active; use ainvoke instead")
1102
+ raise RuntimeError(
1103
+ "Synchronous invoke cannot run while an event loop is already active; "
1104
+ "use ainvoke instead"
1105
+ )
1054
1106
 
1055
1107
 
1056
1108
  def ksadk_prepare_state(payload: dict, session_context: dict) -> dict:
@@ -1093,55 +1145,55 @@ def _wrap_agent_file(from_agent_path: Path, project_name: str, framework: str, a
1093
1145
  """包装单个 Agent 文件到新项目"""
1094
1146
  project_path = Path(project_name)
1095
1147
  package_name = _runtime_package_name_or_exit(project_path.name)
1096
-
1148
+
1097
1149
  if project_path.exists():
1098
1150
  print_error(f"目录 '{project_name}' 已存在")
1099
1151
  raise SystemExit(1)
1100
-
1152
+
1101
1153
  print_title("包装 Agent 文件")
1102
1154
  print_kv("创建项目", project_name)
1103
1155
  print_kv("框架", framework)
1104
1156
  print_kv("包装文件", str(from_agent_path))
1105
1157
  print_kv("Agent 变量", agent_var)
1106
-
1158
+
1107
1159
  # 创建目录
1108
1160
  (project_path / package_name).mkdir(parents=True)
1109
-
1161
+
1110
1162
  # 复制源文件并修复 .env 路径
1111
1163
  source_filename = from_agent_path.name
1112
1164
  dest_path = project_path / package_name / source_filename
1113
-
1165
+
1114
1166
  # 读取源文件内容
1115
- source_content = from_agent_path.read_text(encoding='utf-8')
1116
-
1167
+ source_content = from_agent_path.read_text(encoding="utf-8")
1168
+
1117
1169
  # 修复 load_dotenv 路径:parent -> parent.parent (因为文件被移到了子目录)
1118
1170
  fixed_content = re.sub(
1119
1171
  r'(load_dotenv\s*\(\s*Path\s*\(\s*__file__\s*\)\s*\.parent)(\s*/\s*["\']\.env["\'])',
1120
- r'\1.parent\2',
1121
- source_content
1172
+ r"\1.parent\2",
1173
+ source_content,
1122
1174
  )
1123
-
1175
+
1124
1176
  if fixed_content != source_content:
1125
1177
  print_info("已自动修复 .env 加载路径")
1126
-
1178
+
1127
1179
  # 写入目标文件
1128
- dest_path.write_text(fixed_content, encoding='utf-8')
1129
-
1180
+ dest_path.write_text(fixed_content, encoding="utf-8")
1181
+
1130
1182
  # 检测全局配置
1131
1183
  from ksadk.configs.global_config import (
1132
- global_config_exists,
1133
1184
  get_env_from_global_config,
1185
+ global_config_exists,
1134
1186
  )
1135
-
1187
+
1136
1188
  global_env = {}
1137
1189
  if global_config_exists():
1138
1190
  global_env = get_env_from_global_config()
1139
1191
  if global_env:
1140
- print_info("检测到全局配置,已自动填充凭证")
1141
-
1192
+ print_info("检测到全局配置;项目 .env 仅保留非敏感默认值,凭证不会被复制")
1193
+
1142
1194
  # 生成 .env
1143
1195
  (project_path / ".env").write_text(_generate_env_content(global_env), encoding="utf-8-sig")
1144
-
1196
+
1145
1197
  # LangGraph custom-state 项目生成 adapter,避免直接猜业务 State 语义。
1146
1198
  entry_relative = Path(source_filename)
1147
1199
  export_agent_var = agent_var
@@ -1174,23 +1226,29 @@ def _wrap_agent_file(from_agent_path: Path, project_name: str, framework: str, a
1174
1226
 
1175
1227
  # 生成 agentengine.yaml
1176
1228
  entry_module = entry_relative.with_suffix("").name
1177
- (project_path / "agentengine.yaml").write_text(f"""# AgentEngine 项目配置 (Wrapped)
1229
+ (project_path / "agentengine.yaml").write_text(
1230
+ f"""# AgentEngine 项目配置 (Wrapped)
1178
1231
  name: {package_name}
1179
1232
  version: "1.0.0"
1180
1233
 
1181
1234
  framework: {framework}
1182
1235
  entry_point: {package_name}/{entry_relative}
1183
1236
  agent_variable: {export_agent_var}
1184
- """, encoding="utf-8-sig")
1185
-
1237
+ """,
1238
+ encoding="utf-8-sig",
1239
+ )
1240
+
1186
1241
  # 生成 __init__.py
1187
- (project_path / package_name / "__init__.py").write_text(f'''"""
1242
+ (project_path / package_name / "__init__.py").write_text(
1243
+ f'''"""
1188
1244
  {project_name} - Wrapped Agent
1189
1245
  """
1190
1246
  from .{entry_module} import {export_agent_var} as root_agent
1191
1247
  __all__ = ["root_agent"]
1192
- ''', encoding="utf-8-sig")
1193
-
1248
+ ''',
1249
+ encoding="utf-8-sig",
1250
+ )
1251
+
1194
1252
  # 生成 requirements.txt
1195
1253
  reqs = ""
1196
1254
  if framework == "langchain":
@@ -1202,9 +1260,10 @@ __all__ = ["root_agent"]
1202
1260
  elif framework == "adk":
1203
1261
  reqs = "google-adk\npython-dotenv\n"
1204
1262
  (project_path / "requirements.txt").write_text(reqs, encoding="utf-8")
1205
-
1263
+
1206
1264
  # 生成 README.md
1207
- (project_path / "README.md").write_text(f"""# {project_name}
1265
+ (project_path / "README.md").write_text(
1266
+ f"""# {project_name}
1208
1267
 
1209
1268
  Wrapped Agent project (from `{from_agent_path.name}`).
1210
1269
 
@@ -1214,36 +1273,36 @@ Wrapped Agent project (from `{from_agent_path.name}`).
1214
1273
  cd {project_name}
1215
1274
  agentengine run -i .
1216
1275
  ```
1217
- """, encoding="utf-8-sig")
1218
-
1276
+ """,
1277
+ encoding="utf-8-sig",
1278
+ )
1279
+
1219
1280
  print_success("包装完成")
1220
1281
  print_rule("快速开始")
1221
1282
  _print_quick_start_commands(project_name, ["agentengine run -i ."])
1222
1283
 
1223
1284
 
1224
- def _wrap_agent_directory(from_agent_dir: Path, project_name: str, framework: str,
1225
- entry_file: Path, agent_var: str):
1285
+ def _wrap_agent_directory(
1286
+ from_agent_dir: Path, project_name: str, framework: str, entry_file: Path, agent_var: str
1287
+ ):
1226
1288
  """包装 Agent 目录到新项目"""
1227
- import shutil
1228
-
1289
+
1229
1290
  project_path = Path(project_name)
1230
1291
  package_name = _runtime_package_name_or_exit(project_path.name)
1231
- source_dir_name = from_agent_dir.name
1232
-
1233
1292
  if project_path.exists():
1234
1293
  print_error(f"目录 '{project_name}' 已存在")
1235
1294
  raise SystemExit(1)
1236
-
1295
+
1237
1296
  print_title("包装 Agent 目录")
1238
1297
  print_kv("创建项目", project_name)
1239
1298
  print_kv("框架", framework)
1240
1299
  print_kv("包装目录", str(from_agent_dir))
1241
1300
  print_kv("入口文件", entry_file.name)
1242
1301
  print_kv("Agent 变量", agent_var)
1243
-
1302
+
1244
1303
  # 创建项目目录
1245
1304
  project_path.mkdir(parents=True)
1246
-
1305
+
1247
1306
  # 复制整个源目录到项目中(作为 package)
1248
1307
  dest_package_path = project_path / package_name
1249
1308
  ignore_names = {
@@ -1272,42 +1331,46 @@ def _wrap_agent_directory(from_agent_dir: Path, project_name: str, framework: st
1272
1331
  return ignored
1273
1332
 
1274
1333
  shutil.copytree(from_agent_dir, dest_package_path, ignore=_ignore_copytree)
1275
-
1334
+
1276
1335
  print_info(f"已复制 {sum(1 for _ in dest_package_path.rglob('*.py'))} 个 Python 文件")
1277
-
1336
+
1278
1337
  # 递归修复 .env 路径
1279
1338
  fixed_count = _fix_dotenv_paths_recursive(dest_package_path, depth=2)
1280
1339
  if fixed_count > 0:
1281
1340
  print_info(f"已自动修复 {fixed_count} 个文件的 .env 加载路径")
1282
-
1341
+
1283
1342
  # 修复嵌套目录导入路径
1284
1343
  # 查找源目录中的子目录(作为 Python 包)
1285
- subdirs = [d.name for d in from_agent_dir.iterdir()
1286
- if d.is_dir() and not d.name.startswith('.') and not d.name.startswith('_')
1287
- and (d / '__init__.py').exists()]
1288
-
1344
+ subdirs = [
1345
+ d.name
1346
+ for d in from_agent_dir.iterdir()
1347
+ if d.is_dir()
1348
+ and not d.name.startswith(".")
1349
+ and not d.name.startswith("_")
1350
+ and (d / "__init__.py").exists()
1351
+ ]
1352
+
1289
1353
  if subdirs:
1290
1354
  # 修复入口文件中的导入
1291
1355
  dest_entry_file = dest_package_path / entry_file.relative_to(from_agent_dir)
1292
1356
  if _fix_nested_imports(dest_entry_file, subdirs):
1293
1357
  print_info(f"已修复嵌套目录导入: {', '.join(subdirs)}")
1294
-
1295
-
1358
+
1296
1359
  # 检测全局配置
1297
1360
  from ksadk.configs.global_config import (
1298
- global_config_exists,
1299
1361
  get_env_from_global_config,
1362
+ global_config_exists,
1300
1363
  )
1301
-
1364
+
1302
1365
  global_env = {}
1303
1366
  if global_config_exists():
1304
1367
  global_env = get_env_from_global_config()
1305
1368
  if global_env:
1306
- print_info("检测到全局配置,已自动填充凭证")
1307
-
1369
+ print_info("检测到全局配置;项目 .env 仅保留非敏感默认值,凭证不会被复制")
1370
+
1308
1371
  # 生成 .env
1309
1372
  (project_path / ".env").write_text(_generate_env_content(global_env), encoding="utf-8-sig")
1310
-
1373
+
1311
1374
  # 生成 agentengine.yaml
1312
1375
  # entry_point 相对于项目根目录
1313
1376
  entry_relative = entry_file.relative_to(from_agent_dir)
@@ -1350,72 +1413,79 @@ def _wrap_agent_directory(from_agent_dir: Path, project_name: str, framework: st
1350
1413
  export_agent_var = "root_agent"
1351
1414
  print_warn("LangGraph state 检测: ambiguous adapter generated, review required")
1352
1415
 
1353
- (project_path / "agentengine.yaml").write_text(f"""# AgentEngine 项目配置 (Wrapped Directory)
1416
+ (project_path / "agentengine.yaml").write_text(
1417
+ f"""# AgentEngine 项目配置 (Wrapped Directory)
1354
1418
  name: {package_name}
1355
1419
  version: "1.0.0"
1356
1420
 
1357
1421
  framework: {framework}
1358
1422
  entry_point: {package_name}/{entry_relative}
1359
1423
  agent_variable: {export_agent_var}
1360
- """, encoding="utf-8-sig")
1361
-
1424
+ """,
1425
+ encoding="utf-8-sig",
1426
+ )
1427
+
1362
1428
  # 确保 __init__.py 正确导出 root_agent
1363
1429
  init_file = dest_package_path / "__init__.py"
1364
1430
  entry_module = ".".join(entry_relative.with_suffix("").parts) # e.g. src.agentengine_adapter
1365
1431
  expected_export_line = f"from .{entry_module} import {export_agent_var} as root_agent"
1366
-
1432
+
1367
1433
  # 检查现有 __init__.py 是否已导出 root_agent
1368
1434
  init_has_export = False
1369
1435
  if init_file.exists():
1370
- init_content = init_file.read_text(encoding='utf-8')
1436
+ init_content = init_file.read_text(encoding="utf-8")
1371
1437
  if expected_export_line in init_content:
1372
1438
  init_has_export = True
1373
-
1439
+
1374
1440
  if not init_has_export:
1375
1441
  # 追加或创建导出语句
1376
- export_code = f'''
1442
+ export_code = f"""
1377
1443
  # AgentEngine 导出 (自动添加)
1378
1444
  {expected_export_line}
1379
1445
  __all__ = ["root_agent"]
1380
- '''
1446
+ """
1381
1447
  if init_file.exists():
1382
1448
  # 追加到现有文件
1383
- with open(init_file, 'a', encoding='utf-8') as f:
1449
+ with open(init_file, "a", encoding="utf-8") as f:
1384
1450
  f.write(export_code)
1385
1451
  print_info("已修复 __init__.py 导出")
1386
1452
  else:
1387
- init_file.write_text(f'''"""
1453
+ init_file.write_text(
1454
+ f'''"""
1388
1455
  {project_name} - Wrapped Agent
1389
1456
  """
1390
1457
  {expected_export_line}
1391
1458
  __all__ = ["root_agent"]
1392
- ''', encoding="utf-8-sig")
1393
-
1459
+ ''',
1460
+ encoding="utf-8-sig",
1461
+ )
1462
+
1394
1463
  # 处理 requirements.txt
1395
1464
  source_requirements = from_agent_dir / "requirements.txt"
1396
1465
  dest_requirements = project_path / "requirements.txt"
1397
-
1466
+
1398
1467
  if source_requirements.exists():
1399
1468
  # 如果源目录有 requirements.txt,复制并补充必要的依赖
1400
1469
  import shutil as shutil_req
1470
+
1401
1471
  shutil_req.copy(source_requirements, dest_requirements)
1402
1472
  print_info("已复制 requirements.txt")
1403
-
1473
+
1404
1474
  # 检查是否缺少必要依赖,追加
1405
- existing_reqs = dest_requirements.read_text(encoding='utf-8').lower()
1475
+ existing_reqs = dest_requirements.read_text(encoding="utf-8").lower()
1406
1476
  missing = []
1407
- if framework == "langgraph" and 'langgraph' not in existing_reqs:
1477
+ if framework == "langgraph" and "langgraph" not in existing_reqs:
1408
1478
  missing.append("langgraph")
1409
1479
  if framework == "deepagents":
1410
- if 'deepagents' not in existing_reqs:
1480
+ if "deepagents" not in existing_reqs:
1411
1481
  missing.append("deepagents")
1412
- if 'langgraph' not in existing_reqs:
1482
+ if "langgraph" not in existing_reqs:
1413
1483
  missing.append("langgraph")
1414
- if 'python-dotenv' not in existing_reqs and 'dotenv' not in existing_reqs:
1484
+ if "python-dotenv" not in existing_reqs and "dotenv" not in existing_reqs:
1415
1485
  missing.append("python-dotenv")
1416
-
1486
+
1417
1487
  if missing:
1418
- with open(dest_requirements, 'a', encoding='utf-8') as f:
1488
+ with open(dest_requirements, "a", encoding="utf-8") as f:
1419
1489
  f.write("\n# Added by agentengine\n")
1420
1490
  for pkg in missing:
1421
1491
  f.write(f"{pkg}\n")
@@ -1425,9 +1495,10 @@ __all__ = ["root_agent"]
1425
1495
  reqs = _generate_requirements_from_imports(dest_package_path, framework)
1426
1496
  dest_requirements.write_text(reqs, encoding="utf-8")
1427
1497
  print_info(f"已自动生成 requirements.txt ({reqs.count(chr(10))} 个依赖)")
1428
-
1498
+
1429
1499
  # 生成 README.md
1430
- (project_path / "README.md").write_text(f"""# {project_name}
1500
+ (project_path / "README.md").write_text(
1501
+ f"""# {project_name}
1431
1502
 
1432
1503
  Wrapped Agent project (from `{from_agent_dir.name}/`).
1433
1504
 
@@ -1437,14 +1508,16 @@ Wrapped Agent project (from `{from_agent_dir.name}/`).
1437
1508
  cd {project_name}
1438
1509
  agentengine run -i .
1439
1510
  ```
1440
- """, encoding="utf-8-sig")
1441
-
1511
+ """,
1512
+ encoding="utf-8-sig",
1513
+ )
1514
+
1442
1515
  # === 运行时验证 ===
1443
1516
  print_rule("验证 Agent 加载")
1444
1517
  import subprocess
1445
1518
  import sys
1446
-
1447
- verify_code = f'''
1519
+
1520
+ verify_code = f"""
1448
1521
  import sys
1449
1522
  sys.path.insert(0, ".")
1450
1523
  try:
@@ -1453,16 +1526,16 @@ try:
1453
1526
  except Exception as e:
1454
1527
  print("ERROR:" + str(e))
1455
1528
  sys.exit(1)
1456
- '''
1457
-
1529
+ """
1530
+
1458
1531
  result = subprocess.run(
1459
1532
  [sys.executable, "-c", verify_code],
1460
1533
  cwd=str(project_path),
1461
1534
  capture_output=True,
1462
1535
  text=True,
1463
- timeout=30
1536
+ timeout=30,
1464
1537
  )
1465
-
1538
+
1466
1539
  if result.returncode == 0:
1467
1540
  output = result.stdout.strip()
1468
1541
  if output.startswith("TYPE:"):
@@ -1474,47 +1547,16 @@ except Exception as e:
1474
1547
  error_msg = result.stderr or result.stdout
1475
1548
  print_warn(f"Agent 加载警告: {error_msg[:200]}")
1476
1549
  print_info("提示: 请检查依赖是否已安装,或代码是否有错误")
1477
-
1550
+
1478
1551
  print_success("包装完成")
1479
1552
  print_rule("快速开始")
1480
1553
  _print_quick_start_commands(project_name, ["agentengine run -i ."])
1481
1554
 
1482
1555
 
1483
- def _write_hermes_project_template(project_path: Path, project_name: str, package_name: str) -> None:
1484
- """生成 Hermes container-first 项目骨架。"""
1485
- repo_template_root = Path(__file__).resolve().parents[2] / "deploy" / "hermes"
1486
- if repo_template_root.exists():
1487
- replacements = {
1488
- "{{PROJECT_NAME}}": project_name,
1489
- "{{PACKAGE_NAME}}": package_name,
1490
- }
1491
- for source in repo_template_root.rglob("*"):
1492
- relative = source.relative_to(repo_template_root)
1493
- if source.is_dir():
1494
- (project_path / relative).mkdir(parents=True, exist_ok=True)
1495
- continue
1496
- destination_relative = relative
1497
- if source.name.endswith(".template"):
1498
- destination_relative = relative.with_name(source.name[:-9])
1499
- content = source.read_text(encoding="utf-8")
1500
- for key, value in replacements.items():
1501
- content = content.replace(key, value)
1502
- destination = project_path / destination_relative
1503
- destination.parent.mkdir(parents=True, exist_ok=True)
1504
- destination.write_text(content, encoding="utf-8-sig")
1505
- continue
1506
- destination = project_path / destination_relative
1507
- destination.parent.mkdir(parents=True, exist_ok=True)
1508
- shutil.copy2(source, destination)
1509
- entrypoint = project_path / "entrypoint.sh"
1510
- if entrypoint.exists():
1511
- entrypoint.chmod(0o755)
1512
- return
1513
-
1514
- runtime_dir = project_path / "runtime"
1515
- runtime_dir.mkdir(parents=True, exist_ok=True)
1516
-
1517
- (project_path / "agentengine.yaml").write_text(f"""# AgentEngine Hermes 项目配置
1556
+ def _write_hermes_project_config(project_path: Path, package_name: str) -> None:
1557
+ """Write the deployable Hermes config; the runtime image is platform-owned."""
1558
+ (project_path / "agentengine.yaml").write_text(
1559
+ f"""# AgentEngine Hermes project configuration
1518
1560
  name: {package_name}
1519
1561
  version: "1.0.0"
1520
1562
 
@@ -1532,353 +1574,92 @@ deploy:
1532
1574
  min_replicas: 1
1533
1575
  max_replicas: 1
1534
1576
  concurrency: 1000
1535
- """, encoding="utf-8-sig")
1536
-
1537
- (project_path / "Dockerfile").write_text("""FROM python:3.12-slim
1538
-
1539
- ENV PYTHONUNBUFFERED=1 \\
1540
- PYTHONDONTWRITEBYTECODE=1 \\
1541
- PIP_NO_CACHE_DIR=1 \\
1542
- PORT=8080 \\
1543
- API_SERVER_HOST=127.0.0.1 \\
1544
- API_SERVER_PORT=8642 \\
1545
- HERMES_DASHBOARD_HOST=127.0.0.1 \\
1546
- HERMES_DASHBOARD_PORT=9119
1547
-
1548
- WORKDIR /app
1549
-
1550
- RUN apt-get update \\
1551
- && apt-get install -y --no-install-recommends bash curl tini \\
1552
- && rm -rf /var/lib/apt/lists/*
1553
-
1554
- RUN pip install --no-cache-dir \\
1555
- "fastapi>=0.100" \\
1556
- "uvicorn[standard]>=0.23" \\
1557
- "httpx>=0.24" \\
1558
- "pyyaml>=6.0" \\
1559
- "python-dotenv>=1.0" \\
1560
- "hermes-agent==0.9.0"
1561
-
1562
- COPY runtime ./runtime
1563
- COPY entrypoint.sh ./entrypoint.sh
1564
- RUN chmod +x /app/entrypoint.sh
1565
-
1566
- EXPOSE 8080
1567
-
1568
- ENTRYPOINT ["tini", "--"]
1569
- CMD ["/app/entrypoint.sh"]
1570
- """, encoding="utf-8")
1571
-
1572
- (project_path / "entrypoint.sh").write_text("""#!/usr/bin/env bash
1573
- set -euo pipefail
1574
-
1575
- export HOME="${HOME:-/home/agent}"
1576
- export PORT="${PORT:-8080}"
1577
- export API_SERVER_HOST="${API_SERVER_HOST:-127.0.0.1}"
1578
- export API_SERVER_PORT="${API_SERVER_PORT:-8642}"
1579
- export HERMES_DASHBOARD_HOST="${HERMES_DASHBOARD_HOST:-127.0.0.1}"
1580
- export HERMES_DASHBOARD_PORT="${HERMES_DASHBOARD_PORT:-9119}"
1581
- export API_SERVER_ENABLED="${API_SERVER_ENABLED:-true}"
1582
-
1583
- mkdir -p "${HOME}/.hermes"
1584
-
1585
- cat > "${HOME}/.hermes/.env" <<EOF
1586
- OPENAI_API_KEY=${OPENAI_API_KEY:-}
1587
- OPENAI_BASE_URL=${OPENAI_BASE_URL:-}
1588
- OPENAI_MODEL_NAME=${OPENAI_MODEL_NAME:-}
1589
- API_SERVER_ENABLED=${API_SERVER_ENABLED}
1590
- API_SERVER_KEY=${API_SERVER_KEY:-}
1591
- API_SERVER_HOST=${API_SERVER_HOST}
1592
- API_SERVER_PORT=${API_SERVER_PORT}
1593
- EOF
1594
-
1595
- cat > "${HOME}/.hermes/config.yaml" <<EOF
1596
- model:
1597
- provider: custom
1598
- default: "${OPENAI_MODEL_NAME:-}"
1599
- base_url: "${OPENAI_BASE_URL:-}"
1600
- api_server:
1601
- enabled: true
1602
- host: "${API_SERVER_HOST}"
1603
- port: ${API_SERVER_PORT}
1604
- EOF
1605
-
1606
- hermes gateway run --replace &
1607
- HERMES_API_PID=$!
1608
-
1609
- hermes dashboard --host "${HERMES_DASHBOARD_HOST}" --port "${HERMES_DASHBOARD_PORT}" --no-open &
1610
- HERMES_DASHBOARD_PID=$!
1611
-
1612
- cleanup() {
1613
- kill "${HERMES_API_PID}" "${HERMES_DASHBOARD_PID}" 2>/dev/null || true
1614
- }
1615
- trap cleanup EXIT
1616
-
1617
- exec uvicorn runtime.app:app --host 0.0.0.0 --port "${PORT}"
1618
- """, encoding="utf-8")
1619
-
1620
- (runtime_dir / "__init__.py").write_text("", encoding="utf-8")
1621
- (runtime_dir / "app.py").write_text("""from __future__ import annotations
1622
-
1623
- import asyncio
1624
- import contextlib
1625
- import json
1626
- import os
1627
- import pty
1628
- import select
1629
- import signal
1630
- import termios
1631
- from typing import Iterable
1632
-
1633
- import httpx
1634
- from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
1635
- from fastapi.responses import Response
1636
- from starlette.websockets import WebSocketState
1637
-
1638
-
1639
- TERMINAL_SUBPROTOCOL = "ks-terminal.v1"
1640
- SHELL_METACHARS = set("|&;<>()$`\\\\\\n\\r")
1641
- SINGLE_READONLY = {"status", "doctor", "version", "insights"}
1642
- NESTED_READONLY = {
1643
- "sessions": {"list": (2, 2), "show": (3, 3), "export": (3, 3)},
1644
- "config": {"show": (2, 2), "check": (2, 2), "path": (2, 2), "env-path": (2, 2)},
1645
- "skills": {"list": (2, 2), "audit": (2, 2), "check": (2, 2)},
1646
- "tools": {"list": (2, 2)},
1647
- "cron": {"list": (2, 2), "status": (2, 2)},
1648
- "gateway": {"status": (2, 2)},
1649
- }
1650
-
1651
- app = FastAPI()
1652
-
1653
-
1654
- def _api_base() -> str:
1655
- return f"http://{os.getenv('API_SERVER_HOST', '127.0.0.1')}:{os.getenv('API_SERVER_PORT', '8642')}"
1656
-
1657
-
1658
- def _dashboard_base() -> str:
1659
- return f"http://{os.getenv('HERMES_DASHBOARD_HOST', '127.0.0.1')}:{os.getenv('HERMES_DASHBOARD_PORT', '9119')}"
1660
-
1661
-
1662
- def _validate_exec_argv(argv: Iterable[str]) -> list[str]:
1663
- normalized = [str(item).strip() for item in argv]
1664
- if not normalized:
1665
- raise ValueError("missing argv")
1666
- for item in normalized:
1667
- if not item or item.startswith("-") or any(char in SHELL_METACHARS for char in item):
1668
- raise ValueError(f"unsafe argv: {item}")
1669
- if normalized[0] in SINGLE_READONLY:
1670
- if len(normalized) != 1:
1671
- raise ValueError("unsupported argv")
1672
- return normalized
1673
- nested = NESTED_READONLY.get(normalized[0])
1674
- if not nested or len(normalized) < 2:
1675
- raise ValueError("unsupported argv")
1676
- bounds = nested.get(normalized[1])
1677
- if not bounds:
1678
- raise ValueError("unsupported argv")
1679
- if not (bounds[0] <= len(normalized) <= bounds[1]):
1680
- raise ValueError("unsupported argv")
1681
- return normalized
1682
-
1683
-
1684
- async def _proxy_http(request: Request, base_url: str, path: str) -> Response:
1685
- target = f"{base_url}/{path.lstrip('/')}"
1686
- if request.url.query:
1687
- target = f"{target}?{request.url.query}"
1688
- headers = {
1689
- key: value
1690
- for key, value in request.headers.items()
1691
- if key.lower() not in {"host", "content-length"}
1692
- }
1693
- async with httpx.AsyncClient(timeout=None) as client:
1694
- upstream = await client.request(
1695
- request.method,
1696
- target,
1697
- headers=headers,
1698
- content=await request.body(),
1699
- )
1700
- response_headers = {
1701
- key: value
1702
- for key, value in upstream.headers.items()
1703
- if key.lower() not in {"content-encoding", "transfer-encoding", "connection"}
1704
- }
1705
- return Response(upstream.content, status_code=upstream.status_code, headers=response_headers)
1706
-
1707
-
1708
- @app.get("/health")
1709
- async def health() -> dict:
1710
- return {"ok": True}
1711
-
1712
-
1713
- @app.api_route("/v1/{path:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"])
1714
- async def proxy_api(path: str, request: Request) -> Response:
1715
- return await _proxy_http(request, _api_base(), f"v1/{path}")
1716
-
1717
-
1718
- def _set_winsize(fd: int, rows: int, cols: int) -> None:
1719
- termios.tcsetwinsize(fd, (int(rows or 24), int(cols or 80)))
1720
-
1721
-
1722
- async def _pty_reader(ws: WebSocket, fd: int) -> None:
1723
- loop = asyncio.get_running_loop()
1724
- while True:
1725
- await loop.run_in_executor(None, lambda: select.select([fd], [], [], None))
1726
- data = os.read(fd, 4096)
1727
- if not data:
1728
- return
1729
- await ws.send_bytes(data)
1730
-
1577
+ """,
1578
+ encoding="utf-8-sig",
1579
+ )
1731
1580
 
1732
- async def _wait_process(pid: int) -> int:
1733
- loop = asyncio.get_running_loop()
1734
- _, status = await loop.run_in_executor(None, os.waitpid, pid, 0)
1735
- if os.WIFEXITED(status):
1736
- return os.WEXITSTATUS(status)
1737
- if os.WIFSIGNALED(status):
1738
- return 128 + os.WTERMSIG(status)
1739
- return status
1740
1581
 
1582
+ def _write_codex_project_config(project_path: Path, package_name: str) -> None:
1583
+ """Write the minimal codex runtime project:yaml 驱动,无 package/agent.py。
1741
1584
 
1742
- @app.websocket("/_ksadk/terminal/ws")
1743
- async def terminal_ws(ws: WebSocket) -> None:
1744
- if TERMINAL_SUBPROTOCOL not in (ws.headers.get("sec-websocket-protocol") or ""):
1745
- await ws.close(code=4400, reason="missing ks-terminal.v1 subprotocol")
1746
- return
1747
- await ws.accept(subprotocol=TERMINAL_SUBPROTOCOL)
1748
- pid = None
1749
- fd = None
1750
- receive_task = None
1751
- reader_task = None
1752
- wait_task = None
1753
- try:
1754
- first = await ws.receive_text()
1755
- payload = json.loads(first)
1756
- if payload.get("type") != "start":
1757
- raise ValueError("first frame must be start")
1758
- mode = payload.get("mode")
1759
- argv = payload.get("argv") or []
1760
- if mode == "tui":
1761
- command = ["hermes", "chat"]
1762
- elif mode == "exec":
1763
- command = ["hermes", *_validate_exec_argv(argv)]
1764
- else:
1765
- raise ValueError("unsupported mode")
1766
-
1767
- pid, fd = pty.fork()
1768
- if pid == 0:
1769
- os.execvp(command[0], command)
1770
-
1771
- _set_winsize(fd, int(payload.get("rows") or 24), int(payload.get("cols") or 80))
1772
- await ws.send_text(json.dumps({"type": "ready"}))
1773
- reader_task = asyncio.create_task(_pty_reader(ws, fd))
1774
- wait_task = asyncio.create_task(_wait_process(pid))
1775
- receive_task = asyncio.create_task(ws.receive())
1776
-
1777
- while True:
1778
- done, _pending = await asyncio.wait({wait_task, receive_task}, return_when=asyncio.FIRST_COMPLETED)
1779
- if wait_task in done:
1780
- if reader_task:
1781
- reader_task.cancel()
1782
- if receive_task:
1783
- receive_task.cancel()
1784
- code = wait_task.result()
1785
- if ws.client_state == WebSocketState.CONNECTED:
1786
- await ws.send_text(json.dumps({"type": "exit", "code": code}))
1787
- return
1585
+ codex 的 agent 逻辑由 prompt 承载,所以只生成
1586
+ canonical agentengine.yaml(framework: codex,model+prompt)+ requirements +
1587
+ README。model/prompt 经 CodexRuntimeAdapter 传入 codex thread(开发者指令)。
1588
+ """
1589
+ (project_path / "agentengine.yaml").write_text(
1590
+ f"""# AgentEngine codex runtime 项目配置
1591
+ name: {package_name}
1592
+ version: "1.0.0"
1788
1593
 
1789
- message = receive_task.result()
1790
- receive_task = asyncio.create_task(ws.receive())
1791
- if message.get("bytes") is not None:
1792
- os.write(fd, message["bytes"])
1793
- continue
1794
- text = message.get("text")
1795
- if not text:
1796
- continue
1797
- control = json.loads(text)
1798
- if control.get("type") == "resize":
1799
- _set_winsize(fd, int(control.get("rows") or 24), int(control.get("cols") or 80))
1800
- elif control.get("type") == "signal":
1801
- sig = signal.SIGINT if control.get("signal") == "SIGINT" else signal.SIGTERM
1802
- os.kill(pid, sig)
1803
- elif control.get("type") == "stdin_eof":
1804
- os.close(fd)
1805
- fd = None
1806
- except WebSocketDisconnect:
1807
- return
1808
- except Exception as exc:
1809
- if ws.client_state == WebSocketState.CONNECTED:
1810
- await ws.send_text(json.dumps({"type": "error", "message": str(exc)}))
1811
- await ws.close()
1812
- finally:
1813
- for task in (receive_task, reader_task):
1814
- if task and not task.done():
1815
- task.cancel()
1816
- if pid is not None and (wait_task is None or not wait_task.done()):
1817
- with contextlib.suppress(ProcessLookupError):
1818
- os.kill(pid, signal.SIGTERM)
1819
- if wait_task and not wait_task.done():
1820
- wait_task.cancel()
1821
- if fd is not None:
1822
- with contextlib.suppress(OSError):
1823
- os.close(fd)
1824
-
1825
-
1826
- @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"])
1827
- async def proxy_dashboard(path: str, request: Request) -> Response:
1828
- return await _proxy_http(request, _dashboard_base(), path)
1829
- """, encoding="utf-8")
1830
-
1831
- (project_path / "README.md").write_text(f"""# {project_name}
1832
-
1833
- Hermes AgentEngine container-first 项目。
1594
+ # 框架:codex(本地和部署统一使用 CodexRuntimeAdapter)
1595
+ framework: codex
1596
+ artifact_type: ManagedRuntime
1597
+
1598
+ # 托管运行时版本可选;省略时云端由 Runtime catalog 选择默认值。
1599
+ # 本地 `ksadk web` 会使用已安装的 openai-codex 并提示该版本未锁定。
1600
+ runtime:
1601
+ name: codex
1602
+
1603
+ # codex 的模型与开发者指令(CodexRuntimeAdapter 传入 codex thread)
1604
+ model: glm-5.2
1605
+ prompt: |
1606
+ 你是 codex 编码助手。简洁回答,能跑命令验证就跑(shell 工具),中文回复。
1607
+ """,
1608
+ encoding="utf-8-sig",
1609
+ )
1610
+ (project_path / "requirements.txt").write_text(
1611
+ "ksadk[codex]\n",
1612
+ encoding="utf-8", # 无 BOM:pip 解析 BOM 会报 Invalid requirement
1613
+ )
1614
+ (project_path / "README.md").write_text(
1615
+ f"""# {package_name} — codex runtime agent
1834
1616
 
1835
1617
  ## 快速开始
1836
1618
 
1837
1619
  ```bash
1838
- cd {project_name}
1839
-
1840
- # 1. 编辑 .env,填写模型配置
1841
- vim .env
1842
-
1843
- # 2. 部署平台预置 Hermes runtime 镜像
1844
- agentengine hermes deploy
1845
-
1846
- # 3. 打开 Hermes 管理 UI
1847
- agentengine hermes open
1848
-
1849
- # 4. 进入 pod 内 Hermes 原生 TUI
1850
- agentengine invoke
1851
-
1852
- # 5. 使用统一 hosted chat
1853
- agentengine hermes open --chat
1854
-
1855
- # 6. 受限只读运维子命令
1856
- agentengine hermes exec <agent> -- status
1857
-
1858
- # 7. Pairing 审批透传
1859
- agentengine hermes pairing <agent> -- list
1620
+ # 1. 编辑 .env 填 OPENAI_API_KEY / OPENAI_BASE_URL / OPENAI_MODEL_NAME
1621
+ # 2. 本地运行(浏览器对话,codex 自动探测并启用代理)
1622
+ agentengine web .
1623
+ # 或
1624
+ ksadk web .
1860
1625
  ```
1861
1626
 
1862
- ## Runtime Contract
1863
-
1864
- - `/` 反代到 Hermes dashboard 管理 UI
1865
- - `/chat` 由 AgentEngine hosted UI/router 处理
1866
- - `/v1/*` 反代到 Hermes OpenAI-compatible API server
1867
- - `/_ksadk/terminal/ws` 提供 `ks-terminal.v1` 原生 TUI/exec/pairing websocket
1868
- """, encoding="utf-8-sig")
1627
+ ## 说明
1628
+
1629
+ - codex 的 agent 逻辑由 `agentengine.yaml` 的 `prompt`(开发者指令)承载,无 agent.py。
1630
+ - codex 自动探测模型协议:OpenAI 官方直连,星流 chat 模型自动启用转换代理。
1631
+ - `agentengine build .` 只生成 YAML manifest bundle,不打包本机 Codex 二进制。若
1632
+ `runtime.version` 未指定,build 需要连接到已配置 Runtime catalog;离线构建请显式锁定版本。
1633
+ - 部署时服务端解析 ManagedRuntime 版本和 Linux 镜像 digest。云端必须已发布 Runtime
1634
+ catalog、对应镜像和内联 manifest 控制面;未发布时请继续使用本地 `ksadk web`,不要把
1635
+ `runtime.version` 随意改成开发机版本,KsADK 不回退为 Code 部署。
1636
+ """,
1637
+ encoding="utf-8-sig",
1638
+ )
1869
1639
 
1870
1640
 
1871
- @click.command(context_settings=dict(help_option_names=['-h', '--help']))
1872
- @click.argument('project_name', required=False)
1873
- @click.option('--framework', '-f', type=click.Choice(['adk', 'langchain', 'langgraph', 'deepagents', 'openclaw', 'hermes']),
1874
- default='langgraph', help='框架类型 (default: langgraph)')
1875
- @click.option('--from-agent', 'from_agent_path', type=click.Path(exists=True),
1876
- help='包装现有 Agent 文件或目录')
1641
+ @click.command(context_settings=dict(help_option_names=["-h", "--help"]))
1642
+ @click.argument("project_name", required=False)
1643
+ @click.option(
1644
+ "--framework",
1645
+ "-f",
1646
+ type=click.Choice(
1647
+ ["adk", "langchain", "langgraph", "deepagents", "openclaw", "hermes", "codex"]
1648
+ ),
1649
+ default="langgraph",
1650
+ help="框架类型 (default: langgraph)",
1651
+ )
1652
+ @click.option(
1653
+ "--from-agent",
1654
+ "from_agent_path",
1655
+ type=click.Path(exists=True),
1656
+ help="包装现有 Agent 文件或目录",
1657
+ )
1877
1658
  def create(project_name: str, framework: str, from_agent_path: str):
1878
1659
  """创建新的 Agent 项目
1879
-
1660
+
1880
1661
  PROJECT_NAME: 项目名称
1881
-
1662
+
1882
1663
  使用 --from-agent 可包装现有代码:
1883
1664
  agentengine init --from-agent ./my_agent.py # 单文件
1884
1665
  agentengine init --from-agent ./my_agent/ # 目录
@@ -1886,158 +1667,151 @@ def create(project_name: str, framework: str, from_agent_path: str):
1886
1667
  # === 包装模式 ===
1887
1668
  if from_agent_path:
1888
1669
  from_path = Path(from_agent_path)
1889
-
1670
+
1890
1671
  # === 目录模式 ===
1891
1672
  if from_path.is_dir():
1892
1673
  print_info(f"扫描目录: {from_path}")
1893
-
1674
+
1894
1675
  # 查找入口文件
1895
1676
  entry_result = _find_entry_file(from_path)
1896
1677
  if not entry_result:
1897
- print_error("未找到有效的入口文件 (agent.py, main.py, __init__.py 或包含 Agent 定义的文件)")
1678
+ print_error(
1679
+ "未找到有效的入口文件 (agent.py, main.py, __init__.py 或包含 Agent 定义的文件)"
1680
+ )
1898
1681
  raise SystemExit(1)
1899
-
1682
+
1900
1683
  entry_file, detected_var = entry_result
1901
1684
  print_info(f"检测到入口: {entry_file.name}")
1902
1685
  print_info(f"检测到变量: {detected_var}")
1903
-
1686
+
1904
1687
  # 检测框架:优先读取已有 agentengine.yaml
1905
- detected_framework = _load_framework_from_agentengine_yaml(from_path) or 'unknown'
1906
- if detected_framework != 'unknown':
1688
+ detected_framework = _load_framework_from_agentengine_yaml(from_path) or "unknown"
1689
+ if detected_framework != "unknown":
1907
1690
  print_info(f"从 agentengine.yaml 检测到框架: {detected_framework}")
1908
1691
  else:
1909
- entry_content = entry_file.read_text(encoding='utf-8')
1692
+ entry_content = entry_file.read_text(encoding="utf-8")
1910
1693
  detected_framework = _detect_framework(entry_content)
1911
-
1694
+
1912
1695
  # 如果入口文件未检测到框架,扫描整个目录
1913
- if detected_framework == 'unknown':
1696
+ if detected_framework == "unknown":
1914
1697
  for py_file in _iter_python_files(from_path):
1915
1698
  try:
1916
- content = py_file.read_text(encoding='utf-8')
1699
+ content = py_file.read_text(encoding="utf-8")
1917
1700
  except Exception:
1918
1701
  continue
1919
1702
  detected_framework = _detect_framework(content)
1920
- if detected_framework != 'unknown':
1703
+ if detected_framework != "unknown":
1921
1704
  break
1922
-
1923
- if detected_framework == 'unknown':
1705
+
1706
+ if detected_framework == "unknown":
1924
1707
  print_warn("无法自动检测框架,将使用默认 langgraph")
1925
- detected_framework = 'langgraph'
1708
+ detected_framework = "langgraph"
1926
1709
  else:
1927
1710
  print_info(f"检测到框架: {detected_framework}")
1928
-
1711
+
1929
1712
  # 如果没有指定项目名,使用目录名
1930
1713
  if not project_name:
1931
- project_name = from_path.name.replace('_', '-')
1932
-
1933
- _wrap_agent_directory(from_path, project_name, detected_framework, entry_file, detected_var)
1714
+ project_name = from_path.name.replace("_", "-")
1715
+
1716
+ _wrap_agent_directory(
1717
+ from_path, project_name, detected_framework, entry_file, detected_var
1718
+ )
1934
1719
  return
1935
-
1720
+
1936
1721
  # === 单文件模式 ===
1937
1722
  else:
1938
- content = from_path.read_text(encoding='utf-8')
1939
-
1723
+ content = from_path.read_text(encoding="utf-8")
1724
+
1940
1725
  # 自动检测框架
1941
1726
  detected_framework = _detect_framework(content)
1942
- if detected_framework == 'unknown':
1727
+ if detected_framework == "unknown":
1943
1728
  print_warn("无法自动检测框架,将使用默认 langgraph")
1944
- detected_framework = 'langgraph'
1729
+ detected_framework = "langgraph"
1945
1730
  else:
1946
1731
  print_info(f"检测到框架: {detected_framework}")
1947
-
1732
+
1948
1733
  # 自动检测 Agent 变量
1949
- detected_var = _detect_agent_variable(content)
1950
- if not detected_var:
1734
+ detected_agent_var = _detect_agent_variable(content)
1735
+ if not detected_agent_var:
1951
1736
  print_warn("无法自动检测 Agent 变量,将使用默认 root_agent")
1952
- detected_var = 'root_agent'
1737
+ detected_agent_var = "root_agent"
1953
1738
  else:
1954
- print_info(f"检测到变量: {detected_var}")
1955
-
1739
+ print_info(f"检测到变量: {detected_agent_var}")
1740
+
1956
1741
  # 如果没有指定项目名,使用文件名
1957
1742
  if not project_name:
1958
- project_name = from_path.stem.replace('_', '-')
1959
-
1960
- _wrap_agent_file(from_path, project_name, detected_framework, detected_var)
1743
+ project_name = from_path.stem.replace("_", "-")
1744
+
1745
+ _wrap_agent_file(from_path, project_name, detected_framework, detected_agent_var)
1961
1746
  return
1962
-
1747
+
1963
1748
  # === 正常模板模式 ===
1964
1749
  # 如果没有提供项目名称,进入交互模式
1965
1750
  if not project_name:
1966
1751
  print_title("初始化新项目")
1967
-
1968
- project_name = questionary.text(
1969
- "请输入项目名称:",
1970
- style=custom_style
1971
- ).ask()
1972
-
1752
+
1753
+ project_name = questionary.text("请输入项目名称:", style=custom_style).ask()
1754
+
1973
1755
  if not project_name:
1974
1756
  print_error("取消创建")
1975
1757
  raise SystemExit(0)
1976
-
1758
+
1977
1759
  framework = questionary.select(
1978
1760
  "请选择开发框架:",
1979
- choices=['langgraph', 'langchain', 'deepagents', 'adk', 'openclaw', 'hermes'],
1980
- default='langgraph',
1981
- style=custom_style
1761
+ choices=["langgraph", "langchain", "deepagents", "adk", "openclaw", "hermes", "codex"],
1762
+ default="langgraph",
1763
+ style=custom_style,
1982
1764
  ).ask()
1983
-
1765
+
1984
1766
  if not framework:
1985
1767
  print_error("取消创建")
1986
1768
  raise SystemExit(0)
1987
-
1769
+
1988
1770
  project_path = Path(project_name)
1989
-
1771
+
1990
1772
  if project_path.exists():
1991
1773
  print_error(f"目录 '{project_name}' 已存在")
1992
1774
  raise SystemExit(1)
1993
-
1775
+
1994
1776
  print_kv("创建项目", project_name)
1995
1777
  print_kv("框架", framework)
1996
-
1778
+
1997
1779
  package_name = _runtime_package_name_or_exit(project_path.name)
1998
1780
  project_path.mkdir(parents=True)
1999
- if framework not in {"openclaw", "hermes"}:
1781
+ if framework not in {"openclaw", "hermes", "codex"}:
2000
1782
  (project_path / package_name).mkdir(parents=True)
2001
-
1783
+
2002
1784
  # 检测全局配置
2003
1785
  from ksadk.configs.global_config import (
2004
- global_config_exists,
2005
1786
  get_env_from_global_config,
1787
+ global_config_exists,
2006
1788
  )
2007
-
1789
+
2008
1790
  global_env = {}
2009
1791
  if global_config_exists():
2010
1792
  global_env = get_env_from_global_config()
2011
1793
  if global_env:
2012
- print_info("检测到全局配置,已自动填充凭证")
2013
-
1794
+ print_info("检测到全局配置;项目 .env 仅保留非敏感默认值,凭证不会被复制")
1795
+
2014
1796
  # .env - 生成配置文件
2015
- # 如果有全局配置,使用全局配置的值;否则使用占位符
2016
- # 如果有全局配置,使用全局配置的值;否则使用空字符串
2017
- api_key = global_env.get("OPENAI_API_KEY", "")
1797
+ # 仅继承非敏感的 endpoint/model/region 默认值;绝不复制凭证。
2018
1798
  base_url = global_env.get("OPENAI_BASE_URL", "")
2019
1799
  model_name = global_env.get("OPENAI_MODEL_NAME", "")
2020
-
2021
- ks_ak = global_env.get("KSYUN_ACCESS_KEY", "")
2022
- ks_sk = global_env.get("KSYUN_SECRET_KEY", "")
1800
+
2023
1801
  ks_region = global_env.get("KSYUN_REGION", "cn-beijing-6")
2024
- ks_account = global_env.get("KSYUN_ACCOUNT_ID", "")
2025
-
1802
+
2026
1803
  # 构建 .env 内容
2027
1804
  if framework == "openclaw":
2028
1805
  env_content = f"""# ======================
2029
1806
  # OpenClaw 标准部署最小配置
2030
1807
  # ======================
2031
- KSYUN_ACCESS_KEY={ks_ak}
2032
- KSYUN_SECRET_KEY={ks_sk}
1808
+ # KSYUN_ACCESS_KEY=
1809
+ # KSYUN_SECRET_KEY=
2033
1810
  KSYUN_REGION={ks_region}
2034
1811
  """
2035
- if ks_account:
2036
- env_content += f"KSYUN_ACCOUNT_ID={ks_account}\n"
2037
- else:
2038
- env_content += "# KSYUN_ACCOUNT_ID=your-account-id\n"
1812
+ env_content += "# KSYUN_ACCOUNT_ID=your-account-id\n"
2039
1813
 
2040
- env_content += f"\nOPENAI_API_KEY={api_key}\n"
1814
+ env_content += "\n# OPENAI_API_KEY=\n"
2041
1815
  if base_url:
2042
1816
  env_content += f"OPENAI_BASE_URL={base_url}\n"
2043
1817
  else:
@@ -2051,18 +1825,13 @@ KSYUN_REGION={ks_region}
2051
1825
  env_content = f"""# ======================
2052
1826
  # Hermes 标准部署最小配置
2053
1827
  # ======================
2054
- KSYUN_ACCESS_KEY={ks_ak}
2055
- KSYUN_SECRET_KEY={ks_sk}
1828
+ # KSYUN_ACCESS_KEY=
1829
+ # KSYUN_SECRET_KEY=
2056
1830
  KSYUN_REGION={ks_region}
2057
1831
  """
2058
- if ks_account:
2059
- env_content += f"KSYUN_ACCOUNT_ID={ks_account}\n"
2060
- else:
2061
- env_content += "# KSYUN_ACCOUNT_ID=your-account-id\n"
1832
+ env_content += "# KSYUN_ACCOUNT_ID=your-account-id\n"
2062
1833
 
2063
- env_content += f"""
2064
- OPENAI_API_KEY={api_key}
2065
- """
1834
+ env_content += "\n# OPENAI_API_KEY=\n"
2066
1835
  if base_url:
2067
1836
  env_content += f"OPENAI_BASE_URL={base_url}\n"
2068
1837
  else:
@@ -2083,7 +1852,6 @@ HERMES_DASHBOARD_PORT=9119
2083
1852
  PORT=8080
2084
1853
  # HERMES_CONTEXT_LENGTH=200000
2085
1854
  # HERMES_FALLBACK_MODEL=deepseek-v4-pro
2086
- # HERMES_IMAGE=hub.kce.ksyun.com/agentengine-public/hermes-agent:2026.5.29.2-ksadk-v1
2087
1855
  """
2088
1856
  env_example_content = """# ======================
2089
1857
  # Hermes 标准部署最小配置示例
@@ -2106,17 +1874,14 @@ HERMES_DASHBOARD_PORT=9119
2106
1874
  PORT=8080
2107
1875
  # HERMES_CONTEXT_LENGTH=200000
2108
1876
  # HERMES_FALLBACK_MODEL=deepseek-v4-pro
2109
- # HERMES_IMAGE=hub.kce.ksyun.com/agentengine-public/hermes-agent:2026.5.29.2-ksadk-v1
2110
1877
  """
1878
+ elif framework == "codex":
1879
+ env_content = _generate_codex_env_content(global_env)
2111
1880
  else:
2112
- langfuse_public = global_env.get("LANGFUSE_PUBLIC_KEY", "")
2113
- langfuse_secret = global_env.get("LANGFUSE_SECRET_KEY", "")
2114
- langfuse_url = global_env.get("LANGFUSE_BASE_URL", "")
2115
-
2116
- env_content = f"""# ======================
1881
+ env_content = """# ======================
2117
1882
  # 模型配置 (必填, 可以从星流平台获取https://ksp.console.ksyun.com/#/apiKey)
2118
1883
  # ======================
2119
- OPENAI_API_KEY={api_key}
1884
+ # OPENAI_API_KEY=
2120
1885
  """
2121
1886
 
2122
1887
  # 可选字段:如果有值则启用,否则注释掉
@@ -2135,43 +1900,22 @@ OPENAI_API_KEY={api_key}
2135
1900
  # 可观测性 (可选)
2136
1901
  # ======================
2137
1902
  """
2138
- if langfuse_public:
2139
- env_content += f"LANGFUSE_PUBLIC_KEY={langfuse_public}\n"
2140
- else:
2141
- env_content += "# LANGFUSE_PUBLIC_KEY=pk-xxx\n"
2142
-
2143
- if langfuse_secret:
2144
- env_content += f"LANGFUSE_SECRET_KEY={langfuse_secret}\n"
2145
- else:
2146
- env_content += "# LANGFUSE_SECRET_KEY=sk-xxx\n"
2147
-
2148
- if langfuse_url:
2149
- env_content += f"LANGFUSE_BASE_URL={langfuse_url}\n"
2150
- else:
2151
- env_content += "# LANGFUSE_BASE_URL=https://cloud.langfuse.com\n"
1903
+ env_content += "# OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf\n"
1904
+ env_content += "# OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://collector.example.com/v1/traces\n"
1905
+ env_content += "# OTEL_EXPORTER_OTLP_TRACES_HEADERS=Authorization=Bearer%20placeholder\n"
2152
1906
 
2153
1907
  env_content += """
2154
1908
  # ======================
2155
1909
  # 金山云配置 (可选,需要部署时必选)
2156
1910
  # ======================
2157
1911
  """
2158
- if ks_ak:
2159
- env_content += f"KSYUN_ACCESS_KEY={ks_ak}\n"
2160
- else:
2161
- env_content += "# KSYUN_ACCESS_KEY=your-api-key-here\n"
2162
-
2163
- if ks_sk:
2164
- env_content += f"KSYUN_SECRET_KEY={ks_sk}\n"
2165
- else:
2166
- env_content += "# KSYUN_SECRET_KEY=your-api-secret-here\n"
1912
+ env_content += "# KSYUN_ACCESS_KEY=your-api-key-here\n"
1913
+ env_content += "# KSYUN_SECRET_KEY=your-api-secret-here\n"
2167
1914
 
2168
1915
  env_content += f"KSYUN_REGION={ks_region}\n"
2169
1916
 
2170
- if ks_account:
2171
- env_content += f"KSYUN_ACCOUNT_ID={ks_account}\n"
2172
- else:
2173
- env_content += "# KSYUN_ACCOUNT_ID=your-account-id\n"
2174
-
1917
+ env_content += "# KSYUN_ACCOUNT_ID=your-account-id\n"
1918
+
2175
1919
  # 使用 utf-8-sig 编码 (带 BOM),确保 Windows 程序正确识别为 UTF-8
2176
1920
  (project_path / ".env").write_text(env_content, encoding="utf-8-sig")
2177
1921
  if framework == "hermes":
@@ -2185,16 +1929,35 @@ OPENAI_API_KEY={api_key}
2185
1929
  print_info("部署前如需覆盖模型/网关参数,可先编辑 .env")
2186
1930
  return
2187
1931
  if framework == "hermes":
2188
- _write_hermes_project_template(project_path, project_name, package_name)
1932
+ _write_hermes_project_config(project_path, package_name)
2189
1933
  print_success("项目创建成功")
2190
1934
  print_rule("快速开始")
2191
1935
  print_info("快速开始 (复制并执行):")
2192
1936
  _print_quick_start_commands(project_name, ["agentengine hermes deploy"])
2193
1937
  print_info("部署前如需覆盖模型/运行时参数,可先编辑 .env")
2194
1938
  return
2195
-
1939
+ if framework == "codex":
1940
+ _write_codex_project_config(project_path, package_name)
1941
+ print_success("项目创建成功")
1942
+ print_rule("快速开始")
1943
+ print_info("快速开始 (复制并执行):")
1944
+ _print_quick_start_commands(project_name, ["ksadk web ."])
1945
+ print_info("编辑 .env 填星流 OPENAI_API_KEY/BASE/MODEL_NAME;codex 自动探测并启用代理")
1946
+ # codex 本地环境检测(不阻断):缺 openai-codex SDK 时提醒
1947
+ import importlib.util
1948
+
1949
+ if importlib.util.find_spec("openai_codex") is None:
1950
+ print_warn(
1951
+ escape(
1952
+ "缺少 codex runtime SDK:请先 `pip install 'ksadk[codex]'`"
1953
+ "(内含 codex CLI 二进制)"
1954
+ )
1955
+ )
1956
+ return
1957
+
2196
1958
  # agentengine.yaml - Agent 配置
2197
- (project_path / "agentengine.yaml").write_text(f"""# AgentEngine 项目配置
1959
+ (project_path / "agentengine.yaml").write_text(
1960
+ f"""# AgentEngine 项目配置
2198
1961
  name: {package_name}
2199
1962
  version: "1.0.0"
2200
1963
 
@@ -2209,23 +1972,27 @@ agent_variable: root_agent
2209
1972
  # deploy:
2210
1973
  # timeout: 300
2211
1974
  # memory: 512
2212
- """, encoding="utf-8-sig")
2213
-
1975
+ """,
1976
+ encoding="utf-8-sig",
1977
+ )
1978
+
2214
1979
  # __init__.py
2215
- (project_path / package_name / "__init__.py").write_text(f'''"""
1980
+ (project_path / package_name / "__init__.py").write_text(
1981
+ f'''"""
2216
1982
  {project_name} - KsADK Agent
2217
1983
  """
2218
1984
  from .agent import root_agent
2219
1985
  __all__ = ["root_agent"]
2220
- ''', encoding="utf-8-sig")
2221
-
1986
+ ''',
1987
+ encoding="utf-8-sig",
1988
+ )
1989
+
2222
1990
  # agent.py
2223
1991
  template = TEMPLATES[framework]["agent.py"]
2224
1992
  (project_path / package_name / "agent.py").write_text(
2225
- template.format(package_name=package_name),
2226
- encoding="utf-8-sig"
1993
+ template.format(package_name=package_name), encoding="utf-8-sig"
2227
1994
  )
2228
-
1995
+
2229
1996
  # README.md
2230
1997
  if framework == "openclaw":
2231
1998
  readme = f"""# {project_name}
@@ -2292,12 +2059,12 @@ agentengine deploy . # 部署到云端
2292
2059
  reqs += "deepagents\nlangchain\nlangchain-openai\nlanggraph\npython-dotenv\n"
2293
2060
  elif framework == "adk":
2294
2061
  reqs += "google-adk\npython-dotenv\n"
2295
-
2062
+
2296
2063
  (project_path / "requirements.txt").write_text(reqs, encoding="utf-8")
2297
-
2064
+
2298
2065
  print_success("项目创建成功")
2299
2066
  print_rule("快速开始")
2300
-
2067
+
2301
2068
  print_info("快速开始 (复制并执行):")
2302
2069
  _print_quick_start_commands(project_name, ["agentengine config"])
2303
2070
  print_info("或直接运行 (环境变量中需包含模型 API Key):")