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.
- package/README.md +2 -2
- package/package.json +1 -1
- package/plugins/huaweicloud-core/.claude-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/.codex-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/.mcp.json +3 -0
- package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +1 -1
- package/plugins/huaweicloud-core/dist/approval-roster.js +2 -0
- package/plugins/huaweicloud-core/dist/lib/hdkit/hdkit-gate.js +7 -0
- package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +30 -1
- package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +21 -0
- package/plugins/huaweicloud-core/dist/mcp-server.js +5019 -3879
- package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
- package/plugins/huaweicloud-core/dist/packs/registry.js +1 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/approval.js +13 -2
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +198 -10
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +11 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +22 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +46 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-upload.js +11 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +20 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +26 -18
- package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +97 -0
- package/plugins/huaweicloud-core/dist/sandbox/deploy-nginx.js +30 -14
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-backend.js +37 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-connections.js +84 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-envd-client.js +229 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-envd-protocol.js +151 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-envd-transport.js +121 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-service-api.js +80 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbox/devbox-upload.js +106 -0
- package/plugins/huaweicloud-core/dist/sandbox/hwlink-connection.js +12 -0
- package/plugins/huaweicloud-core/dist/sandbox/upload-project.js +5 -2
- package/plugins/huaweicloud-core/dist/tool-definitions.js +4 -0
- package/plugins/huaweicloud-core/dist/tools.js +1 -0
- package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
- package/plugins/huaweicloud-core/safety/policy.json +2 -1
- package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +67 -16
- package/plugins/huaweicloud-core/skills/huawei-sandbox/references/devbox-backend.md +78 -0
- package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +14 -0
- package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +2 -1
- package/plugins/huaweicloud-core/src/approval-roster.ts +2 -0
- package/plugins/huaweicloud-core/src/lib/hdkit/hdkit-gate.ts +7 -0
- package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +30 -1
- package/plugins/huaweicloud-core/src/lib/hdkit/sandbox-pool.ts +22 -0
- package/plugins/huaweicloud-core/src/packs/registry.ts +1 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/approval.ts +15 -2
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +206 -11
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +12 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +23 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +49 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-upload.ts +11 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +23 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +27 -17
- package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +105 -0
- package/plugins/huaweicloud-core/src/sandbox/deploy-nginx.ts +36 -18
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-backend.ts +44 -0
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-connections.ts +115 -0
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-envd-client.ts +281 -0
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-envd-protocol.ts +180 -0
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-envd-transport.ts +142 -0
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-service-api.ts +102 -0
- package/plugins/huaweicloud-core/src/sandbox/devbox/devbox-upload.ts +167 -0
- package/plugins/huaweicloud-core/src/sandbox/hwlink-connection.ts +12 -0
- package/plugins/huaweicloud-core/src/sandbox/upload-project.ts +5 -2
- package/plugins/huaweicloud-core/src/tool-definitions.ts +4 -0
- package/plugins/huaweicloud-core/src/tools.ts +3 -0
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import { execWithSessionSchema, execOneShotSchema, execPollSchema, closeSessionSchema, uploadFileSchema, uploadProjectSchema, deployNginxSchema, deployCheckSchema, checkUserSchema, exposeTunnelSchema, exposePollSchema, renewTunnelSchema, keepaliveWatchdogSchema, signAgreementSchema, connectSchema, credentialsSchema, shutdownSchema, } from "./schemas.js";
|
|
1
|
+
import { execWithSessionSchema, execOneShotSchema, execPollSchema, closeSessionSchema, uploadFileSchema, uploadProjectSchema, deployNginxSchema, deployCheckSchema, checkUserSchema, exposeTunnelSchema, exposePollSchema, renewTunnelSchema, keepaliveWatchdogSchema, signAgreementSchema, connectSchema, credentialsSchema, shutdownSchema, killSchema, } from "./schemas.js";
|
|
2
2
|
import { handleExecWithSession, handleExecOneShot, handleCloseSession } from "./handlers-session.js";
|
|
3
3
|
import { handleHwexecPoll } from "./handlers-hwexec.js";
|
|
4
4
|
import { handleUploadFile, handleUploadProject } from "./handlers-upload.js";
|
|
5
5
|
import { handleDeployNginx, handleDeployCheck } from "./handlers-deploy.js";
|
|
6
6
|
import { handleExposeTunnel, handleExposePoll, handleRenewTunnel, handleKeepaliveWatchdog } from "./handlers-tunnel.js";
|
|
7
|
-
import { handleCheckUser, handleSignAgreement, handleConnect, handleShutdown } from "./handlers-account.js";
|
|
7
|
+
import { handleCheckUser, handleSignAgreement, handleConnect, handleShutdown, handleKill } from "./handlers-account.js";
|
|
8
8
|
import { handleCredentials } from "./handlers-credentials.js";
|
|
9
9
|
// The sandbox pack's stable face (split from the former 879-line monolith
|
|
10
10
|
// for the jscpd complex-file bar, cx < 50 per file; the safety-policy.ts
|
|
@@ -26,13 +26,13 @@ export { SANDBOX_TIMEOUT_MS } from "./schemas.js";
|
|
|
26
26
|
export const SANDBOX_TOOLS = [
|
|
27
27
|
{
|
|
28
28
|
name: 'huaweicloud_sandbox_exec_with_session',
|
|
29
|
-
description: 'Execute a command on a workspace terminal
|
|
29
|
+
description: '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".',
|
|
30
30
|
schema: execWithSessionSchema,
|
|
31
31
|
handler: handleExecWithSession,
|
|
32
32
|
},
|
|
33
33
|
{
|
|
34
34
|
name: 'huaweicloud_sandbox_exec_one_shot',
|
|
35
|
-
description: '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.',
|
|
35
|
+
description: '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.',
|
|
36
36
|
schema: execOneShotSchema,
|
|
37
37
|
handler: handleExecOneShot,
|
|
38
38
|
},
|
|
@@ -44,88 +44,94 @@ export const SANDBOX_TOOLS = [
|
|
|
44
44
|
},
|
|
45
45
|
{
|
|
46
46
|
name: 'huaweicloud_sandbox_close_session',
|
|
47
|
-
description: '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.',
|
|
47
|
+
description: '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).',
|
|
48
48
|
schema: closeSessionSchema,
|
|
49
49
|
handler: handleCloseSession,
|
|
50
50
|
},
|
|
51
51
|
{
|
|
52
52
|
name: 'huaweicloud_sandbox_upload_file',
|
|
53
|
-
description: 'Upload a local file into the sandbox workspace.
|
|
53
|
+
description: '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.',
|
|
54
54
|
schema: uploadFileSchema,
|
|
55
55
|
handler: handleUploadFile,
|
|
56
56
|
},
|
|
57
57
|
{
|
|
58
58
|
name: 'huaweicloud_sandbox_upload_project',
|
|
59
|
-
description: 'Package a local project directory and upload it to a sandbox workspace
|
|
59
|
+
description: '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.',
|
|
60
60
|
schema: uploadProjectSchema,
|
|
61
61
|
handler: handleUploadProject,
|
|
62
62
|
},
|
|
63
63
|
{
|
|
64
64
|
name: 'huaweicloud_sandbox_deploy_nginx',
|
|
65
|
-
description: '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.',
|
|
65
|
+
description: '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.',
|
|
66
66
|
schema: deployNginxSchema,
|
|
67
67
|
handler: handleDeployNginx,
|
|
68
68
|
},
|
|
69
69
|
{
|
|
70
70
|
name: 'huaweicloud_sandbox_deploy_check',
|
|
71
|
-
description: '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.',
|
|
71
|
+
description: '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.',
|
|
72
72
|
schema: deployCheckSchema,
|
|
73
73
|
handler: handleDeployCheck,
|
|
74
74
|
},
|
|
75
75
|
{
|
|
76
76
|
name: 'huaweicloud_sandbox_expose_tunnel',
|
|
77
|
-
description: '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.',
|
|
77
|
+
description: '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.',
|
|
78
78
|
schema: exposeTunnelSchema,
|
|
79
79
|
handler: handleExposeTunnel,
|
|
80
80
|
},
|
|
81
81
|
{
|
|
82
82
|
name: 'huaweicloud_sandbox_expose_poll',
|
|
83
|
-
description: '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.',
|
|
83
|
+
description: '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.',
|
|
84
84
|
schema: exposePollSchema,
|
|
85
85
|
handler: handleExposePoll,
|
|
86
86
|
},
|
|
87
87
|
{
|
|
88
88
|
name: 'huaweicloud_sandbox_renew_tunnel',
|
|
89
|
-
description: "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.",
|
|
89
|
+
description: "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.",
|
|
90
90
|
schema: renewTunnelSchema,
|
|
91
91
|
handler: handleRenewTunnel,
|
|
92
92
|
},
|
|
93
93
|
{
|
|
94
94
|
name: 'huaweicloud_sandbox_keepalive_watchdog',
|
|
95
|
-
description: '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).',
|
|
95
|
+
description: '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).',
|
|
96
96
|
schema: keepaliveWatchdogSchema,
|
|
97
97
|
handler: handleKeepaliveWatchdog,
|
|
98
98
|
},
|
|
99
99
|
{
|
|
100
100
|
name: 'huaweicloud_sandbox_check_user',
|
|
101
|
-
description: 'Check if the current user has completed real-name verification and signed the required agreements.
|
|
101
|
+
description: '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.',
|
|
102
102
|
schema: checkUserSchema,
|
|
103
103
|
handler: handleCheckUser,
|
|
104
104
|
},
|
|
105
105
|
{
|
|
106
106
|
name: 'huaweicloud_sandbox_sign_agreement',
|
|
107
|
-
description:
|
|
107
|
+
description: '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.',
|
|
108
108
|
schema: signAgreementSchema,
|
|
109
109
|
handler: handleSignAgreement,
|
|
110
110
|
},
|
|
111
111
|
{
|
|
112
112
|
name: 'huaweicloud_sandbox_connect',
|
|
113
|
-
description: '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.',
|
|
113
|
+
description: '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.',
|
|
114
114
|
schema: connectSchema,
|
|
115
115
|
handler: handleConnect,
|
|
116
116
|
},
|
|
117
117
|
{
|
|
118
118
|
name: 'huaweicloud_sandbox_credentials',
|
|
119
|
-
description: '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.',
|
|
119
|
+
description: '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.',
|
|
120
120
|
schema: credentialsSchema,
|
|
121
121
|
handler: handleCredentials,
|
|
122
122
|
},
|
|
123
123
|
{
|
|
124
124
|
name: 'huaweicloud_sandbox_shutdown',
|
|
125
|
-
description: '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.',
|
|
125
|
+
description: '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.',
|
|
126
126
|
schema: shutdownSchema,
|
|
127
127
|
handler: handleShutdown,
|
|
128
128
|
},
|
|
129
|
+
{
|
|
130
|
+
name: 'huaweicloud_sandbox_kill',
|
|
131
|
+
description: '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).',
|
|
132
|
+
schema: killSchema,
|
|
133
|
+
handler: handleKill,
|
|
134
|
+
},
|
|
129
135
|
];
|
|
130
136
|
// Schema map keyed by tool name for src/tool-schemas.ts: TOOL_SCHEMAS spreads
|
|
131
137
|
// it in place, keeping the satisfies Record<ToolName, LooseToolSchema>
|
|
@@ -148,6 +154,7 @@ export const SANDBOX_TOOL_SCHEMAS = {
|
|
|
148
154
|
huaweicloud_sandbox_connect: connectSchema,
|
|
149
155
|
huaweicloud_sandbox_credentials: credentialsSchema,
|
|
150
156
|
huaweicloud_sandbox_shutdown: shutdownSchema,
|
|
157
|
+
huaweicloud_sandbox_kill: killSchema,
|
|
151
158
|
};
|
|
152
159
|
// Dispatch map merged into PACK_TOOL_HANDLERS in packs/registry.ts. Typed over
|
|
153
160
|
// SandboxToolName, so a tool added to SANDBOX_TOOLS without a handler entry
|
|
@@ -170,4 +177,5 @@ export const SANDBOX_TOOL_HANDLERS = {
|
|
|
170
177
|
huaweicloud_sandbox_connect: handleConnect,
|
|
171
178
|
huaweicloud_sandbox_credentials: handleCredentials,
|
|
172
179
|
huaweicloud_sandbox_shutdown: handleShutdown,
|
|
180
|
+
huaweicloud_sandbox_kill: handleKill,
|
|
173
181
|
};
|
|
@@ -9,6 +9,9 @@
|
|
|
9
9
|
import { execOneShot } from "./hwlink-connection.js";
|
|
10
10
|
import { DEVBRIDGE_BAD_GATEWAY_MARKER, DEVBRIDGE_PORT_NOT_CONFIGURED_MARKER, DEVBRIDGE_TUNNEL_DOMAIN, DEVBRIDGE_TUNNEL_NOT_FOUND_MARKER, } from "./devbridge-gateway.js";
|
|
11
11
|
import { stripTerminalEscapes } from "./sandbox-output.js";
|
|
12
|
+
import { backendForWorkspace } from "./devbox/devbox-backend.js";
|
|
13
|
+
import { requireDevboxConnection } from "./devbox/devbox-connections.js";
|
|
14
|
+
import { probeDevboxAppUrl } from "./devbox/devbox-envd-client.js";
|
|
12
15
|
export const TUNNEL_URL_PATTERN = /TUNNEL_URL:(https:\/\/[A-Za-z0-9_-]+-\d+\.devbridge-s2\.hwtunnel\.com)/;
|
|
13
16
|
export function buildExposeRemediation(port) {
|
|
14
17
|
return `In the sandbox: source /tmp/hw_api_key 2>/dev/null; for T in $(devbridge list 2>/dev/null | awk '{gsub(/\\033\\]133;C\\007/, ""); if ($1 !~ /^Tunnel/ && $1 !~ /^No$/) print $1}'); do devbridge port list "$T" 2>/dev/null | awk -v P=${port} '{gsub(/\\033\\]133;C\\007/, ""); if ($1 == P) f=1} END {exit f ? 0 : 1}' && devbridge delete "$T" 2>/dev/null || true; done; devbridge create <name>; devbridge port create <tunnelId> -p ${port} --protocol http -a; if command -v setsid >/dev/null 2>&1; then setsid nohup devbridge host <tunnelId> -p ${port} -e 72 > /tmp/host.log 2>&1 < /dev/null & else nohup devbridge host <tunnelId> -p ${port} -e 72 > /tmp/host.log 2>&1 < /dev/null & fi; disown 2>/dev/null || true; the loop deletes ONLY the tunnels whose port list contains ${port} (any tunnel name — query each tunnel's ports with devbridge port list; a name-based match would miss the custom-named tunnels this flow itself creates), INCLUDING a keepalive-protected tunnel bound to THIS port — a port cannot have two tunnels, so the same-port tunnel is always replaced; all OTHER ports, other sessions and keepalive-protected tunnels on other ports are preserved (never wipe every tunnel here — a global delete kills every session's tunnels). The gsub strips OSC 133 shell-integration markers that wrap every output line on integration-enabled terminals — without it the CLI receives glued tunnel IDs it rejects and the delete silently no-ops. If deploy_nginx reported a different (auto-incremented) port in its "port" field, use THAT port instead of the one shown here. Full procedure in huawei-sandbox skill, Step 7 (Expose via DevBridge).`;
|
|
@@ -59,6 +62,9 @@ timeoutMs = 60000) {
|
|
|
59
62
|
if (!workspaceId) {
|
|
60
63
|
throw new Error('sandbox deploy check: workspace_id is required.');
|
|
61
64
|
}
|
|
65
|
+
if (backendForWorkspace(workspaceId) === 'devbox') {
|
|
66
|
+
return await deployCheckDevbox(workspaceId, { port, project, outputDir, frameworkType }, timeoutMs);
|
|
67
|
+
}
|
|
62
68
|
const projectPath = `/workspace/${project}`;
|
|
63
69
|
const outputPath = outputDir.startsWith('/') ? outputDir : `${projectPath}/${outputDir}`;
|
|
64
70
|
const isCrossPlatform = frameworkType === 'cross-platform';
|
|
@@ -232,6 +238,7 @@ fi
|
|
|
232
238
|
: 'complete';
|
|
233
239
|
return {
|
|
234
240
|
ok: true,
|
|
241
|
+
backend: 'legacy',
|
|
235
242
|
complete,
|
|
236
243
|
checkType: isCrossPlatform ? 'cross-platform' : 'standard',
|
|
237
244
|
checks,
|
|
@@ -244,3 +251,93 @@ fi
|
|
|
244
251
|
remediation: nextStepValue === 'expose_via_devbridge' ? buildExposeRemediation(port) : undefined,
|
|
245
252
|
};
|
|
246
253
|
}
|
|
254
|
+
/**
|
|
255
|
+
* Devbox deploy check: no DevBridge probing. The remote script still checks
|
|
256
|
+
* nginx/output/fingerprint; the app-port URL is probed from the devkit side
|
|
257
|
+
* (the platform URL is public, single-port, and requires 0.0.0.0 binding).
|
|
258
|
+
*/
|
|
259
|
+
async function deployCheckDevbox(workspaceId, { port, project, outputDir, frameworkType }, timeoutMs) {
|
|
260
|
+
const projectPath = `/workspace/${project}`;
|
|
261
|
+
const outputPath = outputDir.startsWith('/') ? outputDir : `${projectPath}/${outputDir}`;
|
|
262
|
+
const isCrossPlatform = frameworkType === 'cross-platform';
|
|
263
|
+
const script = [
|
|
264
|
+
'export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"; echo "=== DEPLOY CHECK (devbox) ==="',
|
|
265
|
+
'PASS=0',
|
|
266
|
+
'TOTAL=0',
|
|
267
|
+
'TOTAL=$((TOTAL+1))',
|
|
268
|
+
`HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:${port} 2>/dev/null)`,
|
|
269
|
+
'if [ -n "$HTTP_CODE" ] && [ "$HTTP_CODE" != "000" ]; then',
|
|
270
|
+
` echo "nginx_serving:PASS (port ${port}, HTTP \${HTTP_CODE})"`,
|
|
271
|
+
' PASS=$((PASS+1))',
|
|
272
|
+
'else',
|
|
273
|
+
` echo "nginx_serving:FAIL (port ${port}, no HTTP response)"`,
|
|
274
|
+
'fi',
|
|
275
|
+
'TOTAL=$((TOTAL+1))',
|
|
276
|
+
`if [ -d "${outputPath}" ] && ls -A "${outputPath}" 2>/dev/null | grep -q .; then`,
|
|
277
|
+
` echo "output_dir:PASS (${outputPath})"`,
|
|
278
|
+
' PASS=$((PASS+1))',
|
|
279
|
+
'else',
|
|
280
|
+
` echo "output_dir:FAIL (${outputPath} empty or missing)"`,
|
|
281
|
+
'fi',
|
|
282
|
+
'TOTAL=$((TOTAL+1))',
|
|
283
|
+
`FINGERPRINT_FILE="${outputPath}/.deploy_fingerprint"`,
|
|
284
|
+
'FINGERPRINT_EXPECTED=$(cat "$FINGERPRINT_FILE" 2>/dev/null)',
|
|
285
|
+
'if [ -n "$FINGERPRINT_EXPECTED" ]; then',
|
|
286
|
+
` FINGERPRINT_ACTUAL=$(curl -s http://localhost:${port}/.deploy_fingerprint 2>/dev/null)`,
|
|
287
|
+
' if [ "$FINGERPRINT_EXPECTED" = "$FINGERPRINT_ACTUAL" ]; then',
|
|
288
|
+
' echo "content_verified:PASS"',
|
|
289
|
+
' PASS=$((PASS+1))',
|
|
290
|
+
' else',
|
|
291
|
+
' echo "content_verified:FAIL (fingerprint mismatch)"',
|
|
292
|
+
' fi',
|
|
293
|
+
'else',
|
|
294
|
+
' echo "content_verified:SKIP (no fingerprint file)"',
|
|
295
|
+
' TOTAL=$((TOTAL-1))',
|
|
296
|
+
'fi',
|
|
297
|
+
'echo "SCORE:${PASS}/${TOTAL}"',
|
|
298
|
+
'[ "${PASS}" = "${TOTAL}" ] && echo "VERDICT:COMPLETE" || echo "VERDICT:INCOMPLETE"',
|
|
299
|
+
].join('\n');
|
|
300
|
+
const result = await execOneShot(workspaceId, script, 'root', timeoutMs);
|
|
301
|
+
const stdout = String(result.stdout || '');
|
|
302
|
+
const parsed = parseDeployCheckOutput(stdout);
|
|
303
|
+
const connection = requireDevboxConnection(workspaceId);
|
|
304
|
+
const probe = await probeDevboxAppUrl(connection.envdUrl, port, 10000);
|
|
305
|
+
const checks = {
|
|
306
|
+
...parsed.checks,
|
|
307
|
+
app_url_accessible: {
|
|
308
|
+
status: probe.ok ? 'PASS' : 'FAIL',
|
|
309
|
+
detail: `(${probe.url} -> HTTP ${probe.status || 'unreachable'})`,
|
|
310
|
+
},
|
|
311
|
+
qr_code: { status: 'SKIP', detail: '(not generated on devbox)' },
|
|
312
|
+
};
|
|
313
|
+
const scoredChecks = Object.values(checks).filter((entry) => entry.status !== 'SKIP');
|
|
314
|
+
const pass = scoredChecks.filter((entry) => entry.status === 'PASS').length;
|
|
315
|
+
const total = scoredChecks.length;
|
|
316
|
+
const complete = pass === total;
|
|
317
|
+
const missing = Object.entries(checks)
|
|
318
|
+
.filter(([, entry]) => entry.status === 'FAIL')
|
|
319
|
+
.map(([key]) => key);
|
|
320
|
+
const nextStep = complete
|
|
321
|
+
? 'complete'
|
|
322
|
+
: missing.includes('nginx_serving')
|
|
323
|
+
? 'configure_nginx'
|
|
324
|
+
: missing.includes('app_url_accessible')
|
|
325
|
+
? 'expose_tunnel'
|
|
326
|
+
: 'review_checks';
|
|
327
|
+
return {
|
|
328
|
+
ok: true,
|
|
329
|
+
backend: 'devbox',
|
|
330
|
+
complete,
|
|
331
|
+
checkType: isCrossPlatform ? 'cross-platform' : 'standard',
|
|
332
|
+
checks,
|
|
333
|
+
score: { pass, total },
|
|
334
|
+
publicUrl: probe.url,
|
|
335
|
+
missingSteps: missing.length > 0 ? missing.join(', ') : undefined,
|
|
336
|
+
parseWarning: parsed.parseWarning,
|
|
337
|
+
rawOutput: parsed.parseWarning ? stdout.trim() : undefined,
|
|
338
|
+
nextStep,
|
|
339
|
+
remediation: nextStep === 'expose_tunnel'
|
|
340
|
+
? 'devbox 预览为单端口公开地址:确认应用绑定 0.0.0.0,然后调用 huaweicloud_sandbox_expose_tunnel 获取应用端口 URL。'
|
|
341
|
+
: undefined,
|
|
342
|
+
};
|
|
343
|
+
}
|
|
@@ -6,6 +6,9 @@
|
|
|
6
6
|
// through the one-shot surface in hwlink-connection.ts; session-manager.ts
|
|
7
7
|
// re-exports the public names as the stable public face.
|
|
8
8
|
import { execOneShot } from "./hwlink-connection.js";
|
|
9
|
+
import { backendForWorkspace } from "./devbox/devbox-backend.js";
|
|
10
|
+
import { getDevboxConnection } from "./devbox/devbox-connections.js";
|
|
11
|
+
import { devboxAppPortUrl } from "./devbox/devbox-envd-client.js";
|
|
9
12
|
import { evaluateDeployNginxVerify, parseDeployNginxVerifyOutput, resolveNginxConfigPath, } from "./deploy-nginx-verify.js";
|
|
10
13
|
export function formatPortConflictWarning(basePort, targetPort) {
|
|
11
14
|
return targetPort !== basePort ? `Port ${basePort} is in use — auto-assigned port ${targetPort}` : undefined;
|
|
@@ -154,25 +157,34 @@ fi`;
|
|
|
154
157
|
`if echo "$NGINX_T_OUTPUT" | grep -Eq "syntax is ok|test is successful"; then echo "DB_NGINX_T=PASS"; else echo "DB_NGINX_T=FAIL"; echo "$NGINX_T_OUTPUT" | sed "s/^/DB_NGINX_T_OUTPUT: /"; fi`,
|
|
155
158
|
].join('\n');
|
|
156
159
|
const result = await execOneShot(workspaceId, cmd, username, timeoutMs);
|
|
160
|
+
const backend = backendForWorkspace(workspaceId);
|
|
161
|
+
const isDevbox = backend === 'devbox';
|
|
162
|
+
const connection = isDevbox ? getDevboxConnection(workspaceId) : undefined;
|
|
163
|
+
const previewUrl = isDevbox && connection ? devboxAppPortUrl(connection.envdUrl, targetPort) : undefined;
|
|
157
164
|
let tunnelActive = false;
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
165
|
+
if (!isDevbox) {
|
|
166
|
+
try {
|
|
167
|
+
// Version-aware: devbridge 0.1.x exposes JSON via `list -j`; 0.2.x removed -j and
|
|
168
|
+
// prints a table whose data rows start with the 8-char base32 tunnel ID.
|
|
169
|
+
// #999: the data-disk-first PATH — a fresh one-shot shell does not inherit
|
|
170
|
+
// any prior export, and after the Layer-3 install + dedup (or a reboot) the
|
|
171
|
+
// only surviving binary lives at /workspace/.local/bin.
|
|
172
|
+
const tunnelCheck = await execOneShot(workspaceId, '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"', username, 10000);
|
|
173
|
+
tunnelActive = String(tunnelCheck.stdout || '').includes('ACTIVE');
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
// a failed probe leaves tunnelActive false; the result then carries the incomplete-deployment warning
|
|
177
|
+
}
|
|
169
178
|
}
|
|
170
179
|
const warning = [
|
|
171
|
-
!tunnelActive
|
|
180
|
+
!isDevbox && !tunnelActive
|
|
172
181
|
? 'No active DevBridge tunnel — deployment is incomplete. Proceed to Step 7 to expose the app.'
|
|
173
182
|
: undefined,
|
|
183
|
+
isDevbox
|
|
184
|
+
? 'devbox 后端不使用 DevBridge 隧道:确认应用/nginx 绑定 0.0.0.0,然后调用 deploy_check 验证应用端口 URL。'
|
|
185
|
+
: undefined,
|
|
174
186
|
formatPortConflictWarning(basePort, targetPort),
|
|
175
|
-
tunnelActive ? formatPortDriftWarning(basePort, targetPort) : undefined,
|
|
187
|
+
!isDevbox && tunnelActive ? formatPortDriftWarning(basePort, targetPort) : undefined,
|
|
176
188
|
]
|
|
177
189
|
.filter(Boolean)
|
|
178
190
|
.join(' | ') || undefined;
|
|
@@ -186,6 +198,8 @@ fi`;
|
|
|
186
198
|
return {
|
|
187
199
|
ok: false,
|
|
188
200
|
error: verdict.error,
|
|
201
|
+
backend,
|
|
202
|
+
...(previewUrl ? { previewUrl } : {}),
|
|
189
203
|
nginxType,
|
|
190
204
|
port: targetPort,
|
|
191
205
|
nodePort: effectiveNodePort || undefined,
|
|
@@ -200,6 +214,8 @@ fi`;
|
|
|
200
214
|
}
|
|
201
215
|
return {
|
|
202
216
|
ok: true,
|
|
217
|
+
backend,
|
|
218
|
+
...(previewUrl ? { previewUrl } : {}),
|
|
203
219
|
nginxType,
|
|
204
220
|
port: targetPort,
|
|
205
221
|
nodePort: effectiveNodePort || undefined,
|
|
@@ -209,7 +225,7 @@ fi`;
|
|
|
209
225
|
verification: { configPath, nginxTest: verify.nginxTest },
|
|
210
226
|
exitCode: result.exitCode,
|
|
211
227
|
stdout: result.stdout,
|
|
212
|
-
nextStep: 'expose_via_devbridge',
|
|
228
|
+
nextStep: isDevbox ? 'deploy_check' : 'expose_via_devbridge',
|
|
213
229
|
warning,
|
|
214
230
|
};
|
|
215
231
|
}
|
|
@@ -0,0 +1,37 @@
|
|
|
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
|
+
const workspaceBackends = new Map();
|
|
6
|
+
export function sandboxBackend() {
|
|
7
|
+
const raw = process.env.HW_SANDBOX_BACKEND;
|
|
8
|
+
if (raw === undefined || raw === '' || raw === 'legacy')
|
|
9
|
+
return 'legacy';
|
|
10
|
+
if (raw === 'devbox')
|
|
11
|
+
return 'devbox';
|
|
12
|
+
throw new Error(`HW_SANDBOX_BACKEND must be "legacy" or "devbox" (got "${raw}"). ` +
|
|
13
|
+
'Unknown values fail fast at startup instead of silently routing sandbox traffic.');
|
|
14
|
+
}
|
|
15
|
+
export function isDevboxBackend() {
|
|
16
|
+
return sandboxBackend() === 'devbox';
|
|
17
|
+
}
|
|
18
|
+
export function rememberWorkspaceBackend(workspaceId, backend) {
|
|
19
|
+
if (!workspaceId)
|
|
20
|
+
return;
|
|
21
|
+
workspaceBackends.set(workspaceId, backend);
|
|
22
|
+
}
|
|
23
|
+
export function forgetWorkspaceBackend(workspaceId) {
|
|
24
|
+
workspaceBackends.delete(workspaceId);
|
|
25
|
+
}
|
|
26
|
+
/** Backend this workspace was connected on; falls back to the operator posture. */
|
|
27
|
+
export function backendForWorkspace(workspaceId) {
|
|
28
|
+
if (workspaceId) {
|
|
29
|
+
const pinned = workspaceBackends.get(workspaceId);
|
|
30
|
+
if (pinned)
|
|
31
|
+
return pinned;
|
|
32
|
+
}
|
|
33
|
+
return sandboxBackend();
|
|
34
|
+
}
|
|
35
|
+
export function _clearWorkspaceBackendsForTests() {
|
|
36
|
+
workspaceBackends.clear();
|
|
37
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
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
|
+
const connections = new Map();
|
|
6
|
+
function str(value) {
|
|
7
|
+
return typeof value === 'string' && value !== '' ? value : undefined;
|
|
8
|
+
}
|
|
9
|
+
/** Fold a hdkitservice devbox connect/refresh response into the cache. */
|
|
10
|
+
export function setDevboxConnectionFromResponse(workspaceId, result) {
|
|
11
|
+
const sandboxId = str(result.sandbox_id) || str(result.sandboxId) || str(result.session_id) || str(result.dev_stage_id);
|
|
12
|
+
if (!sandboxId) {
|
|
13
|
+
throw new Error('DevBox connect response did not include a sandbox id — refusing to cache a partial connection.');
|
|
14
|
+
}
|
|
15
|
+
const envdUrl = str(result.envd_url) || str(result.envdUrl);
|
|
16
|
+
const connectToken = str(result.connect_token) || str(result.connectToken);
|
|
17
|
+
if (!envdUrl || !connectToken) {
|
|
18
|
+
throw new Error('DevBox connect response did not include EnvD credentials — refusing to cache a partial connection.');
|
|
19
|
+
}
|
|
20
|
+
const existing = connections.get(workspaceId);
|
|
21
|
+
const record = {
|
|
22
|
+
workspaceId,
|
|
23
|
+
sandboxId,
|
|
24
|
+
state: str(result.state) || 'running',
|
|
25
|
+
templateId: str(result.template_id) || str(result.templateId) || existing?.templateId,
|
|
26
|
+
envdUrl,
|
|
27
|
+
tunnelId: str(result.tunnel_id) || str(result.tunnelId),
|
|
28
|
+
connectToken,
|
|
29
|
+
envdAccessToken: str(result.envd_access_token) || str(result.envdAccessToken),
|
|
30
|
+
envdVersion: str(result.envd_version) || str(result.envdVersion),
|
|
31
|
+
tokenExpiration: str(result.token_expiration) || str(result.tokenExpiration),
|
|
32
|
+
endAt: str(result.end_at) || str(result.endAt),
|
|
33
|
+
poolType: str(result.pool_type) || str(result.poolType) || 'ephemeral',
|
|
34
|
+
started: result.started === true,
|
|
35
|
+
pauseRetentionHours: typeof result.pause_retention_hours === 'number'
|
|
36
|
+
? result.pause_retention_hours
|
|
37
|
+
: typeof result.pauseRetentionHours === 'number'
|
|
38
|
+
? result.pauseRetentionHours
|
|
39
|
+
: existing?.pauseRetentionHours,
|
|
40
|
+
};
|
|
41
|
+
connections.set(workspaceId, record);
|
|
42
|
+
// The sandbox id is the workspace id on the devbox path; keep the alias hot
|
|
43
|
+
// so a caller holding either identifier resolves the same cache entry.
|
|
44
|
+
if (sandboxId !== workspaceId)
|
|
45
|
+
connections.set(sandboxId, record);
|
|
46
|
+
return record;
|
|
47
|
+
}
|
|
48
|
+
export function getDevboxConnection(workspaceId) {
|
|
49
|
+
if (!workspaceId)
|
|
50
|
+
return undefined;
|
|
51
|
+
return connections.get(workspaceId);
|
|
52
|
+
}
|
|
53
|
+
export function requireDevboxConnection(workspaceId) {
|
|
54
|
+
const connection = connections.get(workspaceId);
|
|
55
|
+
if (!connection) {
|
|
56
|
+
throw new Error(`No DevBox connection for workspace "${workspaceId}" in this process. ` +
|
|
57
|
+
'Call huaweicloud_sandbox_connect again with valid AK/SK — devbox tokens are memory-only and do not survive a restart.');
|
|
58
|
+
}
|
|
59
|
+
return connection;
|
|
60
|
+
}
|
|
61
|
+
export function clearDevboxConnection(workspaceId) {
|
|
62
|
+
if (!workspaceId)
|
|
63
|
+
return;
|
|
64
|
+
const connection = connections.get(workspaceId);
|
|
65
|
+
if (!connection)
|
|
66
|
+
return;
|
|
67
|
+
connections.delete(connection.workspaceId);
|
|
68
|
+
connections.delete(connection.sandboxId);
|
|
69
|
+
}
|
|
70
|
+
export function _clearDevboxConnectionsForTests() {
|
|
71
|
+
connections.clear();
|
|
72
|
+
}
|
|
73
|
+
const TOKEN_REFRESH_WINDOW_MS = 5 * 60 * 1000;
|
|
74
|
+
/** True when the EnvD token expires inside the refresh window (or is unparsable). */
|
|
75
|
+
export function devboxTokenNeedsRefresh(connection) {
|
|
76
|
+
if (!connection.tokenExpiration)
|
|
77
|
+
return false;
|
|
78
|
+
const raw = connection.tokenExpiration.trim();
|
|
79
|
+
const epochSeconds = Number(raw);
|
|
80
|
+
const expiresAt = Number.isFinite(epochSeconds) ? epochSeconds * 1000 : Date.parse(raw);
|
|
81
|
+
if (!Number.isFinite(expiresAt))
|
|
82
|
+
return true;
|
|
83
|
+
return expiresAt <= Date.now() + TOKEN_REFRESH_WINDOW_MS;
|
|
84
|
+
}
|