huaweicloud-devkit 2.0.0-next.3 → 2.0.0-next.4

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 (161) hide show
  1. package/README.md +3 -1
  2. package/package.json +3 -1
  3. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +16 -3
  4. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +16 -3
  5. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +16 -3
  6. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +16 -3
  7. package/plugins/huaweicloud-core/.mcp.json +55 -1
  8. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +16 -3
  9. package/plugins/huaweicloud-core/dist/agents/codex-config.js +374 -0
  10. package/plugins/huaweicloud-core/dist/agents/codex-desktop.js +8 -1
  11. package/plugins/huaweicloud-core/dist/agents/codex.js +9 -0
  12. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +141 -86
  13. package/plugins/huaweicloud-core/dist/agents/opencode.js +106 -39
  14. package/plugins/huaweicloud-core/dist/approval-gate.js +1185 -0
  15. package/plugins/huaweicloud-core/dist/approval-ledger.js +2331 -0
  16. package/plugins/huaweicloud-core/dist/approval-roster.js +89 -0
  17. package/plugins/huaweicloud-core/dist/approval-types.js +1 -0
  18. package/plugins/huaweicloud-core/dist/approvals-cli.js +4 -4
  19. package/plugins/huaweicloud-core/dist/data/icons-manifest.v1.json +23 -5
  20. package/plugins/huaweicloud-core/dist/dep/receipts.js +65 -5
  21. package/plugins/huaweicloud-core/dist/hcloud-cli.js +1 -1
  22. package/plugins/huaweicloud-core/dist/hcloud-plan.js +62 -61
  23. package/plugins/huaweicloud-core/dist/lib/approval-mode.js +7 -5
  24. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +18 -4
  25. package/plugins/huaweicloud-core/dist/lib/call-trace.js +7 -14
  26. package/plugins/huaweicloud-core/dist/lib/confirm-language.js +50 -0
  27. package/plugins/huaweicloud-core/dist/lib/credentials.js +9 -9
  28. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkit-gate.js +1398 -0
  29. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +362 -32
  30. package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +6 -16
  31. package/plugins/huaweicloud-core/dist/lib/opencode-ask-rule.js +224 -78
  32. package/plugins/huaweicloud-core/dist/lib/opencode-saved-perms.js +282 -0
  33. package/plugins/huaweicloud-core/dist/lib/supplemental-redaction.js +116 -0
  34. package/plugins/huaweicloud-core/dist/lib/tool-schema-parts.js +31 -0
  35. package/plugins/huaweicloud-core/dist/lib/workspace-glob.js +442 -0
  36. package/plugins/huaweicloud-core/dist/mcp-config-io.js +28 -1
  37. package/plugins/huaweicloud-core/dist/mcp-protocol.js +68 -16
  38. package/plugins/huaweicloud-core/dist/mcp-server.js +6506 -912
  39. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  40. package/plugins/huaweicloud-core/dist/mcp-stdio-transport.js +14 -4
  41. package/plugins/huaweicloud-core/dist/packs/auth/approval.js +249 -0
  42. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +44 -44
  43. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +85 -130
  44. package/plugins/huaweicloud-core/dist/packs/obs/approval.js +110 -0
  45. package/plugins/huaweicloud-core/dist/packs/obs/tools.js +7 -2
  46. package/plugins/huaweicloud-core/dist/packs/registry.js +19 -1
  47. package/plugins/huaweicloud-core/dist/packs/sandbox/approval.js +245 -0
  48. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +156 -23
  49. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +13 -1
  50. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-hwexec.js +136 -0
  51. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +11 -1
  52. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +1 -0
  53. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +79 -9
  54. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +28 -9
  55. package/plugins/huaweicloud-core/dist/packs/secrets/approval.js +46 -0
  56. package/plugins/huaweicloud-core/dist/packs/secrets/tools.js +4 -1
  57. package/plugins/huaweicloud-core/dist/packs/update/approval.js +79 -0
  58. package/plugins/huaweicloud-core/dist/packs/update/tools.js +8 -1
  59. package/plugins/huaweicloud-core/dist/packs/voucher/tools.js +1 -1
  60. package/plugins/huaweicloud-core/dist/packs-configure.js +74 -0
  61. package/plugins/huaweicloud-core/dist/safety/classify-text.js +36 -0
  62. package/plugins/huaweicloud-core/dist/safety/policy.js +2 -0
  63. package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +1 -1
  64. package/plugins/huaweicloud-core/dist/sandbox/devbridge-auth.js +65 -14
  65. package/plugins/huaweicloud-core/dist/sandbox/devbridge-cleanup.js +422 -0
  66. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose-flow.js +66 -16
  67. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose.js +13 -10
  68. package/plugins/huaweicloud-core/dist/sandbox/devbridge-keepalive.js +42 -2
  69. package/plugins/huaweicloud-core/dist/sandbox/devbridge-key.js +11 -3
  70. package/plugins/huaweicloud-core/dist/sandbox/devbridge-tunnel.js +6 -0
  71. package/plugins/huaweicloud-core/dist/sandbox/devbridge-validation.js +10 -1
  72. package/plugins/huaweicloud-core/dist/sandbox/hwexec-task.js +244 -0
  73. package/plugins/huaweicloud-core/dist/setup-cli.js +36 -1
  74. package/plugins/huaweicloud-core/dist/tool-definitions.js +9 -1
  75. package/plugins/huaweicloud-core/dist/tool-schemas.js +32 -6
  76. package/plugins/huaweicloud-core/dist/tools.js +76 -9
  77. package/plugins/huaweicloud-core/dist/update-registry.js +358 -5
  78. package/plugins/huaweicloud-core/dist/update-upgrade.js +1083 -14
  79. package/plugins/huaweicloud-core/dist/vendor-gate.js +2 -2
  80. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +150 -1
  81. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +53 -3
  82. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  83. package/plugins/huaweicloud-core/safety/policy.json +18 -11
  84. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +114 -10
  85. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +190 -138
  86. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +36 -12
  87. package/plugins/huaweicloud-core/skills/huawei-voucher/SKILL.md +2 -0
  88. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +2 -2
  89. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +11 -7
  90. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +74 -29
  91. package/plugins/huaweicloud-core/skills/huaweicloud-troubleshooting/SKILL.md +21 -19
  92. package/plugins/huaweicloud-core/src/agents/codex-config.ts +432 -0
  93. package/plugins/huaweicloud-core/src/agents/codex-desktop.ts +8 -1
  94. package/plugins/huaweicloud-core/src/agents/codex.ts +10 -0
  95. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +176 -88
  96. package/plugins/huaweicloud-core/src/agents/opencode.ts +125 -54
  97. package/plugins/huaweicloud-core/src/approval-gate.ts +1306 -0
  98. package/plugins/huaweicloud-core/src/approval-ledger.ts +2446 -0
  99. package/plugins/huaweicloud-core/src/approval-roster.ts +127 -0
  100. package/plugins/huaweicloud-core/src/approval-types.ts +237 -0
  101. package/plugins/huaweicloud-core/src/approvals-cli.ts +4 -4
  102. package/plugins/huaweicloud-core/src/data/icons-manifest.v1.json +23 -5
  103. package/plugins/huaweicloud-core/src/dep/receipts.ts +84 -5
  104. package/plugins/huaweicloud-core/src/hcloud-cli.ts +3 -0
  105. package/plugins/huaweicloud-core/src/hcloud-plan.ts +68 -70
  106. package/plugins/huaweicloud-core/src/lib/approval-mode.ts +7 -5
  107. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +19 -4
  108. package/plugins/huaweicloud-core/src/lib/call-trace.ts +7 -17
  109. package/plugins/huaweicloud-core/src/lib/confirm-language.ts +51 -0
  110. package/plugins/huaweicloud-core/src/lib/credentials.ts +9 -8
  111. package/plugins/huaweicloud-core/src/lib/hdkit/hdkit-gate.ts +1428 -0
  112. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +377 -30
  113. package/plugins/huaweicloud-core/src/lib/hdkit/sandbox-pool.ts +8 -15
  114. package/plugins/huaweicloud-core/src/lib/opencode-ask-rule.ts +302 -83
  115. package/plugins/huaweicloud-core/src/lib/opencode-saved-perms.ts +354 -0
  116. package/plugins/huaweicloud-core/src/lib/supplemental-redaction.ts +129 -0
  117. package/plugins/huaweicloud-core/src/lib/tool-schema-parts.ts +40 -0
  118. package/plugins/huaweicloud-core/src/lib/workspace-glob.ts +414 -0
  119. package/plugins/huaweicloud-core/src/mcp-config-io.ts +27 -1
  120. package/plugins/huaweicloud-core/src/mcp-protocol.ts +81 -17
  121. package/plugins/huaweicloud-core/src/mcp-server.ts +7 -7
  122. package/plugins/huaweicloud-core/src/mcp-stdio-transport.ts +14 -4
  123. package/plugins/huaweicloud-core/src/packs/auth/approval.ts +302 -0
  124. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +54 -45
  125. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +99 -137
  126. package/plugins/huaweicloud-core/src/packs/obs/approval.ts +122 -0
  127. package/plugins/huaweicloud-core/src/packs/obs/tools.ts +7 -2
  128. package/plugins/huaweicloud-core/src/packs/registry.ts +42 -1
  129. package/plugins/huaweicloud-core/src/packs/sandbox/approval.ts +296 -0
  130. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +168 -23
  131. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +11 -1
  132. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-hwexec.ts +228 -0
  133. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +11 -1
  134. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +1 -0
  135. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +100 -8
  136. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +31 -8
  137. package/plugins/huaweicloud-core/src/packs/secrets/approval.ts +50 -0
  138. package/plugins/huaweicloud-core/src/packs/secrets/tools.ts +4 -1
  139. package/plugins/huaweicloud-core/src/packs/update/approval.ts +87 -0
  140. package/plugins/huaweicloud-core/src/packs/update/tools.ts +8 -1
  141. package/plugins/huaweicloud-core/src/packs/voucher/tools.ts +1 -1
  142. package/plugins/huaweicloud-core/src/packs-configure.ts +75 -0
  143. package/plugins/huaweicloud-core/src/safety/classify-text.ts +40 -0
  144. package/plugins/huaweicloud-core/src/safety/policy.ts +7 -0
  145. package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +1 -1
  146. package/plugins/huaweicloud-core/src/sandbox/devbridge-auth.ts +74 -14
  147. package/plugins/huaweicloud-core/src/sandbox/devbridge-cleanup.ts +509 -0
  148. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose-flow.ts +70 -18
  149. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose.ts +26 -10
  150. package/plugins/huaweicloud-core/src/sandbox/devbridge-keepalive.ts +41 -2
  151. package/plugins/huaweicloud-core/src/sandbox/devbridge-key.ts +9 -3
  152. package/plugins/huaweicloud-core/src/sandbox/devbridge-tunnel.ts +24 -0
  153. package/plugins/huaweicloud-core/src/sandbox/devbridge-validation.ts +11 -1
  154. package/plugins/huaweicloud-core/src/sandbox/hwexec-task.ts +304 -0
  155. package/plugins/huaweicloud-core/src/setup-cli.ts +39 -1
  156. package/plugins/huaweicloud-core/src/tool-definitions.ts +9 -1
  157. package/plugins/huaweicloud-core/src/tool-schemas.ts +39 -6
  158. package/plugins/huaweicloud-core/src/tools.ts +124 -10
  159. package/plugins/huaweicloud-core/src/update-registry.ts +340 -5
  160. package/plugins/huaweicloud-core/src/update-upgrade.ts +1130 -14
  161. package/plugins/huaweicloud-core/src/vendor-gate.ts +2 -2
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: huawei-sandbox
3
- description: 'Use when creating, connecting, or managing Huawei Cloud Sandbox instances and workspace terminals, or when a Huawei Cloud task needs a temporary runtime to deploy, run, or preview a web application. A request that names no cloud vendor is not thereby a Huawei Cloud task: when the vendor is unknown and cannot be inferred, ask which cloud the user means before routing here — deployment/website vocabulary alone is not vendor evidence. Cloud-facing tools take a vendorConfirmed parameter — pass the user’s establishing words, never an invented quote. Covers sandbox lifecycle (check-user, sign-agreement, connect, release), session-based terminal execution, and credential injection. Triggers on: sandbox, workspace, terminal, web app deployment, deploy web app, preview app, deploy github, github repo, deploy repo, website, static site, web application, backend service, 工作台, workbench, full-stack, 全栈, CRUD 应用, database-backed REST API, PostgREST, postgres, hwlink, devstation, hdkitservice, remote exec. NOT for: ECS instances (use huawei-ecs), CCE clusters (use huawei-cce).'
3
+ description: 'Use when creating, connecting, or managing Huawei Cloud Sandbox instances and workspace terminals, or when a Huawei Cloud task needs a temporary runtime to deploy, run, or preview a web application. A request that names no cloud vendor is not thereby a Huawei Cloud task: when the vendor is unknown and cannot be inferred, ask which cloud the user means before routing here — deployment/website vocabulary alone is not vendor evidence. Cloud-facing tools take a vendorConfirmed parameter — pass the user’s establishing words, never an invented quote. Covers sandbox lifecycle (check-user, sign-agreement, connect, shutdown, release), session-based terminal execution, and credential injection. Triggers on: sandbox, workspace, terminal, web app deployment, deploy web app, preview app, deploy github, github repo, deploy repo, website, static site, web application, backend service, 工作台, workbench, full-stack, 全栈, CRUD 应用, database-backed REST API, PostgREST, postgres, hwlink, devstation, hdkitservice, remote exec. NOT for: ECS instances (use huawei-ecs), CCE clusters (use huawei-cce).'
4
4
  version: 1
5
5
  ---
6
6
 
@@ -45,38 +45,94 @@ Hard rules:
45
45
  - **Pre-code checkpoint (MANDATORY)**: before uploading or writing ANY application code, verify the backend choice matches this gate. If an SPA-only deployment already started and persistence turns out to be implied, STOP, tell the developer, and redirect to the full-stack path — do not paper over it with a bolted-on static backend.
46
46
  - After the choice: PostgREST → follow [Full-Stack: REST API over PostgreSQL](#full-stack-rest-api-over-postgresql-postgrest) **FIRST** (backend before any frontend code), then continue with the web deployment steps; 自带后端 / 纯静态 → continue with [Web Application Deployment](#web-application-deployment).
47
47
 
48
+ ## Pool-Selection Gate (MANDATORY — do not skip)
49
+
50
+ Before `huaweicloud_sandbox_connect`, select the pool by **task intent**, not by tech stack. Default is `ephemeral`.
51
+
52
+ ### 1. Default ephemeral
53
+
54
+ - Preview / demo / trial / one-off / sensitive burn-after-use → `ephemeral`, even for full-stack or DB-backed projects.
55
+ - A DB/full-stack stack is only a capability hint; it does not by itself require persistence.
56
+
57
+ ### 2. Persistent only with explicit or confirmed long-term intent
58
+
59
+ Use `persistent` only when:
60
+
61
+ - the developer explicitly says long-term / cross-day / resume later / keep data / development workbench; or
62
+ - you infer a workbench/long-term task from the conversation, but the developer did not say it explicitly → ask once before connecting.
63
+
64
+ If the intent is ambiguous, ask exactly one question:
65
+
66
+ > 这个任务需要跨会话保留数据吗?① 临时预览/一次性(默认,非持久化) ② 长期/跨天继续(持久化)
67
+
68
+ ### 3. Task continuity
69
+
70
+ - Same task / same deployment follow-up: keep the current pool; do not re-evaluate mid-task.
71
+ - New task: re-evaluate. A new preview stays `ephemeral` even if a persistent sandbox already exists.
72
+ - If the new preview might reuse the existing environment/data, ask once:
73
+ > 已有持久化沙箱,是否直接复用(保留现有环境/数据),还是新建临时预览环境?
74
+ - Switching pools does not migrate data; tell the developer.
75
+
76
+ ### 4. Never
77
+
78
+ - Never select `persistent` merely because the project is full-stack or DB-backed.
79
+ - Never switch pool silently mid-task.
80
+ - Never ask the pool question when the intent is already explicit.
81
+
48
82
  ## Overview
49
83
 
50
84
  Domain expertise for Huawei Cloud Sandbox (DevStation) instances and workspace terminal execution. Covers sandbox lifecycle via hdkitservice API and remote terminal command execution via hwlink protocol.
51
85
 
86
+ ## Approval gate (the nine mutating tools)
87
+
88
+ The mutating sandbox tools run through the devkit approval gate. Gated: `connect`, `exec_with_session`, `exec_one_shot`, `expose_tunnel`, `renew_tunnel`, `keepalive_watchdog`, `sign_agreement`, `credentials`, `shutdown`. Not gated: `check_user`, `exec_poll`, `close_session`, `upload_file`, `upload_project`, `deploy_nginx`, `deploy_check`.
89
+
90
+ - **connect / shutdown / the tunnel faces / sign_agreement / credentials confirm on every call.** There is no content rule that exempts them. A first call returns `USER_CONFIRMATION_REQUIRED` with a minted `approvalToken` (token mode) or raises the confirmation form / chat envelope (ask mode). Tell the user the approve line (`npx huaweicloud-devkit approve <token>`), wait, then retry the same call with `approvalToken` and `approvedByUser: true`. Never sign the agreement or inject credentials without the user's explicit approval — the gate now enforces mechanically what this skill always demanded.
91
+ - **The exec tools are content-classified.** A benign command (`ls`, `npm install`, `mkdir`, builds) runs with NO confirmation surface at all. A write-classified command (an `hcloud` write through the terminal, anything the text classifier marks write/execution) confirms on every call. The strict engine REFUSES, with the rule named and no confirmation able to unlock it, the families its rows cover: credential-file reads (`cat ~/.huaweicloud/config.json`, `env` dumps), recursive forced rm in any combined-flag spelling — `rm -rf`/`-fr`, flags interposed (`rm -v -rf x`) or after the target, `--`, quoted (`"dist"`/`'dist'`), glob (`dist/*`), `$VAR` (including `$PWD`), dot-prefixed names (`.git`, `.next`, `.cache`), `.`, `..`, `~`, `$HOME`, `*`, and `--no-preserve-root` — `find` with `-delete`, pipelines sweeping files into rm (`ls | xargs rm -rf`), downloads piped into a shell (`curl|wget … | bash|sh`), disk format, and shutdown commands. The refusal set is those rows and nothing more: a command outside them is NOT silently stopped, so prefer targeted deletions (rm with exact file names, no combined -rf flag) yourself — and treat any refusal as a boundary to rework, never a prompt to retry.
92
+ - **The retry memo.** When an approved exec's delivery was uncertain (the call threw, completion unknowable), a byte-identical retry reuses the prior consent and the response carries `approvedVia: "retry-uncertain"` — no second confirmation. A delivered call clears the memo: the same command again confirms like any first call. Different arguments always confirm again. The memo lives in the devkit server process: after a restart the same command confirms again.
93
+ - **Session standing consent (ask mode).** The confirmation form offers "Remember for this session"; when the user ticks it, identical later calls run without asking (`approvedVia: "standing-session"`) until the devkit server restarts.
94
+
95
+ Never fabricate `approvedByUser: true`, never run the approve or pin verbs yourself, and never treat a strict-classification refusal as something a confirmation could unlock. The full contract: the safety skill's `references/approvals.md`.
96
+
97
+ **Bash-face widening (operator-approved).** The same destructive rows also apply to the agent's own Bash face through the safety hook: unanchored recursive rm — any combined-flag spelling, including `rm -rf node_modules` and the quoted/glob/`$VAR` forms — and `find … -delete` now deny there too. The operator chose the safe direction: a false deny on the agent face costs one rephrased command, a miss costs the workspace. A human's own terminal is unaffected — the hook gates the agent face only.
98
+
52
99
  ## 两池沙箱(pool_type)
53
100
 
54
101
  > 口径基调:一切以实测为准,口头支持不作数(下表生命周期为实测/平台侧现状;数值为服务端配置下发的默认口径,平台调参以服务端回显为准)。
55
102
 
56
- `huaweicloud_sandbox_connect` 用 `pool_type` 选择资源池(服务端权威映射模板;**没有 persist_mode 参数**——上游参数面仅 template_id/flavor_id):
103
+ `huaweicloud_sandbox_connect` 用 `pool_type` 选择资源池(服务端权威映射模板;**没有 persist_mode 参数**;客户端不再支持传 template_id/自定义模板):
104
+
105
+ > 下表生命周期数值仅用于内部选池与诊断:persistent 只播报沙箱生命周期与核时提醒;ephemeral 数值只在下文 **TTL 播报** 的时机与口径内提示,其余场合不向开发者播报。
57
106
 
58
107
  | pool_type | 语义 | 生命周期(平台策略) | 适用 |
59
108
  | ------------------- | ------------------ | ------------------------------------------------------------ | --------------------------- |
60
109
  | `ephemeral`(默认) | 非持久沙箱 | 闲置 30 分钟自动关机 + 闲置 1 小时自动删除(平台定时任务) | 临时运行/预览,勿存重要数据 |
61
110
  | `persistent` | 持久沙箱(EVS 盘) | 数据跨关机保留;闲置 1 小时自动关机;闲置回收保留期上限 7 天 | 需要跨会话保留数据 |
62
111
 
63
- Selection rules(agent 按意图自动选池,开发者可覆盖;意图不明确时呈现两类供选择):
64
-
65
- | 意图 / 场景 | pool_type | 理由 |
66
- | ------------------------- | ---------- | ----------------------------------- |
67
- | 预览 / 试用 / demo | ephemeral | 用完即弃,无需保留状态 |
68
- | 一次性任务(跑完即弃) | ephemeral | 结果带出沙箱;实例随闲置回收 |
69
- | 敏感内容(即焚) | ephemeral | 闲置 1 小时自动删除,数据随实例消亡 |
70
- | 开发工作台 / workbench | persistent | 会话跨天;状态需跨关机保留 |
71
- | 带数据库项目(DB-backed) | persistent | 数据落在挂载的 EVS 盘(32G) |
72
- | 跨日评审 / 展示 | persistent | 评审者后续日期回访;实例保留 |
73
-
112
+ Selection rules(按意图自动选池;具体按 [Pool-Selection Gate](#pool-selection-gate-mandatory--do-not-skip) 执行;默认 `ephemeral`,`persistent` 需明确长期意图或确认;开发者可覆盖):
113
+
114
+ | 意图 / 场景 | pool_type | 理由 |
115
+ | ---------------------------- | ---------- | -------------------------------------- |
116
+ | 预览 / 试用 / demo | ephemeral | 用完即弃,无需保留状态 |
117
+ | 一次性任务(跑完即弃) | ephemeral | 结果带出沙箱;实例随闲置回收 |
118
+ | 敏感内容(即焚) | ephemeral | 闲置 1 小时自动删除,数据随实例消亡 |
119
+ | 带数据库但只是预览/演示 | ephemeral | 预览可重建数据;技术栈不是持久化触发器 |
120
+ | 开发工作台 / workbench | persistent | 会话跨天;状态需跨关机保留 |
121
+ | 带数据库且需要跨会话保留数据 | persistent | 数据落在挂载的 EVS 盘(32G) |
122
+ | 跨日评审 / 展示 | persistent | 评审者后续日期回访;实例保留 |
123
+
124
+ - **预览/一次性即使全栈/DB 也用 `ephemeral`**;技术栈不是持久化触发器
125
+ - **`persistent` 只能来自明确长期意图,或推断后确认**;不得仅因 full-stack/DB 选 persistent
126
+ - **同一任务沿用当前池**;新任务重新选型;新预览默认 `ephemeral`,必要时问一次是否复用已有 persistent
127
+ - **切换池数据不迁移**
74
128
  - **配额**:每用户每类型 1 台(1+1 可并存);同池 connect 自动复用已有实例
75
- - **429 双错误码**:`HDKIT_QUOTA_EXCEEDED`(账号配额满,重试无效→引导释放/复用);`HDKIT_CAPACITY_INSUFFICIENT`(池容量不足,服务端直接返回最终文案“DevKit 免费资源当前使用人数较多,建议您错峰使用,感谢理解!”,客户端不再附加引导)。响应带 `Retry-After`
129
+ - **429 三错误码**:`HDKIT_QUOTA_EXCEEDED`(账号配额满,重试无效→引导释放/复用);`HDKIT_TEMPLATE_QUOTA_EXCEEDED`(当前账号此类型沙箱运行中实例达上限,需关机/释放同类型实例后重试,无 `Retry-After`);`HDKIT_CAPACITY_INSUFFICIENT`(池容量不足,服务端直接返回最终文案“DevKit 免费资源当前使用人数较多,建议您错峰使用,感谢理解!”,客户端不再附加引导)。`HDKIT_QUOTA_EXCEEDED` / `HDKIT_CAPACITY_INSUFFICIENT` 响应带 `Retry-After: 60`
76
130
  - **TTL 播报**:仅 connect(会话首次连接 / 复用被唤醒 `started=true`)与 expose_tunnel(交付地址时)返回生命周期提示;其余执行类工具不逐次播报。**ephemeral 池部署的公网地址会随沙箱闲置关机失效**,向开发者交付 URL 时必须转述 `urlLifetimeHint` / `warnings` 中的存活期提示(隧道有效期 ≠ 沙箱存活期)。数值以服务端回显为准,缺失时用默认口径兜底
131
+ - **核时提醒(persistent 播报追加)**:persistent 池的生命周期播报(connect 的 `pool.ttl_hint` 与 expose_tunnel 的 `urlLifetimeHint`)追加「如暂时不需要使用,建议尽快关机,避免持续消耗核时;可以告诉我帮你关机(实例与数据盘保留,下次连接会自动唤醒)。」;ephemeral 播报不出现该提示
77
132
  - **烧核播报口径**:沙箱运行消耗核时,播报用「平台赠送 + 活动赚取」口径(非直接计费);账号核时耗尽(`HD.97520422`)时工具返回值给出友好引导
133
+ - **关机纪律**:仅当开发者明确要求关机时调用 `huaweicloud_sandbox_shutdown`;调用前确认一次,绝不自动关机。关机 ≠ 删除:只 close,不 delete,实例与 EVS 数据盘保留,下次 connect 自动唤醒。非持久化沙箱也可关机,但不主动提示;不要向开发者提“控制台关机”。
78
134
  - **删除纪律**:不向开发者暴露生命周期删除 API(回收走平台闲置策略 G1);开发者主动删除时必须二次确认(确认要删除?数据不可恢复);绝不做延后代删
79
- - 显式 `template_id` 优先于 `pool_type`(自定义模板场景)
135
+ - 不支持传 `template_id`;自定义模板已下线,客户端只传 `pool_type`
80
136
  - 完整口径、容量规划与 G 清单:[references/resource-pool.md](references/resource-pool.md)
81
137
 
82
138
  ## Activation
@@ -110,6 +166,7 @@ Selection rules(agent 按意图自动选池,开发者可覆盖;意图不
110
166
  | --------------------------------- | ---------------------------------------------------------------------------------------------------------------- |
111
167
  | `huaweicloud_sandbox_connect` | Connect to sandbox (one instance per user per pool; `pool_type` selects ephemeral/persistent, default ephemeral) |
112
168
  | `huaweicloud_sandbox_credentials` | Inject temporary AK/SK into a running sandbox |
169
+ | `huaweicloud_sandbox_shutdown` | Shut down a running sandbox (close only; instance/data disk retained; reconnect wakes it) |
113
170
 
114
171
  ### Tunnel Persistence (public URL lifetime)
115
172
 
@@ -121,53 +178,62 @@ Selection rules(agent 按意图自动选池,开发者可覆盖;意图不
121
178
 
122
179
  ### Terminal Execution
123
180
 
124
- | Tool | Purpose |
125
- | --------------------------------------- | --------------------------------------------------------------------------- |
126
- | `huaweicloud_sandbox_exec_with_session` | Session-based execution (state persists; best for interactive work) |
127
- | `huaweicloud_sandbox_exec_one_shot` | One-shot execution (fresh connection; best for long/heavy commands) |
128
- | `huaweicloud_sandbox_upload_file` | Upload a local file into the sandbox (chunked base64 write + md5 verify) |
129
- | `huaweicloud_sandbox_upload_project` | Upload a local project directory to sandbox (HTTP tunnel, tar.gz + extract) |
130
- | `huaweicloud_sandbox_deploy_nginx` | Deploy nginx config with permissions fix and reload in one call |
131
- | `huaweicloud_sandbox_deploy_check` | Run deployment completeness check (nginx, DevBridge, URL, QR if needed) |
132
- | `huaweicloud_sandbox_close_session` | Close a persistent terminal session |
181
+ | Tool | Purpose |
182
+ | --------------------------------------- | ----------------------------------------------------------------------------------------------- |
183
+ | `huaweicloud_sandbox_exec_with_session` | Session-based execution (state persists; best for interactive work) |
184
+ | `huaweicloud_sandbox_exec_one_shot` | One-shot execution (fresh connection; best for long/heavy commands — `mode: "async"` for >120s) |
185
+ | `huaweicloud_sandbox_exec_poll` | Poll an async task's verdict (done/running/lost/never/unknown) + log tail |
186
+ | `huaweicloud_sandbox_upload_file` | Upload a local file into the sandbox (chunked base64 write + md5 verify) |
187
+ | `huaweicloud_sandbox_upload_project` | Upload a local project directory to sandbox (HTTP tunnel, tar.gz + extract) |
188
+ | `huaweicloud_sandbox_deploy_nginx` | Deploy nginx config with permissions fix and reload in one call |
189
+ | `huaweicloud_sandbox_deploy_check` | Run deployment completeness check (nginx, DevBridge, URL, QR if needed) |
190
+ | `huaweicloud_sandbox_close_session` | Close a persistent terminal session |
133
191
 
134
192
  ### Tool Selection Guide
135
193
 
136
- | Scenario | Use | Why |
137
- | ---------------------------------- | ---------------------------------- | ------------------------------------------------------------ |
138
- | `cd`, env setup, command chains | `exec_with_session` | Needs shared shell state across calls |
139
- | `npm install`, `apt-get`, builds | `exec_one_shot` | Long-running (>30s), no state needed, more stable |
140
- | `curl`, health checks, quick tests | Either — `exec_one_shot` preferred | Stateless, fast |
141
- | Server startup (background) | `exec_with_session` | Need to `nohup ... &` then check output in same session |
142
- | Deployment scripts | `exec_one_shot+shot` | Long script, fresh connection avoids session timeouts |
143
- | nginx configuration | `deploy_nginx` | Auto-generates correct template + permissions + reload |
144
- | Deployment completeness check | `deploy_check` | Verifies nginx, DevBridge, URL, QR before reporting success |
145
- | Tunnel lifetime renewal | `renew_tunnel` | Rolling-window renewal, same URL stays alive |
146
- | URL must outlive the session | `keepalive_watchdog` | Unattended host re-attach + daily renewal + health check |
147
- | Single file upload (<1MB) | `upload_file` | Base64 chunked, reliable for small files |
148
- | Project directory upload (>1MB) | `upload_project` | HTTP tunnel, much faster than base64 for multi-file projects |
149
-
150
- **Timeout tuning**: default is 120s. For commands expected to run longer (e.g. large builds), pass `timeout_ms` explicitly:
194
+ | Scenario | Use | Why |
195
+ | ---------------------------------- | -------------------------------------- | --------------------------------------------------------------------------- |
196
+ | `cd`, env setup, command chains | `exec_with_session` | Needs shared shell state across calls |
197
+ | `npm install`, `apt-get`, builds | `exec_one_shot` (async) + `exec_poll` | Long-running, no state needed; async survives the sync timeout |
198
+ | Long build (>120s) | `exec_one_shot` mode: `"async"` + poll | The claim protocol keeps exactly one copy running; log captured server-side |
199
+ | `curl`, health checks, quick tests | Either — `exec_one_shot` preferred | Stateless, fast |
200
+ | Server startup (background) | `exec_with_session` | Need to `nohup ... &` then check output in same session |
201
+ | Deployment scripts | `exec_one_shot` (async for long ones) | Long script, fresh connection avoids session timeouts |
202
+ | nginx configuration | `deploy_nginx` | Auto-generates correct template + permissions + reload |
203
+ | Deployment completeness check | `deploy_check` | Verifies nginx, DevBridge, URL, QR before reporting success |
204
+ | Tunnel lifetime renewal | `renew_tunnel` | Rolling-window renewal, same URL stays alive |
205
+ | URL must outlive the session | `keepalive_watchdog` | Unattended host re-attach + daily renewal + health check |
206
+ | 暂不使用 / 节省核时 | `sandbox_shutdown` | 只关机不删除;数据盘保留,下次 connect 自动唤醒 |
207
+ | Single file upload (<1MB) | `upload_file` | Base64 chunked, reliable for small files |
208
+ | Project directory upload (>1MB) | `upload_project` | HTTP tunnel, much faster than base64 for multi-file projects |
209
+
210
+ **Long commands: async mode, not bigger timeouts.** A command that can outlive the sync timeout (default 120s — builds, installs, test suites) must run as an async task instead of raising `timeout_ms`:
151
211
 
152
212
  ```json
153
- { "timeout_ms": 300000 }
213
+ { "command": "cd /workspace/<dirname> && <buildCmd>", "mode": "async", "task_id": "build-<dirname>-1" }
154
214
  ```
155
215
 
156
- **Session recovery**: if `exec_with_session` returns `session is not ready`, the WebSocket connection has dropped. Do NOT retry the same session — fall back to `exec_one_shot` for that command instead. To recover state (cd, env vars), reconstruct them explicitly in the one-shot command.
216
+ `exec_one_shot` with `mode: "async"` claims a per-task directory on the sandbox, spawns the command detached (it survives the exec session), and returns immediately with `{started, taskId, taskDir}`. Poll with `huaweicloud_sandbox_exec_poll` (`task_id`, `wait_ms` up to 60000, `tail_bytes` default 4096) until the verdict is `done` — `exitCode` and `logTail` are the command's result, and the log is captured server-side (no `tee` needed).
217
+
218
+ The retry ladder (the claim protocol is double-spawn-safe by construction):
219
+
220
+ - `started: "uncertain"` (the start exec timed out — the claim may already be placed) → **retry with the SAME task_id**: the task's claim file blocks a second copy from ever spawning.
221
+ - `started: "dup"` → the task already exists; the receipt carries the current verdict (a `done` verdict hands over the result immediately).
222
+ - `started: "dup"` + verdict `never` → the start exec died between claim and spawn — **start over with a NEW task_id** (a same-id retry can never spawn).
157
223
 
158
- **Timeout recovery**: if `exec_one_shot` returns a timeout error, check whether partial output is available before declaring failure:
224
+ Poll verdicts: `done` (exitCode, logTail), `running` (logTail — keep polling), `lost` (the wrapper died without an exit status, or the sandbox rebooted — restart with a new task_id if needed), `never` (new task_id), `unknown` (no task directory and no memory of the task_id — never started here, or everything restarted). Poll correctness never depends on this agent's memory of the task; only the lost/unknown split does.
159
225
 
160
- - For build commands: check `tail -30 /tmp/build.log` — the build may have completed but the tee pipe didn't flush before timeout
161
- - For long scripts: split into independent `exec_one_shot` calls (max 5 sub-commands per call, 15s timeout per call)
162
- - Do NOT retry the same composite command — split and retry individual steps
226
+ **Sync fallback**: for callers that prefer bounded waits, sync `exec_one_shot` with an explicit `timeout_ms` stays supported (see the timeout table in the build section below). A sync timeout no longer has a recovery decision tree — the command may still be running server-side with no captured output; migrate the command to `mode: "async"` with a new `task_id` and poll it to completion instead of blind-retrying.
227
+
228
+ **Session recovery**: if `exec_with_session` returns `session is not ready`, the WebSocket connection has dropped. Do NOT retry the same session — fall back to `exec_one_shot` for that command instead. To recover state (cd, env vars), reconstruct them explicitly in the one-shot command.
163
229
 
164
230
  ## Workflow
165
231
 
166
232
  **Step 0 — Target-Selection Gate (MANDATORY)**: before any sandbox lifecycle tool, confirm the target. If the developer asked to deploy/host/publish a site without naming a target, STOP and run the [Target-Selection Gate](#target-selection-gate-mandatory--do-not-skip) first; do NOT call `huaweicloud_sandbox_connect` until it is resolved. Proceed with this workflow only if the target is already confirmed as sandbox (or a temporary runtime).
167
233
 
168
- **Step 0.3 — Resource pool selection**: once the target is sandbox, pick the pool type per the [两池沙箱(pool_type)](#两池沙箱pool_type) selection rules (auto by intent, developer may override; 1 instance per type, same type reuses). Check the task survives the chosen type's lifecycle window (ephemeral: idle 30min shutdown + 1h delete; persistent: 7-day idle reclaim cap) before connecting.
234
+ **Step 0.5 — Stack-Selection Gate (MANDATORY)**: before selecting a pool or uploading application code, confirm the backend stack via the [Stack-Selection Gate](#stack-selection-gate-mandatory--do-not-skip). 工作台/workbench/全栈/full-stack/CRUD/持久化 ⇒ full-stack (PostgreSQL + PostgREST default) — do NOT start an SPA-only deployment for a workbench request.
169
235
 
170
- **Step 0.5 — Stack-Selection Gate (MANDATORY)**: before uploading or writing any application code, confirm the backend stack via the [Stack-Selection Gate](#stack-selection-gate-mandatory--do-not-skip). 工作台/workbench/全栈/full-stack/CRUD/持久化 ⇒ full-stack (PostgreSQL + PostgREST default) — do NOT start an SPA-only deployment for a workbench request.
236
+ **Step 0.6 — Pool-Selection Gate (MANDATORY)**: once the target is sandbox and the stack is known, select the pool per the [Pool-Selection Gate](#pool-selection-gate-mandatory--do-not-skip). Default `ephemeral`; use `persistent` only with explicit long-term intent or after confirmation. Same task reuses the current pool; a new task is re-evaluated. Check the task survives the chosen type's lifecycle window (ephemeral: idle 30min shutdown + 1h delete; persistent: 7-day idle reclaim cap) before connecting.
171
237
 
172
238
  Setup is a **plugin-side preflight** — the developer should be asked a question only once, when the agreement actually needs signing:
173
239
 
@@ -189,8 +255,10 @@ Setup is a **plugin-side preflight** — the developer should be asked a questio
189
255
  sleep 1
190
256
  # Remove stale nginx configs from previous deployments
191
257
  sudo rm -f /etc/nginx/conf.d/*.conf /etc/nginx/conf.d/*.conf.bak 2>/dev/null
192
- # Remove stale DevBridge tunnels
193
- devbridge delete-all 2>/dev/null || true
258
+ # Remove stale DevBridge tunnels only (keep other ports/sessions):
259
+ # list and delete orphan IDs; the automated connect cleanup does this too.
260
+ devbridge list
261
+ # devbridge delete <orphan-id>
194
262
  # Reload nginx to apply
195
263
  sudo nginx -s reload 2>/dev/null || true
196
264
  ```
@@ -212,7 +280,7 @@ Setup is a **plugin-side preflight** — the developer should be asked a questio
212
280
 
213
281
  **DevBridge API Key 前置引导(before expose, not mid-expose)**: the address-generation service (DevBridge 0.2.x) requires an API Key. Recent sandbox images auto-acquire one from the platform keyring — but if the sandbox was created on an older image (cannot auto-acquire), prepare the key at THIS stage instead of being interrupted halfway through the expose flow: create it once at https://devstation.connect.huaweicloud.com/space/devbridge/apikey (value shown only once, `devbridge_` prefix), hand it over via `export HW_API_KEY=<key>` locally (preferred) or paste it in the conversation for the `api_key` param, then run `huaweicloud_sandbox_credentials`. Full why/where/how guide: [Step 1, NO_CREDENTIAL branch](#step-1-authenticate--api-key-only-aksk-removed-auto-create-fallback).
214
282
 
215
- 8. **Execute commands**: use `huaweicloud_sandbox_exec_with_session` for interactive work (cd, env setup), or `huaweicloud_sandbox_exec_one_shot` for long-running builds/installs. See [Tool Selection Guide](#tool-selection-guide).
283
+ 8. **Execute commands**: use `huaweicloud_sandbox_exec_with_session` for interactive work (cd, env setup), or `huaweicloud_sandbox_exec_one_shot` for long-running builds/installs — commands that can exceed the sync timeout go out as `mode: "async"` + `huaweicloud_sandbox_exec_poll`. See [Tool Selection Guide](#tool-selection-guide).
216
284
  9. **Upload project** (if deploying local code): `huaweicloud_sandbox_upload_project` to transfer a local project directory into `/workspace/<name>` — uses HTTP tunnel, much faster than base64 for multi-file projects. Use `huaweicloud_sandbox_upload_file` for single files.
217
285
  10. **Expose the deployed app and return the public URL**: set up a public access link for the app port and give the URL to the developer as the final result (see "Expose the deployed app (public URL)") — this step uses an internal tunnel mechanism that must never be mentioned to the developer. **Every URL handoff MUST include the sandbox-lifetime notice from `urlLifetimeHint` (or `warnings`)**: the address dies when the sandbox idles out (ephemeral: shutdown/delete; persistent: shutdown, data retained), and the tunnel expiry is not the sandbox lifetime
218
286
 
@@ -366,7 +434,7 @@ fi
366
434
 
367
435
  - `-s` (silent) is **required** in the sandbox — without it the installer blocks reading `/dev/tty`.
368
436
  - **Old tunnels do not survive the upgrade**: 0.1.x-created tunnels are not registered on the s2 gateway — always rebuild the tunnel after upgrading (the expose flow below does this via pre-cleanup).
369
- - If `10006: quota exceeded` appears after upgrading, stale pre-upgrade tunnels still count against the quota — `devbridge delete-all` and retry.
437
+ - If `10006: quota exceeded` appears after upgrading, stale pre-upgrade tunnels still count against the quota — the expose tool now removes orphans first, then the oldest non-keepalive tunnel one at a time. Manually: `devbridge list` and `devbridge delete <id>` for stale entries; reserve `devbridge delete-all` for an explicit full reset.
370
438
 
371
439
  ### Sandbox filesystem persistence: what survives a reboot (#999)
372
440
 
@@ -423,6 +491,7 @@ devbridge auth status
423
491
  - **`API_KEY_AUTO`** → done (plugin auto-created and injected; zero user action).
424
492
  - **`API_KEY_FILE`** → done (user-provided or auto-injected file fallback).
425
493
  - **`NO_CREDENTIAL`** → auto-create failed. Check the error:
494
+ - **Version gate** (`HDKIT_VERSION_TOO_OLD`): NOT a credential problem — the plugin version is too old. The failure carries the upgrade remediation under gateRemediation (npx --yes huaweicloud-devkit@latest update --target <agent>, restart the agent session, or call `huaweicloud_upgrade`); creating a key or re-running `huaweicloud_sandbox_credentials` cannot clear it.
426
495
  - **Quota full** (`HDKIT_DEVBRIDGE_KEY_QUOTA_EXCEEDED`): guide the user to clean unused keys at https://devstation.connect.huaweicloud.com/space/devbridge/apikey (the `currentKeys` field shows the list). `devkit-*` keys auto-recreate — clean other stale keys first.
427
496
  - **Other errors**: one-time manual fallback — create a key at the console page, `export HW_API_KEY=<key>` locally, re-run `huaweicloud_sandbox_credentials`, then retry.
428
497
 
@@ -431,10 +500,13 @@ devbridge auth status
431
500
  Run the web server and the tunnel in the background, then read the URL from the log; the app lives in the workspace mount, e.g. `/workspace/<repo-name>`:
432
501
 
433
502
  ```bash
434
- # 0. Pre-cleanup: kill old processes and stale tunnels
435
- pkill -f "devbridge host" 2>/dev/null || true
436
- sleep 2
437
- devbridge delete-all 2>/dev/null || true
503
+ # 0. Pre-cleanup: replace ONLY the tunnels bound to <port>; keep other ports/sessions.
504
+ # (huaweicloud_sandbox_expose_tunnel does this automatically with cleanup_mode=stale.)
505
+ # Port-attributed, any tunnel name — a tunnel-<port>- name match would miss the
506
+ # custom-named tunnels `devbridge create <name>` makes. The gsub strips the OSC 133
507
+ # markers integration-enabled terminals wrap around every output line — without it
508
+ # devbridge rejects the glued tunnel IDs and the delete silently no-ops (#946).
509
+ for T in $(devbridge list 2>/dev/null | awk '{gsub(/\033\]133;C\007/, ""); if ($1 !~ /^Tunnel/ && $1 !~ /^No$/) print $1}'); do devbridge port list "$T" 2>/dev/null | awk -v P=<port> '{gsub(/\033\]133;C\007/, ""); if ($1 == P) f=1} END {exit f ? 0 : 1}' && devbridge delete "$T" 2>/dev/null || true; done
438
510
 
439
511
  # 1. Start tunnel (setsid-detached so the host survives the exec session; -e 72 = 72h lifetime)
440
512
  if command -v setsid > /dev/null 2>&1; then setsid nohup devbridge host -p <port> -e 72 > /tmp/host.log 2>&1 < /dev/null & else nohup devbridge host -p <port> -e 72 > /tmp/host.log 2>&1 < /dev/null & fi
@@ -452,8 +524,9 @@ if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "304" ]; then
452
524
  echo "Tunnel verified: $TUNNEL_URL (HTTP $HTTP_CODE)"
453
525
  else
454
526
  echo "WARN: Tunnel URL unreachable (HTTP $HTTP_CODE). Rebuilding tunnel..."
455
- pkill -f "devbridge host" && sleep 2
456
- devbridge delete-all 2>/dev/null || true
527
+ # Rebuild only this port's tunnels (port-attributed, any name); never touch other ports.
528
+ # The gsub strips OSC 133 markers so devbridge receives clean IDs (#946).
529
+ for T in $(devbridge list 2>/dev/null | awk '{gsub(/\033\]133;C\007/, ""); if ($1 !~ /^Tunnel/ && $1 !~ /^No$/) print $1}'); do devbridge port list "$T" 2>/dev/null | awk -v P=<port> '{gsub(/\033\]133;C\007/, ""); if ($1 == P) f=1} END {exit f ? 0 : 1}' && devbridge delete "$T" 2>/dev/null || true; done
457
530
  if command -v setsid > /dev/null 2>&1; then setsid nohup devbridge host -p <port> -e 72 > /tmp/host.log 2>&1 < /dev/null & else nohup devbridge host -p <port> -e 72 > /tmp/host.log 2>&1 < /dev/null & fi
458
531
  disown 2>/dev/null || true
459
532
  sleep 10
@@ -474,8 +547,9 @@ fi
474
547
  # 0.2.x: `devbridge list` (plain table; data rows start with the 8-char tunnel ID)
475
548
  # 0.1.x (legacy): `devbridge list -j` (JSON)
476
549
  devbridge list
477
- # Step B: Remove all stale tunnels
478
- devbridge delete-all
550
+ # Step B: Remove stale tunnels one by one (the expose tool already does
551
+ # orphans first, then oldest non-keepalive; keep keepalive-protected tunnels)
552
+ # devbridge delete <stale-id>
479
553
  # Step C: Retry tunnel creation
480
554
  if command -v setsid > /dev/null 2>&1; then setsid nohup devbridge host -p <port> -e 72 > /tmp/host.log 2>&1 < /dev/null & else nohup devbridge host -p <port> -e 72 > /tmp/host.log 2>&1 < /dev/null & fi
481
555
  disown 2>/dev/null || true
@@ -710,7 +784,7 @@ Use `exec_one_shot` for install (no shared state needed). Skip if `node_modules`
710
784
  cd /workspace/<dirname> && [ -d node_modules ] && echo "SKIP: node_modules exists" || <installCmd>
711
785
  ```
712
786
 
713
- Wait for install to complete. For large projects on aarch64 sandboxes (1000+ packages), set `timeout_ms` to 180000 (3 min).
787
+ Wait for install to complete. For large projects on aarch64 sandboxes (1000+ packages), the install can exceed the sync timeout — run it as an async task instead of raising `timeout_ms`: `exec_one_shot` with `mode: "async"` + a `task_id`, then `exec_poll` to completion (same flow as builds below).
714
788
 
715
789
  **Node version compatibility**: if `npm install` fails with native module errors (e.g., `rollup 4`, `@esbuild`, `node-gyp`), check the Node version:
716
790
 
@@ -738,7 +812,7 @@ fi
738
812
 
739
813
  #### 4c: Build
740
814
 
741
- **Timeout strategy by framework type:**
815
+ **Timeout strategy by framework type** (sync-mode `timeout_ms` — the fallback for callers that stay synchronous; async tasks need none of this table, their command is unbounded and polled):
742
816
 
743
817
  | Type | timeout_ms | Rationale |
744
818
  | ------------------------------ | --------------- | ------------------------------------- |
@@ -748,13 +822,19 @@ fi
748
822
  | Monorepo | 600000 (10 min) | Multiple apps, shared packages |
749
823
  | `null` (no build) | N/A | Skip |
750
824
 
751
- **Build with `exec_one_shot`:**
825
+ **Build as an async task (preferred)**: `exec_one_shot` with `mode: "async"` + a `task_id`, then poll to completion — the task's server-side log survives the exec timeout (no `tee` needed), exactly one copy of the command runs (the claim protocol), and the poll hands over the `exitCode` and `logTail`:
752
826
 
753
- ```bash
754
- cd /workspace/<dirname> && [ -d <outputDir> ] && echo "SKIP: <outputDir> exists" || (umask 022 && <buildCmd> 2>&1 | tee /tmp/build.log)
827
+ ```json
828
+ {
829
+ "command": "cd /workspace/<dirname> && [ -d <outputDir> ] && echo \"SKIP: <outputDir> exists\" || (umask 022 && <buildCmd>)",
830
+ "mode": "async",
831
+ "task_id": "build-<dirname>-1"
832
+ }
755
833
  ```
756
834
 
757
- Always pipe build output through `tee /tmp/build.log` — captures stderr+stdout so diagnostics are available even if the command times out.
835
+ Poll with `huaweicloud_sandbox_exec_poll` (`task_id`, `wait_ms` up to 60000) until `verdict: "done"`. The retry ladder applies: `started: "uncertain"` → retry the SAME `task_id`; `started: "dup"` + verdict `never` → start a new `task_id`.
836
+
837
+ **Sync fallback (for callers that stay synchronous)**: run the build inline with `exec_one_shot` and an explicit `timeout_ms` from the table above — the async mechanism has replaced the sync post-timeout recovery tree; if a sync build still times out, do not blind-retry it: restart it as an async task with a new `task_id` and poll.
758
838
 
759
839
  **OutDir verification**: before building for the first time, check the project's actual output directory (not just the default from framework detection). Projects can override outDir in config (e.g., VitePress `outDir: '../dist'`):
760
840
 
@@ -779,43 +859,14 @@ fi
779
859
 
780
860
  If `REAL_OUTDIR` differs from `<outputDir>`, use `REAL_OUTDIR` for all subsequent steps (nginx config, port check, etc.).
781
861
 
782
- **Post-timeout recovery**: if `exec_one_shot` returns a timeout error (Request timed out), do NOT fail immediately. First dump any captured build log, then check the output directory:
783
-
784
- ```bash
785
- # If timeout occurred, show captured output and verify build
786
- if timeout_error; then
787
- echo "=== Build log (tail) ==="
788
- tail -30 /tmp/build.log 2>/dev/null
789
- echo "=== Checking output ==="
790
- if [ -d <outputDir> ] && [ "$(ls -A <outputDir> 2>/dev/null)" ]; then
791
- # Verify at least one key output file exists (not just empty dir from broken build)
792
- if [ -f <outputDir>/index.html ] || [ -f <outputDir>/server.js ] || [ -f <outputDir>/app.js ]; then
793
- echo "Build output detected despite timeout — continuing with deployment"
794
- else
795
- echo "ERROR: Output directory exists but missing expected files (index.html/server.js). Build may have failed silently."
796
- echo "Full log: /tmp/build.log"
797
- exit 1
798
- fi
799
- else
800
- echo "ERROR: Build did not complete. Output directory empty or missing."
801
- echo "Full log: /tmp/build.log"
802
- exit 1
803
- fi
804
- fi
805
- ```
862
+ **Post-timeout handling**: the async mechanism replaced the old post-timeout recovery tree. A sync timeout means the command may still be running server-side with no captured output — do NOT retry the same composite command. Restart it as an async task (new `task_id`) and poll to completion; the poll's `logTail` shows what the run produced, `exitCode` whether it succeeded.
806
863
 
807
864
  For SSR frameworks, also verify the server entry point exists: `test -f <outputDir>/server.js || test -f node_modules/next/dist/server/next-server.js`.
808
865
 
809
- **Build progress visibility**: for very large builds, touch a marker file before starting and use `exec_with_session` to poll intermediate logs:
866
+ **Build progress visibility**: for very large builds, the async task's poll IS the progress view — each `huaweicloud_sandbox_exec_poll` call returns the task's `logTail` (the last `tail_bytes`, default 4096, of the captured stdout+stderr). Poll with a `wait_ms` to wait server-side between reads; no marker files or side-channel `cat` calls are needed:
810
867
 
811
- ```bash
812
- # Before build:
813
- touch /tmp/build-start && echo "Build started at $(date)"
814
-
815
- # During build via exec_with_session (separate call for polling):
816
- cat .next/trace 2>/dev/null | tail -5 # Next.js build trace
817
- # or
818
- tail -5 /tmp/build.log 2>/dev/null
868
+ ```json
869
+ { "task_id": "build-<dirname>-1", "wait_ms": 30000 }
819
870
  ```
820
871
 
821
872
  - `cd /workspace/<dirname>/<subAppPath>` for Monorepo sub-apps.
@@ -827,10 +878,10 @@ tail -5 /tmp/build.log 2>/dev/null
827
878
 
828
879
  Build failures fall into two categories. Handle them differently:
829
880
 
830
- | Failure Type | Behavior |
831
- | ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
832
- | **Timeout** (timed out) | Check `/tmp/build.log` tail and output directory — build may have completed but `tee` pipe didn't flush. See Post-timeout recovery above. |
833
- | **Non-zero exit code** | **STOP immediately.** The build engine explicitly rejected the output. Do NOT retry, modify source, or tweak env vars. Follow the procedure below. |
881
+ | Failure Type | Behavior |
882
+ | ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
883
+ | **Timeout** (timed out) | The command may still be running server-side — do NOT blind-retry it. Migrate to `mode: "async"` with a NEW `task_id` and poll it to completion (async tasks never hit this row: their timeout became the `started: "uncertain"` receipt with the same-task_id retry ladder). |
884
+ | **Non-zero exit code** | **STOP immediately.** The build engine explicitly rejected the output. Do NOT retry, modify source, or tweak env vars. Follow the procedure below. |
834
885
 
835
886
  **When a build exits with non-zero exit code:**
836
887
 
@@ -1003,7 +1054,7 @@ If the status code is not 2xx/3xx:
1003
1054
 
1004
1055
  ### Step 7: Expose via DevBridge [REQUIRED — deployment incomplete without this]
1005
1056
 
1006
- **Preferred: call `huaweicloud_sandbox_expose_tunnel` with the ACTUAL port returned by `deploy_nginx` (`{"port": <port>}`)** — it authenticates automatically through the credential waterfall (keyring → API-Key file → auto-created API Key), pre-cleans stale tunnels, starts the host, extracts the public URL, and health-checks it before returning. If it reports `ok: false` with an API-Key hint, create the key and re-run `sandbox_credentials`, then call it again. The tool's returned `publicUrl` is the deployment result; an `ok: false` verdict (including a migrated-placeholder URL) means the deployment is NOT complete — never fabricate or reuse a dead URL.
1057
+ **Preferred: call `huaweicloud_sandbox_expose_tunnel` with the ACTUAL port returned by `deploy_nginx` (`{"port": <port>}`)** — it authenticates automatically through the credential waterfall (keyring → API-Key file → auto-created API Key), selectively cleans only same-port/orphan tunnels (other ports, other sessions and keepalive-protected tunnels are preserved), starts the host, extracts the public URL, and health-checks it before returning. If it reports `ok: false` with an API-Key hint, create the key and re-run `sandbox_credentials`, then call it again. The tool's returned `publicUrl` is the deployment result; an `ok: false` verdict (including a migrated-placeholder URL) means the deployment is NOT complete — never fabricate or reuse a dead URL.
1007
1058
 
1008
1059
  **Manual fallback** (only when the tool is unavailable or must be debugged by hand): follow the rest of this section.
1009
1060
 
@@ -1013,7 +1064,7 @@ Follow the standard [Expose the deployed app](#expose-the-deployed-app-public-ur
1013
1064
 
1014
1065
  Use `exec_with_session` for the Expose steps, and copy the guarded `setsid nohup … < /dev/null & disown` launch verbatim — the guard (not the exec flavor) is what makes the host survive the session. For SSR, DevBridge tunnels the nginx public port (not the Node port directly).
1015
1066
 
1016
- **Pre-flight**: always run `devbridge delete-all` before creating a new tunnel to prevent `10006: quota exceeded` from accumulated stale tunnels. If you still get quota error, list tunnels with `devbridge list` (0.2.x plain table; 0.1.x legacy `-j` JSON), delete stale ones, and retry.
1067
+ **Pre-flight**: `huaweicloud_sandbox_expose_tunnel` now performs **selective cleanup** automatically (default `cleanup_mode=stale`): it removes orphan records/hosts and replaces the tunnel bound to the requested port; all other ports, other sessions and keepalive-protected tunnels are preserved (the same-port tunnel is the one documented exception — a port cannot have two tunnels). On `10006: quota exceeded` it removes all orphans first, then the oldest non-keepalive tunnel one at a time; keepalive-protected tunnels are never auto-deleted and a still-full quota returns `devbridge_tunnel_quota_exceeded`. `cleanup_mode=none` skips cleanup entirely (a stale same-port host can then conflict). For manual flows, prefer `devbridge list` + `devbridge delete <id>` for stale entries; use `devbridge delete-all` only for an explicit full reset (shared-sandbox warning below).
1017
1068
 
1018
1069
  > **Concurrency warning**: `devbridge delete-all` and `pkill -f "devbridge host"` are GLOBAL operations scoped to the whole sandbox — if multiple sessions share the same sandbox, pre-cleaning can kill tunnels published by other sessions and invalidate URLs you handed out earlier. For shared sandboxes, prefer `devbridge list` and delete only stale/your-own tunnels instead of blanket `delete-all`, and re-expose only after confirming the target port is still served.
1019
1070
 
@@ -1080,45 +1131,46 @@ Returns `complete: true/false`, `score`, and `nextStep` to fix missing items.
1080
1131
 
1081
1132
  - [Framework Commands](references/framework-commands.md) — command mapping for all supported frameworks
1082
1133
  - [Nginx Templates](references/nginx-templates.md) — nginx configuration templates and fallback
1083
- - [Resource Pool](references/resource-pool.md) — 资源池定稿口径:两沙箱类型、申请/限流参数(持久 2U4G×300 + 4U8G×200、非持久 2U4G×1000、overlayer 5GB/实例、EVS 300TB)、配额 1/类型 与 429+Retry-After 语义
1134
+ - [Resource Pool](references/resource-pool.md) — 资源池定稿口径:两沙箱类型、申请/限流参数(持久 2U4G×300 + 4U8G×200、非持久 2U4G×1000、overlayer 5GB/实例、EVS 300TB)、配额 1/类型 与 429 三码(Retry-After 仅随配额满与容量不足)语义
1084
1135
  - [Tunnel persistence](references/tunnel-persistence.md) — renewal, re-attach, and the keepalive watchdog
1085
1136
  - [Full-stack PostgREST](references/fullstack-postgrest.md) — the measured PostgreSQL 16 + PostgREST + nginx procedure
1086
1137
 
1087
1138
  ## Critical Warnings
1088
1139
 
1089
- | Trap | Why |
1090
- | -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1091
- | Target not confirmed | "部署到华为云" without a named target is NOT a go signal. You MUST run the Target-Selection Gate and get an explicit choice before calling any sandbox lifecycle tool. Skipping it and defaulting to the sandbox is a violation. |
1092
- | Stack not confirmed (workbench ⇒ SPA) | 工作台/全栈/full-stack/CRUD/数据库/持久化 requests are full-stack workbench deployments (PostgreSQL + PostgREST default) even when no database is mentioned. NEVER infer or default the stack to SPA — run the Stack-Selection Gate (Step 0.5) before uploading or writing ANY application code; an SPA-only deployment that already started with persistence implied must be STOPped and redirected to the full-stack path, not papered over with a bolted-on static backend. |
1093
- | Pool type fixes durability | 预览/试用/即焚 requests belong on the `ephemeral` pool — idle 30min auto-shutdown + 1h auto-delete (平台定时任务,已实测), nothing survives it, data dies with the box; 工作台/带数据库/跨日 requests belong on the `persistent` pool (EVS 32G mounted, survives reboots, idle reclaim within 7 days max). Pick per the 两池沙箱(pool_type) selection rules (Step 0.3) BEFORE calling `sandbox_connect`, and never promise durability on an ephemeral sandbox. A rejected connect returns HTTP 429 with a Retry-After header and a dual error code — the CODE, not the status, separates the two failure classes: HDKIT_QUOTA_EXCEEDED (quota — 1 instance per pool type; release or reuse, retry useless) vs HDKIT_CAPACITY_INSUFFICIENT (pool capacity; retry later / off-peak). |
1094
- | Agreement required first | `sandbox_connect` fails if the agreement isn't signed; the `sandbox_check_user` preflight detects this, so surface it to the developer only when signing is needed |
1095
- | Real-name required | `sandbox_connect` fails if `realnameVerified=false`; tell the developer once and stop, don't loop on connect |
1096
- | Never expose tunnel details | Do not mention "DevBridge"/"tunnel"/"devbridge" to the developer — say "正在生成访问地址..." and hand over only the URL |
1097
- | devbridge auth: API Key only | DevBridge auth is fixed to API Key (AK/SK login removed, 2026-11-04). The waterfall: keyring (ours + platform legacy) → file → auto-create fallback. Use `devbridge auth login --api-key` only — never `--access-key/--secret-key`. |
1098
- | devbridge 0.1.x is dead | Sandboxes created before Sep 2026 ship 0.1.13, which connects to a migrated gateway serving a 「服务已迁移」 placeholder with HTTP 200. Check `devbridge version` first and upgrade in place (Step 0) — old tunnels never survive the upgrade |
1099
- | CLI PATH | The installer only writes `~/.bashrc`; run `export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"` (prepend, data-disk first) in the session before using `devbridge` — appending lets a stale image binary in `/usr/local/bin` win, and `~/.huawei/bin` alone is wiped on reboot (#999) |
1100
- | Never install tunnel tooling locally | If the sandbox cannot install it, report a generic error and stop — installing on the developer's machine defeats sandbox deployment |
1101
- | Return the deployment URL | Always hand the public URL from the host log to the developer as the final result |
1102
- | Deploy is not just nginx | Configuring nginx does NOT complete the deployment. Steps 7 (DevBridge expose) and deploy_check are REQUIRED — `deploy_nginx` returns `nextStep: expose_via_devbridge` as a reminder. Do not stop after nginx. |
1103
- | Call deploy_check before success | Always call `huaweicloud_sandbox_deploy_check` before reporting deployment success. A green nginx status does not mean the tunnel is accessible — verify end-to-end with the tool. |
1104
- | Session state persists | `exec_with_session` preserves `cd`, env vars, aliases between calls |
1105
- | Long commands prefer one-shot | `exec_one_shot` creates a fresh connection per call — more stable for builds, installs, and scripts >30s. See [Tool Selection Guide](#tool-selection-guide). |
1106
- | SSR nginx/Node ports must differ | nginx `proxy_pass` targets `<nodePort>`, not `<port>`. `deploy_nginx` auto-defaults `nodePort` to `<port>+1` — always start the Node process with `PORT=<nodePort>` to match. Same-port = EADDRINUSE. |
1107
- | HTTP 200 ≠ correct content | A green HTTP check does not guarantee the right project is serving — old processes from a previous session bound to the same port will still return 200. `deploy_check` verifies the deployment fingerprint to catch this. |
1108
- | 404 "tunnel not found" ≠ content issue | The s2 gateway answers 404 with body `tunnel not found` when the host process is dead (the tunnel record may STILL show in `devbridge list`) and `port not configured` for an unregistered URL port — both mean the URL is dead, not that the app returned 404. `expose_tunnel`/`deploy_check` verify the probe body and refuse such URLs; a shared sandbox's second deployment also kills earlier URLs (global pre-clean), so re-expose and hand over the fresh URL. |
1109
- | Destructive commands blocked | `rm -rf /`, `mkfs`, `dd if=`, fork bombs are denied by safety policy |
1110
- | Workspace ID = dev_stage_id | Use `dev_stage_id` from `sandbox_connect` as `workspace_id` for terminal exec |
1111
- | Projects live in `/workspace` | Clone/install project code under `/workspace/<repo-name>` (filesystem-root workspace mount, not `$HOME/workspace`), never in `/tmp` — ephemeral locations lose the project when the sandbox session restarts |
1112
- | Upload project for local code | Use `sandbox_upload_project` to transfer local projects — packages as tar.gz, uploads via HTTP tunnel, extracts on sandbox. Much faster than base64 for multi-file projects |
1113
- | Upload file for single files | Use `sandbox_upload_file` for individual files — base64 chunked, reliable for small files (<1MB) |
1114
- | Node.js >= 22 required | Sandbox terminal uses built-in WebSocket (globalThis.WebSocket); if Node.js is missing, install it from the Huawei Cloud mirror (see "Node.js in the sandbox") |
1115
- | Sandbox restart kills processes | After sandbox restarts, all user processes (nginx, Node.js, Python servers) are stopped. Re-run startup commands and verify ports are listening before proceeding. |
1116
- | Cross-platform binaries incompatible | The sandbox runs Linux. Native binaries built on Windows/macOS (e.g., Prisma client, `node_modules/.prisma/`, platform-specific native addons) will not execute. Always install and build dependencies inside the sandbox, not locally. |
1117
- | Cross-platform needs QR code | When `detect_framework` returns `type: "cross-platform"` (Taro, uni-app), generating a QR code image is **mandatory** — the deployment is incomplete without it. Check the Deployment Completion Check table in Step 7. |
1118
- | Build fails do NOT auto-fix | When a build exits with non-zero exit code, STOP and present the error + fix options to the developer. Do not silently retry, modify configs, or change source files without explicit approval. See 4c-aux. |
1119
- | Tunnel description: no spaces/hyphens | `devbridge create <name> -d 'hello world'` fails with `Invalid tunnel description: only Chinese characters, digits, letters, length 0-64`. The message is misleading — the real rule is no spaces/hyphens. Omit `-d` or use bare letters/digits. |
1120
- | Use `host`, never `connect` | `devbridge connect` is the sender side (for on-prem machines dialing out). For public preview it loops `Connection failed, retrying...` forever with no hint. Always use `devbridge host <tunnelId> -p <port>`. |
1121
- | Port drift detaches the tunnel | When deploy_nginx auto-increments to a free port, an existing tunnel stays bound to the old port — re-bind: `devbridge port create <tunnelId> -p <newPort> --protocol http -a` and restart `devbridge host`. deploy_nginx emits a warning when this happens. |
1140
+ | Trap | Why |
1141
+ | --------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1142
+ | Target not confirmed | "部署到华为云" without a named target is NOT a go signal. You MUST run the Target-Selection Gate and get an explicit choice before calling any sandbox lifecycle tool. Skipping it and defaulting to the sandbox is a violation. |
1143
+ | Stack not confirmed (workbench ⇒ SPA) | 工作台/全栈/full-stack/CRUD/数据库/持久化 requests are full-stack workbench deployments (PostgreSQL + PostgREST default) even when no database is mentioned. NEVER infer or default the stack to SPA — run the Stack-Selection Gate (Step 0.5) before uploading or writing ANY application code; an SPA-only deployment that already started with persistence implied must be STOPped and redirected to the full-stack path, not papered over with a bolted-on static backend. |
1144
+ | Pool type fixes durability | 预览/试用/即焚 requests belong on the `ephemeral` pool — idle 30min auto-shutdown + 1h auto-delete (平台定时任务,已实测), nothing survives it, data dies with the box; 工作台/需要跨会话保留数据/跨日 requests belong on the `persistent` pool (EVS 32G mounted, survives reboots, idle reclaim within 7 days max). Pick per the [Pool-Selection Gate](#pool-selection-gate-mandatory--do-not-skip) (Step 0.6) BEFORE calling `sandbox_connect`, and never promise durability on an ephemeral sandbox. A rejected connect returns HTTP 429 with one of three codes — the CODE, not the status, separates the failure classes: HDKIT_QUOTA_EXCEEDED (quota — 1 instance per pool type; release or reuse, retry useless; Retry-After 60), HDKIT_TEMPLATE_QUOTA_EXCEEDED (the running instances of this account for this sandbox type are at the limit — shut down or release an instance of the same type and retry; no Retry-After), or HDKIT_CAPACITY_INSUFFICIENT (pool capacity; retry later / off-peak; Retry-After 60). |
1145
+ | Gateway 502/504 vs the 409 version gate | A connect answered by gateway 502/504 is a transient orchestration timeout, NOT a failed create: Gateway 502/504 timeouts during orchestration are retried automatically (30s/45s backoff) — the server may already have created the instance, so a retry reuses it; on exhaustion the result is ok:false with the attempt count, and the remediation follows the failing answer — a gateway page carries the transient-class copy, while a business-coded 502 that carries its own remediation keeps it (one without its own copy falls to the transient copy). A 409 `HDKIT_VERSION_TOO_OLD` is the client-version gate — a different failure, not transient: follow the returned remediation (npx --yes huaweicloud-devkit@latest update --target <agent>, restart the agent session, or call `huaweicloud_upgrade`); retrying connect cannot clear it. The same gate fires on the expose relay's auto-create, surfacing error_code HDKIT_VERSION_TOO_OLD with the upgrade remediation instead of a credential failure. Do not debug either as a credential or deployment issue. |
1146
+ | Agreement required first | `sandbox_connect` fails if the agreement isn't signed; the `sandbox_check_user` preflight detects this, so surface it to the developer only when signing is needed |
1147
+ | Real-name required | `sandbox_connect` fails if `realnameVerified=false`; tell the developer once and stop, don't loop on connect |
1148
+ | Never expose tunnel details | Do not mention "DevBridge"/"tunnel"/"devbridge" to the developer — say "正在生成访问地址..." and hand over only the URL |
1149
+ | devbridge auth: API Key only | DevBridge auth is fixed to API Key (AK/SK login removed, 2026-11-04). The waterfall: keyring (ours + platform legacy) → file → auto-create fallback. Use `devbridge auth login --api-key` only — never `--access-key/--secret-key`. |
1150
+ | devbridge 0.1.x is dead | Sandboxes created before Sep 2026 ship 0.1.13, which connects to a migrated gateway serving a 「服务已迁移」 placeholder with HTTP 200. Check `devbridge version` first and upgrade in place (Step 0) — old tunnels never survive the upgrade |
1151
+ | CLI PATH | The installer only writes `~/.bashrc`; run `export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"` (prepend, data-disk first) in the session before using `devbridge` — appending lets a stale image binary in `/usr/local/bin` win, and `~/.huawei/bin` alone is wiped on reboot (#999) |
1152
+ | Never install tunnel tooling locally | If the sandbox cannot install it, report a generic error and stop — installing on the developer's machine defeats sandbox deployment |
1153
+ | Return the deployment URL | Always hand the public URL from the host log to the developer as the final result |
1154
+ | Deploy is not just nginx | Configuring nginx does NOT complete the deployment. Steps 7 (DevBridge expose) and deploy_check are REQUIRED — `deploy_nginx` returns `nextStep: expose_via_devbridge` as a reminder. Do not stop after nginx. |
1155
+ | Call deploy_check before success | Always call `huaweicloud_sandbox_deploy_check` before reporting deployment success. A green nginx status does not mean the tunnel is accessible — verify end-to-end with the tool. |
1156
+ | Session state persists | `exec_with_session` preserves `cd`, env vars, aliases between calls |
1157
+ | Long commands prefer one-shot | `exec_one_shot` creates a fresh connection per call — more stable for builds, installs, and scripts >30s. See [Tool Selection Guide](#tool-selection-guide). |
1158
+ | SSR nginx/Node ports must differ | nginx `proxy_pass` targets `<nodePort>`, not `<port>`. `deploy_nginx` auto-defaults `nodePort` to `<port>+1` — always start the Node process with `PORT=<nodePort>` to match. Same-port = EADDRINUSE. |
1159
+ | HTTP 200 ≠ correct content | A green HTTP check does not guarantee the right project is serving — old processes from a previous session bound to the same port will still return 200. `deploy_check` verifies the deployment fingerprint to catch this. |
1160
+ | 404 "tunnel not found" ≠ content issue | The s2 gateway answers 404 with body `tunnel not found` when the host process is dead (the tunnel record may STILL show in `devbridge list`) and `port not configured` for an unregistered URL port — both mean the URL is dead, not that the app returned 404. `expose_tunnel`/`deploy_check` verify the probe body and refuse such URLs; a shared sandbox's second deployment also kills earlier URLs (global pre-clean), so re-expose and hand over the fresh URL. |
1161
+ | Destructive commands blocked | `rm -rf /`, `mkfs`, `dd if=`, fork bombs, and shutdown/reboot/init verbs at command position are denied on every host — by the agent Bash hook where installed, and server-side by the sandbox exec approval gate's strict classification (a strict deny survives every confirmation) |
1162
+ | Workspace ID = dev_stage_id | Use `dev_stage_id` from `sandbox_connect` as `workspace_id` for terminal exec |
1163
+ | Projects live in `/workspace` | Clone/install project code under `/workspace/<repo-name>` (filesystem-root workspace mount, not `$HOME/workspace`), never in `/tmp` — ephemeral locations lose the project when the sandbox session restarts |
1164
+ | Upload project for local code | Use `sandbox_upload_project` to transfer local projects — packages as tar.gz, uploads via HTTP tunnel, extracts on sandbox. Much faster than base64 for multi-file projects |
1165
+ | Upload file for single files | Use `sandbox_upload_file` for individual files — base64 chunked, reliable for small files (<1MB) |
1166
+ | Node.js >= 22 required | Sandbox terminal uses built-in WebSocket (globalThis.WebSocket); if Node.js is missing, install it from the Huawei Cloud mirror (see "Node.js in the sandbox") |
1167
+ | Sandbox restart kills processes | After sandbox restarts, all user processes (nginx, Node.js, Python servers) are stopped. Re-run startup commands and verify ports are listening before proceeding. |
1168
+ | Cross-platform binaries incompatible | The sandbox runs Linux. Native binaries built on Windows/macOS (e.g., Prisma client, `node_modules/.prisma/`, platform-specific native addons) will not execute. Always install and build dependencies inside the sandbox, not locally. |
1169
+ | Cross-platform needs QR code | When `detect_framework` returns `type: "cross-platform"` (Taro, uni-app), generating a QR code image is **mandatory** — the deployment is incomplete without it. Check the Deployment Completion Check table in Step 7. |
1170
+ | Build fails do NOT auto-fix | When a build exits with non-zero exit code, STOP and present the error + fix options to the developer. Do not silently retry, modify configs, or change source files without explicit approval. See 4c-aux. |
1171
+ | Tunnel description: no spaces/hyphens | `devbridge create <name> -d 'hello world'` fails with `Invalid tunnel description: only Chinese characters, digits, letters, length 0-64`. The message is misleading — the real rule is no spaces/hyphens. Omit `-d` or use bare letters/digits. |
1172
+ | Use `host`, never `connect` | `devbridge connect` is the sender side (for on-prem machines dialing out). For public preview it loops `Connection failed, retrying...` forever with no hint. Always use `devbridge host <tunnelId> -p <port>`. |
1173
+ | Port drift detaches the tunnel | When deploy_nginx auto-increments to a free port, an existing tunnel stays bound to the old port — re-bind: `devbridge port create <tunnelId> -p <newPort> --protocol http -a` and restart `devbridge host`. deploy_nginx emits a warning when this happens. |
1122
1174
 
1123
1175
  ## Node.js in the sandbox
1124
1176