huaweicloud-devkit 2.0.1-next.2 → 2.0.1-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 (75) hide show
  1. package/README.md +26 -3
  2. package/README.zh-CN.md +24 -1
  3. package/package.json +1 -1
  4. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +1 -1
  5. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +1 -1
  6. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +1 -1
  7. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +1 -1
  8. package/plugins/huaweicloud-core/.mcp.json +3 -0
  9. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +1 -1
  10. package/plugins/huaweicloud-core/dist/approval-roster.js +2 -0
  11. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkit-gate.js +7 -0
  12. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +30 -1
  13. package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +21 -0
  14. package/plugins/huaweicloud-core/dist/mcp-server.js +4227 -3049
  15. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  16. package/plugins/huaweicloud-core/dist/packs/registry.js +1 -0
  17. package/plugins/huaweicloud-core/dist/packs/sandbox/approval.js +13 -2
  18. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +198 -10
  19. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +11 -0
  20. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +22 -0
  21. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +46 -0
  22. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-upload.js +11 -0
  23. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +20 -0
  24. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +26 -18
  25. package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +97 -0
  26. package/plugins/huaweicloud-core/dist/sandbox/deploy-nginx.js +30 -14
  27. package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-backend.js +37 -0
  28. package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-connections.js +84 -0
  29. package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-envd-client.js +229 -0
  30. package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-envd-protocol.js +151 -0
  31. package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-envd-transport.js +121 -0
  32. package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-service-api.js +80 -0
  33. package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-upload.js +106 -0
  34. package/plugins/huaweicloud-core/dist/sandbox/hwlink-connection.js +12 -0
  35. package/plugins/huaweicloud-core/dist/sandbox/upload-project.js +5 -2
  36. package/plugins/huaweicloud-core/dist/server-install.js +363 -0
  37. package/plugins/huaweicloud-core/dist/setup-cli.js +16 -0
  38. package/plugins/huaweicloud-core/dist/tool-definitions.js +4 -0
  39. package/plugins/huaweicloud-core/dist/tools.js +1 -0
  40. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  41. package/plugins/huaweicloud-core/safety/policy.json +2 -1
  42. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +67 -16
  43. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/devbox-backend.md +78 -0
  44. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +14 -0
  45. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +2 -1
  46. package/plugins/huaweicloud-core/src/approval-roster.ts +2 -0
  47. package/plugins/huaweicloud-core/src/lib/hdkit/hdkit-gate.ts +7 -0
  48. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +30 -1
  49. package/plugins/huaweicloud-core/src/lib/hdkit/sandbox-pool.ts +22 -0
  50. package/plugins/huaweicloud-core/src/mcp-server-remote.ts +68 -5
  51. package/plugins/huaweicloud-core/src/mcp-server.ts +4 -1
  52. package/plugins/huaweicloud-core/src/packs/registry.ts +1 -0
  53. package/plugins/huaweicloud-core/src/packs/sandbox/approval.ts +15 -2
  54. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +206 -11
  55. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +12 -0
  56. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +23 -0
  57. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +49 -0
  58. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-upload.ts +11 -0
  59. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +23 -0
  60. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +27 -17
  61. package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +105 -0
  62. package/plugins/huaweicloud-core/src/sandbox/deploy-nginx.ts +36 -18
  63. package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-backend.ts +44 -0
  64. package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-connections.ts +115 -0
  65. package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-envd-client.ts +281 -0
  66. package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-envd-protocol.ts +180 -0
  67. package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-envd-transport.ts +142 -0
  68. package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-service-api.ts +102 -0
  69. package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-upload.ts +167 -0
  70. package/plugins/huaweicloud-core/src/sandbox/hwlink-connection.ts +12 -0
  71. package/plugins/huaweicloud-core/src/sandbox/upload-project.ts +5 -2
  72. package/plugins/huaweicloud-core/src/server-install.ts +442 -0
  73. package/plugins/huaweicloud-core/src/setup-cli.ts +16 -0
  74. package/plugins/huaweicloud-core/src/tool-definitions.ts +4 -0
  75. package/plugins/huaweicloud-core/src/tools.ts +3 -0
@@ -83,9 +83,11 @@ If the intent is ambiguous, ask exactly one question:
83
83
 
84
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.
85
85
 
86
- ## Approval gate (the nine mutating tools)
86
+ ## Approval gate (the ten mutating tools)
87
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`.
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`, `kill`. Not gated: `check_user`, `exec_poll`, `close_session`, `upload_file`, `upload_project`, `deploy_nginx`, `deploy_check`.
89
+
90
+ `kill` confirms on every call and is devbox-only: it permanently deletes the sandbox (shutdown only pauses). Always ask the developer for an explicit second confirmation before calling it; on the legacy backend it returns `HDKIT_BACKEND_UNSUPPORTED` and you must use `shutdown` instead.
89
91
 
90
92
  - **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
93
  - **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.
@@ -135,6 +137,46 @@ Selection rules(按意图自动选池;具体按 [Pool-Selection Gate](#pool-
135
137
  - 不支持传 `template_id`;自定义模板已下线,客户端只传 `pool_type`
136
138
  - 完整口径、容量规划与 G 清单:[references/resource-pool.md](references/resource-pool.md)
137
139
 
140
+ ## DevBox backend (HW_SANDBOX_BACKEND=devbox)
141
+
142
+ `HW_SANDBOX_BACKEND=devbox` selects the platform resource-pool backend (the legacy default is DevStation). After a connect, the workspace's backend is pinned in-process — do not expect a mid-session env flip to re-route a connected workspace.
143
+
144
+ **Tenant and credentials**: tenant = STS `principal_id`. Every IAM sub-account (and the primary account) gets its own ephemeral sandbox; `account_id`/domain is audit-only and never isolation/quota. devbox v1 accepts only `:user:` identities — agency/temporary credentials are rejected with `HDKIT_IDENTITY_UNSUPPORTED`. Every control-plane call (`connect`/refresh/`shutdown`/`kill`/status) uses the user's AK/SK (+ optional `X-HW-Security-Token`) — there is no sandbox key, so AK/SK rotation or a devkit restart requires re-authentication. `HDKIT_CREDENTIAL_INVALID`/`HDKIT_CREDENTIAL_EXPIRED` (401) → re-authenticate (`auth init` / `auth switch`); `HDKIT_CREDENTIAL_FORBIDDEN` (403) → fix IAM authorization (not a re-login); `HDKIT_IAM_ERROR` (502) → upstream IAM failure, retry later.
145
+
146
+ **What changes on devbox**:
147
+
148
+ | Area | devbox behavior |
149
+ | ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
150
+ | `check_user` / `sign_agreement` | Skipped locally (`skipped:true`, no fake real-name/agreement claim); do not ask the developer to sign. |
151
+ | `connect` | Only `pool_type=ephemeral` (persistent → `HDKIT_BACKEND_UNSUPPORTED`); `env` maps to `envVars`; `git` is NOT cloned at create (clone with `exec_one_shot` or use `upload_project`); `timeout_seconds` sets the TTL (10–86400, default 1800); EnvD tokens are not returned in the tool result. |
152
+ | `exec_with_session` | DEGRADED to one-shot: returns `degraded:true`, `statePersisted:false`; no shell state survives. Commands must be self-contained. |
153
+ | `exec_one_shot` | EnvD `Process/Start` (non-PTY, `/bin/bash -l -c`); the async claim protocol is unchanged. |
154
+ | `upload_file` / `upload_project` | Binary write via EnvD `/files` + md5 check; project archive extracted with tar in the sandbox (no HTTP tunnel). |
155
+ | `deploy_nginx` | No DevBridge probe; returns `backend:"devbox"`, `previewUrl` (app-port URL), `nextStep:"deploy_check"`. |
156
+ | `deploy_check` | Checks nginx/output/fingerprint in-sandbox and probes the public app-port URL client-side; no DevBridge tunnel checks. |
157
+ | `expose_tunnel` | Returns the public app-port URL synchronously (`backend:"devbox"`, `publicUrl`, `accessible`) — no tunnel, no keepalive. Single port, public by default; the app MUST bind `0.0.0.0` (a `127.0.0.1`-only app is unreachable). |
158
+ | `expose_poll` / `renew_tunnel` / `keepalive_watchdog` | Not applicable (`HDKIT_BACKEND_UNSUPPORTED` + `reason:"not_applicable"`). |
159
+ | `shutdown` | pause (`state:"paused"`, `pause_retention_hours` 168 by default); a later connect resumes the same sandbox. |
160
+ | `kill` | devbox-only DELETE (irreversible; second confirmation required). Legacy → `HDKIT_BACKEND_UNSUPPORTED`; use `shutdown` there. |
161
+ | `close_session` | Not applicable (no terminal session); leaves the sandbox untouched. |
162
+ | `credentials` | Not supported; use connect `envVars` or write `/tmp` files with `exec_one_shot`. |
163
+
164
+ **Self-contained commands (required on devbox)** — every `exec_one_shot` runs in a fresh shell:
165
+
166
+ ```bash
167
+ # Environment file (either one line per command, or persist a script in /tmp)
168
+ cd /workspace/<dir> && set -a && source .env 2>/dev/null; set +a; <build command>
169
+ # or: write /tmp/devkit-env.sh once, then prefix every command with: source /tmp/devkit-env.sh
170
+
171
+ # Start an SSR/backend service detached, then verify with a SEPARATE one-shot
172
+ cd /workspace/<dir> && setsid nohup <serve-command> > /tmp/app.log 2>&1 < /dev/null & echo started
173
+ sleep 2; curl -fsS http://localhost:<port>/ || tail -n 50 /tmp/app.log
174
+ ```
175
+
176
+ - Interactive scaffolds must be non-interactive: `npm create vite@latest app -- --template react` (never a bare `npm create`).
177
+ - The server must bind `0.0.0.0` (or the platform-reachable interface), not `127.0.0.1`.
178
+ - Full backend/deployment guide: [DevBox backend](references/devbox-backend.md).
179
+
138
180
  ## Activation
139
181
 
140
182
  - **Proactive offering**: when the developer's Huawei Cloud task needs a temporary runtime (e.g. "deploy this web app", "run this app and preview it"), offer the sandbox proactively — the developer never has to say "use sandbox". A task whose cloud vendor is unknown or named as another cloud is out of scope here; settle the vendor first. Prompt: "This task can be satisfied by a sandbox — use it?"
@@ -208,6 +250,8 @@ Selection rules(按意图自动选池;具体按 [Pool-Selection Gate](#pool-
208
250
  | Single file upload (<1MB) | `upload_file` | Base64 chunked, reliable for small files |
209
251
  | Project directory upload (>1MB) | `upload_project` | HTTP tunnel, much faster than base64 for multi-file projects |
210
252
 
253
+ **On the devbox backend, ignore the state column**: `exec_with_session` degrades to a one-shot (`degraded:true`, `statePersisted:false`). Use `exec_one_shot` for everything, with self-contained commands (`cd ... && ...`, `source ...; ...`); the async + poll doctrine is unchanged. `expose_tunnel` returns the app-port URL synchronously; `expose_poll`/`renew_tunnel`/`keepalive_watchdog` are not applicable. See [DevBox backend](#devbox-backend-hw_sandbox_backenddevbox).
254
+
211
255
  **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`:
212
256
 
213
257
  ```json
@@ -245,7 +289,7 @@ Setup is a **plugin-side preflight** — the developer should be asked a questio
245
289
  2. **Real-name verification only** (`HDKIT_NOT_REALNAME`): tell the developer once, "Huawei Cloud requires real-name verification before using the sandbox — please complete it in the Huawei Cloud console (实名认证)." and stop — do not retry `connect` in a loop
246
290
  3. **Sign agreement only** (`HDKIT_NOT_AGREEMENT`): **STOP and do NOT sign on your own.** Ask the developer: "Huawei Cloud sandbox requires signing the latest developer service agreement. May I sign it for you?" Then **wait for the developer to explicitly agree** (e.g. "签署" / "确认" / "sign it"). Only after explicit consent call `huaweicloud_sandbox_sign_agreement` and return its result (`signed`/`signedCount`) to the developer. **Never sign a legal agreement on the developer's behalf without their explicit, unambiguous consent.** Do not expose the underlying sandbox/DevBridge service as a separate entity the developer must understand or sign up for
247
291
  4. **Both missing** (`HDKIT_NOT_REALNAME_AND_AGREEMENT`): present **both** requirements together in one message — the real-name verification steps (console, step 2) **and** the agreement-signing request (step 3, wait for explicit consent) — so the developer can complete both at once
248
- 5. **Connect**: `huaweicloud_sandbox_connect` — returns `session_id`, `dev_stage_id`, `connection_id`, `connection_address`, `expiresAt` (STS credential expiry). The `source` parameter identifies the calling agent (valid values: `CLI`, `WEB`, `VSCODE`, `WEBVNC`, `WEBPTY`, `WEBIDE`, `CURSOR`, etc. — case-sensitive, all uppercase). When the `git` parameter is provided (with `repo_url`, `target_path`, optional `repo_branch`), code is automatically transferred to the sandbox: local `git clone` followed by `uploadProject` (falls back to direct sandbox clone when local git is unavailable). Check `_repoStatus` in the response: `uploaded_from_local`, `cloned_in_sandbox`, or `already_exists` (reconnect).
292
+ 5. **Connect**: `huaweicloud_sandbox_connect` — returns `session_id`, `dev_stage_id`, `connection_id`, `connection_address`, `expiresAt` (STS credential expiry). The `source` parameter identifies the calling agent (valid values: `CLI`, `WEB`, `VSCODE`, `WEBVNC`, `WEBPTY`, `WEBIDE`, `CURSOR`, etc. — case-sensitive, all uppercase). When the `git` parameter is provided (with `repo_url`, `target_path`, optional `repo_branch`), code is automatically transferred to the sandbox: local `git clone` followed by `uploadProject` (falls back to direct sandbox clone when local git is unavailable). Check `_repoStatus` in the response: `uploaded_from_local`, `cloned_in_sandbox`, or `already_exists` (reconnect). **devbox backend**: `env` maps to `envVars`; `git` is NOT transferred at create — clone with `exec_one_shot` (`git clone ...`) or use `upload_project`; `timeout_seconds` sets the sandbox TTL; `check_user`/`sign_agreement` are skipped and `credentials` is unsupported.
249
293
  6. **Cleanup previous deployments** (after first connect to a sandbox): nginx configs, DevBridge tunnels, and stale web processes from previous deployments can cause port conflicts and quota errors. Run cleanup immediately after connect:
250
294
 
251
295
  ```bash
@@ -264,7 +308,7 @@ Setup is a **plugin-side preflight** — the developer should be asked a questio
264
308
  sudo nginx -s reload 2>/dev/null || true
265
309
  ```
266
310
 
267
- 7. **Inject credentials** (optional): `huaweicloud_sandbox_credentials` — enables cloud API access from sandbox. Pass `session_id` **or** `dev_stage_id` (at least one; both come from `sandbox_connect`, and `dev_stage_id` may be omitted to reuse the most recent connect). The tool validates the AK/SK against IAM first — an invalid SK is rejected here instead of failing later with `APIGW.0301` during exec. Example:
311
+ 7. **Inject credentials** (optional; **skip on devbox** — `huaweicloud_sandbox_credentials` returns `HDKIT_BACKEND_UNSUPPORTED`; use connect `envVars` or write `/tmp` files with `exec_one_shot`): `huaweicloud_sandbox_credentials` — enables cloud API access from sandbox. Pass `session_id` **or** `dev_stage_id` (at least one; both come from `sandbox_connect`, and `dev_stage_id` may be omitted to reuse the most recent connect). The tool validates the AK/SK against IAM first — an invalid SK is rejected here instead of failing later with `APIGW.0301` during exec. Example:
268
312
 
269
313
  ```json
270
314
  { "dev_stage_id": "<dev_stage_id from connect>" }
@@ -281,9 +325,9 @@ Setup is a **plugin-side preflight** — the developer should be asked a questio
281
325
 
282
326
  **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).
283
327
 
284
- 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).
328
+ 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). **devbox backend**: use `exec_one_shot` with self-contained commands (no shell state survives); `exec_with_session` returns `degraded:true`/`statePersisted:false`.
285
329
  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.
286
- 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
330
+ 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. **devbox backend**: `expose_tunnel` returns the app-port URL directly (no tunnel, single port); the app must bind `0.0.0.0`; skip `expose_poll`/`renew_tunnel`/`keepalive_watchdog`. **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
287
331
 
288
332
  ## File Transfer (local → sandbox)
289
333
 
@@ -1135,6 +1179,7 @@ Returns `complete: true/false`, `score`, and `nextStep` to fix missing items.
1135
1179
  - [Framework Commands](references/framework-commands.md) — command mapping for all supported frameworks
1136
1180
  - [Nginx Templates](references/nginx-templates.md) — nginx configuration templates and fallback
1137
1181
  - [Resource Pool](references/resource-pool.md) — 资源池定稿口径:两沙箱类型、申请/限流参数(持久 2U4G×300 + 4U8G×200、非持久 2U4G×1000、overlayer 5GB/实例、EVS 300TB)、配额 1/类型 与 429 三码(Retry-After 仅随配额满与容量不足)语义
1182
+ - [DevBox backend](references/devbox-backend.md) — `HW_SANDBOX_BACKEND=devbox` 运维开关、租户/凭证口径、one-shot 部署/SSR、预览 URL、限制
1138
1183
  - [Tunnel persistence](references/tunnel-persistence.md) — renewal, re-attach, and the keepalive watchdog
1139
1184
  - [Full-stack PostgREST](references/fullstack-postgrest.md) — the measured PostgreSQL 16 + PostgREST + nginx procedure
1140
1185
 
@@ -1156,7 +1201,10 @@ Returns `complete: true/false`, `score`, and `nextStep` to fix missing items.
1156
1201
  | Return the deployment URL | Always hand the public URL from the host log to the developer as the final result |
1157
1202
  | 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. |
1158
1203
  | 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. |
1159
- | Session state persists | `exec_with_session` preserves `cd`, env vars, aliases between calls |
1204
+ | Session state persists (legacy only) | On the legacy DevStation backend `exec_with_session` preserves `cd`, env vars, aliases between calls. On devbox it degrades to one-shot and returns `degraded:true`/`statePersisted:false` — commands must be self-contained |
1205
+ | devbox preview is one public port | `expose_tunnel` on devbox returns the app-port URL directly (no tunnel). The app MUST bind `0.0.0.0`; a `127.0.0.1`-only app is unreachable. `expose_poll`/`renew_tunnel`/`keepalive_watchdog` are not applicable. |
1206
+ | devbox kill is irreversible | `kill` deletes the sandbox permanently (data and URL gone); ask for a second confirmation and prefer `shutdown` (pause, 168h retention) unless the developer explicitly wants deletion. `kill` on legacy returns `HDKIT_BACKEND_UNSUPPORTED`. |
1207
+ | devbox credentials unsupported | `huaweicloud_sandbox_credentials` returns `HDKIT_BACKEND_UNSUPPORTED` on devbox; use connect `envVars` or write `/tmp` files with `exec_one_shot`. |
1160
1208
  | 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). |
1161
1209
  | 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. |
1162
1210
  | 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. |
@@ -1190,12 +1238,15 @@ node --version
1190
1238
 
1191
1239
  ## Environment Variables
1192
1240
 
1193
- | Variable | Required | Description |
1194
- | ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1195
- | `HW_ACCESS_KEY` | Yes | Huawei Cloud AK |
1196
- | `HW_SECRET_KEY` | Yes | Huawei Cloud SK |
1197
- | `HW_SECURITY_TOKEN` | No | STS security token |
1198
- | `HW_API_KEY` | No | DevBridge API Key (`devbridge_...`) — required for devbridge 0.2.x tunnel login; injected into the sandbox via `huaweicloud_sandbox_credentials` (`api_key` param or local env) |
1199
- | `HW_WORKSPACE_ID` | No | Default workspace ID |
1200
- | `HDKITSERVICE_ENDPOINT` | No | hdkitservice API endpoint (default: devkit.huaweicloud.com) |
1201
- | `HWLINK_ENDPOINT` | No | DevStation API endpoint (default: devstation.myhuaweicloud.com) |
1241
+ | Variable | Required | Description |
1242
+ | ----------------------------------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1243
+ | `HW_ACCESS_KEY` | Yes | Huawei Cloud AK |
1244
+ | `HW_SECRET_KEY` | Yes | Huawei Cloud SK |
1245
+ | `HW_SECURITY_TOKEN` | No | STS security token |
1246
+ | `HW_API_KEY` | No | DevBridge API Key (`devbridge_...`) — required for devbridge 0.2.x tunnel login; injected into the sandbox via `huaweicloud_sandbox_credentials` (`api_key` param or local env) |
1247
+ | `HW_WORKSPACE_ID` | No | Default workspace ID |
1248
+ | `HDKITSERVICE_ENDPOINT` | No | hdkitservice API endpoint (default: devkit.huaweicloud.com) |
1249
+ | `HWLINK_ENDPOINT` | No | DevStation API endpoint (default: devstation.myhuaweicloud.com) |
1250
+ | `HW_SANDBOX_BACKEND` | No | `legacy` (default) or `devbox`; unknown values fail fast at startup |
1251
+ | `HW_SANDBOX_CONNECT_TIMEOUT_SECONDS` | No | devbox TTL for connect/refresh (10-86400, default 1800) |
1252
+ | `DEVBOX_TLS_INSECURE` / `DEVBOX_TEST_GATEWAY_HOST` / `DEVBOX_TEST_GATEWAY_IP` | No | TEST-ONLY devbox transport overrides; never set in production |
@@ -0,0 +1,78 @@
1
+ <!-- generated from src/packs/sandbox/skills/huawei-sandbox - do not edit -->
2
+
3
+ # DevBox 后端(HW_SANDBOX_BACKEND=devbox)
4
+
5
+ > 平台资源池方案。`legacy`(默认)走 DevStation/hwlink;`devbox` 走 hdkitservice `/sandbox/devbox/*` + DevBox EnvD。
6
+ > 本文件是 v1 口径;与代码冲突时以代码与实测为准。
7
+
8
+ ## 开关与回退
9
+
10
+ - `HW_SANDBOX_BACKEND=legacy|devbox`;未知值启动即报错,不做静默回退。
11
+ - connect 成功后 workspace→backend 记在进程内;会话中途改 env 不会把已连接 workspace 路由到另一个后端。
12
+ - 已存在的 legacy 沙箱不跨后端迁移;回退到 `legacy` 后用 legacy 的 connect 重新接管原 DevStation 实例。
13
+ - `HW_SANDBOX_CONNECT_TIMEOUT_SECONDS`:devbox connect/refresh 的默认 TTL(10–86400,默认 1800)。
14
+ - 测试专用(生产禁止):`DEVBOX_TLS_INSECURE=1`、`DEVBOX_TEST_GATEWAY_HOST`、`DEVBOX_TEST_GATEWAY_IP`。只影响 devbox 数据面/控制面;生产必须严格 TLS、真实域名。
15
+
16
+ ## 租户与凭证(A:每次 AK/SK)
17
+
18
+ - tenant = STS `principal_id`:每个 IAM 子账号独立租户、独立一台 ephemeral 沙箱;主账号自身也是独立租户。`account_id`/domain 只审计,不参与隔离/配额。
19
+ - 所有控制面(connect / refresh / shutdown / kill / status)每次都用 AK/SK(+ 可选 `X-HW-Security-Token`)调 hdkitservice;**没有 sandbox key**,没有 key 表/本地 store/多 key/吊销。
20
+ - v1 只接受 `principal_urn` 为 `:user:` 的凭证;agency/临时凭证返回 `HDKIT_IDENTITY_UNSUPPORTED`(403)。
21
+ - 凭证失效/轮换或 devkit 重启 → 401 `HDKIT_CREDENTIAL_INVALID` → 重新认证(`auth init` / `auth switch`)。`HDKIT_CREDENTIAL_FORBIDDEN`(403)是 IAM 授权问题,不要当过期重登;`HDKIT_IAM_ERROR`(502)是上游 IAM 失败,重试即可。
22
+ - 单沙箱 EnvD `connect_token` / `envd_access_token` 只在 devkit 进程内存;不进 tool result/日志/落盘。数据面 401 时自动 refresh + 重试一次(仍失败需要重新认证)。
23
+
24
+ ## 生命周期
25
+
26
+ | 项 | devbox v1 |
27
+ | -------- | -------------------------------------------------------------------------------------------- |
28
+ | 池类型 | 仅 `ephemeral`;`persistent` → `HDKIT_BACKEND_UNSUPPORTED`,不创建、不静默降级 |
29
+ | TTL | `timeout_seconds`(10–86400,默认 1800);connect/refresh 延长同一沙箱 |
30
+ | shutdown | = pause;默认保留 168h,暂停仍计入平台 Key 容量 |
31
+ | kill | = delete;不可逆,独立工具 + always 审批 + 二次确认;legacy 返回 `HDKIT_BACKEND_UNSUPPORTED` |
32
+ | 回收 | 业务层每小时兜底:`paused_at` 超 168h 主动 DELETE;所有软删除路径释放 `active_slot` |
33
+ | 重启复用 | 有效 AK/SK 重新 connect 复用原 sandbox(running/paused);暂停先 resume |
34
+ | 账号切换 | 下一次控制面调用用新 AK/SK 重新认证,天然路由到新 tenant |
35
+
36
+ ## 平台 Key 池(服务端)
37
+
38
+ - 同账号最多 20 个 DevBox API Key,同一 Namespace;每 Key 容量默认 100。Key 只存在 hdkitservice 配置/密钥管理,永不进 devkit。
39
+ - create 前原子预留(`devbox_platform_key_usage` 行 + reservation);失败/删除释放;暂停不释放。
40
+ - 沙箱按创建它的 `platform_key_id` 路由,不跨 Key 兜底;Key 不可用 → `HDKIT_DEVBOX_KEY_UNAVAILABLE`(502)。
41
+ - 孤儿收养按 metadata `devkit_reservation_id` 幂等,不盲目 `used+1`;stale 清理同事务先 released 再按全集重算 used。
42
+ - 同账号 Key 轮换:新 Key active;旧 Key draining(只停新建,已有沙箱继续)。
43
+
44
+ ## 数据面(EnvD one-shot)
45
+
46
+ - 执行:`POST /process.Process/Start`,非 PTY,`/bin/bash -l -c <command>`,读到 `end`;不实现 `Process/Connect`、`SendInput`、`SendSignal`、PTY。
47
+ - 文件:`GET/POST /files?path=<abs>`;upload_project 用 tar.gz + 沙箱内解压。
48
+ - 头:`Cookie: relay_token=<connectToken>` + `X-Access-Token` + `E2B-Sandbox-Id` + `E2B-Sandbox-Port: 49983`。
49
+ - `exec_with_session` 降级 one-shot,返回 `degraded:true` / `statePersisted:false`;`close_session` not_applicable。
50
+ - async 仍用 V2 claim 协议(`exec_one_shot` mode:"async" + `exec_poll`)。
51
+
52
+ ## 预览
53
+
54
+ - `expose_tunnel` 直接返回应用端口 URL(把 envdUrl 主机的 `-49983` 换成 `-<port>`),不走 DevBridge、不建隧道、不装 keepalive。
55
+ - **单端口、默认公开**;应用必须绑定 `0.0.0.0`(`127.0.0.1` 不可达)。
56
+ - `expose_poll` / `renew_tunnel` / `keepalive_watchdog` 返回 `HDKIT_BACKEND_UNSUPPORTED` + `reason:"not_applicable"`。
57
+
58
+ ## 模板与 nginx
59
+
60
+ - 平台支持自定义模板/镜像;我们团队提供含 nginx 的镜像,平台侧配置 template_id。
61
+ - `default` 模板没有 nginx:可跑 create/connect/exec one-shot/files/app port;`deploy_nginx` 的真实 E2E 等自定义模板到位后再跑。
62
+ - 不做 Python 静态服务器 fallback。
63
+
64
+ ## 常见错误码
65
+
66
+ | 码 | HTTP | 处置 |
67
+ | ------------------------------ | ---- | ------------------------------------------------------------------- |
68
+ | `HDKIT_CREDENTIAL_INVALID` | 401 | AK/SK 无效/失效 → 重新认证 |
69
+ | `HDKIT_CREDENTIAL_EXPIRED` | 401 | 临时凭证过期(v1 保留,未来支持) |
70
+ | `HDKIT_CREDENTIAL_FORBIDDEN` | 403 | IAM 无权限 → 修授权,不是重登 |
71
+ | `HDKIT_IDENTITY_UNSUPPORTED` | 403 | agency/临时凭证 → v1 不支持 |
72
+ | `HDKIT_IAM_ERROR` | 502 | 上游 IAM 失败 → 稍后重试 |
73
+ | `HDKIT_CONNECT_IN_PROGRESS` | 409 | 同租户并发 connect → 稍后重试 |
74
+ | `HDKIT_DEVBOX_CREATE_FAILED` | 502 | 平台创建失败,带 request id |
75
+ | `HDKIT_DEVBOX_KEY_UNAVAILABLE` | 502 | 平台 Key 容量满/不可用 → 联系运营 |
76
+ | `HDKIT_CAPACITY_INSUFFICIENT` | 429 | 平台资源不足 → 错峰 |
77
+ | `HDKIT_BACKEND_UNSUPPORTED` | 400 | 后端不支持该操作(persistent/kill on legacy/credentials/tunnel 类) |
78
+ | `HDKIT_SANDBOX_NOT_FOUND` | 404 | 不存在或跨 tenant(不泄漏存在性) |
@@ -105,3 +105,17 @@
105
105
  - 池模板当前为**白名单条件实测**(仅对测试账号加白),公开上线后需复测模板 ID 与口径
106
106
  - 上游 429 真实响应结构未实测:服务端映射先按已知错误码实现,联调实测后校准
107
107
  - 沙箱实例状态机外的过渡态(`cde.1000/1002` 排队中)由服务端等待超时兜底
108
+
109
+ ## DevBox 后端(平台资源池方案,HW_SANDBOX_BACKEND=devbox)
110
+
111
+ 本节只描述 devbox;上面的 legacy 两池口径不变。devbox v1 仅支持 ephemeral,收到 persistent 返回 HDKIT_BACKEND_UNSUPPORTED。
112
+
113
+ - 租户:tenant = STS principal_id(每个 IAM 子账号独立一台 ephemeral;domain 只审计);v1 只接受 :user:,agency/临时凭证拒绝 HDKIT_IDENTITY_UNSUPPORTED。
114
+ - 凭证:所有控制面每次用 AK/SK(+ 可选 X-HW-Security-Token);没有 sandbox key;失效/轮换/重启需重新认证;HDKIT_IAM_ERROR 502 是上游 IAM 失败。
115
+ - 平台 Key 池(服务端):同账号最多 20 Key、同一 Namespace、每 Key 默认容量 100;创建前原子预留,暂停计入容量,删除释放;按创建 Key 路由不跨 Key;Key 不可用返回 HDKIT_DEVBOX_KEY_UNAVAILABLE。
116
+ - 生命周期:TTL 由 connect 的 timeout_seconds 控制(10-86400,默认 1800);shutdown=pause(默认保留 168h);kill=delete(不可逆,devbox-only,单独审批);业务层每小时回收超期 paused。
117
+ - 数据面:EnvD one-shot Process/Start(非 PTY)+ /files;exec_with_session 降级 one-shot(degraded:true/statePersisted:false);close_session not_applicable;async 仍走 claim 协议。
118
+ - 预览:expose_tunnel 直接返回应用端口 URL;单端口公开,应用必须绑定 0.0.0.0;expose_poll/renew_tunnel/keepalive_watchdog not_applicable;不使用 DevBridge。
119
+ - 运维开关:HW_SANDBOX_BACKEND=legacy|devbox;DEVBOX_TLS_INSECURE / DEVBOX_TEST_GATEWAY_* 仅测试,生产严格 TLS/真实域名。
120
+
121
+ 完整口径见 [devbox-backend.md](devbox-backend.md)。
@@ -18,12 +18,13 @@ One per line, append-shaped: a sibling registration adds its tools here without
18
18
  - `huaweicloud_sandbox_sign_agreement`
19
19
  - `huaweicloud_sandbox_credentials`
20
20
  - `huaweicloud_sandbox_shutdown`
21
+ - `huaweicloud_sandbox_kill`
21
22
  - `huaweicloud_auth_init`
22
23
  - `huaweicloud_auth_switch`
23
24
 
24
25
  ## The two gate flavors
25
26
 
26
- - **Always.** The call confirms on every invocation — connect, shutdown, the tunnel faces, sign_agreement, credentials, and the hcloud run face's write-classified commands. No content rule ever exempts them.
27
+ - **Always.** The call confirms on every invocation — connect, shutdown, kill (devbox-only delete), the tunnel faces, sign_agreement, credentials, and the hcloud run face's write-classified commands. No content rule ever exempts them.
27
28
  - **Classified.** The two sandbox exec faces classify the `command` string first (the same engines the Bash safety face uses). A benign command runs with NO confirmation surface at all — no form, no envelope, no token. A write-classified command confirms on every call. The strict engine refuses some content with the rule named and no confirmation unlocks it — the families its rows cover: credential-file reads, environment dumps, recursive forced rm in any combined-flag spelling (`rm -rf`/`-fr`, flags interposed or after the target, `--`, quoted, glob, `$VAR`, dot-prefixed names, `.`, `..`, `~`, `$HOME`, `*`, `--no-preserve-root`), `find` with `-delete`, pipelines sweeping files into rm, downloads piped into a shell, 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), and treat any refusal as a boundary to rework.
28
29
 
29
30
  The same destructive rows also deny on the agent's own Bash face through the safety hook (the operator-approved widening): unanchored recursive rm — any combined-flag spelling, including `rm -rf node_modules` and the quoted/glob/`$VAR` forms — and `find … -delete` now refuse 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.
@@ -40,6 +40,7 @@ export const APPROVAL_TOOLS = [
40
40
  'huaweicloud_sandbox_sign_agreement',
41
41
  'huaweicloud_sandbox_credentials',
42
42
  'huaweicloud_sandbox_shutdown',
43
+ 'huaweicloud_sandbox_kill',
43
44
  'huaweicloud_auth_init',
44
45
  'huaweicloud_auth_switch',
45
46
  'huaweicloud_obs_set_website_config',
@@ -105,6 +106,7 @@ export const APPROVAL_TOOL_INPUT_SHAPES: Record<(typeof APPROVAL_TOOLS)[number],
105
106
  huaweicloud_sandbox_sign_agreement: 'structured',
106
107
  huaweicloud_sandbox_credentials: 'structured',
107
108
  huaweicloud_sandbox_shutdown: 'structured',
109
+ huaweicloud_sandbox_kill: 'structured',
108
110
  huaweicloud_auth_init: 'structured',
109
111
  huaweicloud_auth_switch: 'structured',
110
112
  huaweicloud_obs_set_website_config: 'structured',
@@ -353,6 +353,13 @@ const NON_RETRYABLE_CLIENT_CODES: ReadonlySet<string> = new Set([
353
353
  'HDKIT_NOT_REALNAME',
354
354
  'HDKIT_NOT_AGREEMENT',
355
355
  'HDKIT_NOT_REALNAME_AND_AGREEMENT',
356
+ // DevBox control-plane verdicts: re-authentication / IAM authorization /
357
+ // backend-scope rejections cannot be advanced by retrying the same call.
358
+ 'HDKIT_CREDENTIAL_INVALID',
359
+ 'HDKIT_CREDENTIAL_EXPIRED',
360
+ 'HDKIT_CREDENTIAL_FORBIDDEN',
361
+ 'HDKIT_IDENTITY_UNSUPPORTED',
362
+ 'HDKIT_BACKEND_UNSUPPORTED',
356
363
  ]);
357
364
 
358
365
  export function isNonRetryableBusinessError(error: unknown): boolean {
@@ -139,7 +139,9 @@ function transportReason(error: unknown, fallback: string): Error {
139
139
  return Object.assign(new Error(cleanMessage(reason) || fallback), { bodyUnreadable: true });
140
140
  }
141
141
 
142
- async function hdkitRequest(
142
+ // Devbox control plane reuses the exact same credential/token/retry envelope;
143
+ // exported for devbox-service-api.ts (the design keeps one request seam).
144
+ export async function hdkitRequest(
143
145
  method: string,
144
146
  path: string,
145
147
  body: unknown,
@@ -304,6 +306,33 @@ async function hdkitRequest(
304
306
  ],
305
307
  };
306
308
  }
309
+ // Devbox 控制面凭证码(A:每次 AK/SK,无 sandbox key):401 重新认证、
310
+ // 403 修 IAM 授权、identity 不支持 agency/临时凭证——都不是重试能推进的。
311
+ if (canonCode(code) === 'HDKIT_CREDENTIAL_INVALID' || canonCode(code) === 'HDKIT_CREDENTIAL_EXPIRED') {
312
+ err.remediation = {
313
+ hint: 'DevBox 控制面凭证无效或已失效(devbox 没有 sandbox key,每次调用都用 AK/SK):',
314
+ steps: [
315
+ '运行 npx huaweicloud-devkit auth init 重新配置有效 AK/SK(或 huaweicloud_auth_switch)',
316
+ '临时凭证已过期时先刷新 STS 凭证再重试',
317
+ '重新认证后 connect 会复用原 sandbox(running/paused),不会新建',
318
+ ],
319
+ };
320
+ }
321
+ if (canonCode(code) === 'HDKIT_CREDENTIAL_FORBIDDEN') {
322
+ err.remediation = {
323
+ hint: '当前账号无权限执行 DevBox 控制面操作:',
324
+ steps: ['检查 IAM 授权是否包含所需沙箱/DevBox 权限', '不要当作凭证过期反复重登;授权修正后重试'],
325
+ };
326
+ }
327
+ if (canonCode(code) === 'HDKIT_IDENTITY_UNSUPPORTED') {
328
+ err.remediation = {
329
+ hint: 'devbox v1 只接受 IAM 用户(principal_urn 为 :user:)的凭证:',
330
+ steps: [
331
+ '改用 IAM 用户的永久 AK/SK(临时/agency 凭证不在 v1 范围)',
332
+ '不要降级成 account 级租户;每个 IAM 子账号独立 sandbox',
333
+ ],
334
+ };
335
+ }
307
336
  // 429 三错误码(两池配额契约 + 用户级模板 running 上限,dev dff5df91 + 45dd4f99):
308
337
  // 配额满与模板上限给出各自的引导;池容量不足只透传服务端最终文案
309
338
  // (“DevKit 免费资源当前使用人数较多,建议您错峰使用,感谢理解!”),不再附加
@@ -284,6 +284,28 @@ export function enrichConnectResult<T>(result: T, options: { announce?: boolean
284
284
  const rec = result as Record<string, unknown>;
285
285
  const poolType = asString(rec.pool_type || rec.poolType);
286
286
  const announce = options.announce !== false;
287
+ // Devbox lifecycle is server-authoritative (end_at / token_expiration /
288
+ // pause_retention_hours), NOT the DevStation idle policy numbers. Never fall
289
+ // through to the legacy idle shutdown/delete broadcast on this backend.
290
+ if (asString(rec.backend) === 'devbox') {
291
+ if (!announce) {
292
+ delete rec.pool;
293
+ return result;
294
+ }
295
+ const endAt = asString(rec.end_at || rec.endAt);
296
+ const tokenExpiration = asString(rec.token_expiration || rec.tokenExpiration);
297
+ const retentionRaw = rec.pause_retention_hours ?? rec.pauseRetentionHours;
298
+ const retention = typeof retentionRaw === 'number' && retentionRaw > 0 ? retentionRaw : 168;
299
+ rec.pool = {
300
+ pool_type: 'ephemeral',
301
+ lifecycle: `devbox ephemeral sandbox${endAt ? `; TTL ends ${endAt}` : ''}; pause retention ${retention}h`,
302
+ ttl_hint:
303
+ `DevBox 沙箱${endAt ? `到期时间 ${endAt}` : '按平台 TTL 到期'};` +
304
+ `shutdown 暂停后保留 ${retention} 小时,超期由平台回收。重要数据请及时保存或迁出。` +
305
+ (tokenExpiration ? ` EnvD 数据面 token 到期时间 ${tokenExpiration},devkit 会自动刷新一次。` : ''),
306
+ } satisfies ConnectPoolBroadcast;
307
+ return result;
308
+ }
287
309
  if (!announce || !poolType || !isPoolType(poolType)) {
288
310
  delete rec.pool;
289
311
  return result;
@@ -1,4 +1,12 @@
1
- import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http';
1
+ import {
2
+ createServer,
3
+ type IncomingHttpHeaders,
4
+ type IncomingMessage,
5
+ type Server,
6
+ type ServerResponse,
7
+ } from 'node:http';
8
+ import { timingSafeEqual } from 'node:crypto';
9
+ import { readFileSync } from 'node:fs';
2
10
  import { format } from 'node:util';
3
11
  import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
4
12
  import type { JSONRPCMessage } from '@modelcontextprotocol/sdk/types.js';
@@ -12,6 +20,7 @@ export const DEFAULT_HOST = '127.0.0.1';
12
20
  interface RemoteServerOptions {
13
21
  port?: number;
14
22
  host?: string;
23
+ authPasswordFile?: string;
15
24
  }
16
25
 
17
26
  interface StartedRemoteServer {
@@ -20,15 +29,46 @@ interface StartedRemoteServer {
20
29
  close: () => Promise<void>;
21
30
  }
22
31
 
32
+ // Constant-time comparison over the raw bytes: length is checked once
33
+ // (an early exit on length only reveals whether the length matches —
34
+ // the generated password is fixed-length, so nothing usable leaks), and
35
+ // equal-length comparison runs in constant time. Plain `===` would leak
36
+ // how many leading characters a guess got right.
37
+ function constantTimeEquals(actual: string, expected: string): boolean {
38
+ const actualBytes = Buffer.from(actual, 'utf8');
39
+ const expectedBytes = Buffer.from(expected, 'utf8');
40
+ return actualBytes.length === expectedBytes.length && timingSafeEqual(actualBytes, expectedBytes);
41
+ }
42
+
43
+ // Pure helper: does an HTTP request carry the expected password? Accepted
44
+ // either as `Authorization: Bearer <password>` or as a direct
45
+ // `x-devkit-password` header. An empty expected password means auth is off
46
+ // and every request passes. Exported for tests.
47
+ export function verifyAuthPassword(headers: IncomingHttpHeaders, expected: string): boolean {
48
+ if (!expected) return true;
49
+ const auth = String(headers.authorization ?? '').trim();
50
+ const bearer = auth.startsWith('Bearer ') ? auth.slice(7).trim() : '';
51
+ if (bearer && constantTimeEquals(bearer, expected)) return true;
52
+ const direct = String(headers['x-devkit-password'] ?? '').trim();
53
+ return direct.length > 0 && constantTimeEquals(direct, expected);
54
+ }
55
+
23
56
  export async function startRemoteServer({
24
57
  port = DEFAULT_PORT,
25
58
  host = DEFAULT_HOST,
59
+ authPasswordFile,
26
60
  }: RemoteServerOptions = {}): Promise<StartedRemoteServer> {
61
+ // Fail closed: an unreadable or missing password file aborts startup —
62
+ // a misconfigured auth flag must never degrade to open access.
63
+ let authPassword = '';
64
+ if (authPasswordFile) {
65
+ authPassword = readFileSync(authPasswordFile, 'utf8').trim();
66
+ }
27
67
  // node:http wants a void-returning listener; the async request handling
28
68
  // lives in handleRemoteRequest and every failure path inside it answers
29
69
  // the response (400/202/500) rather than rejecting.
30
70
  const server = createServer((req, res) => {
31
- void handleRemoteRequest(req, res);
71
+ void handleRemoteRequest(req, res, authPassword);
32
72
  });
33
73
 
34
74
  await new Promise<void>((resolvePromise, rejectPromise) => {
@@ -49,12 +89,12 @@ export async function startRemoteServer({
49
89
  };
50
90
  }
51
91
 
52
- async function handleRemoteRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
92
+ async function handleRemoteRequest(req: IncomingMessage, res: ServerResponse, authPassword: string): Promise<void> {
53
93
  res.setHeader('Access-Control-Allow-Origin', '*');
54
94
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
55
95
  res.setHeader(
56
96
  'Access-Control-Allow-Headers',
57
- 'Content-Type, MCP-Protocol-Version, Mcp-Session-Id, Accept, Authorization',
97
+ 'Content-Type, MCP-Protocol-Version, Mcp-Session-Id, Accept, Authorization, X-DevKit-Password',
58
98
  );
59
99
  res.setHeader('Access-Control-Expose-Headers', 'MCP-Protocol-Version, Mcp-Session-Id');
60
100
 
@@ -64,9 +104,32 @@ async function handleRemoteRequest(req: IncomingMessage, res: ServerResponse): P
64
104
  return;
65
105
  }
66
106
 
107
+ // Liveness stays unauthenticated by contract: load balancers and systemd
108
+ // watchdogs must observe health without knowing the password. Query
109
+ // strings are stripped so probes like /health?probe=1 keep working.
110
+ if (req.method === 'GET' && (req.url ?? '').split('?')[0] === '/health') {
111
+ res.writeHead(200, { 'Content-Type': 'application/json' });
112
+ res.end(JSON.stringify({ ok: true }));
113
+ return;
114
+ }
115
+
116
+ // The auth gate runs before the shell method filter, so an unauthorized
117
+ // request is told 401 even for non-POST methods (mirrors the v1 server
118
+ // face); everything except /health needs the password when one is set.
119
+ if (authPassword && !verifyAuthPassword(req.headers, authPassword)) {
120
+ res.writeHead(401, {
121
+ 'Content-Type': 'application/json',
122
+ 'WWW-Authenticate': 'Bearer realm="huaweicloud-devkit-mcp"',
123
+ });
124
+ res.end(
125
+ JSON.stringify({ error: 'Unauthorized', hint: 'send Authorization: Bearer <password> or x-devkit-password' }),
126
+ );
127
+ return;
128
+ }
129
+
67
130
  // The shell keeps the method filter: GET stays 405 (legacy contract; the
68
131
  // SDK transport would turn it into a 406/200 SSE stream) and only POST
69
- // reaches the transport.
132
+ // reaches the transport. /health above is the one GET carve-out.
70
133
  if (req.method !== 'POST') {
71
134
  res.writeHead(405, { Allow: 'POST, OPTIONS' });
72
135
  res.end();
@@ -16,6 +16,9 @@ const portIdx = process.argv.indexOf('--port');
16
16
  const remotePort = portIdx > -1 ? Number(process.argv[portIdx + 1]) : DEFAULT_PORT;
17
17
  const hostIdx = process.argv.indexOf('--host');
18
18
  const remoteHost = hostIdx > -1 && process.argv[hostIdx + 1] ? process.argv[hostIdx + 1] : DEFAULT_HOST;
19
+ const authFileIdx = process.argv.indexOf('--auth-password-file');
20
+ const authFileArg = authFileIdx > -1 ? process.argv[authFileIdx + 1] : undefined;
21
+ const authPasswordFile = authFileArg ? resolve(authFileArg) : undefined;
19
22
 
20
23
  const projectDirIdx = process.argv.indexOf('--codearts-project-dir');
21
24
  if (projectDirIdx > -1 && process.argv[projectDirIdx + 1]) {
@@ -75,7 +78,7 @@ if (transport === 'remote') {
75
78
  );
76
79
  }
77
80
  const { startRemoteServer } = await import('./mcp-server-remote.ts');
78
- startRemoteServer({ port: remotePort, host: remoteHost }).catch((error: unknown) => {
81
+ startRemoteServer({ port: remotePort, host: remoteHost, authPasswordFile }).catch((error: unknown) => {
79
82
  process.stderr.write(
80
83
  `Failed to start MCP remote server: ${error instanceof Error ? error.message : String(error)}\n`,
81
84
  );
@@ -82,6 +82,7 @@ export const PACK_OF = {
82
82
  huaweicloud_sandbox_connect: 'sandbox',
83
83
  huaweicloud_sandbox_credentials: 'sandbox',
84
84
  huaweicloud_sandbox_shutdown: 'sandbox',
85
+ huaweicloud_sandbox_kill: 'sandbox',
85
86
  huaweicloud_voucher_status: 'voucher',
86
87
  huaweicloud_voucher_claim: 'voucher',
87
88
  huaweicloud_competition_voucher_claim: 'voucher',
@@ -7,10 +7,10 @@ import { isSecretRef } from '../../lib/secret-vault/refs.ts';
7
7
  import type { ApprovalSpec } from '../../approval-types.ts';
8
8
  import type { ToolArgs } from '../../tools.ts';
9
9
 
10
- // The sandbox pack's approval spec table. Nine tools join the gate: the two
10
+ // The sandbox pack's approval spec table. Ten tools join the gate: the two
11
11
  // exec faces are CLASSIFIED (content decides — a benign command runs with no
12
12
  // confirmation surface at all, a write-classified one confirms on every
13
- // call), the seven mutating lifecycle faces are ALWAYS (a human present per
13
+ // call), the eight mutating lifecycle faces are ALWAYS (a human present per
14
14
  // call, no content rule ever exempts them). The strict classification runs
15
15
  // on the exec faces' `command` argument through the SAME engines the Bash
16
16
  // face uses — classifyTextCommand plus the cloud-risk-rules catalog — so a
@@ -283,6 +283,18 @@ const shutdownSpec: ApprovalSpec = {
283
283
  }),
284
284
  };
285
285
 
286
+ // kill = devbox-only DELETE (irreversible). The confirmation view must say
287
+ // delete, not close: shutdown keeps the instance, kill does not.
288
+ const killSpec: ApprovalSpec = {
289
+ ...sandboxBinding(),
290
+ flavor: 'always',
291
+ summarize: (bindingValue) =>
292
+ viewOf(bindingValue, (view) => {
293
+ const target = fieldEcho(view, ['session_id', 'dev_stage_id', 'workspace_id']);
294
+ return `huaweicloud_sandbox_kill: DELETE the devbox sandbox permanently (irreversible — use shutdown to keep the instance)${target !== '' ? ` (${target})` : ''}`;
295
+ }),
296
+ };
297
+
286
298
  export const SANDBOX_APPROVAL_SPECS = {
287
299
  huaweicloud_sandbox_connect: connectSpec,
288
300
  huaweicloud_sandbox_exec_with_session: execSpec('exec_with_session'),
@@ -293,4 +305,5 @@ export const SANDBOX_APPROVAL_SPECS = {
293
305
  huaweicloud_sandbox_sign_agreement: signAgreementSpec,
294
306
  huaweicloud_sandbox_credentials: credentialsSpec,
295
307
  huaweicloud_sandbox_shutdown: shutdownSpec,
308
+ huaweicloud_sandbox_kill: killSpec,
296
309
  } as const satisfies Record<string, ApprovalSpec>;