huaweicloud-devkit 1.1.13 → 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 (697) 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 -9
  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} +210 -36
  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 -60
  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/{sandbox/hdkitservice-api.mjs → lib/hdkit/hdkitservice-api.ts} +99 -118
  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/skills/huaweicloud-core/SKILL.md +0 -32
  660. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/scripts/cli/cli_reporting.py +0 -589
  661. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/references/test-report.md +0 -35
  662. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/scripts/cli/cli_reporting.py +0 -928
  663. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/scripts/cli/cli_reporting.py +0 -928
  664. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/references/test-report.md +0 -52
  665. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/scripts/cli/cli_reporting.py +0 -928
  666. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/scripts/cli/cli_reporting.py +0 -577
  667. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/scripts/cli/cli_reporting.py +0 -928
  668. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/scripts/gaussdb_cli.sh +0 -138
  669. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/scripts/install_cli.sh +0 -94
  670. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/scripts/smn_dms_skill.py +0 -444
  671. package/plugins/huaweicloud-core/src/account-type.mjs +0 -135
  672. package/plugins/huaweicloud-core/src/auth/agent-registration.mjs +0 -243
  673. package/plugins/huaweicloud-core/src/auth/credential-validator.mjs +0 -198
  674. package/plugins/huaweicloud-core/src/auth/credentials.mjs +0 -446
  675. package/plugins/huaweicloud-core/src/auth/project-id.mjs +0 -68
  676. package/plugins/huaweicloud-core/src/auth/reconcile.mjs +0 -257
  677. package/plugins/huaweicloud-core/src/detect-framework.mjs +0 -402
  678. package/plugins/huaweicloud-core/src/hcloud-cli.mjs +0 -825
  679. package/plugins/huaweicloud-core/src/koocli-version.mjs +0 -47
  680. package/plugins/huaweicloud-core/src/mcp-config-merge.mjs +0 -219
  681. package/plugins/huaweicloud-core/src/mcp-protocol.mjs +0 -109
  682. package/plugins/huaweicloud-core/src/mcp-server-remote.mjs +0 -108
  683. package/plugins/huaweicloud-core/src/mcp-server.mjs +0 -221
  684. package/plugins/huaweicloud-core/src/officeace-paths.mjs +0 -51
  685. package/plugins/huaweicloud-core/src/preflight.mjs +0 -125
  686. package/plugins/huaweicloud-core/src/proxy/proxy-config.mjs +0 -187
  687. package/plugins/huaweicloud-core/src/risk-rule-engine.mjs +0 -182
  688. package/plugins/huaweicloud-core/src/safety-policy.mjs +0 -625
  689. package/plugins/huaweicloud-core/src/sandbox/hwlink-api.mjs +0 -224
  690. package/plugins/huaweicloud-core/src/sandbox/session-manager.mjs +0 -2594
  691. package/plugins/huaweicloud-core/src/setup-cli.mjs +0 -5379
  692. package/plugins/huaweicloud-core/src/telemetry/agent-registry.mjs +0 -341
  693. package/plugins/huaweicloud-core/src/telemetry/telemetry.mjs +0 -492
  694. package/plugins/huaweicloud-core/src/tools.mjs +0 -3190
  695. package/plugins/huaweicloud-core/src/update-check.mjs +0 -476
  696. package/plugins/huaweicloud-core/src/ws-exec/hwlink-exec-client.js +0 -461
  697. package/plugins/huaweicloud-core/src/ws-exec/ws-exec-client.js +0 -365
@@ -1,2594 +0,0 @@
1
- import { spawn, execFile } from 'node:child_process';
2
- import { promisify } from 'node:util';
3
- import { createConnection as netConnect } from 'node:net';
4
- import {
5
- existsSync,
6
- readFileSync,
7
- statSync,
8
- mkdirSync,
9
- rmSync,
10
- createReadStream,
11
- appendFileSync,
12
- unlinkSync,
13
- } from 'node:fs';
14
- import { createHash, randomBytes } from 'node:crypto';
15
- import { join, dirname, basename } from 'node:path';
16
- import { tmpdir } from 'node:os';
17
- import { fileURLToPath, pathToFileURL } from 'node:url';
18
-
19
- import { createConnection, getCredentials } from './hwlink-api.mjs';
20
- import { getWebSocketImpl } from '../proxy/proxy-agent.mjs';
21
- import { trackSandboxConnect, trackSandboxDisconnect } from '../telemetry/telemetry.mjs';
22
- import { buildExposeLifetimeNotice } from './sandbox-pool.mjs';
23
-
24
- const execFileAsync = promisify(execFile);
25
-
26
- // Public tunnel URL domain for the DevBridge s2 gateway. The pre-migration Huawei Cloud
27
- // bridge domain was retired in Sep 2026 and now serves a 「服务已迁移」 placeholder page with
28
- // HTTP 200 — never construct tunnel URLs from it.
29
- const DEVBRIDGE_TUNNEL_DOMAIN = 'devbridge-s2.hwtunnel.com';
30
- // Migration placeholder page marker — a tunnel URL returning this body must be treated as unreachable.
31
- const DEVBRIDGE_MIGRATION_MARKER = '服务已迁移';
32
- // Gateway-level tunnel error markers (verified against the live s2 gateway, Oct 2026).
33
- // The gateway answers with exact text/plain bodies:
34
- // 404 "tunnel not found" — no live host session on the gateway (host process dead or
35
- // tunnel deleted); the tunnel RECORD may still exist in `list`
36
- // 404 "port not configured" — the URL's port is not registered on the tunnel
37
- // 502 "bad gateway" — host session alive, but the registered port has no local service
38
- // A bare status check cannot distinguish these from app-generated 404/502 responses, so the
39
- // checks below match the exact body AND gate on the HTTP status code.
40
- const DEVBRIDGE_TUNNEL_NOT_FOUND_MARKER = 'tunnel not found';
41
- const DEVBRIDGE_PORT_NOT_CONFIGURED_MARKER = 'port not configured';
42
- const DEVBRIDGE_BAD_GATEWAY_MARKER = 'bad gateway';
43
-
44
- const __dirname = dirname(fileURLToPath(import.meta.url));
45
- export const WS_EXEC_INDEX_URL = pathToFileURL(join(__dirname, '..', 'ws-exec', 'index.js')).href;
46
-
47
- export const TUNNEL_URL_PATTERN = /TUNNEL_URL:(https:\/\/[A-Za-z0-9_-]+-\d+\.devbridge-s2\.hwtunnel\.com)/;
48
-
49
- let currentWorkspaceId = process.env.HW_WORKSPACE_ID || null;
50
-
51
- function getCurrentWorkspaceId() {
52
- return currentWorkspaceId;
53
- }
54
-
55
- function setWorkspaceId(id) {
56
- if (id && id !== currentWorkspaceId) {
57
- trackSandboxConnect();
58
- }
59
- currentWorkspaceId = id;
60
- process.env.HW_WORKSPACE_ID = id;
61
- }
62
-
63
- function resolveEnv() {
64
- const env = { ...process.env };
65
- env.PATH = `${env.HOME || '/root'}/.huawei/bin:${env.PATH || ''}`;
66
- return env;
67
- }
68
-
69
- async function runNodeExec(args, timeoutMs = 30000) {
70
- const env = resolveEnv();
71
- return new Promise((resolve) => {
72
- const proc = spawn('node', args, { env, stdio: ['pipe', 'pipe', 'pipe'] });
73
- let stdout = '';
74
- let stderr = '';
75
- proc.stdout.on('data', (d) => {
76
- stdout += d.toString();
77
- });
78
- proc.stderr.on('data', (d) => {
79
- stderr += d.toString();
80
- });
81
-
82
- const timer = setTimeout(() => {
83
- proc.kill();
84
- resolve({ error: 'timed out', exitCode: 124 });
85
- }, timeoutMs);
86
-
87
- proc.on('close', (code) => {
88
- clearTimeout(timer);
89
- const out = stdout.trim();
90
- if (out) {
91
- try {
92
- resolve({ ...JSON.parse(out), exitCode: code || 0 });
93
- return;
94
- } catch {}
95
- }
96
- if (code && code !== 0 && !out) {
97
- resolve({ error: stderr.trim() || `exit code ${code}`, exitCode: code });
98
- return;
99
- }
100
- resolve({ data: out, exitCode: code || 0 });
101
- });
102
- });
103
- }
104
-
105
- const sessions = new Map();
106
-
107
- async function getSession(workspaceId, username, timeoutMs) {
108
- const key = `${workspaceId}:${username}`;
109
- if (sessions.has(key)) return sessions.get(key);
110
-
111
- const { ak, sk, securitytoken } = getCredentials();
112
- const { wsUrl, source } = await createConnection(workspaceId, ak, sk, securitytoken);
113
-
114
- const WebSocketImpl = await getWebSocketImpl(wsUrl);
115
-
116
- const { connectHwlinkTerminalSession } = await import(WS_EXEC_INDEX_URL);
117
- const session = await connectHwlinkTerminalSession({
118
- url: wsUrl,
119
- source,
120
- username,
121
- timeoutMs,
122
- WebSocketImpl,
123
- });
124
-
125
- sessions.set(key, session);
126
- return session;
127
- }
128
-
129
- async function createTunnelSession(workspaceId, username, timeoutMs = 30000) {
130
- const { ak, sk, securitytoken } = getCredentials();
131
- const { wsUrl, source } = await createConnection(workspaceId, ak, sk, securitytoken);
132
- const WebSocketImpl = await getWebSocketImpl(wsUrl);
133
-
134
- const { HwlinkWebSocketMultiplexer } = await import(WS_EXEC_INDEX_URL);
135
- const mux = new HwlinkWebSocketMultiplexer(wsUrl, source, { WebSocketImpl, protocol: 'devenv' });
136
-
137
- await new Promise((resolve, reject) => {
138
- const timer = setTimeout(() => {
139
- clearInterval(interval);
140
- reject(new Error('tunnel session WebSocket open timeout'));
141
- }, timeoutMs);
142
- const interval = setInterval(() => {
143
- if (mux.readyState === 1) {
144
- clearTimeout(timer);
145
- clearInterval(interval);
146
- resolve();
147
- } else if (mux.readyState === 3) {
148
- clearTimeout(timer);
149
- clearInterval(interval);
150
- reject(new Error('tunnel session WebSocket closed'));
151
- }
152
- }, 100);
153
- mux.onClose = () => {
154
- clearTimeout(timer);
155
- clearInterval(interval);
156
- reject(new Error('tunnel session WebSocket closed'));
157
- };
158
- mux.onError = (err) => {
159
- clearTimeout(timer);
160
- clearInterval(interval);
161
- reject(err);
162
- };
163
- });
164
-
165
- return { mux, close: () => mux.close() };
166
- }
167
-
168
- export async function execOneShot(workspaceId, command, username, timeoutMs) {
169
- const { ak, sk, securitytoken } = getCredentials();
170
- const { wsUrl, source } = await createConnection(workspaceId, ak, sk, securitytoken);
171
-
172
- const WebSocketImpl = await getWebSocketImpl(wsUrl);
173
-
174
- const { executeHwlinkCommand } = await import(WS_EXEC_INDEX_URL);
175
- return await executeHwlinkCommand({
176
- url: wsUrl,
177
- source,
178
- username,
179
- command,
180
- timeoutMs,
181
- WebSocketImpl,
182
- });
183
- }
184
-
185
- export async function execWithSession(workspaceId, command, username, timeoutMs) {
186
- const session = await getSession(workspaceId, username, timeoutMs);
187
- return await session.exec(command, { timeoutMs });
188
- }
189
-
190
- export const UPLOAD_CHUNK_SIZE = 30000;
191
-
192
- export const UPLOAD_BATCH_SIZE = 2;
193
-
194
- export const UPLOAD_MAX_RETRIES = 3;
195
-
196
- export function splitBase64Chunks(base64, chunkSize = UPLOAD_CHUNK_SIZE) {
197
- const chunks = [];
198
- for (let offset = 0; offset < base64.length; offset += chunkSize) {
199
- chunks.push(base64.slice(offset, offset + chunkSize));
200
- }
201
- return chunks;
202
- }
203
-
204
- export function formatPortConflictWarning(basePort, targetPort) {
205
- return targetPort !== basePort ? `Port ${basePort} is in use — auto-assigned port ${targetPort}` : undefined;
206
- }
207
-
208
- export function formatPortDriftWarning(basePort, targetPort) {
209
- if (targetPort === basePort) return undefined;
210
- return `Port ${basePort} was occupied — nginx now listens on port ${targetPort}. Any DevBridge tunnel bound to port ${basePort} is detached: run "devbridge port create <tunnelId> -p ${targetPort} --protocol http -a" and restart "devbridge host" for the new port.`;
211
- }
212
-
213
- export async function resolveProxyNodePort(nodePort, nginxListenPort, isPortInUse) {
214
- const baseCandidate = nodePort && nodePort !== nginxListenPort ? nodePort : nginxListenPort + 1;
215
- let candidate = baseCandidate;
216
- for (
217
- let attempt = 0;
218
- attempt < 10 && (candidate === nginxListenPort || (await isPortInUse(candidate)));
219
- attempt += 1
220
- ) {
221
- candidate += 1;
222
- }
223
- return candidate;
224
- }
225
-
226
- export function buildExposeRemediation(port) {
227
- return `In the sandbox: source /tmp/hw_creds.sh; source /tmp/hw_api_key 2>/dev/null; devbridge delete-all; devbridge create <name>; devbridge port create <tunnelId> -p ${port} --protocol http -a; nohup devbridge host <tunnelId> -p ${port} > /tmp/host.log 2>&1 & If deploy_nginx reported a different (auto-incremented) port in its "port" field, use THAT port instead of the one shown here. Full procedure in huawei-sandbox skill, Step 7 (Expose via DevBridge).`;
228
- }
229
-
230
- // #953: classify a local upload path BEFORE touching the file, so the error names
231
- // the real problem instead of a misleading "not found" when an entire parent
232
- // directory is missing (agent-side paths often do not exist at all).
233
- // kind: 'file' (uploadFileWithSession) | 'directory' (uploadProjectWithSession).
234
- // Returns null when the path exists with the expected type; otherwise an Error
235
- // whose message distinguishes missing-path from missing-parent, with a copy-to-tmp
236
- // hint that names the actual OS temp dir.
237
- export function classifyLocalUploadPath(localPath, kind = 'file') {
238
- const expected = kind === 'directory' ? 'directory' : 'regular file';
239
- const prefix = kind === 'directory' ? 'sandbox upload project' : 'sandbox upload';
240
- if (existsSync(localPath)) {
241
- const stat = statSync(localPath);
242
- const matches = kind === 'directory' ? stat.isDirectory() : stat.isFile();
243
- if (!matches) {
244
- return new Error(`${prefix}: path is not a ${expected}: ${localPath}`);
245
- }
246
- return null;
247
- }
248
- const parent = dirname(localPath);
249
- if (!existsSync(parent)) {
250
- return new Error(
251
- `${prefix}: directory not found: ${parent}. The DevKit MCP server reads files from ` +
252
- `the machine it runs on. Verify the path, or first copy the ${expected} to the local ` +
253
- `temp directory (${tmpdir()}) and upload from there.`,
254
- );
255
- }
256
- return new Error(`${prefix}: local ${expected} not found: ${localPath}`);
257
- }
258
-
259
- // #953: reset command for uploadFileWithSession. mkdir -p the remote parent BEFORE any
260
- // chunk writes — the `printf >>` appends land in "${remotePath}.b64tmp" next to the
261
- // target, so an absent directory (e.g. /workspace/game2048/) would fail the very first
262
- // batch. This aligns base64-path behavior with upload_project's file server (which
263
- // already makedirs). Both paths are quoted; "path with spaces" is covered by tests.
264
- export function buildUploadResetCommand(remotePath, tmpPath) {
265
- return `mkdir -p "$(dirname "${remotePath}")" && rm -f "${tmpPath}"`;
266
- }
267
-
268
- export async function uploadFileWithSession(workspaceId, localPath, remotePath, username = 'root', timeoutMs = 30000) {
269
- const localError = classifyLocalUploadPath(localPath, 'file');
270
- if (localError) {
271
- throw localError;
272
- }
273
- const content = readFileSync(localPath);
274
- const base64 = content.toString('base64');
275
- const expectedMd5 = createHash('md5').update(content).digest('hex');
276
- const chunks = splitBase64Chunks(base64);
277
- const tmp = `${remotePath}.b64tmp`;
278
-
279
- const reset = await execWithSession(workspaceId, buildUploadResetCommand(remotePath, tmp), username, timeoutMs);
280
- if (reset.exitCode !== 0) {
281
- throw new Error(`sandbox upload: failed to reset temp file: ${reset.stdout || reset.error || reset.exitCode}`);
282
- }
283
-
284
- for (let batchStart = 0; batchStart < chunks.length; batchStart += UPLOAD_BATCH_SIZE) {
285
- const batch = chunks.slice(batchStart, batchStart + UPLOAD_BATCH_SIZE);
286
- const combinedChunk = batch.join('');
287
- const batchNum = Math.floor(batchStart / UPLOAD_BATCH_SIZE) + 1;
288
- const totalBatches = Math.ceil(chunks.length / UPLOAD_BATCH_SIZE);
289
- const cmd = `printf '%s' '${combinedChunk}' >> "${tmp}"`;
290
-
291
- let batchOk = false;
292
- let lastError;
293
- for (let retry = 0; retry < UPLOAD_MAX_RETRIES; retry++) {
294
- const res = await execWithSession(workspaceId, cmd, username, timeoutMs);
295
- if (res.exitCode === 0) {
296
- batchOk = true;
297
- break;
298
- }
299
- lastError = res.stdout || res.error || res.exitCode;
300
- console.error(` upload retry ${retry + 1}/${UPLOAD_MAX_RETRIES} for batch ${batchNum}/${totalBatches}`);
301
- await new Promise((r) => setTimeout(r, 2000));
302
- }
303
- if (!batchOk) {
304
- throw new Error(`sandbox upload: failed writing batch ${batchNum}/${totalBatches}: ${lastError}`);
305
- }
306
- if (batchNum % 10 === 0 || batchNum === totalBatches) {
307
- console.error(` upload progress: batch ${batchNum}/${totalBatches}`);
308
- }
309
- }
310
-
311
- const decode = await execWithSession(
312
- workspaceId,
313
- `base64 -d "${tmp}" > "${remotePath}" && rm -f "${tmp}"`,
314
- username,
315
- timeoutMs,
316
- );
317
- if (decode.exitCode !== 0) {
318
- throw new Error(
319
- `sandbox upload: failed decoding to ${remotePath}: ${decode.stdout || decode.error || decode.exitCode}`,
320
- );
321
- }
322
-
323
- const verify = await execWithSession(workspaceId, `md5sum "${remotePath}"`, username, timeoutMs);
324
- let md5Verified = false;
325
- if (verify.exitCode === 0) {
326
- const remoteMd5 = String(verify.stdout || '')
327
- // eslint-disable-next-line no-control-regex
328
- .replace(/\x1b\[[0-9;]*[A-Za-z]/g, '')
329
- // eslint-disable-next-line no-control-regex
330
- .replace(/\x1b\][^\x07]*\x07/g, '')
331
- .trim()
332
- .split(/\s+/)[0];
333
- md5Verified = remoteMd5 === expectedMd5;
334
- if (!md5Verified) {
335
- throw new Error(
336
- `sandbox upload: md5 mismatch for ${remotePath} (expected ${expectedMd5}, got ${remoteMd5 || 'none'})`,
337
- );
338
- }
339
- }
340
-
341
- return {
342
- ok: true,
343
- localPath,
344
- remotePath,
345
- bytes: content.length,
346
- chunks: chunks.length,
347
- md5: expectedMd5,
348
- md5Verified,
349
- };
350
- }
351
-
352
- const SANDBOX_FILE_SERVER_SCRIPT = readFileSync(join(__dirname, 'sandbox-file-server.py'), 'utf8');
353
-
354
- const TUNNEL_READY_TIMEOUT_MS = 30000;
355
- const SERVER_HEALTH_MAX_RETRIES = 30;
356
- const SERVER_HEALTH_INTERVAL_MS = 1000;
357
- const UPLOAD_LOG_PATH = join(tmpdir(), 'sandbox-upload.log');
358
-
359
- function uploadLog(message) {
360
- const ts = new Date().toISOString();
361
- const line = `[${ts}] ${message}\n`;
362
- console.error(line.trimEnd());
363
- try {
364
- appendFileSync(UPLOAD_LOG_PATH, line);
365
- } catch {}
366
- }
367
-
368
- function rotateUploadLog(maxBytes = 100 * 1024) {
369
- try {
370
- if (existsSync(UPLOAD_LOG_PATH)) {
371
- const stat = statSync(UPLOAD_LOG_PATH);
372
- if (stat.size > maxBytes) {
373
- unlinkSync(UPLOAD_LOG_PATH);
374
- }
375
- }
376
- } catch {}
377
- }
378
-
379
- function generateUploadToken() {
380
- return randomBytes(16).toString('hex');
381
- }
382
-
383
- async function createTarGz(localDir, exclude = []) {
384
- const archiveName = `${basename(localDir)}.tar.gz`;
385
- const archiveDir = join(tmpdir(), `sandbox-upload-${Date.now()}`);
386
- mkdirSync(archiveDir, { recursive: true });
387
- const archivePath = join(archiveDir, archiveName);
388
-
389
- const hasGit = existsSync(join(localDir, '.git'));
390
- if (hasGit) {
391
- await execFileAsync('git', [
392
- '-C',
393
- localDir,
394
- 'archive',
395
- '--format=tar.gz',
396
- `--prefix=${basename(localDir)}/`,
397
- `--output=${archivePath}`,
398
- 'HEAD',
399
- ]);
400
- } else {
401
- const args = [];
402
- for (const pattern of exclude) {
403
- if (pattern.startsWith('**/')) {
404
- const base = pattern.slice(3);
405
- for (let depth = 0; depth <= 4; depth++) {
406
- const prefix = depth === 0 ? '' : '*/'.repeat(depth);
407
- args.push('--exclude', `${prefix}${base}`);
408
- }
409
- } else {
410
- args.push('--exclude', pattern);
411
- }
412
- }
413
- args.push('-czf', archivePath, '-C', dirname(localDir), basename(localDir));
414
- await execFileAsync('tar', args);
415
- }
416
-
417
- return archivePath;
418
- }
419
-
420
- async function computeMd5(filePath) {
421
- return new Promise((resolve, reject) => {
422
- const hash = createHash('md5');
423
- createReadStream(filePath)
424
- .on('data', (chunk) => hash.update(chunk))
425
- .on('end', () => resolve(hash.digest('hex')))
426
- .on('error', reject);
427
- });
428
- }
429
-
430
- function cleanupLocalArchive(archivePath) {
431
- try {
432
- rmSync(dirname(archivePath), { recursive: true, force: true });
433
- } catch {}
434
- }
435
-
436
- async function deployFileServer(workspaceId, username, port = 8888, token = '') {
437
- const scriptPath = '/tmp/sandbox-file-server.py';
438
- const pidFile = '/tmp/sandbox-file-server.pid';
439
- uploadLog(`deployFileServer: killing old server (pidFile=${pidFile})`);
440
- await execWithSession(workspaceId, `kill $(cat ${pidFile} 2>/dev/null) 2>/dev/null; rm -f ${pidFile}`, username);
441
- const b64 = Buffer.from(SANDBOX_FILE_SERVER_SCRIPT).toString('base64');
442
- uploadLog(`deployFileServer: writing script (${b64.length} b64 chars)`);
443
- await execWithSession(workspaceId, `echo '${b64}' | base64 -d > ${scriptPath}`, username);
444
- const cmd = token
445
- ? `python3 ${scriptPath} ${port} ${token} & echo $! > ${pidFile}`
446
- : `python3 ${scriptPath} ${port} & echo $! > ${pidFile}`;
447
- uploadLog(`deployFileServer: starting server on port ${port}`);
448
- const startResult = await execWithSession(workspaceId, cmd, username);
449
- uploadLog(
450
- `deployFileServer: start result exitCode=${startResult.exitCode} stdout=${JSON.stringify(startResult.stdout?.slice(0, 200))}`,
451
- );
452
- return startResult;
453
- }
454
-
455
- async function uploadViaTunnel(localPort, archivePath, archiveSize, archiveRemotePath, uploadToken, timeoutMs) {
456
- const archiveBuffer = readFileSync(archivePath);
457
- const headers = [
458
- 'POST /upload HTTP/1.1',
459
- 'Host: localhost',
460
- 'Content-Type: application/octet-stream',
461
- `Content-Length: ${archiveSize}`,
462
- `X-Target-Path: ${archiveRemotePath}`,
463
- `X-Upload-Token: ${uploadToken}`,
464
- 'Connection: close',
465
- '',
466
- '',
467
- ].join('\r\n');
468
- return new Promise((resolve, reject) => {
469
- let settled = false;
470
- const done = (fn) => {
471
- if (!settled) {
472
- settled = true;
473
- clearTimeout(timer);
474
- sock.destroy();
475
- fn();
476
- }
477
- };
478
- const timer = setTimeout(() => done(() => reject(new Error(`upload timeout after ${timeoutMs}ms`))), timeoutMs);
479
- const sock = netConnect({ host: '127.0.0.1', port: localPort }, () => {
480
- sock.write(headers);
481
- sock.write(archiveBuffer);
482
- });
483
- let respBuf = Buffer.alloc(0);
484
- let contentLength = -1;
485
- let headerEnd = -1;
486
- sock.on('data', (chunk) => {
487
- respBuf = Buffer.concat([respBuf, chunk]);
488
- if (contentLength < 0) {
489
- const resp = respBuf.toString();
490
- headerEnd = resp.indexOf('\r\n\r\n');
491
- if (headerEnd > 0) {
492
- const headerBlock = resp.slice(0, headerEnd);
493
- const clMatch = headerBlock.match(/Content-Length:\s*(\d+)/i);
494
- if (clMatch) contentLength = parseInt(clMatch[1], 10);
495
- }
496
- }
497
- if (contentLength >= 0 && headerEnd > 0) {
498
- const bodyReceived = respBuf.length - (headerEnd + 4);
499
- if (bodyReceived >= contentLength) {
500
- done(() => {
501
- const resp = respBuf.toString();
502
- const statusLine = resp.split('\r\n')[0] || '';
503
- const statusCode = parseInt(statusLine.split(' ')[1], 10);
504
- const body = resp.slice(headerEnd + 4, headerEnd + 4 + contentLength);
505
- if (!statusCode || statusCode < 200 || statusCode >= 300) {
506
- uploadLog(`uploadViaTunnel: POST failed with HTTP ${statusCode}: ${body.slice(0, 200)}`);
507
- reject(new Error(`upload HTTP ${statusCode}: ${body}`));
508
- return;
509
- }
510
- try {
511
- resolve(JSON.parse(body));
512
- } catch (error) {
513
- reject(new Error(`invalid JSON response: ${body.slice(0, 200)}`));
514
- }
515
- });
516
- }
517
- }
518
- });
519
- sock.on('close', () => {
520
- done(() => {
521
- const resp = respBuf.toString();
522
- const statusLine = resp.split('\r\n')[0] || '';
523
- const statusCode = parseInt(statusLine.split(' ')[1], 10);
524
- const he = resp.indexOf('\r\n\r\n');
525
- const body = he > 0 ? resp.slice(he + 4) : '';
526
- if (!statusCode || statusCode < 200 || statusCode >= 300) {
527
- uploadLog(`uploadViaTunnel: POST failed with HTTP ${statusCode}: ${body.slice(0, 200)}`);
528
- reject(new Error(`upload HTTP ${statusCode}: ${body}`));
529
- return;
530
- }
531
- try {
532
- resolve(JSON.parse(body));
533
- } catch (error) {
534
- reject(new Error(`invalid JSON response: ${body.slice(0, 200)}`));
535
- }
536
- });
537
- });
538
- sock.on('error', (err) => {
539
- done(() => {
540
- uploadLog(`uploadViaTunnel: socket error: ${err.message}`);
541
- reject(err);
542
- });
543
- });
544
- });
545
- }
546
-
547
- async function waitForServerReady(localPort) {
548
- for (let i = 0; i < SERVER_HEALTH_MAX_RETRIES; i++) {
549
- try {
550
- uploadLog(`waitForServerReady: attempt ${i + 1}, checking http://localhost:${localPort}/health`);
551
- const ok = await new Promise((resolve) => {
552
- let settled = false;
553
- const done = (val) => {
554
- if (!settled) {
555
- settled = true;
556
- sock.destroy();
557
- resolve(val);
558
- }
559
- };
560
- const sock = netConnect({ host: '127.0.0.1', port: localPort }, () => {
561
- sock.write('GET /health HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n');
562
- });
563
- let resp = '';
564
- sock.on('data', (c) => {
565
- resp += c.toString();
566
- if (resp.includes('200 OK')) done(true);
567
- });
568
- sock.on('close', () => done(resp.includes('200 OK')));
569
- sock.on('error', () => done(false));
570
- setTimeout(() => done(false), 3000);
571
- });
572
- if (ok) {
573
- uploadLog(`waitForServerReady: server ready on port ${localPort} after ${i} retries`);
574
- return;
575
- }
576
- uploadLog(`waitForServerReady: health check returned non-200 (retry ${i + 1})`);
577
- } catch (error) {
578
- uploadLog(`waitForServerReady: health check failed: ${error.message} (retry ${i + 1})`);
579
- }
580
- await new Promise((r) => setTimeout(r, SERVER_HEALTH_INTERVAL_MS));
581
- }
582
- throw new Error(
583
- `sandbox file server not ready after ${SERVER_HEALTH_MAX_RETRIES * SERVER_HEALTH_INTERVAL_MS}ms (log: ${UPLOAD_LOG_PATH})`,
584
- );
585
- }
586
-
587
- async function cleanupFileServer(workspaceId, username) {
588
- const pidFile = '/tmp/sandbox-file-server.pid';
589
- const scriptPath = '/tmp/sandbox-file-server.py';
590
- await execWithSession(workspaceId, `kill $(cat ${pidFile}) 2>/dev/null; rm -f ${pidFile} ${scriptPath}`, username);
591
- }
592
-
593
- async function uploadViaHttpTunnel(workspaceId, archivePath, archiveRemotePath, username, timeoutMs, options) {
594
- const sandboxPort = options.sandboxPort || 8888;
595
- const uploadToken = generateUploadToken();
596
- const archiveSize = statSync(archivePath).size;
597
-
598
- uploadLog(
599
- `uploadViaHttpTunnel: start (archive=${archivePath}, size=${archiveSize}, remotePath=${archiveRemotePath})`,
600
- );
601
-
602
- uploadLog(`uploadViaHttpTunnel: deploying file server on sandbox port ${sandboxPort}`);
603
- await deployFileServer(workspaceId, username, sandboxPort, uploadToken);
604
-
605
- uploadLog(`uploadViaHttpTunnel: creating dedicated tunnel session`);
606
- const tunnelSession = await createTunnelSession(workspaceId, username);
607
-
608
- uploadLog(`uploadViaHttpTunnel: creating tunnel channel (localPort=0, remotePort=${sandboxPort})`);
609
- const { HwlinkTunnelChannel } = await import(WS_EXEC_INDEX_URL);
610
- const tunnel = new HwlinkTunnelChannel({
611
- localPort: 0,
612
- remotePort: sandboxPort,
613
- });
614
- tunnel.attach(tunnelSession.mux);
615
-
616
- uploadLog(`uploadViaHttpTunnel: waiting for tunnel ready (timeout=${TUNNEL_READY_TIMEOUT_MS}ms)`);
617
- try {
618
- await Promise.race([
619
- tunnel.ready,
620
- new Promise((_, reject) =>
621
- setTimeout(
622
- () => reject(new Error(`tunnel ready timeout after ${TUNNEL_READY_TIMEOUT_MS}ms`)),
623
- TUNNEL_READY_TIMEOUT_MS,
624
- ),
625
- ),
626
- ]);
627
- uploadLog(`uploadViaHttpTunnel: tunnel ready, localPort=${tunnel.localPort}`);
628
- } catch (tunnelReadyError) {
629
- uploadLog(`uploadViaHttpTunnel: TUNNEL READY FAILED: ${tunnelReadyError.message}`);
630
- tunnel.close();
631
- throw new Error(
632
- `HTTP tunnel failed to establish: ${tunnelReadyError.message}. ` +
633
- `This means the WebSocket port-forwarding channel to sandbox port ${sandboxPort} could not be opened. ` +
634
- `Common causes: (1) Python file server not running on sandbox, (2) sandbox port ${sandboxPort} blocked, ` +
635
- `(3) hwlink multiplexer channel rejected. ` +
636
- `Diagnostic log: ${UPLOAD_LOG_PATH}`,
637
- { cause: tunnelReadyError },
638
- );
639
- }
640
-
641
- try {
642
- uploadLog(`uploadViaHttpTunnel: waiting for server health on localhost:${tunnel.localPort}`);
643
- await waitForServerReady(tunnel.localPort);
644
-
645
- uploadLog(`uploadViaHttpTunnel: sending POST with ${archiveSize} bytes`);
646
- const result = await uploadViaTunnel(
647
- tunnel.localPort,
648
- archivePath,
649
- archiveSize,
650
- archiveRemotePath,
651
- uploadToken,
652
- timeoutMs,
653
- );
654
- uploadLog(`uploadViaHttpTunnel: upload complete (bytes=${result.bytes}, md5=${result.md5})`);
655
- return result;
656
- } catch (uploadError) {
657
- uploadLog(`uploadViaHttpTunnel: UPLOAD FAILED: ${uploadError.message}`);
658
- throw uploadError;
659
- } finally {
660
- tunnel.close();
661
- tunnelSession.close();
662
- }
663
- }
664
-
665
- export async function uploadProjectWithSession(
666
- workspaceId,
667
- localDir,
668
- remoteDir,
669
- username = 'root',
670
- timeoutMs = 300000,
671
- options = {},
672
- ) {
673
- if (!workspaceId) {
674
- throw new Error(
675
- 'sandbox upload project: workspace_id is required. ' +
676
- 'Set HW_WORKSPACE_ID env var or ensure huaweicloud_sandbox_connect was called first.',
677
- );
678
- }
679
- const localError = classifyLocalUploadPath(localDir, 'directory');
680
- if (localError) {
681
- throw localError;
682
- }
683
-
684
- rotateUploadLog();
685
-
686
- const projectName = basename(localDir);
687
- const targetParentDir = remoteDir || '/workspace';
688
- const archiveRemotePath = `${targetParentDir}/${projectName}.tar.gz`;
689
-
690
- const archivePath = await createTarGz(localDir, options.exclude);
691
- const archiveSize = statSync(archivePath).size;
692
- const expectedMd5 = await computeMd5(archivePath);
693
-
694
- uploadLog(`uploadProject: ${localDir} -> ${archiveRemotePath} (archive=${archiveSize} bytes, md5=${expectedMd5})`);
695
-
696
- const SIZE_50MB = 50 * 1024 * 1024;
697
- if (archiveSize > SIZE_50MB) {
698
- uploadLog(
699
- `uploadProject: archive size ${(archiveSize / (1024 * 1024)).toFixed(1)}MB exceeds 50MB. ` +
700
- `Dependencies or platform binaries may have been included. ` +
701
- `Ensure exclude list contains "**/node_modules" to match all nesting levels.`,
702
- );
703
- }
704
-
705
- let result;
706
- let tunnelError;
707
- for (let attempt = 0; attempt < UPLOAD_MAX_RETRIES; attempt++) {
708
- try {
709
- await cleanupFileServer(workspaceId, username).catch(() => {});
710
- result = await uploadViaHttpTunnel(workspaceId, archivePath, archiveRemotePath, username, timeoutMs, options);
711
- tunnelError = null;
712
- break;
713
- } catch (error) {
714
- tunnelError = error;
715
- const errorType = error.code || error.name || 'unknown';
716
- uploadLog(`uploadProject: attempt ${attempt + 1}/${UPLOAD_MAX_RETRIES} failed [${errorType}]: ${error.message}`);
717
- await new Promise((r) => setTimeout(r, 5000));
718
- }
719
- }
720
- if (tunnelError) {
721
- uploadLog(`uploadProject: all ${UPLOAD_MAX_RETRIES} attempts failed: ${tunnelError.message}`);
722
- uploadLog(`uploadProject: NOT falling back to base64 (removed). Rethrowing with diagnostics.`);
723
- cleanupLocalArchive(archivePath);
724
- throw new Error(
725
- `sandbox upload failed after ${UPLOAD_MAX_RETRIES} attempts: HTTP tunnel could not transfer the project archive. ` +
726
- `Archive size: ${(archiveSize / 1024).toFixed(1)}KB. ` +
727
- `Root cause: ${tunnelError.message}. ` +
728
- `Diagnostic log: ${UPLOAD_LOG_PATH}`,
729
- { cause: tunnelError },
730
- );
731
- }
732
-
733
- if (options.verify !== false && result.md5 && result.md5 !== expectedMd5) {
734
- throw new Error(`md5 mismatch: expected ${expectedMd5}, got ${result.md5}`);
735
- }
736
-
737
- if (options.extract !== false) {
738
- await execWithSession(
739
- workspaceId,
740
- `mkdir -p "${targetParentDir}" && tar -xzf "${archiveRemotePath}" -C "${targetParentDir}" && rm -f "${archiveRemotePath}"`,
741
- username,
742
- timeoutMs,
743
- );
744
- try {
745
- await execWithSession(
746
- workspaceId,
747
- [
748
- `REAL_PATH=$(readlink -f "${targetParentDir}/${projectName}" 2>/dev/null || echo "${targetParentDir}/${projectName}")`,
749
- `if [ ! -d "$REAL_PATH" ] && [ -d "${targetParentDir}" ]; then`,
750
- ` REAL_PATH="${targetParentDir}/${projectName}"`,
751
- `fi`,
752
- `chmod -R o+rX "$REAL_PATH" 2>/dev/null || true`,
753
- `find "$REAL_PATH" -type d -exec chmod o+x {} \\; 2>/dev/null || true`,
754
- `find "$REAL_PATH" -type f -path "*/node_modules/.bin/*" -exec chmod +x {} \\; 2>/dev/null || true`,
755
- ].join('\n'),
756
- username,
757
- 15000,
758
- );
759
- } catch {}
760
- }
761
-
762
- try {
763
- await cleanupFileServer(workspaceId, username);
764
- } catch {}
765
- cleanupLocalArchive(archivePath);
766
-
767
- return {
768
- ok: true,
769
- localDir,
770
- remotePath: options.extract !== false ? `${targetParentDir}/${projectName}` : archiveRemotePath,
771
- bytes: result.bytes || 0,
772
- md5: result.md5 || expectedMd5,
773
- md5Verified: result.md5 ? result.md5 === expectedMd5 : true,
774
- extracted: options.extract !== false,
775
- };
776
- }
777
-
778
- // A1 (#935): normalize the deploy_nginx configName to a bare filename. A value
779
- // carrying path separators (e.g. `/root/hc-activity.conf`, `./x/y.conf`) used to
780
- // be spliced verbatim into `/etc/nginx/conf.d/${configName}.conf`, producing the
781
- // broken path `/etc/nginx/conf.d//root/hc-activity.conf` (nginx never serves it,
782
- // the tunnel answers 502). Only the basename is kept and the `.conf` suffix is
783
- // stripped before the path is rebuilt as `/etc/nginx/conf.d/<name>.conf`. A
784
- // pure filename (no separators) keeps the previous behavior unchanged.
785
- export function resolveNginxConfigPath(configName, project) {
786
- const raw = String(configName || project || '');
787
- const base = raw.split(/[\\/]/).filter(Boolean).pop() || '';
788
- const name = base.replace(/\.conf$/i, '') || 'default';
789
- return `/etc/nginx/conf.d/${name}.conf`;
790
- }
791
-
792
- // A1 (#935): parse the write-verification block appended to the deploy_nginx
793
- // script. The old flow returned ok:true whenever the deploy script exited 0,
794
- // even when the tee write silently failed — the config file never existed and
795
- // the tunnel answered 502. The verification block emits explicit markers:
796
- // DB_NGINX_CONFIG_MISSING=1 — the target config file does not exist
797
- // DB_NGINX_T=PASS|FAIL — nginx -t verdict, with failure output echoed
798
- // as `DB_NGINX_T_OUTPUT: ...` lines
799
- // #946 (regression, 2026-11-03 E2E): strip OSC/CSI escapes + \r BEFORE the
800
- // anchored ^DB_NGINX_ lookups — integration-enabled shells wrap every line in
801
- // \x1b]133;C\x07, which used to blind the nginxTest match and turn a PASS into
802
- // "nginx -t did not pass" (deploy_nginx ok:false false negative; the config was
803
- // written and nginx -t actually passed — measured twice on real sandboxes).
804
- export function parseDeployNginxVerifyOutput(stdout) {
805
- const text = stripTerminalEscapes(stdout);
806
- const configMissing = /DB_NGINX_CONFIG_MISSING=1/.test(text);
807
- const nginxTest = (text.match(/^DB_NGINX_T=(\w+)$/m) || [])[1] || '';
808
- const nginxTestOutput = (text.match(/^DB_NGINX_T_OUTPUT: .*$/gm) || [])
809
- .map((line) => line.replace(/^DB_NGINX_T_OUTPUT: /, ''))
810
- .join('\n');
811
- return { configMissing, nginxTest, nginxTestOutput };
812
- }
813
-
814
- // A1 (#935): the deploy verdict. A deploy script exit of 0 alone is NOT proof
815
- // of success — the tee write can fail silently (broken pipe) and nginx -t can
816
- // reject the config. Returns ok:false with an explicit, actionable error for
817
- // any verification failure; a pure function so the verdict is unit-testable.
818
- export function evaluateDeployNginxVerify(result, verify, configPath) {
819
- const exitCode = result?.exitCode;
820
- const writeVerified = exitCode === 0 && !verify.configMissing && verify.nginxTest === 'PASS';
821
- if (writeVerified) return { ok: true };
822
- const problems = [];
823
- if (exitCode !== 0) problems.push(`deploy script exited with code ${exitCode}`);
824
- if (verify.configMissing) problems.push(`nginx config file ${configPath} was not created (tee write failed)`);
825
- if (verify.nginxTest !== 'PASS')
826
- problems.push(`nginx -t did not pass${verify.nginxTestOutput ? ` — ${verify.nginxTestOutput}` : ''}`);
827
- return {
828
- ok: false,
829
- error: `sandbox deploy nginx: configuration write verification failed — ${problems.join('; ')}.`,
830
- };
831
- }
832
-
833
- export async function deployNginx(
834
- workspaceId,
835
- { nginxType, port, project, outputDir, nodePort, publicPort, configName },
836
- username = 'root',
837
- timeoutMs = 60000,
838
- ) {
839
- if (!workspaceId) {
840
- throw new Error('sandbox deploy nginx: workspace_id is required.');
841
- }
842
- if (!nginxType || !port || !project || !outputDir) {
843
- throw new Error('sandbox deploy nginx: nginxType, port, project, and outputDir are required.');
844
- }
845
-
846
- const nginxCheck = await execOneShot(
847
- workspaceId,
848
- 'command -v nginx >/dev/null 2>&1 && echo "INSTALLED" || echo "MISSING"',
849
- username,
850
- 10000,
851
- );
852
- if (!String(nginxCheck.stdout || '').includes('INSTALLED')) {
853
- throw new Error(
854
- 'sandbox deploy nginx: nginx is not installed. Install it first:\n' +
855
- ' Detect OS: source /etc/os-release && echo $ID\n' +
856
- ' apt: sudo apt-get update -qq && sudo apt-get install -y -qq nginx\n' +
857
- ' yum: sudo yum install -y nginx\n' +
858
- ' dnf: sudo dnf install -y nginx\n' +
859
- 'Alternatively, skip nginx and use Python HTTP server (see nginx-templates.md).',
860
- );
861
- }
862
-
863
- const listenPort = publicPort || port;
864
- const basePort = nginxType === 'proxy' ? listenPort : port;
865
-
866
- let targetPort = basePort;
867
- const maxPortAttempts = 10;
868
- for (let offset = 0; offset < maxPortAttempts; offset += 1) {
869
- targetPort = basePort + offset;
870
- try {
871
- const portCheck = await execOneShot(
872
- workspaceId,
873
- `ss -tlnp 2>/dev/null | grep -q ":${targetPort} " && echo "IN_USE" || echo "FREE"`,
874
- username,
875
- 10000,
876
- );
877
- if (!String(portCheck.stdout || '').includes('IN_USE')) break;
878
- } catch {}
879
- if (offset === maxPortAttempts - 1) {
880
- throw new Error(
881
- `sandbox deploy nginx: all ports ${basePort}-${basePort + maxPortAttempts - 1} are in use. Free a port and try again.`,
882
- );
883
- }
884
- }
885
-
886
- const effectiveNodePort =
887
- nginxType === 'proxy'
888
- ? await resolveProxyNodePort(nodePort, targetPort, async (candidate) => {
889
- const portCheck = await execOneShot(
890
- workspaceId,
891
- `ss -tlnp 2>/dev/null | grep -q ":${candidate} " && echo "IN_USE" || echo "FREE"`,
892
- username,
893
- 10000,
894
- );
895
- return String(portCheck.stdout || '').includes('IN_USE');
896
- })
897
- : undefined;
898
-
899
- const projectPath = `/workspace/${project}`;
900
- const outputPath = outputDir.startsWith('/') ? outputDir : `${projectPath}/${outputDir}`;
901
-
902
- const resolveScript = `REAL_PROJECT=$(readlink -f "${projectPath}" 2>/dev/null || echo "${projectPath}")
903
- REAL_OUTPUT="${outputPath}"
904
- if [ "\${REAL_PROJECT}" != "${projectPath}" ]; then
905
- REL_OUTPUT=$(echo "${outputDir}" | sed "s|${projectPath}/||")
906
- REAL_OUTPUT="\${REAL_PROJECT}/\${REL_OUTPUT}"
907
- fi`;
908
-
909
- const templates = {
910
- spa: `server {
911
- listen ${targetPort};
912
- root ${outputPath};
913
- index index.html;
914
-
915
- location / {
916
- try_files $uri /index.html;
917
- }
918
-
919
- location ~* \\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
920
- expires 1h;
921
- add_header Cache-Control "public, immutable";
922
- }
923
- }`,
924
- proxy: `server {
925
- listen ${targetPort};
926
- server_name _;
927
- large_client_header_buffers 4 32k;
928
-
929
- location / {
930
- proxy_pass http://127.0.0.1:${effectiveNodePort};
931
- proxy_http_version 1.1;
932
- proxy_set_header Upgrade $http_upgrade;
933
- proxy_set_header Connection 'upgrade';
934
- proxy_set_header Host $host;
935
- proxy_set_header X-Real-IP $remote_addr;
936
- proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
937
- proxy_set_header X-Forwarded-Proto $scheme;
938
- proxy_cache_bypass $http_upgrade;
939
- proxy_read_timeout 60s;
940
- proxy_buffer_size 128k;
941
- proxy_buffers 4 256k;
942
- proxy_busy_buffers_size 256k;
943
- }
944
- }`,
945
- static: `server {
946
- listen ${targetPort};
947
- root ${outputPath};
948
- index index.html;
949
-
950
- location / {
951
- try_files $uri $uri.html $uri/ =404;
952
- autoindex off;
953
- }
954
-
955
- location ~* \\.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
956
- expires 1h;
957
- add_header Cache-Control "public, immutable";
958
- }
959
- }`,
960
- };
961
-
962
- const config = templates[nginxType];
963
- if (!config) {
964
- throw new Error(`sandbox deploy nginx: unknown nginxType "${nginxType}". Must be one of: spa, proxy, static`);
965
- }
966
-
967
- // A1 (#935): configName is normalized to a bare filename so a path-shaped
968
- // value can never produce `/etc/nginx/conf.d//root/xxx.conf` again.
969
- const configPath = resolveNginxConfigPath(configName, project);
970
-
971
- const cmd = [
972
- resolveScript,
973
- `sudo mkdir -p /etc/nginx/conf.d`,
974
- `sudo tee ${configPath} > /dev/null << 'NGINX_EOF'`,
975
- config,
976
- `NGINX_EOF`,
977
- `# Resolve symlinks for chmod (chmod does not follow symlinks on Linux)`,
978
- `chmod -R o+rX "$REAL_PROJECT" 2>/dev/null || true`,
979
- `find "$REAL_PROJECT" -type d -exec chmod o+x {} \\; 2>/dev/null || true`,
980
- `find "$REAL_PROJECT" -type f -path "*/node_modules/.bin/*" -exec chmod +x {} \\; 2>/dev/null || true`,
981
- `if pgrep -x nginx > /dev/null 2>&1; then sudo killall -9 nginx 2>/dev/null; sleep 1; fi
982
- sudo nginx`,
983
- `# A1 (#935): verify the config write took effect before reporting success`,
984
- `NGINX_CONFIG_PATH=${configPath}`,
985
- `if [ ! -f "$NGINX_CONFIG_PATH" ]; then echo "DB_NGINX_CONFIG_MISSING=1"; fi`,
986
- `NGINX_T_OUTPUT=$(sudo nginx -t 2>&1 || true)`,
987
- `if echo "$NGINX_T_OUTPUT" | grep -Eq "syntax is ok|test is successful"; then echo "DB_NGINX_T=PASS"; else echo "DB_NGINX_T=FAIL"; echo "$NGINX_T_OUTPUT" | sed "s/^/DB_NGINX_T_OUTPUT: /"; fi`,
988
- ].join('\n');
989
-
990
- const result = await execOneShot(workspaceId, cmd, username, timeoutMs);
991
-
992
- let tunnelActive = false;
993
- try {
994
- // Version-aware: devbridge 0.1.x exposes JSON via `list -j`; 0.2.x removed -j and
995
- // prints a table whose data rows start with the 8-char base32 tunnel ID.
996
- const tunnelCheck = await execOneShot(
997
- workspaceId,
998
- '(devbridge list -j 2>/dev/null | grep -q \'"tunnelId"\' || devbridge list 2>/dev/null | grep -Eq \'^[a-z2-7]{8}[[:space:]]\') && echo "ACTIVE" || echo "INACTIVE"',
999
- username,
1000
- 10000,
1001
- );
1002
- tunnelActive = String(tunnelCheck.stdout || '').includes('ACTIVE');
1003
- } catch {}
1004
-
1005
- const warnings = [];
1006
- if (!tunnelActive) {
1007
- warnings.push('No active DevBridge tunnel — deployment is incomplete. Proceed to Step 7 to expose the app.');
1008
- }
1009
- const conflictWarning = formatPortConflictWarning(basePort, targetPort);
1010
- if (conflictWarning) warnings.push(conflictWarning);
1011
- const driftWarning = tunnelActive ? formatPortDriftWarning(basePort, targetPort) : undefined;
1012
- if (driftWarning) warnings.push(driftWarning);
1013
-
1014
- // A1 (#935): verify the config write before reporting success. Any
1015
- // verification failure returns ok:false with an explicit, actionable error.
1016
- const verify = parseDeployNginxVerifyOutput(result.stdout);
1017
- const verdict = evaluateDeployNginxVerify(result, verify, configPath);
1018
- if (!verdict.ok) {
1019
- return {
1020
- ok: false,
1021
- error: verdict.error,
1022
- nginxType,
1023
- port: targetPort,
1024
- nodePort: effectiveNodePort || undefined,
1025
- outputPath,
1026
- projectPath,
1027
- configPath,
1028
- exitCode: result.exitCode,
1029
- stdout: result.stdout,
1030
- nextStep: 'fix_and_retry',
1031
- warning: warnings.length > 0 ? warnings.join(' | ') : undefined,
1032
- };
1033
- }
1034
-
1035
- return {
1036
- ok: true,
1037
- nginxType,
1038
- port: targetPort,
1039
- nodePort: effectiveNodePort || undefined,
1040
- outputPath,
1041
- projectPath,
1042
- configPath,
1043
- verification: { configPath, nginxTest: verify.nginxTest },
1044
- exitCode: result.exitCode,
1045
- stdout: result.stdout,
1046
- nextStep: 'expose_via_devbridge',
1047
- warning: warnings.length > 0 ? warnings.join(' | ') : undefined,
1048
- };
1049
- }
1050
-
1051
- export async function deployCheck(
1052
- workspaceId,
1053
- { port, project, outputDir, frameworkType },
1054
- username = 'root',
1055
- timeoutMs = 30000,
1056
- ) {
1057
- if (!workspaceId) {
1058
- throw new Error('sandbox deploy check: workspace_id is required.');
1059
- }
1060
-
1061
- const projectPath = `/workspace/${project}`;
1062
- const outputPath = outputDir.startsWith('/') ? outputDir : `${projectPath}/${outputDir}`;
1063
- const isCrossPlatform = frameworkType === 'cross-platform';
1064
-
1065
- const checkScript = buildDeployCheckScript({ port, project, outputPath, isCrossPlatform });
1066
- const result = await execOneShot(workspaceId, checkScript, username, timeoutMs);
1067
- const stdout = String(result.stdout || '');
1068
- return parseDeployCheckOutput(stdout, { port, isCrossPlatform });
1069
- }
1070
-
1071
- export function buildDeployCheckScript({ port, project, outputPath, isCrossPlatform: _isCrossPlatform }) {
1072
- return [
1073
- `echo "=== DEPLOY CHECK ==="`,
1074
- `PASS=0`,
1075
- `TOTAL=0`,
1076
- ``,
1077
- `TOTAL=$((TOTAL+1))`,
1078
- `HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:${port} 2>/dev/null)`,
1079
- `if [ -n "$HTTP_CODE" ] && [ "$HTTP_CODE" != "000" ]; then`,
1080
- ` echo "nginx_serving:PASS (port ${port}, HTTP \${HTTP_CODE})"`,
1081
- ` PASS=$((PASS+1))`,
1082
- `else`,
1083
- ` echo "nginx_serving:FAIL (port ${port}, no HTTP response)"`,
1084
- `fi`,
1085
- ``,
1086
- `TOTAL=$((TOTAL+1))`,
1087
- `if [ -d "${outputPath}" ] && ls -A "${outputPath}" 2>/dev/null | grep -q .; then`,
1088
- ` echo "output_dir:PASS (${outputPath})"`,
1089
- ` PASS=$((PASS+1))`,
1090
- `else`,
1091
- ` echo "output_dir:FAIL (${outputPath} empty or missing)"`,
1092
- `fi`,
1093
- ``,
1094
- `TOTAL=$((TOTAL+1))`,
1095
- `FINGERPRINT_FILE="${outputPath}/.deploy_fingerprint"`,
1096
- `FINGERPRINT_EXPECTED=$(cat "$FINGERPRINT_FILE" 2>/dev/null)`,
1097
- `if [ -n "$FINGERPRINT_EXPECTED" ]; then`,
1098
- ` FINGERPRINT_ACTUAL=$(curl -s http://localhost:${port}/.deploy_fingerprint 2>/dev/null)`,
1099
- ` if [ "$FINGERPRINT_EXPECTED" = "$FINGERPRINT_ACTUAL" ]; then`,
1100
- ` echo "content_verified:PASS"`,
1101
- ` PASS=$((PASS+1))`,
1102
- ` else`,
1103
- ` echo "content_verified:FAIL (fingerprint mismatch — nginx may be serving stale content from a previous deployment)"`,
1104
- ` fi`,
1105
- `else`,
1106
- ` echo "content_verified:SKIP (no fingerprint file)"`,
1107
- ` TOTAL=$((TOTAL-1))`,
1108
- `fi`,
1109
- ``,
1110
- `TOTAL=$((TOTAL+1))`,
1111
- `DB_TUNNEL_ACTIVE=0`,
1112
- `if devbridge list -j 2>/dev/null | grep -q '"tunnelId"'; then`,
1113
- ` DB_TUNNEL_ACTIVE=1`,
1114
- `elif devbridge list 2>/dev/null | grep -Eq '^[a-z2-7]{8}[[:space:]]'; then`,
1115
- ` DB_TUNNEL_ACTIVE=1`,
1116
- `fi`,
1117
- `if [ "$DB_TUNNEL_ACTIVE" = "1" ]; then`,
1118
- ` echo "devbridge_tunnel:PASS"`,
1119
- ` PASS=$((PASS+1))`,
1120
- `else`,
1121
- ` echo "devbridge_tunnel:FAIL"`,
1122
- `fi`,
1123
- ``,
1124
- `TOTAL=$((TOTAL+1))`,
1125
- `TUNNEL_IDS=$(devbridge list -j 2>/dev/null | grep -oP '"tunnelId":\\s*"\\K[^"]+' | head -5)`,
1126
- `if [ -z "$TUNNEL_IDS" ]; then`,
1127
- ` TUNNEL_IDS=$(devbridge list 2>/dev/null | grep -E '^[a-z2-7]{8}[[:space:]]' | awk '{print $1}' | head -5)`,
1128
- `fi`,
1129
- `# Gateway-level tunnel errors have exact text/plain bodies (verified on the s2`,
1130
- `# gateway): 404 "tunnel not found" = no live host session (the tunnel RECORD may`,
1131
- `# still be in \`list\`); 404 "port not configured" = URL port not registered; 502`,
1132
- `# "bad gateway" = tunnel alive, local service down. grep -x (exact-line match) +`,
1133
- `# status gating avoids flagging app-generated 404/502 pages.`,
1134
- `probe_tunnel() {`,
1135
- ` local url="$1" code`,
1136
- ` code=$(curl -s -o /tmp/.dc_tunnel_body -w "%{http_code}" --max-time 5 "$url" 2>/dev/null)`,
1137
- ` PROBE_FAIL_REASON=""`,
1138
- ` if [ "$code" = "000" ]; then PROBE_FAIL_REASON="unreachable"; rm -f /tmp/.dc_tunnel_body; return 1; fi`,
1139
- ` if grep -q "${DEVBRIDGE_MIGRATION_MARKER}" /tmp/.dc_tunnel_body 2>/dev/null; then PROBE_FAIL_REASON="migration placeholder page"; rm -f /tmp/.dc_tunnel_body; return 1; fi`,
1140
- ` if [ "$code" = "404" ] && grep -qx "${DEVBRIDGE_TUNNEL_NOT_FOUND_MARKER}" /tmp/.dc_tunnel_body 2>/dev/null; then PROBE_FAIL_REASON="tunnel not found (no live host session on the gateway)"; rm -f /tmp/.dc_tunnel_body; return 1; fi`,
1141
- ` if [ "$code" = "404" ] && grep -qx "${DEVBRIDGE_PORT_NOT_CONFIGURED_MARKER}" /tmp/.dc_tunnel_body 2>/dev/null; then PROBE_FAIL_REASON="port not configured (URL port not registered on the tunnel)"; rm -f /tmp/.dc_tunnel_body; return 1; fi`,
1142
- ` if [ "$code" = "502" ] && grep -qx "${DEVBRIDGE_BAD_GATEWAY_MARKER}" /tmp/.dc_tunnel_body 2>/dev/null; then PROBE_FAIL_REASON="bad gateway (tunnel alive, local service not serving)"; rm -f /tmp/.dc_tunnel_body; return 1; fi`,
1143
- ` rm -f /tmp/.dc_tunnel_body`,
1144
- ` return 0`,
1145
- `}`,
1146
- `# Probe each listed tunnel (bounded to 5) and select the first one that actually`,
1147
- `# serves this port — \`devbridge list\` order is arbitrary, so a stale tunnel listed`,
1148
- `# first must not shadow the live one.`,
1149
- `SELECTED_URL=""`,
1150
- `FIRST_ID=""`,
1151
- `for CAND in $TUNNEL_IDS; do`,
1152
- ` if [ -z "$FIRST_ID" ]; then FIRST_ID="$CAND"; fi`,
1153
- ` CAND_URL="https://\${CAND}-${port}.${DEVBRIDGE_TUNNEL_DOMAIN}"`,
1154
- ` if probe_tunnel "$CAND_URL"; then`,
1155
- ` SELECTED_URL="$CAND_URL"`,
1156
- ` break`,
1157
- ` fi`,
1158
- `done`,
1159
- `TUNNEL_URL="$SELECTED_URL"`,
1160
- `if [ -n "$SELECTED_URL" ]; then`,
1161
- ` echo "tunnel_url_accessible:PASS ($SELECTED_URL)"`,
1162
- ` PASS=$((PASS+1))`,
1163
- `elif [ -n "$FIRST_ID" ]; then`,
1164
- ` echo "tunnel_url_accessible:FAIL (https://\${FIRST_ID}-${port}.${DEVBRIDGE_TUNNEL_DOMAIN} -> $PROBE_FAIL_REASON)"`,
1165
- `else`,
1166
- ` echo "tunnel_url_accessible:FAIL (no tunnel)"`,
1167
- `fi`,
1168
- ``,
1169
- `${`
1170
- TOTAL=$((TOTAL+1))
1171
- if [ -f "${outputPath}/qr.png" ]; then
1172
- echo "qr_code:PASS"
1173
- PASS=$((PASS+1))
1174
- else
1175
- # Auto-detect cross-platform from project files (more reliable than frameworkType param)
1176
- PROJ_DIR="/workspace/${project}"
1177
- IS_CROSS=0
1178
- if [ -f "$PROJ_DIR/manifest.json" ] || grep -qE '"@tarojs/taro"|"@dcloudio/uni-app"' "$PROJ_DIR/package.json" 2>/dev/null; then
1179
- IS_CROSS=1
1180
- fi
1181
- if [ $IS_CROSS -eq 0 ] && ( [ -f "$PROJ_DIR/app.config.ts" ] || [ -f "$PROJ_DIR/app.config.js" ] ) && grep -qE "pages|tabBar" "$PROJ_DIR/app.config."* 2>/dev/null; then
1182
- IS_CROSS=1
1183
- fi
1184
-
1185
- if [ $IS_CROSS -eq 1 ]; then
1186
- if [ -n "$TUNNEL_URL" ]; then
1187
- curl -s "https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=$(python3 -c "import urllib.parse, sys; print(urllib.parse.quote(sys.argv[1]))" "$TUNNEL_URL" 2>/dev/null)" -o "${outputPath}/qr.png" 2>/dev/null
1188
- chmod o+r "${outputPath}/qr.png" 2>/dev/null || true
1189
- if [ -f "${outputPath}/qr.png" ] && [ -s "${outputPath}/qr.png" ]; then
1190
- echo "qr_code:PASS (auto-generated)"
1191
- PASS=$((PASS+1))
1192
- else
1193
- echo "qr_code:FAIL (QR generation failed)"
1194
- fi
1195
- else
1196
- echo "qr_code:FAIL (no tunnel URL for QR generation)"
1197
- fi
1198
- else
1199
- echo "qr_code:SKIP (not a cross-platform project)"
1200
- TOTAL=$((TOTAL-1))
1201
- fi
1202
- fi
1203
- `}`,
1204
- `echo "SCORE:\${PASS}/\${TOTAL}"`,
1205
- `echo "TUNNEL_URL:\${TUNNEL_URL:-}"`,
1206
- `[ "\${PASS}" = "\${TOTAL}" ] && echo "VERDICT:COMPLETE" || echo "VERDICT:INCOMPLETE"`,
1207
- ]
1208
- .filter(Boolean)
1209
- .join('\n');
1210
- }
1211
-
1212
- // Strip terminal escape sequences from sandbox command output (#946): CSI
1213
- // color/cursor codes and OSC shell-integration markers (shells with integration
1214
- // enabled wrap EVERY line in \x1b]133;C\x07, which blinds anchored ^DB_...=
1215
- // parsers), then normalize \r\n / \r line endings to \n.
1216
- // Use new RegExp to avoid ESLint no-control-regex on literal control chars.
1217
- export function stripTerminalEscapes(text) {
1218
- const ESC = '\x1b';
1219
- const csiRe = new RegExp(ESC + '\\[[0-9;]*[a-zA-Z]', 'g');
1220
- const oscRe = new RegExp(ESC + '\\][^' + ESC + '\x07]*(?:\x07|' + ESC + '\\\\)', 'g');
1221
- return String(text || '')
1222
- .replace(csiRe, '')
1223
- .replace(oscRe, '')
1224
- .replace(/\r\n|\r/g, '\n');
1225
- }
1226
-
1227
- export function parseDeployCheckOutput(stdout, { port, isCrossPlatform } = {}) {
1228
- // Strip ANSI escape sequences (CSI color/cursor codes and OSC shell-integration markers)
1229
- // and split on any line-ending style (\r\n, \r, or \n) to handle all terminal outputs.
1230
- const cleanStdout = stripTerminalEscapes(stdout);
1231
- const checks = {};
1232
- const lines = cleanStdout.split('\n');
1233
- for (const line of lines) {
1234
- const trimmed = line.trim();
1235
- const m = trimmed.match(/^(\w+):(PASS|FAIL|SKIP)\b(.*)/);
1236
- if (m) checks[m[1]] = { status: m[2], detail: (m[3] || '').trim() };
1237
- }
1238
- const scoreMatch = cleanStdout.match(/SCORE:(\d+)\/(\d+)/);
1239
- const tunnelMatch = cleanStdout.match(TUNNEL_URL_PATTERN);
1240
- const complete = /VERDICT:COMPLETE/.test(cleanStdout);
1241
-
1242
- const missing = [];
1243
- if (!complete) {
1244
- for (const [key, val] of Object.entries(checks)) {
1245
- if (val.status === 'FAIL') missing.push(key);
1246
- }
1247
- }
1248
-
1249
- // If checks is empty but score was found, parsing failed — return raw output for debugging
1250
- const parseWarning =
1251
- Object.keys(checks).length === 0 && scoreMatch
1252
- ? 'Check output parsing failed — individual check results could not be extracted. See rawOutput for details.'
1253
- : undefined;
1254
-
1255
- const nextStepValue = !complete
1256
- ? missing.includes('devbridge_tunnel') || missing.includes('tunnel_url_accessible')
1257
- ? 'expose_via_devbridge'
1258
- : missing.includes('nginx_serving')
1259
- ? 'configure_nginx'
1260
- : missing.includes('qr_code')
1261
- ? 'generate_qr_code'
1262
- : parseWarning
1263
- ? 'review_raw_output'
1264
- : 'review_checks'
1265
- : 'complete';
1266
-
1267
- return {
1268
- ok: true,
1269
- complete,
1270
- checkType: isCrossPlatform ? 'cross-platform' : 'standard',
1271
- checks,
1272
- score: scoreMatch ? { pass: parseInt(scoreMatch[1], 10), total: parseInt(scoreMatch[2], 10) } : null,
1273
- publicUrl: tunnelMatch ? tunnelMatch[1] : undefined,
1274
- missingSteps: missing.length > 0 ? missing.join(', ') : undefined,
1275
- parseWarning,
1276
- rawOutput: parseWarning ? String(stdout || '').trim() : undefined,
1277
- nextStep: nextStepValue,
1278
- remediation: nextStepValue === 'expose_via_devbridge' ? buildExposeRemediation(port) : undefined,
1279
- };
1280
- }
1281
-
1282
- export async function closeSession(workspaceId, username) {
1283
- const key = `${workspaceId}:${username}`;
1284
- const session = sessions.get(key);
1285
- if (!session) return false;
1286
- sessions.delete(key);
1287
- try {
1288
- session.close();
1289
- } catch {}
1290
- trackSandboxDisconnect();
1291
- return true;
1292
- }
1293
-
1294
- // Build a shell snippet that authenticates devbridge via a verified waterfall:
1295
- // Tier 1 keyring API Key — hwcloud keyring get HW_DEVBRIDGE_API_KEY (platform-injected
1296
- // on hd-space-ai-shell images, or self-injected by devbridge-key.mjs; the value
1297
- // goes to STDERR so 2>&1 is mandatory and the devbridge_ prefix filters
1298
- // "(not found)" / error text). A light revive step (restart the D-Bus session
1299
- // bus + re-unlock the keyring daemon, no dnf) retries once when the first read fails.
1300
- // Tier 2 /tmp/hw_api_key — file channel: written by huaweicloud_sandbox_credentials
1301
- // from HW_API_KEY / the api_key param (user-provided), or by the auto-create
1302
- // fallback (devbridge-key.mjs) when keyring injection is unavailable.
1303
- // AK/SK login (--access-key/--secret-key) was REMOVED: devbridge authentication is
1304
- // now fixed to API Key only (定稿决策,2026-11-04).
1305
- // Every tier performs a real `devbridge auth login --api-key` (exit code checked),
1306
- // then verifies with `auth status` AND a real authenticated API call (`devbridge list`);
1307
- // on failure the waterfall falls through. The list check is required because a stale
1308
- // key can leave a "Logged in" local token while server-side calls return 40100.
1309
- // DB_ATTEMPT_* lines are non-sensitive diagnostics for support escalation.
1310
- // The HOST orchestrates an auto-create fallback between probe rounds: when the
1311
- // first probe returns NO_CREDENTIAL, the host calls ensureDevbridgeKey() and
1312
- // injects the key (keyring preferred, file fallback), then runs a second probe.
1313
- export function buildDevbridgeAuthProbe() {
1314
- return [
1315
- // #999: /workspace/.local/bin FIRST — /workspace is the data disk and
1316
- // survives sandbox reboots; ~/.huawei/bin lives on the system disk and is
1317
- // wiped back to the image state on reboot. Prepended so a stale image
1318
- // binary in /usr/local/bin never wins.
1319
- `export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"`,
1320
- `export HOME="\${HOME:-/root}"`,
1321
- // #998: probe the version in the SAME exec as the auth waterfall (no extra
1322
- // round trip). 0.1.x binaries' AK/SK tier still logs in, so the auth probe
1323
- // alone would green-light an expose that can never work — the version is
1324
- // what names the real cause.
1325
- `DB_VERSION=$(devbridge version 2>/dev/null | head -1)`,
1326
- `echo "DB_VERSION=\${DB_VERSION}"`,
1327
- `DB_OK=0`,
1328
- `db_login_ok() {`,
1329
- // 本地 token 可能仍显示 Logged in,但 API key 已在服务端失效(实测 list/renew 返回 40100)。
1330
- // 因此额外做一次真实鉴权 API 调用,确保探针结果可用(否则 auto-create 自愈不会触发)。
1331
- ` devbridge auth status 2>/dev/null | grep -q "Logged in" || return 1`,
1332
- ` devbridge list >/dev/null 2>&1`,
1333
- `}`,
1334
- `db_diag() { echo "DB_ATTEMPT_$1=$2"; }`,
1335
- ``,
1336
- `# ---- Tier 1: API Key from the sandbox keyring (platform auto-injection) ----`,
1337
- `HW_DB_KEY=""`,
1338
- `if command -v hwcloud >/dev/null 2>&1; then`,
1339
- ` export DBUS_SESSION_BUS_ADDRESS="\${DBUS_SESSION_BUS_ADDRESS:-unix:path=/run/dbus-session}"`,
1340
- ` HW_DB_KEY=$(hwcloud keyring get HW_DEVBRIDGE_API_KEY 2>&1 || true)`,
1341
- ` case "$HW_DB_KEY" in`,
1342
- ` "devbridge_"*) : ;;`,
1343
- ` *)`,
1344
- ` # Light revive: bus down or a locked/absent keyring daemon — restart both, retry once.`,
1345
- ` if ! pgrep -x dbus-daemon >/dev/null 2>&1 && command -v dbus-daemon >/dev/null 2>&1; then`,
1346
- ` dbus-daemon --session --address="$DBUS_SESSION_BUS_ADDRESS" --fork --nopidfile >/dev/null 2>&1 || true`,
1347
- ` sleep 1`,
1348
- ` fi`,
1349
- ` if command -v gnome-keyring-daemon >/dev/null 2>&1; then`,
1350
- ` pkill -f gnome-keyring-daemon 2>/dev/null || true`,
1351
- ` sleep 1`,
1352
- ` printf '\\n' | gnome-keyring-daemon --unlock >/dev/null 2>&1 || true`,
1353
- ` sleep 1`,
1354
- ` HW_DB_KEY=$(hwcloud keyring get HW_DEVBRIDGE_API_KEY 2>&1 || true)`,
1355
- ` fi`,
1356
- ` case "$HW_DB_KEY" in "devbridge_"*) : ;; *) HW_DB_KEY="";; esac`,
1357
- ` ;;`,
1358
- ` esac`,
1359
- `else`,
1360
- ` db_diag KEYRING "hwcloud-not-installed"`,
1361
- `fi`,
1362
- `if [ -n "$HW_DB_KEY" ]; then`,
1363
- ` if devbridge auth login --api-key "$HW_DB_KEY" >/tmp/db_auth.log 2>&1 && db_login_ok; then`,
1364
- ` echo "DB_AUTH_MODE=API_KEY_KEYRING"`,
1365
- ` DB_OK=1`,
1366
- ` else`,
1367
- ` db_diag KEYRING "login-failed"`,
1368
- ` fi`,
1369
- `else`,
1370
- ` db_diag KEYRING "no-valid-key"`,
1371
- `fi`,
1372
- ``,
1373
- `# ---- Tier 2: API Key from /tmp/hw_api_key (file channel; auto-injected or user-provided) ----`,
1374
- `if [ "$DB_OK" -eq 0 ]; then`,
1375
- ` source /tmp/hw_api_key 2>/dev/null`,
1376
- ` if [ -n "$HW_API_KEY" ]; then`,
1377
- ` if devbridge auth login --api-key "$HW_API_KEY" >/tmp/db_auth.log 2>&1 && db_login_ok; then`,
1378
- ` echo "DB_AUTH_MODE=API_KEY_FILE"`,
1379
- ` DB_OK=1`,
1380
- ` else`,
1381
- ` db_diag APIKEY_FILE "login-failed"`,
1382
- ` fi`,
1383
- ` else`,
1384
- ` db_diag APIKEY_FILE "no-file"`,
1385
- ` fi`,
1386
- `fi`,
1387
- ``,
1388
- `if [ "$DB_OK" -eq 0 ]; then`,
1389
- ` echo "DB_AUTH_MODE=NO_CREDENTIAL"`,
1390
- `fi`,
1391
- `unset HW_DB_KEY HW_API_KEY DB_TOKEN_ARGS 2>/dev/null`,
1392
- `devbridge auth status > /tmp/db_status.log 2>&1 || true`,
1393
- ].join('\n');
1394
- }
1395
-
1396
- // Parse the raw stdout of buildDevbridgeAuthProbe into { authMode, attempts, version }.
1397
- // authMode is the LAST DB_AUTH_MODE line; attempts collects the non-sensitive
1398
- // DB_ATTEMPT_* diagnostics emitted by tiers that failed and fell through;
1399
- // version is the devbridge binary version probed in the same exec (#998).
1400
- export function parseDevbridgeAuthOutput(stdout) {
1401
- // #946: OSC 133 markers precede every line on integration-enabled shells; the
1402
- // anchored ^DB_ATTEMPT_ regexes are blind to them without stripping first.
1403
- const text = stripTerminalEscapes(stdout);
1404
- const modes = text.match(/DB_AUTH_MODE=([A-Z_]+)/g) || [];
1405
- const authMode = modes.length > 0 ? modes[modes.length - 1].split('=')[1] : '';
1406
- const attempts = {};
1407
- for (const m of text.matchAll(/^DB_ATTEMPT_([A-Z_]+)=(\S+)$/gm)) {
1408
- attempts[m[1]] = m[2];
1409
- }
1410
- const versionMatch = text.match(/^DB_VERSION=(.*)$/m);
1411
- const version = versionMatch ? versionMatch[1].trim() : '';
1412
- return { authMode, attempts, version };
1413
- }
1414
-
1415
- // #998: 0.1.x binaries cannot serve tunnels — their hardcoded pre-migration
1416
- // gateway was retired (Sep 2026) and now serves a「服务已迁移」placeholder,
1417
- // while their AK/SK auth tier still logs in successfully. Without a version check the auth green-light leads to an
1418
- // expose that fails after retries with no version context, sending the caller
1419
- // chasing credentials/network/port instead of the real cause. Block 0.1.x
1420
- // BEFORE exposing and point at the Step 0 install path. An empty version
1421
- // (binary absent) does not block — the auth waterfall handles that case.
1422
- export function evaluateDevbridgeVersion(version) {
1423
- const v = String(version || '').trim();
1424
- if (!v) return { blocked: false };
1425
- if (/^0\.1($|[.-])/.test(v)) {
1426
- return {
1427
- blocked: true,
1428
- error:
1429
- `devbridge_too_old: ${v} cannot serve tunnels — its hardcoded gateway was migrated and now serves a 「服务已迁移」 placeholder. ` +
1430
- 'An upgrade to 0.2.x is required before exposing; no credential change will fix this.',
1431
- remediation:
1432
- 'Upgrade in place per the huawei-sandbox skill Step 0: install 0.2.x via the GitCode mirror with GitHub fallback ' +
1433
- '(`install.sh -s -u <gitcode URL> -v <target>`, `-s` is required in the sandbox), then re-run huaweicloud_sandbox_expose_tunnel. ' +
1434
- 'Install to /workspace/.local/bin (survives sandbox reboots) — never ~/.huawei/bin (wiped on system-disk reset). ' +
1435
- 'Old 0.1.x tunnels do not survive the upgrade: the expose flow pre-cleans them.',
1436
- };
1437
- }
1438
- return { blocked: false };
1439
- }
1440
-
1441
- // Tunnel lifetime for expose-created hosts, in hours. The report that motivated
1442
- // #919 uses -e 72 so the shared link survives long after the deploying session
1443
- // ends; the value is surfaced to callers via exposeTunnel's expiresAt field.
1444
- export const DEVBRIDGE_HOST_EXPIRY_HOURS = 72;
1445
-
1446
- // Start (or replace) a devbridge host bound to a single port, extract the public
1447
- // URL, and health-check it. Mirrors the huaweicloud-sandbox skill's Expose flow:
1448
- // pre-clean stale tunnels (quota 10006), start host in background, read
1449
- // "Tunnel URL: ..." from /tmp/host.log, curl-check, retry once on unreachable.
1450
- // The host MUST survive the exec session that started it (#919): setsid detaches
1451
- // it from the session's process group, `< /dev/null` drops the controlling tty
1452
- // stdin, and `disown` removes it from the shell's job table — without all three
1453
- // the host is reaped when the one-shot session ends and the tunnel dies
1454
- // immediately after a green in-session health check (the "假成功" bug).
1455
- export function buildDevbridgeExposeScript(port, expiryHours = DEVBRIDGE_HOST_EXPIRY_HOURS) {
1456
- const hostLog = '/tmp/host.log';
1457
- return [
1458
- // Pre-clean is now selective (cleanupDevbridgeTunnels) and runs before this
1459
- // script, so other ports/sessions are preserved.
1460
- // #922 (S8): setsid is unavailable on some sandbox images — fall back to a
1461
- // bare nohup launch so the host still starts; persistence is then judged by
1462
- // the independent re-verify below, which emits the 请勿分享 warning in the
1463
- // non-persistent case. disown is guarded: shells without the builtin must
1464
- // not abort the script.
1465
- `if command -v setsid > /dev/null 2>&1; then setsid nohup devbridge host -p ${port} -e ${expiryHours} > ${hostLog} 2>&1 < /dev/null & else nohup devbridge host -p ${port} -e ${expiryHours} > ${hostLog} 2>&1 < /dev/null & fi`,
1466
- `disown 2>/dev/null || true`,
1467
- `sleep 6`,
1468
- // Port-anchored extraction (#943): a multi-port host prints one "Tunnel URL:" line per
1469
- // port, so a port-blind `sed | tail -1` can pick another port's URL.
1470
- `TUNNEL_URL=$(grep -oE "https://[A-Za-z0-9_-]+-${port}\\.devbridge-s2\\.hwtunnel\\.com" ${hostLog} | head -1)`,
1471
- // A2 (#935): probe with retries + backoff — 502/000 before the gateway is
1472
- // ready is not a failure; the LAST probe decides reachability. The body is
1473
- // captured every probe so DB_TUNNEL_BODY reflects the final one (#943).
1474
- `HTTP_CODE="000"`,
1475
- `if [ -n "$TUNNEL_URL" ]; then`,
1476
- ` for i in 1 2 3 4; do`,
1477
- // #1000: --noproxy — the sandbox injects an HTTP proxy that does NOT route
1478
- // the tunnel domain; without it the probe returns 502/404 fakes and a
1479
- // working tunnel is judged dead.
1480
- ` HTTP_CODE=$(curl -s --noproxy '*' -o /tmp/.db_probe_body -w "%{http_code}" --max-time 10 "$TUNNEL_URL" 2>/dev/null || echo "000")`,
1481
- ` echo "DB_PROBE_$i=$HTTP_CODE"`,
1482
- ` if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "304" ]; then break; fi`,
1483
- ` if [ "$i" != "4" ]; then sleep 5; fi`,
1484
- ` done`,
1485
- `fi`,
1486
- `echo "DB_HOST_LOG="`,
1487
- `tail -n 5 ${hostLog}`,
1488
- `echo "DB_TUNNEL_URL=$TUNNEL_URL"`,
1489
- `echo "DB_HTTP_CODE=$HTTP_CODE"`,
1490
- `echo "DB_EXPIRY_HOURS=${expiryHours}"`,
1491
- // First 64 bytes of the probe body (non-sensitive) so gateway-error markers
1492
- // like "tunnel not found" can be distinguished from app-generated 404/502 pages.
1493
- `echo "DB_TUNNEL_BODY=$(head -c 64 /tmp/.db_probe_body 2>/dev/null)"`,
1494
- `rm -f /tmp/.db_probe_body`,
1495
- `echo "DB_QUOTA_ERROR=$(grep -c '10006' ${hostLog} 2>/dev/null || echo 0)"`,
1496
- ].join('\n');
1497
- }
1498
-
1499
- // Build the script for the SECOND, independent exec session that re-verifies the
1500
- // tunnel with a real GET (#919): the in-session health check inside
1501
- // buildDevbridgeExposeScript cannot prove the host survived session teardown —
1502
- // a GET from a fresh session can. #922 (B2): the response body is kept and
1503
- // checked for the native false-success form — a 200 whose body is "tunnel not
1504
- // found" — and the verdict is emitted as DB_VERIFY_NOT_FOUND so
1505
- // parseDevbridgeVerifyOutput can catch it. The URL is validated (https,
1506
- // URL-safe chars only) before being spliced into the shell command.
1507
- export function buildDevbridgeVerifyScript(tunnelUrl) {
1508
- const url = String(tunnelUrl || '');
1509
- if (!/^https:\/\/[A-Za-z0-9:._/-]+$/.test(url)) {
1510
- throw new Error(
1511
- `sandbox expose tunnel: invalid tunnel URL ${JSON.stringify(url.slice(0, 80))}. Expected an https:// URL with URL-safe characters (from the expose script's DB_TUNNEL_URL output).`,
1512
- );
1513
- }
1514
- const bodyFile = '/tmp/devbridge_verify_body';
1515
- return [
1516
- // #1000: --noproxy — the injected proxy does not route the tunnel domain;
1517
- // a proxied verify returns 502/404 fakes (working tunnel judged dead).
1518
- `VERIFY_CODE=$(curl -s --noproxy '*' -o ${bodyFile} -w "%{http_code}" --max-time 10 "${url}" 2>/dev/null || echo "000")`,
1519
- `VERIFY_NOT_FOUND=$(grep -ci 'tunnel not found' ${bodyFile} 2>/dev/null || true)`,
1520
- `if [ -z "$VERIFY_NOT_FOUND" ]; then VERIFY_NOT_FOUND=0; fi`,
1521
- `rm -f ${bodyFile} 2>/dev/null || true`,
1522
- `echo "DB_VERIFY_HTTP_CODE=$VERIFY_CODE"`,
1523
- `echo "DB_VERIFY_NOT_FOUND=$VERIFY_NOT_FOUND"`,
1524
- ].join('\n');
1525
- }
1526
-
1527
- // A2 (#935): parse the probe sequence emitted by buildDevbridgeExposeScript.
1528
- // Each probe echo is `DB_PROBE_<n>=<code>`; reachability is decided by the
1529
- // LAST probe — intermediate 502/000 probes are gateway-not-ready noise, not
1530
- // failures, so they must not leak into the tool's verdict.
1531
- // #946 (regression): strip OSC/CSI escapes + \r first — integration-enabled
1532
- // shells wrap every line in \x1b]133;C\x07 and blind the anchored
1533
- // ^DB_PROBE_ match (probes came back empty, finalHttpCode always '').
1534
- export function parseDevbridgeProbeSequence(stdout) {
1535
- const text = stripTerminalEscapes(stdout);
1536
- const probes = [];
1537
- for (const m of text.matchAll(/^DB_PROBE_(\d+)=(\S*)$/gm)) {
1538
- probes.push({ attempt: Number(m[1]), httpCode: m[2] });
1539
- }
1540
- const finalHttpCode = probes.length > 0 ? probes[probes.length - 1].httpCode : '';
1541
- return { probes, finalHttpCode };
1542
- }
1543
-
1544
- // A2 (#935): the reachability warning must come from the LAST probe's HTTP
1545
- // status, not from a single early curl — the old single-shot check warned
1546
- // "Tunnel reachable check returned HTTP (expected 200/304)" while the same
1547
- // log showed DB_HTTP_CODE=200. 200/304 = no warning; anything else surfaces
1548
- // as-is.
1549
- export function formatTunnelReachabilityWarning(httpCode) {
1550
- if (httpCode === '200' || httpCode === '304') return undefined;
1551
- return `Tunnel reachable check returned HTTP ${httpCode || '000'} (expected 200/304). The URL may not be serving yet — the final probe decides.`;
1552
- }
1553
-
1554
- // Parse the raw stdout of buildDevbridgeExposeScript into structured fields.
1555
- // `gatewayTunnelError` marks a URL the s2 gateway itself reports as dead
1556
- // (404 "tunnel not found" / "port not configured") — it can never serve content
1557
- // regardless of the app. `badGateway` (502 "bad gateway") means the tunnel is
1558
- // alive but the local service on the exposed port is not serving.
1559
- export function parseDevbridgeExposeOutput(stdout) {
1560
- // #946: strip OSC/CSI escapes + \r BEFORE the anchored ^DB_ lookups — otherwise
1561
- // every field is lost on integration-enabled shells and a perfectly good tunnel
1562
- // comes back as ok:true with publicUrl missing (and pointlessly re-built once).
1563
- const text = stripTerminalEscapes(stdout);
1564
- const getField = (key) => {
1565
- const m = text.match(new RegExp(`^${key}=(.*)$`, 'm'));
1566
- return m ? m[1].trim() : '';
1567
- };
1568
- const tunnelUrl = getField('DB_TUNNEL_URL') || (text.match(/TUNNEL_URL:(https:\/\/[^\s]+)/) || [])[1] || '';
1569
- const httpCode = getField('DB_HTTP_CODE');
1570
- const body = getField('DB_TUNNEL_BODY');
1571
- const quotaError = getField('DB_QUOTA_ERROR') === '1' || /10006/.test(text);
1572
- const tunnelId = (tunnelUrl.match(/^https:\/\/([A-Za-z0-9_-]+)-\d+\./) || [])[1] || '';
1573
- const expiryHours = Number(getField('DB_EXPIRY_HOURS')) || undefined;
1574
- // Exact-body match gated on the status code: an app's own 404/502 page is never misjudged.
1575
- const gatewayTunnelError =
1576
- httpCode === '404' && (body === DEVBRIDGE_TUNNEL_NOT_FOUND_MARKER || body === DEVBRIDGE_PORT_NOT_CONFIGURED_MARKER);
1577
- const badGateway = httpCode === '502' && body === DEVBRIDGE_BAD_GATEWAY_MARKER;
1578
- return { tunnelUrl, httpCode, quotaError, tunnelId, expiryHours, gatewayTunnelError, badGateway };
1579
- }
1580
-
1581
- // Parse the raw stdout of buildDevbridgeVerifyScript into structured fields.
1582
- // Dedicated parser (#922 B1): the verify script emits DB_VERIFY_HTTP_CODE /
1583
- // DB_VERIFY_NOT_FOUND keys — the anchored ^DB_HTTP_CODE= lookup in
1584
- // parseDevbridgeExposeOutput never matches them, which used to leave
1585
- // verifyHttpCode empty and persistent always false.
1586
- export function parseDevbridgeVerifyOutput(stdout) {
1587
- // #946: strip OSC/CSI escapes + \r — the anchored DB_VERIFY_* lookups are blind
1588
- // to them, leaving verifyHttpCode empty and persistent permanently false.
1589
- const text = stripTerminalEscapes(stdout);
1590
- const getField = (key) => {
1591
- const m = text.match(new RegExp(`^${key}=(.*)$`, 'm'));
1592
- return m ? m[1].trim() : '';
1593
- };
1594
- const httpCode = getField('DB_VERIFY_HTTP_CODE');
1595
- const notFoundCount = Number(getField('DB_VERIFY_NOT_FOUND')) || 0;
1596
- const notFound = notFoundCount > 0;
1597
- return { httpCode, notFound };
1598
- }
1599
-
1600
- // Parse and validate a TCP port number destined for shell interpolation. Returns
1601
- // the integer when 1..65535; throws otherwise. Guards the `-p ${port}` shell
1602
- // splice in buildDevbridgeExposeScript against non-numeric / out-of-range input.
1603
- export function validateTunnelPort(port) {
1604
- const n = Number(port);
1605
- if (!Number.isSafeInteger(n) || n < 1 || n > 65535) {
1606
- throw new Error(
1607
- `sandbox expose tunnel: invalid port ${JSON.stringify(port)}. Expected an integer between 1 and 65535 (use the "port" value returned by sandbox_deploy_nginx).`,
1608
- );
1609
- }
1610
- return n;
1611
- }
1612
-
1613
- // Upper bound of devbridge's -e expiry, in hours (measured 2026-10: `-e 720` is
1614
- // accepted and sets expiration = now + 2592001s; larger values are rejected).
1615
- export const DEVBRIDGE_MAX_EXPIRY_HOURS = 720;
1616
-
1617
- // Default renewal horizon for renewTunnel / the keepalive watchdog: 720h gives a
1618
- // 29-day window of tolerance if renewal ever stops firing.
1619
- export const DEVBRIDGE_RENEW_HOURS = 720;
1620
-
1621
- // Validate and clamp a -e expiry value destined for shell interpolation in
1622
- // `devbridge host -p <port> -e <hours>` / `devbridge update <id> -e <hours>`.
1623
- // devbridge accepts 1..720 (30 days); anything else is rejected or clipped by
1624
- // the gateway, so fail fast here instead of surfacing a misleading expiry.
1625
- export function validateExpiryHours(hours) {
1626
- const n = Number(hours);
1627
- if (!Number.isSafeInteger(n) || n < 1 || n > DEVBRIDGE_MAX_EXPIRY_HOURS) {
1628
- throw new Error(
1629
- `sandbox tunnel expiry: invalid expiry_hours ${JSON.stringify(hours)}. Expected an integer between 1 and ${DEVBRIDGE_MAX_EXPIRY_HOURS} (720 = the devbridge 30-day maximum).`,
1630
- );
1631
- }
1632
- return n;
1633
- }
1634
-
1635
- // Validate a DevBridge tunnel ID destined for shell interpolation in
1636
- // `devbridge update <id>` / `devbridge host <id>` / pgrep patterns. IDs are
1637
- // short lowercase base36 tokens (e.g. nv2dvv6w, kag7rozs); the strict charset
1638
- // keeps shell metacharacters out of the splice.
1639
- export function validateTunnelId(tunnelId) {
1640
- const id = String(tunnelId || '');
1641
- if (!/^[A-Za-z0-9_-]{4,32}$/.test(id)) {
1642
- throw new Error(
1643
- `sandbox tunnel: invalid tunnel_id ${JSON.stringify(id.slice(0, 40))}. Expected the short ID from huaweicloud_sandbox_expose_tunnel's "tunnelId" field (URL-safe characters only).`,
1644
- );
1645
- }
1646
- return id;
1647
- }
1648
-
1649
- // Build the script that renews a tunnel's lifetime: `devbridge update <id> -e
1650
- // <hours>`. The expiry is a ROLLING WINDOW (measured 2026-10: renewal sets
1651
- // expiration = now + hours regardless of remaining time, so renewing before
1652
- // expiry keeps the same URL alive indefinitely). The absolute expiration
1653
- // (tunnelExpiration, Unix seconds) is surfaced via show -v so callers get a
1654
- // verifiable timestamp instead of a bare exit code.
1655
- export function buildDevbridgeRenewScript(tunnelId, expiryHours = DEVBRIDGE_RENEW_HOURS) {
1656
- const id = validateTunnelId(tunnelId);
1657
- const hours = validateExpiryHours(expiryHours);
1658
- return [
1659
- `export PATH="$HOME/.huawei/bin:$PATH"`,
1660
- `devbridge update ${id} -e ${hours} > /tmp/db-renew-update.log 2>&1`,
1661
- `DB_RENEW_EXIT=$?`,
1662
- `DB_RENEW_ERROR=$(head -1 /tmp/db-renew-update.log 2>/dev/null)`,
1663
- `rm -f /tmp/db-renew-update.log`,
1664
- `DB_EXPIRATION=$(devbridge show ${id} -v 2>&1 | grep -oE 'tunnelExpiration[^0-9]+[0-9]+' | grep -oE '[0-9]+' | head -1)`,
1665
- `echo "DB_RENEW_EXIT=$DB_RENEW_EXIT"`,
1666
- `echo "DB_RENEW_ID=${id}"`,
1667
- `echo "DB_RENEW_HOURS=${hours}"`,
1668
- `echo "DB_EXPIRATION=$DB_EXPIRATION"`,
1669
- `echo "DB_RENEW_ERROR=$DB_RENEW_ERROR"`,
1670
- ].join('\n');
1671
- }
1672
-
1673
- // Parse the raw stdout of buildDevbridgeRenewScript into structured fields.
1674
- // A renewal is ok only when the update exit code is 0 AND show -v reports the
1675
- // absolute tunnelExpiration — the management plane can lose a tunnel's record
1676
- // (10002 "tunnel not found") while the data plane keeps serving, which a bare
1677
- // exit-code check would misread as success on the old process alone.
1678
- export function parseDevbridgeRenewOutput(stdout) {
1679
- const text = stripTerminalEscapes(stdout);
1680
- const getField = (key) => {
1681
- const m = text.match(new RegExp(`^${key}=(.*)$`, 'm'));
1682
- return m ? m[1].trim() : '';
1683
- };
1684
- const renewExit = getField('DB_RENEW_EXIT');
1685
- const expirationUnix = Number(getField('DB_EXPIRATION')) || undefined;
1686
- const ok = renewExit === '0' && expirationUnix !== undefined;
1687
- const expiration = expirationUnix !== undefined ? new Date(expirationUnix * 1000).toISOString() : undefined;
1688
- return {
1689
- ok,
1690
- tunnelId: getField('DB_RENEW_ID'),
1691
- renewedForHours: Number(getField('DB_RENEW_HOURS')) || undefined,
1692
- expirationUnix,
1693
- expiresAt: expiration,
1694
- error: ok ? undefined : getField('DB_RENEW_ERROR') || `renewal failed (exit ${renewExit || 'unknown'})`,
1695
- };
1696
- }
1697
-
1698
- // Renew a tunnel's lifetime via `devbridge update <id> -e <hours>`. Returns ok,
1699
- // tunnelId, expiresAt (absolute ISO timestamp), renewedForHours. The URL does
1700
- // not change — renewal only extends the lifetime of the existing tunnel ID.
1701
- export async function renewTunnel(workspaceId, { tunnelId, expiryHours }, username = 'root', timeoutMs = 60000) {
1702
- if (!workspaceId) {
1703
- throw new Error('sandbox renew tunnel: workspace_id is required.');
1704
- }
1705
- const script = buildDevbridgeRenewScript(tunnelId, expiryHours);
1706
- const result = await execOneShot(workspaceId, script, username, timeoutMs);
1707
- const parsed = parseDevbridgeRenewOutput(result.stdout);
1708
- return parsed;
1709
- }
1710
-
1711
- // Build the keepalive watchdog script for a set of known tunnels (the
1712
- // three-layer pattern proven in the 2026-10 tunnel-persistence test):
1713
- // 1. host watchdog — re-attach with `devbridge host <id>` when the host
1714
- // process dies; the URL is bound to the tunnel ID, so it never changes
1715
- // 2. daily renewal — `devbridge update <id> -e 720` (29-day failure tolerance)
1716
- // 3. health check — curl each URL every 5 minutes, log on non-200/304
1717
- // URLs are HARDCODED per tunnel (tunnel IDs never change), NOT derived from
1718
- // `devbridge port list` — that table's lines are wrapped in OSC escapes on
1719
- // integration-enabled shells, so anchored greps silently fail and the
1720
- // constructed health URL 404s (measured 2026-10).
1721
- export function buildDevbridgeKeepaliveScript(tunnels) {
1722
- if (!Array.isArray(tunnels) || tunnels.length === 0) {
1723
- throw new Error('sandbox keepalive: tunnels must be a non-empty array of {tunnelId, url}.');
1724
- }
1725
- const entries = tunnels
1726
- .map((t) => `${validateTunnelId(t?.tunnelId)}:${String(t?.url || '')}`)
1727
- .map((entry) => {
1728
- const url = entry.slice(entry.indexOf(':') + 1);
1729
- if (!/^https:\/\/[A-Za-z0-9:._/-]+$/.test(url)) {
1730
- throw new Error(
1731
- `sandbox keepalive: invalid tunnel URL ${JSON.stringify(url.slice(0, 80))} for the keepalive health check. Expected an https:// URL with URL-safe characters (from huaweicloud_sandbox_expose_tunnel's publicUrl).`,
1732
- );
1733
- }
1734
- return entry;
1735
- })
1736
- .join(' ');
1737
- // Heredoc is single-quoted ('DB_KEEPALIVE_EOF') so the writer shell expands
1738
- // nothing; all ${...} expansion happens inside the watchdog at runtime.
1739
- const body = [
1740
- `#!/bin/bash`,
1741
- `export PATH="$HOME/.huawei/bin:$PATH"`,
1742
- `export DBUS_SESSION_BUS_ADDRESS="\${DBUS_SESSION_BUS_ADDRESS:-unix:path=/run/dbus-session}"`,
1743
- `# entries: tunnelId:url (URLs are stable — tunnel IDs never change)`,
1744
- `TUNNELS="${entries}"`,
1745
- `declare -A LAST_RENEW`,
1746
- `while true; do`,
1747
- ` NOW=$(date -u +%s)`,
1748
- ` TS=$(date -u +%Y-%m-%dT%H:%M:%SZ)`,
1749
- ` for entry in $TUNNELS; do`,
1750
- ` ID="\${entry%%:*}"; URL="\${entry#*:}"`,
1751
- ` if ! pgrep -f "devbridge host $ID" > /dev/null 2>&1; then`,
1752
- ` if command -v setsid > /dev/null 2>&1; then setsid nohup devbridge host "$ID" > "/tmp/host-$ID.log" 2>&1 < /dev/null & else nohup devbridge host "$ID" > "/tmp/host-$ID.log" 2>&1 < /dev/null & fi`,
1753
- ` echo "$TS host $ID restarted (same tunnel, URL unchanged)" >> /tmp/tunnel-keepalive.log`,
1754
- ` sleep 8`,
1755
- ` fi`,
1756
- ` if [ $((\${LAST_RENEW[$ID]:-0})) -eq 0 ] || [ $((NOW - \${LAST_RENEW[$ID]})) -ge 86400 ]; then`,
1757
- ` if devbridge update "$ID" -e ${DEVBRIDGE_RENEW_HOURS} > /tmp/keepalive-last-update.log 2>&1; then`,
1758
- ` echo "$TS renew $ID ok (${DEVBRIDGE_RENEW_HOURS}h)" >> /tmp/tunnel-keepalive.log`,
1759
- ` else`,
1760
- ` echo "$TS renew $ID FAILED: $(head -1 /tmp/keepalive-last-update.log)" >> /tmp/tunnel-keepalive.log`,
1761
- ` # Self-heal: CLI token 过期但 key 仍有效时,重新登录后立即重试一次`,
1762
- ` DB_KEY=""`,
1763
- ` if command -v hwcloud >/dev/null 2>&1; then`,
1764
- ` DB_KEY=$(hwcloud keyring get HW_DEVBRIDGE_API_KEY 2>&1 || true)`,
1765
- ` case "$DB_KEY" in "devbridge_"*) : ;; *) DB_KEY="";; esac`,
1766
- ` fi`,
1767
- ` if [ -z "$DB_KEY" ] && [ -s /tmp/hw_api_key ]; then`,
1768
- ` source /tmp/hw_api_key 2>/dev/null || true`,
1769
- ` DB_KEY="\${HW_API_KEY:-}"`,
1770
- ` fi`,
1771
- ` if [ -n "$DB_KEY" ] && devbridge auth login --api-key "$DB_KEY" >/tmp/keepalive-auth.log 2>&1; then`,
1772
- ` if devbridge update "$ID" -e ${DEVBRIDGE_RENEW_HOURS} > /tmp/keepalive-last-update.log 2>&1; then`,
1773
- ` echo "$TS renew $ID ok after re-login (${DEVBRIDGE_RENEW_HOURS}h)" >> /tmp/tunnel-keepalive.log`,
1774
- ` else`,
1775
- ` echo "$TS renew $ID FAILED after re-login: $(head -1 /tmp/keepalive-last-update.log)" >> /tmp/tunnel-keepalive.log`,
1776
- ` fi`,
1777
- ` else`,
1778
- ` echo "$TS renew $ID AUTH_FAILED: no usable key; next expose_tunnel will auto-create" >> /tmp/tunnel-keepalive.log`,
1779
- ` fi`,
1780
- ` unset DB_KEY HW_API_KEY 2>/dev/null`,
1781
- ` fi`,
1782
- ` LAST_RENEW[$ID]=$NOW`,
1783
- ` fi`,
1784
- ` HC=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "$URL/" 2>/dev/null || echo "000")`,
1785
- ` if [ "$HC" != "200" ] && [ "$HC" != "304" ]; then`,
1786
- ` echo "$TS health $ID WARN http=$HC" >> /tmp/tunnel-keepalive.log`,
1787
- ` fi`,
1788
- ` done`,
1789
- ` sleep 300`,
1790
- `done`,
1791
- ].join('\n');
1792
- return [
1793
- `export PATH="$HOME/.huawei/bin:$PATH"`,
1794
- `pkill -f "tunnel-keepalive.sh" 2>/dev/null || true`,
1795
- `sleep 1`,
1796
- `cat > /tmp/tunnel-keepalive.sh << 'DB_KEEPALIVE_EOF'`,
1797
- body,
1798
- `DB_KEEPALIVE_EOF`,
1799
- `chmod +x /tmp/tunnel-keepalive.sh`,
1800
- `bash -n /tmp/tunnel-keepalive.sh > /dev/null 2>&1`,
1801
- `echo "DB_KEEPALIVE_SYNTAX=$?"`,
1802
- `if command -v setsid > /dev/null 2>&1; then setsid nohup /tmp/tunnel-keepalive.sh > /dev/null 2>&1 < /dev/null & else nohup /tmp/tunnel-keepalive.sh > /dev/null 2>&1 < /dev/null & fi`,
1803
- `disown 2>/dev/null || true`,
1804
- `sleep 3`,
1805
- `echo "DB_KEEPALIVE_PID=$(pgrep -f 'tunnel-keepalive.sh' | head -1)"`,
1806
- `echo "DB_KEEPALIVE_LOG=/tmp/tunnel-keepalive.log"`,
1807
- ].join('\n');
1808
- }
1809
-
1810
- // Read the tunnel list of the INSTALLED watchdog (if any). The TUNNELS line in
1811
- // /tmp/tunnel-keepalive.sh is the single source of truth for what is currently
1812
- // protected; expose_tunnel reads it before installing so the new tunnel is
1813
- // MERGED into the existing protection instead of replacing it.
1814
- export function buildKeepaliveTunnelsReadScript() {
1815
- return [
1816
- `LINE=$(grep -m1 '^TUNNELS=' /tmp/tunnel-keepalive.sh 2>/dev/null | sed 's/^TUNNELS=//; s/^"//; s/"$//')`,
1817
- `echo "DB_KEEPALIVE_TUNNELS=$LINE"`,
1818
- ].join('\n');
1819
- }
1820
-
1821
- // Parse the raw stdout of buildKeepaliveTunnelsReadScript. Empty output (no
1822
- // watchdog installed yet) yields [].
1823
- export function parseKeepaliveTunnelsOutput(stdout) {
1824
- const text = stripTerminalEscapes(stdout);
1825
- const m = text.match(/^DB_KEEPALIVE_TUNNELS=(.*)$/m);
1826
- const line = m ? m[1].trim() : '';
1827
- if (!line) return [];
1828
- return line
1829
- .split(/\s+/)
1830
- .map((entry) => {
1831
- const i = entry.indexOf(':');
1832
- return i > 0 ? { tunnelId: entry.slice(0, i), url: entry.slice(i + 1) } : null;
1833
- })
1834
- .filter(Boolean);
1835
- }
1836
-
1837
- // Merge the current watchdog tunnels with the incoming ones: dedupe by
1838
- // tunnelId, incoming wins (same tunnel re-exposed refreshes its URL), existing
1839
- // order preserved, new tunnels appended.
1840
- export function mergeKeepaliveTunnels(existing, incoming) {
1841
- const byId = new Map();
1842
- for (const t of existing || []) {
1843
- if (t?.tunnelId && t?.url) byId.set(t.tunnelId, { tunnelId: t.tunnelId, url: t.url });
1844
- }
1845
- for (const t of incoming || []) {
1846
- if (t?.tunnelId && t?.url) byId.set(t.tunnelId, { tunnelId: t.tunnelId, url: t.url });
1847
- }
1848
- return [...byId.values()];
1849
- }
1850
-
1851
- // Install the keepalive watchdog in the sandbox. Validates every tunnel ID and
1852
- // URL before splicing, aborts on a bash syntax error (DB_KEEPALIVE_SYNTAX != 0),
1853
- // and reports the watchdog PID. Replacing the watchdog (re-running the tool)
1854
- // kills the old loop first so two loops never double-renew.
1855
- export async function installKeepaliveWatchdog(workspaceId, { tunnels }, username = 'root', timeoutMs = 60000) {
1856
- if (!workspaceId) {
1857
- throw new Error('sandbox keepalive: workspace_id is required.');
1858
- }
1859
- const script = buildDevbridgeKeepaliveScript(tunnels);
1860
- const result = await execOneShot(workspaceId, script, username, timeoutMs);
1861
- const text = stripTerminalEscapes(result.stdout);
1862
- const getField = (key) => {
1863
- const m = text.match(new RegExp(`^${key}=(.*)$`, 'm'));
1864
- return m ? m[1].trim() : '';
1865
- };
1866
- const syntax = getField('DB_KEEPALIVE_SYNTAX');
1867
- if (syntax !== '0') {
1868
- return {
1869
- ok: false,
1870
- error: `keepalive watchdog script failed the bash -n syntax check (exit ${syntax || 'unknown'}).`,
1871
- };
1872
- }
1873
- return {
1874
- ok: true,
1875
- scriptPath: '/tmp/tunnel-keepalive.sh',
1876
- logPath: getField('DB_KEEPALIVE_LOG') || '/tmp/tunnel-keepalive.log',
1877
- watchdogPid: getField('DB_KEEPALIVE_PID') || undefined,
1878
- tunnels: (tunnels || []).map((t) => ({ tunnelId: t.tunnelId, url: t.url })),
1879
- };
1880
- }
1881
-
1882
- // ── DevBridge selective cleanup ─────────────────────────────────────────────
1883
- // delete-all is intentionally NOT used: it kills other sessions/ports on a shared
1884
- // sandbox. Cleanup removes only orphan tunnels/hosts and (for expose) tunnels bound
1885
- // to the same port, preserving keepalive-protected and live-unknown tunnels.
1886
- // Same-port is the one documented exception: a keepalive-protected tunnel on the
1887
- // target port is replaced (you cannot bind two tunnels to one port).
1888
-
1889
- // Same charset as validateTunnelId: real IDs may contain 0/1/8/9, so parsing must
1890
- // not assume the base32 subset.
1891
- const DEVBRIDGE_TUNNEL_ID_RE = /^[A-Za-z0-9_-]{4,32}$/;
1892
- const DEVBRIDGE_PATH_EXPORT = 'export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"';
1893
- const DEVBRIDGE_LOCK_PATH = '/tmp/devbridge-cleanup.lock';
1894
- // Worst-case hold: state 60x2 + apply 60x2 + sync ~150 + release 60 ≈ 450s;
1895
- // keep the stale threshold above the worst case so a second cleanup cannot
1896
- // break a lock that is still legitimately held.
1897
- const DEVBRIDGE_LOCK_STALE_MINUTES = 10;
1898
- const DEVBRIDGE_CLEANUP_TIMEOUT_MS = 60000;
1899
-
1900
- export function normalizeCleanupMode(raw) {
1901
- return ['stale', 'all', 'none'].includes(raw) ? raw : 'stale';
1902
- }
1903
-
1904
- export function parseDevbridgeTunnelList(stdout) {
1905
- const text = stripTerminalEscapes(String(stdout || ''));
1906
- const tunnels = [];
1907
- for (const line of text.split(/\r?\n/)) {
1908
- if (/^\s*Tunnel\s+ID\b/i.test(line)) continue;
1909
- const m = line.match(/^\s*([A-Za-z0-9_-]{4,32})\s+(.+)$/);
1910
- if (!m || !DEVBRIDGE_TUNNEL_ID_RE.test(m[1])) continue;
1911
- const id = m[1];
1912
- const rest = m[2];
1913
- const name = rest.trim().split(/\s{2,}|\t+/)[0] || '';
1914
- const portMatch = rest.match(/tunnel-(\d+)-/);
1915
- const expMatch = rest.match(/(\d+)\s*(day|days|hour|hours|minute|minutes)/i);
1916
- const unit = expMatch ? expMatch[2].toLowerCase() : '';
1917
- const multiplier = { day: 86400, days: 86400, hour: 3600, hours: 3600, minute: 60, minutes: 60 }[unit];
1918
- tunnels.push({
1919
- id,
1920
- name,
1921
- port: portMatch ? Number(portMatch[1]) : null,
1922
- expiryText: expMatch ? expMatch[0] : '',
1923
- expirySeconds: expMatch && multiplier ? Number(expMatch[1]) * multiplier : null,
1924
- });
1925
- }
1926
- return tunnels;
1927
- }
1928
-
1929
- export function parseDevbridgeHostProcesses(stdout) {
1930
- const text = stripTerminalEscapes(String(stdout || ''));
1931
- const hosts = [];
1932
- for (const line of text.split(/\r?\n/)) {
1933
- const m = line.match(/^\s*(\d+)\s+(.*)$/);
1934
- if (!m) continue;
1935
- // Anchor the executable so a shell wrapper (`bash -c "...devbridge host..."`)
1936
- // is never mistaken for a real host process.
1937
- const execMatch = m[2].match(/^(?:\S*\/)?devbridge\s+host\b(.*)$/);
1938
- if (!execMatch) continue;
1939
- const rest = execMatch[1].trim();
1940
- const tokens = rest ? rest.split(/\s+/) : [];
1941
- let id = null;
1942
- let port = null;
1943
- for (let i = 0; i < tokens.length; i += 1) {
1944
- const token = tokens[i];
1945
- if (token === '-p' && /^\d+$/.test(tokens[i + 1] || '')) {
1946
- port = Number(tokens[i + 1]);
1947
- i += 1;
1948
- } else if (token === '-e') {
1949
- i += 1;
1950
- } else if (token.startsWith('-')) {
1951
- // unknown flag: skip it
1952
- } else if (!id && DEVBRIDGE_TUNNEL_ID_RE.test(token) && !/^\d+$/.test(token)) {
1953
- id = token;
1954
- }
1955
- }
1956
- if (!id && port == null) continue; // unparseable host: ignore, never kill blindly
1957
- hosts.push({ pid: Number(m[1]), id, port });
1958
- }
1959
- return hosts;
1960
- }
1961
-
1962
- /**
1963
- * Decide which tunnels/hosts to remove.
1964
- * - protected: keepalive TUNNELS entries (never removed unless mode=all or samePort)
1965
- * - orphan: tunnel record with no live host -> removed in stale/quota
1966
- * - orphan host: host process with no matching tunnel record -> killed
1967
- * - quota: also removes the oldest non-protected live tunnels (maxExtra per call)
1968
- */
1969
- export function planDevbridgeCleanup({
1970
- tunnels = [],
1971
- hosts = [],
1972
- keepalive = [],
1973
- mode = 'stale',
1974
- samePort = null,
1975
- maxExtra = 1,
1976
- } = {}) {
1977
- if (mode === 'none') return { deleteIds: [], killPids: [] };
1978
-
1979
- const tunnelIds = new Set(tunnels.map((t) => t.id));
1980
- const protectedIds = new Set(keepalive.map((k) => k.tunnelId).filter(Boolean));
1981
- const portById = new Map();
1982
- for (const t of tunnels) if (t.port != null) portById.set(t.id, t.port);
1983
- for (const k of keepalive) {
1984
- const m = String(k.url || '').match(/-(\d+)\.devbridge-s2\./);
1985
- if (m && tunnelIds.has(k.tunnelId)) portById.set(k.tunnelId, Number(m[1]));
1986
- }
1987
-
1988
- if (mode === 'all') {
1989
- return { deleteIds: [...tunnelIds], killPids: hosts.map((h) => h.pid) };
1990
- }
1991
-
1992
- const liveIds = new Set();
1993
- const mappedPids = new Set();
1994
- for (const h of hosts) {
1995
- if (!h.id && h.port == null) continue; // unattributable host: never kill blindly
1996
- if (h.id && tunnelIds.has(h.id)) {
1997
- liveIds.add(h.id);
1998
- mappedPids.add(h.pid);
1999
- } else if (h.port != null) {
2000
- for (const [id, port] of portById) {
2001
- if (port === h.port) {
2002
- liveIds.add(id);
2003
- mappedPids.add(h.pid);
2004
- }
2005
- }
2006
- }
2007
- }
2008
-
2009
- const killPids = new Set(hosts.filter((h) => (h.id || h.port != null) && !mappedPids.has(h.pid)).map((h) => h.pid));
2010
- const samePortIds = samePort == null ? [] : tunnels.filter((t) => portById.get(t.id) === samePort).map((t) => t.id);
2011
- const orphanIds = tunnels.filter((t) => !protectedIds.has(t.id) && !liveIds.has(t.id)).map((t) => t.id);
2012
- const deleteSet = new Set([...orphanIds, ...samePortIds]);
2013
-
2014
- if (mode === 'quota') {
2015
- const candidates = tunnels
2016
- .filter((t) => !protectedIds.has(t.id) && !deleteSet.has(t.id) && liveIds.has(t.id))
2017
- .sort((a, b) => (a.expirySeconds ?? Number.MAX_SAFE_INTEGER) - (b.expirySeconds ?? Number.MAX_SAFE_INTEGER));
2018
- for (let i = 0; i < Math.max(0, maxExtra) && i < candidates.length; i += 1) {
2019
- deleteSet.add(candidates[i].id);
2020
- }
2021
- }
2022
-
2023
- for (const h of hosts) {
2024
- if (h.id && deleteSet.has(h.id)) killPids.add(h.pid);
2025
- else if (h.port != null && [...deleteSet].some((id) => portById.get(id) === h.port)) killPids.add(h.pid);
2026
- }
2027
-
2028
- return { deleteIds: [...deleteSet], killPids: [...killPids] };
2029
- }
2030
-
2031
- export function buildDevbridgeCleanupApplyScript({ deleteIds = [], killPids = [] } = {}) {
2032
- for (const id of deleteIds) {
2033
- if (!DEVBRIDGE_TUNNEL_ID_RE.test(String(id))) {
2034
- throw new Error(`devbridge cleanup: invalid tunnel id ${JSON.stringify(id)}`);
2035
- }
2036
- }
2037
- for (const pid of killPids) {
2038
- if (!Number.isSafeInteger(pid) || pid <= 0) {
2039
- throw new Error(`devbridge cleanup: invalid pid ${JSON.stringify(pid)}`);
2040
- }
2041
- }
2042
- return [
2043
- DEVBRIDGE_PATH_EXPORT,
2044
- // Re-check the process identity before killing: state→apply can take minutes,
2045
- // so a recycled PID must not hit an unrelated process.
2046
- ...killPids.map(
2047
- (pid) =>
2048
- `if ps -p ${pid} -o args= 2>/dev/null | grep -q "devbridge host"; then kill ${pid} >/dev/null 2>&1 || true; fi`,
2049
- ),
2050
- `sleep 1`,
2051
- ...deleteIds.map((id) => `devbridge delete ${id} >/dev/null 2>&1 || true`),
2052
- `echo "DB_CLEANUP_DELETED=${deleteIds.join(',')}"`,
2053
- `echo "DB_CLEANUP_KILLED=${killPids.join(',')}"`,
2054
- ].join('\n');
2055
- }
2056
-
2057
- export function buildDevbridgeCleanupStateScript() {
2058
- return [
2059
- DEVBRIDGE_PATH_EXPORT,
2060
- // Refresh the CLI token from an existing key. A valid API key can leave an
2061
- // expired CLI token; without this, devbridge list returns 40100 and cleanup
2062
- // is skipped even though the key is usable. Never creates a new key here.
2063
- `DB_KEY=""`,
2064
- `if command -v hwcloud >/dev/null 2>&1; then`,
2065
- ` DB_KEY=$(hwcloud keyring get HW_DEVBRIDGE_API_KEY 2>&1 || true)`,
2066
- ` case "$DB_KEY" in "devbridge_"*) : ;; *) DB_KEY="";; esac`,
2067
- `fi`,
2068
- `if [ -z "$DB_KEY" ] && [ -s /tmp/hw_api_key ]; then`,
2069
- ` source /tmp/hw_api_key 2>/dev/null || true`,
2070
- ` DB_KEY="\${HW_API_KEY:-}"`,
2071
- `fi`,
2072
- `if [ -n "$DB_KEY" ]; then devbridge auth login --api-key "$DB_KEY" >/dev/null 2>&1 || true; fi`,
2073
- `unset DB_KEY HW_API_KEY 2>/dev/null`,
2074
- `echo "DB_CLEANUP_TUNNELS_BEGIN"`,
2075
- `devbridge list 2>&1 || true`,
2076
- `echo "DB_CLEANUP_TUNNELS_END"`,
2077
- `echo "DB_CLEANUP_HOSTS_BEGIN"`,
2078
- `pgrep -af "devbridge host" 2>&1 || true`,
2079
- `echo "DB_CLEANUP_HOSTS_END"`,
2080
- buildKeepaliveTunnelsReadScript(),
2081
- ].join('\n');
2082
- }
2083
-
2084
- export function buildDevbridgeCleanupLockScript() {
2085
- return [
2086
- `LOCK=${DEVBRIDGE_LOCK_PATH}`,
2087
- `if mkdir "$LOCK" 2>/dev/null; then echo LOCK_OK; else`,
2088
- ` if find "$LOCK" -maxdepth 0 -mmin +${DEVBRIDGE_LOCK_STALE_MINUTES} 2>/dev/null | grep -q .; then rmdir "$LOCK" 2>/dev/null || true; fi`,
2089
- ` if mkdir "$LOCK" 2>/dev/null; then echo LOCK_OK; else echo LOCK_BUSY; fi`,
2090
- `fi`,
2091
- ].join('\n');
2092
- }
2093
-
2094
- function cleanupSection(text, name) {
2095
- const m = String(text || '').match(new RegExp(`DB_CLEANUP_${name}_BEGIN\\r?\\n([\\s\\S]*?)DB_CLEANUP_${name}_END`));
2096
- return m ? m[1] : '';
2097
- }
2098
-
2099
- async function execCleanupWithRetry(workspaceId, script, username, timeoutMs = 60000) {
2100
- let lastError;
2101
- for (let i = 1; i <= 2; i += 1) {
2102
- try {
2103
- return await execOneShot(workspaceId, script, username, timeoutMs);
2104
- } catch (error) {
2105
- lastError = error;
2106
- if (i === 2 || !/timeout|websocket/i.test(String(error?.message || ''))) throw error;
2107
- await new Promise((r) => setTimeout(r, 1000));
2108
- }
2109
- }
2110
- throw lastError;
2111
- }
2112
-
2113
- async function syncKeepaliveAfterCleanup(workspaceId, { deletedIds, liveTunnelIds, pruneMissing, username }) {
2114
- let current;
2115
- try {
2116
- const read = await execCleanupWithRetry(workspaceId, buildKeepaliveTunnelsReadScript(), username, 30000);
2117
- current = parseKeepaliveTunnelsOutput(read.stdout);
2118
- } catch {
2119
- return;
2120
- }
2121
- if (!current.length) return;
2122
- const deleted = new Set(deletedIds || []);
2123
- // Prune deleted IDs AND entries that no longer exist in the management plane
2124
- // (ghost tunnels from earlier delete-all calls would otherwise be re-hosted
2125
- // and renewed forever).
2126
- // Only prune "absent" entries when we have at least one confirmed live tunnel
2127
- // (or an explicit all-mode reset). A transient empty list must not wipe the
2128
- // watchdog and silently stop renewals.
2129
- const remaining = current.filter((t) => !deleted.has(t.tunnelId) && (!pruneMissing || liveTunnelIds.has(t.tunnelId)));
2130
- if (remaining.length === current.length) return;
2131
- if (remaining.length === 0) {
2132
- try {
2133
- await execCleanupWithRetry(
2134
- workspaceId,
2135
- `pkill -f "tunnel-keepalive.sh" 2>/dev/null || true; rm -f /tmp/tunnel-keepalive.sh`,
2136
- username,
2137
- 30000,
2138
- );
2139
- } catch {}
2140
- return;
2141
- }
2142
- try {
2143
- await installKeepaliveWatchdog(workspaceId, { tunnels: remaining }, username, 30000);
2144
- } catch {}
2145
- }
2146
-
2147
- export async function cleanupDevbridgeTunnels(
2148
- workspaceId,
2149
- { mode = 'stale', samePort = null, maxExtra = 1, username = 'root' } = {},
2150
- ) {
2151
- if (!workspaceId) throw new Error('devbridge cleanup: workspace_id is required.');
2152
- if (mode === 'none') return { ok: true, skipped: true, deleteIds: [], killPids: [] };
2153
-
2154
- let lockResult;
2155
- try {
2156
- lockResult = await execOneShot(workspaceId, buildDevbridgeCleanupLockScript(), username, 30000);
2157
- } catch {
2158
- return { ok: false, locked: true, deleteIds: [], killPids: [] };
2159
- }
2160
- if (!stripTerminalEscapes(lockResult.stdout).includes('LOCK_OK')) {
2161
- return { ok: false, locked: true, deleteIds: [], killPids: [] };
2162
- }
2163
-
2164
- try {
2165
- const stateResult = await execCleanupWithRetry(workspaceId, buildDevbridgeCleanupStateScript(), username, 60000);
2166
- const text = stripTerminalEscapes(stateResult.stdout);
2167
- const tunnelSection = cleanupSection(text, 'TUNNELS');
2168
- const listOk = /Tunnel ID|No tunnels found/i.test(tunnelSection);
2169
- if (!listOk) {
2170
- // list/auth/network failed — do not delete or kill anything on a guess.
2171
- return { ok: false, listFailed: true, deleteIds: [], killPids: [] };
2172
- }
2173
- const tunnels = parseDevbridgeTunnelList(tunnelSection);
2174
- const hosts = parseDevbridgeHostProcesses(cleanupSection(text, 'HOSTS'));
2175
- // Output-format drift guard: header matched but rows didn't parse, while host
2176
- // processes exist. Never mass-kill hosts on a parse we don't trust.
2177
- if (tunnels.length === 0 && hosts.length > 0 && !/No tunnels found/i.test(tunnelSection)) {
2178
- return { ok: false, listFailed: true, deleteIds: [], killPids: [] };
2179
- }
2180
- const keepalive = parseKeepaliveTunnelsOutput(text);
2181
- const liveTunnelIds = new Set(tunnels.map((t) => t.id));
2182
- const pruneMissing = mode === 'all' || liveTunnelIds.size > 0;
2183
- const plan = planDevbridgeCleanup({ tunnels, hosts, keepalive, mode, samePort, maxExtra });
2184
- if (plan.deleteIds.length === 0 && plan.killPids.length === 0) {
2185
- await syncKeepaliveAfterCleanup(workspaceId, {
2186
- deletedIds: [],
2187
- liveTunnelIds,
2188
- pruneMissing,
2189
- username,
2190
- });
2191
- return { ok: true, deleteIds: [], killPids: [], tunnelCount: tunnels.length };
2192
- }
2193
- await execCleanupWithRetry(
2194
- workspaceId,
2195
- buildDevbridgeCleanupApplyScript(plan),
2196
- username,
2197
- DEVBRIDGE_CLEANUP_TIMEOUT_MS,
2198
- );
2199
- await syncKeepaliveAfterCleanup(workspaceId, {
2200
- deletedIds: plan.deleteIds,
2201
- liveTunnelIds,
2202
- pruneMissing,
2203
- username,
2204
- });
2205
- return { ok: true, ...plan, tunnelCount: tunnels.length };
2206
- } finally {
2207
- try {
2208
- await execCleanupWithRetry(workspaceId, `rmdir ${DEVBRIDGE_LOCK_PATH} 2>/dev/null || true`, username, 30000);
2209
- } catch {}
2210
- }
2211
- }
2212
-
2213
- // Expose a sandbox port to a public DevBridge tunnel URL. `port` MUST be the
2214
- // ACTUAL port reported by deployNginx (deploy_nginx auto-increments on conflict),
2215
- // otherwise the tunnel is bound to a dead port. Returns ok, publicUrl, port,
2216
- // tunnelId, auth mode, expiresAt (tunnel lifetime from -e), and warnings; the
2217
- // tunnel is re-verified from a second independent exec session (#919) and the
2218
- // result carries verifyHttpCode + persistent so callers can tell a
2219
- // session-surviving URL from one that dies with the deploying session.
2220
- export async function exposeTunnel(
2221
- workspaceId,
2222
- {
2223
- port,
2224
- expiryHours,
2225
- keepalive,
2226
- poolType,
2227
- poolContext,
2228
- cleanupMode = 'stale',
2229
- ensureDevbridgeKey,
2230
- buildKeyringInjectScript,
2231
- listKeysForQuotaHint,
2232
- },
2233
- username = 'root',
2234
- timeoutMs = 90000,
2235
- ) {
2236
- if (!workspaceId) {
2237
- throw new Error('sandbox expose tunnel: workspace_id is required.');
2238
- }
2239
- const validatedPort = validateTunnelPort(port);
2240
- const validatedExpiryHours = validateExpiryHours(expiryHours ?? DEVBRIDGE_HOST_EXPIRY_HOURS);
2241
-
2242
- const authScript = buildDevbridgeAuthProbe();
2243
- const authResult = await execOneShot(workspaceId, authScript, username, 30000);
2244
- const { authMode, attempts, version: authVersion } = parseDevbridgeAuthOutput(authResult.stdout);
2245
-
2246
- // #998: version gate BEFORE the expose loop. 0.1.x binaries' AK/SK tier still
2247
- // logs in, so authMode alone would green-light an expose that can never work.
2248
- // This must precede the authMode check — the structured too_old error names
2249
- // the real cause where the auth-failure path would point at credentials.
2250
- const versionCheck = evaluateDevbridgeVersion(authVersion);
2251
- if (versionCheck.blocked) {
2252
- return {
2253
- ok: false,
2254
- error: versionCheck.error,
2255
- error_code: 'devbridge_too_old',
2256
- version: authVersion,
2257
- authMode,
2258
- attempts,
2259
- remediation: versionCheck.remediation,
2260
- };
2261
- }
2262
-
2263
- // Auth waterfall: probe → (auto-create fallback) → expose loop
2264
- // 失效自愈:probe 报 login-failed(key 被删/过期)→ 清缓存 → 重建 → 注入 → 重跑 probe
2265
- let effectiveAuthMode = authMode;
2266
- const isLoginFailed =
2267
- authMode !== 'API_KEY_KEYRING' && authMode !== 'API_KEY_FILE' && attempts.KEYRING === 'login-failed';
2268
-
2269
- if (isLoginFailed && ensureDevbridgeKey) {
2270
- // key 失效(缓存里有 key 但 login 失败)→ 清缓存重建
2271
- try {
2272
- const { recreateDevbridgeKey } = await import('./devbridge-key.mjs');
2273
- const { apiKey } = await recreateDevbridgeKey(poolType || 'ephemeral');
2274
- const injectScript = buildKeyringInjectScript(apiKey);
2275
- await execOneShot(workspaceId, injectScript, username, 15000);
2276
- const healResult = await execOneShot(workspaceId, authScript, username, 30000);
2277
- const healParsed = parseDevbridgeAuthOutput(healResult.stdout);
2278
- if (healParsed.authMode === 'API_KEY_KEYRING' || healParsed.authMode === 'API_KEY_FILE') {
2279
- effectiveAuthMode = 'API_KEY_AUTO';
2280
- }
2281
- } catch {
2282
- // 自愈失败 → 走泛化降级
2283
- }
2284
- }
2285
-
2286
- if (effectiveAuthMode !== 'API_KEY_KEYRING' && effectiveAuthMode !== 'API_KEY_FILE' && ensureDevbridgeKey) {
2287
- // keyring/文件均无 key → host 调 relay API 自动创建 → 注入沙箱 → 重跑 probe
2288
- try {
2289
- const { apiKey } = await ensureDevbridgeKey(poolType || 'ephemeral');
2290
- const injectScript = buildKeyringInjectScript(apiKey);
2291
- await execOneShot(workspaceId, injectScript, username, 15000);
2292
- const authResult2 = await execOneShot(workspaceId, authScript, username, 30000);
2293
- const parsed2 = parseDevbridgeAuthOutput(authResult2.stdout);
2294
- if (parsed2.authMode === 'API_KEY_KEYRING' || parsed2.authMode === 'API_KEY_FILE') {
2295
- effectiveAuthMode = 'API_KEY_AUTO';
2296
- }
2297
- } catch (error) {
2298
- // 自动创建失败(含配额满 13002)→ 结构化降级
2299
- if (error.code === 'HDKIT_DEVBRIDGE_KEY_QUOTA_EXCEEDED') {
2300
- const keysHint = listKeysForQuotaHint ? await listKeysForQuotaHint() : [];
2301
- return {
2302
- ok: false,
2303
- error: error.message,
2304
- error_code: 'HDKIT_DEVBRIDGE_KEY_QUOTA_EXCEEDED',
2305
- authMode: authMode || 'UNKNOWN',
2306
- attempts,
2307
- currentKeys: keysHint,
2308
- hint:
2309
- 'API Key 数量已达上限。请到控制台清理不再使用的 key:' +
2310
- 'https://devstation.connect.huaweicloud.com/space/devbridge/apikey\n' +
2311
- 'devkit-* 开头的是插件自动管理的 key(删除后会自动重建),可优先清理其他闲置 key。',
2312
- };
2313
- }
2314
- // 其他自动创建失败 → 继续走原有降级路径(可能 keyring/file 后续可用)
2315
- }
2316
- }
2317
-
2318
- if (
2319
- effectiveAuthMode !== 'API_KEY_KEYRING' &&
2320
- effectiveAuthMode !== 'API_KEY_FILE' &&
2321
- effectiveAuthMode !== 'API_KEY_AUTO'
2322
- ) {
2323
- const loginOutput = String(authResult.stdout || '') + String(authResult.stderr || '');
2324
- return {
2325
- ok: false,
2326
- error: 'DevBridge authentication failed: no usable credential in the sandbox.',
2327
- authMode: authMode || 'UNKNOWN',
2328
- attempts,
2329
- hint:
2330
- 'No DevBridge API Key is available in this sandbox. Suggested next steps:\n' +
2331
- '1) Re-run huaweicloud_sandbox_credentials, then retry huaweicloud_sandbox_expose_tunnel.\n' +
2332
- '2) If auto-creation failed due to quota (20 key limit), clean up unused keys at ' +
2333
- 'https://devstation.connect.huaweicloud.com/space/devbridge/apikey, then retry.\n' +
2334
- '3) The "attempts" field shows which tiers were tried and why they failed — include it when escalating.',
2335
- loginOutput,
2336
- };
2337
- }
2338
-
2339
- // Selective pre-clean: remove same-port tunnels + orphan records/hosts only.
2340
- // Other ports and keepalive-protected tunnels are preserved.
2341
- const validatedCleanupMode = normalizeCleanupMode(cleanupMode);
2342
- try {
2343
- await cleanupDevbridgeTunnels(workspaceId, {
2344
- mode: validatedCleanupMode,
2345
- samePort: validatedPort,
2346
- username,
2347
- });
2348
- } catch {}
2349
-
2350
- let result = null;
2351
- let attempt = 0;
2352
- let lastQuotaCleanup = null;
2353
- const maxAttempts = 4;
2354
- while (attempt < maxAttempts) {
2355
- attempt += 1;
2356
- const exposeScript = buildDevbridgeExposeScript(validatedPort, validatedExpiryHours);
2357
- result = await execOneShot(workspaceId, exposeScript, username, timeoutMs);
2358
- const parsed = parseDevbridgeExposeOutput(result.stdout);
2359
-
2360
- // 10006 quota exceeded: remove orphan tunnels first, then the oldest non-protected
2361
- // live tunnel (one per retry) until the new tunnel fits. Never touches keepalive keys.
2362
- if (parsed.quotaError && attempt < maxAttempts) {
2363
- const quotaCleanup = await cleanupDevbridgeTunnels(workspaceId, {
2364
- mode: 'quota',
2365
- samePort: validatedPort,
2366
- maxExtra: 1,
2367
- username,
2368
- }).catch(() => null);
2369
- lastQuotaCleanup = quotaCleanup || lastQuotaCleanup;
2370
- // Kill-only progress frees no tunnel quota; only a deleted record can.
2371
- if (quotaCleanup?.deleteIds?.length) continue;
2372
- }
2373
- // Unreachable (000), migrated-gateway placeholder, or gateway-level tunnel errors
2374
- // (404 "tunnel not found" / "port not configured"): one cleanup + rebuild retry.
2375
- // 502 "bad gateway" (host alive, local service down) also gets one retry to cover
2376
- // slow app starts.
2377
- const unreachable = parsed.httpCode === '000' || parsed.httpCode === '';
2378
- const migration = /服务已迁移/.test(String(result.stdout || ''));
2379
- const gatewayTunnelError = parsed.gatewayTunnelError === true;
2380
- const backendDown = parsed.badGateway === true;
2381
- if (unreachable || migration || gatewayTunnelError || backendDown) {
2382
- if (attempt === 1) {
2383
- try {
2384
- // Only the same-port tunnel + orphans; other ports/sessions stay untouched.
2385
- await cleanupDevbridgeTunnels(workspaceId, {
2386
- mode: 'stale',
2387
- samePort: validatedPort,
2388
- username,
2389
- });
2390
- } catch {}
2391
- continue;
2392
- }
2393
- // Retry exhausted: a URL the gateway itself reports as dead (or one pointing at
2394
- // the retired pre-migration gateway) must NOT be handed over as a working
2395
- // deployment link — previously this returned ok:true with a soft warning.
2396
- if (gatewayTunnelError || migration) {
2397
- return {
2398
- ok: false,
2399
- error: gatewayTunnelError
2400
- ? 'DevBridge gateway reports the fresh tunnel URL as dead (404 "tunnel not found" / "port not configured") — the host session is not registered on the gateway. A rebuild was already attempted.'
2401
- : 'DevBridge gateway serves a migration placeholder page (服务已迁移) — the URL points at the retired pre-migration gateway and cannot work.',
2402
- authMode,
2403
- httpCode: parsed.httpCode,
2404
- hostLog: String(result.stdout || '').slice(0, 400),
2405
- };
2406
- }
2407
- }
2408
-
2409
- const warnings = [];
2410
- if (parsed.quotaError && !parsed.tunnelUrl) {
2411
- return {
2412
- ok: false,
2413
- error:
2414
- 'DevBridge tunnel quota exceeded (10006) after cleanup. Keepalive-protected tunnels are preserved; ' +
2415
- 'remove unused tunnels or retry with cleanup_mode=all if a full reset is acceptable.',
2416
- error_code: 'devbridge_tunnel_quota_exceeded',
2417
- authMode: effectiveAuthMode,
2418
- attempts,
2419
- cleanup: lastQuotaCleanup || undefined,
2420
- warnings: 'tunnel quota (10006) still full after removing orphan/oldest non-protected tunnels',
2421
- hostLog: String(result.stdout || '').slice(0, 400),
2422
- };
2423
- }
2424
-
2425
- // #998: a host that never produced a Tunnel URL must NOT surface as ok:true
2426
- // with an undefined publicUrl — that reads as success and sends the caller
2427
- // chasing credentials/network/port while the real cause is the host/版本.
2428
- // Read the version back into the return body: in this incident a single
2429
- // version field would have saved the whole diagnosis.
2430
- if (!parsed.tunnelUrl) {
2431
- let noUrlVersion = authVersion;
2432
- try {
2433
- const versionResult = await execOneShot(
2434
- workspaceId,
2435
- `export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"; devbridge version 2>/dev/null | head -1`,
2436
- username,
2437
- 15000,
2438
- );
2439
- noUrlVersion = String(versionResult.stdout || '').trim() || authVersion;
2440
- } catch {}
2441
- const noUrlCheck = evaluateDevbridgeVersion(noUrlVersion);
2442
- if (noUrlCheck.blocked) {
2443
- warnings.push(
2444
- `devbridge version is ${noUrlVersion} — too old to serve tunnels; upgrade per Step 0 before retrying.`,
2445
- );
2446
- }
2447
- return {
2448
- ok: false,
2449
- error: noUrlCheck.blocked
2450
- ? noUrlCheck.error
2451
- : `Failed to expose a working DevBridge tunnel: the host log contains no Tunnel URL (HTTP probe code ${parsed.httpCode || '000'}) — the host did not start. Check the hostLog below for the real cause.`,
2452
- error_code: noUrlCheck.blocked ? 'devbridge_too_old' : 'no_tunnel_url',
2453
- version: noUrlVersion || undefined,
2454
- httpCode: parsed.httpCode,
2455
- authMode,
2456
- ...(noUrlCheck.blocked ? { remediation: noUrlCheck.remediation } : {}),
2457
- hostLog: String(result.stdout || '').slice(0, 400),
2458
- };
2459
- }
2460
-
2461
- // #919: re-verify with a real GET from a SECOND, independent exec session.
2462
- // The in-session health check above cannot prove the host survived session
2463
- // teardown (setsid/nohup/disown make that likely, not certain). When the
2464
- // fresh-session GET fails, the URL will die with the deploying session —
2465
- // say so explicitly instead of returning a link the visitor cannot open.
2466
- let verifyHttpCode = '';
2467
- let verifyNotFound = false;
2468
- let persistent = undefined;
2469
- if (parsed.tunnelUrl) {
2470
- try {
2471
- const verifyResult = await execOneShot(
2472
- workspaceId,
2473
- buildDevbridgeVerifyScript(parsed.tunnelUrl),
2474
- username,
2475
- 30000,
2476
- );
2477
- // #922 (B1): parse with the dedicated verify parser — the
2478
- // DB_VERIFY_HTTP_CODE key is not visible to parseDevbridgeExposeOutput.
2479
- const verify = parseDevbridgeVerifyOutput(verifyResult.stdout);
2480
- verifyHttpCode = verify.httpCode || '';
2481
- // #922 (B2): a native false-success form answers HTTP 200 with a
2482
- // "tunnel not found" body — treat it as non-persistent.
2483
- verifyNotFound = verify.notFound;
2484
- } catch {}
2485
- // 000 = the fresh session could not reach the tunnel (host already dead
2486
- // or gateway not serving); 200 with a "tunnel not found" body = the
2487
- // gateway answered but the tunnel is gone; anything non-200/304 is
2488
- // surfaced as-is below.
2489
- persistent = verifyHttpCode !== '' && verifyHttpCode !== '000' && !verifyNotFound;
2490
- if (!persistent) {
2491
- if (verifyNotFound) {
2492
- warnings.push(
2493
- '复测返回 HTTP 200 但 body 为 "tunnel not found"(原生假成功形态),隧道实际未生效,请勿分享 (the recheck answered HTTP 200 with a "tunnel not found" body — the tunnel is NOT serving; do NOT share this URL).',
2494
- );
2495
- } else {
2496
- warnings.push(
2497
- '隧道将在会话结束后失效,请勿分享 (the tunnel did NOT survive an independent exec-session recheck — do NOT share this URL; the host process is not persistent).',
2498
- );
2499
- }
2500
- }
2501
- }
2502
-
2503
- // A2 (#935): the reachability warning uses the FINAL probe's HTTP status —
2504
- // intermediate 502/000 probes (gateway not ready yet) must not leak into
2505
- // the verdict, and a sequence of 502/000 → 200 must NOT warn.
2506
- if (parsed.badGateway)
2507
- warnings.push(
2508
- 'Tunnel reachable but the gateway reports "bad gateway" — the local service on the exposed port is not serving.',
2509
- );
2510
- const reachabilityWarning = formatTunnelReachabilityWarning(parsed.httpCode);
2511
- if (reachabilityWarning) warnings.push(reachabilityWarning);
2512
- const expiresAt =
2513
- parsed.expiryHours !== undefined
2514
- ? new Date(Date.now() + parsed.expiryHours * 3_600_000).toISOString()
2515
- : undefined;
2516
-
2517
- // AUTO-ENROLL: every tunnel exposed through this tool is enrolled into the
2518
- // keepalive watchdog by default (user requirement: all devbridge tunnels
2519
- // deployed to the sandbox must be keepalive-protected — unattended renewal
2520
- // + host re-attach + health check). The new tunnel is MERGED into the
2521
- // existing watchdog tunnel list, never replacing other tunnels' coverage.
2522
- // keepalive:false opts out. Non-fatal: an enrollment failure is surfaced
2523
- // as a warning, not a failed expose — the tunnel itself is working.
2524
- let keepaliveEnrollment = undefined;
2525
- if (keepalive !== false && parsed.tunnelUrl && parsed.tunnelId) {
2526
- try {
2527
- const readResult = await execOneShot(workspaceId, buildKeepaliveTunnelsReadScript(), username, 20000);
2528
- const existing = parseKeepaliveTunnelsOutput(readResult.stdout);
2529
- const merged = mergeKeepaliveTunnels(existing, [{ tunnelId: parsed.tunnelId, url: parsed.tunnelUrl }]);
2530
- keepaliveEnrollment = await installKeepaliveWatchdog(workspaceId, { tunnels: merged }, username, 30000);
2531
- if (!keepaliveEnrollment.ok) {
2532
- warnings.push(
2533
- `Keepalive watchdog enrollment failed: ${keepaliveEnrollment.error || 'unknown error'} — the tunnel works but will NOT be auto-renewed. Retry with huaweicloud_sandbox_keepalive_watchdog.`,
2534
- );
2535
- }
2536
- } catch (error) {
2537
- warnings.push(
2538
- `Keepalive watchdog enrollment failed (${error?.message || 'unknown error'}) — the tunnel works but will NOT be auto-renewed. Retry with huaweicloud_sandbox_keepalive_watchdog.`,
2539
- );
2540
- }
2541
- }
2542
-
2543
- // 交付地址时必须播报沙箱存活期(隧道有效期 ≠ 沙箱存活期;keepalive 只保隧道不保沙箱)
2544
- const lifetimeNotice = buildExposeLifetimeNotice(poolContext, parsed.expiryHours);
2545
- if (lifetimeNotice) warnings.push(lifetimeNotice.warning);
2546
-
2547
- return {
2548
- ok: true,
2549
- publicUrl: parsed.tunnelUrl || undefined,
2550
- port: validatedPort,
2551
- ...(lifetimeNotice
2552
- ? { sandboxLifetime: lifetimeNotice.sandboxLifetime, urlLifetimeHint: lifetimeNotice.urlLifetimeHint }
2553
- : {}),
2554
- tunnelId: parsed.tunnelId || undefined,
2555
- // 报告最终生效的认证方式:自动创建兜底成功后应为 API_KEY_AUTO(而非首轮 probe 的 NO_CREDENTIAL)
2556
- authMode: effectiveAuthMode,
2557
- httpCode: parsed.httpCode,
2558
- verifyHttpCode: verifyHttpCode || undefined,
2559
- verifyNotFound: verifyNotFound || undefined,
2560
- persistent,
2561
- expiresAt,
2562
- expiresInHours: parsed.expiryHours,
2563
- keepalive: keepaliveEnrollment
2564
- ? {
2565
- enrolled: keepaliveEnrollment.ok === true,
2566
- tunnelCount: keepaliveEnrollment.ok ? (keepaliveEnrollment.tunnels || []).length : undefined,
2567
- watchdogPid: keepaliveEnrollment.watchdogPid,
2568
- logPath: keepaliveEnrollment.logPath,
2569
- error: keepaliveEnrollment.ok ? undefined : keepaliveEnrollment.error,
2570
- }
2571
- : undefined,
2572
- warnings: warnings.length > 0 ? warnings.join(' ') : undefined,
2573
- hostLog: String(result.stdout || '').slice(0, 400),
2574
- };
2575
- }
2576
-
2577
- return {
2578
- ok: false,
2579
- error: 'Failed to expose a working DevBridge tunnel after retries.',
2580
- authMode,
2581
- hostLog: String(result?.stdout || '').slice(0, 400),
2582
- };
2583
- }
2584
-
2585
- export async function closeAllSessions() {
2586
- for (const [key, session] of sessions) {
2587
- sessions.delete(key);
2588
- try {
2589
- session.close();
2590
- } catch {}
2591
- }
2592
- }
2593
-
2594
- export { getCurrentWorkspaceId, setWorkspaceId, runNodeExec };