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.
Files changed (42) hide show
  1. package/package.json +1 -1
  2. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +3 -16
  3. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +3 -16
  4. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +3 -16
  5. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +3 -16
  6. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +3 -16
  7. package/plugins/huaweicloud-core/dist/explain-error.js +9 -1
  8. package/plugins/huaweicloud-core/dist/hcloud-plan.js +6 -1
  9. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +18 -9
  10. package/plugins/huaweicloud-core/dist/mcp-server.js +435 -282
  11. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  12. package/plugins/huaweicloud-core/dist/packs/registry.js +1 -0
  13. package/plugins/huaweicloud-core/dist/packs/sandbox/expose-task.js +71 -0
  14. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +25 -1
  15. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +28 -3
  16. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +14 -0
  17. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +11 -3
  18. package/plugins/huaweicloud-core/dist/risk-rule-engine.js +20 -4
  19. package/plugins/huaweicloud-core/dist/safety/classify-hcloud.js +6 -6
  20. package/plugins/huaweicloud-core/dist/safety/redact.js +21 -3
  21. package/plugins/huaweicloud-core/dist/safety/risk-merge.js +24 -4
  22. package/plugins/huaweicloud-core/dist/sandbox/devbridge-cleanup.js +1 -1
  23. package/plugins/huaweicloud-core/dist/tool-definitions.js +4 -0
  24. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +14 -1
  25. package/plugins/huaweicloud-core/openclaw.plugin.json +2 -2
  26. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +1 -1
  27. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +42 -39
  28. package/plugins/huaweicloud-core/src/explain-error.ts +9 -1
  29. package/plugins/huaweicloud-core/src/hcloud-plan.ts +6 -1
  30. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +32 -1
  31. package/plugins/huaweicloud-core/src/packs/registry.ts +1 -0
  32. package/plugins/huaweicloud-core/src/packs/sandbox/expose-task.ts +105 -0
  33. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +28 -1
  34. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +41 -15
  35. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +20 -0
  36. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +12 -2
  37. package/plugins/huaweicloud-core/src/risk-rule-engine.ts +20 -7
  38. package/plugins/huaweicloud-core/src/safety/classify-hcloud.ts +28 -16
  39. package/plugins/huaweicloud-core/src/safety/redact.ts +24 -6
  40. package/plugins/huaweicloud-core/src/safety/risk-merge.ts +26 -5
  41. package/plugins/huaweicloud-core/src/sandbox/devbridge-cleanup.ts +7 -5
  42. package/plugins/huaweicloud-core/src/tool-definitions.ts +4 -0
@@ -17,6 +17,7 @@ import {
17
17
  approvalTokenArg,
18
18
  approvedByUserArg,
19
19
  } from '../../lib/tool-schema-parts.ts';
20
+ import { EXPOSE_TASK_ID_PATTERN } from './expose-task.ts';
20
21
 
21
22
  // The sandbox pack's zod schema family, extracted from tools.ts in the
22
23
  // within-pack split for the jscpd complex-file bar. tools.ts stays the stable
@@ -229,6 +230,15 @@ export const exposeTunnelSchema = z.looseObject({
229
230
  .describe(
230
231
  "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).",
231
232
  ),
233
+ mode: z
234
+ .enum(['sync', 'async'])
235
+ .optional()
236
+ .describe(
237
+ 'sync (default): run the whole expose chain and return its result. async: start the chain in the background and return ' +
238
+ '{started:true, taskId, hint} immediately — use it on MCP hosts whose per-request timeout is shorter than the expose ' +
239
+ 'chain (auth + selective cleanup + up to four ~63s expose attempts + re-verify + keepalive enrollment), then poll ' +
240
+ 'huaweicloud_sandbox_expose_poll with taskId. The task receipt lives in this MCP server process (30 min).',
241
+ ),
232
242
  workspace_id: workspaceId,
233
243
  username,
234
244
  timeout_ms: numericArg
@@ -238,6 +248,16 @@ export const exposeTunnelSchema = z.looseObject({
238
248
  approvedByUser: approvedByUserArg,
239
249
  });
240
250
 
251
+ export const exposePollSchema = z.looseObject({
252
+ task_id: z
253
+ .string()
254
+ .regex(
255
+ EXPOSE_TASK_ID_PATTERN,
256
+ 'task_id must be the exp-<uuid> from huaweicloud_sandbox_expose_tunnel mode:"async".',
257
+ )
258
+ .describe('The taskId returned by huaweicloud_sandbox_expose_tunnel with mode:"async".'),
259
+ });
260
+
241
261
  export const renewTunnelSchema = z.looseObject({
242
262
  tunnel_id: z
243
263
  .string()
@@ -9,6 +9,7 @@ import {
9
9
  deployCheckSchema,
10
10
  checkUserSchema,
11
11
  exposeTunnelSchema,
12
+ exposePollSchema,
12
13
  renewTunnelSchema,
13
14
  keepaliveWatchdogSchema,
14
15
  signAgreementSchema,
@@ -20,7 +21,7 @@ import { handleExecWithSession, handleExecOneShot, handleCloseSession } from './
20
21
  import { handleHwexecPoll } from './handlers-hwexec.ts';
21
22
  import { handleUploadFile, handleUploadProject } from './handlers-upload.ts';
22
23
  import { handleDeployNginx, handleDeployCheck } from './handlers-deploy.ts';
23
- import { handleExposeTunnel, handleRenewTunnel, handleKeepaliveWatchdog } from './handlers-tunnel.ts';
24
+ import { handleExposeTunnel, handleExposePoll, handleRenewTunnel, handleKeepaliveWatchdog } from './handlers-tunnel.ts';
24
25
  import { handleCheckUser, handleSignAgreement, handleConnect, handleShutdown } from './handlers-account.ts';
25
26
  import { handleCredentials } from './handlers-credentials.ts';
26
27
  import type { PackToolDefinition, LooseToolSchema } from '../../lib/pack-types.ts';
@@ -108,6 +109,13 @@ export const SANDBOX_TOOLS = [
108
109
  schema: exposeTunnelSchema,
109
110
  handler: handleExposeTunnel,
110
111
  },
112
+ {
113
+ name: 'huaweicloud_sandbox_expose_poll',
114
+ description:
115
+ 'Poll an async expose task started by huaweicloud_sandbox_expose_tunnel with mode: "async". Returns state: running (the chain is still working — call again), done (result carries the full expose envelope: ok, publicUrl, port, tunnelId, expiresAt, urlLifetimeHint, keepalive, warnings), failed (an unexpected throw escaped the chain, with error), or unknown (no receipt in this MCP server process — it never started here, the session restarted, or the 30-minute receipt expired; the tunnel may already exist, so check huaweicloud_sandbox_deploy_check or re-expose — never assume success without a URL). The urlLifetimeHint MUST be relayed with the URL: the tunnel expiry is not the sandbox lifetime.',
116
+ schema: exposePollSchema,
117
+ handler: handleExposePoll,
118
+ },
111
119
  {
112
120
  name: 'huaweicloud_sandbox_renew_tunnel',
113
121
  description:
@@ -139,7 +147,7 @@ export const SANDBOX_TOOLS = [
139
147
  {
140
148
  name: 'huaweicloud_sandbox_connect',
141
149
  description:
142
- '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 are retried automatically (30s/45s backoff) — the server may already have created the instance, so a retry reuses it. 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.',
150
+ 'Connect to a sandbox via hdkitservice. One instance per user per pool — reuses the same-pool sandbox if available, otherwise creates a new one. Quota: 1 instance per pool type (a user may hold 1 ephemeral AND 1 persistent simultaneously; same-type requests reuse the existing instance). On quota exhaustion the API returns HTTP 429 with one of three codes: HDKIT_QUOTA_EXCEEDED (retry useless — release or reuse the existing instance; Retry-After 60), HDKIT_TEMPLATE_QUOTA_EXCEEDED (the running instances of this account for this sandbox type are at the limit — shut down or release an instance of the same type and retry; no Retry-After), or HDKIT_CAPACITY_INSUFFICIENT (pool capacity; retry later / off-peak; Retry-After 60). Gateway 502/504 timeouts during orchestration return a pending receipt (ok:false, pending:true, retryAfter, hint) instead of holding the call through the backoff — the server may already have created the instance; re-call this tool with the SAME parameters after retryAfter and a created instance is reused. An outdated plugin version is rejected by the 409 HDKIT_VERSION_TOO_OLD version gate, surfaced by the sandbox tools (connect/check_user/sign_agreement/credentials) as ok:false and by the voucher trio as claimed:false, always carrying code, message, and remediation naming the upgrade act (npx --yes huaweicloud-devkit@latest update --target <agent>, restart the agent session, or huaweicloud_upgrade), with clientVersion and minVersion present when the service sends them. Returns session_id, dev_stage_id, connection_id, connection_address, expiresAt (STS credential expiry), pool_type/resolved template_id echo, server-configured lifecycle numbers (pool_idle_shutdown_minutes / pool_idle_delete_minutes / pool_reclaim_minutes) and started (true when a reused instance was woken from shutdown). Lifecycle hints are announced only on the first connect of a session or when started=true. Ephemeral pool (default): idle auto-shutdown after 30min, auto-delete after 1h — do not keep important data there. Persistent pool: data disk retained (EVS 32G), idle shutdown after 1h, idle reclaim capped at 7 days. Numbers are configured by hdkitservice; the text follows the server echo and falls back to these defaults. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.',
143
151
  schema: connectSchema,
144
152
  handler: handleConnect,
145
153
  },
@@ -174,6 +182,7 @@ export const SANDBOX_TOOL_SCHEMAS: Readonly<Record<SandboxToolName, LooseToolSch
174
182
  huaweicloud_sandbox_deploy_nginx: deployNginxSchema,
175
183
  huaweicloud_sandbox_deploy_check: deployCheckSchema,
176
184
  huaweicloud_sandbox_expose_tunnel: exposeTunnelSchema,
185
+ huaweicloud_sandbox_expose_poll: exposePollSchema,
177
186
  huaweicloud_sandbox_renew_tunnel: renewTunnelSchema,
178
187
  huaweicloud_sandbox_keepalive_watchdog: keepaliveWatchdogSchema,
179
188
  huaweicloud_sandbox_check_user: checkUserSchema,
@@ -196,6 +205,7 @@ export const SANDBOX_TOOL_HANDLERS: Readonly<Record<SandboxToolName, PackToolDef
196
205
  huaweicloud_sandbox_deploy_nginx: handleDeployNginx,
197
206
  huaweicloud_sandbox_deploy_check: handleDeployCheck,
198
207
  huaweicloud_sandbox_expose_tunnel: handleExposeTunnel,
208
+ huaweicloud_sandbox_expose_poll: handleExposePoll,
199
209
  huaweicloud_sandbox_renew_tunnel: handleRenewTunnel,
200
210
  huaweicloud_sandbox_keepalive_watchdog: handleKeepaliveWatchdog,
201
211
  huaweicloud_sandbox_check_user: handleCheckUser,
@@ -4,6 +4,7 @@ import { fileURLToPath } from 'node:url';
4
4
 
5
5
  import { asText } from './lib/as-text.ts';
6
6
  import { asRecord } from './lib/as-record.ts';
7
+ import { redactEvidenceText } from './safety/redact.ts';
7
8
 
8
9
  const __dirname = dirname(fileURLToPath(import.meta.url));
9
10
  const defaultRulesPath = join(__dirname, '..', 'safety', 'rules', 'cloud-risk-rules.json');
@@ -134,12 +135,7 @@ export function loadRiskRules(options: RiskRuleOptions = {}): RiskCatalog {
134
135
  }
135
136
 
136
137
  function redactEvidence(text: unknown): string {
137
- return String(text)
138
- .replace(
139
- /((?: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,
140
- '$1<redacted>',
141
- )
142
- .replace(/\b(AK|SK)\\*["']?\s*[:=]\s*("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1=<redacted>');
138
+ return redactEvidenceText(text);
143
139
  }
144
140
 
145
141
  function normalizeText(value: unknown): string {
@@ -174,10 +170,27 @@ function evaluationContext(stage: string, input: unknown): EvaluationContext {
174
170
  return { text: normalizeText(input) };
175
171
  }
176
172
 
173
+ // Shell-transcribed commands and nested JSON artifacts arrive with escaped
174
+ // quotes (`\"Action\":` / `{\"privileged\":true}`) — the spelling a shell or
175
+ // an embedded JSON string actually produces. The catalog's JSON-shaped rules
176
+ // were authored against the unescaped spelling, so a backslash between the
177
+ // key and the quote made deny-severity rules (IAM administrator grants, OBS
178
+ // anonymous writes, privileged containers) silently miss. Matching therefore
179
+ // tests the raw value AND a quote-unescaped shadow; evidence/display keep the
180
+ // raw text. Only quote-adjacent backslashes are folded, so Windows paths are
181
+ // untouched.
182
+ function normalizeRuleText(text: string): string {
183
+ return text.replace(/\\+(["'])/g, '$1');
184
+ }
185
+
177
186
  function conditionMatches(condition: RiskRuleCondition, context: EvaluationContext): boolean {
178
187
  const field = condition.field || 'text';
179
188
  const value = Object.hasOwn(context, field) ? context[field] : context.text;
180
- return new RegExp(condition.regex, 'ims').test(String(value || ''));
189
+ const raw = String(value || '');
190
+ const regex = new RegExp(condition.regex, 'ims');
191
+ if (regex.test(raw)) return true;
192
+ const normalized = normalizeRuleText(raw);
193
+ return normalized !== raw && regex.test(normalized);
181
194
  }
182
195
 
183
196
  function ruleMatches(rule: RiskRule, context: EvaluationContext): boolean {
@@ -129,20 +129,28 @@ export function classifyHcloudArgs(args: unknown, options: ClassifyOptions = {})
129
129
  const isWrite = !readOnly && hasWritePrefix(operation, policy);
130
130
 
131
131
  if (isExecution && !options.allowWrites) {
132
- return {
133
- decision: 'deny',
134
- risk: 'execution',
135
- reason: 'Huawei Cloud execution/trigger operation blocked until approved.',
136
- };
132
+ return applyCommandRiskRules(
133
+ {
134
+ decision: 'deny',
135
+ risk: 'execution',
136
+ reason: 'Huawei Cloud execution/trigger operation blocked until approved.',
137
+ },
138
+ normalizedArgs,
139
+ options,
140
+ );
137
141
  }
138
142
 
139
143
  if (isWrite && !options.allowWrites) {
140
- return {
141
- decision: 'deny',
142
- risk: 'write',
143
- reason:
144
- 'Huawei Cloud write operation blocked until the agent presents a plan and receives explicit user approval.',
145
- };
144
+ return applyCommandRiskRules(
145
+ {
146
+ decision: 'deny',
147
+ risk: 'write',
148
+ reason:
149
+ 'Huawei Cloud write operation blocked until the agent presents a plan and receives explicit user approval.',
150
+ },
151
+ normalizedArgs,
152
+ options,
153
+ );
146
154
  }
147
155
 
148
156
  const obsutilWrites = OBSUTIL_WRITES;
@@ -154,11 +162,15 @@ export function classifyHcloudArgs(args: unknown, options: ClassifyOptions = {})
154
162
  const isObsWrite = isObs && obsutilWrites.has(operation.toLowerCase());
155
163
  const isObsRead = isObs && obsutilReads.includes(operation.toLowerCase());
156
164
  if (isObsWrite && !options.allowWrites) {
157
- return {
158
- decision: 'deny',
159
- risk: 'write',
160
- reason: 'OBS write operation blocked until the agent presents a plan and receives explicit user approval.',
161
- };
165
+ return applyCommandRiskRules(
166
+ {
167
+ decision: 'deny',
168
+ risk: 'write',
169
+ reason: 'OBS write operation blocked until the agent presents a plan and receives explicit user approval.',
170
+ },
171
+ normalizedArgs,
172
+ options,
173
+ );
162
174
  }
163
175
  if (isObsRead) {
164
176
  return applyCommandRiskRules(
@@ -6,7 +6,7 @@ function isSecretKeyName(key: unknown, policy: Policy = DEFAULT_POLICY): boolean
6
6
  .toLowerCase()
7
7
  .replace(/[^a-z0-9]/g, '');
8
8
  if (
9
- /access.*key|secret.*key|security.*token|xauth.*token|authorization|password|passwd|adminpass|credential|private.*key|userdata|metadata|inputvalue/.test(
9
+ /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(
10
10
  normalized,
11
11
  )
12
12
  ) {
@@ -15,6 +15,15 @@ function isSecretKeyName(key: unknown, policy: Policy = DEFAULT_POLICY): boolean
15
15
  return policy.secretKeyNamePatterns.some((pattern) => regexFrom(`^(${pattern})$`).test(String(key)));
16
16
  }
17
17
 
18
+ // The key vocabulary is shared by every evidence/command redaction face.
19
+ // Backslashes around the key/value are tolerated because shell-transcribed
20
+ // commands and nested JSON carry `\"password\":\"…\"` spellings; `secret://`
21
+ // refs are exempt (the ref is conversation-safe by doctrine). `secret_text`
22
+ // and `api_key` joined the family with the AX N-R4.1 fix — DEW's plaintext
23
+ // secret and the DevBridge key were crossing every evidence surface.
24
+ const SECRET_KEY_VALUE_RE =
25
+ /((?: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;
26
+
18
27
  function redactString(text: unknown): string {
19
28
  return (
20
29
  String(text)
@@ -32,14 +41,23 @@ function redactString(text: unknown): string {
32
41
  /(["']?(?:user[_-]?data|metadata|private[_-]?key|authorization|x[_-]?auth[_-]?token)["']?\s*[:=]\s*).*/gi,
33
42
  '$1<redacted>',
34
43
  )
35
- .replace(
36
- /(["']?(?:access[_-]?key(?:[_-]?(?:id|secret))?|secret[_-]?key|secret[_-]?string|secret[_-]?binary|security[_-]?token|token|password|passwd|admin[_-]?pass|credential|input[_-]?value)["']?\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi,
37
- '$1<redacted>',
38
- )
39
- .replace(/\b(["']?(?:AK|SK)["']?\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1<redacted>')
44
+ .replace(SECRET_KEY_VALUE_RE, '$1<redacted>')
45
+ // XML settings shapes (`<password>value</password>`, the settings.xml
46
+ // deploy idiom) carry no `:`/`=` separator, so the key-value family
47
+ // never saw them — the artifact evidence echoed the password verbatim
48
+ // (AX N-R4.1). The tag name is backreferenced so a mismatched close
49
+ // tag is not half-redacted.
50
+ .replace(/<(password|passwd|pwd)>[^<]*<\/\1>/gi, '<$1><redacted></$1>')
51
+ .replace(/\b(["']?(?:AK|SK)\\*["']?\s*[:=]\s*[\\"']*\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1<redacted>')
40
52
  );
41
53
  }
42
54
 
55
+ // The string-level evidence redaction entry (risk-rule-engine's excerpt and
56
+ // any future evidence face): one vocabulary, no second drift-prone copy.
57
+ export function redactEvidenceText(text: unknown): string {
58
+ return redactString(text);
59
+ }
60
+
43
61
  // Overload parameter names are documentation only; the implementation below
44
62
  // carries the real, used parameters.
45
63
  export function redactSecrets(value: string, policy?: Policy): string;
@@ -1,4 +1,4 @@
1
- import { evaluateCommandRisk, mergeRiskDecision, type RiskDecision } from '../risk-rule-engine.ts';
1
+ import { evaluateCommandRisk, mergeRiskDecision, type RiskDecision, type RiskEvaluation } from '../risk-rule-engine.ts';
2
2
  import type { ClassifyOptions } from './policy.ts';
3
3
 
4
4
  // The risk-rule merge seam for both classifiers: a non-deny base decision
@@ -10,22 +10,43 @@ function commandRiskText(normalizedArgs: string[], options: ClassifyOptions): st
10
10
  return options.rawCommand || ['hcloud', ...normalizedArgs].join(' ');
11
11
  }
12
12
 
13
+ // A deny-severity base (the generic write/execution gate) still carries the
14
+ // catalog's specialized findings: the approval decision the developer reads
15
+ // must show WHY the command is risky (broad administrator grant, anonymous
16
+ // write, high-cost shape), not only the generic "write must be approved".
17
+ // Only findings/warnings are attached — decision, risk, and reason stay the
18
+ // base's, so the PreToolUse hook's risk-shaped exemption logic does not
19
+ // drift.
20
+ function attachRiskFindings(base: RiskDecision, risk: RiskEvaluation): RiskDecision {
21
+ if (!risk.findings || risk.findings.length === 0) return base;
22
+ const warnFindings = risk.findings.filter((finding) => finding.severity !== 'deny');
23
+ return {
24
+ ...base,
25
+ findings: [...(base.findings || []), ...risk.findings],
26
+ ...(warnFindings.length > 0 ? { warnings: [...(base.warnings || []), ...warnFindings] } : {}),
27
+ };
28
+ }
29
+
30
+ function mergeRisk(base: RiskDecision, risk: RiskEvaluation): RiskDecision {
31
+ return base.decision === 'deny' ? attachRiskFindings(base, risk) : mergeRiskDecision(base, risk);
32
+ }
33
+
13
34
  export function applyCommandRiskRules(
14
35
  base: RiskDecision,
15
36
  normalizedArgs: string[],
16
37
  options: ClassifyOptions,
17
38
  ): RiskDecision {
18
- if (base.decision === 'deny' || options.skipRiskRules === true) {
39
+ if (options.skipRiskRules === true) {
19
40
  return base;
20
41
  }
21
42
  const risk = evaluateCommandRisk(commandRiskText(normalizedArgs, options));
22
- return mergeRiskDecision(base, risk);
43
+ return mergeRisk(base, risk);
23
44
  }
24
45
 
25
46
  export function applyRawCommandRiskRules(base: RiskDecision, command: string, options: ClassifyOptions): RiskDecision {
26
- if (base.decision === 'deny' || options.skipRiskRules === true) {
47
+ if (options.skipRiskRules === true) {
27
48
  return base;
28
49
  }
29
50
  const risk = evaluateCommandRisk(command);
30
- return mergeRiskDecision(base, risk);
51
+ return mergeRisk(base, risk);
31
52
  }
@@ -236,9 +236,7 @@ export function planDevbridgeCleanup({
236
236
  }
237
237
  }
238
238
 
239
- const killPids = new Set(
240
- hosts.filter((h) => (h.id || h.port != null) && !mappedPids.has(h.pid)).map((h) => h.pid),
241
- );
239
+ const killPids = new Set(hosts.filter((h) => (h.id || h.port != null) && !mappedPids.has(h.pid)).map((h) => h.pid));
242
240
  const samePortIds = samePort == null ? [] : tunnels.filter((t) => hasPort(t.id, samePort)).map((t) => t.id);
243
241
  const orphanIds = tunnels.filter((t) => !protectedIds.has(t.id) && !liveIds.has(t.id)).map((t) => t.id);
244
242
  const deleteSet = new Set([...orphanIds, ...samePortIds]);
@@ -275,7 +273,10 @@ export function planDevbridgeCleanup({
275
273
  return { deleteIds: [...deleteSet], killPids: [...killPids] };
276
274
  }
277
275
 
278
- export function buildDevbridgeCleanupApplyScript({ deleteIds = [], killPids = [] }: Partial<DevbridgeCleanupPlan> = {}): string {
276
+ export function buildDevbridgeCleanupApplyScript({
277
+ deleteIds = [],
278
+ killPids = [],
279
+ }: Partial<DevbridgeCleanupPlan> = {}): string {
279
280
  for (const id of deleteIds) {
280
281
  if (!DEVBRIDGE_TUNNEL_ID_PATTERN.test(String(id))) {
281
282
  throw new Error(`devbridge cleanup: invalid tunnel id ${JSON.stringify(id)}`);
@@ -294,7 +295,8 @@ export function buildDevbridgeCleanupApplyScript({ deleteIds = [], killPids = []
294
295
  // Re-check the process identity before killing: state→apply can take
295
296
  // minutes, so a recycled PID must not hit an unrelated process.
296
297
  ...killPids.map(
297
- (pid) => `if ps -p ${pid} -o args= 2>/dev/null | grep -q "devbridge host"; then kill ${pid} >/dev/null 2>&1 || true; fi`,
298
+ (pid) =>
299
+ `if ps -p ${pid} -o args= 2>/dev/null | grep -q "devbridge host"; then kill ${pid} >/dev/null 2>&1 || true; fi`,
298
300
  ),
299
301
  `sleep 1`,
300
302
  ...deleteIds.map((id) => `devbridge delete ${id} >/dev/null 2>&1 || true`),
@@ -186,6 +186,10 @@ export const TOOL_DEFINITIONS_LITERALS = [
186
186
  name: 'huaweicloud_sandbox_expose_tunnel',
187
187
  description: packDescription('huaweicloud_sandbox_expose_tunnel'),
188
188
  },
189
+ {
190
+ name: 'huaweicloud_sandbox_expose_poll',
191
+ description: packDescription('huaweicloud_sandbox_expose_poll'),
192
+ },
189
193
  {
190
194
  name: 'huaweicloud_sandbox_check_user',
191
195
  description: packDescription('huaweicloud_sandbox_check_user'),