huaweicloud-devkit 2.0.0-next.4 → 2.0.0-next.5
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/package.json +1 -1
- package/plugins/huaweicloud-core/.claude-plugin/plugin.json +3 -16
- package/plugins/huaweicloud-core/.codex-plugin/plugin.json +3 -16
- package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +3 -16
- package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +3 -16
- package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +3 -16
- package/plugins/huaweicloud-core/dist/explain-error.js +9 -1
- package/plugins/huaweicloud-core/dist/hcloud-plan.js +6 -1
- package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +18 -9
- package/plugins/huaweicloud-core/dist/mcp-server.js +435 -282
- 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/expose-task.js +71 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +25 -1
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +28 -3
- package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +14 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +11 -3
- package/plugins/huaweicloud-core/dist/risk-rule-engine.js +20 -4
- package/plugins/huaweicloud-core/dist/safety/classify-hcloud.js +6 -6
- package/plugins/huaweicloud-core/dist/safety/redact.js +21 -3
- package/plugins/huaweicloud-core/dist/safety/risk-merge.js +24 -4
- package/plugins/huaweicloud-core/dist/sandbox/devbridge-cleanup.js +1 -1
- package/plugins/huaweicloud-core/dist/tool-definitions.js +4 -0
- package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +14 -1
- package/plugins/huaweicloud-core/openclaw.plugin.json +2 -2
- package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +1 -1
- package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +42 -39
- package/plugins/huaweicloud-core/src/explain-error.ts +9 -1
- package/plugins/huaweicloud-core/src/hcloud-plan.ts +6 -1
- package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +32 -1
- package/plugins/huaweicloud-core/src/packs/registry.ts +1 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/expose-task.ts +105 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +28 -1
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +41 -15
- package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +20 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +12 -2
- package/plugins/huaweicloud-core/src/risk-rule-engine.ts +20 -7
- package/plugins/huaweicloud-core/src/safety/classify-hcloud.ts +28 -16
- package/plugins/huaweicloud-core/src/safety/redact.ts +24 -6
- package/plugins/huaweicloud-core/src/safety/risk-merge.ts +26 -5
- package/plugins/huaweicloud-core/src/sandbox/devbridge-cleanup.ts +7 -5
- package/plugins/huaweicloud-core/src/tool-definitions.ts +4 -0
|
@@ -69,6 +69,7 @@ export const PACK_OF = {
|
|
|
69
69
|
huaweicloud_sandbox_deploy_nginx: 'sandbox',
|
|
70
70
|
huaweicloud_sandbox_deploy_check: 'sandbox',
|
|
71
71
|
huaweicloud_sandbox_expose_tunnel: 'sandbox',
|
|
72
|
+
huaweicloud_sandbox_expose_poll: 'sandbox',
|
|
72
73
|
huaweicloud_sandbox_renew_tunnel: 'sandbox',
|
|
73
74
|
huaweicloud_sandbox_keepalive_watchdog: 'sandbox',
|
|
74
75
|
huaweicloud_sandbox_check_user: 'sandbox',
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
// The async expose-task registry (AX N-SB.1). An expose chain can outlive
|
|
3
|
+
// the host's MCP request timeout (auth gate + selective cleanups + up to
|
|
4
|
+
// four ~63s expose execs + the persistence re-verify + keepalive enrollment)
|
|
5
|
+
// while the server completes it — the synchronous tool then loses the
|
|
6
|
+
// publicUrl. An async start returns immediately and the poll tool delivers
|
|
7
|
+
// the finished result in-band.
|
|
8
|
+
//
|
|
9
|
+
// The registry is process-scoped (the stdio MCP server owns one). A restart
|
|
10
|
+
// loses the receipt while the tunnel may already live; the unknown hint
|
|
11
|
+
// therefore teaches recovery (re-expose / deploy_check) and never fabricates
|
|
12
|
+
// a URL. Entries are swept after the TTL so a long session cannot grow the
|
|
13
|
+
// map unbounded.
|
|
14
|
+
export const EXPOSE_TASK_ID_PATTERN = /^exp-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
15
|
+
const EXPOSE_TASK_TTL_MS = 30 * 60_000;
|
|
16
|
+
const tasks = new Map();
|
|
17
|
+
function sweep(now) {
|
|
18
|
+
for (const [taskId, task] of tasks) {
|
|
19
|
+
if (now - task.startedAt > EXPOSE_TASK_TTL_MS)
|
|
20
|
+
tasks.delete(taskId);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export function startExposeTask(workspaceId, port, run) {
|
|
24
|
+
const now = Date.now();
|
|
25
|
+
sweep(now);
|
|
26
|
+
const taskId = `exp-${randomUUID()}`;
|
|
27
|
+
const snapshot = { startedAt: now, workspaceId, port };
|
|
28
|
+
tasks.set(taskId, { ...snapshot, state: 'running' });
|
|
29
|
+
// The chain runs detached from the tool call: the client may time out or
|
|
30
|
+
// cancel the start request, but the server-side work (and the tunnel it
|
|
31
|
+
// creates) must continue. Both settle paths are recorded, so the promise
|
|
32
|
+
// is never an unhandled rejection.
|
|
33
|
+
void run().then((result) => {
|
|
34
|
+
tasks.set(taskId, { ...snapshot, state: 'done', result });
|
|
35
|
+
}, (error) => {
|
|
36
|
+
tasks.set(taskId, {
|
|
37
|
+
...snapshot,
|
|
38
|
+
state: 'failed',
|
|
39
|
+
error: error instanceof Error ? error.message : String(error),
|
|
40
|
+
});
|
|
41
|
+
});
|
|
42
|
+
return { taskId, startedAt: now };
|
|
43
|
+
}
|
|
44
|
+
export function pollExposeTask(taskId) {
|
|
45
|
+
const now = Date.now();
|
|
46
|
+
sweep(now);
|
|
47
|
+
const task = tasks.get(taskId);
|
|
48
|
+
if (!task) {
|
|
49
|
+
return {
|
|
50
|
+
state: 'unknown',
|
|
51
|
+
hint: 'No task with this id is known to this MCP server process (it never started here, the session restarted, or the ' +
|
|
52
|
+
'30-minute receipt expired). The tunnel may already exist: run huaweicloud_sandbox_deploy_check to read it, or ' +
|
|
53
|
+
're-run huaweicloud_sandbox_expose_tunnel (same port) — do not assume success without a URL.',
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
if (task.state === 'running') {
|
|
57
|
+
return {
|
|
58
|
+
state: 'running',
|
|
59
|
+
elapsedMs: now - task.startedAt,
|
|
60
|
+
hint: 'The expose chain is running in the background (auth, cleanup, host start, health check, keepalive). Call again.',
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
if (task.state === 'done') {
|
|
64
|
+
return { state: 'done', result: task.result };
|
|
65
|
+
}
|
|
66
|
+
return { state: 'failed', error: task.error };
|
|
67
|
+
}
|
|
68
|
+
// Test seam: isolate a process-global registry between cases.
|
|
69
|
+
export function _resetExposeTasksForTests() {
|
|
70
|
+
tasks.clear();
|
|
71
|
+
}
|
|
@@ -50,7 +50,12 @@ export async function handleConnect(args = {}, _opts = {}) {
|
|
|
50
50
|
}
|
|
51
51
|
let connectResult;
|
|
52
52
|
try {
|
|
53
|
-
|
|
53
|
+
// AX N-SB.2: the MCP tool answers inside the host's request budget — a
|
|
54
|
+
// transient gateway timeout returns a pending receipt instead of sleeping
|
|
55
|
+
// through the 30s/45s table (the next call re-attempts and reuses any
|
|
56
|
+
// instance the server already created). Short backoffs (tests/operators)
|
|
57
|
+
// keep the inline ladder.
|
|
58
|
+
connectResult = await hdkitConnectWithRetry(connectArgs, { maxInlineDelayMs: 1000 });
|
|
54
59
|
}
|
|
55
60
|
catch (error) {
|
|
56
61
|
// 业务预期失败(429 三码 / 烧核 / 凭证失效)转结构化返回,remediation 才能穿透 MCP 边界;
|
|
@@ -128,6 +133,25 @@ export async function handleConnect(args = {}, _opts = {}) {
|
|
|
128
133
|
}
|
|
129
134
|
throw error;
|
|
130
135
|
}
|
|
136
|
+
if (connectResult?.pending === true) {
|
|
137
|
+
const retryAfterMs = typeof connectResult.retryAfterMs === 'number' && Number.isFinite(connectResult.retryAfterMs)
|
|
138
|
+
? connectResult.retryAfterMs
|
|
139
|
+
: 30000;
|
|
140
|
+
const retryAfter = `${Math.max(1, Math.ceil(retryAfterMs / 1000))}s`;
|
|
141
|
+
return {
|
|
142
|
+
ok: false,
|
|
143
|
+
pending: true,
|
|
144
|
+
retryAfter,
|
|
145
|
+
retryAfterMs,
|
|
146
|
+
...(typeof connectResult.code === 'string' ? { code: connectResult.code } : {}),
|
|
147
|
+
message: typeof connectResult.message === 'string' && connectResult.message
|
|
148
|
+
? connectResult.message
|
|
149
|
+
: 'the hdkitservice gateway timed out during orchestration.',
|
|
150
|
+
hint: `The sandbox instance may already exist on the server. Re-call huaweicloud_sandbox_connect with the SAME ` +
|
|
151
|
+
`parameters after ~${retryAfter} — a created instance is reused. Do not start a second sandbox and do not ` +
|
|
152
|
+
`debug this as a credential failure.`,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
131
155
|
const rawDevStageId = connectResult?.dev_stage_id || connectResult?.devStageId;
|
|
132
156
|
const devStageId = typeof rawDevStageId === 'string' ? rawDevStageId : undefined;
|
|
133
157
|
let announceConnect = true;
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { exposeTunnel, renewTunnel, installKeepaliveWatchdog, validateTunnelId, } from "../../sandbox/devbridge-tunnel.js";
|
|
2
2
|
import { getCurrentWorkspaceId } from "../../sandbox/session-manager.js";
|
|
3
|
+
import { validateTunnelPort } from "../../sandbox/devbridge-validation.js";
|
|
3
4
|
import { poolContextFor } from "../../lib/hdkit/sandbox-pool.js";
|
|
5
|
+
import { startExposeTask, pollExposeTask } from "./expose-task.js";
|
|
4
6
|
import { buildKeyringInjectScript, ensureDevbridgeKey, listKeysForQuotaHint, recreateDevbridgeKey, } from "../../sandbox/devbridge-key.js";
|
|
5
7
|
import { SANDBOX_TIMEOUT_MS } from "./schemas.js";
|
|
6
8
|
// Tunnel handlers (expose/renew/keepalive-watchdog) for the sandbox pack,
|
|
@@ -18,8 +20,8 @@ export async function handleExposeTunnel(args = {}, _opts = {}) {
|
|
|
18
20
|
const sandboxUser9 = args.username || 'root';
|
|
19
21
|
const sandboxTimeout9 = args.timeout_ms || SANDBOX_TIMEOUT_MS.expose_tunnel;
|
|
20
22
|
const exposePoolContext = poolContextFor(sandboxWsId9);
|
|
21
|
-
|
|
22
|
-
port: args.port,
|
|
23
|
+
const exposeArgs = {
|
|
24
|
+
port: validateTunnelPort(args.port),
|
|
23
25
|
expiryHours: typeof args.expiry_hours === 'number' ? args.expiry_hours : undefined,
|
|
24
26
|
keepalive: typeof args.keepalive === 'boolean' ? args.keepalive : undefined,
|
|
25
27
|
cleanupMode: args.cleanup_mode,
|
|
@@ -27,7 +29,30 @@ export async function handleExposeTunnel(args = {}, _opts = {}) {
|
|
|
27
29
|
poolType: exposePoolContext?.poolMode || 'ephemeral',
|
|
28
30
|
poolContext: exposePoolContext,
|
|
29
31
|
keyUpgrade: { ensureDevbridgeKey, recreateDevbridgeKey, buildKeyringInjectScript, listKeysForQuotaHint },
|
|
30
|
-
}
|
|
32
|
+
};
|
|
33
|
+
// AX N-SB.1: the chain can outlive the host's request timeout while the
|
|
34
|
+
// server completes it — async starts it detached and the poll tool delivers
|
|
35
|
+
// the URL in-band. The fast parameter checks above stay synchronous, so a
|
|
36
|
+
// bad port is an immediate error, not a deferred task failure.
|
|
37
|
+
if (args.mode === 'async') {
|
|
38
|
+
const { taskId } = startExposeTask(sandboxWsId9, exposeArgs.port, () => exposeTunnel(sandboxWsId9, exposeArgs, sandboxUser9, sandboxTimeout9));
|
|
39
|
+
return {
|
|
40
|
+
started: true,
|
|
41
|
+
mode: 'async',
|
|
42
|
+
taskId,
|
|
43
|
+
hint: 'The expose chain is running in the background. Poll huaweicloud_sandbox_expose_poll with this taskId until ' +
|
|
44
|
+
'state is done — the publicUrl and urlLifetimeHint are delivered there (the task receipt lives 30 minutes in ' +
|
|
45
|
+
'this MCP server process).',
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
return await exposeTunnel(sandboxWsId9, exposeArgs, sandboxUser9, sandboxTimeout9);
|
|
49
|
+
}
|
|
50
|
+
export async function handleExposePoll(args = {}, _opts = {}) {
|
|
51
|
+
const taskId = args.task_id;
|
|
52
|
+
if (typeof taskId !== 'string' || taskId === '') {
|
|
53
|
+
throw new Error('task_id is required — pass the taskId returned by huaweicloud_sandbox_expose_tunnel mode:"async".');
|
|
54
|
+
}
|
|
55
|
+
return pollExposeTask(taskId);
|
|
31
56
|
}
|
|
32
57
|
export async function handleRenewTunnel(args = {}, _opts = {}) {
|
|
33
58
|
if (!args.tunnel_id) {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { HWEXEC_POLL_HEADROOM_MS, HWEXEC_TAIL_BYTES_DEFAULT, HWEXEC_TAIL_BYTES_MAX, HWEXEC_TASK_ID_PATTERN, HWEXEC_WAIT_MS_MAX, } from "../../sandbox/hwexec-task.js";
|
|
3
3
|
import { numericArg, looseObject, gitConfig, workspaceId, username, vendorConfirmed, approvalTokenArg, approvedByUserArg, } from "../../lib/tool-schema-parts.js";
|
|
4
|
+
import { EXPOSE_TASK_ID_PATTERN } from "./expose-task.js";
|
|
4
5
|
// The sandbox pack's zod schema family, extracted from tools.ts in the
|
|
5
6
|
// within-pack split for the jscpd complex-file bar. tools.ts stays the stable
|
|
6
7
|
// face: it imports every schema here for the SANDBOX_TOOLS /
|
|
@@ -169,6 +170,13 @@ export const exposeTunnelSchema = z.looseObject({
|
|
|
169
170
|
.enum(['stale', 'all', 'none'])
|
|
170
171
|
.optional()
|
|
171
172
|
.describe("Tunnel cleanup before exposing. stale (default): delete same-port tunnels + orphan records/hosts; preserve other ports, other sessions and keepalive-protected tunnels — except a tunnel bound to THIS port, which is always replaced. all: wipe every tunnel/host (manual full reset only — a shared sandbox loses every session's tunnels). none: no cleanup (a stale same-port host can then conflict)."),
|
|
173
|
+
mode: z
|
|
174
|
+
.enum(['sync', 'async'])
|
|
175
|
+
.optional()
|
|
176
|
+
.describe('sync (default): run the whole expose chain and return its result. async: start the chain in the background and return ' +
|
|
177
|
+
'{started:true, taskId, hint} immediately — use it on MCP hosts whose per-request timeout is shorter than the expose ' +
|
|
178
|
+
'chain (auth + selective cleanup + up to four ~63s expose attempts + re-verify + keepalive enrollment), then poll ' +
|
|
179
|
+
'huaweicloud_sandbox_expose_poll with taskId. The task receipt lives in this MCP server process (30 min).'),
|
|
172
180
|
workspace_id: workspaceId,
|
|
173
181
|
username,
|
|
174
182
|
timeout_ms: numericArg
|
|
@@ -177,6 +185,12 @@ export const exposeTunnelSchema = z.looseObject({
|
|
|
177
185
|
approvalToken: approvalTokenArg,
|
|
178
186
|
approvedByUser: approvedByUserArg,
|
|
179
187
|
});
|
|
188
|
+
export const exposePollSchema = z.looseObject({
|
|
189
|
+
task_id: z
|
|
190
|
+
.string()
|
|
191
|
+
.regex(EXPOSE_TASK_ID_PATTERN, 'task_id must be the exp-<uuid> from huaweicloud_sandbox_expose_tunnel mode:"async".')
|
|
192
|
+
.describe('The taskId returned by huaweicloud_sandbox_expose_tunnel with mode:"async".'),
|
|
193
|
+
});
|
|
180
194
|
export const renewTunnelSchema = z.looseObject({
|
|
181
195
|
tunnel_id: z
|
|
182
196
|
.string()
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { execWithSessionSchema, execOneShotSchema, execPollSchema, closeSessionSchema, uploadFileSchema, uploadProjectSchema, deployNginxSchema, deployCheckSchema, checkUserSchema, exposeTunnelSchema, 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, } 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
|
-
import { handleExposeTunnel, handleRenewTunnel, handleKeepaliveWatchdog } from "./handlers-tunnel.js";
|
|
6
|
+
import { handleExposeTunnel, handleExposePoll, handleRenewTunnel, handleKeepaliveWatchdog } from "./handlers-tunnel.js";
|
|
7
7
|
import { handleCheckUser, handleSignAgreement, handleConnect, handleShutdown } 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
|
|
@@ -78,6 +78,12 @@ export const SANDBOX_TOOLS = [
|
|
|
78
78
|
schema: exposeTunnelSchema,
|
|
79
79
|
handler: handleExposeTunnel,
|
|
80
80
|
},
|
|
81
|
+
{
|
|
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.',
|
|
84
|
+
schema: exposePollSchema,
|
|
85
|
+
handler: handleExposePoll,
|
|
86
|
+
},
|
|
81
87
|
{
|
|
82
88
|
name: 'huaweicloud_sandbox_renew_tunnel',
|
|
83
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.",
|
|
@@ -104,7 +110,7 @@ export const SANDBOX_TOOLS = [
|
|
|
104
110
|
},
|
|
105
111
|
{
|
|
106
112
|
name: 'huaweicloud_sandbox_connect',
|
|
107
|
-
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
|
|
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.',
|
|
108
114
|
schema: connectSchema,
|
|
109
115
|
handler: handleConnect,
|
|
110
116
|
},
|
|
@@ -134,6 +140,7 @@ export const SANDBOX_TOOL_SCHEMAS = {
|
|
|
134
140
|
huaweicloud_sandbox_deploy_nginx: deployNginxSchema,
|
|
135
141
|
huaweicloud_sandbox_deploy_check: deployCheckSchema,
|
|
136
142
|
huaweicloud_sandbox_expose_tunnel: exposeTunnelSchema,
|
|
143
|
+
huaweicloud_sandbox_expose_poll: exposePollSchema,
|
|
137
144
|
huaweicloud_sandbox_renew_tunnel: renewTunnelSchema,
|
|
138
145
|
huaweicloud_sandbox_keepalive_watchdog: keepaliveWatchdogSchema,
|
|
139
146
|
huaweicloud_sandbox_check_user: checkUserSchema,
|
|
@@ -155,6 +162,7 @@ export const SANDBOX_TOOL_HANDLERS = {
|
|
|
155
162
|
huaweicloud_sandbox_deploy_nginx: handleDeployNginx,
|
|
156
163
|
huaweicloud_sandbox_deploy_check: handleDeployCheck,
|
|
157
164
|
huaweicloud_sandbox_expose_tunnel: handleExposeTunnel,
|
|
165
|
+
huaweicloud_sandbox_expose_poll: handleExposePoll,
|
|
158
166
|
huaweicloud_sandbox_renew_tunnel: handleRenewTunnel,
|
|
159
167
|
huaweicloud_sandbox_keepalive_watchdog: handleKeepaliveWatchdog,
|
|
160
168
|
huaweicloud_sandbox_check_user: handleCheckUser,
|
|
@@ -3,6 +3,7 @@ import { dirname, join } from 'node:path';
|
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
4
|
import { asText } from "./lib/as-text.js";
|
|
5
5
|
import { asRecord } from "./lib/as-record.js";
|
|
6
|
+
import { redactEvidenceText } from "./safety/redact.js";
|
|
6
7
|
const __dirname = dirname(fileURLToPath(import.meta.url));
|
|
7
8
|
const defaultRulesPath = join(__dirname, '..', 'safety', 'rules', 'cloud-risk-rules.json');
|
|
8
9
|
const SEVERITY_RANK = {
|
|
@@ -58,9 +59,7 @@ export function loadRiskRules(options = {}) {
|
|
|
58
59
|
return toCatalog(JSON.parse(readFileSync(path, 'utf8')));
|
|
59
60
|
}
|
|
60
61
|
function redactEvidence(text) {
|
|
61
|
-
return
|
|
62
|
-
.replace(/((?:access[_-]?key(?:[_-]?(?:id|secret))?|secret[_-]?key|secret[_-]?string|secret[_-]?binary|secret(?!:\/)|security[_-]?token|x[_-]?auth[_-]?token|token|authorization|password|passwd|admin[_-]?pass|credential)\\*["']?\s*[:=]\s*[\\"'\\]*\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1<redacted>')
|
|
63
|
-
.replace(/\b(AK|SK)\\*["']?\s*[:=]\s*("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1=<redacted>');
|
|
62
|
+
return redactEvidenceText(text);
|
|
64
63
|
}
|
|
65
64
|
function normalizeText(value) {
|
|
66
65
|
if (typeof value === 'string')
|
|
@@ -84,10 +83,27 @@ function evaluationContext(stage, input) {
|
|
|
84
83
|
}
|
|
85
84
|
return { text: normalizeText(input) };
|
|
86
85
|
}
|
|
86
|
+
// Shell-transcribed commands and nested JSON artifacts arrive with escaped
|
|
87
|
+
// quotes (`\"Action\":` / `{\"privileged\":true}`) — the spelling a shell or
|
|
88
|
+
// an embedded JSON string actually produces. The catalog's JSON-shaped rules
|
|
89
|
+
// were authored against the unescaped spelling, so a backslash between the
|
|
90
|
+
// key and the quote made deny-severity rules (IAM administrator grants, OBS
|
|
91
|
+
// anonymous writes, privileged containers) silently miss. Matching therefore
|
|
92
|
+
// tests the raw value AND a quote-unescaped shadow; evidence/display keep the
|
|
93
|
+
// raw text. Only quote-adjacent backslashes are folded, so Windows paths are
|
|
94
|
+
// untouched.
|
|
95
|
+
function normalizeRuleText(text) {
|
|
96
|
+
return text.replace(/\\+(["'])/g, '$1');
|
|
97
|
+
}
|
|
87
98
|
function conditionMatches(condition, context) {
|
|
88
99
|
const field = condition.field || 'text';
|
|
89
100
|
const value = Object.hasOwn(context, field) ? context[field] : context.text;
|
|
90
|
-
|
|
101
|
+
const raw = String(value || '');
|
|
102
|
+
const regex = new RegExp(condition.regex, 'ims');
|
|
103
|
+
if (regex.test(raw))
|
|
104
|
+
return true;
|
|
105
|
+
const normalized = normalizeRuleText(raw);
|
|
106
|
+
return normalized !== raw && regex.test(normalized);
|
|
91
107
|
}
|
|
92
108
|
function ruleMatches(rule, context) {
|
|
93
109
|
const match = rule.match || {};
|
|
@@ -101,18 +101,18 @@ export function classifyHcloudArgs(args, options = {}) {
|
|
|
101
101
|
const isExecution = executionOps.test(operation) && !readOnly;
|
|
102
102
|
const isWrite = !readOnly && hasWritePrefix(operation, policy);
|
|
103
103
|
if (isExecution && !options.allowWrites) {
|
|
104
|
-
return {
|
|
104
|
+
return applyCommandRiskRules({
|
|
105
105
|
decision: 'deny',
|
|
106
106
|
risk: 'execution',
|
|
107
107
|
reason: 'Huawei Cloud execution/trigger operation blocked until approved.',
|
|
108
|
-
};
|
|
108
|
+
}, normalizedArgs, options);
|
|
109
109
|
}
|
|
110
110
|
if (isWrite && !options.allowWrites) {
|
|
111
|
-
return {
|
|
111
|
+
return applyCommandRiskRules({
|
|
112
112
|
decision: 'deny',
|
|
113
113
|
risk: 'write',
|
|
114
114
|
reason: 'Huawei Cloud write operation blocked until the agent presents a plan and receives explicit user approval.',
|
|
115
|
-
};
|
|
115
|
+
}, normalizedArgs, options);
|
|
116
116
|
}
|
|
117
117
|
const obsutilWrites = OBSUTIL_WRITES;
|
|
118
118
|
const obsutilReads = ['ls', 'stat', 'cat', 'help', 'version'];
|
|
@@ -123,11 +123,11 @@ export function classifyHcloudArgs(args, options = {}) {
|
|
|
123
123
|
const isObsWrite = isObs && obsutilWrites.has(operation.toLowerCase());
|
|
124
124
|
const isObsRead = isObs && obsutilReads.includes(operation.toLowerCase());
|
|
125
125
|
if (isObsWrite && !options.allowWrites) {
|
|
126
|
-
return {
|
|
126
|
+
return applyCommandRiskRules({
|
|
127
127
|
decision: 'deny',
|
|
128
128
|
risk: 'write',
|
|
129
129
|
reason: 'OBS write operation blocked until the agent presents a plan and receives explicit user approval.',
|
|
130
|
-
};
|
|
130
|
+
}, normalizedArgs, options);
|
|
131
131
|
}
|
|
132
132
|
if (isObsRead) {
|
|
133
133
|
return applyCommandRiskRules({
|
|
@@ -4,11 +4,18 @@ function isSecretKeyName(key, policy = DEFAULT_POLICY) {
|
|
|
4
4
|
const normalized = String(key)
|
|
5
5
|
.toLowerCase()
|
|
6
6
|
.replace(/[^a-z0-9]/g, '');
|
|
7
|
-
if (/access.*key|secret.*key|security.*token|xauth.*token|authorization|password|passwd|adminpass|credential|private.*key|userdata|metadata|inputvalue/.test(normalized)) {
|
|
7
|
+
if (/access.*key|secret.*key|secret.*string|secret.*binary|secret.*text|api.*key|security.*token|xauth.*token|authorization|password|passwd|adminpass|credential|private.*key|userdata|metadata|inputvalue/.test(normalized)) {
|
|
8
8
|
return true;
|
|
9
9
|
}
|
|
10
10
|
return policy.secretKeyNamePatterns.some((pattern) => regexFrom(`^(${pattern})$`).test(String(key)));
|
|
11
11
|
}
|
|
12
|
+
// The key vocabulary is shared by every evidence/command redaction face.
|
|
13
|
+
// Backslashes around the key/value are tolerated because shell-transcribed
|
|
14
|
+
// commands and nested JSON carry `\"password\":\"…\"` spellings; `secret://`
|
|
15
|
+
// refs are exempt (the ref is conversation-safe by doctrine). `secret_text`
|
|
16
|
+
// and `api_key` joined the family with the AX N-R4.1 fix — DEW's plaintext
|
|
17
|
+
// secret and the DevBridge key were crossing every evidence surface.
|
|
18
|
+
const SECRET_KEY_VALUE_RE = /((?:access[_-]?key(?:[_-]?(?:id|secret))?|secret[_-]?key|secret[_-]?string|secret[_-]?binary|secret[_-]?text|api[_-]?key|secret(?!:\/)|security[_-]?token|x[_-]?auth[_-]?token|token|authorization|password|passwd|admin[_-]?pass|credential|input[_-]?value)\\*["']?\s*[:=]\s*[\\"']*\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi;
|
|
12
19
|
function redactString(text) {
|
|
13
20
|
return (String(text)
|
|
14
21
|
// Opaque blob keys (cloud-init user_data, metadata, private_key) carry
|
|
@@ -22,8 +29,19 @@ function redactString(text) {
|
|
|
22
29
|
// credential itself, so this family consumes to end-of-line like the
|
|
23
30
|
// blob-key branch above.
|
|
24
31
|
.replace(/(["']?(?:user[_-]?data|metadata|private[_-]?key|authorization|x[_-]?auth[_-]?token)["']?\s*[:=]\s*).*/gi, '$1<redacted>')
|
|
25
|
-
.replace(
|
|
26
|
-
|
|
32
|
+
.replace(SECRET_KEY_VALUE_RE, '$1<redacted>')
|
|
33
|
+
// XML settings shapes (`<password>value</password>`, the settings.xml
|
|
34
|
+
// deploy idiom) carry no `:`/`=` separator, so the key-value family
|
|
35
|
+
// never saw them — the artifact evidence echoed the password verbatim
|
|
36
|
+
// (AX N-R4.1). The tag name is backreferenced so a mismatched close
|
|
37
|
+
// tag is not half-redacted.
|
|
38
|
+
.replace(/<(password|passwd|pwd)>[^<]*<\/\1>/gi, '<$1><redacted></$1>')
|
|
39
|
+
.replace(/\b(["']?(?:AK|SK)\\*["']?\s*[:=]\s*[\\"']*\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1<redacted>'));
|
|
40
|
+
}
|
|
41
|
+
// The string-level evidence redaction entry (risk-rule-engine's excerpt and
|
|
42
|
+
// any future evidence face): one vocabulary, no second drift-prone copy.
|
|
43
|
+
export function redactEvidenceText(text) {
|
|
44
|
+
return redactString(text);
|
|
27
45
|
}
|
|
28
46
|
export function redactSecrets(value, policy = DEFAULT_POLICY) {
|
|
29
47
|
if (Array.isArray(value)) {
|
|
@@ -6,17 +6,37 @@ import { evaluateCommandRisk, mergeRiskDecision } from "../risk-rule-engine.js";
|
|
|
6
6
|
function commandRiskText(normalizedArgs, options) {
|
|
7
7
|
return options.rawCommand || ['hcloud', ...normalizedArgs].join(' ');
|
|
8
8
|
}
|
|
9
|
+
// A deny-severity base (the generic write/execution gate) still carries the
|
|
10
|
+
// catalog's specialized findings: the approval decision the developer reads
|
|
11
|
+
// must show WHY the command is risky (broad administrator grant, anonymous
|
|
12
|
+
// write, high-cost shape), not only the generic "write must be approved".
|
|
13
|
+
// Only findings/warnings are attached — decision, risk, and reason stay the
|
|
14
|
+
// base's, so the PreToolUse hook's risk-shaped exemption logic does not
|
|
15
|
+
// drift.
|
|
16
|
+
function attachRiskFindings(base, risk) {
|
|
17
|
+
if (!risk.findings || risk.findings.length === 0)
|
|
18
|
+
return base;
|
|
19
|
+
const warnFindings = risk.findings.filter((finding) => finding.severity !== 'deny');
|
|
20
|
+
return {
|
|
21
|
+
...base,
|
|
22
|
+
findings: [...(base.findings || []), ...risk.findings],
|
|
23
|
+
...(warnFindings.length > 0 ? { warnings: [...(base.warnings || []), ...warnFindings] } : {}),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function mergeRisk(base, risk) {
|
|
27
|
+
return base.decision === 'deny' ? attachRiskFindings(base, risk) : mergeRiskDecision(base, risk);
|
|
28
|
+
}
|
|
9
29
|
export function applyCommandRiskRules(base, normalizedArgs, options) {
|
|
10
|
-
if (
|
|
30
|
+
if (options.skipRiskRules === true) {
|
|
11
31
|
return base;
|
|
12
32
|
}
|
|
13
33
|
const risk = evaluateCommandRisk(commandRiskText(normalizedArgs, options));
|
|
14
|
-
return
|
|
34
|
+
return mergeRisk(base, risk);
|
|
15
35
|
}
|
|
16
36
|
export function applyRawCommandRiskRules(base, command, options) {
|
|
17
|
-
if (
|
|
37
|
+
if (options.skipRiskRules === true) {
|
|
18
38
|
return base;
|
|
19
39
|
}
|
|
20
40
|
const risk = evaluateCommandRisk(command);
|
|
21
|
-
return
|
|
41
|
+
return mergeRisk(base, risk);
|
|
22
42
|
}
|
|
@@ -213,7 +213,7 @@ export function planDevbridgeCleanup({ tunnels = [], hosts = [], keepalive = [],
|
|
|
213
213
|
}
|
|
214
214
|
return { deleteIds: [...deleteSet], killPids: [...killPids] };
|
|
215
215
|
}
|
|
216
|
-
export function buildDevbridgeCleanupApplyScript({ deleteIds = [], killPids = [] } = {}) {
|
|
216
|
+
export function buildDevbridgeCleanupApplyScript({ deleteIds = [], killPids = [], } = {}) {
|
|
217
217
|
for (const id of deleteIds) {
|
|
218
218
|
if (!DEVBRIDGE_TUNNEL_ID_PATTERN.test(String(id))) {
|
|
219
219
|
throw new Error(`devbridge cleanup: invalid tunnel id ${JSON.stringify(id)}`);
|
|
@@ -180,6 +180,10 @@ export const TOOL_DEFINITIONS_LITERALS = [
|
|
|
180
180
|
name: 'huaweicloud_sandbox_expose_tunnel',
|
|
181
181
|
description: packDescription('huaweicloud_sandbox_expose_tunnel'),
|
|
182
182
|
},
|
|
183
|
+
{
|
|
184
|
+
name: 'huaweicloud_sandbox_expose_poll',
|
|
185
|
+
description: packDescription('huaweicloud_sandbox_expose_poll'),
|
|
186
|
+
},
|
|
183
187
|
{
|
|
184
188
|
name: 'huaweicloud_sandbox_check_user',
|
|
185
189
|
description: packDescription('huaweicloud_sandbox_check_user'),
|
|
@@ -478,8 +478,21 @@ def load_cloud_risk_rules():
|
|
|
478
478
|
return None
|
|
479
479
|
|
|
480
480
|
|
|
481
|
+
def normalize_rule_text(text):
|
|
482
|
+
# Twin of risk-rule-engine.normalizeRuleText: shell-transcribed commands
|
|
483
|
+
# and nested JSON carry \"key\": spellings the catalog's JSON-shaped
|
|
484
|
+
# rules were not authored against — a backslash between the key and the
|
|
485
|
+
# quote silently defeated the deny rules. Match the raw text AND its
|
|
486
|
+
# quote-unescaped shadow; the displayed reason keeps the raw command.
|
|
487
|
+
return re.sub(r'\\+(["\'])', r"\1", text)
|
|
488
|
+
|
|
489
|
+
|
|
481
490
|
def condition_matches(condition, text):
|
|
482
|
-
|
|
491
|
+
regex = re.compile(condition.get("regex", r"a^"), re.I | re.M | re.S)
|
|
492
|
+
if regex.search(text) is not None:
|
|
493
|
+
return True
|
|
494
|
+
normalized = normalize_rule_text(text)
|
|
495
|
+
return normalized != text and regex.search(normalized) is not None
|
|
483
496
|
|
|
484
497
|
|
|
485
498
|
def rule_matches(rule, text):
|
|
@@ -2,10 +2,10 @@
|
|
|
2
2
|
"name": "huaweicloud-devkit",
|
|
3
3
|
"id": "huaweicloud-devkit",
|
|
4
4
|
"displayName": "HuaweiCloud DevKit",
|
|
5
|
-
"version": "2.0.0-next.
|
|
5
|
+
"version": "2.0.0-next.5",
|
|
6
6
|
"family": "bundle-plugin",
|
|
7
7
|
"bundleFormat": "codex",
|
|
8
|
-
"description": "Guide coding agents to use Huawei Cloud safely
|
|
8
|
+
"description": "Guide coding agents to use Huawei Cloud safely �?KooCLI, APIs, SDKs, 40 MCP tools, skills, and safety guardrails.",
|
|
9
9
|
"author": {
|
|
10
10
|
"name": "HuaweiCloud Mate",
|
|
11
11
|
"url": "https://github.com/huaweicloud"
|
|
@@ -496,7 +496,7 @@
|
|
|
496
496
|
},
|
|
497
497
|
{
|
|
498
498
|
"field": "text",
|
|
499
|
-
"regex": "--(?:[A-Za-z0-9_.-]*[._-])?(?:admin(?:Pass|[_-]pass)|passwd|password|secret(?:[_-]?key
|
|
499
|
+
"regex": "--(?:[A-Za-z0-9_.-]*[._-])?(?:admin(?:Pass|[_-]pass)|passwd|password|secret[_-]?(?:key|text|string|binary)|secret|api[_-]?key|access[_-]?key|token|ak|sk)\\b\\s*[=:]\\s*[^\\s<][^\\s<>\"']"
|
|
500
500
|
}
|
|
501
501
|
]
|
|
502
502
|
},
|