huaweicloud-devkit 2.0.1-next.3 → 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 (68) hide show
  1. package/README.md +2 -2
  2. package/package.json +1 -1
  3. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +1 -1
  4. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +1 -1
  5. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +1 -1
  6. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +1 -1
  7. package/plugins/huaweicloud-core/.mcp.json +3 -0
  8. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +1 -1
  9. package/plugins/huaweicloud-core/dist/approval-roster.js +2 -0
  10. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkit-gate.js +7 -0
  11. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +30 -1
  12. package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +21 -0
  13. package/plugins/huaweicloud-core/dist/mcp-server.js +5019 -3879
  14. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  15. package/plugins/huaweicloud-core/dist/packs/registry.js +1 -0
  16. package/plugins/huaweicloud-core/dist/packs/sandbox/approval.js +13 -2
  17. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +198 -10
  18. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +11 -0
  19. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +22 -0
  20. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +46 -0
  21. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-upload.js +11 -0
  22. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +20 -0
  23. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +26 -18
  24. package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +97 -0
  25. package/plugins/huaweicloud-core/dist/sandbox/deploy-nginx.js +30 -14
  26. package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-backend.js +37 -0
  27. package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-connections.js +84 -0
  28. package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-envd-client.js +229 -0
  29. package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-envd-protocol.js +151 -0
  30. package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-envd-transport.js +121 -0
  31. package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-service-api.js +80 -0
  32. package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-upload.js +106 -0
  33. package/plugins/huaweicloud-core/dist/sandbox/hwlink-connection.js +12 -0
  34. package/plugins/huaweicloud-core/dist/sandbox/upload-project.js +5 -2
  35. package/plugins/huaweicloud-core/dist/tool-definitions.js +4 -0
  36. package/plugins/huaweicloud-core/dist/tools.js +1 -0
  37. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  38. package/plugins/huaweicloud-core/safety/policy.json +2 -1
  39. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +67 -16
  40. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/devbox-backend.md +78 -0
  41. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +14 -0
  42. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +2 -1
  43. package/plugins/huaweicloud-core/src/approval-roster.ts +2 -0
  44. package/plugins/huaweicloud-core/src/lib/hdkit/hdkit-gate.ts +7 -0
  45. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +30 -1
  46. package/plugins/huaweicloud-core/src/lib/hdkit/sandbox-pool.ts +22 -0
  47. package/plugins/huaweicloud-core/src/packs/registry.ts +1 -0
  48. package/plugins/huaweicloud-core/src/packs/sandbox/approval.ts +15 -2
  49. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +206 -11
  50. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +12 -0
  51. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +23 -0
  52. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +49 -0
  53. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-upload.ts +11 -0
  54. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +23 -0
  55. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +27 -17
  56. package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +105 -0
  57. package/plugins/huaweicloud-core/src/sandbox/deploy-nginx.ts +36 -18
  58. package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-backend.ts +44 -0
  59. package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-connections.ts +115 -0
  60. package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-envd-client.ts +281 -0
  61. package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-envd-protocol.ts +180 -0
  62. package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-envd-transport.ts +142 -0
  63. package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-service-api.ts +102 -0
  64. package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-upload.ts +167 -0
  65. package/plugins/huaweicloud-core/src/sandbox/hwlink-connection.ts +12 -0
  66. package/plugins/huaweicloud-core/src/sandbox/upload-project.ts +5 -2
  67. package/plugins/huaweicloud-core/src/tool-definitions.ts +4 -0
  68. package/plugins/huaweicloud-core/src/tools.ts +3 -0
@@ -16,13 +16,14 @@ import {
16
16
  connectSchema,
17
17
  credentialsSchema,
18
18
  shutdownSchema,
19
+ killSchema,
19
20
  } from './schemas.ts';
20
21
  import { handleExecWithSession, handleExecOneShot, handleCloseSession } from './handlers-session.ts';
21
22
  import { handleHwexecPoll } from './handlers-hwexec.ts';
22
23
  import { handleUploadFile, handleUploadProject } from './handlers-upload.ts';
23
24
  import { handleDeployNginx, handleDeployCheck } from './handlers-deploy.ts';
24
25
  import { handleExposeTunnel, handleExposePoll, handleRenewTunnel, handleKeepaliveWatchdog } from './handlers-tunnel.ts';
25
- import { handleCheckUser, handleSignAgreement, handleConnect, handleShutdown } from './handlers-account.ts';
26
+ import { handleCheckUser, handleSignAgreement, handleConnect, handleShutdown, handleKill } from './handlers-account.ts';
26
27
  import { handleCredentials } from './handlers-credentials.ts';
27
28
  import type { PackToolDefinition, LooseToolSchema } from '../../lib/pack-types.ts';
28
29
 
@@ -49,14 +50,14 @@ export const SANDBOX_TOOLS = [
49
50
  {
50
51
  name: 'huaweicloud_sandbox_exec_with_session',
51
52
  description:
52
- 'Execute a command on a workspace terminal with session reuse (state persists across calls). Shell state (cd, env vars, aliases) carries over between calls. Use for interactive work and command sequences that need shared state. NOT for long-running commands (>30s) — prefer exec_one_shot for those.',
53
+ 'Execute a command on a workspace terminal. Legacy (DevStation) backend: session reuse — shell state (cd, env vars, aliases) persists across calls; use for interactive work and command sequences that need shared state. devbox backend: DEGRADED to one-shot — the command runs once through EnvD Process/Start (non-PTY) with no shell state, and the response carries degraded:true / statePersisted:false; commands must be self-contained (cd ... && ..., source ...; ...). On devbox prefer huaweicloud_sandbox_exec_one_shot. NOT for long-running commands (>30s) — use exec_one_shot with mode:"async".',
53
54
  schema: execWithSessionSchema,
54
55
  handler: handleExecWithSession,
55
56
  },
56
57
  {
57
58
  name: 'huaweicloud_sandbox_exec_one_shot',
58
59
  description:
59
- 'Execute a command on a workspace terminal with a fresh connection per call (no session state carries over). Each invocation opens a new WebSocket connection, executes one command, then disconnects. Use for long-running build/deploy/install commands (>30s) that do not need shell state persistence between calls. More stable than session-based execution for heavy workloads. Commands that can outlive the sync timeout (default 120s) must run in mode: "async" instead: the tool claims a per-task directory with an atomic O_EXCL claim, spawns the command detached (setsid/nohup/disown — it survives the exec session), and returns immediately with {started, taskId, taskDir}; poll the verdict with huaweicloud_sandbox_exec_poll — that async + poll pair is the >30s long-command doctrine, and the same-task_id retry after started:"uncertain" is structurally double-spawn-safe. started:"dup" + verdict "never" → start over with a NEW task_id.',
60
+ 'Execute a command on a workspace terminal with a fresh connection per call (no session state carries over). Each invocation opens a new WebSocket connection, executes one command, then disconnects. devbox backend: runs through EnvD Process/Start (non-PTY, /bin/bash -l -c <command>) and reads the end event; the async claim protocol below is unchanged. Use for long-running build/deploy/install commands (>30s) that do not need shell state persistence between calls. More stable than session-based execution for heavy workloads. Commands that can outlive the sync timeout (default 120s) must run in mode: "async" instead: the tool claims a per-task directory with an atomic O_EXCL claim, spawns the command detached (setsid/nohup/disown — it survives the exec session), and returns immediately with {started, taskId, taskDir}; poll the verdict with huaweicloud_sandbox_exec_poll — that async + poll pair is the >30s long-command doctrine, and the same-task_id retry after started:"uncertain" is structurally double-spawn-safe. started:"dup" + verdict "never" → start over with a NEW task_id.',
60
61
  schema: execOneShotSchema,
61
62
  handler: handleExecOneShot,
62
63
  },
@@ -70,101 +71,108 @@ export const SANDBOX_TOOLS = [
70
71
  {
71
72
  name: 'huaweicloud_sandbox_close_session',
72
73
  description:
73
- 'Close the persistent terminal session for a workspace. This closes the agent-side terminal session only — it does NOT delete the sandbox instance. Resource-pool sandbox deletion is developer-initiated (always ask for a second confirmation before guiding a delete) or handled by the platform resource-group idle-reclaim policy within the 7-day cap (v3 caliber); devkit never defers or performs deletion on the user behalf.',
74
+ 'Close the persistent terminal session for a workspace. This closes the agent-side terminal session only — it does NOT delete the sandbox instance. Resource-pool sandbox deletion is developer-initiated (always ask for a second confirmation before guiding a delete) or handled by the platform resource-group idle-reclaim policy within the 7-day cap (v3 caliber); devkit never defers or performs deletion on the user behalf. devbox backend: there is no terminal session to close — returns backend:"devbox", not_applicable:true and leaves the sandbox untouched (use shutdown to pause / kill to delete).',
74
75
  schema: closeSessionSchema,
75
76
  handler: handleCloseSession,
76
77
  },
77
78
  {
78
79
  name: 'huaweicloud_sandbox_upload_file',
79
80
  description:
80
- 'Upload a local file into the sandbox workspace. Base64-encodes the file, writes it in small chunks through the terminal session (the exec channel is fragile for large single commands), then decodes and verifies the md5 checksum. The remote parent directory is created automatically if absent. Use this instead of embedding large file content directly in a command. local_path must be readable from the machine running the DevKit MCP server — if the file lives elsewhere, copy it to the local temp directory first.',
81
+ 'Upload a local file into the sandbox workspace. Legacy backend: base64-encodes the file, writes it in small chunks through the terminal session (the exec channel is fragile for large single commands), then decodes and verifies the md5 checksum. devbox backend: binary write through EnvD /files plus an md5 check (no terminal session, no base64 chunking). The remote parent directory is created automatically if absent. Use this instead of embedding large file content directly in a command. local_path must be readable from the machine running the DevKit MCP server — if the file lives elsewhere, copy it to the local temp directory first.',
81
82
  schema: uploadFileSchema,
82
83
  handler: handleUploadFile,
83
84
  },
84
85
  {
85
86
  name: 'huaweicloud_sandbox_upload_project',
86
87
  description:
87
- 'Package a local project directory and upload it to a sandbox workspace via HTTP tunnel. Creates a tar.gz archive, uploads it, and extracts it on the sandbox by default. local_dir must be readable from the machine running the DevKit MCP server — if the project lives elsewhere, copy it to the local temp directory first.',
88
+ 'Package a local project directory and upload it to a sandbox workspace. Creates a tar.gz archive, uploads it, and extracts it on the sandbox by default. Legacy backend: uploads via HTTP tunnel. devbox backend: writes the archive through EnvD /files and extracts it with tar inside the sandbox (no HTTP tunnel, no file server). local_dir must be readable from the machine running the DevKit MCP server — if the project lives elsewhere, copy it to the local temp directory first.',
88
89
  schema: uploadProjectSchema,
89
90
  handler: handleUploadProject,
90
91
  },
91
92
  {
92
93
  name: 'huaweicloud_sandbox_deploy_nginx',
93
94
  description:
94
- 'Deploy an nginx configuration on the sandbox and reload. Takes nginxType, port, project, outputDir from framework detection and writes the correct template (SPA try_files, SSR reverse proxy, or static). Also fixes directory traverse permissions on the project path. Use this instead of manually constructing nginx config — it handles permissions, template selection, and reload in one call. If the requested port is already in use, the actual port is auto-incremented and returned in "port" alongside a warning.',
95
+ 'Deploy an nginx configuration on the sandbox and reload. devbox backend: no DevBridge probe; a successful deploy returns backend:"devbox", previewUrl (the app-port URL) and nextStep:"deploy_check". Takes nginxType, port, project, outputDir from framework detection and writes the correct template (SPA try_files, SSR reverse proxy, or static). Also fixes directory traverse permissions on the project path. Use this instead of manually constructing nginx config — it handles permissions, template selection, and reload in one call. If the requested port is already in use, the actual port is auto-incremented and returned in "port" alongside a warning.',
95
96
  schema: deployNginxSchema,
96
97
  handler: handleDeployNginx,
97
98
  },
98
99
  {
99
100
  name: 'huaweicloud_sandbox_deploy_check',
100
101
  description:
101
- 'Run a deployment completeness check on the sandbox. Verifies nginx is serving, output directory exists, DevBridge tunnel is active and accessible, and QR code exists (cross-platform). Returns a score, nextStep, and (when the DevBridge tunnel is missing) an executable "remediation" command string. Call this at the end of a deployment workflow to confirm everything is working before reporting success.',
102
+ 'Run a deployment completeness check on the sandbox. Verifies nginx is serving, output directory exists, DevBridge tunnel is active and accessible, and QR code exists (cross-platform). devbox backend: checks nginx/output/fingerprint inside the sandbox and probes the public app-port URL from the devkit side — there is no DevBridge tunnel check; nextStep is expose_tunnel when the app URL is unreachable. Returns a score, nextStep, and (when the DevBridge tunnel is missing) an executable "remediation" command string. Call this at the end of a deployment workflow to confirm everything is working before reporting success.',
102
103
  schema: deployCheckSchema,
103
104
  handler: handleDeployCheck,
104
105
  },
105
106
  {
106
107
  name: 'huaweicloud_sandbox_expose_tunnel',
107
108
  description:
108
- 'Expose a port on the sandbox to a public DevBridge tunnel URL (devbridge 0.2.x). Authenticates automatically (DevBridge auth is fixed to API Key — AK/SK login removed: the waterfall reads the sandbox keyring, then the /tmp/hw_api_key file channel; when both are empty it auto-creates the per-account × per-pool key (devkit-ephemeral/devkit-persistent) via the DevStation relay API and injects it, reporting authMode API_KEY_AUTO), selectively cleans only same-port/orphan tunnels before exposing (cleanup_mode=stale default — other ports, other sessions and keepalive-protected tunnels are preserved, except a tunnel bound to THIS port, which is always replaced; on 10006 quota it removes orphans first, then the oldest non-keepalive tunnel one at a time), starts the host detached from the exec session (setsid/nohup/disown so it survives session teardown), extracts the public URL (https://<id>-<port>.devbridge-s2.hwtunnel.com), and health-checks it before returning. Use the ACTUAL port reported by huaweicloud_sandbox_deploy_nginx (its "port" field auto-increments on conflict) — never the originally requested port. This automates the manual "Expose the deployed app" flow (huawei-sandbox skill). Returns ok, publicUrl, port, tunnelId, authMode, expiresAt (expiry_hours lifetime, default 72h; 1-720), keepalive.enrolled/tunnelCount/watchdogPid, warnings, sandboxLifetime and urlLifetimeHint. The urlLifetimeHint MUST be relayed to the developer together with the URL: the tunnel expiry is NOT the sandbox lifetime — an idle sandbox shuts down (ephemeral also auto-deletes), which kills the URL. AUTO-ENROLLS the tunnel into the keepalive watchdog (unattended renewal + host re-attach + health check; pass keepalive:false to opt out). The URL is re-verified from a second independent exec session: persistent/verifyHttpCode distinguish a session-surviving URL from one that dies with the deploying session, and a non-persistent URL carries a 请勿分享 warning. Gateway-level tunnel errors (404 "tunnel not found" / "port not configured", 502 "bad gateway") are classified by exact body — an app\'s own 404/502 page is never mistaken for them. When no usable URL is reachable after retries it returns ok:false instead of a dead URL; when the tunnel quota (10006) stays full after the selective cleanup it returns ok:false with error_code devbridge_tunnel_quota_exceeded (keepalive-protected tunnels are preserved — remove unused tunnels or retry with cleanup_mode=all for a full reset). When auto-creation hits the 20-key quota it returns ok:false with error_code HDKIT_DEVBRIDGE_KEY_QUOTA_EXCEEDED, the currentKeys list, and the console cleanup URL; a failed key invalidation self-heals by clearing the cache and recreating before the next probe. The auto-create relay goes through hdkitservice and inherits its 409 HDKIT_VERSION_TOO_OLD version gate: an outdated plugin fails auto-create the same way it fails connect, and the expose failure carries error_code HDKIT_VERSION_TOO_OLD with the upgrade remediation under gateRemediation, and clientVersion and minVersion when the service sends them — upgrade the plugin instead of creating a key by hand.',
109
+ 'Expose a port on the sandbox to a public URL. devbox backend: no DevBridge tunnel — returns the public app-port URL synchronously (backend:"devbox", publicUrl/url, accessible); single port and 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. Legacy backend: public DevBridge tunnel URL (devbridge 0.2.x). Authenticates automatically (DevBridge auth is fixed to API Key — AK/SK login removed: the waterfall reads the sandbox keyring, then the /tmp/hw_api_key file channel; when both are empty it auto-creates the per-account × per-pool key (devkit-ephemeral/devkit-persistent) via the DevStation relay API and injects it, reporting authMode API_KEY_AUTO), selectively cleans only same-port/orphan tunnels before exposing (cleanup_mode=stale default — other ports, other sessions and keepalive-protected tunnels are preserved, except a tunnel bound to THIS port, which is always replaced; on 10006 quota it removes orphans first, then the oldest non-keepalive tunnel one at a time), starts the host detached from the exec session (setsid/nohup/disown so it survives session teardown), extracts the public URL (https://<id>-<port>.devbridge-s2.hwtunnel.com), and health-checks it before returning. Use the ACTUAL port reported by huaweicloud_sandbox_deploy_nginx (its "port" field auto-increments on conflict) — never the originally requested port. This automates the manual "Expose the deployed app" flow (huawei-sandbox skill). Returns ok, publicUrl, port, tunnelId, authMode, expiresAt (expiry_hours lifetime, default 72h; 1-720), keepalive.enrolled/tunnelCount/watchdogPid, warnings, sandboxLifetime and urlLifetimeHint. The urlLifetimeHint MUST be relayed to the developer together with the URL: the tunnel expiry is NOT the sandbox lifetime — an idle sandbox shuts down (ephemeral also auto-deletes), which kills the URL. AUTO-ENROLLS the tunnel into the keepalive watchdog (unattended renewal + host re-attach + health check; pass keepalive:false to opt out). The URL is re-verified from a second independent exec session: persistent/verifyHttpCode distinguish a session-surviving URL from one that dies with the deploying session, and a non-persistent URL carries a 请勿分享 warning. Gateway-level tunnel errors (404 "tunnel not found" / "port not configured", 502 "bad gateway") are classified by exact body — an app\'s own 404/502 page is never mistaken for them. When no usable URL is reachable after retries it returns ok:false instead of a dead URL; when the tunnel quota (10006) stays full after the selective cleanup it returns ok:false with error_code devbridge_tunnel_quota_exceeded (keepalive-protected tunnels are preserved — remove unused tunnels or retry with cleanup_mode=all for a full reset). When auto-creation hits the 20-key quota it returns ok:false with error_code HDKIT_DEVBRIDGE_KEY_QUOTA_EXCEEDED, the currentKeys list, and the console cleanup URL; a failed key invalidation self-heals by clearing the cache and recreating before the next probe. The auto-create relay goes through hdkitservice and inherits its 409 HDKIT_VERSION_TOO_OLD version gate: an outdated plugin fails auto-create the same way it fails connect, and the expose failure carries error_code HDKIT_VERSION_TOO_OLD with the upgrade remediation under gateRemediation, and clientVersion and minVersion when the service sends them — upgrade the plugin instead of creating a key by hand.',
109
110
  schema: exposeTunnelSchema,
110
111
  handler: handleExposeTunnel,
111
112
  },
112
113
  {
113
114
  name: 'huaweicloud_sandbox_expose_poll',
114
115
  description:
115
- 'Poll an async expose task started by huaweicloud_sandbox_expose_tunnel with mode: "async". Returns state: running (the chain is still working — call again), done (result carries the full expose envelope: ok, publicUrl, port, tunnelId, expiresAt, urlLifetimeHint, keepalive, warnings), failed (an unexpected throw escaped the chain, with error), or unknown (no receipt in this MCP server process — it never started here, the session restarted, or the 30-minute receipt expired; the tunnel may already exist, so check huaweicloud_sandbox_deploy_check or re-expose — never assume success without a URL). The urlLifetimeHint MUST be relayed with the URL: the tunnel expiry is not the sandbox lifetime.',
116
+ 'Poll an async expose task started by huaweicloud_sandbox_expose_tunnel with mode: "async". devbox backend: not applicable — expose_tunnel returns the app-port URL synchronously and this tool returns ok:false, code:"HDKIT_BACKEND_UNSUPPORTED", reason:"not_applicable". Returns state: running (the chain is still working — call again), done (result carries the full expose envelope: ok, publicUrl, port, tunnelId, expiresAt, urlLifetimeHint, keepalive, warnings), failed (an unexpected throw escaped the chain, with error), or unknown (no receipt in this MCP server process — it never started here, the session restarted, or the 30-minute receipt expired; the tunnel may already exist, so check huaweicloud_sandbox_deploy_check or re-expose — never assume success without a URL). The urlLifetimeHint MUST be relayed with the URL: the tunnel expiry is not the sandbox lifetime.',
116
117
  schema: exposePollSchema,
117
118
  handler: handleExposePoll,
118
119
  },
119
120
  {
120
121
  name: 'huaweicloud_sandbox_renew_tunnel',
121
122
  description:
122
- "Renew a DevBridge tunnel's lifetime (devbridge update <id> -e <hours>) — a ROLLING window: expiration = now + hours regardless of remaining time, so renewing before expiry keeps the SAME public URL alive indefinitely (the URL is bound to the tunnel ID and never changes). Default 720h = the 30-day maximum. Returns ok, tunnelId, expiresAt (absolute ISO timestamp read back via show -v — a management-plane loss (10002 tunnel not found) is NOT misread as success), renewedForHours. Use the tunnelId from huaweicloud_sandbox_expose_tunnel or extract it from the URL. The keepalive watchdog renews automatically; this tool is the manual/one-off path.",
123
+ "Renew a DevBridge tunnel's lifetime (devbridge update <id> -e <hours>); devbox backend: not applicable (no tunnel) — returns HDKIT_BACKEND_UNSUPPORTED / not_applicable. — a ROLLING window: expiration = now + hours regardless of remaining time, so renewing before expiry keeps the SAME public URL alive indefinitely (the URL is bound to the tunnel ID and never changes). Default 720h = the 30-day maximum. Returns ok, tunnelId, expiresAt (absolute ISO timestamp read back via show -v — a management-plane loss (10002 tunnel not found) is NOT misread as success), renewedForHours. Use the tunnelId from huaweicloud_sandbox_expose_tunnel or extract it from the URL. The keepalive watchdog renews automatically; this tool is the manual/one-off path.",
123
124
  schema: renewTunnelSchema,
124
125
  handler: handleRenewTunnel,
125
126
  },
126
127
  {
127
128
  name: 'huaweicloud_sandbox_keepalive_watchdog',
128
129
  description:
129
- 'Install or replace the 3-layer keepalive watchdog for a set of tunnels (the tunnel-persistence pattern): (1) host re-attach — restarts `devbridge host <id>` when the host process dies (URL unchanged); (2) daily renewal — `update <id> -e 720` (29-day failure tolerance); (3) health check — curls each URL every 5 minutes and logs WARN on non-200/304. URLs are hardcoded per tunnel (never derived from port-list output — OSC escapes make those greps fail silently). Replaces the current watchdog (expose_tunnel MERGES into it; this tool SETS the list). Returns ok, scriptPath, logPath, watchdogPid, tunnels. The watchdog lives at /tmp/tunnel-keepalive.sh — cleared on reboot (the tunnel LIST dies with it): re-run this tool with the full list after a reboot (a re-expose enrolls only its own NEW tunnel).',
130
+ 'Install or replace the 3-layer keepalive watchdog for a set of tunnels (the tunnel-persistence pattern); devbox backend: not applicable (no tunnel) — returns HDKIT_BACKEND_UNSUPPORTED / not_applicable. Legacy details: (1) host re-attach — restarts `devbridge host <id>` when the host process dies (URL unchanged); (2) daily renewal — `update <id> -e 720` (29-day failure tolerance); (3) health check — curls each URL every 5 minutes and logs WARN on non-200/304. URLs are hardcoded per tunnel (never derived from port-list output — OSC escapes make those greps fail silently). Replaces the current watchdog (expose_tunnel MERGES into it; this tool SETS the list). Returns ok, scriptPath, logPath, watchdogPid, tunnels. The watchdog lives at /tmp/tunnel-keepalive.sh — cleared on reboot (the tunnel LIST dies with it): re-run this tool with the full list after a reboot (a re-expose enrolls only its own NEW tunnel).',
130
131
  schema: keepaliveWatchdogSchema,
131
132
  handler: handleKeepaliveWatchdog,
132
133
  },
133
134
  {
134
135
  name: 'huaweicloud_sandbox_check_user',
135
136
  description:
136
- 'Check if the current user has completed real-name verification and signed the required agreements. Returns 200 {realnameVerified, agreementSigned} when all good; throws 403 HDKIT_NOT_REALNAME / HDKIT_NOT_AGREEMENT / HDKIT_NOT_REALNAME_AND_AGREEMENT to indicate what is missing. Never signs anything itself.',
137
+ 'Check if the current user has completed real-name verification and signed the required agreements. devbox backend: skipped locally — returns backend:"devbox", skipped:true, checked:false, realnameVerified:null, agreementSigned:null (no fake verification). Legacy behavior: returns 200 {realnameVerified, agreementSigned} when all good; throws 403 HDKIT_NOT_REALNAME / HDKIT_NOT_AGREEMENT / HDKIT_NOT_REALNAME_AND_AGREEMENT to indicate what is missing. Never signs anything itself.',
137
138
  schema: checkUserSchema,
138
139
  handler: handleCheckUser,
139
140
  },
140
141
  {
141
142
  name: 'huaweicloud_sandbox_sign_agreement',
142
143
  description:
143
- "Sign all unsigned or outdated agreements for the current user. Required before huaweicloud_sandbox_connect if check-user returns agreementSigned=false. CRITICAL: only call after the user explicitly consents to signing — never sign agreements on the user's behalf without their explicit request.",
144
+ 'Sign all unsigned or outdated agreements for the current user. devbox backend: skipped locally (backend:"devbox", skipped:true) — no signing is needed or performed. Required before huaweicloud_sandbox_connect if check-user returns agreementSigned=false (legacy). CRITICAL: only call after the user explicitly consents to signing — never sign agreements on the user\'s behalf without their explicit request.',
144
145
  schema: signAgreementSchema,
145
146
  handler: handleSignAgreement,
146
147
  },
147
148
  {
148
149
  name: 'huaweicloud_sandbox_connect',
149
150
  description:
150
- 'Connect to a sandbox via hdkitservice. One instance per user per pool — reuses the same-pool sandbox if available, otherwise creates a new one. Quota: 1 instance per pool type (a user may hold 1 ephemeral AND 1 persistent simultaneously; same-type requests reuse the existing instance). On quota exhaustion the API returns HTTP 429 with one of three codes: HDKIT_QUOTA_EXCEEDED (retry useless — release or reuse the existing instance; Retry-After 60), HDKIT_TEMPLATE_QUOTA_EXCEEDED (the running instances of this account for this sandbox type are at the limit — shut down or release an instance of the same type and retry; no Retry-After), or HDKIT_CAPACITY_INSUFFICIENT (pool capacity; retry later / off-peak; Retry-After 60). Gateway 502/504 timeouts during orchestration return a pending receipt (ok:false, pending:true, retryAfter, hint) instead of holding the call through the backoff — the server may already have created the instance; re-call this tool with the SAME parameters after retryAfter and a created instance is reused. An outdated plugin version is rejected by the 409 HDKIT_VERSION_TOO_OLD version gate, surfaced by the sandbox tools (connect/check_user/sign_agreement/credentials) as ok:false and by the voucher trio as claimed:false, always carrying code, message, and remediation naming the upgrade act (npx --yes huaweicloud-devkit@latest update --target <agent>, restart the agent session, or huaweicloud_upgrade), with clientVersion and minVersion present when the service sends them. Returns session_id, dev_stage_id, connection_id, connection_address, expiresAt (STS credential expiry), pool_type/resolved template_id echo, server-configured lifecycle numbers (pool_idle_shutdown_minutes / pool_idle_delete_minutes / pool_reclaim_minutes) and started (true when a reused instance was woken from shutdown). Lifecycle hints are announced only on the first connect of a session or when started=true. Ephemeral pool (default): idle auto-shutdown after 30min, auto-delete after 1h — do not keep important data there. Persistent pool: data disk retained (EVS 32G), idle shutdown after 1h, idle reclaim capped at 7 days. Numbers are configured by hdkitservice; the text follows the server echo and falls back to these defaults. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.',
151
+ 'Connect to a sandbox via hdkitservice. One instance per user per pool — reuses the same-pool sandbox if available, otherwise creates a new one. Quota: 1 instance per pool type (a user may hold 1 ephemeral AND 1 persistent simultaneously; same-type requests reuse the existing instance). On quota exhaustion the API returns HTTP 429 with one of three codes: HDKIT_QUOTA_EXCEEDED (retry useless — release or reuse the existing instance; Retry-After 60), HDKIT_TEMPLATE_QUOTA_EXCEEDED (the running instances of this account for this sandbox type are at the limit — shut down or release an instance of the same type and retry; no Retry-After), or HDKIT_CAPACITY_INSUFFICIENT (pool capacity; retry later / off-peak; Retry-After 60). Gateway 502/504 timeouts during orchestration return a pending receipt (ok:false, pending:true, retryAfter, hint) instead of holding the call through the backoff — the server may already have created the instance; re-call this tool with the SAME parameters after retryAfter and a created instance is reused. An outdated plugin version is rejected by the 409 HDKIT_VERSION_TOO_OLD version gate, surfaced by the sandbox tools (connect/check_user/sign_agreement/credentials) as ok:false and by the voucher trio as claimed:false, always carrying code, message, and remediation naming the upgrade act (npx --yes huaweicloud-devkit@latest update --target <agent>, restart the agent session, or huaweicloud_upgrade), with clientVersion and minVersion present when the service sends them. Returns session_id, dev_stage_id, connection_id, connection_address, expiresAt (STS credential expiry), pool_type/resolved template_id echo, server-configured lifecycle numbers (pool_idle_shutdown_minutes / pool_idle_delete_minutes / pool_reclaim_minutes) and started (true when a reused instance was woken from shutdown). Lifecycle hints are announced only on the first connect of a session or when started=true. Ephemeral pool (default): idle auto-shutdown after 30min, auto-delete after 1h — do not keep important data there. Persistent pool: data disk retained (EVS 32G), idle shutdown after 1h, idle reclaim capped at 7 days. Numbers are configured by hdkitservice; the text follows the server echo and falls back to these defaults. devbox backend (HW_SANDBOX_BACKEND=devbox): tenant = STS principal_id (each IAM sub-account gets its own ephemeral sandbox; account/domain are audit-only, never isolation/quota); only ephemeral is supported (persistent → ok:false HDKIT_BACKEND_UNSUPPORTED); every control-plane call uses the user AK/SK (+ optional X-HW-Security-Token) — there is no sandbox key, so AK/SK rotation or a devkit restart requires re-authentication; agency/temporary credentials are rejected with HDKIT_IDENTITY_UNSUPPORTED; env maps to envVars; git is NOT accepted at create (clone with exec_one_shot or use upload_project); timeout_seconds sets the sandbox TTL (10-86400, default 1800); EnvD connect tokens stay in process memory and never appear in this result. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.',
151
152
  schema: connectSchema,
152
153
  handler: handleConnect,
153
154
  },
154
155
  {
155
156
  name: 'huaweicloud_sandbox_credentials',
156
157
  description:
157
- 'Configure temporary AK/SK for a sandbox via hdkitservice. Validates the current AK/SK against IAM before injecting (invalid SK is rejected here instead of failing later with APIGW.0301 during exec), then injects temporary credentials into the sandbox. Also injects an optional DevBridge API Key — required for devbridge 0.2.x tunnel exposure because 0.2.x removed AK/SK login. The API Key is a long-lived account-level credential, so it is stored in a separate file (/tmp/hw_api_key, 0600) from the temporary AK/SK (/tmp/hw_creds.sh). Source of truth: local HW_API_KEY env first, then the api_key param. The sandbox must be in RUNNING state.',
158
+ 'Configure temporary AK/SK for a sandbox via hdkitservice. Validates the current AK/SK against IAM before injecting (invalid SK is rejected here instead of failing later with APIGW.0301 during exec), then injects temporary credentials into the sandbox. Also injects an optional DevBridge API Key — required for devbridge 0.2.x tunnel exposure because 0.2.x removed AK/SK login. The API Key is a long-lived account-level credential, so it is stored in a separate file (/tmp/hw_api_key, 0600) from the temporary AK/SK (/tmp/hw_creds.sh). Source of truth: local HW_API_KEY env first, then the api_key param. The sandbox must be in RUNNING state. devbox backend: NOT supported — returns ok:false, code:"HDKIT_BACKEND_UNSUPPORTED"; use connect envVars or write /tmp files with exec_one_shot.',
158
159
  schema: credentialsSchema,
159
160
  handler: handleCredentials,
160
161
  },
161
162
  {
162
163
  name: 'huaweicloud_sandbox_shutdown',
163
164
  description:
164
- 'Shut down a running sandbox via hdkitservice to stop core-hour consumption. This calls DevStation close, NOT delete: the instance is retained; for persistent sandboxes the EVS data disk is also retained. A later huaweicloud_sandbox_connect wakes it. Works for both ephemeral and persistent sandboxes. Only call when the developer explicitly asks to shut down; never auto-shutdown. Returns devStageId, status (stopped/shutting_down/already_stopped/close_requested) and message.',
165
+ 'Shut down a running sandbox via hdkitservice to stop core-hour consumption. This calls DevStation close, NOT delete: the instance is retained; for persistent sandboxes the EVS data disk is also retained. A later huaweicloud_sandbox_connect wakes it. Works for both ephemeral and persistent sandboxes. devbox backend: shutdown = pause (state:"paused", pause_retention_hours 168 by default; a later connect resumes the same sandbox); the platform Key capacity is still counted while paused. Only call when the developer explicitly asks to shut down; never auto-shutdown. Returns devStageId, status (stopped/shutting_down/already_stopped/close_requested) and message on legacy; state/paused_at/pause_retention_hours on devbox.',
165
166
  schema: shutdownSchema,
166
167
  handler: handleShutdown,
167
168
  },
169
+ {
170
+ name: 'huaweicloud_sandbox_kill',
171
+ description:
172
+ 'Permanently DELETE a devbox sandbox. devbox-only: on the legacy DevStation backend it returns ok:false, code:"HDKIT_BACKEND_UNSUPPORTED" — use huaweicloud_sandbox_shutdown (pause) there. kill is irreversible: the sandbox, its data, and its app-port URL are gone; a later connect creates a NEW sandbox. Requires the always-approval gate and an explicit second confirmation from the developer. Same tenant (principal_id) can connect again after kill (the active slot is released).',
173
+ schema: killSchema,
174
+ handler: handleKill,
175
+ },
168
176
  ] as const satisfies readonly PackToolDefinition[];
169
177
 
170
178
  export type SandboxToolName = (typeof SANDBOX_TOOLS)[number]['name'];
@@ -190,6 +198,7 @@ export const SANDBOX_TOOL_SCHEMAS: Readonly<Record<SandboxToolName, LooseToolSch
190
198
  huaweicloud_sandbox_connect: connectSchema,
191
199
  huaweicloud_sandbox_credentials: credentialsSchema,
192
200
  huaweicloud_sandbox_shutdown: shutdownSchema,
201
+ huaweicloud_sandbox_kill: killSchema,
193
202
  };
194
203
 
195
204
  // Dispatch map merged into PACK_TOOL_HANDLERS in packs/registry.ts. Typed over
@@ -213,4 +222,5 @@ export const SANDBOX_TOOL_HANDLERS: Readonly<Record<SandboxToolName, PackToolDef
213
222
  huaweicloud_sandbox_connect: handleConnect,
214
223
  huaweicloud_sandbox_credentials: handleCredentials,
215
224
  huaweicloud_sandbox_shutdown: handleShutdown,
225
+ huaweicloud_sandbox_kill: handleKill,
216
226
  };
@@ -15,6 +15,9 @@ import {
15
15
  DEVBRIDGE_TUNNEL_NOT_FOUND_MARKER,
16
16
  } from './devbridge-gateway.ts';
17
17
  import { stripTerminalEscapes } from './sandbox-output.ts';
18
+ import { backendForWorkspace } from './devbox/devbox-backend.ts';
19
+ import { requireDevboxConnection } from './devbox/devbox-connections.ts';
20
+ import { probeDevboxAppUrl } from './devbox/devbox-envd-client.ts';
18
21
 
19
22
  interface DeployCheckOptions {
20
23
  port: number;
@@ -30,6 +33,7 @@ interface DeployCheckEntry {
30
33
 
31
34
  interface DeployCheckResult {
32
35
  ok: boolean;
36
+ backend?: 'legacy' | 'devbox';
33
37
  complete: boolean;
34
38
  checkType: string;
35
39
  checks: Record<string, DeployCheckEntry>;
@@ -115,6 +119,9 @@ export async function deployCheck(
115
119
  if (!workspaceId) {
116
120
  throw new Error('sandbox deploy check: workspace_id is required.');
117
121
  }
122
+ if (backendForWorkspace(workspaceId) === 'devbox') {
123
+ return await deployCheckDevbox(workspaceId, { port, project, outputDir, frameworkType }, timeoutMs);
124
+ }
118
125
 
119
126
  const projectPath = `/workspace/${project}`;
120
127
  const outputPath = outputDir.startsWith('/') ? outputDir : `${projectPath}/${outputDir}`;
@@ -293,6 +300,7 @@ fi
293
300
 
294
301
  return {
295
302
  ok: true,
303
+ backend: 'legacy',
296
304
  complete,
297
305
  checkType: isCrossPlatform ? 'cross-platform' : 'standard',
298
306
  checks,
@@ -305,3 +313,100 @@ fi
305
313
  remediation: nextStepValue === 'expose_via_devbridge' ? buildExposeRemediation(port) : undefined,
306
314
  };
307
315
  }
316
+
317
+ /**
318
+ * Devbox deploy check: no DevBridge probing. The remote script still checks
319
+ * nginx/output/fingerprint; the app-port URL is probed from the devkit side
320
+ * (the platform URL is public, single-port, and requires 0.0.0.0 binding).
321
+ */
322
+ async function deployCheckDevbox(
323
+ workspaceId: string,
324
+ { port, project, outputDir, frameworkType }: DeployCheckOptions,
325
+ timeoutMs: number,
326
+ ): Promise<DeployCheckResult> {
327
+ const projectPath = `/workspace/${project}`;
328
+ const outputPath = outputDir.startsWith('/') ? outputDir : `${projectPath}/${outputDir}`;
329
+ const isCrossPlatform = frameworkType === 'cross-platform';
330
+ const script = [
331
+ 'export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"; echo "=== DEPLOY CHECK (devbox) ==="',
332
+ 'PASS=0',
333
+ 'TOTAL=0',
334
+ 'TOTAL=$((TOTAL+1))',
335
+ `HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:${port} 2>/dev/null)`,
336
+ 'if [ -n "$HTTP_CODE" ] && [ "$HTTP_CODE" != "000" ]; then',
337
+ ` echo "nginx_serving:PASS (port ${port}, HTTP \${HTTP_CODE})"`,
338
+ ' PASS=$((PASS+1))',
339
+ 'else',
340
+ ` echo "nginx_serving:FAIL (port ${port}, no HTTP response)"`,
341
+ 'fi',
342
+ 'TOTAL=$((TOTAL+1))',
343
+ `if [ -d "${outputPath}" ] && ls -A "${outputPath}" 2>/dev/null | grep -q .; then`,
344
+ ` echo "output_dir:PASS (${outputPath})"`,
345
+ ' PASS=$((PASS+1))',
346
+ 'else',
347
+ ` echo "output_dir:FAIL (${outputPath} empty or missing)"`,
348
+ 'fi',
349
+ 'TOTAL=$((TOTAL+1))',
350
+ `FINGERPRINT_FILE="${outputPath}/.deploy_fingerprint"`,
351
+ 'FINGERPRINT_EXPECTED=$(cat "$FINGERPRINT_FILE" 2>/dev/null)',
352
+ 'if [ -n "$FINGERPRINT_EXPECTED" ]; then',
353
+ ` FINGERPRINT_ACTUAL=$(curl -s http://localhost:${port}/.deploy_fingerprint 2>/dev/null)`,
354
+ ' if [ "$FINGERPRINT_EXPECTED" = "$FINGERPRINT_ACTUAL" ]; then',
355
+ ' echo "content_verified:PASS"',
356
+ ' PASS=$((PASS+1))',
357
+ ' else',
358
+ ' echo "content_verified:FAIL (fingerprint mismatch)"',
359
+ ' fi',
360
+ 'else',
361
+ ' echo "content_verified:SKIP (no fingerprint file)"',
362
+ ' TOTAL=$((TOTAL-1))',
363
+ 'fi',
364
+ 'echo "SCORE:${PASS}/${TOTAL}"',
365
+ '[ "${PASS}" = "${TOTAL}" ] && echo "VERDICT:COMPLETE" || echo "VERDICT:INCOMPLETE"',
366
+ ].join('\n');
367
+
368
+ const result = await execOneShot(workspaceId, script, 'root', timeoutMs);
369
+ const stdout = String(result.stdout || '');
370
+ const parsed = parseDeployCheckOutput(stdout);
371
+ const connection = requireDevboxConnection(workspaceId);
372
+ const probe = await probeDevboxAppUrl(connection.envdUrl, port, 10000);
373
+ const checks: Record<string, DeployCheckEntry> = {
374
+ ...parsed.checks,
375
+ app_url_accessible: {
376
+ status: probe.ok ? 'PASS' : 'FAIL',
377
+ detail: `(${probe.url} -> HTTP ${probe.status || 'unreachable'})`,
378
+ },
379
+ qr_code: { status: 'SKIP', detail: '(not generated on devbox)' },
380
+ };
381
+ const scoredChecks = Object.values(checks).filter((entry) => entry.status !== 'SKIP');
382
+ const pass = scoredChecks.filter((entry) => entry.status === 'PASS').length;
383
+ const total = scoredChecks.length;
384
+ const complete = pass === total;
385
+ const missing = Object.entries(checks)
386
+ .filter(([, entry]) => entry.status === 'FAIL')
387
+ .map(([key]) => key);
388
+ const nextStep = complete
389
+ ? 'complete'
390
+ : missing.includes('nginx_serving')
391
+ ? 'configure_nginx'
392
+ : missing.includes('app_url_accessible')
393
+ ? 'expose_tunnel'
394
+ : 'review_checks';
395
+ return {
396
+ ok: true,
397
+ backend: 'devbox',
398
+ complete,
399
+ checkType: isCrossPlatform ? 'cross-platform' : 'standard',
400
+ checks,
401
+ score: { pass, total },
402
+ publicUrl: probe.url,
403
+ missingSteps: missing.length > 0 ? missing.join(', ') : undefined,
404
+ parseWarning: parsed.parseWarning,
405
+ rawOutput: parsed.parseWarning ? stdout.trim() : undefined,
406
+ nextStep,
407
+ remediation:
408
+ nextStep === 'expose_tunnel'
409
+ ? 'devbox 预览为单端口公开地址:确认应用绑定 0.0.0.0,然后调用 huaweicloud_sandbox_expose_tunnel 获取应用端口 URL。'
410
+ : undefined,
411
+ };
412
+ }
@@ -7,6 +7,9 @@
7
7
  // re-exports the public names as the stable public face.
8
8
 
9
9
  import { execOneShot } from './hwlink-connection.ts';
10
+ import { backendForWorkspace } from './devbox/devbox-backend.ts';
11
+ import { getDevboxConnection } from './devbox/devbox-connections.ts';
12
+ import { devboxAppPortUrl } from './devbox/devbox-envd-client.ts';
10
13
  import {
11
14
  evaluateDeployNginxVerify,
12
15
  parseDeployNginxVerifyOutput,
@@ -26,6 +29,8 @@ interface DeployNginxOptions {
26
29
  interface DeployNginxResult {
27
30
  ok: boolean;
28
31
  error?: string;
32
+ backend?: 'legacy' | 'devbox';
33
+ previewUrl?: string;
29
34
  nginxType: string;
30
35
  port: number;
31
36
  nodePort: number | undefined;
@@ -230,32 +235,41 @@ fi`;
230
235
  ].join('\n');
231
236
 
232
237
  const result = await execOneShot(workspaceId, cmd, username, timeoutMs);
238
+ const backend = backendForWorkspace(workspaceId);
239
+ const isDevbox = backend === 'devbox';
240
+ const connection = isDevbox ? getDevboxConnection(workspaceId) : undefined;
241
+ const previewUrl = isDevbox && connection ? devboxAppPortUrl(connection.envdUrl, targetPort) : undefined;
233
242
 
234
243
  let tunnelActive = false;
235
- try {
236
- // Version-aware: devbridge 0.1.x exposes JSON via `list -j`; 0.2.x removed -j and
237
- // prints a table whose data rows start with the 8-char base32 tunnel ID.
238
- // #999: the data-disk-first PATH — a fresh one-shot shell does not inherit
239
- // any prior export, and after the Layer-3 install + dedup (or a reboot) the
240
- // only surviving binary lives at /workspace/.local/bin.
241
- const tunnelCheck = await execOneShot(
242
- workspaceId,
243
- 'export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"; (devbridge list -j 2>/dev/null | grep -q \'"tunnelId"\' || devbridge list 2>/dev/null | grep -Eq \'^[a-z2-7]{8}[[:space:]]\') && echo "ACTIVE" || echo "INACTIVE"',
244
- username,
245
- 10000,
246
- );
247
- tunnelActive = String(tunnelCheck.stdout || '').includes('ACTIVE');
248
- } catch {
249
- // a failed probe leaves tunnelActive false; the result then carries the incomplete-deployment warning
244
+ if (!isDevbox) {
245
+ try {
246
+ // Version-aware: devbridge 0.1.x exposes JSON via `list -j`; 0.2.x removed -j and
247
+ // prints a table whose data rows start with the 8-char base32 tunnel ID.
248
+ // #999: the data-disk-first PATH — a fresh one-shot shell does not inherit
249
+ // any prior export, and after the Layer-3 install + dedup (or a reboot) the
250
+ // only surviving binary lives at /workspace/.local/bin.
251
+ const tunnelCheck = await execOneShot(
252
+ workspaceId,
253
+ 'export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"; (devbridge list -j 2>/dev/null | grep -q \'"tunnelId"\' || devbridge list 2>/dev/null | grep -Eq \'^[a-z2-7]{8}[[:space:]]\') && echo "ACTIVE" || echo "INACTIVE"',
254
+ username,
255
+ 10000,
256
+ );
257
+ tunnelActive = String(tunnelCheck.stdout || '').includes('ACTIVE');
258
+ } catch {
259
+ // a failed probe leaves tunnelActive false; the result then carries the incomplete-deployment warning
260
+ }
250
261
  }
251
262
 
252
263
  const warning =
253
264
  [
254
- !tunnelActive
265
+ !isDevbox && !tunnelActive
255
266
  ? 'No active DevBridge tunnel — deployment is incomplete. Proceed to Step 7 to expose the app.'
256
267
  : undefined,
268
+ isDevbox
269
+ ? 'devbox 后端不使用 DevBridge 隧道:确认应用/nginx 绑定 0.0.0.0,然后调用 deploy_check 验证应用端口 URL。'
270
+ : undefined,
257
271
  formatPortConflictWarning(basePort, targetPort),
258
- tunnelActive ? formatPortDriftWarning(basePort, targetPort) : undefined,
272
+ !isDevbox && tunnelActive ? formatPortDriftWarning(basePort, targetPort) : undefined,
259
273
  ]
260
274
  .filter(Boolean)
261
275
  .join(' | ') || undefined;
@@ -270,6 +284,8 @@ fi`;
270
284
  return {
271
285
  ok: false,
272
286
  error: verdict.error,
287
+ backend,
288
+ ...(previewUrl ? { previewUrl } : {}),
273
289
  nginxType,
274
290
  port: targetPort,
275
291
  nodePort: effectiveNodePort || undefined,
@@ -285,6 +301,8 @@ fi`;
285
301
 
286
302
  return {
287
303
  ok: true,
304
+ backend,
305
+ ...(previewUrl ? { previewUrl } : {}),
288
306
  nginxType,
289
307
  port: targetPort,
290
308
  nodePort: effectiveNodePort || undefined,
@@ -294,7 +312,7 @@ fi`;
294
312
  verification: { configPath, nginxTest: verify.nginxTest },
295
313
  exitCode: result.exitCode,
296
314
  stdout: result.stdout,
297
- nextStep: 'expose_via_devbridge',
315
+ nextStep: isDevbox ? 'deploy_check' : 'expose_via_devbridge',
298
316
  warning,
299
317
  };
300
318
  }
@@ -0,0 +1,44 @@
1
+ // Sandbox backend posture: legacy (DevStation/hwlink) or devbox (platform
2
+ // resource pool). The env var is the operator posture; after a successful
3
+ // connect the workspace's backend is pinned in-process so a mid-session env
4
+ // flip can never route one workspace across backends.
5
+
6
+ export type SandboxBackend = 'legacy' | 'devbox';
7
+
8
+ const workspaceBackends = new Map<string, SandboxBackend>();
9
+
10
+ export function sandboxBackend(): SandboxBackend {
11
+ const raw = process.env.HW_SANDBOX_BACKEND;
12
+ if (raw === undefined || raw === '' || raw === 'legacy') return 'legacy';
13
+ if (raw === 'devbox') return 'devbox';
14
+ throw new Error(
15
+ `HW_SANDBOX_BACKEND must be "legacy" or "devbox" (got "${raw}"). ` +
16
+ 'Unknown values fail fast at startup instead of silently routing sandbox traffic.',
17
+ );
18
+ }
19
+
20
+ export function isDevboxBackend(): boolean {
21
+ return sandboxBackend() === 'devbox';
22
+ }
23
+
24
+ export function rememberWorkspaceBackend(workspaceId: string, backend: SandboxBackend): void {
25
+ if (!workspaceId) return;
26
+ workspaceBackends.set(workspaceId, backend);
27
+ }
28
+
29
+ export function forgetWorkspaceBackend(workspaceId: string): void {
30
+ workspaceBackends.delete(workspaceId);
31
+ }
32
+
33
+ /** Backend this workspace was connected on; falls back to the operator posture. */
34
+ export function backendForWorkspace(workspaceId: string | null | undefined): SandboxBackend {
35
+ if (workspaceId) {
36
+ const pinned = workspaceBackends.get(workspaceId);
37
+ if (pinned) return pinned;
38
+ }
39
+ return sandboxBackend();
40
+ }
41
+
42
+ export function _clearWorkspaceBackendsForTests(): void {
43
+ workspaceBackends.clear();
44
+ }
@@ -0,0 +1,115 @@
1
+ // In-process DevBox connection cache (workspace -> single-sandbox EnvD
2
+ // credentials). Tokens are process-memory only: never serialized, never
3
+ // logged, never returned in a tool result. A devkit restart requires a
4
+ // fresh connect with valid AK/SK (A posture — no sandbox key).
5
+
6
+ export interface DevboxConnectionRecord {
7
+ workspaceId: string;
8
+ sandboxId: string;
9
+ state: string;
10
+ templateId?: string;
11
+ envdUrl: string;
12
+ tunnelId?: string;
13
+ connectToken: string;
14
+ envdAccessToken?: string;
15
+ envdVersion?: string;
16
+ /** ISO-8601 (the hdkitservice response shape). */
17
+ tokenExpiration?: string;
18
+ /** ISO-8601 sandbox TTL end. */
19
+ endAt?: string;
20
+ poolType: string;
21
+ started: boolean;
22
+ pauseRetentionHours?: number;
23
+ }
24
+
25
+ const connections = new Map<string, DevboxConnectionRecord>();
26
+
27
+ function str(value: unknown): string | undefined {
28
+ return typeof value === 'string' && value !== '' ? value : undefined;
29
+ }
30
+
31
+ /** Fold a hdkitservice devbox connect/refresh response into the cache. */
32
+ export function setDevboxConnectionFromResponse(
33
+ workspaceId: string,
34
+ result: Record<string, unknown>,
35
+ ): DevboxConnectionRecord {
36
+ const sandboxId =
37
+ str(result.sandbox_id) || str(result.sandboxId) || str(result.session_id) || str(result.dev_stage_id);
38
+ if (!sandboxId) {
39
+ throw new Error('DevBox connect response did not include a sandbox id — refusing to cache a partial connection.');
40
+ }
41
+ const envdUrl = str(result.envd_url) || str(result.envdUrl);
42
+ const connectToken = str(result.connect_token) || str(result.connectToken);
43
+ if (!envdUrl || !connectToken) {
44
+ throw new Error(
45
+ 'DevBox connect response did not include EnvD credentials — refusing to cache a partial connection.',
46
+ );
47
+ }
48
+ const existing = connections.get(workspaceId);
49
+ const record: DevboxConnectionRecord = {
50
+ workspaceId,
51
+ sandboxId,
52
+ state: str(result.state) || 'running',
53
+ templateId: str(result.template_id) || str(result.templateId) || existing?.templateId,
54
+ envdUrl,
55
+ tunnelId: str(result.tunnel_id) || str(result.tunnelId),
56
+ connectToken,
57
+ envdAccessToken: str(result.envd_access_token) || str(result.envdAccessToken),
58
+ envdVersion: str(result.envd_version) || str(result.envdVersion),
59
+ tokenExpiration: str(result.token_expiration) || str(result.tokenExpiration),
60
+ endAt: str(result.end_at) || str(result.endAt),
61
+ poolType: str(result.pool_type) || str(result.poolType) || 'ephemeral',
62
+ started: result.started === true,
63
+ pauseRetentionHours:
64
+ typeof result.pause_retention_hours === 'number'
65
+ ? result.pause_retention_hours
66
+ : typeof result.pauseRetentionHours === 'number'
67
+ ? result.pauseRetentionHours
68
+ : existing?.pauseRetentionHours,
69
+ };
70
+ connections.set(workspaceId, record);
71
+ // The sandbox id is the workspace id on the devbox path; keep the alias hot
72
+ // so a caller holding either identifier resolves the same cache entry.
73
+ if (sandboxId !== workspaceId) connections.set(sandboxId, record);
74
+ return record;
75
+ }
76
+
77
+ export function getDevboxConnection(workspaceId: string | null | undefined): DevboxConnectionRecord | undefined {
78
+ if (!workspaceId) return undefined;
79
+ return connections.get(workspaceId);
80
+ }
81
+
82
+ export function requireDevboxConnection(workspaceId: string): DevboxConnectionRecord {
83
+ const connection = connections.get(workspaceId);
84
+ if (!connection) {
85
+ throw new Error(
86
+ `No DevBox connection for workspace "${workspaceId}" in this process. ` +
87
+ 'Call huaweicloud_sandbox_connect again with valid AK/SK — devbox tokens are memory-only and do not survive a restart.',
88
+ );
89
+ }
90
+ return connection;
91
+ }
92
+
93
+ export function clearDevboxConnection(workspaceId: string | null | undefined): void {
94
+ if (!workspaceId) return;
95
+ const connection = connections.get(workspaceId);
96
+ if (!connection) return;
97
+ connections.delete(connection.workspaceId);
98
+ connections.delete(connection.sandboxId);
99
+ }
100
+
101
+ export function _clearDevboxConnectionsForTests(): void {
102
+ connections.clear();
103
+ }
104
+
105
+ const TOKEN_REFRESH_WINDOW_MS = 5 * 60 * 1000;
106
+
107
+ /** True when the EnvD token expires inside the refresh window (or is unparsable). */
108
+ export function devboxTokenNeedsRefresh(connection: DevboxConnectionRecord): boolean {
109
+ if (!connection.tokenExpiration) return false;
110
+ const raw = connection.tokenExpiration.trim();
111
+ const epochSeconds = Number(raw);
112
+ const expiresAt = Number.isFinite(epochSeconds) ? epochSeconds * 1000 : Date.parse(raw);
113
+ if (!Number.isFinite(expiresAt)) return true;
114
+ return expiresAt <= Date.now() + TOKEN_REFRESH_WINDOW_MS;
115
+ }