huaweicloud-devkit 1.1.14-next.0 → 2.0.0-next.0

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 (703) hide show
  1. package/README.md +16 -5
  2. package/README.zh-CN.md +16 -5
  3. package/bin/dsh-postinstall.cjs +171 -31
  4. package/bin/setup.cjs +1 -1
  5. package/cordis.patch.yml +1 -1
  6. package/integrations/atomcode/hooks/huaweicloud-telemetry.js +29 -33
  7. package/integrations/dsh/hook-plugin.d.mts +19 -0
  8. package/integrations/dsh/hook-plugin.mjs +23 -22
  9. package/integrations/hermes/hooks/huaweicloud-telemetry.py +26 -43
  10. package/integrations/hermes/manifest.yaml +35 -10
  11. package/integrations/opencode/commands/huaweicloud-doctor.md +3 -2
  12. package/integrations/opencode/hooks/skill-tracker.js +70 -89
  13. package/integrations/opencode/opencode.json +5 -6
  14. package/integrations/workbuddy/hooks/telemetry-tracker.py +27 -45
  15. package/package.json +32 -11
  16. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +1 -2
  17. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +1 -2
  18. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +1 -2
  19. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +1 -2
  20. package/plugins/huaweicloud-core/.mcp.json +1 -1
  21. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +1 -2
  22. package/plugins/huaweicloud-core/dist/agents/atomcode.js +118 -0
  23. package/plugins/huaweicloud-core/dist/agents/codearts-work.js +121 -0
  24. package/plugins/huaweicloud-core/dist/agents/codearts.js +69 -0
  25. package/plugins/huaweicloud-core/dist/agents/codex-desktop.js +193 -0
  26. package/plugins/huaweicloud-core/dist/agents/codex.js +205 -0
  27. package/plugins/huaweicloud-core/dist/agents/dsh-patch.js +172 -0
  28. package/plugins/huaweicloud-core/dist/agents/dsh.js +129 -0
  29. package/plugins/huaweicloud-core/dist/agents/hermes-config.js +976 -0
  30. package/plugins/huaweicloud-core/dist/agents/hermes-hook-plugin.js +90 -0
  31. package/plugins/huaweicloud-core/dist/agents/hermes-hooks.js +166 -0
  32. package/plugins/huaweicloud-core/dist/agents/hermes-sdk.js +58 -0
  33. package/plugins/huaweicloud-core/dist/agents/hermes.js +150 -0
  34. package/plugins/huaweicloud-core/dist/agents/officeace-registry.js +179 -0
  35. package/plugins/huaweicloud-core/dist/agents/officeace-sqlite.js +132 -0
  36. package/plugins/huaweicloud-core/dist/agents/officeace.js +173 -0
  37. package/plugins/huaweicloud-core/dist/agents/openclaw.js +54 -0
  38. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +188 -0
  39. package/plugins/huaweicloud-core/dist/agents/opencode.js +112 -0
  40. package/plugins/huaweicloud-core/dist/agents/workbuddy.js +194 -0
  41. package/plugins/huaweicloud-core/dist/auth/account-type.js +136 -0
  42. package/plugins/huaweicloud-core/dist/auth/agent-registration.js +243 -0
  43. package/plugins/huaweicloud-core/dist/auth/cli.js +114 -0
  44. package/plugins/huaweicloud-core/dist/auth/codearts-context.js +131 -0
  45. package/plugins/huaweicloud-core/dist/auth/credential-placeholder.js +41 -0
  46. package/plugins/huaweicloud-core/dist/auth/credential-resolver.js +74 -0
  47. package/plugins/huaweicloud-core/dist/auth/credential-validator.js +139 -0
  48. package/plugins/huaweicloud-core/dist/auth/credentials.js +20 -0
  49. package/plugins/huaweicloud-core/dist/auth/error-table.js +123 -0
  50. package/plugins/huaweicloud-core/dist/auth/hcloud-profile.js +89 -0
  51. package/plugins/huaweicloud-core/dist/auth/init-cli.js +139 -0
  52. package/plugins/huaweicloud-core/dist/auth/missing-credential-error.js +33 -0
  53. package/plugins/huaweicloud-core/dist/auth/obs-config.js +31 -0
  54. package/plugins/huaweicloud-core/dist/auth/project-id.js +90 -0
  55. package/plugins/huaweicloud-core/dist/auth/reconcile.js +256 -0
  56. package/plugins/huaweicloud-core/dist/auth/runtime-credentials.js +32 -0
  57. package/plugins/huaweicloud-core/dist/auth/s1-store.js +171 -0
  58. package/plugins/huaweicloud-core/dist/auth/service.js +397 -0
  59. package/plugins/huaweicloud-core/dist/auth/sts-expiry.js +58 -0
  60. package/plugins/huaweicloud-core/dist/capability-catalog.js +494 -0
  61. package/plugins/huaweicloud-core/dist/codearts-sandbox.js +32 -0
  62. package/plugins/huaweicloud-core/dist/codex-probe.js +77 -0
  63. package/plugins/huaweicloud-core/dist/data/icons-manifest.v1.json +3517 -0
  64. package/plugins/huaweicloud-core/dist/dep/installers/gateway.js +186 -0
  65. package/plugins/huaweicloud-core/dist/dep/installers/hcloud.js +370 -0
  66. package/plugins/huaweicloud-core/dist/dep/installers/table.js +28 -0
  67. package/plugins/huaweicloud-core/dist/dep/provision.js +247 -0
  68. package/plugins/huaweicloud-core/dist/dep/receipts.js +385 -0
  69. package/plugins/huaweicloud-core/dist/detect-framework-match.js +111 -0
  70. package/plugins/huaweicloud-core/dist/detect-framework-pkg.js +85 -0
  71. package/plugins/huaweicloud-core/dist/detect-framework-scan.js +93 -0
  72. package/plugins/huaweicloud-core/dist/detect-framework-table.js +153 -0
  73. package/plugins/huaweicloud-core/dist/detect-framework.js +7 -0
  74. package/plugins/huaweicloud-core/dist/doctor-native.js +167 -0
  75. package/plugins/huaweicloud-core/dist/doctor-payload.js +34 -0
  76. package/plugins/huaweicloud-core/dist/doctor-report.js +8 -0
  77. package/plugins/huaweicloud-core/dist/explain-error.js +209 -0
  78. package/plugins/huaweicloud-core/dist/hcloud-api-error.js +64 -0
  79. package/plugins/huaweicloud-core/dist/hcloud-catalog.js +91 -0
  80. package/plugins/huaweicloud-core/dist/hcloud-cli.js +24 -0
  81. package/plugins/huaweicloud-core/dist/hcloud-obs-redact.js +68 -0
  82. package/plugins/huaweicloud-core/dist/hcloud-plan.js +298 -0
  83. package/plugins/huaweicloud-core/dist/hcloud-probe.js +153 -0
  84. package/plugins/huaweicloud-core/dist/hcloud-run-once.js +245 -0
  85. package/plugins/huaweicloud-core/dist/hcloud-run.js +107 -0
  86. package/plugins/huaweicloud-core/dist/hcloud-sg-preflight.js +104 -0
  87. package/plugins/huaweicloud-core/dist/hcloud-sts.js +113 -0
  88. package/plugins/huaweicloud-core/dist/hcloud-triage.js +71 -0
  89. package/plugins/huaweicloud-core/dist/icon-library.js +216 -0
  90. package/plugins/huaweicloud-core/dist/install-payload.js +35 -0
  91. package/plugins/huaweicloud-core/dist/install-plan.js +85 -0
  92. package/plugins/huaweicloud-core/dist/install-prompts.js +119 -0
  93. package/plugins/huaweicloud-core/dist/koocli-version.js +83 -0
  94. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +234 -0
  95. package/plugins/huaweicloud-core/dist/lib/as-record.js +10 -0
  96. package/plugins/huaweicloud-core/dist/lib/as-text.js +15 -0
  97. package/plugins/huaweicloud-core/dist/lib/banner.js +10 -0
  98. package/plugins/huaweicloud-core/dist/lib/call-trace.js +128 -0
  99. package/plugins/huaweicloud-core/dist/lib/cli-io.js +72 -0
  100. package/plugins/huaweicloud-core/dist/lib/credentials.js +173 -0
  101. package/plugins/huaweicloud-core/dist/lib/dep-resolve.js +64 -0
  102. package/plugins/huaweicloud-core/dist/lib/dependency-model.js +152 -0
  103. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +217 -0
  104. package/plugins/huaweicloud-core/dist/lib/hdkit/hwlink-api.js +163 -0
  105. package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +303 -0
  106. package/plugins/huaweicloud-core/dist/lib/hw-request-signing.js +57 -0
  107. package/plugins/huaweicloud-core/dist/lib/koocli-paths.js +18 -0
  108. package/plugins/huaweicloud-core/dist/lib/native-receipt.js +110 -0
  109. package/plugins/huaweicloud-core/dist/lib/opencode-permission-seam.js +132 -0
  110. package/plugins/huaweicloud-core/dist/lib/pack-state.js +179 -0
  111. package/plugins/huaweicloud-core/dist/lib/pack-types.js +21 -0
  112. package/plugins/huaweicloud-core/dist/lib/secret-vault/cli.js +273 -0
  113. package/plugins/huaweicloud-core/dist/lib/secret-vault/custody.js +396 -0
  114. package/plugins/huaweicloud-core/dist/lib/secret-vault/refs.js +63 -0
  115. package/plugins/huaweicloud-core/dist/lib/secret-vault/store.js +236 -0
  116. package/plugins/huaweicloud-core/dist/lib/skill-frontmatter.js +158 -0
  117. package/plugins/huaweicloud-core/dist/lib/skill-manifest.js +55 -0
  118. package/plugins/huaweicloud-core/dist/lib/skill-tree.js +44 -0
  119. package/plugins/huaweicloud-core/dist/lib/tool-schema-parts.js +66 -0
  120. package/plugins/huaweicloud-core/dist/mcp-agent-config.js +80 -0
  121. package/plugins/huaweicloud-core/dist/mcp-config-backup.js +74 -0
  122. package/plugins/huaweicloud-core/dist/mcp-config-io.js +195 -0
  123. package/plugins/huaweicloud-core/dist/mcp-config-merge.js +188 -0
  124. package/plugins/huaweicloud-core/dist/mcp-protocol.js +320 -0
  125. package/plugins/huaweicloud-core/dist/mcp-server.js +62136 -0
  126. package/plugins/huaweicloud-core/dist/mcp-server.js.map +7 -0
  127. package/plugins/huaweicloud-core/dist/mcp-stdio-transport.js +206 -0
  128. package/plugins/huaweicloud-core/dist/officeace-paths.js +142 -0
  129. package/plugins/huaweicloud-core/dist/packs/auth/pack.js +11 -0
  130. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +276 -0
  131. package/plugins/huaweicloud-core/dist/packs/discovery/pack.js +11 -0
  132. package/plugins/huaweicloud-core/dist/packs/discovery/tools.js +78 -0
  133. package/plugins/huaweicloud-core/dist/packs/enable.js +81 -0
  134. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/pack.js +39 -0
  135. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +435 -0
  136. package/plugins/huaweicloud-core/dist/packs/huaweicloud-open-mcp/approval.js +222 -0
  137. package/plugins/huaweicloud-core/dist/packs/huaweicloud-open-mcp/pack.js +17 -0
  138. package/plugins/huaweicloud-core/dist/packs/huaweicloud-open-mcp/sidecar.js +486 -0
  139. package/plugins/huaweicloud-core/dist/packs/huaweicloud-open-mcp/tools.js +134 -0
  140. package/plugins/huaweicloud-core/dist/packs/obs/pack.js +11 -0
  141. package/plugins/huaweicloud-core/dist/packs/obs/tools.js +425 -0
  142. package/plugins/huaweicloud-core/dist/packs/registry.js +143 -0
  143. package/plugins/huaweicloud-core/dist/packs/sandbox/git-transfer.js +79 -0
  144. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +80 -0
  145. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +138 -0
  146. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-deploy.js +45 -0
  147. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +48 -0
  148. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +59 -0
  149. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-upload.js +34 -0
  150. package/plugins/huaweicloud-core/dist/packs/sandbox/pack.js +14 -0
  151. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +191 -0
  152. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +146 -0
  153. package/plugins/huaweicloud-core/dist/packs/secrets/pack.js +8 -0
  154. package/plugins/huaweicloud-core/dist/packs/secrets/tools.js +126 -0
  155. package/plugins/huaweicloud-core/dist/packs/update/pack.js +11 -0
  156. package/plugins/huaweicloud-core/dist/packs/update/tools.js +82 -0
  157. package/plugins/huaweicloud-core/dist/packs/voucher/pack.js +11 -0
  158. package/plugins/huaweicloud-core/dist/packs/voucher/tools.js +91 -0
  159. package/plugins/huaweicloud-core/dist/packs-cli/commands.js +108 -0
  160. package/plugins/huaweicloud-core/dist/packs-cli/doctor.js +81 -0
  161. package/plugins/huaweicloud-core/dist/packs-cli/report.js +133 -0
  162. package/plugins/huaweicloud-core/dist/packs-cli/slots.js +104 -0
  163. package/plugins/huaweicloud-core/dist/packs-cli/write-command.js +108 -0
  164. package/plugins/huaweicloud-core/dist/packs-cli/writers.js +115 -0
  165. package/plugins/huaweicloud-core/dist/packs-configure.js +81 -0
  166. package/plugins/huaweicloud-core/dist/packs-policy.js +149 -0
  167. package/plugins/huaweicloud-core/dist/payload-files.js +78 -0
  168. package/plugins/huaweicloud-core/dist/payload-native-clean.js +142 -0
  169. package/plugins/huaweicloud-core/dist/payload-native-sync.js +89 -0
  170. package/plugins/huaweicloud-core/dist/payload-placement.js +94 -0
  171. package/plugins/huaweicloud-core/dist/payload-roster.js +80 -0
  172. package/plugins/huaweicloud-core/dist/payload-runtime-deps.js +67 -0
  173. package/plugins/huaweicloud-core/dist/payload-status.js +43 -0
  174. package/plugins/huaweicloud-core/dist/payload-utils.js +42 -0
  175. package/plugins/huaweicloud-core/dist/preflight.js +232 -0
  176. package/plugins/huaweicloud-core/dist/proxy/cli.js +83 -0
  177. package/plugins/huaweicloud-core/dist/proxy/proxy-agent.js +92 -0
  178. package/plugins/huaweicloud-core/dist/proxy/proxy-bypass.js +83 -0
  179. package/plugins/huaweicloud-core/dist/proxy/proxy-cidr.js +105 -0
  180. package/plugins/huaweicloud-core/dist/proxy/proxy-config-io.js +61 -0
  181. package/plugins/huaweicloud-core/dist/proxy/proxy-config.js +10 -0
  182. package/plugins/huaweicloud-core/dist/risk-rule-engine.js +229 -0
  183. package/plugins/huaweicloud-core/dist/safety/classify-hcloud.js +191 -0
  184. package/plugins/huaweicloud-core/dist/safety/classify-text.js +1032 -0
  185. package/plugins/huaweicloud-core/dist/safety/command-operation.js +25 -0
  186. package/plugins/huaweicloud-core/dist/safety/credential-path.js +23 -0
  187. package/plugins/huaweicloud-core/dist/safety/default-policy.js +28 -0
  188. package/plugins/huaweicloud-core/dist/safety/feeder.js +119 -0
  189. package/plugins/huaweicloud-core/dist/safety/heredoc.js +95 -0
  190. package/plugins/huaweicloud-core/dist/safety/policy.js +75 -0
  191. package/plugins/huaweicloud-core/dist/safety/redact.js +42 -0
  192. package/plugins/huaweicloud-core/dist/safety/risk-merge.js +22 -0
  193. package/plugins/huaweicloud-core/dist/safety/script-stream.js +90 -0
  194. package/plugins/huaweicloud-core/dist/safety/secret-exec.js +44 -0
  195. package/plugins/huaweicloud-core/dist/safety/segments.js +138 -0
  196. package/plugins/huaweicloud-core/dist/safety/shell-text.js +414 -0
  197. package/plugins/huaweicloud-core/dist/safety/skill-quality-cli.js +152 -0
  198. package/plugins/huaweicloud-core/dist/safety/tokens.js +297 -0
  199. package/plugins/huaweicloud-core/dist/safety/unwrap.js +148 -0
  200. package/plugins/huaweicloud-core/dist/safety/vocabulary.js +37 -0
  201. package/plugins/huaweicloud-core/dist/safety/windows-rebase.js +56 -0
  202. package/plugins/huaweicloud-core/dist/safety/windows.js +137 -0
  203. package/plugins/huaweicloud-core/dist/safety/xargs-argv.js +64 -0
  204. package/plugins/huaweicloud-core/dist/safety-policy.js +14 -0
  205. package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +246 -0
  206. package/plugins/huaweicloud-core/dist/sandbox/deploy-nginx-verify.js +76 -0
  207. package/plugins/huaweicloud-core/dist/sandbox/deploy-nginx.js +215 -0
  208. package/plugins/huaweicloud-core/dist/sandbox/devbridge-auth.js +246 -0
  209. package/plugins/huaweicloud-core/dist/sandbox/devbridge-exec.js +10 -0
  210. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose-flow.js +225 -0
  211. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose.js +214 -0
  212. package/plugins/huaweicloud-core/dist/sandbox/devbridge-gateway.js +34 -0
  213. package/plugins/huaweicloud-core/dist/sandbox/devbridge-keepalive.js +212 -0
  214. package/plugins/huaweicloud-core/dist/sandbox/devbridge-key.js +175 -0
  215. package/plugins/huaweicloud-core/dist/sandbox/devbridge-renew.js +69 -0
  216. package/plugins/huaweicloud-core/dist/sandbox/devbridge-tunnel.js +48 -0
  217. package/plugins/huaweicloud-core/dist/sandbox/devbridge-validation.js +79 -0
  218. package/plugins/huaweicloud-core/dist/sandbox/devbridge-verify.js +101 -0
  219. package/plugins/huaweicloud-core/dist/sandbox/hwlink-connection.js +145 -0
  220. package/plugins/huaweicloud-core/dist/sandbox/sandbox-file-server.py +45 -0
  221. package/plugins/huaweicloud-core/dist/sandbox/sandbox-output.js +45 -0
  222. package/plugins/huaweicloud-core/dist/sandbox/session-manager.js +55 -0
  223. package/plugins/huaweicloud-core/dist/sandbox/tunnel-http.js +137 -0
  224. package/plugins/huaweicloud-core/dist/sandbox/uninstall-cleanup.js +45 -0
  225. package/plugins/huaweicloud-core/dist/sandbox/upload-diagnostics.js +45 -0
  226. package/plugins/huaweicloud-core/dist/sandbox/upload-file.js +119 -0
  227. package/plugins/huaweicloud-core/dist/sandbox/upload-project.js +171 -0
  228. package/plugins/huaweicloud-core/dist/sandbox/upload-transport.js +96 -0
  229. package/plugins/huaweicloud-core/dist/sandbox/ws-exec-loader.js +43 -0
  230. package/plugins/huaweicloud-core/dist/search-docs.js +64 -0
  231. package/plugins/huaweicloud-core/dist/search-market.js +277 -0
  232. package/plugins/huaweicloud-core/dist/services/availability.js +51 -0
  233. package/plugins/huaweicloud-core/dist/services/regions.js +110 -0
  234. package/plugins/huaweicloud-core/dist/setup-cli.js +1343 -0
  235. package/plugins/huaweicloud-core/dist/skill-disclosure.js +231 -0
  236. package/plugins/huaweicloud-core/dist/targets.js +139 -0
  237. package/plugins/huaweicloud-core/dist/telemetry/agent-detect.js +44 -0
  238. package/plugins/huaweicloud-core/dist/telemetry/agent-registry.js +196 -0
  239. package/plugins/huaweicloud-core/dist/telemetry/agent-versions-desktop.js +143 -0
  240. package/plugins/huaweicloud-core/dist/telemetry/agent-versions.js +78 -0
  241. package/plugins/huaweicloud-core/dist/telemetry/event-pipeline.js +206 -0
  242. package/plugins/huaweicloud-core/dist/telemetry/hook-ingest.js +81 -0
  243. package/plugins/huaweicloud-core/dist/telemetry/identity-stamps.js +104 -0
  244. package/plugins/huaweicloud-core/dist/telemetry/invoke-value.js +47 -0
  245. package/plugins/huaweicloud-core/dist/telemetry/telemetry-fs.js +42 -0
  246. package/plugins/huaweicloud-core/dist/telemetry/telemetry-types.js +14 -0
  247. package/plugins/huaweicloud-core/dist/telemetry/telemetry-values.js +121 -0
  248. package/plugins/huaweicloud-core/dist/telemetry/telemetry.js +262 -0
  249. package/plugins/huaweicloud-core/dist/tool-definitions.js +276 -0
  250. package/plugins/huaweicloud-core/dist/tool-schemas.js +156 -0
  251. package/plugins/huaweicloud-core/dist/tools.js +269 -0
  252. package/plugins/huaweicloud-core/dist/update-cache.js +79 -0
  253. package/plugins/huaweicloud-core/dist/update-check.js +23 -0
  254. package/plugins/huaweicloud-core/dist/update-hint.js +45 -0
  255. package/plugins/huaweicloud-core/dist/update-installed.js +53 -0
  256. package/plugins/huaweicloud-core/dist/update-registry.js +141 -0
  257. package/plugins/huaweicloud-core/dist/update-semver.js +76 -0
  258. package/plugins/huaweicloud-core/dist/update-skip.js +81 -0
  259. package/plugins/huaweicloud-core/dist/update-upgrade.js +94 -0
  260. package/plugins/huaweicloud-core/dist/vendor-gate.js +89 -0
  261. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-exec-client.js +10 -0
  262. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-exec-pending.js +71 -0
  263. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-exec-session.js +235 -0
  264. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-fair-queue.js +139 -0
  265. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-interactive-terminal.js +106 -0
  266. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-multiplexer.js +229 -0
  267. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-normalize.js +53 -0
  268. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-packet.js +148 -0
  269. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-terminal-channel.js +155 -0
  270. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-tunnel-channel.js +254 -0
  271. package/plugins/huaweicloud-core/dist/ws-exec/index.js +20 -0
  272. package/plugins/huaweicloud-core/dist/ws-exec/ws-exec-client.js +76 -0
  273. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +62 -3
  274. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +2500 -33
  275. package/plugins/huaweicloud-core/openclaw.plugin.json +2 -2
  276. package/plugins/huaweicloud-core/safety/policy.json +45 -4
  277. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +47 -15
  278. package/plugins/huaweicloud-core/skills/.manifest.json +67 -0
  279. package/plugins/huaweicloud-core/skills/huawei-billing/SKILL.md +2 -0
  280. package/plugins/huaweicloud-core/skills/huawei-cbr/SKILL.md +2 -0
  281. package/plugins/huaweicloud-core/skills/huawei-cce/SKILL.md +3 -1
  282. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/SKILL.md +27 -51
  283. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/references/acceptance-criteria.md +10 -12
  284. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/references/cli-installation-guide.md +23 -27
  285. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/references/dataflow-diagram.md +2 -0
  286. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/references/iam-policies.md +2 -0
  287. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/references/verification-method.md +8 -16
  288. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/scripts/cli/cli_entry.py +71 -461
  289. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/scripts/ensure_cli.sh +28 -68
  290. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/SKILL.md +56 -144
  291. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/references/acceptance-criteria.md +14 -12
  292. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/references/cli-installation-guide.md +72 -39
  293. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/references/dataflow-diagram.md +3 -1
  294. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/references/iam-policies.md +2 -0
  295. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/references/verification-method.md +12 -0
  296. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/scripts/cli/cli_entry.py +67 -307
  297. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/scripts/ensure_cli.sh +28 -68
  298. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/templates/test-defaults.json +1 -1
  299. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/templates/test-vars.json +9 -9
  300. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/SKILL.md +82 -160
  301. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/references/acceptance-criteria.md +9 -8
  302. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/references/cli-installation-guide.md +73 -40
  303. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/references/dataflow-diagram.md +4 -2
  304. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/references/iam-policies.md +2 -0
  305. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/references/related-commands.md +16 -14
  306. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/references/verification-method.md +7 -20
  307. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/scripts/cli/cli_entry.py +67 -307
  308. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/scripts/ensure_cli.sh +28 -68
  309. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/SKILL.md +92 -95
  310. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/references/acceptance-criteria.md +11 -10
  311. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/references/cli-installation-guide.md +86 -67
  312. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/references/dataflow-diagram.md +4 -2
  313. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/references/iam-policies.md +2 -0
  314. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/references/test-data-guide.md +29 -25
  315. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/references/verification-method.md +13 -11
  316. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/scripts/cli/cli_entry.py +67 -307
  317. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/scripts/ensure_cli.sh +28 -68
  318. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/SKILL.md +107 -127
  319. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/references/acceptance-criteria.md +26 -25
  320. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/references/cli-installation-guide.md +66 -51
  321. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/references/csms-usage.md +23 -19
  322. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/references/dataflow-diagram.md +4 -2
  323. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/references/iam-policies.md +25 -30
  324. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/references/kms-usage.md +13 -11
  325. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/references/verification-method.md +13 -7
  326. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/scripts/cli/cli_entry.py +67 -354
  327. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/scripts/ensure_cli.sh +28 -69
  328. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/templates/test-vars.json +11 -11
  329. package/plugins/huaweicloud-core/skills/huawei-cloud-eye/SKILL.md +2 -0
  330. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/SKILL.md +28 -109
  331. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/references/acceptance-criteria.md +27 -31
  332. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/references/cli-installation-guide.md +49 -24
  333. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/references/dataflow-diagram.md +2 -5
  334. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/references/iam-policies.md +2 -0
  335. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/references/verification-method.md +8 -25
  336. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/scripts/cli/cli_entry.py +67 -307
  337. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/scripts/ensure_cli.sh +28 -68
  338. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/SKILL.md +60 -135
  339. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/references/acceptance-criteria.md +9 -11
  340. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/references/cli-installation-guide.md +16 -12
  341. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/references/dataflow-diagram.md +2 -0
  342. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/references/engine-operation-reference.md +15 -13
  343. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/references/iam-policies.md +9 -7
  344. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/references/security-audit-guide.md +9 -5
  345. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/references/verification-method.md +16 -37
  346. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/scripts/cli/cli_entry.py +101 -0
  347. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/scripts/ensure_cli.sh +27 -184
  348. package/plugins/huaweicloud-core/skills/huawei-cloud-waf-aad-rule-management/SKILL.md +71 -103
  349. package/plugins/huaweicloud-core/skills/huawei-cloud-waf-aad-rule-management/references/acceptance-criteria.md +4 -2
  350. package/plugins/huaweicloud-core/skills/huawei-cloud-waf-aad-rule-management/references/cli-installation-guide.md +72 -84
  351. package/plugins/huaweicloud-core/skills/huawei-cloud-waf-aad-rule-management/references/dataflow-diagram.md +3 -3
  352. package/plugins/huaweicloud-core/skills/huawei-cloud-waf-aad-rule-management/references/iam-policies.md +2 -0
  353. package/plugins/huaweicloud-core/skills/huawei-cloud-waf-aad-rule-management/references/related-commands.md +7 -5
  354. package/plugins/huaweicloud-core/skills/huawei-cloud-waf-aad-rule-management/references/verification-method.md +11 -9
  355. package/plugins/huaweicloud-core/skills/huawei-cloud-waf-aad-rule-management/scripts/cli/cli_entry.py +101 -0
  356. package/plugins/huaweicloud-core/skills/huawei-cloud-waf-aad-rule-management/scripts/ensure_cli.sh +27 -42
  357. package/plugins/huaweicloud-core/skills/huawei-ecs/SKILL.md +2 -0
  358. package/plugins/huaweicloud-core/skills/huawei-ecs/references/create-instance.md +24 -13
  359. package/plugins/huaweicloud-core/skills/huawei-ecs/references/evs.md +2 -0
  360. package/plugins/huaweicloud-core/skills/huawei-ecs/references/flavors.md +2 -0
  361. package/plugins/huaweicloud-core/skills/huawei-ecs/references/hc-activity.md +2 -0
  362. package/plugins/huaweicloud-core/skills/huawei-ecs/references/troubleshooting.md +25 -21
  363. package/plugins/huaweicloud-core/skills/huawei-ecs/references/windows-ssh.md +7 -5
  364. package/plugins/huaweicloud-core/skills/huawei-functiongraph/SKILL.md +2 -0
  365. package/plugins/huaweicloud-core/skills/huawei-functiongraph/references/apig-event-format.md +2 -0
  366. package/plugins/huaweicloud-core/skills/huawei-functiongraph/references/create-function.md +2 -0
  367. package/plugins/huaweicloud-core/skills/huawei-functiongraph/references/deploy-workflow.md +2 -0
  368. package/plugins/huaweicloud-core/skills/huawei-functiongraph/references/triggers.md +2 -0
  369. package/plugins/huaweicloud-core/skills/huawei-getting-started/SKILL.md +2 -0
  370. package/plugins/huaweicloud-core/skills/huawei-iac/SKILL.md +40 -38
  371. package/plugins/huaweicloud-core/skills/huawei-iac/references/architectures.md +2 -0
  372. package/plugins/huaweicloud-core/skills/huawei-iac/references/resource-catalog.md +14 -12
  373. package/plugins/huaweicloud-core/skills/huawei-iac/references/state-file.md +2 -0
  374. package/plugins/huaweicloud-core/skills/huawei-iam/SKILL.md +3 -1
  375. package/plugins/huaweicloud-core/skills/huawei-iam/references/policy-examples.md +2 -0
  376. package/plugins/huaweicloud-core/skills/huawei-iam/references/quick-ref.md +4 -1
  377. package/plugins/huaweicloud-core/skills/huawei-modelarts/SKILL.md +2 -0
  378. package/plugins/huaweicloud-core/skills/huawei-obs/SKILL.md +32 -29
  379. package/plugins/huaweicloud-core/skills/huawei-obs/references/bucket-create.md +2 -0
  380. package/plugins/huaweicloud-core/skills/huawei-obs/references/bucket-lifecycle.md +4 -2
  381. package/plugins/huaweicloud-core/skills/huawei-obs/references/common-pitfalls.md +17 -15
  382. package/plugins/huaweicloud-core/skills/huawei-obs/references/single-file-share.md +2 -0
  383. package/plugins/huaweicloud-core/skills/huawei-obs/references/static-website.md +10 -6
  384. package/plugins/huaweicloud-core/skills/huawei-openapi/SKILL.md +50 -0
  385. package/plugins/huaweicloud-core/skills/huawei-rds/SKILL.md +15 -13
  386. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +98 -91
  387. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/framework-commands.md +2 -0
  388. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/fullstack-postgrest.md +33 -27
  389. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/nginx-templates.md +2 -0
  390. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +3 -1
  391. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/tunnel-persistence.md +9 -2
  392. package/plugins/huaweicloud-core/skills/huawei-voucher/SKILL.md +5 -3
  393. package/plugins/huaweicloud-core/skills/huawei-vpc/SKILL.md +3 -0
  394. package/plugins/huaweicloud-core/skills/huawei-vpc/references/network.md +16 -0
  395. package/plugins/huaweicloud-core/skills/huawei-vpc/references/security-group.md +2 -0
  396. package/plugins/huaweicloud-core/skills/huawei-vpc/references/subnet.md +2 -0
  397. package/plugins/huaweicloud-core/skills/huaweicloud-api-and-sdk/SKILL.md +3 -0
  398. package/plugins/huaweicloud-core/skills/huaweicloud-capability-discovery/SKILL.md +16 -13
  399. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +6 -11
  400. package/plugins/huaweicloud-core/skills/huaweicloud-core/SKILL.md +38 -35
  401. package/plugins/huaweicloud-core/skills/huaweicloud-core/references/report-issue.md +2 -0
  402. package/plugins/huaweicloud-core/skills/huaweicloud-core/references/select.md +2 -0
  403. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +3 -0
  404. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/secrets.md +32 -0
  405. package/plugins/huaweicloud-core/skills/huaweicloud-troubleshooting/SKILL.md +2 -0
  406. package/plugins/huaweicloud-core/src/agents/atomcode.ts +138 -0
  407. package/plugins/huaweicloud-core/src/agents/codearts-work.ts +136 -0
  408. package/plugins/huaweicloud-core/src/agents/codearts.ts +92 -0
  409. package/plugins/huaweicloud-core/src/agents/codex-desktop.ts +219 -0
  410. package/plugins/huaweicloud-core/src/agents/codex.ts +230 -0
  411. package/plugins/huaweicloud-core/src/agents/dsh-patch.ts +195 -0
  412. package/plugins/huaweicloud-core/src/agents/dsh.ts +153 -0
  413. package/plugins/huaweicloud-core/src/agents/hermes-config.ts +974 -0
  414. package/plugins/huaweicloud-core/src/agents/hermes-hook-plugin.ts +99 -0
  415. package/plugins/huaweicloud-core/src/agents/hermes-hooks.ts +187 -0
  416. package/plugins/huaweicloud-core/src/agents/hermes-sdk.ts +63 -0
  417. package/plugins/huaweicloud-core/src/agents/hermes.ts +192 -0
  418. package/plugins/huaweicloud-core/src/agents/officeace-registry.ts +188 -0
  419. package/plugins/huaweicloud-core/src/agents/officeace-sqlite.ts +153 -0
  420. package/plugins/huaweicloud-core/src/agents/officeace.ts +202 -0
  421. package/plugins/huaweicloud-core/src/agents/openclaw.ts +73 -0
  422. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +193 -0
  423. package/plugins/huaweicloud-core/src/agents/opencode.ts +148 -0
  424. package/plugins/huaweicloud-core/src/agents/workbuddy.ts +216 -0
  425. package/plugins/huaweicloud-core/src/auth/account-type.ts +191 -0
  426. package/plugins/huaweicloud-core/src/auth/agent-registration.ts +267 -0
  427. package/plugins/huaweicloud-core/src/auth/cli.ts +133 -0
  428. package/plugins/huaweicloud-core/src/auth/codearts-context.ts +139 -0
  429. package/plugins/huaweicloud-core/src/auth/credential-placeholder.ts +36 -0
  430. package/plugins/huaweicloud-core/src/auth/credential-resolver.ts +81 -0
  431. package/plugins/huaweicloud-core/src/auth/credential-validator.ts +176 -0
  432. package/plugins/huaweicloud-core/src/auth/credentials.ts +52 -0
  433. package/plugins/huaweicloud-core/src/auth/{guidance.mjs → error-table.ts} +58 -12
  434. package/plugins/huaweicloud-core/src/auth/hcloud-profile.ts +119 -0
  435. package/plugins/huaweicloud-core/src/auth/init-cli.ts +155 -0
  436. package/plugins/huaweicloud-core/src/auth/missing-credential-error.ts +44 -0
  437. package/plugins/huaweicloud-core/src/auth/obs-config.ts +42 -0
  438. package/plugins/huaweicloud-core/src/auth/project-id.ts +104 -0
  439. package/plugins/huaweicloud-core/src/auth/reconcile.ts +345 -0
  440. package/plugins/huaweicloud-core/src/auth/runtime-credentials.ts +38 -0
  441. package/plugins/huaweicloud-core/src/auth/s1-store.ts +214 -0
  442. package/plugins/huaweicloud-core/src/auth/{service.mjs → service.ts} +212 -61
  443. package/plugins/huaweicloud-core/src/auth/sts-expiry.ts +58 -0
  444. package/plugins/huaweicloud-core/src/capability-catalog.ts +519 -0
  445. package/plugins/huaweicloud-core/src/codearts-sandbox.ts +32 -0
  446. package/plugins/huaweicloud-core/src/codex-probe.ts +86 -0
  447. package/plugins/huaweicloud-core/src/data/icons-manifest.v1.json +5 -23
  448. package/plugins/huaweicloud-core/src/dep/installers/gateway.ts +213 -0
  449. package/plugins/huaweicloud-core/src/dep/installers/hcloud.ts +407 -0
  450. package/plugins/huaweicloud-core/src/dep/installers/table.ts +123 -0
  451. package/plugins/huaweicloud-core/src/dep/provision.ts +335 -0
  452. package/plugins/huaweicloud-core/src/dep/receipts.ts +464 -0
  453. package/plugins/huaweicloud-core/src/detect-framework-match.ts +143 -0
  454. package/plugins/huaweicloud-core/src/detect-framework-pkg.ts +79 -0
  455. package/plugins/huaweicloud-core/src/detect-framework-scan.ts +117 -0
  456. package/plugins/huaweicloud-core/src/detect-framework-table.ts +166 -0
  457. package/plugins/huaweicloud-core/src/detect-framework.ts +8 -0
  458. package/plugins/huaweicloud-core/src/doctor-native.ts +189 -0
  459. package/plugins/huaweicloud-core/src/doctor-payload.ts +77 -0
  460. package/plugins/huaweicloud-core/src/doctor-report.ts +30 -0
  461. package/plugins/huaweicloud-core/src/explain-error.ts +246 -0
  462. package/plugins/huaweicloud-core/src/hcloud-api-error.ts +69 -0
  463. package/plugins/huaweicloud-core/src/hcloud-catalog.ts +115 -0
  464. package/plugins/huaweicloud-core/src/hcloud-cli.ts +41 -0
  465. package/plugins/huaweicloud-core/src/hcloud-obs-redact.ts +65 -0
  466. package/plugins/huaweicloud-core/src/hcloud-plan.ts +344 -0
  467. package/plugins/huaweicloud-core/src/{hcloud-probe.mjs → hcloud-probe.ts} +87 -72
  468. package/plugins/huaweicloud-core/src/hcloud-run-once.ts +251 -0
  469. package/plugins/huaweicloud-core/src/hcloud-run.ts +151 -0
  470. package/plugins/huaweicloud-core/src/hcloud-sg-preflight.ts +111 -0
  471. package/plugins/huaweicloud-core/src/hcloud-sts.ts +123 -0
  472. package/plugins/huaweicloud-core/src/hcloud-triage.ts +80 -0
  473. package/plugins/huaweicloud-core/src/{icon-library.mjs → icon-library.ts} +115 -23
  474. package/plugins/huaweicloud-core/src/install-payload.ts +63 -0
  475. package/plugins/huaweicloud-core/src/install-plan.ts +85 -0
  476. package/plugins/huaweicloud-core/src/install-prompts.ts +134 -0
  477. package/plugins/huaweicloud-core/src/koocli-version.ts +87 -0
  478. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +315 -0
  479. package/plugins/huaweicloud-core/src/lib/as-record.ts +10 -0
  480. package/plugins/huaweicloud-core/src/lib/as-text.ts +16 -0
  481. package/plugins/huaweicloud-core/src/lib/banner.ts +12 -0
  482. package/plugins/huaweicloud-core/src/lib/call-trace.ts +153 -0
  483. package/plugins/huaweicloud-core/src/lib/cli-io.ts +81 -0
  484. package/plugins/huaweicloud-core/src/lib/credentials.ts +202 -0
  485. package/plugins/huaweicloud-core/src/lib/dep-resolve.ts +107 -0
  486. package/plugins/huaweicloud-core/src/lib/dependency-model.ts +236 -0
  487. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +255 -0
  488. package/plugins/huaweicloud-core/src/lib/hdkit/hwlink-api.ts +245 -0
  489. package/plugins/huaweicloud-core/src/{sandbox/sandbox-pool.mjs → lib/hdkit/sandbox-pool.ts} +115 -47
  490. package/plugins/huaweicloud-core/src/lib/hw-request-signing.ts +101 -0
  491. package/plugins/huaweicloud-core/src/lib/koocli-paths.ts +21 -0
  492. package/plugins/huaweicloud-core/src/lib/native-receipt.ts +131 -0
  493. package/plugins/huaweicloud-core/src/lib/opencode-permission-seam.ts +145 -0
  494. package/plugins/huaweicloud-core/src/lib/pack-state.ts +192 -0
  495. package/plugins/huaweicloud-core/src/lib/pack-types.ts +74 -0
  496. package/plugins/huaweicloud-core/src/lib/secret-vault/cli.ts +270 -0
  497. package/plugins/huaweicloud-core/src/lib/secret-vault/custody.ts +468 -0
  498. package/plugins/huaweicloud-core/src/lib/secret-vault/refs.ts +75 -0
  499. package/plugins/huaweicloud-core/src/lib/secret-vault/store.ts +357 -0
  500. package/plugins/huaweicloud-core/src/lib/skill-frontmatter.ts +164 -0
  501. package/plugins/huaweicloud-core/src/lib/skill-manifest.ts +55 -0
  502. package/plugins/huaweicloud-core/src/lib/skill-tree.ts +45 -0
  503. package/plugins/huaweicloud-core/src/lib/tool-schema-parts.ts +80 -0
  504. package/plugins/huaweicloud-core/src/mcp-agent-config.ts +90 -0
  505. package/plugins/huaweicloud-core/src/{mcp-config-backup.mjs → mcp-config-backup.ts} +14 -10
  506. package/plugins/huaweicloud-core/src/mcp-config-io.ts +215 -0
  507. package/plugins/huaweicloud-core/src/mcp-config-merge.ts +205 -0
  508. package/plugins/huaweicloud-core/src/mcp-protocol.ts +385 -0
  509. package/plugins/huaweicloud-core/src/mcp-server-remote.ts +178 -0
  510. package/plugins/huaweicloud-core/src/mcp-server.ts +87 -0
  511. package/plugins/huaweicloud-core/src/mcp-stdio-transport.ts +245 -0
  512. package/plugins/huaweicloud-core/src/officeace-paths.ts +146 -0
  513. package/plugins/huaweicloud-core/src/packs/auth/pack.ts +14 -0
  514. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +327 -0
  515. package/plugins/huaweicloud-core/src/packs/discovery/pack.ts +14 -0
  516. package/plugins/huaweicloud-core/src/packs/discovery/tools.ts +97 -0
  517. package/plugins/huaweicloud-core/src/packs/enable.ts +90 -0
  518. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/pack.ts +42 -0
  519. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +493 -0
  520. package/plugins/huaweicloud-core/src/packs/huaweicloud-open-mcp/approval.ts +250 -0
  521. package/plugins/huaweicloud-core/src/packs/huaweicloud-open-mcp/pack.ts +19 -0
  522. package/plugins/huaweicloud-core/src/packs/huaweicloud-open-mcp/sidecar.ts +603 -0
  523. package/plugins/huaweicloud-core/src/packs/huaweicloud-open-mcp/tools.ts +155 -0
  524. package/plugins/huaweicloud-core/src/packs/obs/pack.ts +13 -0
  525. package/plugins/huaweicloud-core/src/packs/obs/tools.ts +487 -0
  526. package/plugins/huaweicloud-core/src/packs/registry.ts +162 -0
  527. package/plugins/huaweicloud-core/src/packs/sandbox/git-transfer.ts +93 -0
  528. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +93 -0
  529. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +144 -0
  530. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-deploy.ts +63 -0
  531. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +59 -0
  532. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +101 -0
  533. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-upload.ts +46 -0
  534. package/plugins/huaweicloud-core/src/packs/sandbox/pack.ts +16 -0
  535. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +249 -0
  536. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +183 -0
  537. package/plugins/huaweicloud-core/src/packs/secrets/pack.ts +11 -0
  538. package/plugins/huaweicloud-core/src/packs/secrets/tools.ts +146 -0
  539. package/plugins/huaweicloud-core/src/packs/update/pack.ts +13 -0
  540. package/plugins/huaweicloud-core/src/packs/update/tools.ts +107 -0
  541. package/plugins/huaweicloud-core/src/packs/voucher/pack.ts +13 -0
  542. package/plugins/huaweicloud-core/src/packs/voucher/tools.ts +112 -0
  543. package/plugins/huaweicloud-core/src/packs-cli/commands.ts +121 -0
  544. package/plugins/huaweicloud-core/src/packs-cli/doctor.ts +85 -0
  545. package/plugins/huaweicloud-core/src/packs-cli/report.ts +171 -0
  546. package/plugins/huaweicloud-core/src/packs-cli/slots.ts +139 -0
  547. package/plugins/huaweicloud-core/src/packs-cli/write-command.ts +114 -0
  548. package/plugins/huaweicloud-core/src/packs-cli/writers.ts +125 -0
  549. package/plugins/huaweicloud-core/src/packs-configure.ts +104 -0
  550. package/plugins/huaweicloud-core/src/packs-policy.ts +203 -0
  551. package/plugins/huaweicloud-core/src/payload-files.ts +78 -0
  552. package/plugins/huaweicloud-core/src/payload-native-clean.ts +154 -0
  553. package/plugins/huaweicloud-core/src/payload-native-sync.ts +110 -0
  554. package/plugins/huaweicloud-core/src/payload-placement.ts +107 -0
  555. package/plugins/huaweicloud-core/src/payload-roster.ts +85 -0
  556. package/plugins/huaweicloud-core/src/payload-runtime-deps.ts +68 -0
  557. package/plugins/huaweicloud-core/src/payload-status.ts +53 -0
  558. package/plugins/huaweicloud-core/src/payload-utils.ts +51 -0
  559. package/plugins/huaweicloud-core/src/preflight.ts +250 -0
  560. package/plugins/huaweicloud-core/src/proxy/cli.ts +103 -0
  561. package/plugins/huaweicloud-core/src/proxy/{proxy-agent.mjs → proxy-agent.ts} +25 -16
  562. package/plugins/huaweicloud-core/src/proxy/proxy-bypass.ts +90 -0
  563. package/plugins/huaweicloud-core/src/proxy/proxy-cidr.ts +98 -0
  564. package/plugins/huaweicloud-core/src/proxy/proxy-config-io.ts +73 -0
  565. package/plugins/huaweicloud-core/src/proxy/proxy-config.ts +18 -0
  566. package/plugins/huaweicloud-core/src/risk-rule-engine.ts +325 -0
  567. package/plugins/huaweicloud-core/src/safety/classify-hcloud.ts +246 -0
  568. package/plugins/huaweicloud-core/src/safety/classify-text.ts +1099 -0
  569. package/plugins/huaweicloud-core/src/safety/command-operation.ts +28 -0
  570. package/plugins/huaweicloud-core/src/safety/credential-path.ts +25 -0
  571. package/plugins/huaweicloud-core/src/safety/default-policy.ts +34 -0
  572. package/plugins/huaweicloud-core/src/safety/feeder.ts +140 -0
  573. package/plugins/huaweicloud-core/src/safety/heredoc.ts +100 -0
  574. package/plugins/huaweicloud-core/src/safety/policy.ts +109 -0
  575. package/plugins/huaweicloud-core/src/safety/redact.ts +63 -0
  576. package/plugins/huaweicloud-core/src/safety/risk-merge.ts +31 -0
  577. package/plugins/huaweicloud-core/src/safety/script-stream.ts +95 -0
  578. package/plugins/huaweicloud-core/src/safety/secret-exec.ts +42 -0
  579. package/plugins/huaweicloud-core/src/safety/segments.ts +153 -0
  580. package/plugins/huaweicloud-core/src/safety/shell-text.ts +415 -0
  581. package/plugins/huaweicloud-core/src/safety/skill-quality-cli.ts +141 -0
  582. package/plugins/huaweicloud-core/src/safety/tokens.ts +322 -0
  583. package/plugins/huaweicloud-core/src/safety/unwrap.ts +162 -0
  584. package/plugins/huaweicloud-core/src/safety/vocabulary.ts +38 -0
  585. package/plugins/huaweicloud-core/src/safety/windows-rebase.ts +56 -0
  586. package/plugins/huaweicloud-core/src/safety/windows.ts +133 -0
  587. package/plugins/huaweicloud-core/src/safety/xargs-argv.ts +79 -0
  588. package/plugins/huaweicloud-core/src/safety-policy.ts +16 -0
  589. package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +307 -0
  590. package/plugins/huaweicloud-core/src/sandbox/deploy-nginx-verify.ts +96 -0
  591. package/plugins/huaweicloud-core/src/sandbox/deploy-nginx.ts +300 -0
  592. package/plugins/huaweicloud-core/src/sandbox/devbridge-auth.ts +291 -0
  593. package/plugins/huaweicloud-core/src/sandbox/devbridge-exec.ts +28 -0
  594. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose-flow.ts +289 -0
  595. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose.ts +310 -0
  596. package/plugins/huaweicloud-core/src/sandbox/devbridge-gateway.ts +36 -0
  597. package/plugins/huaweicloud-core/src/sandbox/devbridge-keepalive.ts +254 -0
  598. package/plugins/huaweicloud-core/src/sandbox/{devbridge-key.mjs → devbridge-key.ts} +48 -32
  599. package/plugins/huaweicloud-core/src/sandbox/devbridge-renew.ts +87 -0
  600. package/plugins/huaweicloud-core/src/sandbox/devbridge-tunnel.ts +79 -0
  601. package/plugins/huaweicloud-core/src/sandbox/devbridge-validation.ts +100 -0
  602. package/plugins/huaweicloud-core/src/sandbox/devbridge-verify.ts +120 -0
  603. package/plugins/huaweicloud-core/src/sandbox/hwlink-connection.ts +188 -0
  604. package/plugins/huaweicloud-core/src/sandbox/sandbox-output.ts +46 -0
  605. package/plugins/huaweicloud-core/src/sandbox/session-manager.ts +89 -0
  606. package/plugins/huaweicloud-core/src/sandbox/tunnel-http.ts +155 -0
  607. package/plugins/huaweicloud-core/src/sandbox/{uninstall-cleanup.mjs → uninstall-cleanup.ts} +4 -4
  608. package/plugins/huaweicloud-core/src/sandbox/upload-diagnostics.ts +46 -0
  609. package/plugins/huaweicloud-core/src/sandbox/upload-file.ts +161 -0
  610. package/plugins/huaweicloud-core/src/sandbox/upload-project.ts +218 -0
  611. package/plugins/huaweicloud-core/src/sandbox/upload-transport.ts +150 -0
  612. package/plugins/huaweicloud-core/src/sandbox/ws-exec-loader.ts +104 -0
  613. package/plugins/huaweicloud-core/src/search-docs.ts +64 -0
  614. package/plugins/huaweicloud-core/src/{search-market.mjs → search-market.ts} +96 -28
  615. package/plugins/huaweicloud-core/src/services/availability.ts +53 -0
  616. package/plugins/huaweicloud-core/src/services/regions.ts +110 -0
  617. package/plugins/huaweicloud-core/src/setup-cli.ts +1563 -0
  618. package/plugins/huaweicloud-core/src/skill-disclosure.ts +242 -0
  619. package/plugins/huaweicloud-core/src/targets.ts +156 -0
  620. package/plugins/huaweicloud-core/src/telemetry/{agent-detect.mjs → agent-detect.ts} +16 -5
  621. package/plugins/huaweicloud-core/src/telemetry/agent-registry.ts +210 -0
  622. package/plugins/huaweicloud-core/src/telemetry/agent-versions-desktop.ts +138 -0
  623. package/plugins/huaweicloud-core/src/telemetry/agent-versions.ts +84 -0
  624. package/plugins/huaweicloud-core/src/telemetry/event-pipeline.ts +214 -0
  625. package/plugins/huaweicloud-core/src/telemetry/hook-ingest.ts +82 -0
  626. package/plugins/huaweicloud-core/src/telemetry/identity-stamps.ts +108 -0
  627. package/plugins/huaweicloud-core/src/telemetry/invoke-value.ts +47 -0
  628. package/plugins/huaweicloud-core/src/telemetry/telemetry-fs.ts +47 -0
  629. package/plugins/huaweicloud-core/src/telemetry/telemetry-types.ts +97 -0
  630. package/plugins/huaweicloud-core/src/telemetry/telemetry-values.ts +116 -0
  631. package/plugins/huaweicloud-core/src/telemetry/telemetry.ts +299 -0
  632. package/plugins/huaweicloud-core/src/tool-definitions.ts +294 -0
  633. package/plugins/huaweicloud-core/src/tool-schemas.ts +180 -0
  634. package/plugins/huaweicloud-core/src/tools.ts +417 -0
  635. package/plugins/huaweicloud-core/src/update-cache.ts +95 -0
  636. package/plugins/huaweicloud-core/src/update-check.ts +51 -0
  637. package/plugins/huaweicloud-core/src/update-hint.ts +82 -0
  638. package/plugins/huaweicloud-core/src/update-installed.ts +53 -0
  639. package/plugins/huaweicloud-core/src/update-registry.ts +146 -0
  640. package/plugins/huaweicloud-core/src/update-semver.ts +80 -0
  641. package/plugins/huaweicloud-core/src/update-skip.ts +94 -0
  642. package/plugins/huaweicloud-core/src/update-upgrade.ts +123 -0
  643. package/plugins/huaweicloud-core/src/vendor-gate.ts +103 -0
  644. package/plugins/huaweicloud-core/src/ws-exec/hwlink-exec-client.ts +15 -0
  645. package/plugins/huaweicloud-core/src/ws-exec/hwlink-exec-pending.ts +113 -0
  646. package/plugins/huaweicloud-core/src/ws-exec/hwlink-exec-session.ts +334 -0
  647. package/plugins/huaweicloud-core/src/ws-exec/{hwlink-fair-queue.js → hwlink-fair-queue.ts} +46 -15
  648. package/plugins/huaweicloud-core/src/ws-exec/hwlink-interactive-terminal.ts +158 -0
  649. package/plugins/huaweicloud-core/src/ws-exec/{hwlink-multiplexer.js → hwlink-multiplexer.ts} +108 -30
  650. package/plugins/huaweicloud-core/src/ws-exec/hwlink-normalize.ts +60 -0
  651. package/plugins/huaweicloud-core/src/ws-exec/{hwlink-packet.js → hwlink-packet.ts} +40 -16
  652. package/plugins/huaweicloud-core/src/ws-exec/{hwlink-terminal-channel.js → hwlink-terminal-channel.ts} +30 -18
  653. package/plugins/huaweicloud-core/src/ws-exec/{hwlink-tunnel-channel.mjs → hwlink-tunnel-channel.ts} +75 -27
  654. package/plugins/huaweicloud-core/src/ws-exec/{index.js → index.ts} +11 -11
  655. package/plugins/huaweicloud-core/src/ws-exec/ws-exec-client.ts +102 -0
  656. package/plugins/huaweicloud-core/tsconfig.json +21 -0
  657. package/rules/huawei-agent-rules.mdc +2 -2
  658. package/integrations/hermes/skills-snapshot.json +0 -175
  659. package/integrations/opencode/package-lock.json +0 -24
  660. package/integrations/opencode/package.json +0 -10
  661. package/integrations/opencode/plugins/huaweicloud-devkit.js +0 -194
  662. package/integrations/opencode/skills/huaweicloud-core/SKILL.md +0 -32
  663. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/scripts/cli/cli_reporting.py +0 -589
  664. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/references/test-report.md +0 -35
  665. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/scripts/cli/cli_reporting.py +0 -928
  666. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/scripts/cli/cli_reporting.py +0 -928
  667. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/references/test-report.md +0 -52
  668. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/scripts/cli/cli_reporting.py +0 -928
  669. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/scripts/cli/cli_reporting.py +0 -577
  670. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/scripts/cli/cli_reporting.py +0 -928
  671. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/scripts/gaussdb_cli.sh +0 -138
  672. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/scripts/install_cli.sh +0 -94
  673. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/scripts/smn_dms_skill.py +0 -444
  674. package/plugins/huaweicloud-core/src/account-type.mjs +0 -144
  675. package/plugins/huaweicloud-core/src/auth/agent-registration.mjs +0 -243
  676. package/plugins/huaweicloud-core/src/auth/credential-validator.mjs +0 -198
  677. package/plugins/huaweicloud-core/src/auth/credentials.mjs +0 -534
  678. package/plugins/huaweicloud-core/src/auth/project-id.mjs +0 -68
  679. package/plugins/huaweicloud-core/src/auth/reconcile.mjs +0 -257
  680. package/plugins/huaweicloud-core/src/auth/token-exchange.mjs +0 -100
  681. package/plugins/huaweicloud-core/src/detect-framework.mjs +0 -402
  682. package/plugins/huaweicloud-core/src/hcloud-cli.mjs +0 -864
  683. package/plugins/huaweicloud-core/src/koocli-install.mjs +0 -57
  684. package/plugins/huaweicloud-core/src/koocli-version.mjs +0 -47
  685. package/plugins/huaweicloud-core/src/mcp-config-merge.mjs +0 -219
  686. package/plugins/huaweicloud-core/src/mcp-protocol.mjs +0 -109
  687. package/plugins/huaweicloud-core/src/mcp-server-remote.mjs +0 -108
  688. package/plugins/huaweicloud-core/src/mcp-server.mjs +0 -221
  689. package/plugins/huaweicloud-core/src/officeace-paths.mjs +0 -51
  690. package/plugins/huaweicloud-core/src/preflight.mjs +0 -125
  691. package/plugins/huaweicloud-core/src/proxy/proxy-config.mjs +0 -187
  692. package/plugins/huaweicloud-core/src/risk-rule-engine.mjs +0 -182
  693. package/plugins/huaweicloud-core/src/safety-policy.mjs +0 -625
  694. package/plugins/huaweicloud-core/src/sandbox/hdkitservice-api.mjs +0 -296
  695. package/plugins/huaweicloud-core/src/sandbox/hwlink-api.mjs +0 -259
  696. package/plugins/huaweicloud-core/src/sandbox/session-manager.mjs +0 -2594
  697. package/plugins/huaweicloud-core/src/setup-cli.mjs +0 -5461
  698. package/plugins/huaweicloud-core/src/telemetry/agent-registry.mjs +0 -341
  699. package/plugins/huaweicloud-core/src/telemetry/telemetry.mjs +0 -492
  700. package/plugins/huaweicloud-core/src/tools.mjs +0 -3229
  701. package/plugins/huaweicloud-core/src/update-check.mjs +0 -476
  702. package/plugins/huaweicloud-core/src/ws-exec/hwlink-exec-client.js +0 -461
  703. package/plugins/huaweicloud-core/src/ws-exec/ws-exec-client.js +0 -365
@@ -1,3229 +0,0 @@
1
- import { readFileSync, readdirSync, existsSync, writeFileSync, rmSync, mkdirSync } from 'node:fs';
2
- import { join, dirname, basename } from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
- import { homedir, tmpdir } from 'node:os';
5
- import { spawnSync, execFile } from 'node:child_process';
6
- import { promisify } from 'node:util';
7
- import { createHmac, createHash } from 'node:crypto';
8
-
9
- import { evaluateArtifacts, evaluateCommandRisk, evaluateDeployPlan } from './risk-rule-engine.mjs';
10
- import { classifyTextCommand, redactSecrets } from './safety-policy.mjs';
11
- import { planHcloudCommand, runHcloud, consumeApprovalToken, inspectApprovalToken, hashArgs } from './hcloud-cli.mjs';
12
- import { checkAccountType } from './account-type.mjs';
13
- import { searchMarketplace } from './search-market.mjs';
14
- import { getServiceIcon } from './icon-library.mjs';
15
- import { detectFramework } from './detect-framework.mjs';
16
- import { installKooCli } from './koocli-install.mjs';
17
- import {
18
- execWithSession,
19
- execOneShot,
20
- closeSession,
21
- uploadFileWithSession,
22
- uploadProjectWithSession,
23
- deployNginx,
24
- deployCheck,
25
- exposeTunnel,
26
- renewTunnel,
27
- installKeepaliveWatchdog,
28
- cleanupDevbridgeTunnels,
29
- getCurrentWorkspaceId,
30
- setWorkspaceId,
31
- } from './sandbox/session-manager.mjs';
32
- import {
33
- validatePoolType,
34
- rememberWorkspacePool,
35
- enrichConnectResult,
36
- poolContextFor,
37
- shouldAnnounceConnect,
38
- forgetWorkspacePool,
39
- } from './sandbox/sandbox-pool.mjs';
40
- import { ensureDevbridgeKey, buildKeyringInjectScript, listKeysForQuotaHint } from './sandbox/devbridge-key.mjs';
41
- import {
42
- hdkitCheckUser,
43
- hdkitSignAgreement,
44
- hdkitConnectWithRetry,
45
- hdkitCredentials,
46
- hdkitVoucherStatus,
47
- hdkitVoucherClaim,
48
- hdkitCompetitionVoucherClaim,
49
- hdkitGenerateUserHash,
50
- } from './sandbox/hdkitservice-api.mjs';
51
- import { resolveBackendCredentials } from './sandbox/hwlink-api.mjs';
52
- import { getAuthStatus, syncAuth } from './auth/service.mjs';
53
- import { validateIamCredentials } from './auth/credential-validator.mjs';
54
- import {
55
- readGlobalCredentials,
56
- writeGlobalCredentials,
57
- writeObsConfig as writeObsConfigFile,
58
- setRuntimeCredentials,
59
- clearRuntimeCredentials,
60
- setConfiguredBySession,
61
- backupGlobalCredentials,
62
- writeLastSync,
63
- readCodeArtsCredentials,
64
- globalCredentialsPath,
65
- parseStsExpiry,
66
- resolveCredentialsWithRuntime,
67
- } from './auth/credentials.mjs';
68
- import { trackToolInvoke, trackSkillRetrieve, clearUserHash, cacheUserHash } from './telemetry/telemetry.mjs';
69
- import { fetchWithProxy } from './proxy/proxy-agent.mjs';
70
- import { fingerprint, runHcloudConfigure, runHcloudProfileDelete, resolveManagedProfile } from './auth/reconcile.mjs';
71
- import {
72
- getCachedUpdateInfo,
73
- getUpdateDistTags,
74
- invalidateUpdateCache,
75
- judgeUpdate,
76
- determineTarget,
77
- readInstalledVersion,
78
- writeSkipState,
79
- resolveSkipFilePath,
80
- upgradePackage,
81
- } from './update-check.mjs';
82
- import { hcloudProbeNextStep, hcloudProbeRaw, probeHcloud } from './hcloud-probe.mjs';
83
- import { isUsableOfficeaceRoot, readOfficeaceRootMarker } from './officeace-paths.mjs';
84
-
85
- const __dirname = dirname(fileURLToPath(import.meta.url));
86
- const SKILLS_ROOT_DEV = join(__dirname, '..', 'skills');
87
- function opencodeSkillsDir() {
88
- const home = homedir();
89
- return join(home, '.config', 'opencode', 'skills');
90
- }
91
- function codeartsSkillsDir() {
92
- const home = homedir();
93
- return join(home, '.codeartsdoer', 'skills');
94
- }
95
- function codeartsWorkSkillsDir() {
96
- const home = homedir();
97
- return join(home, '.codeartswork', 'skills');
98
- }
99
- function workbuddySkillsDir() {
100
- const home = homedir();
101
- return join(home, '.workbuddy', 'skills');
102
- }
103
- function dshSkillsDir() {
104
- const home = process.env.DSH_HOME || join(homedir(), '.dsh');
105
- return join(home, 'skills');
106
- }
107
- function readOfficeaceRegistryInstallDir() {
108
- if (process.platform !== 'win32') return null;
109
- try {
110
- const r = spawnSync('reg', ['query', 'HKCU\\SOFTWARE\\OfficeAce\\OfficeAce', '/v', 'InstallDir'], {
111
- encoding: 'utf8',
112
- windowsHide: true,
113
- timeout: 5000,
114
- });
115
- if (r.status === 0) {
116
- const m = r.stdout.match(/InstallDir\s+REG_SZ\s+(.+)/);
117
- if (m) return m[1].trim();
118
- }
119
- } catch {}
120
- return null;
121
- }
122
-
123
- function officeaceSkillsRoot() {
124
- const configRoot = process.env.OFFICE_CLAW_CONFIG_ROOT;
125
- // Same lenient probe as the installer (isUsableOfficeaceRoot) so env pointing
126
- // at "skills present but capabilities.json absent" resolves identically at
127
- // install and at runtime (#559 review).
128
- if (configRoot && isUsableOfficeaceRoot(configRoot)) return join(configRoot, 'skills');
129
- // Same persisted root used by the installer keeps install-time and
130
- // runtime skill discovery consistent (#559).
131
- const markerRoot = readOfficeaceRootMarker();
132
- if (markerRoot) return join(markerRoot, 'skills');
133
- const regDir = readOfficeaceRegistryInstallDir();
134
- if (regDir) {
135
- const dir = join(regDir, '.office-claw', 'skills');
136
- if (existsSync(dir)) return dir;
137
- }
138
- if (process.platform === 'win32') {
139
- const bases = [process.env.ProgramFiles, 'C:\\Program Files', 'D:\\Program Files'];
140
- if (process.env.LOCALAPPDATA) bases.push(join(process.env.LOCALAPPDATA, 'Programs'));
141
- for (const base of bases) {
142
- if (!base) continue;
143
- const dir = join(base, 'OfficeAce', '.office-claw', 'skills');
144
- if (existsSync(dir)) return dir;
145
- }
146
- }
147
- return null;
148
- }
149
-
150
- function hermesSkillsDir() {
151
- if (process.env.HERMES_HOME) return join(process.env.HERMES_HOME, 'skills');
152
- // Hermes on Windows stores under LOCALAPPDATA, not ~/.hermes
153
- if (process.platform === 'win32' && process.env.LOCALAPPDATA) {
154
- return join(process.env.LOCALAPPDATA, 'hermes', 'skills');
155
- }
156
- const home = homedir();
157
- return join(home, '.hermes', 'skills');
158
- }
159
-
160
- function atomcodeSkillsDir() {
161
- const home = process.env.ATOMCODE_HOME || homedir();
162
- return join(home, '.atomcode', 'skills');
163
- }
164
-
165
- function codexDesktopSkillsDir() {
166
- return join(homedir(), '.agents', 'skills');
167
- }
168
-
169
- export function listSkillDirs(root) {
170
- if (!existsSync(root)) return [];
171
- try {
172
- return readdirSync(root, { withFileTypes: true })
173
- .filter((d) => (d.isDirectory() || d.isSymbolicLink()) && existsSync(join(root, d.name, 'SKILL.md')))
174
- .map((d) => d.name);
175
- } catch {
176
- return [];
177
- }
178
- }
179
-
180
- export function findSkillsRoot(candidates) {
181
- for (const dir of candidates) {
182
- if (listSkillDirs(dir).length > 0) return dir;
183
- }
184
- return null;
185
- }
186
-
187
- function resolveSkillsRoot() {
188
- return (
189
- findSkillsRoot([
190
- SKILLS_ROOT_DEV,
191
- dshSkillsDir(),
192
- codeartsSkillsDir(),
193
- codeartsWorkSkillsDir(),
194
- opencodeSkillsDir(),
195
- workbuddySkillsDir(),
196
- officeaceSkillsRoot(),
197
- hermesSkillsDir(),
198
- atomcodeSkillsDir(),
199
- codexDesktopSkillsDir(),
200
- ]) || SKILLS_ROOT_DEV
201
- );
202
- }
203
- const SKILLS_ROOT = resolveSkillsRoot();
204
-
205
- export const TOOL_DEFINITIONS = [
206
- {
207
- name: 'huaweicloud_check_cli',
208
- description:
209
- 'Check whether Huawei Cloud KooCLI hcloud is installed and whether its version matches the plugin paired version. Returns redacted output.',
210
- inputSchema: {
211
- type: 'object',
212
- properties: {},
213
- },
214
- },
215
- {
216
- name: 'huaweicloud_install_hcloud',
217
- description:
218
- 'Install KooCLI (hcloud) from inside the MCP server process via Node (no agent bash tool required). Downloads and extracts the pinned hcloud binary to ~/.local/bin/hcloud. Use when huaweicloud_check_cli reports HCLOUD_NOT_FOUND and the agent bash tool is unavailable (e.g. CodeArts with OPENCODE_CONFIG unset).',
219
- inputSchema: {
220
- type: 'object',
221
- properties: {},
222
- },
223
- },
224
- {
225
- name: 'huaweicloud_plan_cli_command',
226
- description: 'Classify and plan a Huawei Cloud hcloud command without executing it.',
227
- inputSchema: {
228
- type: 'object',
229
- required: ['args'],
230
- properties: {
231
- args: {
232
- type: 'array',
233
- items: { type: 'string' },
234
- description: 'hcloud arguments, excluding the hcloud executable.',
235
- },
236
- allowWrites: {
237
- type: 'boolean',
238
- description: 'Only true after explicit user approval for this exact operation.',
239
- },
240
- },
241
- },
242
- },
243
- {
244
- name: 'huaweicloud_run_readonly_command',
245
- description: 'Run a read-only hcloud command through the toolkit safety policy and redact output.',
246
- inputSchema: {
247
- type: 'object',
248
- required: ['args'],
249
- properties: {
250
- args: {
251
- type: 'array',
252
- items: { type: 'string' },
253
- },
254
- timeoutMs: {
255
- type: 'number',
256
- description: 'Optional timeout in milliseconds. Defaults to 60000.',
257
- },
258
- maxRetries: {
259
- type: 'number',
260
- description: 'Optional retry count for transient network errors. Defaults to 1.',
261
- },
262
- cwd: {
263
- type: 'string',
264
- description: 'Optional working directory for the hcloud process.',
265
- },
266
- },
267
- },
268
- },
269
- {
270
- name: 'huaweicloud_list_operations',
271
- description:
272
- 'List KooCLI operations for a Huawei Cloud service by running local/read-only hcloud <Service> --help.',
273
- inputSchema: {
274
- type: 'object',
275
- required: ['service'],
276
- properties: {
277
- service: {
278
- type: 'string',
279
- description: 'KooCLI service name, such as ECS, VPC, IMS, OBS, RDS, or CDN.',
280
- },
281
- timeoutMs: {
282
- type: 'number',
283
- description: 'Optional timeout in milliseconds. Defaults to 60000.',
284
- },
285
- },
286
- },
287
- },
288
- {
289
- name: 'huaweicloud_run_approved_command',
290
- description:
291
- 'Run a write-capable hcloud command only after the exact command has been shown and explicitly approved by the user.',
292
- inputSchema: {
293
- type: 'object',
294
- required: ['args', 'approvalToken', 'approvedByUser'],
295
- properties: {
296
- args: {
297
- type: 'array',
298
- items: { type: 'string' },
299
- description: 'hcloud arguments, excluding the hcloud executable.',
300
- },
301
- approvalToken: {
302
- type: 'string',
303
- description: 'The approvalToken returned by huaweicloud_plan_cli_command.',
304
- },
305
- approvedByUser: {
306
- type: 'boolean',
307
- description: 'Must be true only after the user explicitly approves this exact command.',
308
- },
309
- timeoutMs: {
310
- type: 'number',
311
- description: 'Optional timeout in milliseconds. Defaults to 60000.',
312
- },
313
- maxRetries: {
314
- type: 'number',
315
- description: 'Optional retry count for transient network errors. Defaults to 1.',
316
- },
317
- cwd: {
318
- type: 'string',
319
- description: 'Optional working directory for the hcloud process.',
320
- },
321
- },
322
- },
323
- },
324
- {
325
- name: 'huaweicloud_show_profile_redacted',
326
- description: 'Inspect a KooCLI profile through hcloud configure show and return only redacted output.',
327
- inputSchema: {
328
- type: 'object',
329
- properties: {
330
- profile: {
331
- type: 'string',
332
- description: 'Optional KooCLI profile name.',
333
- },
334
- },
335
- },
336
- },
337
- {
338
- name: 'huaweicloud_hook_check_command',
339
- description: 'Check a planned shell or hcloud command against Huawei Cloud hook risk rules without executing it.',
340
- inputSchema: {
341
- type: 'object',
342
- required: ['command'],
343
- properties: {
344
- command: { type: 'string', description: 'The exact command text to inspect.' },
345
- },
346
- },
347
- },
348
- {
349
- name: 'huaweicloud_hook_check_artifacts',
350
- description: 'Check generated code, IaC, policy, or config artifacts against Huawei Cloud hook risk rules.',
351
- inputSchema: {
352
- type: 'object',
353
- required: ['artifacts'],
354
- properties: {
355
- artifacts: {
356
- type: 'array',
357
- items: {
358
- type: 'object',
359
- required: ['path', 'content'],
360
- properties: {
361
- path: { type: 'string' },
362
- content: { type: 'string' },
363
- },
364
- },
365
- },
366
- },
367
- },
368
- },
369
- {
370
- name: 'huaweicloud_hook_check_deploy_plan',
371
- description:
372
- 'Check a structured or textual deployment plan for Huawei Cloud sandbox, exposure, IAM, and cost risks.',
373
- inputSchema: {
374
- type: 'object',
375
- required: ['plan'],
376
- properties: {
377
- plan: {
378
- description: 'Deployment plan as an object, array, or string.',
379
- },
380
- },
381
- },
382
- },
383
- {
384
- name: 'huaweicloud_service_catalog',
385
- description: 'Return the recommended capability sources for Huawei Cloud agent tasks.',
386
- inputSchema: {
387
- type: 'object',
388
- properties: {
389
- intent: {
390
- type: 'string',
391
- description: 'Developer intent to route, such as deploy app, use API, debug error, or inspect resources.',
392
- },
393
- },
394
- },
395
- },
396
- {
397
- name: 'huaweicloud_explain_error',
398
- description: 'Explain a Huawei Cloud CLI, API, SDK, or agent workflow error and suggest next diagnostic steps.',
399
- inputSchema: {
400
- type: 'object',
401
- properties: {
402
- service: { type: 'string' },
403
- errorCode: { type: 'string' },
404
- message: { type: 'string' },
405
- requestId: { type: 'string' },
406
- },
407
- },
408
- },
409
- {
410
- name: 'huaweicloud_search_docs',
411
- description:
412
- 'Search across Huawei Cloud SKILL.md files and local documentation. Returns top 10 relevant results with source, name, snippet, and relevance score. Use when the agent needs to discover which skill covers a topic, or when uncertain about API parameters, quotas, or limitations.',
413
- inputSchema: {
414
- type: 'object',
415
- required: ['query'],
416
- properties: {
417
- query: { type: 'string', description: 'Search query across skill descriptions and documentation.' },
418
- topic: {
419
- type: 'string',
420
- description: 'Optional filter: all | ecs | obs | vpc | iam | rds | cce | modelarts | dew. Defaults to all.',
421
- },
422
- },
423
- },
424
- },
425
- {
426
- name: 'huaweicloud_retrieve_skill',
427
- description:
428
- 'Retrieve a full SKILL.md by skill name. Returns the complete skill content plus list of reference files. Use when the agent has identified which skill to load and needs the full procedure.',
429
- inputSchema: {
430
- type: 'object',
431
- required: ['name'],
432
- properties: {
433
- name: { type: 'string', description: 'Skill name, e.g., huaweicloud-core, huawei-ecs, huawei-obs.' },
434
- },
435
- },
436
- },
437
- {
438
- name: 'huaweicloud_list_regions',
439
- description:
440
- 'List available Huawei Cloud regions. Returns region IDs, display names, and endpoints. Use when the agent needs to discover available regions before creating resources.',
441
- inputSchema: {
442
- type: 'object',
443
- properties: {},
444
- },
445
- },
446
- {
447
- name: 'huaweicloud_check_account_type',
448
- description:
449
- 'Check whether the current credentials belong to the primary account or an IAM sub-user. Runs STS GetCallerIdentity + IAM KeystoneListAuthDomains (both read-only, no identity-policy permission required) and applies the validated rule: username == domainName -> primary account, otherwise IAM sub-user. Use before sandbox deployment (primary-account prechecks), account confirmation, or any task that needs to know who the current AK/SK belongs to. Returns isPrimaryAccount, applicable, domainId, domainName, userId, username, principalUrn, and an evidence string. Agency-session credentials are detected and reported as applicable:false.',
450
- inputSchema: {
451
- type: 'object',
452
- properties: {
453
- region: {
454
- type: 'string',
455
- description:
456
- 'Optional region ID for the region-level GetCallerIdentity endpoint (e.g., cn-north-4). Defaults to the configured cli-region.',
457
- },
458
- },
459
- },
460
- },
461
- {
462
- name: 'huaweicloud_get_regional_availability',
463
- description:
464
- 'Check if a specific Huawei Cloud service is available in a target region. Use before creating resources to prevent failures from regional unavailability.',
465
- inputSchema: {
466
- type: 'object',
467
- required: ['service', 'region'],
468
- properties: {
469
- service: {
470
- type: 'string',
471
- description: 'Service name: ecs, obs, rds, gaussdb, cce, modelarts, functiongraph, etc.',
472
- },
473
- region: { type: 'string', description: 'Region ID: cn-south-1, cn-north-4, ap-southeast-3, etc.' },
474
- },
475
- },
476
- },
477
- {
478
- name: 'huaweicloud_search_marketplace',
479
- description:
480
- 'Search the Huawei Cloud agent skill marketplace for available skills. Returns scored results with names, categories, and descriptions. Use when built-in skills are insufficient or the user asks what skills exist.',
481
- inputSchema: {
482
- type: 'object',
483
- properties: {
484
- query: { type: 'string', description: 'Search query across skill name, description, triggers, and service.' },
485
- category: {
486
- type: 'string',
487
- description: 'Optional category filter: computing, storage, network, security, devtools, monitoring, etc.',
488
- },
489
- },
490
- },
491
- },
492
- {
493
- name: 'huaweicloud_get_service_icon',
494
- description:
495
- 'Find the official Huawei Cloud service logo from the Huawei Cloud Icons library (open.huaweicloud.com/openplatform/icons.html). Returns top 5 matches with CDN logo URLs, local paths, category, aliases, and product page links. Provide service (e.g. ecs, obs, modelarts, 对象存储) or category (e.g. 计算, 存储, 人工智能) to browse. Use when generating PPT, architecture diagrams (draw.io), or frontend pages that need official Huawei Cloud service logos.',
496
- inputSchema: {
497
- type: 'object',
498
- properties: {
499
- service: {
500
- type: 'string',
501
- description:
502
- 'Service name, alias, or Chinese name, e.g. ecs, obs, modelarts, 对象存储, 虚拟私有云. Omit to browse by category only.',
503
- },
504
- category: {
505
- type: 'string',
506
- description: 'Optional category filter, e.g. 计算, 存储, 网络, 人工智能, 数据库, 安全, 企业应用.',
507
- },
508
- },
509
- },
510
- },
511
- {
512
- name: 'huaweicloud_detect_framework',
513
- description:
514
- 'Scan a local project directory to identify the web framework (React/Vue/Angular/Next.js/Nuxt/VitePress/Docusaurus/Hugo/Hexo/Taro/uni-app), package manager, and monorepo tool. Returns framework type, build commands, output directory, and port. Use before deploying a web application to determine the correct build pipeline.',
515
- inputSchema: {
516
- type: 'object',
517
- required: ['projectPath'],
518
- properties: {
519
- projectPath: { type: 'string', description: 'Absolute path to the local project directory to scan.' },
520
- },
521
- },
522
- },
523
- {
524
- name: 'huaweicloud_setup_obs_config',
525
- description:
526
- 'Synchronize KooCLI credentials to OBS config (~/.obsutilconfig). KooCLI and OBS use separate credential stores — hcloud commands work fine but OBS commands fail with "Please set ak, sk" unless this sync is done. Run this once to enable OBS operations; re-run after changing hcloud credentials.',
527
- inputSchema: {
528
- type: 'object',
529
- properties: {
530
- profile: { type: 'string', description: 'Optional KooCLI profile name. Uses the active profile by default.' },
531
- },
532
- },
533
- },
534
- {
535
- name: 'huaweicloud_auth_status',
536
- description:
537
- 'Check unified Huawei Cloud authentication status across the global credential vault, OBS, KooCLI, and all supported agent MCP registrations. Returns only redacted/status information, never credentials.',
538
- inputSchema: {
539
- type: 'object',
540
- properties: {
541
- target: {
542
- type: 'string',
543
- description:
544
- 'Agent target to check: opencode, codex, codex-desktop, codearts, codearts-work, workbuddy, dsh, officeace, hermes, openclaw, atomcode, or all (default).',
545
- },
546
- },
547
- },
548
- },
549
- {
550
- name: 'huaweicloud_auth_sync',
551
- description:
552
- 'Synchronize credentials from the global Huawei Cloud credential vault to OBS and report agent registration status. Does not write secrets into any agent config.',
553
- inputSchema: {
554
- type: 'object',
555
- properties: {
556
- target: {
557
- type: 'string',
558
- description:
559
- 'Agent target to report after sync: opencode, codex, codex-desktop, codearts, codearts-work, workbuddy, dsh, officeace, hermes, or all (default).',
560
- },
561
- },
562
- },
563
- },
564
- {
565
- name: 'huaweicloud_auth_init',
566
- description:
567
- 'Set or clear runtime Huawei Cloud credentials (AK/SK) for this MCP session. Runtime credentials take highest priority over environment variables and config files for all subsequent API calls. Use when switching accounts within the same Agent session — call with AK/SK to switch, or with clear=true to fall back to env/file credentials.',
568
- inputSchema: {
569
- type: 'object',
570
- properties: {
571
- ak: { type: 'string', description: 'Huawei Cloud Access Key (required unless clear=true)' },
572
- sk: { type: 'string', description: 'Huawei Cloud Secret Key (required unless clear=true)' },
573
- region: { type: 'string', description: 'Default region (optional)' },
574
- clear: { type: 'boolean', description: 'Set to true to clear runtime credentials and revert to env/file' },
575
- },
576
- },
577
- },
578
- {
579
- name: 'huaweicloud_auth_switch',
580
- description:
581
- 'Switch Huawei Cloud credentials within the current session. action=temporary keeps AK/SK in memory only (restart loses them; hcloud commands are unaffected and an A+C warning will be raised). action=persist writes S1 (single source of truth) with configuredBySession flag and propagates to S2 (KooCLI current profile) and S3 (OBS). action=clear resets runtime credentials. mode=import reads AK/SK from ~/.config/huaweicloud/creds-import.json then wipes it (SK never enters conversation). mode=memory passes AK/SK as tool arguments (SK is visible to model - prefer import). mode=mcp-config reads the injected mcp_settings environment.',
582
- inputSchema: {
583
- type: 'object',
584
- properties: {
585
- mode: { type: 'string', enum: ['import', 'memory', 'mcp-config'], description: 'Credential source channel' },
586
- action: { type: 'string', enum: ['persist', 'temporary', 'clear'], description: 'Apply scope' },
587
- ak: { type: 'string' },
588
- sk: { type: 'string' },
589
- securityToken: { type: 'string' },
590
- region: { type: 'string' },
591
- },
592
- },
593
- },
594
- {
595
- name: 'huaweicloud_auth_confirm',
596
- description:
597
- 'Confirm a pending credential reconciliation choice returned by auth_switch persist when S1 already holds a different account (R2). decision=s1 keeps S1 as source of truth and propagates it; decision=newImported propagates the newly imported account into S1 and mirrors.',
598
- inputSchema: {
599
- type: 'object',
600
- properties: {
601
- token: { type: 'string', description: 'confirmation token from the needs_confirmation response' },
602
- decision: { type: 'string', enum: ['s1', 'newImported'] },
603
- },
604
- },
605
- },
606
- {
607
- name: 'huaweicloud_sandbox_exec_with_session',
608
- description:
609
- 'Execute a command on a workspace terminal with session reuse (state persists across calls). Shell state (cd, env vars, aliases) carries over between calls. Use for interactive work and command sequences that need shared state. NOT for long-running commands (>30s) — prefer exec_one_shot for those.',
610
- inputSchema: {
611
- type: 'object',
612
- required: ['command'],
613
- properties: {
614
- command: { type: 'string', description: 'The shell command to execute on the remote workspace' },
615
- workspace_id: {
616
- type: 'string',
617
- description:
618
- 'Workspace ID from huaweicloud_sandbox_connect return value. Required - must be passed explicitly when HW_WORKSPACE_ID is not set.',
619
- },
620
- username: { type: 'string', description: 'Login username for the remote terminal (default: root)' },
621
- timeout_ms: { type: 'number', description: 'Execution timeout in milliseconds (default: 120000)' },
622
- },
623
- },
624
- },
625
- {
626
- name: 'huaweicloud_sandbox_exec_one_shot',
627
- description:
628
- 'Execute a command on a workspace terminal with a fresh connection per call (no session state carries over). Each invocation opens a new WebSocket connection, executes one command, then disconnects. Use for long-running build/deploy/install commands (>30s) that do not need shell state persistence between calls. More stable than session-based execution for heavy workloads.',
629
- inputSchema: {
630
- type: 'object',
631
- required: ['command'],
632
- properties: {
633
- command: { type: 'string', description: 'The shell command to execute on the remote workspace' },
634
- workspace_id: {
635
- type: 'string',
636
- description:
637
- 'Workspace ID from huaweicloud_sandbox_connect return value. Required - must be passed explicitly when HW_WORKSPACE_ID is not set.',
638
- },
639
- username: { type: 'string', description: 'Login username for the remote terminal (default: root)' },
640
- timeout_ms: { type: 'number', description: 'Execution timeout in milliseconds (default: 120000)' },
641
- },
642
- },
643
- },
644
- {
645
- name: 'huaweicloud_sandbox_close_session',
646
- description:
647
- 'Close the persistent terminal session for a workspace. This closes the agent-side terminal session only — it does NOT delete the sandbox instance. Resource-pool sandbox deletion is developer-initiated (always ask for a second confirmation before guiding a delete) or handled by the platform resource-group idle-reclaim policy within the 7-day cap (v3 caliber); devkit never defers or performs deletion on the user behalf.',
648
- inputSchema: {
649
- type: 'object',
650
- properties: {
651
- workspace_id: {
652
- type: 'string',
653
- description:
654
- 'Workspace ID from huaweicloud_sandbox_connect return value. Required - must be passed explicitly when HW_WORKSPACE_ID is not set.',
655
- },
656
- username: { type: 'string', description: 'Login username (default: root)' },
657
- },
658
- },
659
- },
660
- {
661
- name: 'huaweicloud_sandbox_upload_file',
662
- description:
663
- 'Upload a local file into the sandbox workspace. Base64-encodes the file, writes it in small chunks through the terminal session (the exec channel is fragile for large single commands), then decodes and verifies the md5 checksum. The remote parent directory is created automatically if absent. Use this instead of embedding large file content directly in a command. local_path must be readable from the machine running the DevKit MCP server — if the file lives elsewhere, copy it to the local temp directory first.',
664
- inputSchema: {
665
- type: 'object',
666
- required: ['local_path', 'remote_path'],
667
- properties: {
668
- local_path: {
669
- type: 'string',
670
- description:
671
- 'Absolute path to the local file, readable from the machine running the DevKit MCP server (copy to the local temp dir first if not).',
672
- },
673
- remote_path: { type: 'string', description: 'Target path in the sandbox, e.g. /workspace/<repo>/index.html.' },
674
- workspace_id: {
675
- type: 'string',
676
- description:
677
- 'Workspace ID from huaweicloud_sandbox_connect return value. Required - must be passed explicitly when HW_WORKSPACE_ID is not set.',
678
- },
679
- username: { type: 'string', description: 'Login username (default: root)' },
680
- timeout_ms: { type: 'number', description: 'Execution timeout in milliseconds (default: 60000)' },
681
- },
682
- },
683
- },
684
- {
685
- name: 'huaweicloud_sandbox_upload_project',
686
- description:
687
- 'Package a local project directory and upload it to a sandbox workspace via HTTP tunnel. Falls back to base64 chunking if tunnel fails. Creates a tar.gz archive, uploads it, and extracts it on the sandbox by default. local_dir must be readable from the machine running the DevKit MCP server — if the project lives elsewhere, copy it to the local temp directory first.',
688
- inputSchema: {
689
- type: 'object',
690
- required: ['local_dir'],
691
- properties: {
692
- local_dir: {
693
- type: 'string',
694
- description:
695
- 'Local project directory, readable from the machine running the DevKit MCP server (copy to the local temp dir first if not).',
696
- },
697
- remote_dir: {
698
- type: 'string',
699
- description:
700
- 'Remote parent directory where project will be extracted (default: /workspace). Final layout: <remote_dir>/<dirname>/',
701
- },
702
- workspace_id: {
703
- type: 'string',
704
- description:
705
- 'Workspace ID from huaweicloud_sandbox_connect return value. Required - must be passed explicitly when HW_WORKSPACE_ID is not set.',
706
- },
707
- username: { type: 'string', description: 'Login username (default: root)' },
708
- exclude: {
709
- type: 'array',
710
- items: { type: 'string' },
711
- description: 'Patterns to exclude from archive (default: .git, node_modules, __pycache__, .venv)',
712
- },
713
- extract: {
714
- type: 'boolean',
715
- description: 'Extract tar.gz on sandbox after upload (default: true)',
716
- },
717
- timeout_ms: { type: 'number', description: 'Execution timeout in milliseconds (default: 300000)' },
718
- },
719
- },
720
- },
721
- {
722
- name: 'huaweicloud_sandbox_deploy_nginx',
723
- description:
724
- 'Deploy an nginx configuration on the sandbox and reload. Takes nginxType, port, project, outputDir from framework detection and writes the correct template (SPA try_files, SSR reverse proxy, or static). Also fixes directory traverse permissions on the project path. Use this instead of manually constructing nginx config — it handles permissions, template selection, and reload in one call. If the requested port is already in use, the actual port is auto-incremented and returned in "port" alongside a warning.',
725
- inputSchema: {
726
- type: 'object',
727
- required: ['nginx_type', 'port', 'project', 'output_dir'],
728
- properties: {
729
- nginx_type: {
730
- type: 'string',
731
- description:
732
- 'Nginx config type from framework detection: spa (try_files fallback for SPA/SSG/cross-platform), proxy (reverse proxy for SSR), or static (plain root for Hugo/Hexo).',
733
- enum: ['spa', 'proxy', 'static'],
734
- },
735
- port: { type: 'number', description: 'Listen port (from framework detection).' },
736
- project: { type: 'string', description: 'Project directory name under /workspace, e.g. movie-ticket.' },
737
- output_dir: {
738
- type: 'string',
739
- description: 'Build output directory relative to /workspace/<project>, e.g. dist/build/h5.',
740
- },
741
- node_port: { type: 'number', description: 'Node.js app port for SSR (required when nginx_type=proxy).' },
742
- public_port: { type: 'number', description: 'Public listen port for SSR proxy (optional, defaults to port).' },
743
- config_name: {
744
- type: 'string',
745
- description:
746
- 'Config file name (without .conf suffix). Defaults to the project name, ensuring each project gets its own config. Override with distinct names (e.g. admin, docs) for sub-app deployments.',
747
- },
748
- workspace_id: {
749
- type: 'string',
750
- description:
751
- 'Workspace ID from huaweicloud_sandbox_connect return value. Required - must be passed explicitly when HW_WORKSPACE_ID is not set.',
752
- },
753
- username: { type: 'string', description: 'Login username (default: root)' },
754
- timeout_ms: { type: 'number', description: 'Execution timeout in milliseconds (default: 30000)' },
755
- },
756
- },
757
- },
758
- {
759
- name: 'huaweicloud_sandbox_deploy_check',
760
- description:
761
- 'Run a deployment completeness check on the sandbox. Verifies nginx is serving, output directory exists, DevBridge tunnel is active and accessible, and QR code exists (cross-platform). Returns a score, nextStep, and (when the DevBridge tunnel is missing) an executable "remediation" command string. Call this at the end of a deployment workflow to confirm everything is working before reporting success.',
762
- inputSchema: {
763
- type: 'object',
764
- required: ['port', 'project', 'output_dir'],
765
- properties: {
766
- port: { type: 'number', description: 'App listen port (from framework detection).' },
767
- project: { type: 'string', description: 'Project directory name under /workspace.' },
768
- output_dir: {
769
- type: 'string',
770
- description: 'Build output directory relative to /workspace/<project>, e.g. dist/build/h5.',
771
- },
772
- framework_type: {
773
- type: 'string',
774
- description: 'Framework type from detect_framework. Set to cross-platform for QR code check.',
775
- enum: ['spa', 'ssr', 'ssg', 'cross-platform', 'monorepo', 'static'],
776
- },
777
- workspace_id: {
778
- type: 'string',
779
- description:
780
- 'Workspace ID from huaweicloud_sandbox_connect return value. Required - must be passed explicitly when HW_WORKSPACE_ID is not set.',
781
- },
782
- username: { type: 'string', description: 'Login username (default: root)' },
783
- timeout_ms: { type: 'number', description: 'Execution timeout in milliseconds (default: 30000)' },
784
- },
785
- },
786
- },
787
- {
788
- name: 'huaweicloud_sandbox_expose_tunnel',
789
- description:
790
- 'Expose a port on the sandbox to a public DevBridge tunnel URL (devbridge 0.2.x). Authenticates automatically (keyring → auto-create → /tmp/hw_api_key), selectively cleans only same-port/orphan tunnels (cleanup_mode=stale, default — other ports, other sessions and keepalive-protected tunnels are preserved, except a tunnel bound to THIS port which is replaced), starts the host, extracts the public URL (https://<id>-<port>.devbridge-s2.hwtunnel.com), and health-checks it before returning. On 10006 quota it removes orphans first, then the oldest non-keepalive tunnel one at a time. AUTO-ENROLLS the tunnel into the keepalive watchdog (host re-attach + daily 720h renewal + health check) by default, merged into existing coverage — pass keepalive:false to opt out. Use the ACTUAL port reported by huaweicloud_sandbox_deploy_nginx (its "port" field auto-increments on conflict) — never the originally requested port. Returns ok, publicUrl, port, tunnelId, keepalive.enrolled, warnings, sandboxLifetime and urlLifetimeHint. The urlLifetimeHint MUST be relayed to the developer together with the URL: the tunnel expiry is NOT the sandbox lifetime — an idle sandbox shuts down (ephemeral also auto-deletes), which kills the URL. If the API Key is missing on a release build it returns ok:false with instructions to create one.',
791
- inputSchema: {
792
- type: 'object',
793
- required: ['port'],
794
- properties: {
795
- port: {
796
- type: 'number',
797
- description:
798
- 'Actual port nginx is listening on — use the "port" value returned by huaweicloud_sandbox_deploy_nginx, not the originally requested port.',
799
- },
800
- expiry_hours: {
801
- type: 'number',
802
- description:
803
- 'Tunnel lifetime in hours via devbridge -e (1-720; 720 = the 30-day maximum, default 72). The expiry is a rolling window — the keepalive watchdog renews daily to keep the URL alive indefinitely.',
804
- },
805
- keepalive: {
806
- type: 'boolean',
807
- description:
808
- 'Auto-enroll the tunnel into the keepalive watchdog (default true — every tunnel deployed to the sandbox must be keepalive-protected). Pass false only when the caller explicitly manages keepalive itself.',
809
- },
810
- cleanup_mode: {
811
- type: 'string',
812
- enum: ['stale', 'all', 'none'],
813
- description:
814
- 'Tunnel cleanup before exposing. stale (default): delete same-port tunnels + orphan records/hosts; preserve other ports, other sessions and keepalive-protected tunnels — except a tunnel bound to THIS port, which is always replaced. all: wipe every tunnel/host (manual reset only). none: no cleanup (a stale same-port host can then conflict).',
815
- },
816
- workspace_id: {
817
- type: 'string',
818
- description:
819
- 'Workspace ID from huaweicloud_sandbox_connect return value. Required - must be passed explicitly when HW_WORKSPACE_ID is not set.',
820
- },
821
- username: { type: 'string', description: 'Login username (default: root)' },
822
- timeout_ms: { type: 'number', description: 'Execution timeout in milliseconds (default: 90000)' },
823
- },
824
- },
825
- },
826
- {
827
- name: 'huaweicloud_sandbox_renew_tunnel',
828
- description:
829
- 'Renew a DevBridge tunnel lifetime via devbridge update <tunnelId> -e <hours> (1-720; 720 = the 30-day maximum). The expiry is a rolling window: renewal sets expiration = now + hours regardless of remaining time, so renewing before expiry keeps the SAME tunnel URL alive indefinitely. A renewal counts as ok only when the update succeeds AND show -v reports the absolute tunnelExpiration — the management plane can lose a tunnel record (10002 "tunnel not found") while the data plane keeps serving. Returns ok, tunnelId, expiresAt (ISO), renewedForHours. Pair with huaweicloud_sandbox_keepalive_watchdog for unattended daily renewal.',
830
- inputSchema: {
831
- type: 'object',
832
- required: ['tunnel_id'],
833
- properties: {
834
- tunnel_id: {
835
- type: 'string',
836
- description:
837
- 'Short tunnel ID from huaweicloud_sandbox_expose_tunnel (e.g. nv2dvv6w) — extractable from the public URL as https://<tunnel_id>-<port>.devbridge-s2.hwtunnel.com.',
838
- },
839
- expiry_hours: {
840
- type: 'number',
841
- description:
842
- 'Renewal horizon in hours (1-720, default 720). The expiration becomes now + expiry_hours (rolling window).',
843
- },
844
- workspace_id: {
845
- type: 'string',
846
- description:
847
- 'Workspace ID from huaweicloud_sandbox_connect return value. Required - must be passed explicitly when HW_WORKSPACE_ID is not set.',
848
- },
849
- username: { type: 'string', description: 'Login username (default: root)' },
850
- timeout_ms: { type: 'number', description: 'Execution timeout in milliseconds (default: 60000)' },
851
- },
852
- },
853
- },
854
- {
855
- name: 'huaweicloud_sandbox_keepalive_watchdog',
856
- description:
857
- 'Install a keepalive watchdog in the sandbox that keeps DevBridge tunnel URLs alive indefinitely (three-layer pattern, proven in the 2026-10 tunnel-persistence test): (1) re-attaches the host with devbridge host <tunnelId> if the process dies — the URL is bound to the tunnel ID so it never changes; (2) renews every tunnel daily with devbridge update <tunnelId> -e 720 (29-day failure tolerance); (3) health-checks each URL every 5 minutes, logging warnings to /tmp/tunnel-keepalive.log. Installs as a setsid-detached loop at /tmp/tunnel-keepalive.sh; re-running replaces the old loop. URLs are hardcoded per tunnel because devbridge port list output is wrapped in OSC escapes that break anchored greps. Call AFTER huaweicloud_sandbox_expose_tunnel; requires DevBridge credentials (auth) in the sandbox.',
858
- inputSchema: {
859
- type: 'object',
860
- required: ['tunnels'],
861
- properties: {
862
- tunnels: {
863
- type: 'array',
864
- description:
865
- 'Tunnels to watch. Get tunnelId + url from huaweicloud_sandbox_expose_tunnel (publicUrl contains the tunnelId as https://<tunnel_id>-<port>.devbridge-s2.hwtunnel.com).',
866
- items: {
867
- type: 'object',
868
- required: ['tunnel_id', 'url'],
869
- properties: {
870
- tunnel_id: { type: 'string', description: 'Short tunnel ID (e.g. kag7rozs).' },
871
- url: { type: 'string', description: 'Full public https URL of the tunnel (used for the health check).' },
872
- },
873
- },
874
- },
875
- workspace_id: {
876
- type: 'string',
877
- description:
878
- 'Workspace ID from huaweicloud_sandbox_connect return value. Required - must be passed explicitly when HW_WORKSPACE_ID is not set.',
879
- },
880
- username: { type: 'string', description: 'Login username (default: root)' },
881
- timeout_ms: { type: 'number', description: 'Execution timeout in milliseconds (default: 60000)' },
882
- },
883
- },
884
- },
885
- {
886
- name: 'huaweicloud_sandbox_check_user',
887
- description:
888
- 'Check if the current user has completed real-name verification and signed the required agreements. Returns 200 {realnameVerified, agreementSigned} when all good; throws 403 HDKIT_NOT_REALNAME / HDKIT_NOT_AGREEMENT / HDKIT_NOT_REALNAME_AND_AGREEMENT to indicate what is missing. Never signs anything itself.',
889
- inputSchema: {
890
- type: 'object',
891
- properties: {},
892
- },
893
- },
894
- {
895
- name: 'huaweicloud_sandbox_sign_agreement',
896
- description:
897
- "Sign all unsigned or outdated agreements for the current user. Required before huaweicloud_sandbox_connect if check-user returns agreementSigned=false. CRITICAL: only call after the user explicitly consents to signing — never sign agreements on the user's behalf without their explicit request.",
898
- inputSchema: {
899
- type: 'object',
900
- properties: {},
901
- },
902
- },
903
- {
904
- name: 'huaweicloud_sandbox_connect',
905
- description:
906
- 'Connect to a sandbox via hdkitservice. One instance per user per pool — reuses the same-pool sandbox if available, otherwise creates a new one. Quota: 1 instance per pool type (a user may hold 1 ephemeral AND 1 persistent simultaneously; same-type requests reuse the existing instance). On quota exhaustion the API returns HTTP 429 with a Retry-After header and a dual error code: HDKIT_QUOTA_EXCEEDED (retry useless — release or reuse the existing instance) vs HDKIT_CAPACITY_INSUFFICIENT (pool capacity; retry later / off-peak). Gateway 502/504 timeouts during orchestration are retried automatically (30s/45s backoff) — the server may already have created the instance, so a retry reuses it. Returns session_id, dev_stage_id, connection_id, connection_address, expiresAt (STS credential expiry), pool_type/template_id echo, server-configured lifecycle numbers (pool_idle_shutdown_minutes / pool_idle_delete_minutes / pool_reclaim_minutes) and started (true when a reused instance was woken from shutdown). Lifecycle hints are announced only on the first connect of a session or when started=true. Ephemeral pool (default): idle auto-shutdown after 30min, auto-delete after 1h — do not keep important data there. Persistent pool: data disk retained (EVS 32G), idle shutdown after 1h, idle reclaim capped at 7 days. Numbers are configured by hdkitservice; the text follows the server echo and falls back to these defaults.',
907
- inputSchema: {
908
- type: 'object',
909
- properties: {
910
- source: {
911
- type: 'string',
912
- description:
913
- 'Source identifier (default: WEB). Options: VSCODE, CLI, WEB, WEBVNC, WEBPTY, WEBIDE, CURSOR, etc.',
914
- },
915
- pool_type: {
916
- type: 'string',
917
- enum: ['ephemeral', 'persistent'],
918
- description:
919
- 'Sandbox pool type (default ephemeral). ephemeral = non-persistent: idle auto-shutdown 30min + auto-delete 1h (platform scheduled task, verified) — save important data elsewhere; persistent = data disk retained, idle reclaim within 7 days. Each user may hold one instance per pool type (1+1). Explicit template_id overrides pool_type.',
920
- },
921
- template_id: { type: 'string', description: 'Template ID; overrides server default (only for new sandbox)' },
922
- flavor_id: { type: 'string', description: 'Flavor ID; overrides server default (only for new sandbox)' },
923
- env: { type: 'object', description: 'Environment variables to set in the sandbox (only for new sandbox)' },
924
- git: {
925
- type: 'object',
926
- description: 'Git repo config (only for new sandbox)',
927
- properties: {
928
- repo_url: { type: 'string', description: 'Git repository URL' },
929
- repo_branch: { type: 'string', description: 'Git branch' },
930
- repo_name: { type: 'string', description: 'Repository name' },
931
- target_path: { type: 'string', description: 'Clone target path in sandbox' },
932
- open_type: { type: 'string', description: 'Open type' },
933
- },
934
- },
935
- },
936
- },
937
- },
938
- {
939
- name: 'huaweicloud_sandbox_credentials',
940
- description:
941
- 'Configure temporary AK/SK for a sandbox via hdkitservice. Validates the current AK/SK against IAM before injecting (invalid SK is rejected here instead of failing later with APIGW.0301 during exec), then injects temporary credentials into the sandbox. Also injects an optional DevBridge API Key — required for devbridge 0.2.x tunnel exposure because 0.2.x removed AK/SK login. The API Key is a long-lived account-level credential, so it is stored in a separate file (/tmp/hw_api_key, 0600) from the temporary AK/SK (/tmp/hw_creds.sh). Source of truth: local HW_API_KEY env first, then the api_key param. The sandbox must be in RUNNING state.',
942
- inputSchema: {
943
- type: 'object',
944
- properties: {
945
- session_id: { type: 'string', description: 'Session ID from huaweicloud_sandbox_connect' },
946
- dev_stage_id: { type: 'string', description: 'DevStation environment ID (alternative to session_id)' },
947
- enable_sts: { type: 'boolean', description: 'Whether to enable STS temporary AK/SK (default: true)' },
948
- region: {
949
- type: 'string',
950
- description:
951
- 'Region used for IAM credential validation and project_id resolution (defaults to the configured region)',
952
- },
953
- api_key: {
954
- type: 'string',
955
- description:
956
- 'DevBridge API Key (devbridge_...), injected into the sandbox as HW_API_KEY for devbridge 0.2.x auth. The local HW_API_KEY environment variable takes precedence over this param (preferred delivery — keeps the long-lived key out of the conversation). Users create one at https://devstation.connect.huaweicloud.com/space/devbridge/apikey (full value shown once at creation). Required for exposing web apps via devbridge 0.2.x; if missing, guide the user through creating one.',
957
- },
958
- },
959
- },
960
- },
961
- {
962
- name: 'huaweicloud_voucher_status',
963
- description:
964
- '查询代金券领取状态。用户首次使用、开始会话或询问插件能力时,应主动调用本工具检查:未领取(claimed=false)则主动提示可领取一张代金券;已领取(claimed=true)则不提示、不打扰。',
965
- inputSchema: {
966
- type: 'object',
967
- properties: {
968
- domain_id: {
969
- type: 'string',
970
- description: 'Optional. Leave empty in production — account is resolved from IAM automatically.',
971
- },
972
- },
973
- },
974
- },
975
- {
976
- name: 'huaweicloud_voucher_claim',
977
- description: '领取代金券(一人一次)。重复领取会返回已领取。',
978
- inputSchema: {
979
- type: 'object',
980
- properties: {
981
- domain_id: {
982
- type: 'string',
983
- description: 'Optional. Leave empty in production — account is resolved from IAM automatically.',
984
- },
985
- },
986
- },
987
- },
988
- {
989
- name: 'huaweicloud_competition_voucher_claim',
990
- description:
991
- '领取华为开发者大赛·小红书skill创新赛专属华为云代金券。前置条件:用户已完成该赛事报名(后端自动校验,未报名返回 code=HDKIT_NOT_SIGNED_UP)。仅当用户明确要求领取该赛事代金券时调用,不要主动提示。重复领取会返回已领取。',
992
- inputSchema: {
993
- type: 'object',
994
- properties: {
995
- domain_id: {
996
- type: 'string',
997
- description: 'Optional. Leave empty in production — account is resolved from IAM automatically.',
998
- },
999
- },
1000
- },
1001
- },
1002
- {
1003
- name: 'huaweicloud_check_update',
1004
- description:
1005
- '检查 huaweicloud-devkit 插件是否有新版本。结果含 currentVersion / latestStable / latestNext / targetVersion / updateAvailable / dismissExpiresAt / result。支持 dismiss:true 记录用户拒绝(3 天冷却,新版本会重新提醒)。',
1006
- inputSchema: {
1007
- type: 'object',
1008
- properties: {
1009
- dismiss: { type: 'boolean', description: '用户拒绝升级时传 true,记录冷却状态。' },
1010
- dismissVersion: {
1011
- type: 'string',
1012
- description: '与 dismiss:true 搭配,用户拒绝的版本号。缺省时用当前检测到的 targetVersion。',
1013
- },
1014
- },
1015
- },
1016
- },
1017
- {
1018
- name: 'huaweicloud_upgrade',
1019
- description:
1020
- '升级 huaweicloud-devkit 到最新版本。执行前必须先征得用户同意。version 仅支持 "latest"。完成后需重启会话生效。',
1021
- inputSchema: {
1022
- type: 'object',
1023
- properties: {
1024
- version: { type: 'string', description: '仅支持 "latest"(默认)。' },
1025
- target: {
1026
- type: 'string',
1027
- description: 'agent 目标(opencode/codex/codearts/.../all)。缺省时用 all(仅更新已安装的)。',
1028
- },
1029
- },
1030
- },
1031
- },
1032
- {
1033
- name: 'huaweicloud_obs_set_website_config',
1034
- description:
1035
- '配置 OBS 桶的静态网站托管。KooCLI OBS 不支持 SetBucketWebsite API,此工具内部实现 AWS4 签名调用 OBS REST API,屏蔽签名细节。支持 set(配置)、get(查询)、delete(删除)三种操作。操作前需确保桶已创建且已设置 public-read ACL。',
1036
- inputSchema: {
1037
- type: 'object',
1038
- properties: {
1039
- action: {
1040
- type: 'string',
1041
- enum: ['set', 'get', 'delete'],
1042
- description: '操作类型:set=配置静态网站托管,get=查询当前配置,delete=删除配置',
1043
- },
1044
- bucket: { type: 'string', description: 'OBS 桶名称' },
1045
- region: { type: 'string', description: 'OBS 桶所在区域,如 cn-north-4' },
1046
- indexDocument: {
1047
- type: 'string',
1048
- description: '首页文件名(action=set 时必填),如 index.html',
1049
- },
1050
- errorDocument: {
1051
- type: 'string',
1052
- description: '错误页面文件名(action=set 时可选),如 404.html 或 error.html',
1053
- },
1054
- },
1055
- required: ['action', 'bucket', 'region'],
1056
- },
1057
- },
1058
- {
1059
- name: 'huaweicloud_obs_set_cors',
1060
- description:
1061
- '配置 OBS 桶的 CORS 规则(浏览器直传前置条件)。KooCLI OBS 不支持 cors 子命令,此工具内部实现 AWS4 签名调用 OBS REST API(PUT/GET/DELETE /?cors),屏蔽签名细节。支持 set(配置)、get(查询)、delete(删除)三种操作。allowedMethod 必须含 HEAD(BrowserJS SDK 每次操作前发 HEAD ?apiversion 探测,缺 HEAD 时浏览器吞掉探测请求)。配置成功后用返回体中的 verify 命令做 OPTIONS 预检验证(200 + Access-Control-Allow-Origin 才算成功)。',
1062
- inputSchema: {
1063
- type: 'object',
1064
- properties: {
1065
- action: {
1066
- type: 'string',
1067
- enum: ['set', 'get', 'delete'],
1068
- description: '操作类型:set=配置 CORS 规则,get=查询当前规则,delete=删除规则',
1069
- },
1070
- bucket: { type: 'string', description: 'OBS 桶名称' },
1071
- region: { type: 'string', description: 'OBS 桶所在区域,如 cn-north-4' },
1072
- rules: {
1073
- type: 'array',
1074
- description:
1075
- 'CORS 规则数组(action=set 时必填)。每条规则:allowedOrigin(如 https://your-app)、allowedMethod 数组(GET/PUT/POST/DELETE/HEAD,必须含 HEAD)、allowedHeader 数组(默认 ["*"])、maxAgeSeconds(默认 3000)',
1076
- items: {
1077
- type: 'object',
1078
- properties: {
1079
- allowedOrigin: { type: 'string', description: '允许的来源,如 https://your-app.example.com 或 *' },
1080
- allowedMethod: {
1081
- type: 'array',
1082
- items: { type: 'string' },
1083
- description: '允许的 HTTP 方法,必须包含 HEAD',
1084
- },
1085
- allowedHeader: {
1086
- type: 'array',
1087
- items: { type: 'string' },
1088
- description: '允许的请求头,默认 ["*"]',
1089
- },
1090
- maxAgeSeconds: { type: 'number', description: '预检结果缓存秒数,默认 3000' },
1091
- },
1092
- required: ['allowedOrigin', 'allowedMethod'],
1093
- },
1094
- },
1095
- },
1096
- required: ['action', 'bucket', 'region'],
1097
- },
1098
- },
1099
- ];
1100
-
1101
- function toolInvokeValue(name, args) {
1102
- if (name === 'huaweicloud_run_readonly_command' || name === 'huaweicloud_run_approved_command') {
1103
- const cmdArgs = args.args || [];
1104
- const filtered = cmdArgs.filter((a) => !a.startsWith('--') && !a.startsWith('-') && !a.includes('='));
1105
- if (filtered.length >= 2) return `hcloud ${filtered.slice(0, 2).join(' ')}`;
1106
- }
1107
- if (name === 'huaweicloud_list_operations' && args.service) {
1108
- return args.service;
1109
- }
1110
- if (name === 'huaweicloud_retrieve_skill' && args.name) {
1111
- return args.name;
1112
- }
1113
- if (name === 'huaweicloud_hook_check_command' && args.command) {
1114
- const parts = args.command.split(/\s+/).filter((p) => !p.startsWith('--'));
1115
- if (parts[0] === 'hcloud' && parts[1]) return `hcloud ${parts.slice(1, 3).join(' ')}`;
1116
- return parts.slice(0, 2).join(' ');
1117
- }
1118
- return '1';
1119
- }
1120
-
1121
- const execFilePromise = promisify(execFile);
1122
-
1123
- async function isGitAvailable() {
1124
- try {
1125
- await execFilePromise('git', ['--version'], { timeout: 5000 });
1126
- return true;
1127
- } catch {
1128
- return false;
1129
- }
1130
- }
1131
-
1132
- async function gitCloneToLocal(repoUrl, branch, targetBasename) {
1133
- const tempRoot = join(tmpdir(), `hw-sandbox-git-${Date.now()}`);
1134
- const cloneDir = join(tempRoot, targetBasename);
1135
- mkdirSync(tempRoot, { recursive: true });
1136
- const args = ['clone', '--depth', '1'];
1137
- if (branch) args.push('-b', branch);
1138
- args.push(repoUrl, cloneDir);
1139
- await execFilePromise('git', args, { timeout: 120000 });
1140
- return { cloneDir, tempRoot };
1141
- }
1142
-
1143
- async function transferGitRepo(args, devStageId, connectResult) {
1144
- const git = args.git;
1145
- if (!git?.repo_url || !git?.target_path) return;
1146
-
1147
- const { repo_url, repo_branch, target_path } = git;
1148
-
1149
- try {
1150
- const existsCheck = await execOneShot(
1151
- devStageId,
1152
- `test -d "${target_path}/.git" && echo "EXISTS" || echo "NOT_EXISTS"`,
1153
- 'root',
1154
- 10000,
1155
- );
1156
- if (String(existsCheck.stdout || '').includes('EXISTS')) {
1157
- connectResult._repoStatus = 'already_exists';
1158
- return;
1159
- }
1160
- } catch {
1161
- /* 检查失败继续 */
1162
- }
1163
-
1164
- const hasGit = await isGitAvailable();
1165
- if (hasGit) {
1166
- let tempRoot = null;
1167
- try {
1168
- const targetName = basename(target_path);
1169
- const { cloneDir, tempRoot: root } = await gitCloneToLocal(repo_url, repo_branch, targetName);
1170
- tempRoot = root;
1171
- await uploadProjectWithSession(devStageId, cloneDir, dirname(target_path), 'root', 300000, {
1172
- extract: true,
1173
- exclude: ['.git', 'node_modules'],
1174
- });
1175
- connectResult._repoStatus = 'uploaded_from_local';
1176
- return;
1177
- } catch {
1178
- /* 本地方式失败,进入兜底 */
1179
- } finally {
1180
- if (tempRoot) {
1181
- try {
1182
- rmSync(tempRoot, { recursive: true, force: true });
1183
- } catch {
1184
- /* 清理失败忽略 */
1185
- }
1186
- }
1187
- }
1188
- }
1189
-
1190
- const branchFlag = repo_branch ? `-b ${repo_branch}` : '';
1191
- await execOneShot(
1192
- devStageId,
1193
- `mkdir -p $(dirname "${target_path}") && git clone --depth 1 ${branchFlag} "${repo_url}" "${target_path}"`,
1194
- 'root',
1195
- 120000,
1196
- );
1197
- connectResult._repoStatus = 'cloned_in_sandbox';
1198
- }
1199
-
1200
- const pendingConfirms = new Map();
1201
- // Tombstones for confirm tokens already consumed, so a repeat
1202
- // huaweicloud_auth_confirm call can be classified as already_processed
1203
- // instead of not_found (D4-24, #745). Kept in-memory only: confirm tokens
1204
- // are session-scoped and never persisted across processes.
1205
- const consumedConfirms = new Map();
1206
-
1207
- function readImportFile() {
1208
- const path = join(dirname(globalCredentialsPath()), 'creds-import.json');
1209
- try {
1210
- if (!existsSync(path)) return null;
1211
- // Strip a leading UTF-8 BOM: PowerShell `Set-Content -Encoding UTF8` writes
1212
- // one, which plain JSON.parse rejects (#devkit-体验报告 P1-4).
1213
- const data = JSON.parse(readFileSync(path, 'utf8').replace(/^\uFEFF/, ''));
1214
- return {
1215
- ak: String(data.ak || ''),
1216
- sk: String(data.sk || ''),
1217
- securityToken: String(data.securityToken || ''),
1218
- region: String(data.region || ''),
1219
- };
1220
- } catch {
1221
- // Malformed/undecodable import file is un-replayable — wipe it. A VALID
1222
- // file is kept so a rejected persist can be replayed (see #502).
1223
- try {
1224
- rmSync(path, { force: true });
1225
- } catch {
1226
- // ignore
1227
- }
1228
- return null;
1229
- }
1230
- }
1231
-
1232
- function clearImportFile() {
1233
- const path = join(dirname(globalCredentialsPath()), 'creds-import.json');
1234
- try {
1235
- rmSync(path, { force: true });
1236
- } catch {
1237
- // best-effort: an absent or locked file is not an error
1238
- }
1239
- }
1240
-
1241
- function persistCredentials(ak, sk, securityToken, region) {
1242
- if (String(securityToken || '')) {
1243
- return {
1244
- status: 'error',
1245
- error: 'Temporary STS credentials cannot be persisted (R3). Use action=temporary.',
1246
- scope: 'rejected',
1247
- };
1248
- }
1249
- const before = backupGlobalCredentials();
1250
- writeGlobalCredentials({ ak, sk: String(sk), securityToken: '', region, configuredBySession: true });
1251
- setConfiguredBySession(true);
1252
- let obs;
1253
- try {
1254
- writeObsConfigFile({ ak, sk, securityToken, region });
1255
- obs = { ok: true };
1256
- } catch (error) {
1257
- obs = { ok: false, error: error.message };
1258
- }
1259
- const profile = resolveManagedProfile();
1260
- let hcloud;
1261
- if (!profile) {
1262
- hcloud = { ok: false, reason: 'KooCLI current profile unresolved' };
1263
- } else {
1264
- // #920: `configure set` refuses an empty --cli-security-token, so a stale
1265
- // token already in the profile survives the write and poisons every hcloud
1266
- // call with APIGW.0301 — while the tool still reports "synchronized". When
1267
- // persisting WITHOUT a token, walk the documented manual bypass
1268
- // (delete the profile, then re-configure) so the on-disk profile truly
1269
- // matches the incoming credentials. The delete is best-effort: a missing
1270
- // profile ("nothing to clean") must not fail the persist.
1271
- let profileReset = false;
1272
- if (!String(securityToken || '')) {
1273
- const deleted = runHcloudProfileDelete(profile);
1274
- profileReset = deleted.ok || /not (exist|found)/i.test(deleted.error || '');
1275
- }
1276
- hcloud = runHcloudConfigure(profile, ak, sk, region);
1277
- hcloud.profileReset = profileReset;
1278
- }
1279
- if (hcloud.ok) {
1280
- writeLastSync({ kooCliProfile: profile, s1Fingerprint: fingerprint(ak, sk) });
1281
- }
1282
- return {
1283
- status: obs.ok && hcloud.ok ? 'ok' : 'partial',
1284
- scope: 'persist',
1285
- backedUp: Boolean(before),
1286
- obs: obs.ok ? { configured: true } : { configured: false, error: obs.error },
1287
- hcloud,
1288
- note: 'S1 written with configuredBySession (R9), which now takes priority over env-injected credentials; S2(current profile) and S3 synced. Persisting without a security token resets the target profile first (delete + recreate) so a stale token cannot survive the write (#920). Note: running `auth init` later clears the configuredBySession flag and env credentials regain priority.',
1289
- };
1290
- }
1291
-
1292
- function refreshUserHashAfterAuthChange({ regenerate = true } = {}) {
1293
- clearUserHash();
1294
- if (regenerate) {
1295
- hdkitGenerateUserHash().catch(() => {});
1296
- }
1297
- }
1298
-
1299
- // Reject invalid numeric args up front instead of silently coercing them to
1300
- // NaN (which downstream defaults would absorb as "no timeout set") — see #530.
1301
- const NUMERIC_ARG_KEYS = ['timeoutMs', 'maxRetries', 'timeout_ms'];
1302
-
1303
- function normalizeNumericArgs(args) {
1304
- const out = { ...args };
1305
- for (const key of NUMERIC_ARG_KEYS) {
1306
- const value = out[key];
1307
- if (value === undefined || value === null) continue;
1308
- const num = Number(value);
1309
- // timeouts must be positive; maxRetries may be 0 (means "no retries").
1310
- const isRetries = key === 'maxRetries';
1311
- const valid = Number.isFinite(num) && (isRetries ? Number.isSafeInteger(num) && num >= 0 : num > 0);
1312
- if (!valid) {
1313
- throw new Error(
1314
- `Invalid parameter "${key}": expected a ${isRetries ? 'non-negative integer' : 'positive number'}, received ${JSON.stringify(value)}.`,
1315
- );
1316
- }
1317
- out[key] = num;
1318
- }
1319
- return out;
1320
- }
1321
-
1322
- export async function callTool(name, rawArgs = {}, opts = {}) {
1323
- const args = normalizeNumericArgs(rawArgs);
1324
- const toolValue = toolInvokeValue(name, args);
1325
- trackToolInvoke(name, toolValue);
1326
-
1327
- switch (name) {
1328
- case 'huaweicloud_check_cli':
1329
- return runVersionCheck();
1330
- case 'huaweicloud_install_hcloud':
1331
- return installKooCli();
1332
- case 'huaweicloud_plan_cli_command':
1333
- return planHcloudCommand(args.args || [], { allowWrites: args.allowWrites === true });
1334
- case 'huaweicloud_run_readonly_command':
1335
- return runHcloud(args.args || [], {
1336
- timeoutMs: args.timeoutMs,
1337
- maxRetries: args.maxRetries,
1338
- cwd: args.cwd,
1339
- stdin: args.stdin,
1340
- });
1341
- case 'huaweicloud_list_operations':
1342
- return listOperations(args.service, { timeoutMs: args.timeoutMs });
1343
- case 'huaweicloud_run_approved_command':
1344
- return runApprovedCommand(args);
1345
- case 'huaweicloud_show_profile_redacted':
1346
- return showProfileRedacted(args.profile);
1347
- case 'huaweicloud_hook_check_command':
1348
- return hookResult(evaluateCommandRisk(args.command || ''));
1349
- case 'huaweicloud_hook_check_artifacts':
1350
- return hookResult(evaluateArtifacts(args.artifacts || []));
1351
- case 'huaweicloud_hook_check_deploy_plan':
1352
- return hookResult(evaluateDeployPlan(args.plan || {}));
1353
- case 'huaweicloud_service_catalog':
1354
- return serviceCatalog(args.intent);
1355
- case 'huaweicloud_search_docs':
1356
- return searchDocs(args.query || '', args.topic || 'all');
1357
- case 'huaweicloud_retrieve_skill':
1358
- trackSkillRetrieve(args.name || '');
1359
- return retrieveSkill(args.name || '');
1360
- case 'huaweicloud_list_regions':
1361
- return listRegions();
1362
- case 'huaweicloud_check_account_type':
1363
- return checkAccountType(args);
1364
- case 'huaweicloud_get_regional_availability':
1365
- return getRegionalAvailability(args.service || '', args.region || '');
1366
- case 'huaweicloud_explain_error':
1367
- return explainError(args);
1368
- case 'huaweicloud_search_marketplace':
1369
- return searchMarketplace(args.query || '', args.category || '');
1370
- case 'huaweicloud_get_service_icon':
1371
- return getServiceIcon(args.service || '', args.category || '');
1372
- case 'huaweicloud_detect_framework': {
1373
- const projectPath = args.projectPath;
1374
- if (!projectPath) throw new Error('projectPath is required.');
1375
- const result = detectFramework(projectPath);
1376
- if (!result) {
1377
- return { ok: false, error: 'No recognized web framework found in: ' + projectPath };
1378
- }
1379
- return { ok: true, ...result };
1380
- }
1381
- case 'huaweicloud_setup_obs_config':
1382
- return setupObsConfig(args.profile);
1383
- case 'huaweicloud_auth_status':
1384
- return getAuthStatus(args.target || 'all');
1385
- case 'huaweicloud_auth_sync': {
1386
- const result = syncAuth(args.target || 'all');
1387
- refreshUserHashAfterAuthChange();
1388
- return result;
1389
- }
1390
- case 'huaweicloud_auth_init':
1391
- if (args.clear) {
1392
- clearRuntimeCredentials();
1393
- refreshUserHashAfterAuthChange({ regenerate: false });
1394
- return { status: 'cleared', message: 'Runtime credentials cleared. Fallback to env/file.' };
1395
- }
1396
- if (!args.ak || !args.sk) {
1397
- throw new Error('ak and sk are required. Set clear=true to clear runtime credentials.');
1398
- }
1399
- setRuntimeCredentials(args.ak, args.sk, undefined, args.region);
1400
- refreshUserHashAfterAuthChange();
1401
- return { status: 'ok', message: 'Runtime credentials set for this MCP session.' };
1402
- case 'huaweicloud_auth_switch': {
1403
- const action = args.action || 'temporary';
1404
- if (action === 'clear') {
1405
- clearRuntimeCredentials();
1406
- refreshUserHashAfterAuthChange({ regenerate: false });
1407
- return { status: 'cleared', message: 'Runtime credentials cleared. Fallback to env/file/S1.' };
1408
- }
1409
-
1410
- let ak = args.ak || '';
1411
- let sk = args.sk || '';
1412
- let securityToken = args.securityToken || '';
1413
- let region = args.region || '';
1414
- const sourceChannel = args.mode || 'memory';
1415
- let importedFromFile = false;
1416
-
1417
- if (sourceChannel === 'import' && (!ak || !sk)) {
1418
- const imported = readImportFile();
1419
- if (imported) {
1420
- ({ ak, sk, securityToken, region } = imported);
1421
- importedFromFile = true;
1422
- }
1423
- }
1424
- if (sourceChannel === 'mcp-config' && (!ak || !sk)) {
1425
- const cc = readCodeArtsCredentials();
1426
- if (cc) {
1427
- ak = cc.ak;
1428
- sk = cc.sk;
1429
- securityToken = cc.securityToken || '';
1430
- region = cc.region || region;
1431
- }
1432
- }
1433
-
1434
- if (!ak || !sk) {
1435
- if (sourceChannel === 'import') {
1436
- throw new Error(
1437
- 'ak and sk are required. creds-import.json 缺失或无法解析(可能带 UTF-8 BOM 或非法 JSON),解析失败时文件已被清除。请用无 BOM 的 UTF-8 JSON 重新写入后重试 mode=import(PowerShell 推荐 [IO.File]::WriteAllText 配 UTF8Encoding($false))。',
1438
- );
1439
- }
1440
- throw new Error('ak and sk are required (or provide creds-import.json for mode=import).');
1441
- }
1442
-
1443
- if (action === 'persist' && !String(region || '').trim()) {
1444
- return {
1445
- status: 'error',
1446
- scope: 'invalid_region',
1447
- error:
1448
- 'region is required to persist credentials. Pass --region, or include "region" in creds-import.json (mode=import).',
1449
- };
1450
- }
1451
-
1452
- if (action === 'temporary') {
1453
- setRuntimeCredentials(ak, sk, securityToken || undefined, region);
1454
- refreshUserHashAfterAuthChange();
1455
- if (importedFromFile) clearImportFile();
1456
- return {
1457
- status: 'ok',
1458
- scope: 'temporary',
1459
- note: 'Runtime credentials active for this MCP process. hcloud commands still use the KooCLI current profile; use action=persist to align files.',
1460
- };
1461
- }
1462
-
1463
- // action === 'persist'
1464
- const prev = readGlobalCredentials();
1465
- const conflict = prev?.ak && prev.ak !== ak;
1466
- if (conflict) {
1467
- backupGlobalCredentials();
1468
- const token = `switch-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
1469
- pendingConfirms.set(token, {
1470
- newAk: ak,
1471
- newSk: sk,
1472
- newSecurityToken: securityToken,
1473
- newRegion: region,
1474
- oldFingerprint: fingerprint(prev.ak, prev.sk),
1475
- newFingerprint: fingerprint(ak, sk),
1476
- fromImport: importedFromFile,
1477
- });
1478
- return {
1479
- status: 'needs_confirmation',
1480
- confirmToken: token,
1481
- options: [
1482
- { key: 's1', label: '以 S1 现有账号为准(不切换,恢复 backup)' },
1483
- { key: 'newImported', label: `以新账号(${fingerprint(ak, sk)})为准,覆盖 S1 并同步全部凭证文件` },
1484
- ],
1485
- };
1486
- }
1487
-
1488
- const persisted = persistCredentials(ak, sk, securityToken, region);
1489
- // Clear the import file for non-replayable outcomes (success, or an
1490
- // unfixable rejection such as STS R3). Keep it only for a retryable
1491
- // 'partial' (S1 written but a mirror failed).
1492
- if (importedFromFile && persisted.status !== 'partial') clearImportFile();
1493
- refreshUserHashAfterAuthChange();
1494
- return persisted;
1495
- }
1496
- case 'huaweicloud_auth_confirm': {
1497
- // D4-24 precise JSON contract (#745): a missing or already-consumed
1498
- // confirm token returns a structured result instead of throwing a
1499
- // generic Error string, mirroring runApprovedCommand's contract.
1500
- const pending = pendingConfirms.get(args.token);
1501
- if (!pending) {
1502
- if (args.token && consumedConfirms.has(args.token)) {
1503
- return { status: 'ok', outcome: 'already_processed' };
1504
- }
1505
- return { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND' };
1506
- }
1507
- pendingConfirms.delete(args.token);
1508
- consumedConfirms.set(args.token, { consumedAt: Date.now() });
1509
- if (args.decision === 's1') {
1510
- return { status: 'ok', outcome: 'aborted', message: '保持 S1 现有账号,未覆盖。' };
1511
- }
1512
- const confirmed = persistCredentials(pending.newAk, pending.newSk, pending.newSecurityToken, pending.newRegion);
1513
- if (pending.fromImport && confirmed.status !== 'partial') clearImportFile();
1514
- refreshUserHashAfterAuthChange();
1515
- return confirmed;
1516
- }
1517
- case 'huaweicloud_sandbox_exec_with_session': {
1518
- const sandboxWsId2 = args.workspace_id || getCurrentWorkspaceId();
1519
- if (!sandboxWsId2) {
1520
- throw new Error(
1521
- 'workspace_id is required. No sandbox connected — call huaweicloud_sandbox_connect first, ' +
1522
- 'or set HW_WORKSPACE_ID environment variable before starting the agent.',
1523
- );
1524
- }
1525
- const sandboxUser2 = args.username || 'root';
1526
- const sandboxTimeout2 = args.timeout_ms || 120000;
1527
- const sandboxResult2 = await execWithSession(sandboxWsId2, args.command, sandboxUser2, sandboxTimeout2);
1528
- return {
1529
- stdout: sandboxResult2.stdout,
1530
- exitCode: sandboxResult2.exitCode,
1531
- };
1532
- }
1533
- case 'huaweicloud_sandbox_exec_one_shot': {
1534
- const sandboxWsId3 = args.workspace_id || getCurrentWorkspaceId();
1535
- if (!sandboxWsId3) {
1536
- throw new Error(
1537
- 'workspace_id is required. No sandbox connected — call huaweicloud_sandbox_connect first, ' +
1538
- 'or set HW_WORKSPACE_ID environment variable before starting the agent.',
1539
- );
1540
- }
1541
- const sandboxUser3 = args.username || 'root';
1542
- const sandboxTimeout3 = args.timeout_ms || 120000;
1543
- const sandboxResult3 = await execOneShot(sandboxWsId3, args.command, sandboxUser3, sandboxTimeout3);
1544
- return {
1545
- stdout: sandboxResult3.stdout,
1546
- exitCode: sandboxResult3.exitCode,
1547
- };
1548
- }
1549
- case 'huaweicloud_sandbox_close_session': {
1550
- const sandboxWsId4 = args.workspace_id || getCurrentWorkspaceId();
1551
- if (!sandboxWsId4) {
1552
- throw new Error(
1553
- 'workspace_id is required. No sandbox connected — call huaweicloud_sandbox_connect first, ' +
1554
- 'or set HW_WORKSPACE_ID environment variable before starting the agent.',
1555
- );
1556
- }
1557
- const sandboxUser4 = args.username || 'root';
1558
- const closed = await closeSession(sandboxWsId4, sandboxUser4);
1559
- if (closed) {
1560
- // 池归属缓存随会话关闭清理:长驻进程防只增不减/陈旧池归属
1561
- forgetWorkspacePool(sandboxWsId4);
1562
- }
1563
- return closed ? 'ok' : 'not_connected';
1564
- }
1565
- case 'huaweicloud_sandbox_upload_file': {
1566
- if (!args.local_path || !args.remote_path) {
1567
- throw new Error('local_path and remote_path are required.');
1568
- }
1569
- const sandboxWsId5 = args.workspace_id || getCurrentWorkspaceId();
1570
- if (!sandboxWsId5) {
1571
- throw new Error(
1572
- 'workspace_id is required. No sandbox connected — call huaweicloud_sandbox_connect first, ' +
1573
- 'or set HW_WORKSPACE_ID environment variable before starting the agent.',
1574
- );
1575
- }
1576
- const sandboxUser5 = args.username || 'root';
1577
- const sandboxTimeout5 = args.timeout_ms || 120000;
1578
- return await uploadFileWithSession(
1579
- sandboxWsId5,
1580
- args.local_path,
1581
- args.remote_path,
1582
- sandboxUser5,
1583
- sandboxTimeout5,
1584
- );
1585
- }
1586
- case 'huaweicloud_sandbox_upload_project': {
1587
- if (!args.local_dir) {
1588
- throw new Error('local_dir is required.');
1589
- }
1590
- const sandboxWsId6 = args.workspace_id || getCurrentWorkspaceId();
1591
- if (!sandboxWsId6) {
1592
- throw new Error(
1593
- 'workspace_id is required. No sandbox connected — call huaweicloud_sandbox_connect first, ' +
1594
- 'or set HW_WORKSPACE_ID environment variable before starting the agent.',
1595
- );
1596
- }
1597
- const sandboxUser6 = args.username || 'root';
1598
- const sandboxTimeout6 = args.timeout_ms || 120000;
1599
- return await uploadProjectWithSession(
1600
- sandboxWsId6,
1601
- args.local_dir,
1602
- args.remote_dir,
1603
- sandboxUser6,
1604
- sandboxTimeout6,
1605
- {
1606
- exclude: args.exclude,
1607
- extract: args.extract,
1608
- },
1609
- );
1610
- }
1611
- case 'huaweicloud_sandbox_deploy_nginx': {
1612
- if (!args.nginx_type || !args.port || !args.project || !args.output_dir) {
1613
- throw new Error('nginx_type, port, project, and output_dir are required.');
1614
- }
1615
- const sandboxWsId7 = args.workspace_id || getCurrentWorkspaceId();
1616
- if (!sandboxWsId7) {
1617
- throw new Error(
1618
- 'workspace_id is required. No sandbox connected — call huaweicloud_sandbox_connect first, ' +
1619
- 'or set HW_WORKSPACE_ID environment variable before starting the agent.',
1620
- );
1621
- }
1622
- const sandboxUser7 = args.username || 'root';
1623
- const sandboxTimeout7 = args.timeout_ms || 60000;
1624
- return await deployNginx(
1625
- sandboxWsId7,
1626
- {
1627
- nginxType: args.nginx_type,
1628
- port: args.port,
1629
- project: args.project,
1630
- outputDir: args.output_dir,
1631
- nodePort: args.node_port,
1632
- publicPort: args.public_port,
1633
- configName: args.config_name,
1634
- },
1635
- sandboxUser7,
1636
- sandboxTimeout7,
1637
- );
1638
- }
1639
- case 'huaweicloud_sandbox_deploy_check': {
1640
- if (!args.port || !args.project || !args.output_dir) {
1641
- throw new Error('port, project, and output_dir are required.');
1642
- }
1643
- const sandboxWsId8 = args.workspace_id || getCurrentWorkspaceId();
1644
- if (!sandboxWsId8) {
1645
- throw new Error(
1646
- 'workspace_id is required. No sandbox connected — call huaweicloud_sandbox_connect first, ' +
1647
- 'or set HW_WORKSPACE_ID environment variable before starting the agent.',
1648
- );
1649
- }
1650
- const sandboxUser8 = args.username || 'root';
1651
- const sandboxTimeout8 = args.timeout_ms || 30000;
1652
- return await deployCheck(
1653
- sandboxWsId8,
1654
- {
1655
- port: args.port,
1656
- project: args.project,
1657
- outputDir: args.output_dir,
1658
- frameworkType: args.framework_type,
1659
- },
1660
- sandboxUser8,
1661
- sandboxTimeout8,
1662
- );
1663
- }
1664
- case 'huaweicloud_sandbox_expose_tunnel': {
1665
- if (!args.port) {
1666
- throw new Error(
1667
- 'port is required. Use the ACTUAL "port" value returned by huaweicloud_sandbox_deploy_nginx (it may have been auto-incremented on a port conflict).',
1668
- );
1669
- }
1670
- const sandboxWsId9 = args.workspace_id || getCurrentWorkspaceId();
1671
- if (!sandboxWsId9) {
1672
- throw new Error(
1673
- 'workspace_id is required. No sandbox connected — call huaweicloud_sandbox_connect first, ' +
1674
- 'or set HW_WORKSPACE_ID environment variable before starting the agent.',
1675
- );
1676
- }
1677
- const sandboxUser9 = args.username || 'root';
1678
- const sandboxTimeout9 = args.timeout_ms || 90000;
1679
- const exposePoolContext = poolContextFor(sandboxWsId9);
1680
- return await exposeTunnel(
1681
- sandboxWsId9,
1682
- {
1683
- port: args.port,
1684
- expiryHours: args.expiry_hours,
1685
- keepalive: args.keepalive,
1686
- cleanupMode: args.cleanup_mode,
1687
- // DevBridge API Key 自动创建兜底(认证固定 apikey,AK/SK 已移除)
1688
- poolType: exposePoolContext?.poolMode || 'ephemeral',
1689
- poolContext: exposePoolContext,
1690
- ensureDevbridgeKey,
1691
- buildKeyringInjectScript,
1692
- listKeysForQuotaHint,
1693
- },
1694
- sandboxUser9,
1695
- sandboxTimeout9,
1696
- );
1697
- }
1698
- case 'huaweicloud_sandbox_renew_tunnel': {
1699
- if (!args.tunnel_id) {
1700
- throw new Error(
1701
- 'tunnel_id is required. Get it from huaweicloud_sandbox_expose_tunnel or extract it from the public URL (https://<tunnel_id>-<port>.devbridge-s2.hwtunnel.com).',
1702
- );
1703
- }
1704
- const sandboxWsId10 = args.workspace_id || getCurrentWorkspaceId();
1705
- if (!sandboxWsId10) {
1706
- throw new Error(
1707
- 'workspace_id is required. No sandbox connected — call huaweicloud_sandbox_connect first, ' +
1708
- 'or set HW_WORKSPACE_ID environment variable before starting the agent.',
1709
- );
1710
- }
1711
- return await renewTunnel(
1712
- sandboxWsId10,
1713
- { tunnelId: args.tunnel_id, expiryHours: args.expiry_hours },
1714
- args.username || 'root',
1715
- args.timeout_ms || 60000,
1716
- );
1717
- }
1718
- case 'huaweicloud_sandbox_keepalive_watchdog': {
1719
- if (!Array.isArray(args.tunnels) || args.tunnels.length === 0) {
1720
- throw new Error(
1721
- 'tunnels is required — a non-empty array of {tunnel_id, url} from huaweicloud_sandbox_expose_tunnel results.',
1722
- );
1723
- }
1724
- const sandboxWsId11 = args.workspace_id || getCurrentWorkspaceId();
1725
- if (!sandboxWsId11) {
1726
- throw new Error(
1727
- 'workspace_id is required. No sandbox connected — call huaweicloud_sandbox_connect first, ' +
1728
- 'or set HW_WORKSPACE_ID environment variable before starting the agent.',
1729
- );
1730
- }
1731
- const tunnels11 = args.tunnels.map((t) => ({ tunnelId: t.tunnel_id || t.tunnelId, url: t.url }));
1732
- return await installKeepaliveWatchdog(
1733
- sandboxWsId11,
1734
- { tunnels: tunnels11 },
1735
- args.username || 'root',
1736
- args.timeout_ms || 60000,
1737
- );
1738
- }
1739
- case 'huaweicloud_sandbox_check_user': {
1740
- try {
1741
- return await hdkitCheckUser();
1742
- } catch (error) {
1743
- if (error?.code === 'HDKIT_VERSION_TOO_OLD') {
1744
- return {
1745
- ok: false,
1746
- code: error.code,
1747
- message: error.message,
1748
- ...(error.clientVersion ? { clientVersion: error.clientVersion } : {}),
1749
- ...(error.minVersion ? { minVersion: error.minVersion } : {}),
1750
- ...(error.remediation ? { remediation: error.remediation } : {}),
1751
- };
1752
- }
1753
- throw error;
1754
- }
1755
- }
1756
- case 'huaweicloud_sandbox_sign_agreement':
1757
- return await hdkitSignAgreement();
1758
- case 'huaweicloud_sandbox_connect': {
1759
- // 两池:客户端校验 pool_type(非法值在本地即报错,不发无效请求);未传交由服务端默认 ephemeral
1760
- const connectArgs = { ...args };
1761
- let poolType;
1762
- try {
1763
- poolType = connectArgs.pool_type !== undefined ? validatePoolType(connectArgs.pool_type) : null;
1764
- if (poolType) connectArgs.pool_type = poolType;
1765
- } catch (error) {
1766
- // 非法 pool_type 结构化返回:MCP 错误信封只携带 code+message,指引字段在 throw 路径会丢失(参照 voucher 模式)
1767
- return { ok: false, code: 'HDKIT_INVALID_POOL_TYPE', message: error.message };
1768
- }
1769
- let connectResult;
1770
- try {
1771
- connectResult = await hdkitConnectWithRetry(connectArgs);
1772
- } catch (error) {
1773
- // 业务预期失败(429 双码 / 烧核 / 凭证失效)转结构化返回,remediation 才能穿透 MCP 边界;
1774
- // 其余错误维持抛出(MCP 层透传 code+message)
1775
- if (
1776
- error?.code === 'HDKIT_QUOTA_EXCEEDED' ||
1777
- error?.code === 'HDKIT_CAPACITY_INSUFFICIENT' ||
1778
- error?.code === 'HDKIT_CRED_INVALID' ||
1779
- error?.code === 'HDKIT_VERSION_TOO_OLD' ||
1780
- error?.coreHoursExhausted
1781
- ) {
1782
- return {
1783
- ok: false,
1784
- code: error.code,
1785
- message: error.message,
1786
- ...(error.retryAfter !== undefined ? { retryAfter: error.retryAfter } : {}),
1787
- ...(error.coreHoursExhausted ? { coreHoursExhausted: true } : {}),
1788
- ...(error.clientVersion ? { clientVersion: error.clientVersion } : {}),
1789
- ...(error.minVersion ? { minVersion: error.minVersion } : {}),
1790
- ...(error.remediation ? { remediation: error.remediation } : {}),
1791
- };
1792
- }
1793
- throw error;
1794
- }
1795
- const devStageId = connectResult?.dev_stage_id || connectResult?.devStageId;
1796
- let announceConnect = true;
1797
- if (devStageId) {
1798
- setWorkspaceId(devStageId);
1799
- // 播报判定:会话首次 connect 或复用实例被唤醒(started=true)才提示,其余复用静默
1800
- announceConnect = shouldAnnounceConnect(devStageId, connectResult || {});
1801
- // 池归属 + 生命周期口径缓存(服务端回显优先,缺失时客户端默认兜底)。
1802
- // 双读兜底与 devStageId 同型(防服务端 wire 命名漂移,QA #1082 配对复审教训)
1803
- rememberWorkspacePool(devStageId, connectResult?.pool_type || connectResult?.poolType, connectResult || {});
1804
- // 只清理孤儿隧道/宿主;保留其他端口、其他会话与 keepalive 名单内的隧道
1805
- try {
1806
- await cleanupDevbridgeTunnels(devStageId, { mode: 'stale' });
1807
- } catch {}
1808
- try {
1809
- await execWithSession(
1810
- devStageId,
1811
- 'export PATH=/workspace/.local/bin:$HOME/.huawei/bin${PATH:+:$PATH}',
1812
- 'root',
1813
- 10000,
1814
- );
1815
- } catch {}
1816
- await transferGitRepo(args, devStageId, connectResult);
1817
- }
1818
- // 生命周期提示:仅首次连接 / 关机唤醒时播报(服务端回显 pool_type 才生成)
1819
- return enrichConnectResult(connectResult, { announce: announceConnect });
1820
- }
1821
- case 'huaweicloud_sandbox_credentials': {
1822
- const devStageId = args.dev_stage_id || getCurrentWorkspaceId();
1823
- let resolved;
1824
- try {
1825
- resolved = resolveCredentialsWithRuntime();
1826
- } catch {
1827
- resolved = null;
1828
- }
1829
- if (!resolved?.ak || !resolved?.sk) {
1830
- return {
1831
- ok: false,
1832
- error: 'Huawei Cloud credentials are not configured. Nothing was injected into the sandbox.',
1833
- hint: 'Run "npx huaweicloud-devkit auth init" or set HW_ACCESS_KEY/HW_SECRET_KEY, then retry.',
1834
- };
1835
- }
1836
- const validation = await validateIamCredentials({
1837
- ak: resolved.ak,
1838
- sk: resolved.sk,
1839
- securityToken: resolved.securityToken,
1840
- region: args.region || resolved.region,
1841
- });
1842
- if (!validation.valid && !validation.skipped) {
1843
- return {
1844
- ok: false,
1845
- error: 'Credential validation failed before injection: ' + validation.error,
1846
- hint: 'Credentials were NOT injected into the sandbox. Fix AK/SK first: run "npx huaweicloud-devkit auth init" or correct HW_ACCESS_KEY/HW_SECRET_KEY, then retry.',
1847
- };
1848
- }
1849
- const credResult = await hdkitCredentials(args.session_id, devStageId, args.enable_sts !== false);
1850
- const sandboxWsIdCred = args.dev_stage_id || getCurrentWorkspaceId();
1851
- // The DevBridge API Key is a LONG-LIVED account-level credential (no expiry, manual
1852
- // revocation only) — unlike the temporary STS AK/SK. It is stored in its own file
1853
- // (/tmp/hw_api_key, 0600) so an accidental dump of /tmp/hw_creds.sh never exposes it,
1854
- // and the local HW_API_KEY env takes precedence over the tool param so the key can be
1855
- // delivered without entering the conversation.
1856
- const apiKey = process.env.HW_API_KEY || args.api_key || '';
1857
- const apiKeyFile = '/tmp/hw_api_key';
1858
- if (sandboxWsIdCred) {
1859
- try {
1860
- const { ak, sk, securitytoken } = await resolveBackendCredentials();
1861
- const credsScript = [
1862
- `export HW_ACCESS_KEY='${ak}'`,
1863
- `export HW_SECRET_KEY='${sk}'`,
1864
- securitytoken ? `export HW_SECURITY_TOKEN='${securitytoken}'` : '',
1865
- securitytoken ? `export X_HW_SECURITY_TOKEN='${securitytoken}'` : '',
1866
- validation.projectId ? `export HW_PROJECT_ID='${validation.projectId}'` : '',
1867
- ]
1868
- .filter(Boolean)
1869
- .join('\n');
1870
- const credsFile = '/tmp/hw_creds.sh';
1871
- await execOneShot(
1872
- sandboxWsIdCred,
1873
- `cat > ${credsFile} << 'HWCREDS_EOF'\n${credsScript}\nHWCREDS_EOF\nchmod 600 ${credsFile}`,
1874
- 'root',
1875
- 15000,
1876
- );
1877
- await execWithSession(sandboxWsIdCred, `source ${credsFile} && echo "CREDS_SOURCED"`, 'root', 15000);
1878
- if (apiKey) {
1879
- await execOneShot(
1880
- sandboxWsIdCred,
1881
- `cat > ${apiKeyFile} << 'HWAPIKEY_EOF'\nexport HW_API_KEY='${apiKey}'\nHWAPIKEY_EOF\nchmod 600 ${apiKeyFile}`,
1882
- 'root',
1883
- 15000,
1884
- );
1885
- } else {
1886
- // Refresh with no key → drop any stale copy, same semantics as the creds file rewrite.
1887
- await execOneShot(sandboxWsIdCred, `rm -f ${apiKeyFile}`, 'root', 15000);
1888
- }
1889
- } catch {}
1890
- }
1891
- const result = {
1892
- ...credResult,
1893
- credentialValidation: validation.warning ? 'passed-with-warning' : 'passed',
1894
- };
1895
- if (sandboxWsIdCred) result.apiKeyInjected = Boolean(apiKey);
1896
- if (apiKey) {
1897
- result.apiKeyHint =
1898
- 'DevBridge API Key written to /tmp/hw_api_key (0600, kept separate from the temporary AK/SK in /tmp/hw_creds.sh — it is a long-lived account-level credential). At expose time the auth waterfall prefers the platform-injected keyring key (API_KEY_KEYRING), falls back to AK/SK, then to this file (API_KEY_FILE). Never echo the key into logs.';
1899
- } else {
1900
- result.apiKeyHint =
1901
- 'No DevBridge API Key provided locally — that is fine on recent sandbox images (hd-space-ai-shell line): the platform auto-injects the key into the sandbox keyring (HW_DEVBRIDGE_API_KEY via hwcloud) and the expose-time auth waterfall picks it up with zero user action. Only older sandboxes (created before the injection existed, image not upgradeable in place) need the one-time manual fallback: create an API Key at https://devstation.connect.huaweicloud.com/space/devbridge/apikey, set the local HW_API_KEY environment variable (preferred — keeps the key out of the conversation), and re-run this tool to inject it as /tmp/hw_api_key.';
1902
- }
1903
- if (validation.projectId) result.projectId = validation.projectId;
1904
- if (validation.warning) result.warning = validation.warning;
1905
- if (validation.skipped) result.warning = validation.error;
1906
- return result;
1907
- }
1908
- case 'huaweicloud_voucher_status':
1909
- return await hdkitVoucherStatus(args.domain_id);
1910
- case 'huaweicloud_voucher_claim': {
1911
- const result = await hdkitVoucherClaim(args.domain_id);
1912
- // #1014 P0: 领券成功后补缓存 userHash(响应携带时),flush 前兜底补齐队列缺失字段。
1913
- if (result?.userHash) cacheUserHash(result.userHash);
1914
- return result;
1915
- }
1916
- case 'huaweicloud_competition_voucher_claim': {
1917
- const result = await hdkitCompetitionVoucherClaim(args.domain_id);
1918
- if (result?.userHash) cacheUserHash(result.userHash);
1919
- return result;
1920
- }
1921
- case 'huaweicloud_check_update':
1922
- return await handleCheckUpdate(args, { sessionId: opts?.sessionId, doQuery: opts?.doQuery });
1923
- case 'huaweicloud_upgrade':
1924
- return await handleUpgrade(args, { sessionId: opts?.sessionId });
1925
- case 'huaweicloud_obs_set_website_config':
1926
- return await handleObsWebsiteConfig(args);
1927
- case 'huaweicloud_obs_set_cors':
1928
- return await handleObsCorsConfig(args);
1929
- default:
1930
- throw new Error(`Unknown tool: ${name}`);
1931
- }
1932
- }
1933
-
1934
- async function handleCheckUpdate(args = {}, opts = {}) {
1935
- const { sessionId = null, doQuery } = opts;
1936
- const current = readInstalledVersion() || '0.0.0';
1937
- if (args.dismiss === true) {
1938
- const distTags = await getUpdateDistTags(current, { sessionId, doQuery });
1939
- if (!distTags) {
1940
- // 查询失败:不降级为 current 冷却、不写 skip,返回 check_failed。
1941
- // 不调 invalidateUpdateCache(),以保留 failedAt 的 5 分钟失败节流。
1942
- return judgeUpdate(current, null, null);
1943
- }
1944
- const target = determineTarget(current, distTags);
1945
- const dismissedVersion =
1946
- typeof args.dismissVersion === 'string' && args.dismissVersion ? args.dismissVersion : target || current;
1947
- const state = writeSkipState(resolveSkipFilePath(sessionId), dismissedVersion);
1948
- invalidateUpdateCache();
1949
- return judgeUpdate(current, distTags, state);
1950
- }
1951
- return getCachedUpdateInfo(current, { sessionId, doQuery });
1952
- }
1953
-
1954
- async function handleUpgrade(args = {}, opts = {}) {
1955
- const sessionId = opts?.sessionId || null;
1956
- const target = typeof args.target === 'string' && args.target ? args.target : 'all';
1957
- const version = typeof args.version === 'string' && args.version ? args.version : 'latest';
1958
- const current = readInstalledVersion() || '0.0.0';
1959
- const info = await getCachedUpdateInfo(current, { sessionId });
1960
- if (info && info.result === 'up_to_date') {
1961
- return {
1962
- success: false,
1963
- requiresRestart: false,
1964
- message: '已是最新版本,无需升级。',
1965
- currentVersion: info.currentVersion,
1966
- targetVersion: info.targetVersion,
1967
- };
1968
- }
1969
- return upgradePackage({ target, version });
1970
- }
1971
-
1972
- function hookResult(result) {
1973
- return {
1974
- ok: result.decision !== 'deny',
1975
- decision: result.decision,
1976
- findings: result.findings,
1977
- nextStep:
1978
- result.decision === 'deny'
1979
- ? 'Revise the command, artifact, or deployment plan before execution.'
1980
- : result.decision === 'warn'
1981
- ? 'Review the warnings with the user before proceeding.'
1982
- : 'No Huawei Cloud hook risk rule matched.',
1983
- };
1984
- }
1985
-
1986
- export async function runVersionCheck(options = {}) {
1987
- const result = probeHcloud(options);
1988
- return {
1989
- installed: result.installed,
1990
- authenticated: result.ok && !/配置文件中不存在配置项|USE_ERROR.*配置/i.test(result.output || ''),
1991
- errorCode: result.errorCode,
1992
- status: result.status,
1993
- output: result.output,
1994
- kooCliVersion: result.requiredVersion || undefined,
1995
- installedVersion: result.installedVersion || undefined,
1996
- versionMismatch: Boolean(result.versionMismatch),
1997
- nextStep: hcloudProbeNextStep(result),
1998
- raw: hcloudProbeRaw(result),
1999
- authHint:
2000
- 'If hcloud is installed but commands fail with "配置文件中不存在配置项", run `npx huaweicloud-devkit auth init` outside agent chat to configure credentials.',
2001
- };
2002
- }
2003
-
2004
- async function showProfileRedacted(profile) {
2005
- const args = ['configure', 'show'];
2006
- if (profile) {
2007
- args.push('--cli-profile', String(profile));
2008
- }
2009
- const result = await runHcloud(args, { allowWrites: false, allowCredentialRead: true }).catch((error) => ({
2010
- ok: false,
2011
- blocked: true,
2012
- reason: error.message,
2013
- }));
2014
- if (result.blocked) {
2015
- return {
2016
- ok: false,
2017
- blockedByPolicy: true,
2018
- reason: result.reason,
2019
- safeAlternative:
2020
- 'Use huaweicloud_show_profile_redacted so profile output is returned through the redaction pipeline.',
2021
- };
2022
- }
2023
- return {
2024
- ok: result.ok,
2025
- note: result.ok
2026
- ? 'Profile information was returned through the toolkit redaction pipeline.'
2027
- : 'Failed to retrieve profile — hcloud may not be installed or configured.',
2028
- result: redactSecrets(result),
2029
- };
2030
- }
2031
-
2032
- async function setupObsConfig(profile) {
2033
- const stored = readGlobalCredentials();
2034
- if (stored?.ak && stored?.sk) {
2035
- try {
2036
- const obs = writeObsConfigFile(stored);
2037
- return {
2038
- ok: true,
2039
- existed: false,
2040
- created: true,
2041
- path: obs.path,
2042
- region: stored.region,
2043
- endpoint: obs.endpoint,
2044
- source: 'global-credentials',
2045
- note: 'OBS credentials synced from the global credential vault. OBS commands (hcloud OBS ls, mb, cp, etc.) should now work.',
2046
- };
2047
- } catch (error) {
2048
- return {
2049
- ok: false,
2050
- error: error.message,
2051
- nextStep: 'Run "npx huaweicloud-devkit auth init" to refresh credentials and region.',
2052
- };
2053
- }
2054
- }
2055
-
2056
- return setupObsConfigFromHcloud(profile);
2057
- }
2058
-
2059
- async function setupObsConfigFromHcloud(profile) {
2060
- const obsConfigPath = join(homedir(), '.obsutilconfig');
2061
- if (existsSync(obsConfigPath)) {
2062
- return {
2063
- ok: true,
2064
- existed: true,
2065
- path: obsConfigPath,
2066
- note: 'OBS config already exists. Delete ~/.obsutilconfig first if you need to re-sync.',
2067
- };
2068
- }
2069
-
2070
- const args = ['configure', 'show'];
2071
- if (profile) args.push('--cli-profile', String(profile));
2072
- const result = await runHcloud(args, { allowWrites: false, allowCredentialRead: true });
2073
-
2074
- if (!result.ok) {
2075
- return {
2076
- ok: false,
2077
- error: 'Failed to read hcloud profile.',
2078
- detail: result.error || result.stderr || 'hcloud not installed or not configured',
2079
- nextStep: 'Run "npx huaweicloud-devkit auth init" outside agent chat, then retry.',
2080
- };
2081
- }
2082
-
2083
- let accessKeyId;
2084
- let secretAccessKey;
2085
- let region;
2086
-
2087
- try {
2088
- const parsed = typeof result.stdout === 'string' ? JSON.parse(result.stdout) : result.stdout;
2089
- const cred = parsed.currentCredential || {};
2090
- accessKeyId = cred.accessKeyId || cred.ak || cred.access_key || '';
2091
- secretAccessKey = cred.secretAccessKey || cred.sk || cred.secret_key || '';
2092
- region = parsed.currentRegion || parsed.region || '';
2093
- } catch {
2094
- return {
2095
- ok: false,
2096
- error: 'Failed to parse hcloud profile output.',
2097
- detail: 'hcloud configure show returned unexpected format',
2098
- };
2099
- }
2100
-
2101
- if (!accessKeyId || !secretAccessKey) {
2102
- return {
2103
- ok: false,
2104
- error: 'No credentials found in hcloud profile.',
2105
- nextStep: 'Run "npx huaweicloud-devkit auth init" outside agent chat to set up credentials first.',
2106
- };
2107
- }
2108
-
2109
- if (!region) {
2110
- return {
2111
- ok: false,
2112
- error: 'No region found in hcloud profile.',
2113
- nextStep: 'Run "npx huaweicloud-devkit auth init" outside agent chat to configure credentials and region.',
2114
- };
2115
- }
2116
-
2117
- const endpoint = `https://obs.${region}.myhuaweicloud.com`;
2118
- // Flat key=value format (no [default] section) as written by KooCLI 7.x `hcloud OBS config`.
2119
- const configContent = `endpoint=${endpoint}\nak=${accessKeyId}\nsk=${secretAccessKey}\n`;
2120
-
2121
- try {
2122
- writeFileSync(obsConfigPath, configContent, { encoding: 'utf8', mode: 0o600 });
2123
- } catch (error) {
2124
- return {
2125
- ok: false,
2126
- error: 'Failed to write OBS config file.',
2127
- detail: error.message,
2128
- path: obsConfigPath,
2129
- };
2130
- }
2131
-
2132
- return {
2133
- ok: true,
2134
- existed: false,
2135
- created: true,
2136
- path: obsConfigPath,
2137
- region,
2138
- endpoint,
2139
- note: 'OBS credentials synced from hcloud profile. OBS commands (hcloud OBS ls, mb, cp, etc.) should now work.',
2140
- };
2141
- }
2142
-
2143
- const SERVICE_EXAMPLES = {
2144
- ECS: { list: 'ECS ListServersDetails', create: 'ECS CreateServers', show: 'IMS GlanceShowImage' },
2145
- VPC: { list: 'VPC ListVpcs', create: 'VPC CreateVpc', show: 'VPC ShowVpc' },
2146
- FUNCTIONGRAPH: {
2147
- list: 'FunctionGraph ListFunctions',
2148
- create: 'FunctionGraph CreateFunction',
2149
- show: 'FunctionGraph ShowFunctionConfig',
2150
- },
2151
- APIG: { list: 'APIG ListInstancesV2', create: 'APIG CreateInstanceV2', show: 'APIG ShowDetailsOfInstanceV2' },
2152
- OBS: { list: 'OBS ls', create: 'OBS mb obs://<bucket>', show: 'OBS stat obs://<bucket>/<key>' },
2153
- RDS: { list: 'RDS ListInstances', create: 'RDS CreateInstance', show: 'RDS ShowInstance' },
2154
- CES: { list: 'CES ListAlarms', create: 'CES CreateAlarm', show: 'CES ListMetrics' },
2155
- GAUSSDB: { list: 'GaussDB ListInstances', create: 'GaussDB CreateInstance', show: 'GaussDB ShowInstance' },
2156
- DDS: { list: 'DDS ListInstances', create: 'DDS CreateInstance', show: 'DDS ShowInstance' },
2157
- DCS: { list: 'DCS ListInstances', create: 'DCS CreateInstance', show: 'DCS ShowInstance' },
2158
- };
2159
-
2160
- // DMS and DEW are Huawei Cloud aggregate service names that do not exist as
2161
- // single KooCLI service identifiers. Each maps to real KooCLI sub-services.
2162
- const AGGREGATE_SERVICE_MAP = {
2163
- DMS: ['Kafka', 'RabbitMQ', 'RocketMQ'],
2164
- DEW: ['KMS', 'CSMS'],
2165
- };
2166
-
2167
- // Identity-class notes per service. BSS leads: its operations are split between
2168
- // Customer-level APIs (work with a normal IAM user) and Partner-level APIs
2169
- // (only valid for a partner/dealer identity). Calling a Partner-level API with a
2170
- // customer credential returns APIGW.0301 even when AK/SK are perfectly valid —
2171
- // the common false-positive diagnosis is "cli-domain-id missing".
2172
- const SERVICE_IDENTITY_NOTES = {
2173
- BSS: [
2174
- {
2175
- identity: 'Customer-level (normal IAM user)',
2176
- apis: [
2177
- 'ShowCustomerAccountBalances',
2178
- 'ListCustomerBillsFeeRecords',
2179
- 'ListCustomerCouponChangeRecords',
2180
- 'ListResourceUsage',
2181
- 'ListCosts',
2182
- ],
2183
- note: 'Work with a normal IAM user that has BSS Administrator or Finance role.',
2184
- },
2185
- {
2186
- identity: 'Partner-level (partner/dealer only)',
2187
- apis: ['ListQuotaCoupons', 'ListSubCustomerCoupons', 'ListSubCustomerBillDetail'],
2188
- note: 'APIGW.0301 here means the caller identity is not a partner — NOT bad AK/SK or a missing cli-domain-id.',
2189
- },
2190
- ],
2191
- };
2192
-
2193
- async function listOperations(service, options = {}) {
2194
- const serviceName = String(service || '').trim();
2195
- if (!/^[A-Za-z][A-Za-z0-9-]{1,63}$/.test(serviceName)) {
2196
- throw new Error('service must be a KooCLI service name such as ECS, VPC, IMS, OBS, RDS, or CDN.');
2197
- }
2198
- const upperName = serviceName.toUpperCase();
2199
- const subServices = AGGREGATE_SERVICE_MAP[upperName];
2200
- if (subServices && subServices.length) {
2201
- const results = await Promise.all(
2202
- subServices.map(async (sub) => {
2203
- const r = await runHcloud([sub, '--help'], {
2204
- timeoutMs: options.timeoutMs,
2205
- maxRetries: 0,
2206
- });
2207
- let result = r;
2208
- if (!result.ok) {
2209
- result = await runHcloud([sub, 'help'], {
2210
- timeoutMs: options.timeoutMs,
2211
- maxRetries: 0,
2212
- });
2213
- }
2214
- return {
2215
- subService: sub,
2216
- command: `hcloud ${sub} --help`,
2217
- examples: SERVICE_EXAMPLES[sub.toUpperCase()] || {
2218
- note: `No cached examples for ${sub}. Use the help text above to discover available operations.`,
2219
- },
2220
- result,
2221
- };
2222
- }),
2223
- );
2224
- return {
2225
- service: serviceName,
2226
- aggregate: true,
2227
- aggregatedFrom: subServices,
2228
- selectionRule:
2229
- 'DMS/DEW are aggregate service names. Use each sub-service help text below to select the exact KooCLI operation name.',
2230
- identityNotes: SERVICE_IDENTITY_NOTES[upperName] || null,
2231
- subServices: results,
2232
- };
2233
- }
2234
- const isObs = /^obs$/i.test(serviceName);
2235
- const svc = isObs ? 'obs' : serviceName;
2236
- const args = isObs ? ['obs', 'help'] : [svc, '--help'];
2237
- let result = await runHcloud(args, {
2238
- timeoutMs: options.timeoutMs,
2239
- maxRetries: 0,
2240
- });
2241
- if (!result.ok && !isObs) {
2242
- result = await runHcloud([svc, 'help'], {
2243
- timeoutMs: options.timeoutMs,
2244
- maxRetries: 0,
2245
- });
2246
- }
2247
- return {
2248
- service: serviceName,
2249
- command: isObs ? 'hcloud obs help' : `hcloud ${svc} --help`,
2250
- selectionRule:
2251
- 'Use this help text to select the exact KooCLI operation name before planning any service command. After selecting an operation, run "hcloud <Service> <Operation> --help" to confirm exact parameter names before constructing the command.',
2252
- identityNotes: SERVICE_IDENTITY_NOTES[upperName] || null,
2253
- examples: SERVICE_EXAMPLES[upperName] || {
2254
- note: `No cached examples for ${serviceName}. Use the help text above to discover available operations.`,
2255
- },
2256
- result,
2257
- };
2258
- }
2259
-
2260
- async function runApprovedCommand(args = {}) {
2261
- if (args.approvedByUser !== true) {
2262
- throw new Error('approvedByUser must be true after explicit user approval for this exact command.');
2263
- }
2264
- const token = String(args.approvalToken || '');
2265
-
2266
- // D4-24 precise JSON contract (#745): expired and already-consumed tokens
2267
- // return a structured result instead of throwing a generic Error string, so
2268
- // clients can machine-assert the two non-success states.
2269
- const inspection = inspectApprovalToken(token);
2270
- if (inspection.state === 'already_consumed') {
2271
- return { status: 'ok', outcome: 'already_processed' };
2272
- }
2273
- if (inspection.state === 'expired') {
2274
- return { status: 'rejected', code: 'CONFIRM_TOKEN_EXPIRED' };
2275
- }
2276
- if (inspection.state === 'not_found') {
2277
- // A token that was never created (typo / unknown / pruned beyond the
2278
- // tombstone window) is still a rejection, but carries no expired/already
2279
- // semantics — surface a distinct code so clients can tell the cases apart.
2280
- return { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND' };
2281
- }
2282
-
2283
- const stored = consumeApprovalToken(token);
2284
- if (!stored) {
2285
- // Defensive: inspectApprovalToken said 'valid' but consume returned null
2286
- // (e.g. raced and pruned between the two reads). Re-classify so we never
2287
- // return a misleading success.
2288
- const recheck = inspectApprovalToken(token);
2289
- if (recheck.state === 'expired') return { status: 'rejected', code: 'CONFIRM_TOKEN_EXPIRED' };
2290
- if (recheck.state === 'already_consumed') return { status: 'ok', outcome: 'already_processed' };
2291
- return { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND' };
2292
- }
2293
- const providedArgs = Array.isArray(args.args) ? args.args.map(String) : [];
2294
- if (hashArgs(providedArgs) !== stored.argsHash) {
2295
- const redactedStored = JSON.stringify(stored.argsRedacted);
2296
- const redactedProvided = JSON.stringify(redactSecrets(providedArgs));
2297
- if (redactedStored !== redactedProvided) {
2298
- throw new Error(
2299
- 'Provided args do not match the approved plan. Use the exact args from the plan. ' +
2300
- 'If the plan shows <redacted> for passwords or secrets, replace <redacted> with the actual values in approvedCommand.',
2301
- );
2302
- }
2303
- }
2304
- const strictPlan = planHcloudCommand(providedArgs, { allowWrites: false });
2305
- const result = await runHcloud(providedArgs, {
2306
- allowWrites: true,
2307
- timeoutMs: args.timeoutMs,
2308
- maxRetries: args.maxRetries,
2309
- cwd: args.cwd,
2310
- stdin: args.stdin,
2311
- });
2312
- result.approved = true;
2313
- result.plan = strictPlan;
2314
- return result;
2315
- }
2316
-
2317
- function serviceCatalog(intent = '') {
2318
- const it = String(intent).toLowerCase();
2319
- const routeMap = [
2320
- {
2321
- keywords: [
2322
- 'ecs',
2323
- 'server',
2324
- 'vm',
2325
- 'instance',
2326
- 'compute',
2327
- 'flavor',
2328
- 'image',
2329
- '弹性云服务器',
2330
- '云服务器',
2331
- '服务器',
2332
- '虚拟机',
2333
- '镜像',
2334
- ],
2335
- skills: ['huawei-ecs'],
2336
- services: ['ECS'],
2337
- },
2338
- {
2339
- keywords: [
2340
- 'vpc',
2341
- 'subnet',
2342
- 'network',
2343
- 'security group',
2344
- 'eip',
2345
- 'nat',
2346
- 'vpn',
2347
- 'bandwidth',
2348
- '虚拟私有云',
2349
- '子网',
2350
- '网络',
2351
- '安全组',
2352
- '弹性公网IP',
2353
- 'NAT网关',
2354
- 'VPN网关',
2355
- '带宽',
2356
- ],
2357
- skills: ['huawei-vpc'],
2358
- services: ['VPC', 'EIP'],
2359
- },
2360
- {
2361
- keywords: [
2362
- 'obs',
2363
- 'bucket',
2364
- 'storage',
2365
- 'object',
2366
- 'static website',
2367
- 'static site',
2368
- 'hosting',
2369
- '对象存储',
2370
- '存储桶',
2371
- '桶',
2372
- '存储',
2373
- '对象',
2374
- '静态网站',
2375
- '静态托管',
2376
- ],
2377
- skills: ['huawei-obs'],
2378
- services: ['OBS'],
2379
- },
2380
- {
2381
- keywords: [
2382
- 'functiongraph',
2383
- 'serverless',
2384
- 'function',
2385
- 'lambda',
2386
- 'trigger',
2387
- 'faas',
2388
- '函数工作流',
2389
- '函数',
2390
- '触发器',
2391
- '无服务器',
2392
- '函数计算',
2393
- ],
2394
- skills: ['huawei-functiongraph'],
2395
- services: ['FunctionGraph'],
2396
- },
2397
- {
2398
- keywords: ['cce', 'kubernetes', 'k8s', 'container', 'cluster', 'node pool', 'swr', 'docker', 'image registry'],
2399
- skills: ['huawei-cce'],
2400
- services: ['CCE', 'SWR'],
2401
- },
2402
- {
2403
- keywords: ['apig', 'api gateway', 'publish', 'throttle', 'API网关', '限流'],
2404
- skills: ['huawei-cloud-apig-instance-management'],
2405
- services: ['APIG'],
2406
- },
2407
- {
2408
- keywords: ['rds', 'mysql', 'postgresql', 'database', 'db', '关系型数据库', '数据库'],
2409
- skills: ['huawei-rds'],
2410
- services: ['RDS'],
2411
- },
2412
- {
2413
- keywords: ['gaussdb', 'distributed', 'sharding', 'opengauss', '高斯数据库', '分布式数据库'],
2414
- skills: ['huawei-cloud-gaussdb-instance-management'],
2415
- services: ['GaussDB'],
2416
- },
2417
- {
2418
- keywords: [
2419
- 'iam',
2420
- 'permission',
2421
- 'policy',
2422
- 'role',
2423
- 'user',
2424
- 'ak/sk',
2425
- 'access key',
2426
- 'agency',
2427
- '身份认证',
2428
- '身份管理',
2429
- '权限',
2430
- '策略',
2431
- '角色',
2432
- '用户',
2433
- '访问密钥',
2434
- '委托',
2435
- ],
2436
- skills: ['huawei-iam'],
2437
- services: ['IAM'],
2438
- },
2439
- {
2440
- keywords: [
2441
- 'dew',
2442
- 'secret',
2443
- 'kms',
2444
- 'encrypt',
2445
- 'decrypt',
2446
- 'certificate',
2447
- 'csms',
2448
- '数据加密服务',
2449
- '密钥管理',
2450
- '密钥',
2451
- '加密',
2452
- '解密',
2453
- '证书',
2454
- '凭据管理',
2455
- ],
2456
- skills: ['huawei-cloud-dew-key-management'],
2457
- services: ['CSMS', 'KMS'],
2458
- },
2459
- {
2460
- keywords: ['modelarts', 'ai', 'model', 'training', 'inference', 'machine learning'],
2461
- skills: ['huawei-modelarts'],
2462
- services: ['ModelArts'],
2463
- },
2464
- {
2465
- keywords: ['billing', 'cost', 'bill', 'budget', 'expense', 'bss', '计费', '费用', '账单', '预算', '开销'],
2466
- skills: ['huawei-billing'],
2467
- services: ['BSS'],
2468
- },
2469
- {
2470
- keywords: ['waf', 'aad', 'ddos', 'firewall', 'web protection'],
2471
- skills: ['huawei-cloud-waf-aad-rule-management'],
2472
- services: ['WAF', 'AAD'],
2473
- },
2474
- {
2475
- keywords: ['smn', 'dms', 'notification', 'message', 'kafka', 'rabbitmq'],
2476
- skills: ['huawei-cloud-smn-dms-message'],
2477
- services: ['SMN', 'DMS'],
2478
- },
2479
- {
2480
- keywords: ['ces', 'monitor', 'alarm', 'metric', 'dashboard', 'cloud eye', '监控', '告警', '云监控'],
2481
- skills: ['huawei-cloud-eye'],
2482
- services: ['CES'],
2483
- },
2484
- {
2485
- keywords: ['cts', 'audit', 'trace', 'tracker', '审计', '追踪'],
2486
- skills: ['huawei-cloud-cts-trace-management'],
2487
- services: ['CTS'],
2488
- },
2489
- {
2490
- keywords: ['cbr', 'backup', 'restore', 'vault', 'snapshot', '备份', '恢复', '快照', '存储库'],
2491
- skills: ['huawei-cbr'],
2492
- services: ['CBR'],
2493
- },
2494
- {
2495
- keywords: ['deployment', 'deploy', 'ci/cd', 'pipeline', 'release'],
2496
- skills: ['huawei-cloud-deployment-task-management'],
2497
- services: ['CloudDeploy'],
2498
- },
2499
- {
2500
- keywords: [
2501
- 'sandbox',
2502
- 'devstation',
2503
- 'workspace',
2504
- 'terminal',
2505
- 'preview',
2506
- 'hwlink',
2507
- 'website',
2508
- 'web app',
2509
- 'webapp',
2510
- 'hosting',
2511
- '网站',
2512
- '网页',
2513
- '静态',
2514
- ],
2515
- skills: ['huawei-sandbox'],
2516
- services: ['Sandbox', 'DevStation'],
2517
- },
2518
- {
2519
- keywords: [
2520
- 'dds',
2521
- 'dcs',
2522
- 'mongodb',
2523
- 'redis',
2524
- 'memcached',
2525
- 'cache',
2526
- 'document db',
2527
- '文档数据库',
2528
- '缓存',
2529
- '内存数据库',
2530
- ],
2531
- skills: ['huawei-cloud-dds-dcs-instance-management'],
2532
- services: ['DDS', 'DCS'],
2533
- },
2534
- {
2535
- keywords: ['elb', 'load balancer', '负载均衡', '弹性负载均衡', '监听器', '证书'],
2536
- skills: ['huawei-vpc'],
2537
- services: ['ELB'],
2538
- },
2539
- {
2540
- keywords: ['voucher', 'coupon', 'incentive', 'credit', '领券', '代金券', '优惠券', '激励金', '领取'],
2541
- skills: ['huawei-voucher'],
2542
- services: ['Incentive Voucher'],
2543
- },
2544
- ];
2545
- const matched = [];
2546
- const tokens = new Set(it.split(/[\s,./-]+/).filter((t) => t.length > 0));
2547
- const cjk = /[\u4e00-\u9fff]/;
2548
- for (const route of routeMap) {
2549
- if (
2550
- route.keywords.some((kw) => (kw.includes(' ') || cjk.test(kw) ? it.includes(kw.toLowerCase()) : tokens.has(kw)))
2551
- ) {
2552
- matched.push(route);
2553
- }
2554
- }
2555
- const recommendedSkills = [...new Set(matched.flatMap((r) => r.skills))];
2556
- const recommendedServices = [...new Set(matched.flatMap((r) => r.services))].slice(0, 5);
2557
-
2558
- // Deployment intent (deploy/host/publish a web app or static website) must never
2559
- // default to a storage/other service — recommend the sandbox first.
2560
- const deploymentIntent = /deploy|host|hosting|publish|website|web app|preview|部署|托管|发布|网站|网页/.test(it);
2561
- if (deploymentIntent && recommendedSkills.includes('huawei-sandbox')) {
2562
- const idx = recommendedSkills.indexOf('huawei-sandbox');
2563
- recommendedSkills.splice(idx, 1);
2564
- recommendedSkills.unshift('huawei-sandbox');
2565
- }
2566
-
2567
- return {
2568
- intent,
2569
- recommendedSkills: recommendedSkills.length ? recommendedSkills : ['Use huaweicloud-core to route intent.'],
2570
- recommendedServices: recommendedServices.length
2571
- ? recommendedServices
2572
- : ['Run hcloud --help to list available services.'],
2573
- capabilityOrder: [
2574
- 'Huawei Cloud Skills for task-specific workflows and examples',
2575
- 'KooCLI hcloud for local authenticated operations and quick inspection',
2576
- 'Huawei Cloud API documentation for exact request and response contracts',
2577
- 'Huawei Cloud SDKs for application code integration',
2578
- 'Huawei Cloud MCP when an official or approved server is available',
2579
- 'Terraform Provider only when IaC reviewability and repeatability are important',
2580
- ],
2581
- ruleOfThumb: {
2582
- skills: 'Start here when the user describes a scenario or wants a guided workflow.',
2583
- cli: 'Use for local diagnostics, read-only inspection, and commands the user can review.',
2584
- api: 'Use for exact service contract, region endpoint, project_id, pagination, and error codes.',
2585
- sdk: 'Use when writing application code that calls Huawei Cloud services.',
2586
- mcp: 'Prefer approved MCP tools when available because tools can carry structured schemas.',
2587
- terraform: 'Keep low priority in V1; suggest it for reviewed infrastructure changes, not quick diagnosis.',
2588
- },
2589
- };
2590
- }
2591
-
2592
- function explainError({ service = 'unknown', errorCode = '', message = '', requestId = '' } = {}) {
2593
- const combined = `${errorCode} ${message}`.toLowerCase();
2594
- const suggestions = [];
2595
- const svc = String(service).toLowerCase();
2596
-
2597
- const SERVICE_ALIASES = {
2598
- functiongraph: 'FSS',
2599
- fgs: 'FSS',
2600
- ecs: 'Ecs',
2601
- ECS: 'Ecs',
2602
- kps: 'Kps',
2603
- KPS: 'Kps',
2604
- };
2605
- // #935 E2E-B1: real MCP calls pass only errorCode (e.g. Ecs.0019, KPS.9004)
2606
- // with no service — derive the service key from the dotted-code prefix so the
2607
- // service-keyed mapping table is hit. Explicit service behavior is unchanged.
2608
- let resolvedService = service;
2609
- if ((!service || svc === 'unknown') && /^[A-Za-z]+\.\w+/.test(errorCode)) {
2610
- const prefix = errorCode.split('.')[0].toLowerCase();
2611
- resolvedService = SERVICE_ALIASES[prefix] || errorCode.split('.')[0].toUpperCase();
2612
- }
2613
- const patternKey = SERVICE_ALIASES[svc] || resolvedService;
2614
-
2615
- // devkit internal credential/environment error codes (experience-report #3.9)
2616
- // — these come from devkit's own guidance/credential layer, not Huawei Cloud API.
2617
- const devkitErrorPatterns = {
2618
- HDKIT_CRED_MISSING:
2619
- '未配置华为云凭证。运行 npx huaweicloud-devkit auth init 配置 AK/SK,或注入 HW_X_AUTH_TOKEN(devkit 会自动用 token 换取临时 AK/SK)。',
2620
- HDKIT_CRED_INVALID: '凭证已被华为云拒绝(AK/SK 无效或已过期)。重新生成 AK/SK 后 auth init。',
2621
- HDKIT_CRED_FORBIDDEN: '凭证有效但无权限列出项目。检查 IAM 授权(可用 huaweicloud_check_account_type 判断账号类型)。',
2622
- HDKIT_CRED_REGION_MISSING: '缺少 region 配置。运行 hcloud configure set --cli-region=<region>。',
2623
- HDKIT_KOOCLI_NOT_READY: 'KooCLI(hcloud)未安装或未就绪。运行 npx huaweicloud-devkit install-hcloud。',
2624
- HDKIT_PROJECT_ID_MISSING: '缺少 project_id。运行 npx huaweicloud-devkit auth init 自动配置。',
2625
- TOKEN_INVALID: 'X-Auth-Token 无效或已过期。重新注入有效的 HW_X_AUTH_TOKEN。',
2626
- TOKEN_EXPIRED: 'X-Auth-Token 已过期。重启进程重新注入凭证。',
2627
- TOKEN_EXCHANGE_FAILED:
2628
- 'X-Auth-Token 换取临时 AK/SK 失败,通常是网络无法访问 IAM 端点。检查网络连通性与 token 有效性。',
2629
- HDKIT_SUB_ACCOUNT_RESTRICTED: '沙箱使用限制:当前子账号无法使用沙箱。切换主账号认证(auth_init)后重试。',
2630
- };
2631
- if (devkitErrorPatterns[errorCode]) {
2632
- suggestions.push(`${errorCode}: ${devkitErrorPatterns[errorCode]}`);
2633
- }
2634
-
2635
- const hwErrorPatterns = {
2636
- OBS: {
2637
- InvalidAccessKeyId:
2638
- 'OBS uses AK/SK directly (not IAM tokens). Verify AK/SK validity, OBS endpoint, and OBS permissions.',
2639
- UserRestricted:
2640
- 'This IAM user is restricted from OBS operations (403). Check IAM console → Users → Permissions: grant OBS bucket/object actions, or use an unrestricted account. If the account is a sub-account, the main account may have imposed restrictions.',
2641
- },
2642
- APIG: {
2643
- 'APIC.7241': 'The enterprise_project_id is required for enterprise accounts. Add --enterprise_project_id=0.',
2644
- 'APIC.7242':
2645
- 'The EIP binding method depends on loadbalancer_provider. Use AddIngressEipV2 for elb, AddEipV2 for lvs.',
2646
- 'APIC.7256': 'Bandwidth minimum is 5 Mbps. Use --bandwidth_size=5 or higher.',
2647
- 'APIC.7310': 'available_zone_ids must use AZ codes (e.g. ap-southeast-3a), NOT UUIDs from ListAvailableZonesV2.',
2648
- },
2649
- FSS: {
2650
- 'FSS.0403':
2651
- 'Missing FunctionGraph IAM permissions. Attach FunctionGraph FullAccess role or grant specific actions.',
2652
- 'FSS.1078': '--code_filename is filename-only (no path). cd to the file directory before running the command.',
2653
- 'FSS.1417':
2654
- 'event_data field validation failed. Check parameter format: use dotted key=value, verify required hidden-optional fields.',
2655
- },
2656
- VPC: {
2657
- 'VPC.0301': 'Bandwidth name is required for PER type EIPs, even though --help marks it optional.',
2658
- },
2659
- Ecs: {
2660
- 'Ecs.0707':
2661
- 'The flavor + image-type combination does not exist ("the product does not exist") — the error does not say which side is wrong, so check BOTH (#922): (1) the flavor is abandoned/sellout in this region/AZ (check os_extra_specs.cond:operation:status and cond:operation:az; see the huawei-ecs skill references/flavors.md for the AZ-vs-global-status conflict rule); (2) the image TYPE is incompatible with the flavor — market-type images fail with KunPeng flavors (kc1/kc2 etc.). Fix: switch the image to a gold-type image or switch to a compatible general-purpose flavor (verified: kc2.small.2 + market Ubuntu → Ecs.0707; s6.medium.2 + gold Ubuntu works), re-listing with hcloud ECS ListFlavors / hcloud IMS ListImages --__imagetype=gold first.',
2662
- // #935 (report 4 problem 1 / report 1 坑5): real-world ECS order failures
2663
- // with no mapping — flavor offline, AZ capacity, balance, keypair restriction.
2664
- 'Ecs.0019':
2665
- 'The flavor has been taken offline (Ecs.0019). Run `hcloud ECS ListFlavors --cli-region=<region>` to query currently on-sale flavors and switch to a replacement flavor (see the huawei-ecs skill references/flavors.md for the cond:operation:status field rules — a flavor marked 卖光/下线 keeps failing until you pick an on-sale one), then recreate.',
2666
- 'Ecs.0319':
2667
- 'The requested flavor has insufficient capacity in the selected availability zone (Ecs.0319). Fix: retry in a different availability zone, or switch to a replacement flavor (list on-sale flavors with `hcloud ECS ListFlavors --cli-region=<region>`), then recreate.',
2668
- 'Ecs.0044':
2669
- 'The requested volume type is sold out in the selected availability zone (Ecs.0044, e.g. "the volumeType [SATA] is sellout in az[cn-north-4a]"). This is the ROOT VOLUME/DISK type being unavailable — a different failure from Ecs.0319 (flavor capacity). Fix: switch `--server.root_volume.volumetype` to an available type (SAS/SSD/GPSSD — query availability first) or retry in a different availability zone (`hcloud ECS NovaListAvailabilityZones --cli-region=<region>`). ListFlavors does NOT pre-warn about volume-type sellouts — you only find out at order time.',
2670
- 'Ecs.0067':
2671
- 'Order submission rejected for balance reasons (Ecs.0067). Check the cash balance with `hcloud BSS ShowCustomerAccountBalances --cli-region=cn-north-1` and top up if needed — pay-per-use order risk control checks the CASH balance only (代金券/vouchers do NOT participate in order risk control; they only offset the bill at settlement). Also settle any historical arrears, however small, before retrying.',
2672
- },
2673
- APIGW: {
2674
- 'APIGW.0301':
2675
- 'Incorrect IAM authentication information. The AK/SK is invalid (check the SK for typos), the security token is missing or expired, or the profile lacks project_id. Fix: re-run "npx huaweicloud-devkit auth init" (it auto-sets project_id), or set it manually: hcloud configure set --cli-project-id=<project_id> after finding it via hcloud IAM KeystoneListProjects --cli-region=<region> --name=<region>.',
2676
- 'APIGW.0802':
2677
- 'The current IAM user has no permissions in the requested region. Go to IAM console → Users → Permissions → add the target region, or switch to a different region.',
2678
- },
2679
- // #935 (report 1 坑5): KPS keypair creation has its own restriction code —
2680
- // the Kps service had no entry at all, so the error fell through to generic advice.
2681
- Kps: {
2682
- 'KPS.9004':
2683
- 'Keypair creation rejected for account restrictions (KPS.9004). Check the cash balance with `hcloud BSS ShowCustomerAccountBalances --cli-region=cn-north-1` and top up if needed, and settle any historical arrears (even a small unpaid amount triggers this) — then retry `hcloud ECS NovaCreateKeypair` or create the keypair in the console.',
2684
- },
2685
- };
2686
- if (hwErrorPatterns[patternKey] && hwErrorPatterns[patternKey][errorCode]) {
2687
- suggestions.push(hwErrorPatterns[patternKey][errorCode]);
2688
- }
2689
- const svcPatterns = hwErrorPatterns[patternKey] || {};
2690
- for (const [code, tip] of Object.entries(svcPatterns)) {
2691
- if (errorCode && code.includes(errorCode)) {
2692
- if (!suggestions.includes(tip)) suggestions.push(tip);
2693
- }
2694
- }
2695
-
2696
- // G: when the active credential set is a temporary STS token that has already
2697
- // expired, surface that as the primary cause before generic auth guidance.
2698
- let activeCreds;
2699
- try {
2700
- activeCreds = resolveCredentialsWithRuntime({ allowMissing: true });
2701
- } catch {
2702
- activeCreds = null;
2703
- }
2704
- if (activeCreds?.ak && activeCreds?.sk && activeCreds.securityToken) {
2705
- const expiry = parseStsExpiry({ securityToken: activeCreds.securityToken });
2706
- if (expiry !== null && expiry <= Date.now()) {
2707
- suggestions.push(
2708
- 'CREDENTIAL_EXPIRED: the temporary STS security token has expired. Re-authenticate to obtain fresh credentials (e.g. run "npx huaweicloud-devkit auth init" or re-login / restart the session).',
2709
- );
2710
- }
2711
- }
2712
-
2713
- if (/auth|token|credential|ak|sk|401|403|unauthorized|forbidden|Incorrect IAM/i.test(combined)) {
2714
- if (svc === 'obs') {
2715
- suggestions.push(
2716
- 'OBS uses AK/SK directly, not IAM tokens. Verify AK/SK validity and OBS bucket permissions via hcloud configure list or the Huawei Cloud console.',
2717
- );
2718
- } else {
2719
- suggestions.push('Check KooCLI profile, region, project_id, and IAM permissions without printing secrets.');
2720
- }
2721
- }
2722
- if (/APIGW\.(\d+)/i.test(errorCode)) {
2723
- suggestions.push(
2724
- 'APIGW.' +
2725
- (errorCode.match(/APIGW\.(\d+)/i) || [])[1] +
2726
- ': API Gateway layer error. ' +
2727
- (errorCode === 'APIGW.0802'
2728
- ? 'IAM user has no region permissions — check IAM console → User → Permissions → add target region.'
2729
- : errorCode === 'APIGW.0301'
2730
- ? 'Incorrect IAM authentication information — verify AK/SK (SK typos are the usual cause), security token expiry, and that project_id is configured (auth init auto-sets it).'
2731
- : 'Verify the API request, region endpoint, and IAM permissions.'),
2732
- );
2733
- }
2734
- if (/region|endpoint|project/i.test(combined)) {
2735
- suggestions.push('Confirm the service endpoint, region, and project_id match the target resource.');
2736
- }
2737
- if (/quota|limit|insufficient|reach the limit/i.test(combined)) {
2738
- suggestions.push(
2739
- 'Check quota and resource limits before retrying a create or scale operation. Consider switching accounts or requesting a quota increase.',
2740
- );
2741
- }
2742
- if (/not.?found|404/i.test(combined)) {
2743
- if (/list.?regions/i.test(svc)) {
2744
- suggestions.push('Use hcloud IAM KeystoneListRegions (not list-regions).');
2745
- } else {
2746
- suggestions.push('List resources in the same region/project and verify the resource identifier.');
2747
- }
2748
- }
2749
- if (!suggestions.length) {
2750
- suggestions.push(
2751
- 'No known error-code pattern matched. Re-run the failing command with --debug to capture ' +
2752
- 'X-Request-Id from the response headers, then re-call explain_error with service, operation, ' +
2753
- 'region, the full redacted message, and requestId.',
2754
- );
2755
- if (errorCode) {
2756
- suggestions.push(
2757
- `Search the error code "${errorCode}" in the Huawei Cloud error center (support.huaweicloud.com) for the authoritative cause.`,
2758
- );
2759
- }
2760
- }
2761
-
2762
- if (requestId) {
2763
- suggestions.push('Provide the Request ID (' + requestId + ') when contacting Huawei Cloud support.');
2764
- }
2765
-
2766
- const uniqueSuggestions = suggestions.filter((s, i, arr) => {
2767
- return !arr.slice(0, i).some((prev) => prev.substring(0, 50).toLowerCase() === s.substring(0, 50).toLowerCase());
2768
- });
2769
-
2770
- return {
2771
- service,
2772
- errorCode,
2773
- requestId,
2774
- suggestions: uniqueSuggestions,
2775
- };
2776
- }
2777
-
2778
- async function searchDocs(query, topic = 'all') {
2779
- const q = String(query || '').toLowerCase();
2780
- const tokens = q.split(/\s+/).filter((t) => t.length > 0);
2781
- const results = [];
2782
- try {
2783
- if (existsSync(SKILLS_ROOT)) {
2784
- const dirs = listSkillDirs(SKILLS_ROOT);
2785
- for (const dir of dirs) {
2786
- const skillPath = join(SKILLS_ROOT, dir, 'SKILL.md');
2787
- if (!existsSync(skillPath)) continue;
2788
- const content = readFileSync(skillPath, 'utf8');
2789
- const frontmatter = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
2790
- let description = '';
2791
- let name = dir;
2792
- if (frontmatter) {
2793
- const fm = frontmatter[1];
2794
- const nameMatch = fm.match(/^name:\s*(.+)$/m);
2795
- if (nameMatch) name = nameMatch[1].trim();
2796
- const descMatch = fm.match(/^description:\s*(.+)$/m);
2797
- if (descMatch) description = descMatch[1].trim();
2798
- }
2799
- if (topic !== 'all') {
2800
- const topicLower = topic.toLowerCase();
2801
- if (!name.toLowerCase().includes(topicLower) && !description.toLowerCase().includes(topicLower)) continue;
2802
- }
2803
- const descLower = description.toLowerCase();
2804
- const nameLower = name.toLowerCase();
2805
- const contentLower = content.toLowerCase();
2806
- const relevance = tokens.reduce((score, token) => {
2807
- return (
2808
- score +
2809
- (descLower.includes(token) ? 3 : 0) +
2810
- (nameLower.includes(token) ? 2 : 0) +
2811
- (contentLower.includes(token) ? 1 : 0)
2812
- );
2813
- }, 0);
2814
- if (relevance > 0) {
2815
- results.push({
2816
- source: 'skills/' + dir + '/SKILL.md',
2817
- name,
2818
- snippet: description.substring(0, 200),
2819
- relevance,
2820
- });
2821
- }
2822
- }
2823
- }
2824
- } catch (error) {
2825
- return { ok: false, error: error.message, results: [] };
2826
- }
2827
- results.sort((a, b) => b.relevance - a.relevance);
2828
- return { ok: true, query: q, topic, count: results.length, results: results.slice(0, 10) };
2829
- }
2830
-
2831
- async function retrieveSkill(name) {
2832
- const skillName = String(name || '').trim();
2833
- if (!skillName) return { ok: false, error: 'Skill name is required.' };
2834
- const skillPath = join(SKILLS_ROOT, skillName, 'SKILL.md');
2835
- if (!existsSync(skillPath)) {
2836
- const dirs = listSkillDirs(SKILLS_ROOT);
2837
- return { ok: false, error: 'Skill "' + skillName + '" not found. Available: ' + dirs.join(', ') };
2838
- }
2839
- const content = readFileSync(skillPath, 'utf8');
2840
- const references = [];
2841
- const refDir = join(SKILLS_ROOT, skillName, 'references');
2842
- if (existsSync(refDir)) {
2843
- readdirSync(refDir).forEach((f) => {
2844
- const refPath = join(refDir, f);
2845
- references.push({ filename: f, content: readFileSync(refPath, 'utf8').substring(0, 4000) });
2846
- });
2847
- }
2848
- const frontmatter = content.match(/^---\r?\n([\s\S]*?)\r?\n---/);
2849
- let version = 1,
2850
- description = '';
2851
- if (frontmatter) {
2852
- const fm = frontmatter[1];
2853
- const vm = fm.match(/^version:\s*(.+)$/m);
2854
- if (vm) version = vm[1].trim();
2855
- const dm = fm.match(/^description:\s*(.+)$/m);
2856
- if (dm) description = dm[1].trim();
2857
- }
2858
- return { ok: true, name: skillName, version, description, content, references };
2859
- }
2860
-
2861
- async function listRegions() {
2862
- const result = await runHcloud(['IAM', 'KeystoneListRegions'], { timeoutMs: 30000, maxRetries: 0 }).catch(
2863
- (error) => ({
2864
- ok: false,
2865
- error: error.message,
2866
- }),
2867
- );
2868
- if (!result.ok) {
2869
- return {
2870
- ok: false,
2871
- error: result.error || 'Failed to list regions.',
2872
- fallback: 'Check https://developer.huaweicloud.com/endpoint for available regions.',
2873
- staticRegions: [
2874
- { id: 'cn-north-1', description: '华北-北京一' },
2875
- { id: 'cn-north-4', description: '华北-北京四' },
2876
- { id: 'cn-east-3', description: '华东-上海一' },
2877
- { id: 'cn-east-2', description: '华东-上海二' },
2878
- { id: 'cn-south-1', description: '华南-广州' },
2879
- { id: 'ap-southeast-1', description: '香港' },
2880
- { id: 'ap-southeast-3', description: '新加坡' },
2881
- { id: 'ap-southeast-2', description: '曼谷' },
2882
- { id: 'af-south-1', description: '约翰内斯堡' },
2883
- ],
2884
- note: 'hcloud unavailable. Showing static region list. For the complete list, visit the fallback URL.',
2885
- };
2886
- }
2887
- let regions;
2888
- try {
2889
- const parsed = typeof result.stdout === 'string' ? JSON.parse(result.stdout) : result.stdout;
2890
- const rawRegions = parsed.regions || [];
2891
- regions = rawRegions.map((r) => ({
2892
- id: r.id,
2893
- description: r.description || r.names,
2894
- type: r.type,
2895
- locales: r.locales,
2896
- }));
2897
- } catch {
2898
- regions = [{ raw: String(result.stdout).substring(0, 1000) }];
2899
- }
2900
- regions.sort((a, b) => String(a.id || '').localeCompare(String(b.id || '')));
2901
- return { ok: true, count: regions.length, regions };
2902
- }
2903
-
2904
- async function getRegionalAvailability(service, region) {
2905
- const svc = String(service || '')
2906
- .toLowerCase()
2907
- .trim();
2908
- const reg = String(region || '')
2909
- .toLowerCase()
2910
- .trim();
2911
- if (!svc || !reg) return { ok: false, error: 'Both service and region are required.' };
2912
- const known = {
2913
- ecs: [
2914
- 'cn-south-1',
2915
- 'cn-north-4',
2916
- 'cn-north-1',
2917
- 'cn-east-3',
2918
- 'cn-east-2',
2919
- 'ap-southeast-3',
2920
- 'ap-southeast-2',
2921
- 'ap-southeast-1',
2922
- 'ap-southeast-4',
2923
- 'af-south-1',
2924
- 'tr-west-1',
2925
- 'sa-brazil-1',
2926
- 'la-north-2',
2927
- 'na-mexico-1',
2928
- 'me-east-1',
2929
- ],
2930
- obs: [
2931
- 'cn-south-1',
2932
- 'cn-north-4',
2933
- 'cn-north-1',
2934
- 'cn-east-3',
2935
- 'cn-east-2',
2936
- 'ap-southeast-3',
2937
- 'ap-southeast-2',
2938
- 'ap-southeast-1',
2939
- 'af-south-1',
2940
- ],
2941
- vpc: [
2942
- 'cn-south-1',
2943
- 'cn-north-4',
2944
- 'cn-north-1',
2945
- 'cn-east-3',
2946
- 'cn-east-2',
2947
- 'ap-southeast-3',
2948
- 'ap-southeast-2',
2949
- 'ap-southeast-1',
2950
- 'ap-southeast-4',
2951
- 'af-south-1',
2952
- 'tr-west-1',
2953
- 'sa-brazil-1',
2954
- 'la-north-2',
2955
- 'me-east-1',
2956
- ],
2957
- iam: ['global'],
2958
- rds: [
2959
- 'cn-south-1',
2960
- 'cn-north-4',
2961
- 'cn-north-1',
2962
- 'cn-east-3',
2963
- 'cn-east-2',
2964
- 'ap-southeast-3',
2965
- 'ap-southeast-2',
2966
- 'ap-southeast-1',
2967
- ],
2968
- gaussdb: ['cn-south-1', 'cn-north-4', 'cn-east-3'],
2969
- cce: [
2970
- 'cn-south-1',
2971
- 'cn-north-4',
2972
- 'cn-north-1',
2973
- 'cn-east-3',
2974
- 'cn-east-2',
2975
- 'ap-southeast-3',
2976
- 'ap-southeast-2',
2977
- 'ap-southeast-1',
2978
- ],
2979
- modelarts: ['cn-south-1', 'cn-north-4', 'cn-east-3'],
2980
- functiongraph: [
2981
- 'cn-south-1',
2982
- 'cn-north-4',
2983
- 'cn-north-1',
2984
- 'cn-east-3',
2985
- 'cn-east-2',
2986
- 'ap-southeast-3',
2987
- 'ap-southeast-2',
2988
- 'ap-southeast-1',
2989
- ],
2990
- dew: ['cn-south-1', 'cn-north-4', 'cn-east-3', 'ap-southeast-3'],
2991
- smn: ['cn-south-1', 'cn-north-4', 'cn-east-3', 'ap-southeast-3'],
2992
- ces: ['cn-south-1', 'cn-north-4', 'cn-east-3', 'ap-southeast-3'],
2993
- cts: ['cn-south-1', 'cn-north-4', 'cn-east-3', 'ap-southeast-3'],
2994
- apig: ['cn-south-1', 'cn-north-4', 'cn-east-3', 'ap-southeast-3'],
2995
- cbr: ['cn-south-1', 'cn-north-4', 'cn-east-3', 'ap-southeast-3'],
2996
- dds: ['cn-south-1', 'cn-north-4', 'cn-east-3', 'ap-southeast-3'],
2997
- dcs: ['cn-south-1', 'cn-north-4', 'cn-east-3', 'ap-southeast-3'],
2998
- };
2999
- if (!known[svc])
3000
- return {
3001
- ok: false,
3002
- service: svc,
3003
- region: reg,
3004
- available: false,
3005
- note:
3006
- 'Service ' +
3007
- svc +
3008
- ' is not in the regional availability cache. Run hcloud ' +
3009
- svc.toUpperCase() +
3010
- ' --help to verify, or check https://developer.huaweicloud.com/endpoint.',
3011
- };
3012
- const available = known[svc].includes(reg) || known[svc].includes('global');
3013
- return {
3014
- ok: true,
3015
- service: svc,
3016
- region: reg,
3017
- available,
3018
- note: available
3019
- ? svc + ' is available in ' + reg + '.'
3020
- : svc +
3021
- ' availability in ' +
3022
- reg +
3023
- ' could not be confirmed. Verify at https://developer.huaweicloud.com/endpoint.',
3024
- sourcedFrom: 'static cache, update via npm package upgrade',
3025
- disclaimer:
3026
- 'This result reflects service-level availability only. It does NOT guarantee that your IAM user has permissions in this region. Account-level restrictions (e.g., APIGW.0802) may block actual API calls even when the service is available.',
3027
- };
3028
- }
3029
-
3030
- export function classifyRawCommand(command) {
3031
- return classifyTextCommand(command);
3032
- }
3033
-
3034
- // ── OBS Static Website Hosting (AWS4 signed REST API) ──
3035
-
3036
- async function handleObsWebsiteConfig(args) {
3037
- const { action, bucket, region, indexDocument, errorDocument } = args;
3038
- if (!bucket || !region) {
3039
- throw new Error('bucket and region are required');
3040
- }
3041
- const creds = resolveCredentialsWithRuntime({});
3042
- if (!creds?.ak || !creds?.sk) {
3043
- throw new Error('OBS website config requires AK/SK credentials. Run huaweicloud_auth_init first.');
3044
- }
3045
-
3046
- const host = `${bucket}.obs.${region}.myhuaweicloud.com`;
3047
- const endpoint = `https://${host}`;
3048
-
3049
- if (action === 'get') {
3050
- const res = await obsSignedRequest('GET', endpoint, '/?website', '', creds, region);
3051
- return { ok: res.status === 200, status: res.status, body: res.body };
3052
- }
3053
-
3054
- if (action === 'delete') {
3055
- const res = await obsSignedRequest('DELETE', endpoint, '/?website', '', creds, region);
3056
- return { ok: res.status === 204, status: res.status };
3057
- }
3058
-
3059
- if (action === 'set') {
3060
- if (!indexDocument) {
3061
- throw new Error('indexDocument is required for action=set');
3062
- }
3063
- const xmlParts = ['<WebsiteConfiguration>', ` <IndexDocument><Suffix>${indexDocument}</Suffix></IndexDocument>`];
3064
- if (errorDocument) {
3065
- xmlParts.push(` <ErrorDocument><Key>${errorDocument}</Key></ErrorDocument>`);
3066
- }
3067
- xmlParts.push('</WebsiteConfiguration>');
3068
- const body = xmlParts.join('\n');
3069
- const res = await obsSignedRequest('PUT', endpoint, '/?website', body, creds, region);
3070
- const websiteUrl = `http://${bucket}.obs-website.${region}.myhuaweicloud.com`;
3071
- return {
3072
- ok: res.status === 200,
3073
- status: res.status,
3074
- websiteUrl,
3075
- message:
3076
- res.status === 200
3077
- ? `Static website hosting configured. Website URL: ${websiteUrl} (may take ~1 min to propagate)`
3078
- : `Failed to configure website: HTTP ${res.status}`,
3079
- };
3080
- }
3081
-
3082
- throw new Error(`Unknown action: ${action}. Use set, get, or delete.`);
3083
- }
3084
-
3085
- // #1003: same-structure extension of handleObsWebsiteConfig — KooCLI OBS does
3086
- // not expose a cors subcommand and there is no SetBucketCors MCP path, so
3087
- // agents fell back to installing a Python SDK in the sandbox just to configure
3088
- // CORS. This reuses obsSignedRequest (AWS4, s3 service) against /?cors.
3089
- async function handleObsCorsConfig(args = {}) {
3090
- const { action, bucket, region, rules } = args;
3091
- if (!bucket || !region) {
3092
- throw new Error('bucket and region are required');
3093
- }
3094
- const creds = resolveCredentialsWithRuntime({});
3095
- if (!creds?.ak || !creds?.sk) {
3096
- throw new Error('OBS CORS config requires AK/SK credentials. Run huaweicloud_auth_init first.');
3097
- }
3098
-
3099
- const host = `${bucket}.obs.${region}.myhuaweicloud.com`;
3100
- const endpoint = `https://${host}`;
3101
- const preflightHint =
3102
- 'Verify with an OPTIONS preflight before declaring success: ' +
3103
- `curl -i -X OPTIONS --noproxy '*' 'https://${host}/<object-key>' -H 'Origin: <your-app-origin>' -H 'Access-Control-Request-Method: HEAD' ` +
3104
- 'must return HTTP 200 with an Access-Control-Allow-Origin header (200 without CORS headers = config not effective; ' +
3105
- '403 = rule missing the requested method). See the huawei-obs skill common-pitfalls.md p05.';
3106
-
3107
- if (action === 'get') {
3108
- const res = await obsSignedRequest('GET', endpoint, '/?cors', '', creds, region, 'cors');
3109
- return { ok: res.status === 200, status: res.status, rules: res.body, verify: preflightHint };
3110
- }
3111
-
3112
- if (action === 'delete') {
3113
- const res = await obsSignedRequest('DELETE', endpoint, '/?cors', '', creds, region, 'cors');
3114
- return { ok: res.status === 204, status: res.status };
3115
- }
3116
-
3117
- if (action === 'set') {
3118
- if (!Array.isArray(rules) || rules.length === 0) {
3119
- throw new Error('rules array is required for action=set (allowedOrigin + allowedMethod, HEAD included)');
3120
- }
3121
- for (const rule of rules) {
3122
- if (!rule?.allowedOrigin || !Array.isArray(rule?.allowedMethod) || rule.allowedMethod.length === 0) {
3123
- throw new Error('each CORS rule needs allowedOrigin and a non-empty allowedMethod array');
3124
- }
3125
- if (!rule.allowedMethod.includes('HEAD')) {
3126
- // p01: the BrowserJS SDK's HEAD ?apiversion probe gets swallowed by the
3127
- // browser when HEAD is missing — the exact failure this tool exists to
3128
- // prevent, so reject it at the input boundary instead of at runtime.
3129
- throw new Error(
3130
- "allowedMethod must include 'HEAD' — the BrowserJS SDK sends a HEAD ?apiversion probe before every " +
3131
- 'operation, and a CORS rule without HEAD makes the browser swallow it as Network Error (p01).',
3132
- );
3133
- }
3134
- }
3135
- const escapeXml = (s) =>
3136
- String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
3137
- const xmlParts = ['<CORSConfiguration>'];
3138
- for (const rule of rules) {
3139
- xmlParts.push(' <CORSRule>');
3140
- xmlParts.push(` <AllowedOrigin>${escapeXml(rule.allowedOrigin)}</AllowedOrigin>`);
3141
- for (const method of rule.allowedMethod) {
3142
- xmlParts.push(` <AllowedMethod>${escapeXml(method)}</AllowedMethod>`);
3143
- }
3144
- for (const header of rule.allowedHeader || ['*']) {
3145
- xmlParts.push(` <AllowedHeader>${escapeXml(header)}</AllowedHeader>`);
3146
- }
3147
- if (rule.maxAgeSeconds != null) {
3148
- xmlParts.push(` <MaxAgeSeconds>${Number(rule.maxAgeSeconds)}</MaxAgeSeconds>`);
3149
- }
3150
- xmlParts.push(' </CORSRule>');
3151
- }
3152
- xmlParts.push('</CORSConfiguration>');
3153
- const body = xmlParts.join('\n');
3154
- const res = await obsSignedRequest('PUT', endpoint, '/?cors', body, creds, region, 'cors');
3155
- return {
3156
- ok: res.status === 200,
3157
- status: res.status,
3158
- message:
3159
- res.status === 200
3160
- ? `CORS configured for ${bucket} (${rules.length} rule(s)).`
3161
- : `Failed to configure CORS: HTTP ${res.status}`,
3162
- verify: preflightHint,
3163
- };
3164
- }
3165
-
3166
- throw new Error(`Unknown action: ${action}. Use set, get, or delete.`);
3167
- }
3168
-
3169
- // Single AWS4-signed OBS REST API caller shared by the website/CORS tools
3170
- // (#1003): subresource is the bucket subresource being addressed — 'website'
3171
- // for PUT/GET/DELETE /?website, 'cors' for /?cors. Credential scope uses the
3172
- // s3 service name (OBS is S3-compatible).
3173
- async function obsSignedRequest(method, endpoint, pathAndQuery, body, creds, region, subresource = 'website') {
3174
- const now = new Date();
3175
- const dateStamp = now.toISOString().slice(0, 10).replace(/-/g, '');
3176
- const amzDate = dateStamp + 'T' + now.toISOString().slice(11, 19).replace(/:/g, '') + 'Z';
3177
- const payloadHash = createHash('sha256').update(body).digest('hex');
3178
-
3179
- const url = new URL(endpoint + pathAndQuery);
3180
- const canonicalUri = '/';
3181
- const canonicalQueryString = `${subresource}=`;
3182
- const canonicalHeaders = `host:${url.host}\n` + `x-amz-content-sha256:${payloadHash}\n` + `x-amz-date:${amzDate}\n`;
3183
- const signedHeaders = 'host;x-amz-content-sha256;x-amz-date';
3184
- const canonicalRequest = [
3185
- method,
3186
- canonicalUri,
3187
- canonicalQueryString,
3188
- canonicalHeaders,
3189
- signedHeaders,
3190
- payloadHash,
3191
- ].join('\n');
3192
-
3193
- const credentialScope = `${dateStamp}/${region}/s3/aws4_request`;
3194
- const stringToSign = [
3195
- 'AWS4-HMAC-SHA256',
3196
- amzDate,
3197
- credentialScope,
3198
- createHash('sha256').update(canonicalRequest).digest('hex'),
3199
- ].join('\n');
3200
-
3201
- const kDate = createHmac('sha256', 'AWS4' + creds.sk)
3202
- .update(dateStamp)
3203
- .digest();
3204
- const kRegion = createHmac('sha256', kDate).update(region).digest();
3205
- const kService = createHmac('sha256', kRegion).update('s3').digest();
3206
- const kSigning = createHmac('sha256', kService).update('aws4_request').digest();
3207
- const signature = createHmac('sha256', kSigning).update(stringToSign).digest('hex');
3208
-
3209
- const authorization =
3210
- `AWS4-HMAC-SHA256 Credential=${creds.ak}/${credentialScope}, ` +
3211
- `SignedHeaders=${signedHeaders}, Signature=${signature}`;
3212
-
3213
- const headers = {
3214
- Host: url.host,
3215
- 'x-amz-content-sha256': payloadHash,
3216
- 'x-amz-date': amzDate,
3217
- Authorization: authorization,
3218
- };
3219
- if (body) headers['Content-Type'] = 'application/xml';
3220
- if (creds.securityToken) headers['x-amz-security-token'] = creds.securityToken;
3221
-
3222
- const res = await fetchWithProxy(endpoint + pathAndQuery, {
3223
- method,
3224
- headers,
3225
- body: body || undefined,
3226
- });
3227
- const resBody = await res.text();
3228
- return { status: res.status, body: resBody };
3229
- }