Huawei sandbox

From huaweicloud/huaweicloud-devkit · View interactive version

Huawei sandbox is an AI agent skill from the GitHub repository huaweicloud/huaweicloud-devkit. Use when creating, connecting, or managing Huawei Cloud Sandbox instances and workspace terminals, or when a task needs a temporary runtime to deploy, run, or preview a web application, backend service, or full-stack workbench. Covers sandbox lifecycle (check-user, sign-agreement, connect, shutdown,

How to use this skill

Skill file

Huawei Cloud Sandbox

STOP - Do not answer from general knowledge. Follow the procedure below.

Target-Selection Gate (MANDATORY — do not skip)

When the developer asks to deploy / host / publish / 上线 / 部署 / 发布 / 搭建 a website, web app, or static site WITHOUT naming a specific target, you MUST present the target options and obtain an explicit choice BEFORE calling any sandbox lifecycle tool (huaweicloud_sandbox_check_user, huaweicloud_sandbox_connect, huaweicloud_sandbox_upload_project, huaweicloud_sandbox_deploy_nginx, etc.).

Use the question tool and present, in this exact order:

  1. 沙箱 (Sandbox) — temporary runtime, instant preview URL (recommended for quick preview)
  2. OBS 静态托管 — long-term static hosting + CDN + custom domain. Remind the developer: a custom domain (域名) must be prepared in advance — the default OBS endpoint does not support HTTPS for static hosting
  3. ECS — server-based hosting. Remind the developer: ECS must be paired with an EIP (弹性公网IP) for public access — extra billing applies
  4. CCE — container-based hosting

Hard rules:

Stack-Selection Gate (MANDATORY — do not skip)

When the request involves a workbench / 工作台 / 全栈 / full-stack project — front-end plus back-end, CRUD with persistence, or a database-backed app — you MUST treat it as a full-stack workbench deployment: the back end defaults to PostgreSQL + PostgREST even when the developer never mentions 数据库/postgres/CRUD. Do NOT silently fall through to the SPA/nginx-only path.

Use the question tool to confirm the stack whenever the backend is ambiguous, presenting the PostgREST default first:

  1. PostgreSQL + PostgREST 全栈 (recommended) — schema + read-only api_user role, nginx /api/ reverse proxy; the REST layer needs zero application code
  2. 应用自带后端 — the project ships its own server (Express/Next API/Nuxt server routes); deploy it inside the sandbox per its framework
  3. 纯静态/SPA — no persistence; nginx-only

Hard rules:

Pool-Selection Gate (MANDATORY — do not skip)

Before huaweicloud_sandbox_connect, select the pool by task intent, not by tech stack. Default is ephemeral.

1. Default ephemeral

2. Persistent only with explicit or confirmed long-term intent

Use persistent only when:

If the intent is ambiguous, ask exactly one question:

这个任务需要跨会话保留数据吗?① 临时预览/一次性(默认,非持久化) ② 长期/跨天继续(持久化)

3. Task continuity

> 已有持久化沙箱,是否直接复用(保留现有环境/数据),还是新建临时预览环境?

4. Never

Overview

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.

两池沙箱(pool_type)

口径基调:一切以实测为准,口头支持不作数(下表生命周期为实测/平台侧现状;数值为服务端配置下发的默认口径,平台调参以服务端回显为准)。

huaweicloud_sandbox_connect 用 pool_type 选择资源池(服务端权威映射模板;没有 persist_mode 参数;客户端不再支持传 template_id/自定义模板):

下表生命周期数值仅用于内部选池与诊断:ephemeral 不向开发者播报;persistent 只播报沙箱生命周期与核时提醒,不播报隧道有效期/自动续期。

| pool_type | 语义 | 生命周期(平台策略) | 适用 |

| ------------------- | ------------------ | ------------------------------------------------------------ | --------------------------- |

| ephemeral(默认) | 非持久沙箱 | 闲置 30 分钟自动关机 + 闲置 1 小时自动删除(平台定时任务) | 临时运行/预览,勿存重要数据 |

| persistent | 持久沙箱(EVS 盘) | 数据跨关机保留;闲置 1 小时自动关机;闲置回收保留期上限 7 天 | 需要跨会话保留数据 |

Selection rules(按意图自动选池;具体按 Pool-Selection Gate 执行;默认 ephemeral,persistent 需明确长期意图或确认;开发者可覆盖):

| 意图 / 场景 | pool_type | 理由 |

| ---------------------------- | ---------- | -------------------------------------- |

| 预览 / 试用 / demo | ephemeral | 用完即弃,无需保留状态 |

| 一次性任务(跑完即弃) | ephemeral | 结果带出沙箱;实例随闲置回收 |

| 敏感内容(即焚) | ephemeral | 闲置 1 小时自动删除,数据随实例消亡 |

| 带数据库但只是预览/演示 | ephemeral | 预览可重建数据;技术栈不是持久化触发器 |

| 开发工作台 / workbench | persistent | 会话跨天;状态需跨关机保留 |

| 带数据库且需要跨会话保留数据 | persistent | 数据落在挂载的 EVS 盘(32G) |

| 跨日评审 / 展示 | persistent | 评审者后续日期回访;实例保留 |

Activation

MCP Tools

User Verification (Prerequisites)

| Tool | Purpose |

| ------------------------------------ | ----------------------------------------------------------- |

| huaweicloud_sandbox_check_user | Check real-name verification and agreement signing status |

| huaweicloud_sandbox_sign_agreement | Sign unsigned/outdated agreements (required before connect) |

Local Detection

| Tool | Purpose |

| ------------------------------ | ---------------------------------------------------------- |

| huaweicloud_detect_framework | Scan local project, return framework type + build commands |

Sandbox Lifecycle

| Tool | Purpose |

| --------------------------------- | ---------------------------------------------------------------------------------------------------------------- |

| huaweicloud_sandbox_connect | Connect to sandbox (one instance per user per pool; pool_type selects ephemeral/persistent, default ephemeral) |

| huaweicloud_sandbox_credentials | Inject temporary AK/SK into a running sandbox |

| huaweicloud_sandbox_shutdown | Shut down a running sandbox (close only; instance/data disk retained; reconnect wakes it) |

Tunnel Persistence (public URL lifetime)

| Tool | Purpose |

| ---------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

| huaweicloud_sandbox_expose_tunnel | Expose a port → public tunnel URL (auth, pre-clean, health check; expiry_hours 1-720, def 72). AUTO-enrolls into the keepalive watchdog (merged into existing coverage; keepalive: false opts out) |

| huaweicloud_sandbox_renew_tunnel | Renew a tunnel lifetime (update -e, rolling window; returns absolute expiresAt) |

| huaweicloud_sandbox_keepalive_watchdog | Install/replace the 3-layer watchdog: host re-attach + daily 720h renewal + 5-min health check |

Terminal Execution

| Tool | Purpose |

| --------------------------------------- | --------------------------------------------------------------------------- |

| huaweicloud_sandbox_exec_with_session | Session-based execution (state persists; best for interactive work) |

| huaweicloud_sandbox_exec_one_shot | One-shot execution (fresh connection; best for long/heavy commands) |

| huaweicloud_sandbox_upload_file | Upload a local file into the sandbox (chunked base64 write + md5 verify) |

| huaweicloud_sandbox_upload_project | Upload a local project directory to sandbox (HTTP tunnel, tar.gz + extract) |

| huaweicloud_sandbox_deploy_nginx | Deploy nginx config with permissions fix and reload in one call |

| huaweicloud_sandbox_deploy_check | Run deployment completeness check (nginx, DevBridge, URL, QR if needed) |

| huaweicloud_sandbox_close_session | Close a persistent terminal session |

Tool Selection Guide

| Scenario | Use | Why |

| ---------------------------------- | ---------------------------------- | ------------------------------------------------------------ |

| cd, env setup, command chains | exec_with_session | Needs shared shell state across calls |

| npm install, apt-get, builds | exec_one_shot | Long-running (>30s), no state needed, more stable |

| curl, health checks, quick tests | Either — exec_one_shot preferred | Stateless, fast |

| Server startup (background) | exec_with_session | Need to nohup ... & then check output in same session |

| Deployment scripts | exec_one_shot+shot | Long script, fresh connection avoids session timeouts |

| nginx configuration | deploy_nginx | Auto-generates correct template + permissions + reload |

| Deployment completeness check | deploy_check | Verifies nginx, DevBridge, URL, QR before reporting success |

| Tunnel lifetime renewal | renew_tunnel | Rolling-window renewal, same URL stays alive |

| URL must outlive the session | keepalive_watchdog | Unattended host re-attach + daily renewal + health check |

| 暂不使用 / 节省核时 | sandbox_shutdown | 只关机不删除;数据盘保留,下次 connect 自动唤醒 |

| Single file upload (<1MB) | upload_file | Base64 chunked, reliable for small files |

| Project directory upload (>1MB) | upload_project | HTTP tunnel, much faster than base64 for multi-file projects |

Timeout tuning: default is 120s. For commands expected to run longer (e.g. large builds), pass timeout_ms explicitly:

{ "timeout_ms": 300000 }

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.

Timeout recovery: if exec_one_shot returns a timeout error, check whether partial output is available before declaring failure:

Workflow

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 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).

Step 0.5 — Stack-Selection Gate (MANDATORY): before selecting a pool or uploading application code, confirm the backend stack via the Stack-Selection Gate. 工作台/workbench/全栈/full-stack/CRUD/持久化 ⇒ full-stack (PostgreSQL + PostgREST default) — do NOT start an SPA-only deployment for a workbench request.

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. 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.

Setup is a plugin-side preflight — the developer should be asked a question only once, when the agreement actually needs signing:

  1. Check user (transparent): huaweicloud_sandbox_check_user — returns realnameVerified/agreementSigned (200) when all good, OR throws a 403 error with one of these codes:
  1. 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
  2. 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
  3. 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
  4. 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).
  5. 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:

```bash

# Kill stale Node.js web processes from previous deployments

pkill -9 -f "next-server" 2>/dev/null || true

pkill -9 -f "next start" 2>/dev/null || true

pkill -9 -f "nuxt" 2>/dev/null || true

sleep 1

# Remove stale nginx configs from previous deployments

sudo rm -f /etc/nginx/conf.d/.conf /etc/nginx/conf.d/.conf.bak 2>/dev/null

# Remove stale DevBridge tunnels only (keep other ports/sessions):

# list and delete orphan IDs; the automated connect cleanup does this too.

devbridge list

# devbridge delete <orphan-id>

# Reload nginx to apply

sudo nginx -s reload 2>/dev/null || true

```

  1. 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:

```json

{ "dev_stage_id": "<dev_stage_id from connect>" }

```

After injection, credentials are also written to /tmp/hw_creds.sh for shell access (includes HW_PROJECT_ID when resolvable):

```bash

# Source credentials in any sandbox shell before using hcloud/devbridge:

source /tmp/hw_creds.sh 2>/dev/null && echo "Credentials loaded"

```

If source /tmp/hw_creds.sh returns empty, the credentials injection may not have completed — re-run huaweicloud_sandbox_credentials.

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.

  1. 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.
  2. 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.
  3. 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. For ephemeral sandboxes, hand over the URL only: do not include tunnel/sandbox lifetime, auto-renewal, idle shutdown/delete, or migration suggestions. For persistent sandboxes, include only the sandbox lifecycle notice (idle shutdown, data retained, reclaim cap); do not include tunnel expiry or auto-renewal

File Transfer (local → sandbox)

upload_project (preferred for directories)

huaweicloud_sandbox_upload_project packages a local directory as tar.gz, uploads it to the sandbox via HTTP tunnel, and extracts it. This is the fastest way to transfer multi-file projects.

Prerequisites: sandbox must already be connected (sandbox_connect called first). The tool handles everything internally — no manual setup needed.

{
  "local_dir": "/path/to/local/project",
  "remote_dir": "/workspace",
  "extract": true,
  "exclude": [
    "**/node_modules",
    ".git",
    "__pycache__",
    ".next",
    ".nuxt",
    ".output",
    ".turbo",
    ".cache",
    ".swc",
    "dist",
    "coverage",
    "*.pyc"
  ]
}

upload_file (for single files)

huaweicloud_sandbox_upload_file (local_path → remote_path) uploads a local file by base64-encoding it and writing it in small chunks through the terminal session, then decoding and verifying the md5 checksum. Use it for individual files, especially small ones (<1MB).

Exec channel size limit

huaweicloud_sandbox_exec_with_session and huaweicloud_sandbox_exec_one_shot are fragile for long commands and large inline content. Do NOT paste a file's base64 directly into a single command:

| Payload | Result |

| --------------------------- | -------------------------------------- |

| ~30KB base64 in one command | exec timeout |

| ~12KB base64 in one command | session crash (session is not ready) |

| ~4–5KB normal command | OK |

Keep individual exec commands small (≤ ~4KB). For larger content, use huaweicloud_sandbox_upload_file instead.

OBS transfer fallback

When the upload tool is unavailable, transfer through OBS: upload to a public-read object locally, then pull it into the sandbox.

# Local: upload to OBS (public read)
hcloud OBS cp <local-file> obs://<bucket>/<key> -f -acl=public-read
# Sandbox: pull it down
curl -s -o /workspace/<repo>/<file> https://<bucket>.obs.<region>.myhuaweicloud.com/<key>

Requires OBS credentials (huaweicloud_setup_obs_config). Bucket ACL does not cascade to objects — set object-level -acl=public-read for anonymous reads.

Expose the deployed app (public URL)

Expose a deployed web app to a public URL and return that URL to the developer.

Workspace URL vs public share link (401 trap — do not confuse them)

User-facing language rule: the tunnel mechanism below is an internal implementation detail. Never mention "DevBridge", "tunnel", or the tunnel CLI to the developer. Tell the developer only: "正在生成访问地址..." while exposing, then hand over the final URL.

Step 0: Ensure DevBridge CLI 0.2.x (install or upgrade in place)

Check the version first. Sandboxes created before Sep 2026 ship devbridge 0.1.13, whose hardcoded gateway (cn-north-4-bridge.myhuaweicloud.com) was migrated and now serves a 「服务已迁移」 placeholder page — 0.1.x can no longer connect:

export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"   # PREPEND — appending lets a stale image binary in /usr/local/bin win
devbridge version 2>/dev/null || echo "not installed"
# Official installer (GitHub can be slow/flaky from the sandbox — force HTTP/1.1 and retry all errors)
curl -fsSL --http1.1 --retry 3 --retry-all-errors --max-time 120 \
  https://github.com/huaweicloud/devspace-devbridge/releases/latest/download/install.sh \
  -o /tmp/devbridge-install.sh

# Preferred: install via the GitCode mirror (domestic CDN, much faster).
# Extract the version baked into the installer, then point -u at the matching GitCode tag.
# Note: GitCode repo is named "devbrige" (missing 'd') — this is the actual repo name, not a typo.
#       GitHub repo is "devspace-devbridge" (correct spelling). Do NOT "fix" the GitCode URL.
DB_TARGET=$(grep -m1 'DEFAULT_VERSION=' /tmp/devbridge-install.sh | cut -d'"' -f2)
if ! bash /tmp/devbridge-install.sh -s -u "https://gitcode.com/CloudDeveloperDepartment/devbrige/releases/download/${DB_TARGET}" -v "${DB_TARGET}"; then
  bash /tmp/devbridge-install.sh -s   # fallback: GitHub (baked-in URL)
fi
export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"   # PREPEND (session shells do not re-source ~/.bashrc)

# Layer 3 (both installer paths failed): direct GitHub release tar.gz.
# Asset naming is fixed: devbridge_linux_arm64_<version>-release.tar.gz (the sandbox
# is Linux aarch64). If DB_TARGET is empty the installer download itself failed —
# resolve the latest tag from the GitHub releases API first.
# Install to /workspace/.local/bin — /workspace is the sandbox's DATA disk and
# survives reboots; ~/.huawei/bin lives on the SYSTEM disk and a reboot wipes it
# back to the image state (measured 2026-10-22: an overnight reboot reverted
# ~/.huawei/bin/devbridge 0.2.2 to the image's 0.1.13 — yesterday's success
# replayed as today's unexplained failure). (#999)
if ! command -v devbridge >/dev/null 2>&1; then
  [ -z "$DB_TARGET" ] && DB_TARGET=$(curl -fsSL --http1.1 --retry 2 --max-time 60 \
    https://api.github.com/repos/huaweicloud/devspace-devbridge/releases/latest | grep -m1 '"tag_name"' | cut -d'"' -f4)
  mkdir -p /workspace/.local/bin
  curl -fsSL --http1.1 --retry 3 --retry-all-errors --max-time 180 \
    "https://github.com/huaweicloud/devspace-devbridge/releases/download/${DB_TARGET}/devbridge_linux_arm64_${DB_TARGET}.tar.gz" \
    -o /tmp/devbridge.tar.gz \
    && rm -rf /tmp/devbridge-pkg && mkdir -p /tmp/devbridge-pkg \
    && tar -xzf /tmp/devbridge.tar.gz -C /tmp/devbridge-pkg \
    && install -m 0755 /tmp/devbridge-pkg/devbridge /workspace/.local/bin/devbridge
  export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"
fi
devbridge version                     # must print 0.2.x-release

# Remove the stale image-installed binary so only ONE version remains.
# (Image sandboxes ship 0.1.x at /usr/local/bin/devbridge; the installer writes
# /workspace/.local/bin. Compare against the explicit install path — never
# `command -v`, which can resolve to the stale binary itself when PATH order differs.)
if [ -f /usr/local/bin/devbridge ] && [ -x /workspace/.local/bin/devbridge ] && [ "$(readlink -f /usr/local/bin/devbridge)" != "$(readlink -f /workspace/.local/bin/devbridge)" ]; then
  rm -f /usr/local/bin/devbridge && echo "stale /usr/local/bin/devbridge removed"
fi
# A leftover 0.2.x in ~/.huawei/bin (installed by older docs) is valid until the
# next reboot — deduplicate it against the /workspace copy so the version check
# above can never report the image's 0.1.x.
if [ -x "$HOME/.huawei/bin/devbridge" ] && [ -x /workspace/.local/bin/devbridge ] && [ "$(readlink -f "$HOME/.huawei/bin/devbridge")" != "$(readlink -f /workspace/.local/bin/devbridge)" ]; then
  rm -f "$HOME/.huawei/bin/devbridge" && echo "stale ~/.huawei/bin/devbridge removed"
fi

Sandbox filesystem persistence: what survives a reboot (#999)

| Path | Type | After a sandbox reboot |

| -------------------------------------------- | -------------- | ------------------------------------------------------------------------------------ |

| /workspace (incl. /workspace/.local/bin) | Data disk | Survives — install project code and the devbridge 0.2.x binary here |

| $HOME (incl. ~/.huawei/bin) | System disk | Rolled back to the image state — an installed binary is lost, 0.1.13 returns |

| /usr/local/bin | System disk | Rolled back — the image-preinstalled 0.1.x returns |

| /tmp | Session-scoped | Cleared — /tmp/hw_creds.sh, /tmp/hw_api_key, /tmp/tunnel-keepalive.sh are gone |

Measured (2026-10-22): an overnight reboot reverted ~/.huawei/bin/devbridge 0.2.2 to the image's 0.1.13 — yesterday's successful operation replayed as today's unexplained failure. Recovery after a reboot: re-run the Step 0 install (or just re-export the PATH to the surviving /workspace/.local/bin), re-run huaweicloud_sandbox_credentials to re-inject /tmp credentials, and re-run huaweicloud_sandbox_keepalive_watchdog to restore the keepalive loop.

Step 1: Authenticate — API Key only (AK/SK removed, auto-create fallback)

DevBridge authentication is fixed to API Key (定稿决策,2026-11-04)。AK/SK login (--access-key/--secret-key) has been REMOVED — the auth waterfall no longer reads /tmp/hw_creds.sh for devbridge purposes.

Authentication tries sources in order, each verified with a real devbridge auth login --api-key + auth status before use. Note: the probe tests keyring and file in one exec — file hits before auto-create triggers (if a user-provided key exists, it wins over auto-creation):

huaweicloud_sandbox_expose_tunnel runs this waterfall automatically and reports the winning mode (API_KEY_KEYRING / API_KEY_AUTO / API_KEY_FILE) or NO_CREDENTIAL.

Key lifecycle (per account × pool, fixed name):

Quota handling (实测 2026-11-04): 20 key limit per account, error code 13002 → 429 HDKIT_DEVBRIDGE_KEY_QUOTA_EXCEEDED. The structured fallback includes the current key list (with last_used_at for stale detection) and the console cleanup URL: https://devstation.connect.huaweicloud.com/space/devbridge/apikey. devkit-* prefixed keys are plugin-managed (auto-recreated after deletion) — advise users to clean OTHER stale keys first.

Manual equivalent (for debugging, not for agent use):

export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"
export HOME="${HOME:-/root}"
export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=/run/dbus-session}"
# Tier 1: keyring (stderr! prefix filter!)
HW_DB_KEY=$(hwcloud keyring get HW_DEVBRIDGE_API_KEY 2>&1 || true)
case "$HW_DB_KEY" in
  devbridge_*) devbridge auth login --api-key "$HW_DB_KEY" ;;
  *) # Tier 3: file fallback
    source /tmp/hw_api_key 2>/dev/null
    if [ -n "$HW_API_KEY" ]; then devbridge auth login --api-key "$HW_API_KEY"; fi ;;
esac
devbridge auth status

Step 2: Expose

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>:

# 0. Pre-cleanup: replace ONLY the tunnel bound to <port>; keep other ports/sessions.
#    (huaweicloud_sandbox_expose_tunnel does this automatically with cleanup_mode=stale.)
OLD_ID=$(devbridge list 2>/dev/null | awk '$2 ~ /^tunnel-<port>-/ {print $1; exit}')
[ -n "$OLD_ID" ] && devbridge delete "$OLD_ID" >/dev/null 2>&1 || true

# 1. Start tunnel
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
disown 2>/dev/null || true
sleep 10 && cat /tmp/host.log

# 2. Extract tunnel URL and health-check before returning
TUNNEL_URL=$(grep -oP 'Tunnel URL: \K.*' /tmp/host.log)
# --noproxy is MANDATORY (#1000): the sandbox injects an HTTP proxy that does NOT
# route the tunnel domain — without it a working tunnel verifies as 502/404 and
# sends you chasing credentials/version/port.
HTTP_CODE=$(curl -s --noproxy '*' -o /dev/null -w "%{http_code}" --max-time 10 "$TUNNEL_URL" 2>/dev/null || echo "000")
if [ "$HTTP_CODE" = "200" ] || [ "$HTTP_CODE" = "304" ]; then
  echo "Tunnel verified: $TUNNEL_URL (HTTP $HTTP_CODE)"
else
  echo "WARN: Tunnel URL unreachable (HTTP $HTTP_CODE). Rebuilding tunnel..."
  # Rebuild only this port's tunnel; never kill/delete other ports or sessions.
  OLD_ID=$(devbridge list 2>/dev/null | awk '$2 ~ /^tunnel-<port>-/ {print $1; exit}')
  [ -n "$OLD_ID" ] && devbridge delete "$OLD_ID" >/dev/null 2>&1 || true
  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
  disown 2>/dev/null || true
  sleep 10
  TUNNEL_URL=$(grep -oP 'Tunnel URL: \K.*' /tmp/host.log)
  HTTP_CODE=$(curl -s --noproxy '*' -o /dev/null -w "%{http_code}" --max-time 10 "$TUNNEL_URL" 2>/dev/null || echo "000")
  echo "Retry tunnel: $TUNNEL_URL (HTTP $HTTP_CODE)"
fi

Never return a tunnel URL without verifying it first — a stale URL (from a killed tunnel process) will silently fail. Always curl-check before giving the URL to the developer. Note: a migrated gateway serves its placeholder page with HTTP 200 — a bare status check is not enough when diagnosing "200 but wrong content".

Proxy trap on verify commands (#1000): every curl against *.hwtunnel.com MUST pass --noproxy '*' — the sandbox injects an HTTP/HTTPS proxy that does not route the tunnel domain, so a proxied verify returns 502/404 fakes while the tunnel is actually serving. If a tunnel "fails" verification, re-test with --noproxy '*' BEFORE checking versions/credentials/ports (same trap on the SSH path: huawei-ecs skill references/windows-ssh.md §0.1).

Quota recovery: if the tunnel creation fails with 10006: quota exceeded:

# Step A: List all tunnels (both active and stale)
#   0.2.x: `devbridge list` (plain table; data rows start with the 8-char tunnel ID)
#   0.1.x (legacy): `devbridge list -j` (JSON)
devbridge list
# Step B: Remove stale tunnels one by one (the expose tool already does
#   orphans first, then oldest non-keepalive; keep keepalive-protected tunnels)
# devbridge delete <stale-id>
# Step C: Retry tunnel creation
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
disown 2>/dev/null || true
sleep 10 && cat /tmp/host.log

This eliminates the most common deployment failure — historical tunnels from previous sessions accumulating past the max=10 quota.

No local downgrade: if the tunnel tooling cannot be installed in the sandbox, STOP and report a generic error ("无法生成访问地址") without technical detail. Never install it on the developer's local machine — a local install would defeat the purpose of sandbox deployment.

Step 3: Keep the URL alive (persistence & renewal)

AUTO-ENROLLMENT: huaweicloud_sandbox_expose_tunnel automatically enrolls every exposed tunnel into the keepalive watchdog (merged into existing coverage — exposing a second tunnel never drops the first one's protection; keepalive: false opts out). The developer's requirement — "every tunnel deployed to the sandbox must be keepalive-protected" — is satisfied by the tool itself, not by remembering to call the watchdog.

The tunnel URL is bound to the tunnel ID, not the host process — persistence is about preventing expiry, never URL recovery. -e accepts 1..720 hours (720 = the 30-day maximum); the expiry is a rolling window (renewal sets expiration = now + hours regardless of remaining time), so renewing before expiry keeps the same URL alive indefinitely.

Complete measured procedure and traps (OSC-escape port list, health-check URL, watchdog pgrep): see references/tunnel-persistence.md.

Full-Stack: REST API over PostgreSQL (PostgREST)

When deploying a full-stack workbench project (前后端工作台) or asking for a database-backed REST API inside the sandbox (postgres, postgrest, 数据库, RESTful 接口, 工作台后端):

  1. PostgreSQL 16 from PGDG — the OS repo only ships PG 13, and PostgREST 16.x requires PG ≥ 14. HCE is NOT el8-lib-compatible: hand-write the repo file (the el8 path is rhel-8-aarch64 WITH a hyphen), install the RPMs one-per-call with --nodeps, and shim the sonames — including the REAL libicu-60 package (ICU symlinks load but crash on versioned symbols).
  2. PostgREST linux-static-aarch64 — dynamic Ubuntu builds fail on HCE glibc. Create the schema and a read-only api_user role (the anon role gates all writes; POST/PATCH → 401).
  3. Nginx single-origin — / serves the frontend, /api/ reverse-proxies to PostgREST (no CORS, same origin). The frontend dir needs chmod o+x on the whole path chain or nginx returns 403.
  4. Expose + keep alive (automatic) — huaweicloud_sandbox_expose_tunnel with the nginx port; it AUTO-enrolls the tunnel into the keepalive watchdog (merged into existing coverage). Prefer expiry_hours: 720 for long-lived workbench deployments.

Complete measured procedure (full command chain) plus the 2026-10 field notes (Aliyun mirror URLs, cross-mirror resume corruption, upload_file 640 → PGRST002, exec-channel escaping → upload files and run psql -f / curl -d @file): see references/fullstack-postgrest.md. For the sandbox restart recovery checklist (what survives on /workspace vs what is lost on the 系统盘, plus the write-GRANT rollback trap): see the Sandbox Restart Recovery Checklist section in the same file.

Web Application Deployment

When deploying a web application to the sandbox, build the app inside the sandbox before exposing it. Source code is uploaded, dependencies installed, and the framework built in the sandbox environment.

Backend selection (Stack-Selection Gate): the backend choice was already confirmed by the Stack-Selection Gate before any code was uploaded. If the project includes a PostgreSQL + PostgREST backend (or the developer asked for one), set up the backend FIRST by following Full-Stack: REST API over PostgreSQL — install PostgreSQL/PostgREST, create the schema, and point the frontend's nginx /api/ location at PostgREST — then continue with the steps below. Every tunnel exposed afterwards is auto-enrolled into the keepalive watchdog.

沙箱无 systemd(实测 #935 报告3 问题3):沙箱为无 systemd 的容器环境,systemctl 全部失效(System has not been booted with systemd)—— 不要用 systemctl start/reload/restart nginx。Nginx 配置变更直接使用 nginx -t 验证 + nginx -s reload 热加载,或直接执行 nginx 二进制(sudo nginx 启动 / nginx -s stop 停止)。huaweicloud_sandbox_deploy_nginx 工具返回的 nextStep 文案与该语义一致(配置写入后自动回验存在性与 nginx -t,通过后即生效,无需 systemctl)。

Step 1: Detect Framework Locally

Always call huaweicloud_detect_framework first before connecting to the sandbox. It scans the local project and returns:

If detection returns null, the project is not a recognized web app. Stop and tell the developer.

If detection returns type: "monorepo", show the subApps list to the developer and ask which sub-app to deploy. Then re-detect that sub-app's framework.

Step 2: Connect and Upload

Follow the standard Workflow steps 1-6 to connect to the sandbox, then:

{
  "local_dir": "<projectPath>",
  "remote_dir": "/workspace",
  "exclude": [
    "**/node_modules",
    ".git",
    "__pycache__",
    ".next",
    ".nuxt",
    ".output",
    ".turbo",
    ".cache",
    ".swc",
    "dist",
    "coverage",
    "*.pyc"
  ]
}

Always exclude build artifacts and dependency directories — they will be re-installed/built inside the sandbox:

| Pattern | Why excluded |

| ----------------- | ---------------------------------------------- |

| **/node_modules | Dependencies — reinstall in sandbox |

| .git | Version control — not needed for deployment |

| __pycache__ | Python bytecode cache |

| .next | Next.js build output — rebuild in sandbox |

| .nuxt | Nuxt build cache — rebuild in sandbox |

| .output | Nuxt production output — rebuild in sandbox |

| .turbo | Turborepo cache — re-run in sandbox |

| .cache | Generic tool cache (Parcel, Storybook, etc.) |

| .swc | Taro/Webpack SWC cache — regenerate in sandbox |

| dist | Build output — rebuild in sandbox |

| coverage | Test coverage reports — not needed for deploy |

| *.pyc | Python compiled files |

Post-upload permission fix: after upload_project extracts the project, fix file permissions lost during transfer (native binaries from other platforms, .bin symlinks):

# Fix executable permissions on node_modules/.bin (lost during cross-platform transfer)
chmod -R +x /workspace/<dirname>/node_modules/.bin 2>/dev/null || true
# Fix world-read on all files (sandbox default umask may restrict)
chmod -R o+rX /workspace/<dirname> 2>/dev/null || true

Step 3: Sandbox Environment Readiness

Install OS-level dependencies before uploading the project (independent of project code, can run in parallel if desired).

3a: Detect OS and package manager
source /etc/os-release 2>/dev/null
echo "OS_DETECTED=${ID:-unknown}|${ID_LIKE:-}"
if command -v apt-get >/dev/null 2>&1; then echo "PKG_MGR=apt"; elif command -v yum >/dev/null 2>&1; then echo "PKG_MGR=yum"; elif command -v dnf >/dev/null 2>&1; then echo "PKG_MGR=dnf"; elif command -v apk >/dev/null 2>&1; then echo "PKG_MGR=apk"; else echo "PKG_MGR=unknown"; fi

Use the detected PKG_MGR for all package installations below.

Architecture awareness: the sandbox runs Linux aarch64 (ARM64). Native binaries built on x64 (Windows/macOS Intel) will not execute. Always install dependencies and build inside the sandbox. For projects with native addons (Taro @swc/core, Prisma, esbuild, node-gyp), local x64 pre-build + upload of dist/ output is a viable alternative when sandbox builds fail.

GitCode SSL: if git clone from GitCode fails with SSL certificate errors, use a one-shot override (do NOT set it globally — that would disable cert verification for every repo):

git -c http.sslVerify=false clone <repo-url>

Then retry the clone. This bypasses SSL verification only for this single clone.

index.html overwritten by the platform landing page: when a repo is cloned inside the sandbox (fallback path, used only when the operator machine has no git), the DevStation portal-template init may asynchronously write a default GitCode/AtomGit landing page over the repo's index.html, leaving a blank page after deploy. Symptoms: git show HEAD:index.html shows the user's original page but /workspace/<repo>/index.html is a Vue SPA shell referencing cdn-static.gitcode.com. Recovery:

cd /workspace/<repo> && git checkout HEAD -- index.html

Prevention: sandbox_connect clones locally and uploads the finished tree by default (_repoStatus: 'uploaded_from_local'), which never triggers this race — keep local git available so the fallback in-sandbox clone is not used. The overwrite itself is DevStation platform behavior; report persistent occurrences to the platform team.

3b: Install nginx (before project upload)
# Use the detected PKG_MGR from step 3a
case "$PKG_MGR" in
  apt) sudo apt-get update -qq && sudo apt-get install -y -qq nginx ;;
  yum) sudo yum install -y nginx ;;
  dnf) sudo dnf install -y nginx ;;
esac
sudo nginx -t && echo "nginx: ready"

If nginx cannot be installed, skip to Python HTTP server fallback (see references/nginx-templates.md).

3c: Verify remaining tools

Before installing project dependencies, verify the sandbox has the required runtime tools. Run each check as a separate exec_one_shot call with 15s timeout — do not bundle all checks into one command. A single hung subcommand (e.g., make --version or hugo version) will timeout the entire check, blocking deployment:

Check 1: node --version       (timeout: 15s)
Check 2: npm --version         (timeout: 15s)
Check 3: nginx -v 2>&1         (timeout: 15s)
Check 4: git --version         (timeout: 15s)
Check 5: python3 --version     (timeout: 15s)
Check 6: curl --version | head -1 (timeout: 15s)
Check 7: wget --version | head -1 (timeout: 15s)
Check 8: make --version | head -1 (timeout: 15s)
Check 9: pnpm --version        (timeout: 15s)
Check 10: yarn --version       (timeout: 15s)
Check 11: hugo version         (timeout: 15s)
Check 12: devbridge version    (timeout: 15s)

For each check, parse the output: if stdout contains MISSING: or the tool wasn't found, install it. Skip framework-specific tools not needed for the current project (e.g., skip Hugo for React apps).

Install only missing tools — parse the pre-flight output and install only tools reported as MISSING. Use OS-aware commands:

| Missing Tool | Install Command (apt) | Install Command (yum/dnf) |

| ------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- |

| Node.js | Follow Node.js in the sandbox | Same |

| nginx | sudo apt-get update -qq && sudo apt-get install -y -qq nginx | sudo yum install -y nginx |

| curl | sudo apt-get update -qq && sudo apt-get install -y -qq curl | sudo yum install -y curl |

| wget | sudo apt-get update -qq && sudo apt-get install -y -qq wget | sudo yum install -y wget |

| make | sudo apt-get update -qq && sudo apt-get install -y -qq make | sudo yum install -y make |

| pnpm | npm i -g pnpm | Same |

| yarn | npm i -g yarn | Same |

| Hugo | curl -fsSL https://github.com/gohugoio/hugo/releases/download/v0.140.0/hugo_extended_0.140.0_linux-amd64.tar.gz -o /tmp/hugo.tar.gz && sudo tar -xzf /tmp/hugo.tar.gz -C /usr/local/bin hugo && rm /tmp/hugo.tar.gz | Same |

| DevBridge | Follow Step 0 of "Expose the deployed app" — checks version, installs or upgrades in place via the official installer | Same |

If Node.js is missing, install it first — all build workflows depend on it. Stop and report to the developer if Node.js installation fails.

Step 4: Install and Build

4a: Inject Environment Variables

Before any project commands, parse .env* files and inject them into the shell environment. Prisma, Drizzle, and other ORM/database tools do NOT auto-read framework-level env files:

cd /workspace/<dirname>
# Load env files if present (most specific first)
for f in .env.local .env.development.local .env.development .env; do
  if [ -f "$f" ]; then
    set -a && source "$f" 2>/dev/null; set +a
    echo "Loaded env: $f"
  fi
done
# Verify key variables for common tools
echo "DATABASE_URL=${DATABASE_URL:-<NOT SET>}"
echo "NODE_ENV=${NODE_ENV:-development}"

This must run via exec_with_session so the exported variables persist for subsequent build commands in the same session.

Prisma / ORM compatibility: Prisma CLI (prisma generate, prisma db push, prisma migrate) only reads .env by default, NOT .env.local or .env.development. If the project uses .env.local for DATABASE_URL, link it before any Prisma command:

# Prisma requires .env (not .env.local) — symlink if needed
if [ -f .env.local ] && [ ! -f .env ]; then ln -sf .env.local .env 2>/dev/null || cp .env.local .env; fi
# Then re-source
set -a && source .env 2>/dev/null; set +a
4b: Install Dependencies

Use exec_one_shot for install (no shared state needed). Skip if node_modules already exists:

cd /workspace/<dirname> && [ -d node_modules ] && echo "SKIP: node_modules exists" || <installCmd>

Wait for install to complete. For large projects on aarch64 sandboxes (1000+ packages), set timeout_ms to 180000 (3 min).

Node version compatibility: if npm install fails with native module errors (e.g., rollup 4, @esbuild, node-gyp), check the Node version:

node -v

Node v24+ uses musl-based binaries on some sandbox images, which may break native addons built for glibc. If native modules fail:

Prisma / database initialization: if prisma/schema.prisma exists in the project, initialize the database after install and before build. Prisma Client generation (prisma generate) is usually handled by postinstall, but prisma db push (SQLite) or prisma migrate deploy (PostgreSQL/MySQL) must be run manually:

cd /workspace/<dirname>
if [ -f prisma/schema.prisma ]; then
  echo "Prisma schema detected — initializing database..."
  npx prisma db push --skip-generate 2>/dev/null || npx prisma migrate deploy 2>/dev/null || echo "WARN: skip db init"
fi

--skip-generate avoids redundant generation when postinstall already ran prisma generate. For SQLite, DATABASE_URL="file:./dev.db" must be set in .env/.env.local before this step.

4c: Build

Timeout strategy by framework type:

| Type | timeout_ms | Rationale |

| ------------------------------ | --------------- | ------------------------------------- |

| SPA / SSG | 300000 (5 min) | Vite/Webpack builds typically < 3 min |

| Cross-platform (Taro, uni-app) | 900000 (15 min) | Webpack5 H5 slow on aarch64, 7-8 min |

| SSR (Next.js, Nuxt) | 600000 (10 min) | Full-stack compilation + SSG pages |

| Monorepo | 600000 (10 min) | Multiple apps, shared packages |

| null (no build) | N/A | Skip |

Build with exec_one_shot:

cd /workspace/<dirname> && [ -d <outputDir> ] && echo "SKIP: <outputDir> exists" || (umask 022 && <buildCmd> 2>&1 | tee /tmp/build.log)

Always pipe build output through tee /tmp/build.log — captures stderr+stdout so diagnostics are available even if the command times out.

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'):

# Check for custom outDir in common config files
grep -r "outDir\|outputDir\|dest\|distDir" /workspace/<dirname>/.vitepress/config.* 2>/dev/null || true

If a custom outDir is found, use that instead of the framework-detected default for all subsequent checks.

Post-build output verification: after a successful build, verify the actual index.html location. Framework-returned outputDir may be inaccurate — either a subdirectory (e.g., uni-app v3: dist → dist/build/h5) or a completely different top-level path (e.g., Vite build.outDir pointing to portal/public). Search the whole project (skipping node_modules), not just <outputDir>:

# Find the real index.html after build (search whole project, not just the default outputDir)
REAL_INDEX=$(find /workspace/<dirname> -path '*/node_modules' -prune -o -name index.html -type f -print 2>/dev/null | head -1)
if [ -n "$REAL_INDEX" ] && [ -f "$REAL_INDEX" ]; then
  REAL_OUTDIR=$(dirname "$REAL_INDEX")
  echo "Actual output dir: $REAL_OUTDIR"
  # Use REAL_OUTDIR for nginx config instead of framework-reported outputDir
fi

If REAL_OUTDIR differs from <outputDir>, use REAL_OUTDIR for all subsequent steps (nginx config, port check, etc.).

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:

# If timeout occurred, show captured output and verify build
if timeout_error; then
  echo "=== Build log (tail) ==="
  tail -30 /tmp/build.log 2>/dev/null
  echo "=== Checking output ==="
  if [ -d <outputDir> ] && [ "$(ls -A <outputDir> 2>/dev/null)" ]; then
    # Verify at least one key output file exists (not just empty dir from broken build)
    if [ -f <outputDir>/index.html ] || [ -f <outputDir>/server.js ] || [ -f <outputDir>/app.js ]; then
      echo "Build output detected despite timeout — continuing with deployment"
    else
      echo "ERROR: Output directory exists but missing expected files (index.html/server.js). Build may have failed silently."
      echo "Full log: /tmp/build.log"
      exit 1
    fi
  else
    echo "ERROR: Build did not complete. Output directory empty or missing."
    echo "Full log: /tmp/build.log"
    exit 1
  fi
fi

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.

Build progress visibility: for very large builds, touch a marker file before starting and use exec_with_session to poll intermediate logs:

# Before build:
touch /tmp/build-start && echo "Build started at $(date)"

# During build via exec_with_session (separate call for polling):
cat .next/trace 2>/dev/null | tail -5  # Next.js build trace
# or
tail -5 /tmp/build.log 2>/dev/null
4c-aux: Build Failure Response

Build failures fall into two categories. Handle them differently:

| Failure Type | Behavior |

| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |

| 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. |

| 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. |

When a build exits with non-zero exit code:

  1. STOP — do NOT retry, do NOT modify source code, do NOT change environment variables
  2. Extract the error from /tmp/build.log:

```bash

tail -30 /tmp/build.log

```

  1. Present the failure to the developer with:
  1. Offer fix options (1-3 choices) and wait for the developer to choose before applying any fix:
  1. After the developer selects a fix, apply it, then restart only the failed build — do NOT rebuild already-succeeded apps

| Rule | Rationale |

| ---------------------- | -------------------------------------------------------------- |

| No blind retry | Retrying without diagnosis wastes time and obscures real error |

| No silent source edits | Modifying project files without consent destroys trust |

| Developer decides fix | Different projects have different fix preferences |

| Only rebuild failed | Avoid redundant work in monorepo deployments |

Monorepo-specific: if one sub-app build fails while others succeed, report the failure immediately — do NOT delay until all builds complete. Continue other builds in parallel if possible, but notify the developer as soon as a failure is detected.

4d: Fix Build Output Permissions

After a successful build, fix directory traverse permissions on the build output. Build tools (webpack, vite, uni-app) may create directories with restrictive permissions that block nginx from traversing to index.html. Always resolve symlinks first — chmod does not follow symlinks on Linux:

# Fix directory execute permissions for nginx traverse
REAL_OUTDIR="<outputDir>"   # use actual output dir from post-build verification
PROJECT_ROOT="/workspace/<dirname>"

# Resolve symlinks — monorepo sub-apps may be symlinked
REAL_ROOT=$(readlink -f "$PROJECT_ROOT" 2>/dev/null || echo "$PROJECT_ROOT")
REL_OUTDIR=$(echo "$REAL_OUTDIR" | sed "s|$PROJECT_ROOT/||")
REAL_OUTDIR="${REAL_ROOT}/${REL_OUTDIR}"

# Fix permissions on resolved real paths
find "$REAL_ROOT" -path "*/${REAL_OUTDIR}" -prune -o -type d -exec chmod o+x {} \; 2>/dev/null || true
chmod -R o+rX "$REAL_ROOT" 2>/dev/null || true
chmod -R +x "$REAL_ROOT/node_modules/.bin" 2>/dev/null || true

This prevents the most common deployment failure: nginx 500 with stat() ... Permission denied caused by missing o+x on intermediate directories.

4e: Write Deployment Fingerprint

After a successful build, write a deployment fingerprint into the output directory. This enables deploy_check to verify the nginx-served content belongs to the current deployment (not a stale process from an earlier session):

echo "deployed-$(date +%s)-<dirname>" > /workspace/<dirname>/<outputDir>/.deploy_fingerprint
chmod o+r /workspace/<dirname>/<outputDir>/.deploy_fingerprint 2>/dev/null || true

For SSR proxy type, nginx does not serve static files from .next — the fingerprint check will gracefully SKIP in deploy_check. The fingerprint is still written as a deployment marker for debugging.

Step 5: Port Availability Check

Before configuring nginx or starting the app, verify the target ports are free. Port conflicts from previous deployments cause silent failures:

# Check ports from framework detection
check_port() {
  PORT=$1
  # Prefer lsof (most portable), fallback to netstat, then ss
  if command -v lsof >/dev/null 2>&1; then
    PID=$(lsof -ti :$PORT 2>/dev/null)
    if [ -n "$PID" ]; then
      echo "PORT_IN_USE:$PORT (PID=$PID)"
      kill -9 $PID 2>/dev/null && echo "Killed PID $PID on port $PORT"
    else
      echo "PORT_FREE:$PORT"
    fi
  elif command -v netstat >/dev/null 2>&1; then
    PID=$(netstat -tlnp 2>/dev/null | grep ":$PORT " | awk '{print $NF}' | sed 's|/.*||')
    if [ -n "$PID" ] && [ "$PID" != "-" ]; then
      echo "PORT_IN_USE:$PORT (PID=$PID)"
      kill -9 $PID 2>/dev/null && echo "Killed PID $PID on port $PORT"
    else
      echo "PORT_FREE:$PORT"
    fi
  else
    # Last resort: ss (iproute2)
    PID=$(ss -tlnp 2>/dev/null | grep ":$PORT " | sed -n 's/.*pid=\([0-9]*\).*/\1/p' | head -1)
    if [ -n "$PID" ]; then
      echo "PORT_IN_USE:$PORT (PID=$PID)"
      kill -9 $PID 2>/dev/null && echo "Killed PID $PID on port $PORT"
    else
      echo "PORT_FREE:$PORT"
    fi
  fi
}
check_port <port>
# For SSR, also check the Node port
check_port <nodePort>

| Scenario | Port | Action if occupied |

| ---------------------- | ------------------------------------ | -------------------------------------- |

| SPA/SSG/Cross-platform | nginx port (from framework.detect) | Kill old process, then configure nginx |

| SSR | nginx public port + Node app port | Kill old processes on both ports |

If the port cannot be freed (different user/process), the deploy_nginx tool auto-increments to the next available port (up to 10 attempts). For SSR (proxy) mode, nginx listens on the resolved targetPort, and the Node app follows the returned nodePort field — bind the Node process to the nodePort that deploy_nginx returns, and update all subsequent nginx config and DevBridge references accordingly.

Configure Nginx

Use huaweicloud_sandbox_deploy_nginx to write the correct template, fix directory permissions, and reload nginx — all in one call:

{
  "nginx_type": "<nginxType>",
  "port": <port>,
  "project": "<dirname>",
  "output_dir": "<outputDir>",
  "node_port": <nodePort>,
  "public_port": <publicPort>
}

The tool automatically handles:

If the tool returns ok: false, nginx may not be installed — fall back to Python HTTP server (see references/nginx-templates.md).

Verify nginx is serving — curl-check the app before proceeding to DevBridge:

curl -s -o /dev/null -w "nginx status: %{http_code}\n" http://localhost:<port>

If the status code is not 2xx/3xx:

If curl is unavailable, check port via lsof -i :<port> or netstat -tlnp | grep :<port>

Step 6: Start the App [REQUIRED]

Runtime environment variables: SSR apps often need DATABASE_URL, NEXTAUTH_URL, NEXTAUTH_SECRET, etc. at runtime. Before starting, verify env vars from Step 4a are still loaded, and re-source .env if the shell session was reset:

```bash

cd /workspace/<dirname>

# Re-load env vars (SSR apps need them at runtime, not just build time)

if [ -f .env ]; then set -a && source .env 2>/dev/null; set +a; echo "Loaded .env"; fi

if [ -f .env.local ]; then set -a && source .env.local 2>/dev/null; set +a; echo "Loaded .env.local"; fi

# Verify critical vars

echo "DATABASE_URL=${DATABASE_URL:-<NOT SET>}"

echo "NEXTAUTH_URL=${NEXTAUTH_URL:-<NOT SET>}"

```

Then start with PORT=<nodePort> <serveCmd> via exec_with_session to run the Node process in background.

Step 7: Expose via DevBridge [REQUIRED — deployment incomplete without this]

Preferred: call huaweicloud_sandbox_expose_tunnel with the ACTUAL port returned by deploy_nginx ({"port": <port>}) — it authenticates automatically (probing AK/SK vs API-Key builds), 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.

Manual fallback (only when the tool is unavailable or must be debugged by hand): follow Expose the deployed app below.

When deploy_check returns nextStep: expose_via_devbridge, it also returns an executable remediation string — run those devbridge commands in the sandbox (after source /tmp/hw_creds.sh). Until a tunnel exists, deploy_check returns no publicUrl; do not fabricate a URL.

Follow the standard Expose the deployed app procedure. The app is already running on the detected port — only DevBridge tunnel setup is needed.

Use exec_with_session to background DevBridge. For SSR, DevBridge tunnels the nginx public port (not the Node port directly).

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).

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.

Extract the tunnel URL from DevBridge output. The public URL has the form https://<id>-<port>.devbridge-s2.hwtunnel.com. Return this URL to the developer as the deployment result.

Cross-platform H5 QR code

If detect_framework returned type: "cross-platform" (Taro, uni-app), after exposing the tunnel, generate a QR code for mobile scanning:

TUNNEL_URL="<extracted-tunnel-url>"

# Generate QR inside nginx-served output directory so it is accessible via the tunnel URL
curl -s "https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=$(python3 -c "import urllib.parse, sys; print(urllib.parse.quote(sys.argv[1]))" "$TUNNEL_URL")" -o /workspace/<dirname>/<outputDir>/qr.png
chmod o+r /workspace/<dirname>/<outputDir>/qr.png
echo "QR code URL: ${TUNNEL_URL}/qr.png"
echo "Desktop URL: $TUNNEL_URL"

Do NOT use qrencode -t ANSI256 — terminal ANSI/ASCII QR codes have low precision and phone cameras cannot scan them. Also, never save the QR image outside the nginx root (e.g., /workspace/qr.png) — it must be inside the output directory so it is served by nginx alongside the app.

After generating the QR code, return both URLs to the developer:

桌面访问: <tunnel-url>
手机扫码: <tunnel-url>/qr.png
Deployment Completion Check [REQUIRED]

Before reporting success, call huaweicloud_sandbox_deploy_check to verify the deployment is complete:

{
  "port": <port>,
  "project": "<dirname>",
  "output_dir": "<outputDir>",
  "framework_type": "<type>"
}

The tool checks:

Returns complete: true/false, score, and nextStep to fix missing items.

If complete is false, follow nextStep to resolve before reporting success. Do not return a deployment URL until complete: true.

| Framework Type | Must Return |

| --------------------------- | ------------------------- |

| cross-platform | Desktop URL + QR code URL |

| spa / ssg / static | Desktop URL |

| ssr | Desktop URL |

| monorepo (cross-platform) | Desktop URL + QR code URL |

If the framework is cross-platform and the QR code was not generated, the deployment is incomplete — go back and generate it before reporting success.

References

Critical Warnings

| Trap | Why |

| -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

| 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. |

| 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 |

| Real-name required | sandbox_connect fails if realnameVerified=false; tell the developer once and stop, don't loop on connect |

| Never expose tunnel details | Do not mention "DevBridge"/"tunnel"/"devbridge" to the developer — say "正在生成访问地址..." and hand over only the URL |

| 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) → auto-create fallback → file. Use devbridge auth login --api-key only — never --access-key/--secret-key. |

| 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 |

| CLI PATH | The installer only writes ~/.bashrc; run export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH" (prepend) in the session before using devbridge — appending lets a stale image binary in /usr/local/bin win. /workspace/.local/bin survives sandbox reboots; ~/.huawei/bin is on the system disk and is wiped on reboot (#999) |

| 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 |

| Return the deployment URL | Always hand the public URL from the host log to the developer as the final result |

| 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. |

| 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. |

| Session state persists | exec_with_session preserves cd, env vars, aliases between calls |

| 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. |

| 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. |

| 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. |

| Destructive commands blocked | rm -rf /, mkfs, dd if=, fork bombs are denied by safety policy |

| Workspace ID = dev_stage_id | Use dev_stage_id from sandbox_connect as workspace_id for terminal exec |

| 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 |

| 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 |

| Upload file for single files | Use sandbox_upload_file for individual files — base64 chunked, reliable for small files (<1MB) |

| 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") |

| 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. |

| 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. |

| 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. |

| 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. |

| 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. |

| 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>. |

| 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. |

| 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. |

Node.js in the sandbox

If the sandbox has no Node.js, download it from the Huawei Cloud mirror. Pick the tarball matching the sandbox arch (uname -m: aarch64 -> arm64, x86_64 -> x64):

# aarch64 sandbox:
curl -fsSL https://mirrors.huaweicloud.com/nodejs/v24.19.0/node-v24.19.0-linux-arm64.tar.gz -o node.tar.gz
# x86_64 sandbox:
curl -fsSL https://mirrors.huaweicloud.com/nodejs/v24.19.0/node-v24.19.0-linux-x64.tar.gz -o node.tar.gz
sudo tar -xzf node.tar.gz -C /usr/local --strip-components=1
node --version

Environment Variables

| Variable | Required | Description |

| ----------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

| HW_ACCESS_KEY | Yes | Huawei Cloud AK |

| HW_SECRET_KEY | Yes | Huawei Cloud SK |

| HW_SECURITY_TOKEN | No | STS security token |

| 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) |

| HW_WORKSPACE_ID | No | Default workspace ID |

| HDKITSERVICE_ENDPOINT | No | hdkitservice API endpoint (default: devkit.huaweicloud.com) |

| HWLINK_ENDPOINT | No | DevStation API endpoint (default: devstation.myhuaweicloud.com) |

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.