huaweicloud-devkit 1.1.14-next.2 → 2.0.0-next.1

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 (706) hide show
  1. package/README.md +16 -17
  2. package/README.zh-CN.md +16 -17
  3. package/bin/dsh-postinstall.cjs +171 -31
  4. package/bin/setup.cjs +1 -1
  5. package/cordis.patch.yml +1 -1
  6. package/integrations/atomcode/hooks/huaweicloud-telemetry.js +29 -33
  7. package/integrations/dsh/hook-plugin.d.mts +19 -0
  8. package/integrations/dsh/hook-plugin.mjs +23 -22
  9. package/integrations/hermes/hooks/huaweicloud-telemetry.py +26 -43
  10. package/integrations/hermes/manifest.yaml +35 -10
  11. package/integrations/opencode/commands/huaweicloud-doctor.md +3 -2
  12. package/integrations/opencode/hooks/skill-tracker.js +70 -89
  13. package/integrations/opencode/opencode.json +5 -6
  14. package/integrations/workbuddy/hooks/telemetry-tracker.py +27 -45
  15. package/package.json +32 -11
  16. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +1 -2
  17. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +1 -2
  18. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +1 -2
  19. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +1 -2
  20. package/plugins/huaweicloud-core/.mcp.json +1 -1
  21. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +1 -2
  22. package/plugins/huaweicloud-core/dist/agents/atomcode.js +118 -0
  23. package/plugins/huaweicloud-core/dist/agents/codearts-work.js +121 -0
  24. package/plugins/huaweicloud-core/dist/agents/codearts.js +69 -0
  25. package/plugins/huaweicloud-core/dist/agents/codex-desktop.js +193 -0
  26. package/plugins/huaweicloud-core/dist/agents/codex.js +205 -0
  27. package/plugins/huaweicloud-core/dist/agents/dsh-patch.js +172 -0
  28. package/plugins/huaweicloud-core/dist/agents/dsh.js +129 -0
  29. package/plugins/huaweicloud-core/dist/agents/hermes-config.js +976 -0
  30. package/plugins/huaweicloud-core/dist/agents/hermes-hook-plugin.js +90 -0
  31. package/plugins/huaweicloud-core/dist/agents/hermes-hooks.js +166 -0
  32. package/plugins/huaweicloud-core/dist/agents/hermes-sdk.js +58 -0
  33. package/plugins/huaweicloud-core/dist/agents/hermes.js +150 -0
  34. package/plugins/huaweicloud-core/dist/agents/officeace-registry.js +179 -0
  35. package/plugins/huaweicloud-core/dist/agents/officeace-sqlite.js +142 -0
  36. package/plugins/huaweicloud-core/dist/agents/officeace.js +173 -0
  37. package/plugins/huaweicloud-core/dist/agents/openclaw.js +54 -0
  38. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +192 -0
  39. package/plugins/huaweicloud-core/dist/agents/opencode.js +112 -0
  40. package/plugins/huaweicloud-core/dist/agents/workbuddy.js +194 -0
  41. package/plugins/huaweicloud-core/dist/approvals-cli.js +159 -0
  42. package/plugins/huaweicloud-core/dist/auth/account-type.js +136 -0
  43. package/plugins/huaweicloud-core/dist/auth/agent-registration.js +243 -0
  44. package/plugins/huaweicloud-core/dist/auth/cli.js +114 -0
  45. package/plugins/huaweicloud-core/dist/auth/codearts-context.js +131 -0
  46. package/plugins/huaweicloud-core/dist/auth/credential-placeholder.js +41 -0
  47. package/plugins/huaweicloud-core/dist/auth/credential-resolver.js +74 -0
  48. package/plugins/huaweicloud-core/dist/auth/credential-validator.js +139 -0
  49. package/plugins/huaweicloud-core/dist/auth/credentials.js +20 -0
  50. package/plugins/huaweicloud-core/dist/auth/error-table.js +123 -0
  51. package/plugins/huaweicloud-core/dist/auth/hcloud-profile.js +89 -0
  52. package/plugins/huaweicloud-core/dist/auth/init-cli.js +139 -0
  53. package/plugins/huaweicloud-core/dist/auth/missing-credential-error.js +33 -0
  54. package/plugins/huaweicloud-core/dist/auth/obs-config.js +31 -0
  55. package/plugins/huaweicloud-core/dist/auth/project-id.js +90 -0
  56. package/plugins/huaweicloud-core/dist/auth/reconcile.js +256 -0
  57. package/plugins/huaweicloud-core/dist/auth/runtime-credentials.js +32 -0
  58. package/plugins/huaweicloud-core/dist/auth/s1-store.js +171 -0
  59. package/plugins/huaweicloud-core/dist/auth/service.js +397 -0
  60. package/plugins/huaweicloud-core/dist/auth/sts-expiry.js +58 -0
  61. package/plugins/huaweicloud-core/dist/capability-catalog.js +494 -0
  62. package/plugins/huaweicloud-core/dist/codearts-sandbox.js +32 -0
  63. package/plugins/huaweicloud-core/dist/codex-probe.js +77 -0
  64. package/plugins/huaweicloud-core/dist/data/icons-manifest.v1.json +3517 -0
  65. package/plugins/huaweicloud-core/dist/dep/installers/gateway.js +186 -0
  66. package/plugins/huaweicloud-core/dist/dep/installers/hcloud.js +370 -0
  67. package/plugins/huaweicloud-core/dist/dep/installers/table.js +28 -0
  68. package/plugins/huaweicloud-core/dist/dep/provision.js +247 -0
  69. package/plugins/huaweicloud-core/dist/dep/receipts.js +385 -0
  70. package/plugins/huaweicloud-core/dist/detect-framework-match.js +111 -0
  71. package/plugins/huaweicloud-core/dist/detect-framework-pkg.js +85 -0
  72. package/plugins/huaweicloud-core/dist/detect-framework-scan.js +93 -0
  73. package/plugins/huaweicloud-core/dist/detect-framework-table.js +153 -0
  74. package/plugins/huaweicloud-core/dist/detect-framework.js +7 -0
  75. package/plugins/huaweicloud-core/dist/doctor-native.js +167 -0
  76. package/plugins/huaweicloud-core/dist/doctor-payload.js +34 -0
  77. package/plugins/huaweicloud-core/dist/doctor-report.js +8 -0
  78. package/plugins/huaweicloud-core/dist/explain-error.js +209 -0
  79. package/plugins/huaweicloud-core/dist/hcloud-api-error.js +64 -0
  80. package/plugins/huaweicloud-core/dist/hcloud-catalog.js +91 -0
  81. package/plugins/huaweicloud-core/dist/hcloud-cli.js +24 -0
  82. package/plugins/huaweicloud-core/dist/hcloud-obs-redact.js +68 -0
  83. package/plugins/huaweicloud-core/dist/hcloud-plan.js +320 -0
  84. package/plugins/huaweicloud-core/dist/hcloud-probe.js +153 -0
  85. package/plugins/huaweicloud-core/dist/hcloud-run-once.js +245 -0
  86. package/plugins/huaweicloud-core/dist/hcloud-run.js +110 -0
  87. package/plugins/huaweicloud-core/dist/hcloud-sg-preflight.js +104 -0
  88. package/plugins/huaweicloud-core/dist/hcloud-sts.js +113 -0
  89. package/plugins/huaweicloud-core/dist/hcloud-triage.js +71 -0
  90. package/plugins/huaweicloud-core/dist/icon-library.js +216 -0
  91. package/plugins/huaweicloud-core/dist/install-payload.js +35 -0
  92. package/plugins/huaweicloud-core/dist/install-plan.js +85 -0
  93. package/plugins/huaweicloud-core/dist/install-prompts.js +119 -0
  94. package/plugins/huaweicloud-core/dist/koocli-version.js +83 -0
  95. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +353 -0
  96. package/plugins/huaweicloud-core/dist/lib/approvals-pin.js +128 -0
  97. package/plugins/huaweicloud-core/dist/lib/as-record.js +10 -0
  98. package/plugins/huaweicloud-core/dist/lib/as-text.js +15 -0
  99. package/plugins/huaweicloud-core/dist/lib/banner.js +10 -0
  100. package/plugins/huaweicloud-core/dist/lib/call-trace.js +128 -0
  101. package/plugins/huaweicloud-core/dist/lib/cli-io.js +72 -0
  102. package/plugins/huaweicloud-core/dist/lib/credentials.js +173 -0
  103. package/plugins/huaweicloud-core/dist/lib/dep-resolve.js +64 -0
  104. package/plugins/huaweicloud-core/dist/lib/dependency-model.js +152 -0
  105. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +217 -0
  106. package/plugins/huaweicloud-core/dist/lib/hdkit/hwlink-api.js +163 -0
  107. package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +303 -0
  108. package/plugins/huaweicloud-core/dist/lib/hw-request-signing.js +57 -0
  109. package/plugins/huaweicloud-core/dist/lib/koocli-paths.js +18 -0
  110. package/plugins/huaweicloud-core/dist/lib/native-receipt.js +110 -0
  111. package/plugins/huaweicloud-core/dist/lib/opencode-permission-seam.js +132 -0
  112. package/plugins/huaweicloud-core/dist/lib/pack-state.js +179 -0
  113. package/plugins/huaweicloud-core/dist/lib/pack-types.js +21 -0
  114. package/plugins/huaweicloud-core/dist/lib/secret-vault/cli.js +273 -0
  115. package/plugins/huaweicloud-core/dist/lib/secret-vault/custody.js +396 -0
  116. package/plugins/huaweicloud-core/dist/lib/secret-vault/refs.js +63 -0
  117. package/plugins/huaweicloud-core/dist/lib/secret-vault/store.js +236 -0
  118. package/plugins/huaweicloud-core/dist/lib/skill-frontmatter.js +158 -0
  119. package/plugins/huaweicloud-core/dist/lib/skill-manifest.js +55 -0
  120. package/plugins/huaweicloud-core/dist/lib/skill-tree.js +44 -0
  121. package/plugins/huaweicloud-core/dist/lib/tool-schema-parts.js +66 -0
  122. package/plugins/huaweicloud-core/dist/mcp-agent-config.js +80 -0
  123. package/plugins/huaweicloud-core/dist/mcp-config-backup.js +74 -0
  124. package/plugins/huaweicloud-core/dist/mcp-config-io.js +195 -0
  125. package/plugins/huaweicloud-core/dist/mcp-config-merge.js +188 -0
  126. package/plugins/huaweicloud-core/dist/mcp-protocol.js +320 -0
  127. package/plugins/huaweicloud-core/dist/mcp-server.js +62222 -0
  128. package/plugins/huaweicloud-core/dist/mcp-server.js.map +7 -0
  129. package/plugins/huaweicloud-core/dist/mcp-stdio-transport.js +206 -0
  130. package/plugins/huaweicloud-core/dist/officeace-paths.js +142 -0
  131. package/plugins/huaweicloud-core/dist/packs/auth/pack.js +11 -0
  132. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +276 -0
  133. package/plugins/huaweicloud-core/dist/packs/discovery/pack.js +11 -0
  134. package/plugins/huaweicloud-core/dist/packs/discovery/tools.js +78 -0
  135. package/plugins/huaweicloud-core/dist/packs/enable.js +81 -0
  136. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/pack.js +39 -0
  137. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +453 -0
  138. package/plugins/huaweicloud-core/dist/packs/huaweicloud-open-mcp/approval.js +222 -0
  139. package/plugins/huaweicloud-core/dist/packs/huaweicloud-open-mcp/pack.js +17 -0
  140. package/plugins/huaweicloud-core/dist/packs/huaweicloud-open-mcp/sidecar.js +486 -0
  141. package/plugins/huaweicloud-core/dist/packs/huaweicloud-open-mcp/tools.js +134 -0
  142. package/plugins/huaweicloud-core/dist/packs/obs/pack.js +11 -0
  143. package/plugins/huaweicloud-core/dist/packs/obs/tools.js +425 -0
  144. package/plugins/huaweicloud-core/dist/packs/registry.js +143 -0
  145. package/plugins/huaweicloud-core/dist/packs/sandbox/git-transfer.js +79 -0
  146. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +80 -0
  147. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +138 -0
  148. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-deploy.js +45 -0
  149. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +48 -0
  150. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +59 -0
  151. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-upload.js +34 -0
  152. package/plugins/huaweicloud-core/dist/packs/sandbox/pack.js +14 -0
  153. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +191 -0
  154. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +146 -0
  155. package/plugins/huaweicloud-core/dist/packs/secrets/pack.js +8 -0
  156. package/plugins/huaweicloud-core/dist/packs/secrets/tools.js +126 -0
  157. package/plugins/huaweicloud-core/dist/packs/update/pack.js +11 -0
  158. package/plugins/huaweicloud-core/dist/packs/update/tools.js +82 -0
  159. package/plugins/huaweicloud-core/dist/packs/voucher/pack.js +11 -0
  160. package/plugins/huaweicloud-core/dist/packs/voucher/tools.js +91 -0
  161. package/plugins/huaweicloud-core/dist/packs-cli/commands.js +108 -0
  162. package/plugins/huaweicloud-core/dist/packs-cli/doctor.js +81 -0
  163. package/plugins/huaweicloud-core/dist/packs-cli/report.js +133 -0
  164. package/plugins/huaweicloud-core/dist/packs-cli/slots.js +104 -0
  165. package/plugins/huaweicloud-core/dist/packs-cli/write-command.js +108 -0
  166. package/plugins/huaweicloud-core/dist/packs-cli/writers.js +115 -0
  167. package/plugins/huaweicloud-core/dist/packs-configure.js +81 -0
  168. package/plugins/huaweicloud-core/dist/packs-policy.js +149 -0
  169. package/plugins/huaweicloud-core/dist/payload-files.js +78 -0
  170. package/plugins/huaweicloud-core/dist/payload-native-clean.js +142 -0
  171. package/plugins/huaweicloud-core/dist/payload-native-sync.js +89 -0
  172. package/plugins/huaweicloud-core/dist/payload-placement.js +94 -0
  173. package/plugins/huaweicloud-core/dist/payload-roster.js +80 -0
  174. package/plugins/huaweicloud-core/dist/payload-runtime-deps.js +75 -0
  175. package/plugins/huaweicloud-core/dist/payload-status.js +43 -0
  176. package/plugins/huaweicloud-core/dist/payload-utils.js +42 -0
  177. package/plugins/huaweicloud-core/dist/preflight.js +232 -0
  178. package/plugins/huaweicloud-core/dist/proxy/cli.js +83 -0
  179. package/plugins/huaweicloud-core/dist/proxy/proxy-agent.js +92 -0
  180. package/plugins/huaweicloud-core/dist/proxy/proxy-bypass.js +83 -0
  181. package/plugins/huaweicloud-core/dist/proxy/proxy-cidr.js +105 -0
  182. package/plugins/huaweicloud-core/dist/proxy/proxy-config-io.js +61 -0
  183. package/plugins/huaweicloud-core/dist/proxy/proxy-config.js +10 -0
  184. package/plugins/huaweicloud-core/dist/risk-rule-engine.js +229 -0
  185. package/plugins/huaweicloud-core/dist/safety/classify-hcloud.js +191 -0
  186. package/plugins/huaweicloud-core/dist/safety/classify-text.js +1045 -0
  187. package/plugins/huaweicloud-core/dist/safety/command-operation.js +25 -0
  188. package/plugins/huaweicloud-core/dist/safety/credential-path.js +23 -0
  189. package/plugins/huaweicloud-core/dist/safety/default-policy.js +28 -0
  190. package/plugins/huaweicloud-core/dist/safety/feeder.js +119 -0
  191. package/plugins/huaweicloud-core/dist/safety/heredoc.js +95 -0
  192. package/plugins/huaweicloud-core/dist/safety/policy.js +76 -0
  193. package/plugins/huaweicloud-core/dist/safety/redact.js +42 -0
  194. package/plugins/huaweicloud-core/dist/safety/risk-merge.js +22 -0
  195. package/plugins/huaweicloud-core/dist/safety/script-stream.js +90 -0
  196. package/plugins/huaweicloud-core/dist/safety/secret-exec.js +44 -0
  197. package/plugins/huaweicloud-core/dist/safety/segments.js +138 -0
  198. package/plugins/huaweicloud-core/dist/safety/shell-text.js +414 -0
  199. package/plugins/huaweicloud-core/dist/safety/skill-quality-cli.js +152 -0
  200. package/plugins/huaweicloud-core/dist/safety/tokens.js +297 -0
  201. package/plugins/huaweicloud-core/dist/safety/unwrap.js +148 -0
  202. package/plugins/huaweicloud-core/dist/safety/vocabulary.js +37 -0
  203. package/plugins/huaweicloud-core/dist/safety/windows-rebase.js +56 -0
  204. package/plugins/huaweicloud-core/dist/safety/windows.js +137 -0
  205. package/plugins/huaweicloud-core/dist/safety/xargs-argv.js +64 -0
  206. package/plugins/huaweicloud-core/dist/safety-policy.js +14 -0
  207. package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +246 -0
  208. package/plugins/huaweicloud-core/dist/sandbox/deploy-nginx-verify.js +76 -0
  209. package/plugins/huaweicloud-core/dist/sandbox/deploy-nginx.js +215 -0
  210. package/plugins/huaweicloud-core/dist/sandbox/devbridge-auth.js +246 -0
  211. package/plugins/huaweicloud-core/dist/sandbox/devbridge-exec.js +10 -0
  212. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose-flow.js +225 -0
  213. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose.js +214 -0
  214. package/plugins/huaweicloud-core/dist/sandbox/devbridge-gateway.js +34 -0
  215. package/plugins/huaweicloud-core/dist/sandbox/devbridge-keepalive.js +212 -0
  216. package/plugins/huaweicloud-core/dist/sandbox/devbridge-key.js +175 -0
  217. package/plugins/huaweicloud-core/dist/sandbox/devbridge-renew.js +69 -0
  218. package/plugins/huaweicloud-core/dist/sandbox/devbridge-tunnel.js +48 -0
  219. package/plugins/huaweicloud-core/dist/sandbox/devbridge-validation.js +79 -0
  220. package/plugins/huaweicloud-core/dist/sandbox/devbridge-verify.js +101 -0
  221. package/plugins/huaweicloud-core/dist/sandbox/hwlink-connection.js +145 -0
  222. package/plugins/huaweicloud-core/dist/sandbox/sandbox-file-server.py +45 -0
  223. package/plugins/huaweicloud-core/dist/sandbox/sandbox-output.js +45 -0
  224. package/plugins/huaweicloud-core/dist/sandbox/session-manager.js +55 -0
  225. package/plugins/huaweicloud-core/dist/sandbox/tunnel-http.js +137 -0
  226. package/plugins/huaweicloud-core/dist/sandbox/uninstall-cleanup.js +45 -0
  227. package/plugins/huaweicloud-core/dist/sandbox/upload-diagnostics.js +45 -0
  228. package/plugins/huaweicloud-core/dist/sandbox/upload-file.js +119 -0
  229. package/plugins/huaweicloud-core/dist/sandbox/upload-project.js +171 -0
  230. package/plugins/huaweicloud-core/dist/sandbox/upload-transport.js +96 -0
  231. package/plugins/huaweicloud-core/dist/sandbox/ws-exec-loader.js +43 -0
  232. package/plugins/huaweicloud-core/dist/search-docs.js +64 -0
  233. package/plugins/huaweicloud-core/dist/search-market.js +277 -0
  234. package/plugins/huaweicloud-core/dist/services/availability.js +51 -0
  235. package/plugins/huaweicloud-core/dist/services/regions.js +110 -0
  236. package/plugins/huaweicloud-core/dist/setup-cli.js +1350 -0
  237. package/plugins/huaweicloud-core/dist/skill-disclosure.js +231 -0
  238. package/plugins/huaweicloud-core/dist/targets.js +139 -0
  239. package/plugins/huaweicloud-core/dist/telemetry/agent-detect.js +44 -0
  240. package/plugins/huaweicloud-core/dist/telemetry/agent-registry.js +196 -0
  241. package/plugins/huaweicloud-core/dist/telemetry/agent-versions-desktop.js +143 -0
  242. package/plugins/huaweicloud-core/dist/telemetry/agent-versions.js +78 -0
  243. package/plugins/huaweicloud-core/dist/telemetry/event-pipeline.js +206 -0
  244. package/plugins/huaweicloud-core/dist/telemetry/hook-ingest.js +81 -0
  245. package/plugins/huaweicloud-core/dist/telemetry/identity-stamps.js +104 -0
  246. package/plugins/huaweicloud-core/dist/telemetry/invoke-value.js +47 -0
  247. package/plugins/huaweicloud-core/dist/telemetry/telemetry-fs.js +42 -0
  248. package/plugins/huaweicloud-core/dist/telemetry/telemetry-types.js +14 -0
  249. package/plugins/huaweicloud-core/dist/telemetry/telemetry-values.js +121 -0
  250. package/plugins/huaweicloud-core/dist/telemetry/telemetry.js +262 -0
  251. package/plugins/huaweicloud-core/dist/tool-definitions.js +276 -0
  252. package/plugins/huaweicloud-core/dist/tool-schemas.js +156 -0
  253. package/plugins/huaweicloud-core/dist/tools.js +269 -0
  254. package/plugins/huaweicloud-core/dist/update-cache.js +79 -0
  255. package/plugins/huaweicloud-core/dist/update-check.js +23 -0
  256. package/plugins/huaweicloud-core/dist/update-hint.js +45 -0
  257. package/plugins/huaweicloud-core/dist/update-installed.js +53 -0
  258. package/plugins/huaweicloud-core/dist/update-registry.js +147 -0
  259. package/plugins/huaweicloud-core/dist/update-semver.js +76 -0
  260. package/plugins/huaweicloud-core/dist/update-skip.js +81 -0
  261. package/plugins/huaweicloud-core/dist/update-upgrade.js +101 -0
  262. package/plugins/huaweicloud-core/dist/vendor-gate.js +89 -0
  263. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-exec-client.js +10 -0
  264. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-exec-pending.js +71 -0
  265. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-exec-session.js +235 -0
  266. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-fair-queue.js +139 -0
  267. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-interactive-terminal.js +106 -0
  268. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-multiplexer.js +229 -0
  269. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-normalize.js +53 -0
  270. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-packet.js +148 -0
  271. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-terminal-channel.js +155 -0
  272. package/plugins/huaweicloud-core/dist/ws-exec/hwlink-tunnel-channel.js +254 -0
  273. package/plugins/huaweicloud-core/dist/ws-exec/index.js +20 -0
  274. package/plugins/huaweicloud-core/dist/ws-exec/ws-exec-client.js +76 -0
  275. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +62 -3
  276. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +2519 -33
  277. package/plugins/huaweicloud-core/openclaw.plugin.json +2 -2
  278. package/plugins/huaweicloud-core/safety/policy.json +53 -4
  279. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +47 -9
  280. package/plugins/huaweicloud-core/skills/.manifest.json +67 -0
  281. package/plugins/huaweicloud-core/skills/huawei-billing/SKILL.md +2 -0
  282. package/plugins/huaweicloud-core/skills/huawei-cbr/SKILL.md +2 -0
  283. package/plugins/huaweicloud-core/skills/huawei-cce/SKILL.md +3 -1
  284. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/SKILL.md +27 -51
  285. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/references/acceptance-criteria.md +10 -12
  286. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/references/cli-installation-guide.md +23 -27
  287. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/references/dataflow-diagram.md +2 -0
  288. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/references/iam-policies.md +2 -0
  289. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/references/verification-method.md +8 -16
  290. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/scripts/cli/cli_entry.py +71 -461
  291. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/scripts/ensure_cli.sh +28 -68
  292. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/SKILL.md +56 -144
  293. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/references/acceptance-criteria.md +14 -12
  294. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/references/cli-installation-guide.md +72 -39
  295. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/references/dataflow-diagram.md +3 -1
  296. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/references/iam-policies.md +2 -0
  297. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/references/verification-method.md +12 -0
  298. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/scripts/cli/cli_entry.py +67 -307
  299. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/scripts/ensure_cli.sh +28 -68
  300. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/templates/test-defaults.json +1 -1
  301. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/templates/test-vars.json +9 -9
  302. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/SKILL.md +82 -160
  303. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/references/acceptance-criteria.md +9 -8
  304. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/references/cli-installation-guide.md +73 -40
  305. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/references/dataflow-diagram.md +4 -2
  306. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/references/iam-policies.md +2 -0
  307. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/references/related-commands.md +16 -14
  308. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/references/verification-method.md +7 -20
  309. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/scripts/cli/cli_entry.py +67 -307
  310. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/scripts/ensure_cli.sh +28 -68
  311. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/SKILL.md +92 -95
  312. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/references/acceptance-criteria.md +11 -10
  313. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/references/cli-installation-guide.md +86 -67
  314. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/references/dataflow-diagram.md +4 -2
  315. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/references/iam-policies.md +2 -0
  316. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/references/test-data-guide.md +29 -25
  317. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/references/verification-method.md +13 -11
  318. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/scripts/cli/cli_entry.py +67 -307
  319. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/scripts/ensure_cli.sh +28 -68
  320. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/SKILL.md +107 -127
  321. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/references/acceptance-criteria.md +26 -25
  322. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/references/cli-installation-guide.md +66 -51
  323. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/references/csms-usage.md +23 -19
  324. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/references/dataflow-diagram.md +4 -2
  325. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/references/iam-policies.md +25 -30
  326. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/references/kms-usage.md +13 -11
  327. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/references/verification-method.md +13 -7
  328. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/scripts/cli/cli_entry.py +67 -354
  329. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/scripts/ensure_cli.sh +28 -69
  330. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/templates/test-vars.json +11 -11
  331. package/plugins/huaweicloud-core/skills/huawei-cloud-eye/SKILL.md +2 -0
  332. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/SKILL.md +28 -109
  333. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/references/acceptance-criteria.md +27 -31
  334. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/references/cli-installation-guide.md +49 -24
  335. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/references/dataflow-diagram.md +2 -5
  336. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/references/iam-policies.md +2 -0
  337. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/references/verification-method.md +8 -25
  338. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/scripts/cli/cli_entry.py +67 -307
  339. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/scripts/ensure_cli.sh +28 -68
  340. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/SKILL.md +60 -135
  341. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/references/acceptance-criteria.md +9 -11
  342. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/references/cli-installation-guide.md +16 -12
  343. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/references/dataflow-diagram.md +2 -0
  344. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/references/engine-operation-reference.md +15 -13
  345. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/references/iam-policies.md +9 -7
  346. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/references/security-audit-guide.md +9 -5
  347. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/references/verification-method.md +16 -37
  348. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/scripts/cli/cli_entry.py +101 -0
  349. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/scripts/ensure_cli.sh +27 -184
  350. package/plugins/huaweicloud-core/skills/huawei-cloud-waf-aad-rule-management/SKILL.md +71 -103
  351. package/plugins/huaweicloud-core/skills/huawei-cloud-waf-aad-rule-management/references/acceptance-criteria.md +4 -2
  352. package/plugins/huaweicloud-core/skills/huawei-cloud-waf-aad-rule-management/references/cli-installation-guide.md +72 -84
  353. package/plugins/huaweicloud-core/skills/huawei-cloud-waf-aad-rule-management/references/dataflow-diagram.md +3 -3
  354. package/plugins/huaweicloud-core/skills/huawei-cloud-waf-aad-rule-management/references/iam-policies.md +2 -0
  355. package/plugins/huaweicloud-core/skills/huawei-cloud-waf-aad-rule-management/references/related-commands.md +7 -5
  356. package/plugins/huaweicloud-core/skills/huawei-cloud-waf-aad-rule-management/references/verification-method.md +11 -9
  357. package/plugins/huaweicloud-core/skills/huawei-cloud-waf-aad-rule-management/scripts/cli/cli_entry.py +101 -0
  358. package/plugins/huaweicloud-core/skills/huawei-cloud-waf-aad-rule-management/scripts/ensure_cli.sh +27 -42
  359. package/plugins/huaweicloud-core/skills/huawei-ecs/SKILL.md +2 -0
  360. package/plugins/huaweicloud-core/skills/huawei-ecs/references/create-instance.md +24 -13
  361. package/plugins/huaweicloud-core/skills/huawei-ecs/references/evs.md +2 -0
  362. package/plugins/huaweicloud-core/skills/huawei-ecs/references/flavors.md +2 -0
  363. package/plugins/huaweicloud-core/skills/huawei-ecs/references/hc-activity.md +2 -0
  364. package/plugins/huaweicloud-core/skills/huawei-ecs/references/troubleshooting.md +25 -21
  365. package/plugins/huaweicloud-core/skills/huawei-ecs/references/windows-ssh.md +7 -5
  366. package/plugins/huaweicloud-core/skills/huawei-functiongraph/SKILL.md +2 -0
  367. package/plugins/huaweicloud-core/skills/huawei-functiongraph/references/apig-event-format.md +2 -0
  368. package/plugins/huaweicloud-core/skills/huawei-functiongraph/references/create-function.md +2 -0
  369. package/plugins/huaweicloud-core/skills/huawei-functiongraph/references/deploy-workflow.md +2 -0
  370. package/plugins/huaweicloud-core/skills/huawei-functiongraph/references/triggers.md +2 -0
  371. package/plugins/huaweicloud-core/skills/huawei-getting-started/SKILL.md +2 -0
  372. package/plugins/huaweicloud-core/skills/huawei-iac/SKILL.md +40 -38
  373. package/plugins/huaweicloud-core/skills/huawei-iac/references/architectures.md +2 -0
  374. package/plugins/huaweicloud-core/skills/huawei-iac/references/resource-catalog.md +14 -12
  375. package/plugins/huaweicloud-core/skills/huawei-iac/references/state-file.md +2 -0
  376. package/plugins/huaweicloud-core/skills/huawei-iam/SKILL.md +3 -1
  377. package/plugins/huaweicloud-core/skills/huawei-iam/references/policy-examples.md +2 -0
  378. package/plugins/huaweicloud-core/skills/huawei-iam/references/quick-ref.md +4 -1
  379. package/plugins/huaweicloud-core/skills/huawei-modelarts/SKILL.md +2 -0
  380. package/plugins/huaweicloud-core/skills/huawei-obs/SKILL.md +32 -29
  381. package/plugins/huaweicloud-core/skills/huawei-obs/references/bucket-create.md +2 -0
  382. package/plugins/huaweicloud-core/skills/huawei-obs/references/bucket-lifecycle.md +4 -2
  383. package/plugins/huaweicloud-core/skills/huawei-obs/references/common-pitfalls.md +17 -15
  384. package/plugins/huaweicloud-core/skills/huawei-obs/references/single-file-share.md +2 -0
  385. package/plugins/huaweicloud-core/skills/huawei-obs/references/static-website.md +10 -6
  386. package/plugins/huaweicloud-core/skills/huawei-openapi/SKILL.md +50 -0
  387. package/plugins/huaweicloud-core/skills/huawei-rds/SKILL.md +15 -13
  388. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +100 -93
  389. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/framework-commands.md +2 -0
  390. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/fullstack-postgrest.md +33 -27
  391. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/nginx-templates.md +2 -0
  392. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +7 -5
  393. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/tunnel-persistence.md +9 -2
  394. package/plugins/huaweicloud-core/skills/huawei-voucher/SKILL.md +5 -3
  395. package/plugins/huaweicloud-core/skills/huawei-vpc/SKILL.md +3 -0
  396. package/plugins/huaweicloud-core/skills/huawei-vpc/references/network.md +16 -0
  397. package/plugins/huaweicloud-core/skills/huawei-vpc/references/security-group.md +2 -0
  398. package/plugins/huaweicloud-core/skills/huawei-vpc/references/subnet.md +2 -0
  399. package/plugins/huaweicloud-core/skills/huaweicloud-api-and-sdk/SKILL.md +3 -0
  400. package/plugins/huaweicloud-core/skills/huaweicloud-capability-discovery/SKILL.md +16 -13
  401. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +10 -12
  402. package/plugins/huaweicloud-core/skills/huaweicloud-core/SKILL.md +38 -37
  403. package/plugins/huaweicloud-core/skills/huaweicloud-core/references/report-issue.md +2 -0
  404. package/plugins/huaweicloud-core/skills/huaweicloud-core/references/select.md +2 -0
  405. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +16 -6
  406. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +47 -0
  407. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/secrets.md +32 -0
  408. package/plugins/huaweicloud-core/skills/huaweicloud-troubleshooting/SKILL.md +2 -0
  409. package/plugins/huaweicloud-core/src/agents/atomcode.ts +138 -0
  410. package/plugins/huaweicloud-core/src/agents/codearts-work.ts +136 -0
  411. package/plugins/huaweicloud-core/src/agents/codearts.ts +92 -0
  412. package/plugins/huaweicloud-core/src/agents/codex-desktop.ts +219 -0
  413. package/plugins/huaweicloud-core/src/agents/codex.ts +230 -0
  414. package/plugins/huaweicloud-core/src/agents/dsh-patch.ts +195 -0
  415. package/plugins/huaweicloud-core/src/agents/dsh.ts +153 -0
  416. package/plugins/huaweicloud-core/src/agents/hermes-config.ts +974 -0
  417. package/plugins/huaweicloud-core/src/agents/hermes-hook-plugin.ts +99 -0
  418. package/plugins/huaweicloud-core/src/agents/hermes-hooks.ts +187 -0
  419. package/plugins/huaweicloud-core/src/agents/hermes-sdk.ts +63 -0
  420. package/plugins/huaweicloud-core/src/agents/hermes.ts +192 -0
  421. package/plugins/huaweicloud-core/src/agents/officeace-registry.ts +188 -0
  422. package/plugins/huaweicloud-core/src/agents/officeace-sqlite.ts +163 -0
  423. package/plugins/huaweicloud-core/src/agents/officeace.ts +202 -0
  424. package/plugins/huaweicloud-core/src/agents/openclaw.ts +73 -0
  425. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +197 -0
  426. package/plugins/huaweicloud-core/src/agents/opencode.ts +148 -0
  427. package/plugins/huaweicloud-core/src/agents/workbuddy.ts +216 -0
  428. package/plugins/huaweicloud-core/src/approvals-cli.ts +187 -0
  429. package/plugins/huaweicloud-core/src/auth/account-type.ts +191 -0
  430. package/plugins/huaweicloud-core/src/auth/agent-registration.ts +267 -0
  431. package/plugins/huaweicloud-core/src/auth/cli.ts +133 -0
  432. package/plugins/huaweicloud-core/src/auth/codearts-context.ts +139 -0
  433. package/plugins/huaweicloud-core/src/auth/credential-placeholder.ts +36 -0
  434. package/plugins/huaweicloud-core/src/auth/credential-resolver.ts +81 -0
  435. package/plugins/huaweicloud-core/src/auth/credential-validator.ts +176 -0
  436. package/plugins/huaweicloud-core/src/auth/credentials.ts +52 -0
  437. package/plugins/huaweicloud-core/src/auth/{guidance.mjs → error-table.ts} +58 -12
  438. package/plugins/huaweicloud-core/src/auth/hcloud-profile.ts +119 -0
  439. package/plugins/huaweicloud-core/src/auth/init-cli.ts +155 -0
  440. package/plugins/huaweicloud-core/src/auth/missing-credential-error.ts +44 -0
  441. package/plugins/huaweicloud-core/src/auth/obs-config.ts +42 -0
  442. package/plugins/huaweicloud-core/src/auth/project-id.ts +104 -0
  443. package/plugins/huaweicloud-core/src/auth/reconcile.ts +345 -0
  444. package/plugins/huaweicloud-core/src/auth/runtime-credentials.ts +38 -0
  445. package/plugins/huaweicloud-core/src/auth/s1-store.ts +214 -0
  446. package/plugins/huaweicloud-core/src/auth/{service.mjs → service.ts} +210 -36
  447. package/plugins/huaweicloud-core/src/auth/sts-expiry.ts +58 -0
  448. package/plugins/huaweicloud-core/src/capability-catalog.ts +519 -0
  449. package/plugins/huaweicloud-core/src/codearts-sandbox.ts +32 -0
  450. package/plugins/huaweicloud-core/src/codex-probe.ts +86 -0
  451. package/plugins/huaweicloud-core/src/data/icons-manifest.v1.json +5 -23
  452. package/plugins/huaweicloud-core/src/dep/installers/gateway.ts +213 -0
  453. package/plugins/huaweicloud-core/src/dep/installers/hcloud.ts +407 -0
  454. package/plugins/huaweicloud-core/src/dep/installers/table.ts +123 -0
  455. package/plugins/huaweicloud-core/src/dep/provision.ts +335 -0
  456. package/plugins/huaweicloud-core/src/dep/receipts.ts +464 -0
  457. package/plugins/huaweicloud-core/src/detect-framework-match.ts +143 -0
  458. package/plugins/huaweicloud-core/src/detect-framework-pkg.ts +79 -0
  459. package/plugins/huaweicloud-core/src/detect-framework-scan.ts +117 -0
  460. package/plugins/huaweicloud-core/src/detect-framework-table.ts +166 -0
  461. package/plugins/huaweicloud-core/src/detect-framework.ts +8 -0
  462. package/plugins/huaweicloud-core/src/doctor-native.ts +189 -0
  463. package/plugins/huaweicloud-core/src/doctor-payload.ts +77 -0
  464. package/plugins/huaweicloud-core/src/doctor-report.ts +30 -0
  465. package/plugins/huaweicloud-core/src/explain-error.ts +246 -0
  466. package/plugins/huaweicloud-core/src/hcloud-api-error.ts +69 -0
  467. package/plugins/huaweicloud-core/src/hcloud-catalog.ts +115 -0
  468. package/plugins/huaweicloud-core/src/hcloud-cli.ts +41 -0
  469. package/plugins/huaweicloud-core/src/hcloud-obs-redact.ts +65 -0
  470. package/plugins/huaweicloud-core/src/hcloud-plan.ts +383 -0
  471. package/plugins/huaweicloud-core/src/{hcloud-probe.mjs → hcloud-probe.ts} +87 -60
  472. package/plugins/huaweicloud-core/src/hcloud-run-once.ts +251 -0
  473. package/plugins/huaweicloud-core/src/hcloud-run.ts +154 -0
  474. package/plugins/huaweicloud-core/src/hcloud-sg-preflight.ts +111 -0
  475. package/plugins/huaweicloud-core/src/hcloud-sts.ts +123 -0
  476. package/plugins/huaweicloud-core/src/hcloud-triage.ts +80 -0
  477. package/plugins/huaweicloud-core/src/{icon-library.mjs → icon-library.ts} +115 -23
  478. package/plugins/huaweicloud-core/src/install-payload.ts +63 -0
  479. package/plugins/huaweicloud-core/src/install-plan.ts +85 -0
  480. package/plugins/huaweicloud-core/src/install-prompts.ts +134 -0
  481. package/plugins/huaweicloud-core/src/koocli-version.ts +87 -0
  482. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +496 -0
  483. package/plugins/huaweicloud-core/src/lib/approvals-pin.ts +153 -0
  484. package/plugins/huaweicloud-core/src/lib/as-record.ts +10 -0
  485. package/plugins/huaweicloud-core/src/lib/as-text.ts +16 -0
  486. package/plugins/huaweicloud-core/src/lib/banner.ts +12 -0
  487. package/plugins/huaweicloud-core/src/lib/call-trace.ts +153 -0
  488. package/plugins/huaweicloud-core/src/lib/cli-io.ts +81 -0
  489. package/plugins/huaweicloud-core/src/lib/credentials.ts +202 -0
  490. package/plugins/huaweicloud-core/src/lib/dep-resolve.ts +107 -0
  491. package/plugins/huaweicloud-core/src/lib/dependency-model.ts +236 -0
  492. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +255 -0
  493. package/plugins/huaweicloud-core/src/lib/hdkit/hwlink-api.ts +245 -0
  494. package/plugins/huaweicloud-core/src/{sandbox/sandbox-pool.mjs → lib/hdkit/sandbox-pool.ts} +126 -47
  495. package/plugins/huaweicloud-core/src/lib/hw-request-signing.ts +101 -0
  496. package/plugins/huaweicloud-core/src/lib/koocli-paths.ts +21 -0
  497. package/plugins/huaweicloud-core/src/lib/native-receipt.ts +131 -0
  498. package/plugins/huaweicloud-core/src/lib/opencode-permission-seam.ts +145 -0
  499. package/plugins/huaweicloud-core/src/lib/pack-state.ts +192 -0
  500. package/plugins/huaweicloud-core/src/lib/pack-types.ts +74 -0
  501. package/plugins/huaweicloud-core/src/lib/secret-vault/cli.ts +270 -0
  502. package/plugins/huaweicloud-core/src/lib/secret-vault/custody.ts +468 -0
  503. package/plugins/huaweicloud-core/src/lib/secret-vault/refs.ts +75 -0
  504. package/plugins/huaweicloud-core/src/lib/secret-vault/store.ts +357 -0
  505. package/plugins/huaweicloud-core/src/lib/skill-frontmatter.ts +164 -0
  506. package/plugins/huaweicloud-core/src/lib/skill-manifest.ts +55 -0
  507. package/plugins/huaweicloud-core/src/lib/skill-tree.ts +45 -0
  508. package/plugins/huaweicloud-core/src/lib/tool-schema-parts.ts +80 -0
  509. package/plugins/huaweicloud-core/src/mcp-agent-config.ts +90 -0
  510. package/plugins/huaweicloud-core/src/{mcp-config-backup.mjs → mcp-config-backup.ts} +14 -10
  511. package/plugins/huaweicloud-core/src/mcp-config-io.ts +215 -0
  512. package/plugins/huaweicloud-core/src/mcp-config-merge.ts +205 -0
  513. package/plugins/huaweicloud-core/src/mcp-protocol.ts +385 -0
  514. package/plugins/huaweicloud-core/src/mcp-server-remote.ts +178 -0
  515. package/plugins/huaweicloud-core/src/mcp-server.ts +87 -0
  516. package/plugins/huaweicloud-core/src/mcp-stdio-transport.ts +245 -0
  517. package/plugins/huaweicloud-core/src/officeace-paths.ts +146 -0
  518. package/plugins/huaweicloud-core/src/packs/auth/pack.ts +14 -0
  519. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +327 -0
  520. package/plugins/huaweicloud-core/src/packs/discovery/pack.ts +14 -0
  521. package/plugins/huaweicloud-core/src/packs/discovery/tools.ts +97 -0
  522. package/plugins/huaweicloud-core/src/packs/enable.ts +90 -0
  523. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/pack.ts +42 -0
  524. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +513 -0
  525. package/plugins/huaweicloud-core/src/packs/huaweicloud-open-mcp/approval.ts +250 -0
  526. package/plugins/huaweicloud-core/src/packs/huaweicloud-open-mcp/pack.ts +19 -0
  527. package/plugins/huaweicloud-core/src/packs/huaweicloud-open-mcp/sidecar.ts +603 -0
  528. package/plugins/huaweicloud-core/src/packs/huaweicloud-open-mcp/tools.ts +155 -0
  529. package/plugins/huaweicloud-core/src/packs/obs/pack.ts +13 -0
  530. package/plugins/huaweicloud-core/src/packs/obs/tools.ts +487 -0
  531. package/plugins/huaweicloud-core/src/packs/registry.ts +162 -0
  532. package/plugins/huaweicloud-core/src/packs/sandbox/git-transfer.ts +93 -0
  533. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +93 -0
  534. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +144 -0
  535. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-deploy.ts +63 -0
  536. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +59 -0
  537. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +101 -0
  538. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-upload.ts +46 -0
  539. package/plugins/huaweicloud-core/src/packs/sandbox/pack.ts +16 -0
  540. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +249 -0
  541. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +183 -0
  542. package/plugins/huaweicloud-core/src/packs/secrets/pack.ts +11 -0
  543. package/plugins/huaweicloud-core/src/packs/secrets/tools.ts +146 -0
  544. package/plugins/huaweicloud-core/src/packs/update/pack.ts +13 -0
  545. package/plugins/huaweicloud-core/src/packs/update/tools.ts +107 -0
  546. package/plugins/huaweicloud-core/src/packs/voucher/pack.ts +13 -0
  547. package/plugins/huaweicloud-core/src/packs/voucher/tools.ts +112 -0
  548. package/plugins/huaweicloud-core/src/packs-cli/commands.ts +121 -0
  549. package/plugins/huaweicloud-core/src/packs-cli/doctor.ts +85 -0
  550. package/plugins/huaweicloud-core/src/packs-cli/report.ts +171 -0
  551. package/plugins/huaweicloud-core/src/packs-cli/slots.ts +139 -0
  552. package/plugins/huaweicloud-core/src/packs-cli/write-command.ts +114 -0
  553. package/plugins/huaweicloud-core/src/packs-cli/writers.ts +125 -0
  554. package/plugins/huaweicloud-core/src/packs-configure.ts +104 -0
  555. package/plugins/huaweicloud-core/src/packs-policy.ts +203 -0
  556. package/plugins/huaweicloud-core/src/payload-files.ts +78 -0
  557. package/plugins/huaweicloud-core/src/payload-native-clean.ts +154 -0
  558. package/plugins/huaweicloud-core/src/payload-native-sync.ts +110 -0
  559. package/plugins/huaweicloud-core/src/payload-placement.ts +107 -0
  560. package/plugins/huaweicloud-core/src/payload-roster.ts +85 -0
  561. package/plugins/huaweicloud-core/src/payload-runtime-deps.ts +76 -0
  562. package/plugins/huaweicloud-core/src/payload-status.ts +53 -0
  563. package/plugins/huaweicloud-core/src/payload-utils.ts +51 -0
  564. package/plugins/huaweicloud-core/src/preflight.ts +250 -0
  565. package/plugins/huaweicloud-core/src/proxy/cli.ts +103 -0
  566. package/plugins/huaweicloud-core/src/proxy/{proxy-agent.mjs → proxy-agent.ts} +25 -16
  567. package/plugins/huaweicloud-core/src/proxy/proxy-bypass.ts +90 -0
  568. package/plugins/huaweicloud-core/src/proxy/proxy-cidr.ts +98 -0
  569. package/plugins/huaweicloud-core/src/proxy/proxy-config-io.ts +73 -0
  570. package/plugins/huaweicloud-core/src/proxy/proxy-config.ts +18 -0
  571. package/plugins/huaweicloud-core/src/risk-rule-engine.ts +325 -0
  572. package/plugins/huaweicloud-core/src/safety/classify-hcloud.ts +246 -0
  573. package/plugins/huaweicloud-core/src/safety/classify-text.ts +1114 -0
  574. package/plugins/huaweicloud-core/src/safety/command-operation.ts +28 -0
  575. package/plugins/huaweicloud-core/src/safety/credential-path.ts +25 -0
  576. package/plugins/huaweicloud-core/src/safety/default-policy.ts +34 -0
  577. package/plugins/huaweicloud-core/src/safety/feeder.ts +140 -0
  578. package/plugins/huaweicloud-core/src/safety/heredoc.ts +100 -0
  579. package/plugins/huaweicloud-core/src/safety/policy.ts +111 -0
  580. package/plugins/huaweicloud-core/src/safety/redact.ts +63 -0
  581. package/plugins/huaweicloud-core/src/safety/risk-merge.ts +31 -0
  582. package/plugins/huaweicloud-core/src/safety/script-stream.ts +95 -0
  583. package/plugins/huaweicloud-core/src/safety/secret-exec.ts +42 -0
  584. package/plugins/huaweicloud-core/src/safety/segments.ts +153 -0
  585. package/plugins/huaweicloud-core/src/safety/shell-text.ts +415 -0
  586. package/plugins/huaweicloud-core/src/safety/skill-quality-cli.ts +141 -0
  587. package/plugins/huaweicloud-core/src/safety/tokens.ts +322 -0
  588. package/plugins/huaweicloud-core/src/safety/unwrap.ts +162 -0
  589. package/plugins/huaweicloud-core/src/safety/vocabulary.ts +38 -0
  590. package/plugins/huaweicloud-core/src/safety/windows-rebase.ts +56 -0
  591. package/plugins/huaweicloud-core/src/safety/windows.ts +133 -0
  592. package/plugins/huaweicloud-core/src/safety/xargs-argv.ts +79 -0
  593. package/plugins/huaweicloud-core/src/safety-policy.ts +16 -0
  594. package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +307 -0
  595. package/plugins/huaweicloud-core/src/sandbox/deploy-nginx-verify.ts +96 -0
  596. package/plugins/huaweicloud-core/src/sandbox/deploy-nginx.ts +300 -0
  597. package/plugins/huaweicloud-core/src/sandbox/devbridge-auth.ts +291 -0
  598. package/plugins/huaweicloud-core/src/sandbox/devbridge-exec.ts +28 -0
  599. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose-flow.ts +289 -0
  600. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose.ts +310 -0
  601. package/plugins/huaweicloud-core/src/sandbox/devbridge-gateway.ts +36 -0
  602. package/plugins/huaweicloud-core/src/sandbox/devbridge-keepalive.ts +254 -0
  603. package/plugins/huaweicloud-core/src/sandbox/{devbridge-key.mjs → devbridge-key.ts} +48 -32
  604. package/plugins/huaweicloud-core/src/sandbox/devbridge-renew.ts +87 -0
  605. package/plugins/huaweicloud-core/src/sandbox/devbridge-tunnel.ts +79 -0
  606. package/plugins/huaweicloud-core/src/sandbox/devbridge-validation.ts +100 -0
  607. package/plugins/huaweicloud-core/src/sandbox/devbridge-verify.ts +120 -0
  608. package/plugins/huaweicloud-core/src/sandbox/hwlink-connection.ts +188 -0
  609. package/plugins/huaweicloud-core/src/sandbox/sandbox-output.ts +46 -0
  610. package/plugins/huaweicloud-core/src/sandbox/session-manager.ts +89 -0
  611. package/plugins/huaweicloud-core/src/sandbox/tunnel-http.ts +155 -0
  612. package/plugins/huaweicloud-core/src/sandbox/{uninstall-cleanup.mjs → uninstall-cleanup.ts} +4 -4
  613. package/plugins/huaweicloud-core/src/sandbox/upload-diagnostics.ts +46 -0
  614. package/plugins/huaweicloud-core/src/sandbox/upload-file.ts +161 -0
  615. package/plugins/huaweicloud-core/src/sandbox/upload-project.ts +218 -0
  616. package/plugins/huaweicloud-core/src/sandbox/upload-transport.ts +150 -0
  617. package/plugins/huaweicloud-core/src/sandbox/ws-exec-loader.ts +104 -0
  618. package/plugins/huaweicloud-core/src/search-docs.ts +64 -0
  619. package/plugins/huaweicloud-core/src/{search-market.mjs → search-market.ts} +96 -28
  620. package/plugins/huaweicloud-core/src/services/availability.ts +53 -0
  621. package/plugins/huaweicloud-core/src/services/regions.ts +110 -0
  622. package/plugins/huaweicloud-core/src/setup-cli.ts +1570 -0
  623. package/plugins/huaweicloud-core/src/skill-disclosure.ts +242 -0
  624. package/plugins/huaweicloud-core/src/targets.ts +156 -0
  625. package/plugins/huaweicloud-core/src/telemetry/{agent-detect.mjs → agent-detect.ts} +16 -5
  626. package/plugins/huaweicloud-core/src/telemetry/agent-registry.ts +210 -0
  627. package/plugins/huaweicloud-core/src/telemetry/agent-versions-desktop.ts +138 -0
  628. package/plugins/huaweicloud-core/src/telemetry/agent-versions.ts +84 -0
  629. package/plugins/huaweicloud-core/src/telemetry/event-pipeline.ts +214 -0
  630. package/plugins/huaweicloud-core/src/telemetry/hook-ingest.ts +82 -0
  631. package/plugins/huaweicloud-core/src/telemetry/identity-stamps.ts +108 -0
  632. package/plugins/huaweicloud-core/src/telemetry/invoke-value.ts +47 -0
  633. package/plugins/huaweicloud-core/src/telemetry/telemetry-fs.ts +47 -0
  634. package/plugins/huaweicloud-core/src/telemetry/telemetry-types.ts +97 -0
  635. package/plugins/huaweicloud-core/src/telemetry/telemetry-values.ts +116 -0
  636. package/plugins/huaweicloud-core/src/telemetry/telemetry.ts +299 -0
  637. package/plugins/huaweicloud-core/src/tool-definitions.ts +294 -0
  638. package/plugins/huaweicloud-core/src/tool-schemas.ts +180 -0
  639. package/plugins/huaweicloud-core/src/tools.ts +417 -0
  640. package/plugins/huaweicloud-core/src/update-cache.ts +95 -0
  641. package/plugins/huaweicloud-core/src/update-check.ts +51 -0
  642. package/plugins/huaweicloud-core/src/update-hint.ts +82 -0
  643. package/plugins/huaweicloud-core/src/update-installed.ts +53 -0
  644. package/plugins/huaweicloud-core/src/update-registry.ts +152 -0
  645. package/plugins/huaweicloud-core/src/update-semver.ts +80 -0
  646. package/plugins/huaweicloud-core/src/update-skip.ts +94 -0
  647. package/plugins/huaweicloud-core/src/update-upgrade.ts +130 -0
  648. package/plugins/huaweicloud-core/src/vendor-gate.ts +103 -0
  649. package/plugins/huaweicloud-core/src/ws-exec/hwlink-exec-client.ts +15 -0
  650. package/plugins/huaweicloud-core/src/ws-exec/hwlink-exec-pending.ts +113 -0
  651. package/plugins/huaweicloud-core/src/ws-exec/hwlink-exec-session.ts +334 -0
  652. package/plugins/huaweicloud-core/src/ws-exec/{hwlink-fair-queue.js → hwlink-fair-queue.ts} +46 -15
  653. package/plugins/huaweicloud-core/src/ws-exec/hwlink-interactive-terminal.ts +158 -0
  654. package/plugins/huaweicloud-core/src/ws-exec/{hwlink-multiplexer.js → hwlink-multiplexer.ts} +108 -30
  655. package/plugins/huaweicloud-core/src/ws-exec/hwlink-normalize.ts +60 -0
  656. package/plugins/huaweicloud-core/src/ws-exec/{hwlink-packet.js → hwlink-packet.ts} +40 -16
  657. package/plugins/huaweicloud-core/src/ws-exec/{hwlink-terminal-channel.js → hwlink-terminal-channel.ts} +30 -18
  658. package/plugins/huaweicloud-core/src/ws-exec/{hwlink-tunnel-channel.mjs → hwlink-tunnel-channel.ts} +75 -27
  659. package/plugins/huaweicloud-core/src/ws-exec/{index.js → index.ts} +11 -11
  660. package/plugins/huaweicloud-core/src/ws-exec/ws-exec-client.ts +102 -0
  661. package/plugins/huaweicloud-core/tsconfig.json +21 -0
  662. package/rules/huawei-agent-rules.mdc +2 -2
  663. package/integrations/hermes/skills-snapshot.json +0 -175
  664. package/integrations/opencode/skills/huaweicloud-core/SKILL.md +0 -32
  665. package/plugins/huaweicloud-core/skills/huawei-cloud-apig-instance-management/scripts/cli/cli_reporting.py +0 -589
  666. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/references/test-report.md +0 -35
  667. package/plugins/huaweicloud-core/skills/huawei-cloud-cts-trace-management/scripts/cli/cli_reporting.py +0 -928
  668. package/plugins/huaweicloud-core/skills/huawei-cloud-dds-dcs-instance-management/scripts/cli/cli_reporting.py +0 -928
  669. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/references/test-report.md +0 -52
  670. package/plugins/huaweicloud-core/skills/huawei-cloud-deployment-task-management/scripts/cli/cli_reporting.py +0 -928
  671. package/plugins/huaweicloud-core/skills/huawei-cloud-dew-key-management/scripts/cli/cli_reporting.py +0 -577
  672. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/scripts/cli/cli_reporting.py +0 -928
  673. package/plugins/huaweicloud-core/skills/huawei-cloud-gaussdb-instance-management/scripts/gaussdb_cli.sh +0 -138
  674. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/scripts/install_cli.sh +0 -94
  675. package/plugins/huaweicloud-core/skills/huawei-cloud-smn-dms-message/scripts/smn_dms_skill.py +0 -444
  676. package/plugins/huaweicloud-core/src/account-type.mjs +0 -135
  677. package/plugins/huaweicloud-core/src/auth/agent-registration.mjs +0 -243
  678. package/plugins/huaweicloud-core/src/auth/credential-validator.mjs +0 -198
  679. package/plugins/huaweicloud-core/src/auth/credentials.mjs +0 -446
  680. package/plugins/huaweicloud-core/src/auth/project-id.mjs +0 -68
  681. package/plugins/huaweicloud-core/src/auth/reconcile.mjs +0 -257
  682. package/plugins/huaweicloud-core/src/auto-upgrade-runner.mjs +0 -58
  683. package/plugins/huaweicloud-core/src/detect-framework.mjs +0 -402
  684. package/plugins/huaweicloud-core/src/hcloud-cli.mjs +0 -825
  685. package/plugins/huaweicloud-core/src/koocli-version.mjs +0 -47
  686. package/plugins/huaweicloud-core/src/mcp-config-merge.mjs +0 -219
  687. package/plugins/huaweicloud-core/src/mcp-protocol.mjs +0 -118
  688. package/plugins/huaweicloud-core/src/mcp-server-remote.mjs +0 -108
  689. package/plugins/huaweicloud-core/src/mcp-server.mjs +0 -233
  690. package/plugins/huaweicloud-core/src/officeace-paths.mjs +0 -51
  691. package/plugins/huaweicloud-core/src/preflight.mjs +0 -125
  692. package/plugins/huaweicloud-core/src/proxy/proxy-config.mjs +0 -187
  693. package/plugins/huaweicloud-core/src/risk-rule-engine.mjs +0 -182
  694. package/plugins/huaweicloud-core/src/safety-policy.mjs +0 -625
  695. package/plugins/huaweicloud-core/src/sandbox/hdkitservice-api.mjs +0 -293
  696. package/plugins/huaweicloud-core/src/sandbox/hwlink-api.mjs +0 -224
  697. package/plugins/huaweicloud-core/src/sandbox/session-manager.mjs +0 -2594
  698. package/plugins/huaweicloud-core/src/setup-cli.mjs +0 -5379
  699. package/plugins/huaweicloud-core/src/telemetry/agent-registry.mjs +0 -341
  700. package/plugins/huaweicloud-core/src/telemetry/telemetry.mjs +0 -492
  701. package/plugins/huaweicloud-core/src/tools.mjs +0 -3211
  702. package/plugins/huaweicloud-core/src/update-auto.mjs +0 -669
  703. package/plugins/huaweicloud-core/src/update-check.mjs +0 -607
  704. package/plugins/huaweicloud-core/src/update-policy.mjs +0 -82
  705. package/plugins/huaweicloud-core/src/ws-exec/hwlink-exec-client.js +0 -461
  706. package/plugins/huaweicloud-core/src/ws-exec/ws-exec-client.js +0 -365
@@ -12,6 +12,7 @@ plugin hooks.
12
12
  """
13
13
 
14
14
  import json
15
+ import os
15
16
  import re
16
17
  import sys
17
18
  from pathlib import Path
@@ -21,29 +22,189 @@ DENY_PREFIX = "Huawei Cloud safety hook blocked this action: "
21
22
  RULES_PATH = Path(__file__).resolve().parents[1] / "safety" / "rules" / "cloud-risk-rules.json"
22
23
  POLICY_PATH = Path(__file__).resolve().parents[1] / "safety" / "policy.json"
23
24
 
24
- PLUGIN_DIR = Path(__file__).resolve().parents[2]
25
+ # parents[1] is the plugin dir (hooks/ sits directly under it); the previous
26
+ # parents[2] landed telemetry one level too high, which in the codex plugin
27
+ # cache layout wrote a 'telemetry' sibling next to the version dir and broke
28
+ # codex's version resolution (same failure the bundled server's depth-based
29
+ # PLUGIN_DIR caused before the resolvePluginDir fix in telemetry.ts).
30
+ PLUGIN_DIR = Path(__file__).resolve().parents[1]
25
31
  TELEMETRY_DIR = PLUGIN_DIR / "telemetry"
26
32
  HOOK_EVENTS_PATH = TELEMETRY_DIR / "hook-events.jsonl"
27
33
 
28
34
  CONFIG_FILE_RE = None
29
35
  SECRET_READ_RE = None
36
+ SECRET_CLI_RE = None
37
+ APPROVAL_CLI_RE = None
30
38
  WRITE_OPERATION_RE = None
39
+ WRITE_VOCAB_RE = None
40
+ READ_OPERATION_RE = None
41
+ READ_OPERATION_EXCEPTIONS = set()
42
+ BLOCKED_CONFIGURE_SUBCOMMANDS = set()
43
+
44
+ # OBS util write-capable subcommands — the write-gate's OBS face and (via the
45
+ # load_policy union) the obfuscation gate's vocabulary. Kept as one set per
46
+ # layer with the TS twin (src/safety/tokens.ts OBSUTIL_WRITES), pinned by the
47
+ # hook-parity battery.
48
+ OBSUTIL_WRITES = {
49
+ "mb", "cp", "mv", "rm", "delete", "mkdir", "sync", "restore", "chattri",
50
+ "bucketpolicy", "lifecycle", "cors", "website", "sign", "share-add", "share-update", "share-rm",
51
+ # KooCLI 7.3.12 write-capable subcommands (-method based, except
52
+ # custom-domain which writes via -cname/certificate options),
53
+ # plus the full-name put/delete public-access-block writes.
54
+ "bucket-tagging", "object-tagging", "encryption", "custom-domain", "mirror-back-to-source",
55
+ "put-public-access-block", "delete-public-access-block",
56
+ # Pre-existing on 7.2.x too but never dispositioned (7.3.12-pin sweep),
57
+ # plus create-share (issues capability tokens — sign's class) and update
58
+ # (obsutil self-update — mutates the installed binary).
59
+ "abort", "archive", "create-share", "update",
60
+ }
61
+ # The OBS subcommand half of the obfuscation gate's vocabulary (marker-gated
62
+ # at the gate — see the load_policy comment). Module-compiled, not
63
+ # policy-derived: OBSUTIL_WRITES has its own pinned dual-home doctrine
64
+ # (the KooCLI 7.3.12 lockstep sweep), so it is not foldable into
65
+ # policy.json's prefix list. The marker that gates it is the word-bounded
66
+ # OBS service token (also matches `obs://` — the colon is a boundary);
67
+ # `observations`/`jobs` stay non-markers. A bare `cloud` SUBSTRING was the
68
+ # round-2 marker and denied routine huaweicloud-bearing PATHS
69
+ # (cp $(mktemp -d)/x plugins/huaweicloud-core/dist/foo) — the decoded-bin
70
+ # clause (decode_ansi_c_spans, interrogate round 3) now carries the
71
+ # mangled-bin class that substring existed for.
72
+ OBS_VOCAB_RE = re.compile(r"(^|[^a-z])(?:" + "|".join(sorted(OBSUTIL_WRITES)) + ")", re.I)
73
+ OBS_MARKER_RE = re.compile(r"\bOBS\b", re.I)
31
74
 
32
75
 
33
76
  def load_policy():
34
- global CONFIG_FILE_RE, SECRET_READ_RE, WRITE_OPERATION_RE
77
+ global CONFIG_FILE_RE, SECRET_READ_RE, SECRET_CLI_RE, APPROVAL_CLI_RE, WRITE_OPERATION_RE, WRITE_VOCAB_RE, READ_OPERATION_RE, READ_OPERATION_EXCEPTIONS
35
78
  try:
36
79
  with POLICY_PATH.open("r", encoding="utf-8") as file_obj:
37
80
  policy = json.load(file_obj)
81
+ # Write/read vocabularies FIRST, per-field isolated (interrogate
82
+ # round 1): an invalid regex in a LATER field's list
83
+ # (credentialFilePatterns, blockedSecretOperations, ...) must not
84
+ # abort the load before the vocabularies compile — their
85
+ # unavailability fails their gates CLOSED (hcloud_write_blocked /
86
+ # the obfuscation clause), so unrelated corruption must not trigger
87
+ # that arm while the lists are intact. Non-list values normalize to
88
+ # [] so every degraded shape funnels into the fail-closed arms
89
+ # instead of "|".join-ing a string into a garbage char-alternation.
90
+ write_prefixes = policy.get("writeOperationPrefixes", [])
91
+ if not isinstance(write_prefixes, list):
92
+ write_prefixes = []
93
+ if write_prefixes:
94
+ # Applied to the OPERATION TOKEN (positional, like the TS
95
+ # hasWritePrefix): ^ matches token start, [A-Za-z0-9] admits
96
+ # compound names (NovaCreate…). The older whole-text form with
97
+ # (^|[A-Za-z0-9]) never matched a space-preceded plain
98
+ # operation AND matched prose after `echo`.
99
+ WRITE_OPERATION_RE = re.compile(r"(^|[A-Za-z0-9])(" + "|".join(write_prefixes) + r")\w*", re.I)
100
+ # Write-operation vocabulary for the obfuscation gate's
101
+ # fail-closed clause — DERIVED from the same policy list as
102
+ # WRITE_OPERATION_RE, never a second hand-maintained
103
+ # alternation: the hardcoded 20-word copy this replaced had
104
+ # drifted from the 37 policy.json prefixes, and the 17 missing
105
+ # words (invoke/execute/trigger/deploy among them) let mangled
106
+ # writes through the py-hook faces (Hermes importlib, WorkBuddy
107
+ # deploy) while the TS layer denied (writeVocabHit over
108
+ # DEFAULT_POLICY.writeOperationPrefixes in classify-text.ts).
109
+ # The OBSUTIL_WRITES union rides a SEPARATE marker-gated regex
110
+ # (interrogate round 2): routing dies with the keyword under
111
+ # ANSI-C mangling, so non-prefix obsutil subcommand writes
112
+ # (rm/cp/mv/sync/chattri…) must be in the vocab — but those
113
+ # short words are routine shell vocabulary, so that arm fires
114
+ # only when the shadow also carries a cloud marker (any *cloud
115
+ # spelling — the mangled bin leaves `x68cloud` — or the OBS
116
+ # service token), keeping `docker rm $(docker ps -aq)` and
117
+ # `mkdir -p $(pwd)/build` legitimate. The vocabulary's own
118
+ # failure mode lives at the gate: an unavailable derivation
119
+ # fails the clause CLOSED.
120
+ WRITE_VOCAB_RE = re.compile(r"(^|[^a-z])(?:" + "|".join(write_prefixes) + ")", re.I)
121
+ read_prefixes = policy.get("readOperationPrefixes", [])
122
+ if not isinstance(read_prefixes, list):
123
+ read_prefixes = []
124
+ else:
125
+ # Item-level filtering (TS toStringArray parity, loop round 3):
126
+ # a non-string item used to make "|".join throw, the outer
127
+ # except swallow the whole load, and every LATER field
128
+ # (secret/configure vocabularies) stay None — gates of the
129
+ # `if RE and ...` form skip → fail-open.
130
+ read_prefixes = [p for p in read_prefixes if isinstance(p, str)]
131
+ if read_prefixes:
132
+ # The read vocabulary, likewise derived (interrogate round 1 —
133
+ # the hardcoded mirror was the last hand-maintained policy
134
+ # copy). Kept in the historical \b-anywhere shape for BOTH
135
+ # consumers: record_cli_event matches it against the
136
+ # "Service Operation" cmd string (the read word is the SECOND
137
+ # word), and the write gate's read exemption anchors it at the
138
+ # operation token's start via re.match (TS hasReadPrefix's
139
+ # ^prefix parity — \b at position 0 is equivalent).
140
+ try:
141
+ READ_OPERATION_RE = re.compile(r"\b(" + "|".join(read_prefixes) + r")\w*", re.I)
142
+ except re.error:
143
+ # A regex-metacharacter string in the list ("Get(") degrades
144
+ # ONLY the read vocabulary — fail-closed (no read can be
145
+ # proven, writes stay denied). Swallowing it into the outer
146
+ # handler left every LATER field unloaded and its gates
147
+ # skipping: fail-open (loop round 4, seat-2 B2).
148
+ READ_OPERATION_RE = None
149
+ read_exceptions_raw = policy.get("readOperationExceptions", [])
150
+ if not isinstance(read_exceptions_raw, list):
151
+ read_exceptions_raw = []
152
+ # Exact-name exception arm (TS hasReadPrefix's readOperationExceptions
153
+ # parity, loop round 3): query-result operations whose names lead with
154
+ # a write word (DDM MigrateResults, DATAARTSSTUDIO ImportResult). A
155
+ # general Result(s)-suffix regex was tried in round 2 and killed by the
156
+ # corpus (five real writes end in Result(s)) — exact names only.
157
+ # Exact matching also sidesteps the py `$`-before-trailing-newline vs
158
+ # JS `$` divergence a suffix regex carried (loop round 2, seat-2 B3).
159
+ # Item filtering: same fail-open shape as read_prefixes above.
160
+ READ_OPERATION_EXCEPTIONS = {
161
+ str(op).lower() for op in read_exceptions_raw if isinstance(op, str)
162
+ }
38
163
  cred_patterns = policy.get("credentialFilePatterns", [])
39
164
  if cred_patterns:
40
165
  CONFIG_FILE_RE = re.compile("|".join(cred_patterns), re.I)
41
- blocked_secrets = policy.get("blockedSecretOperations", [])
166
+ blocked_secrets = [op for op in policy.get("blockedSecretOperations", []) if op != ""]
42
167
  if blocked_secrets:
43
- SECRET_READ_RE = re.compile("|".join(re.escape(op) for op in blocked_secrets), re.I)
44
- write_prefixes = policy.get("writeOperationPrefixes", [])
45
- if write_prefixes:
46
- WRITE_OPERATION_RE = re.compile(r"(^|[A-Za-z0-9])(" + "|".join(write_prefixes) + r")\w*", re.I)
168
+ # Only entries that are a PREFIX of another entry (ShowSecret is
169
+ # a stem of ShowSecretVersion) get boundary guards, so the stem
170
+ # does not substring-match longer operations or stem-containing
171
+ # resource names (ShowSecretsConfig, showsecret-demo). The
172
+ # self-specific entries stay unguarded: their substring
173
+ # semantics on the quote-stripped shadow must match the TS
174
+ # layer's unguarded alternatives or the layers drift.
175
+ def _secret_pattern(op):
176
+ pattern = re.escape(op)
177
+ is_stem = any(
178
+ other != op and other.lower().startswith(op.lower()) for other in blocked_secrets
179
+ )
180
+ if is_stem:
181
+ pattern = r"(?<![A-Za-z0-9._/-])" + pattern + r"(?![A-Za-z0-9._/-])"
182
+ return pattern
183
+
184
+ SECRET_READ_RE = re.compile("|".join(_secret_pattern(op) for op in blocked_secrets), re.I)
185
+ blocked_configure = policy.get("blockedConfigureSubcommands", [])
186
+ if blocked_configure:
187
+ global BLOCKED_CONFIGURE_SUBCOMMANDS
188
+ BLOCKED_CONFIGURE_SUBCOMMANDS = {cmd.lower() for cmd in blocked_configure}
189
+ blocked_secret_cli = policy.get("blockedSecretCliPatterns", [])
190
+ if blocked_secret_cli:
191
+ SECRET_CLI_RE = re.compile("|".join(blocked_secret_cli), re.I)
192
+ # The approval CLI's terminal-confirm verb. No order-independent
193
+ # bin+verb pair guard here, unlike the reveal pair below: `approve`
194
+ # is a common word, so a Huawei Cloud operation named e.g.
195
+ # ApproveThing must never trip this gate. These anchored patterns
196
+ # fire only when a devkit binary spelling is present too.
197
+ blocked_approval_cli = policy.get("blockedApprovalCliPatterns", [])
198
+ if isinstance(blocked_approval_cli, list):
199
+ blocked_approval_cli = [p for p in blocked_approval_cli if isinstance(p, str)]
200
+ if blocked_approval_cli:
201
+ try:
202
+ APPROVAL_CLI_RE = re.compile("|".join(blocked_approval_cli), re.I)
203
+ except re.error:
204
+ # Isolate this gate's degradation: a malformed pattern
205
+ # leaves APPROVAL_CLI_RE None instead of aborting the
206
+ # whole policy load.
207
+ APPROVAL_CLI_RE = None
47
208
  except Exception:
48
209
  pass
49
210
 
@@ -51,26 +212,151 @@ def load_policy():
51
212
  load_policy()
52
213
 
53
214
  ENV_DUMP_RE = re.compile(
54
- r"(env|printenv|Get-ChildItem\s+Env:|gci\s+Env:|dir\s+Env:).*(HUAWEICLOUD|HWC_|HCLOUD|HW_|OS_)", re.I,
55
- )
56
- # Credential variable references bypass the env-command gate above: HW_ is
57
- # the plugin's own documented credential prefix (HW_ACCESS_KEY/HW_SECRET_KEY/
58
- # HW_SECURITY_TOKEN), cloud environments also expose the AWS-style
59
- # HUAWEICLOUD_SECRET_ACCESS_KEY name, and `echo $HW_SECRET_KEY` /
60
- # `printenv HW_ACCESS_KEY` / `echo $HUAWEICLOUD_SECRET_ACCESS_KEY` previously
61
- # fell through to allow (#561 D4-2, #770 D4-2).
62
- #
63
- # The negative lookbehind exempts literal-NAME references — backslash-escaped
64
- # (\$HW_*) or single-quoted ('$HW_*', which the shell never expands) —
65
- # while unescaped `$HW_*` is a potential expansion/dump regardless of the
66
- # command. Aligned with safety-policy.mjs L419-423.
67
- CRED_VAR_REF_RE = re.compile(
68
- r"(?<!['\\])\$\{?(?:HUAWEICLOUD|HWC|HW|OS)_(?:SECRET_ACCESS_KEY|ACCESS_KEY|SECRET_KEY|SECURITY_TOKEN)"
69
- r"|(?:^|\s)printenv\s+(?:HUAWEICLOUD|HWC|HW|OS)_(?:SECRET_ACCESS_KEY|ACCESS_KEY|SECRET_KEY|SECURITY_TOKEN)",
215
+ r"(^|\s)(env|printenv|export\s+-p|declare|typeset|set|Get-ChildItem\s+Env:|gci\s+Env:|dir\s+Env:)(?![A-Za-z0-9_-]).*(HUAWEICLOUD(?!-devkit)|HWC_|HCLOUD_|OS_|HW_(?:ACCESS_KEY|SECRET_KEY|SECRET_ACCESS_KEY|SECURITY_TOKEN|API_KEY|VAULT_MASTER_KEY))",
70
216
  re.I,
71
217
  )
72
218
  HCLOUD_RE = re.compile(r"(^|\s)hcloud(\.exe)?\s+", re.I)
73
- READ_OPERATION_RE = re.compile(r"\b(List|Show|Get|Describe|NovaList|NovaShow)\w*", re.I)
219
+ # READ_OPERATION_RE is policy-derived (load_policy, from
220
+ # readOperationPrefixes) — see the derivation comment there for the two
221
+ # consumer shapes (record_cli_event's \b-anywhere, the write gate's
222
+ # re.match anchoring).
223
+ # Mirrors the TS layer's #650 D4-2 gate: unescaped $HW_/$HUAWEICLOUD_/
224
+ # $HWC_/$OS_ credential expansions are a potential dump regardless of the
225
+ # command. The negative lookbehind exempts backslash-escaped or single-quoted
226
+ # names (the shell never expands those), so this stays on RAW text.
227
+ CRED_EXPANSION_RE = re.compile(
228
+ r"(?<!['\\])\$\{?(?:HUAWEICLOUD|HWC|HW|OS)_(?:ACCESS_KEY|SECRET_KEY|SECRET_ACCESS_KEY|SECURITY_TOKEN|API_KEY|VAULT_MASTER_KEY)",
229
+ re.I,
230
+ )
231
+ # printenv with a bare credential name: a command-name gate, so it runs on
232
+ # the quote-stripped shadow (quoting a command name does not stop it).
233
+ PRINTENV_CRED_RE = re.compile(
234
+ r"(^|\s)printenv\s+.*(?:HUAWEICLOUD|HWC|HW|OS)_(?:ACCESS_KEY|SECRET_KEY|SECRET_ACCESS_KEY|SECURITY_TOKEN|API_KEY|VAULT_MASTER_KEY)",
235
+ re.I,
236
+ )
237
+
238
+
239
+ def strip_shell_quotes(text):
240
+ """Quote/backslash/dollar/backtick-stripped shadow for presence gates:
241
+ quoted tokens (``secret 'get'``, ``bash -c "hcloud ..."``) and ANSI-C
242
+ quoting (``$'get'``) must not slip past the raw-text regexes the shell
243
+ would still execute. Variable indirection (``$S``) remains a documented
244
+ residual — a text gate cannot see through expansion. None of the
245
+ canonical command tokens contain the stripped characters.
246
+
247
+ Line continuations drop FIRST (interrogate round 4): bash removes the
248
+ \\<newline> pair at parser level, and the surviving newline broke
249
+ contiguity everywhere (``h\\<LF>cloud`` never routed,
250
+ ``De\\<LF>leteServers`` never matched a prefix). Single-quoted spans
251
+ keep the pair in real bash — over-stripping there only ever JOINS text
252
+ (fail-closed toward detection, never hides a marker)."""
253
+ text = re.sub(r"\\\n", "", text)
254
+ return re.sub(r"['\"\\\\$`]", "", text)
255
+
256
+
257
+ ANSI_C_DECODE_RE = re.compile(r"\\(?:x([0-9a-fA-F]{1,2})|([0-7]{1,3})|u([0-9a-fA-F]{1,4})|U([0-9a-fA-F]{1,8}))")
258
+
259
+ # The JS /\s/ character class (interrogate round 10): the glued tokenizer's
260
+ # word separators — str.isspace() is a superset (\x85, \x1c-\x1f) that bash
261
+ # does not treat as IFS and JS does not match.
262
+ JS_WHITESPACE_RE = re.compile(r"[\t\n\v\f\r \u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]")
263
+
264
+
265
+ def decode_ansi_c_spans(text):
266
+ """Reconstruct the argv letters ANSI-C quoting builds: inside $'…' spans
267
+ (opened only OUTSIDE quotes — a $ already inside a plain quoted span is
268
+ a literal), decode \\xHH, \\NNN (octal), \\uHHHH, and \\UHHHHHHHH
269
+ escapes to their characters; everything else passes through verbatim
270
+ (interrogate round 3: the obfuscation gate's candidates now see
271
+ ``h$'\\x63'loud`` as the ``hcloud`` the shell actually executes, so
272
+ mangling past a marker — the round-2 cloud-marker gate's bypass — no
273
+ longer hides the bin, the service token, or the operation word).
274
+ \\' inside the span does not close it; \\\\ and unrecognized escapes
275
+ stay literal (conservative); an unterminated span returns the ORIGINAL
276
+ text (no decode — today's shadow); $"…" spans pass through (locale
277
+ quoting, no escape processing for identifiers); command substitution
278
+ $(…) stays opaque (the documented residual — the printf-built bin
279
+ class). Mirrored by decodeAnsiCSpans in src/safety/shell-text.ts —
280
+ hook-parity pins the shared verdicts."""
281
+ if "$'" not in text:
282
+ return text
283
+ out = []
284
+ i, n = 0, len(text)
285
+ quote = None
286
+ while i < n:
287
+ ch = text[i]
288
+ if quote is not None:
289
+ out.append(ch)
290
+ if ch == "\\" and quote == '"' and i + 1 < n:
291
+ out.append(text[i + 1])
292
+ i += 2
293
+ continue
294
+ if ch == quote:
295
+ quote = None
296
+ i += 1
297
+ continue
298
+ if ch in ("'", '"'):
299
+ quote = ch
300
+ out.append(ch)
301
+ i += 1
302
+ continue
303
+ if ch == "\\" and i + 1 < n:
304
+ # Outside quotes a backslash escapes the NEXT character (both
305
+ # stay — the shadow's own backslash-strip handles them).
306
+ # Without this, an escaped quote opened PHANTOM quote state and
307
+ # disabled the entire decode for the rest of the payload
308
+ # (interrogate round 4: \' ; h$'\x63'loud … let the mangled
309
+ # write through every layer), and \$' mis-parsed as an ANSI-C
310
+ # span opener instead of \$ + plain quotes.
311
+ out.append(ch)
312
+ out.append(text[i + 1])
313
+ i += 2
314
+ continue
315
+ if ch == "$" and i + 1 < n and text[i + 1] == "'":
316
+ j = i + 2
317
+ span = []
318
+ closed = False
319
+ while j < n:
320
+ c = text[j]
321
+ if c == "'":
322
+ closed = True
323
+ j += 1
324
+ break
325
+ if c == "\\" and j + 1 < n:
326
+ nxt = text[j + 1]
327
+ if nxt == "'":
328
+ span.append("'")
329
+ j += 2
330
+ continue
331
+ m = ANSI_C_DECODE_RE.match(text, j)
332
+ if m:
333
+ digits = m.group(1) or m.group(2) or m.group(3) or m.group(4)
334
+ is_octal = m.group(2) is not None
335
+ radix = 8 if is_octal else 16
336
+ try:
337
+ value = int(digits, radix)
338
+ if is_octal:
339
+ value &= 0xFF # bash masks \NNN to 8 bits (NUL-truncating >0o377)
340
+ if 0 <= value <= 0x10FFFF:
341
+ span.append(chr(value))
342
+ j = m.end()
343
+ continue
344
+ except ValueError:
345
+ pass
346
+ span.append(c)
347
+ span.append(nxt)
348
+ j += 2
349
+ continue
350
+ span.append(c)
351
+ j += 1
352
+ if not closed:
353
+ return text
354
+ out.append("".join(span))
355
+ i = j
356
+ continue
357
+ out.append(ch)
358
+ i += 1
359
+ return "".join(out)
74
360
 
75
361
 
76
362
  def deny(reason, hermes=False):
@@ -99,16 +385,32 @@ def allow():
99
385
 
100
386
 
101
387
  def record_cli_event(text):
388
+ # Telemetry opt-out gates the local spool too (no collection while
389
+ # off, so nothing is transmitted retroactively on re-enable).
390
+ if os.environ.get("HUAWEICLOUD_DEVKIT_TELEMETRY") == "off":
391
+ return
102
392
  m = HCLOUD_RE.search(text)
103
393
  if not m:
104
394
  return
105
395
  rest = text[m.end():].strip()
106
396
  parts = rest.split()
107
397
  cmd = " ".join(p for p in parts if not p.startswith("--") and not p.startswith("-") and "=" not in p)
398
+ # Trim to Service+Operation: no file paths / bucket names ride along
399
+ # (matches the MCP face's trim in tools.ts).
400
+ cmd = " ".join(cmd.split()[:2])
108
401
  if not cmd:
109
402
  return
110
- is_read = bool(READ_OPERATION_RE.search(cmd))
111
- is_write = bool(WRITE_OPERATION_RE.search(cmd)) if WRITE_OPERATION_RE else False
403
+ is_read = bool(READ_OPERATION_RE.search(cmd)) if READ_OPERATION_RE else False
404
+ # Per-word write search (interrogate round 2): the cmd string is
405
+ # "Service Operation" — the write prefix regex's (^|[A-Za-z0-9]) class
406
+ # never matches the SPACE before the operation, so the canonical
407
+ # `hcloud ECS CreateServers` labeled cli:invoke. Searching each word
408
+ # anchors at the operation token's start (compound NovaCreate still
409
+ # admits mid-token). OBS subcommand writes stay unlabeled (cli:invoke)
410
+ # — the label vocabulary is the policy prefix list, same as the gate's.
411
+ is_write = (
412
+ any(WRITE_OPERATION_RE.search(w) for w in cmd.split()) if WRITE_OPERATION_RE else False
413
+ )
112
414
  event_key = "cli:read" if is_read else ("cli:write" if is_write else "cli:invoke")
113
415
  event = {"key": event_key, "value": f"hcloud {cmd}", "capability": "cli"}
114
416
  try:
@@ -179,6 +481,2053 @@ def first_denied_command_rule(text):
179
481
  return None
180
482
 
181
483
 
484
+ SHELL_FIRST = {"bash", "sh", "zsh", "dash", "bash.exe", "sh.exe", "/bin/bash", "/bin/sh", "/bin/zsh", "/bin/dash"}
485
+ COMMAND_PREFIXES = {
486
+ "sudo", "nohup", "env", "time", "do", "then", "elif", "elseif", "else", "xargs",
487
+ "if", "while", "until", "exec", "command", "coproc", "!", "{", "(", "timeout",
488
+ "watch",
489
+ # busybox: the applet dispatcher — `busybox sh -c '…'` / `busybox awk
490
+ # '…'` run the applet named as the next token (interrogate round 14 C3).
491
+ "busybox",
492
+ "nice", "stdbuf", "setsid", "ionice", "start", "call",
493
+ # PowerShell scriptblock control grammar and cmd `if`-condition words:
494
+ # a wrapper payload headed by these runs its body, so the re-base must
495
+ # see through them. None is a plausible bare POSIX program name.
496
+ "try", "catch", "finally", "begin", "process", "end", "switch", "default",
497
+ "foreach", "where", "function", "filter", "defined", "exist", "not",
498
+ "errorlevel", "%",
499
+ }
500
+ # Value-taking single-letter flags PER PREFIX (a shared set over-stripped:
501
+ # `time -p` and `command -p` take no value, so the command token was eaten).
502
+ PREFIX_FLAGS_WITH_VALUE = {
503
+ "sudo": {"-u", "-g", "-p", "-U", "-r", "-t", "-D", "-C", "--user", "--group", "--prompt", "--other-user", "--role", "--type"},
504
+ "nice": {"-n", "--adjustment"},
505
+ "xargs": {"-I", "-d", "-E", "-S", "--replace", "--delimiter", "--max-args", "--max-chars"},
506
+ "stdbuf": {"-o", "-e", "-i"},
507
+ "env": {"-u", "--unset"},
508
+ "timeout": {"--signal", "-s", "-k", "--kill-after"},
509
+ # watch's -n/--interval carry the interval; -d/-t/-g/-b/-e are boolean
510
+ # (the COMMAND words follow the flags — never consume them).
511
+ "watch": {"-n", "--interval"},
512
+ # cmd.exe's `start` takes slash flags (`/b /wait /min …`); `/d <path>`
513
+ # carries a value.
514
+ "start": {"/d"},
515
+ }
516
+
517
+
518
+ def basename_of(token):
519
+ t = token.replace("\\", "/")
520
+ return t.rsplit("/", 1)[-1]
521
+
522
+
523
+ def is_redirection_token(token):
524
+ return re.match(r"^\d*(>>|>|<|&>>|>&|<&)", token) is not None
525
+ DEVKIT_BIN_NAMES = {
526
+ "huaweicloud-devkit", "huaweicloud-devkit.js", "huaweicloud-devkit.cjs",
527
+ "huaweicloud-devkit.mjs", "huaweicloud-devkit.ts", "huaweicloud-devkit.exe",
528
+ "setup-cli.js", "setup-cli.mjs", "setup-cli.ts", "setup.cjs",
529
+ }
530
+ # Argument-less full-dump forms — at COMMAND POSITION (start or after a
531
+ # separator) so `make env` / `rg env` stay legitimate: env/printenv/export/
532
+ # declare/typeset take flags; bare `set` dumps but `set -e` sets an option.
533
+ # A following pipe or redirect means the dump leaves the process either way.
534
+ # The flags alternation is deliberately unambiguous: the long-flag branch
535
+ # carries (?!u\s) so a bare `-u` can ONLY parse through the `-u <value>`
536
+ # branch — the two-branch overlap on `-u ...` chains was exponential
537
+ # backtracking on failing tails (CodeQL; measured on the TS twin: 26
538
+ # repetitions of ' -u -- ' took 14.3s, 28 took >120s pre-fix, 5000 take 1ms
539
+ # post-fix). Must stay structurally identical to classify-text.ts.
540
+ ARGLESS_DUMP_RE = re.compile(
541
+ r"(?:^|[;&|\n\r)]|\|\||&&)\s*(?:env|printenv|export|declare|typeset)(?![A-Za-z0-9_-])(?:\s+(?:-u\s+\S+|--?(?!u\s)[A-Za-z0-9-]+(?:=[^ ]*)?))*(\s*[|>].*)?\s*$",
542
+ re.I,
543
+ )
544
+ BARE_SET_RE = re.compile(r"(?:^|[;&|\n\r)]|\|\||&&)\s*set\s*$", re.I)
545
+ DUMP_PIPE_RE = re.compile(r"(?:^|[;&|\n\r)]|\|\||&&)\s*(?:env|printenv|set)(?![A-Za-z0-9_-])\s*(?:\||>)", re.I)
546
+ OBFUSCATION_RE = re.compile(r"\$['\"]|\$\(|`")
547
+ CLOUD_BIN_RE = re.compile(
548
+ r"(^|[^a-z0-9.-])(?:huaweicloud-devkit|setup-cli\.(?:js|mjs|ts|cjs)|setup\.cjs)|(^|[^a-z0-9.-])hcloud(\.exe)?\s",
549
+ re.I,
550
+ )
551
+ DEVKIT_BIN_RE = re.compile(
552
+ r"(^|[^a-z0-9.-])(?:huaweicloud-devkit|setup-cli\.(?:js|mjs|ts|cjs)|setup\.cjs)",
553
+ re.I,
554
+ )
555
+ REVEAL_PAIR_RE = re.compile(r"(?:^|\s)secret\s+get\b", re.I)
556
+
557
+
558
+ def _is_devkit_bin(token):
559
+ return _matches_bin_name(token, DEVKIT_BIN_NAMES)
560
+
561
+
562
+ def _unwrap_secret_exec(tokens):
563
+ """Mirror of the TS unwrapSecretExecWrapper: find `<devkit-bin> [--
564
+ ] secret exec ... -- <child>` anywhere in the token stream and return
565
+ the child tokens, so a wrapped hcloud write keeps its classification."""
566
+ for i in range(len(tokens) - 2):
567
+ if not _is_devkit_bin(tokens[i]):
568
+ continue
569
+ j = i + 1
570
+ while j < len(tokens) and tokens[j] == "--":
571
+ j += 1
572
+ if j + 1 >= len(tokens) or tokens[j].lower() != "secret" or tokens[j + 1].lower() != "exec":
573
+ continue
574
+ try:
575
+ dd = tokens.index("--", j + 2)
576
+ except ValueError:
577
+ continue
578
+ if dd + 1 < len(tokens):
579
+ return tokens[dd + 1:]
580
+ return None
581
+
582
+
583
+ SKQ_VALUE_FLAGS = {"--skill-name", "--session-id", "--json"}
584
+ SKQ_BIN_NAMES = ("skill-quality-cli", "skill-quality-cli.exe", "skill-quality-cli.bin")
585
+
586
+
587
+ def _normalize_bin_token(token):
588
+ """Strip a trailing @version spec (never a path segment), leading $/$(
589
+ runs, and quote/backslash/dollar mangling the tokenizer preserves but
590
+ the shell removes. `<` is deliberately NOT stripped: a `<hcloud` token
591
+ is a redirection, not an hcloud invocation."""
592
+ base = str(token).lower()
593
+ base = re.sub(r"@[^/\\]*$", "", base)
594
+ base = re.sub(r"^[$(]+", "", base)
595
+ return re.sub(r"['\"`$\\]", "", base)
596
+
597
+
598
+ def _matches_bin_name(token, names):
599
+ """Try BOTH the raw token (Windows \\-qualified paths keep their
600
+ separators) and the normalized form (POSIX quote/escape mangling)."""
601
+ raw = re.sub(r"@[^/\\]*$", "", str(token).lower())
602
+ norm = _normalize_bin_token(token)
603
+ return any(
604
+ raw == n or raw.endswith("/" + n) or raw.endswith("\\" + n) or norm == n or norm.endswith("/" + n) or norm.endswith("\\" + n)
605
+ for n in names
606
+ )
607
+
608
+
609
+ def _is_hcloud_bin(token):
610
+ t = _normalize_bin_token(token)
611
+ return t == "hcloud" or t.endswith("/hcloud") or t == "hcloud.exe"
612
+
613
+
614
+ # Windows script-taking wrappers (cmd /c|/k "…", powershell|pwsh
615
+ # -Command|-c "…", .exe, path-qualified, `//c` Git-Bash, glued /c"…", and
616
+ # quote-mangled spellings) — mirrors the TS windowsScriptArgAt
617
+ # (#731/#760 parity). Both shells accept OPTIONS before the script flag
618
+ # (`-NoProfile -Command`, cmd `/d /s /v:on` before `/c`); the option
619
+ # region is scanned without a count cap or a closed option set.
620
+ # PowerShell ALSO binds the first POSITIONAL argument to -Command
621
+ # (`powershell hcloud ECS ListServers`), covered by a second pass that
622
+ # skips the KNOWN value-taking options' values.
623
+ WINDOWS_CMD_NAMES = ("cmd", "cmd.exe")
624
+ WINDOWS_PS_NAMES = ("powershell", "powershell.exe", "pwsh", "pwsh.exe")
625
+ POWERSHELL_VALUE_OPTIONS = {
626
+ "-executionpolicy", "-outputformat", "-inputformat", "-workingdirectory",
627
+ "-windowstyle", "-version", "-configurationname", "-psconsolefile",
628
+ "-settingsfile", "-custompipename",
629
+ }
630
+ POWERSHELL_TERMINAL_OPTIONS = {"-file", "-encodedcommand", "-enc"}
631
+ POWERSHELL_COMMAND_FLAG_RE = re.compile(r"^-c(?:o(?:m(?:m(?:a(?:n(?:d)?)?)?)?)?)?(?:([\"':])(.*))?$", re.I)
632
+ CMD_SCRIPT_FLAG_RE = re.compile(r"^/+([ckr])(.*)$", re.I)
633
+
634
+
635
+ def _strip_edge_quotes(token):
636
+ """Leading/trailing quote strip mirroring the TS per-token edge strip
637
+ (`/^[\\'"]|[\\'"]$/g`): py's tokenizer keeps edge quotes on plain words
638
+ (``DeleteServers"``), and the windows payload join must match the TS
639
+ payload construction or glued-flag forms drift between layers."""
640
+ return re.sub(r"^['\"]|['\"]$", "", token)
641
+
642
+
643
+ def _peel_glued_redirect(token):
644
+ """Peel a trailing glued redirection (with its operand) off a token:
645
+ `hcloud>out`, `OBS>&2`, and the INPUT forms `hcloud<f`, `hcloud<<EOF`
646
+ (interrogate round 9 — bash runs `bin<file args…` as the bin with the
647
+ full argv; the operand is stdin, never argv) — bash still runs the bin
648
+ with the service."""
649
+ t = re.sub(r">{1,2}[^>;&|\s]*$", "", str(token))
650
+ t = re.sub(r"<{1,2}[^<>;&|\s]*$", "", t)
651
+ return re.sub(r">&\d+$", "", t)
652
+
653
+
654
+ def _is_hcloud_head(token):
655
+ """Dual raw+normalized hcloud bin predicate (mirrors the TS
656
+ isHcloudToken): the RAW token is checked first so Windows
657
+ drive-qualified (`C:\\hcloud.exe`) and drive-relative (`d:hcloud.exe`)
658
+ bins keep their separators; quote-mangled paths strip quotes but KEEP
659
+ backslashes; fully mangled spellings and the cmd `@` sigil fall
660
+ through to the normalized check."""
661
+ # Trailing shell-operator runs (`hcloud>`, `hcloud;`) and glued
662
+ # redirect-with-operand (`hcloud>out`) attach to the bin in one
663
+ # token — bash still runs the bin.
664
+ raw = re.sub(r"^[$(<{&@.`]+", "", str(token).lower())
665
+ raw = _peel_glued_redirect(re.sub(r"[>;&|]+$", "", raw))
666
+ if (
667
+ raw == "hcloud"
668
+ or raw == "hcloud.exe"
669
+ or raw.endswith("/hcloud")
670
+ or raw.endswith("\\hcloud")
671
+ or raw.endswith("/hcloud.exe")
672
+ or raw.endswith("\\hcloud.exe")
673
+ or re.match(r"^[a-z]:hcloud(\.exe)?$", raw)
674
+ ):
675
+ return True
676
+ no_quotes = raw.replace("'", "").replace('"', "").replace("(", "").replace(")", "")
677
+ if no_quotes != raw and (
678
+ no_quotes.endswith("\\hcloud") or no_quotes.endswith("\\hcloud.exe") or re.match(r"^[a-z]:hcloud(\.exe)?$", no_quotes)
679
+ ):
680
+ return True
681
+ # Fully normalized: the PowerShell call operator on a parenthesized
682
+ # string literal (`&('hcloud')`, `.('hcloud')`) peels its wrapping
683
+ # punctuation to the canonical bin.
684
+ t = raw
685
+ for ch in "'\"\\`$()":
686
+ t = t.replace(ch, "")
687
+ return t == "hcloud" or t == "hcloud.exe" or t.endswith("/hcloud")
688
+
689
+
690
+ def _windows_script_arg_at(tokens, idx):
691
+ payload = _windows_script_arg_at_raw(tokens, idx)
692
+ # cmd/PS glue braces to commands without whitespace (`try{hcloud …`,
693
+ # `}finally{`); the POSIX vocabulary is word-exact, so braces are
694
+ # spaced at the single extraction chokepoint every consumer shares —
695
+ # but ONLY at command-grammar positions: `{` preceded by
696
+ # start/whitespace/word-char/`)`/`}`, and `}` followed by a letter.
697
+ # `={`/`:{`/`[`-glued and value-internal braces keep the token whole
698
+ # so argv service/operation positions do not shift.
699
+ if payload is None:
700
+ return None
701
+ payload = re.sub(r"(^|[\sA-Za-z0-9)}])\{", r"\1 { ", payload)
702
+ return re.sub(r"\}(?=[A-Za-z])", "} ", payload)
703
+
704
+
705
+ def _windows_script_arg_at_raw(tokens, idx):
706
+ """The command payload of a Windows script wrapper at idx, or None: cmd
707
+ needs /c or /k (after any slash options), powershell needs -Command in
708
+ any unambiguous abbreviation (after dash options; -File/-EncodedCommand
709
+ are terminal — encoded payloads are a documented residual) or binds the
710
+ first positional argument to -Command. Both shells take the ENTIRE
711
+ remainder as the command — quoted, the payload is one token; unquoted,
712
+ `cmd /c hcloud ECS ListServers` runs the whole line — so the remainder
713
+ is joined, never truncated."""
714
+ if idx >= len(tokens):
715
+ return None
716
+ head = str(tokens[idx])
717
+ is_cmd = _matches_bin_name(head, WINDOWS_CMD_NAMES)
718
+ is_ps = not is_cmd and _matches_bin_name(head, WINDOWS_PS_NAMES)
719
+ if not is_cmd and not is_ps:
720
+ return None
721
+
722
+ def payload_at(j, glued=None):
723
+ # The GLUED fragment keeps its edge-quote strip (carved from a
724
+ # word token). The REST tokens join with plain spaces — a cmd /
725
+ # powershell payload is a COMMAND LINE — and the joined payload's
726
+ # `\"` pairs (span-internal escapes) are RESOLVED so the
727
+ # re-tokenization regroups `\"hcloud …\"` into a proper span.
728
+ if glued is not None:
729
+ glued = _strip_edge_quotes(glued)
730
+
731
+ def _resolve(x):
732
+ return x.replace('\\"', '"').replace('\\\\', '\\')
733
+
734
+ rest = [str(t) for t in tokens[j + 1:]]
735
+ if glued is not None:
736
+ return _resolve(glued + " " + " ".join(rest) if rest else glued)
737
+ return _resolve(" ".join(rest)) if rest else None
738
+
739
+ if is_cmd:
740
+ j = idx + 1
741
+ while j < len(tokens):
742
+ tok = str(tokens[j]).lower()
743
+ if not tok.startswith("/"):
744
+ # Real cmd SKIPS non-switch junk before /c|/k (Wine and
745
+ # ReactOS both scan past anything not starting with `/`) —
746
+ # bailing here would launder `cmd foo /c hcloud <write>`;
747
+ # junk is skipped.
748
+ j += 1
749
+ continue
750
+ m = CMD_SCRIPT_FLAG_RE.match(str(tokens[j]))
751
+ if m:
752
+ return payload_at(j, m.group(2) or None)
753
+ j += 1
754
+ return None
755
+ # PowerShell, pass 1: the -Command flag (or a terminal option) anywhere
756
+ # after the head — option order is free, every earlier token is an
757
+ # option or its value. The payload may be colon- or quote-glued to the
758
+ # flag itself, captured from the ORIGINAL token (service names keep
759
+ # case).
760
+ for j in range(idx + 1, len(tokens)):
761
+ tok = str(tokens[j]).lower()
762
+ if tok in POWERSHELL_TERMINAL_OPTIONS:
763
+ return None
764
+ m = POWERSHELL_COMMAND_FLAG_RE.match(str(tokens[j]))
765
+ if m:
766
+ if m.group(2) is None:
767
+ return payload_at(j)
768
+ # An empty attached value (`-Command:` with nothing after the
769
+ # colon) is the same real argv as the bare flag — PowerShell
770
+ # treats the trailing arguments as the command — so it must
771
+ # not bail the whole wrapper (`-Command:""` already denies).
772
+ if not m.group(2):
773
+ return payload_at(j)
774
+ attached = _strip_edge_quotes(m.group(2))
775
+ rest = [str(t) for t in tokens[j + 1:]]
776
+
777
+ def _res(x):
778
+ return x.replace('\\"', '"').replace('\\\\', '\\')
779
+
780
+ return _res(attached + " " + " ".join(rest) if rest else attached)
781
+ # Pass 2: no flag — the first positional argument IS the command
782
+ # (powershell.exe binds position 0 to -Command). Known value-taking
783
+ # options consume their value first.
784
+ j = idx + 1
785
+ while j < len(tokens):
786
+ tok = str(tokens[j]).lower()
787
+ if tok in POWERSHELL_TERMINAL_OPTIONS:
788
+ return None
789
+ if tok.startswith("-"):
790
+ j += 1
791
+ if tok in POWERSHELL_VALUE_OPTIONS and j < len(tokens) and not str(tokens[j]).lower().startswith("-"):
792
+ j += 1
793
+ continue
794
+ return payload_at(j - 1)
795
+ return None
796
+
797
+
798
+ def _is_script_command_head(tokens, idx):
799
+ """A shell/eval token that actually heads a SCRIPT command (bash -c
800
+ <script>, eval <script>) — the re-base target for the wrapper
801
+ fallbacks. A bare `bash deploy.sh` (no -c) is NOT a script head."""
802
+ s = str(tokens[idx]).lower()
803
+ base = basename_of(s)
804
+ shell_like = s in SHELL_FIRST or (base != s and base in SHELL_FIRST)
805
+ if shell_like:
806
+ flag = str(tokens[idx + 1]) if idx + 1 < len(tokens) else ""
807
+ return bool(re.match(r"^-[a-z]*c$", flag, re.I)) and idx + 2 < len(tokens)
808
+ if s == "eval" and idx + 1 < len(tokens):
809
+ return True
810
+ return _windows_script_arg_at(tokens, idx) is not None
811
+
812
+
813
+ def _grammar_child_at(tokens, start):
814
+ """Where the wrapper's grammar model says the CHILD starts, judged from
815
+ a value-slot: a token index (grammar child head — hcloud bin or script
816
+ head reached through the wrapper's own flag grammar; the re-base
817
+ composes the deny from there), -1 (a `--` separator is still reachable
818
+ — the separator's child is authoritative and the walk continues), or
819
+ -2 (the flag region ends at a non-child token — the slot re-base
820
+ stands, fail closed). A script-head slot IS the child — handled by the
821
+ caller, never here."""
822
+ n = start
823
+ while n < len(tokens):
824
+ t = str(tokens[n])
825
+ if t == "--":
826
+ return -1
827
+ if not t.startswith("-"):
828
+ break
829
+ if "=" not in t and t.lower() in SKQ_VALUE_FLAGS:
830
+ n += 2
831
+ continue
832
+ n += 1
833
+ if n >= len(tokens):
834
+ return -1
835
+ if _is_hcloud_bin(tokens[n]) or _is_script_command_head(tokens, n):
836
+ return n
837
+ return -2
838
+
839
+
840
+ def _unwrap_skill_quality(tokens):
841
+ """Mirror of the TS unwrapSkillQualityCli: `skill-quality-cli run
842
+ [flags] [--] <child>` — bare/path-qualified/.exe/.bin bins (quote
843
+ mangled too), unknown -prefixed tokens skipped before `run`, the
844
+ separator decision INSIDE the flag walk, and REMAINDER fallbacks to
845
+ the first hcloud bin (with a following token) or script command head
846
+ when the flag grammar is unknown. The wrapper must not launder the
847
+ write gate."""
848
+ for i in range(len(tokens) - 1):
849
+ if not _matches_bin_name(tokens[i], SKQ_BIN_NAMES):
850
+ continue
851
+ j = i + 1
852
+ while j < len(tokens) and str(tokens[j]).startswith("-"):
853
+ j += 1
854
+ if j >= len(tokens):
855
+ continue
856
+ if _normalize_bin_token(tokens[j]) != "run":
857
+ # A non-flag token before `run`: different subcommand or an
858
+ # unknown value flag's VALUE — fail closed only when a real
859
+ # child follows the hcloud bin (a lone trailing hcloud token is
860
+ # a subcommand argument, not a child).
861
+ for idx in range(j + 1, len(tokens) - 1):
862
+ if _is_hcloud_bin(tokens[idx]):
863
+ return tokens[idx:]
864
+ continue
865
+ k = j + 1
866
+ while k < len(tokens):
867
+ tok = str(tokens[k])
868
+ if tok == "--":
869
+ s = k + 1
870
+ while s < len(tokens) and str(tokens[s]) == "--":
871
+ s += 1
872
+ if s < len(tokens):
873
+ return tokens[s:]
874
+ break
875
+ if tok.startswith("-"):
876
+ k += 1
877
+ if "=" not in tok and tok.lower() in SKQ_VALUE_FLAGS and k < len(tokens):
878
+ # Wrapper-ambiguous value slot — worst-case parse
879
+ # controls: a script-head slot IS the child UNLESS the
880
+ # wrapper's `--` directly follows; an hcloud slot
881
+ # resolves through the grammar model.
882
+ slot_is_hcloud = _is_hcloud_bin(tokens[k])
883
+ slot_is_script = _is_script_command_head(tokens, k)
884
+ if (slot_is_hcloud or slot_is_script) and k + 1 < len(tokens):
885
+ if slot_is_script:
886
+ if str(tokens[k + 1]) != "--":
887
+ return tokens[k:]
888
+ else:
889
+ grammar_child = _grammar_child_at(tokens, k + 1)
890
+ if grammar_child == -2:
891
+ return tokens[k:]
892
+ if grammar_child >= 0:
893
+ return tokens[grammar_child:]
894
+ k += 1
895
+ continue
896
+ if _is_hcloud_bin(tok):
897
+ return tokens[k:]
898
+ for idx in range(k + 1, len(tokens) - 1):
899
+ if _is_hcloud_bin(tokens[idx]):
900
+ return tokens[idx:]
901
+ for idx in range(k + 1, len(tokens)):
902
+ if _is_script_command_head(tokens, idx):
903
+ return tokens[idx:]
904
+ # No hcloud bin or script head in the tail: the verbatim child.
905
+ return tokens[k:]
906
+ return None
907
+
908
+
909
+ def split_tokens(text):
910
+ """Quote-aware tokenizer mirroring the TS ``splitSimpleCommand``: a
911
+ quoted span becomes ONE token (quotes stripped from its content), so
912
+ ``bash -c "hcloud ECS X"`` yields ``['bash','-c','hcloud ECS X']`` and
913
+ the -c argument keeps its grouping. Double-quoted spans honor
914
+ backslash escapes (``\\"`` nests quotes — the canonical bash way to
915
+ embed a Windows wrapper); single-quoted spans do not (POSIX). Plain
916
+ words strip a leading/trailing quote like the TS per-token edge
917
+ replace, so the two tokenizers agree on mangled spellings.
918
+
919
+ Line continuations are removed before scanning (interrogate round 4):
920
+ bash drops the \\<newline> pair at parser level, and the word scan
921
+ would otherwise split ``De\\<LF>leteServers`` into two tokens leaving
922
+ the operation slot reading ``De\\``. Single-quoted spans keep the pair
923
+ in real bash — over-stripping there only ever JOINS tokens
924
+ (fail-closed toward classification, never hides one)."""
925
+ text = re.sub(r"\\\n", "", text)
926
+ tokens = []
927
+ i, n = 0, len(text)
928
+ while i < n:
929
+ ch = text[i]
930
+ if ch == "'":
931
+ end = text.find(ch, i + 1)
932
+ if end < 0:
933
+ tokens.append(text[i + 1:])
934
+ break
935
+ tokens.append(text[i + 1:end])
936
+ i = end + 1
937
+ elif ch == '"':
938
+ # Double-quoted span, escape-aware (`\"` nests quotes). The
939
+ # closer is REQUIRED: an unterminated `"` falls back to a word
940
+ # scan (mirroring the TS \S+ alternative).
941
+ j = i + 1
942
+ span = []
943
+ closed = False
944
+ while j < n:
945
+ if text[j] == "\\" and j + 1 < n and text[j + 1] in ('"', "\\"):
946
+ span.append(text[j])
947
+ span.append(text[j + 1])
948
+ j += 2
949
+ continue
950
+ if text[j] == '"':
951
+ closed = True
952
+ break
953
+ span.append(text[j])
954
+ j += 1
955
+ if closed:
956
+ tokens.append("".join(span))
957
+ i = j + 1
958
+ else:
959
+ j = i
960
+ while j < n and not text[j].isspace():
961
+ j += 1
962
+ tokens.append(re.sub(r"^['\"]|['\"]$", "", text[i:j]))
963
+ i = j
964
+ elif ch.isspace():
965
+ i += 1
966
+ else:
967
+ j = i
968
+ while j < n and not text[j].isspace():
969
+ j += 1
970
+ tokens.append(re.sub(r"^['\"]|['\"]$", "", text[i:j]))
971
+ i = j
972
+ return tokens
973
+
974
+
975
+ def split_tokens_glued(text):
976
+ """Bash-word-faithful tokenizer for the write gate's glued-bin fallback
977
+ (interrogate round 9): adjacent quoted spans and word characters form
978
+ ONE token — ``"hcl"oud ECS Delete`` is the single word ``hcloud`` to
979
+ bash, with ``ECS``/``Delete`` as real argv — unlike split_tokens, which
980
+ keeps the span/fragment distinction other consumers rely on (the
981
+ windows-payload piece-split's quote-carrying refusal, the feeder
982
+ expanders). Single-quoted spans keep their literal backslashes; double-
983
+ quoted spans resolve \\" and \\\\ pairs; unterminated spans run to the
984
+ end; \\<newline> continuations drop first (bash's own first pass).
985
+ Word separators are the EXACT JS /\\s/ set (interrogate round 10):
986
+ str.isspace() also splits on \\x85 and \\x1c-\\x1f, which JS does not
987
+ and bash does not treat as IFS — the round-9 tokenizer re-chose the
988
+ language-native class after the strip-set lesson and drifted the twins
989
+ on those (fail-closed over-deny, non-executable shapes). Mirrored by
990
+ splitSimpleCommandGlued in src/safety/shell-text.ts — the tokenizer
991
+ twin corpus pins the shared outputs."""
992
+ text = re.sub(r"\\\n", "", text)
993
+ tokens = []
994
+ cur = []
995
+
996
+ def _flush():
997
+ if cur:
998
+ tokens.append("".join(cur))
999
+ del cur[:]
1000
+
1001
+ i, n = 0, len(text)
1002
+ while i < n:
1003
+ ch = text[i]
1004
+ if ch == "'":
1005
+ end = text.find(ch, i + 1)
1006
+ if end < 0:
1007
+ cur.append(text[i + 1:])
1008
+ i = n
1009
+ continue
1010
+ cur.append(text[i + 1:end])
1011
+ i = end + 1
1012
+ continue
1013
+ if ch == '"':
1014
+ j = i + 1
1015
+ closed = False
1016
+ while j < n:
1017
+ if text[j] == "\\" and j + 1 < n and text[j + 1] in ('"', "\\"):
1018
+ cur.append(text[j])
1019
+ cur.append(text[j + 1])
1020
+ j += 2
1021
+ continue
1022
+ if text[j] == '"':
1023
+ closed = True
1024
+ break
1025
+ cur.append(text[j])
1026
+ j += 1
1027
+ i = n if j >= n and not closed else j + 1
1028
+ continue
1029
+ if JS_WHITESPACE_RE.match(ch):
1030
+ _flush()
1031
+ i += 1
1032
+ continue
1033
+ cur.append(ch)
1034
+ i += 1
1035
+ _flush()
1036
+ return tokens
1037
+
1038
+
1039
+ def _skip_prefix_args(prefix, tokens):
1040
+ """Mirror of the TS skipPrefixArguments: strip the prefix's flag region
1041
+ (dash flags, durations, start/call slash flags) honoring the
1042
+ per-prefix value-flag grammar."""
1043
+ value_flags = PREFIX_FLAGS_WITH_VALUE.get(prefix, set())
1044
+ rest = tokens
1045
+ while rest and (
1046
+ rest[0].startswith("-")
1047
+ or re.match(r"^\d*\.?\d+[smh]?$", rest[0], re.I)
1048
+ or (prefix in ("start", "call") and rest[0].startswith("/"))
1049
+ ):
1050
+ # Round 19 F1b: the value-flag comparison strips quote-mangling.
1051
+ flag = re.sub(r"['\"\\$]", "", str(rest[0]))
1052
+ rest = rest[1:]
1053
+ if "=" not in flag and flag in value_flags and rest:
1054
+ rest = rest[1:]
1055
+ return rest
1056
+
1057
+
1058
+ def _hcloud_piece_at(tokens, i):
1059
+ """cmd/PS payload words glue shell separators to the bin (`x&&hcloud`,
1060
+ `ListServers}catch{hcloud`): split candidate tokens on separator runs
1061
+ before the head checks, re-basing to the piece bin + the pieces and
1062
+ tokens that follow. Tokens carrying quote characters are NOT split —
1063
+ their separators are quote-protected argument VALUES
1064
+ (`--description='a;hcloud;DeleteServers'`), not live command sites.
1065
+ Returns the re-based stream or None."""
1066
+ tok = str(tokens[i])
1067
+ if _is_hcloud_head(tok):
1068
+ stream = [str(t) for t in tokens[i:]]
1069
+ else:
1070
+ if re.search(r"['\"]", tok):
1071
+ return None
1072
+ pieces = [p for p in re.split(r"[;&|]+", tok) if p]
1073
+ at = -1
1074
+ for k, p in enumerate(pieces):
1075
+ if _is_hcloud_head(p):
1076
+ at = k
1077
+ break
1078
+ if at < 0:
1079
+ return None
1080
+ stream = pieces[at:] + [str(t) for t in tokens[i + 1:]]
1081
+ # Drop pure-closer tokens that follow the bin (`.( 'hcloud' )`
1082
+ # tokenizes the `)` standalone) — they would occupy the service slot
1083
+ # and mask the operation behind them.
1084
+ k = 1
1085
+ while k < len(stream) and re.match(r"^[)\]}]+$", stream[k]):
1086
+ k += 1
1087
+ return stream[:1] + stream[k:]
1088
+
1089
+
1090
+ def hcloud_leading_segment(tokens):
1091
+ """Strip command-position prefixes (shell -c, sudo/env/xargs/do/then,
1092
+ the PS/cmd control vocabulary, VAR= assignments) and report the token
1093
+ list when its command token is hcloud (any path-qualified /
1094
+ quote-mangled / @-sigil spelling), else None. The windows-payload
1095
+ context is recorded in _LEADING_WINDOWS_PAYLOAD for the caller that
1096
+ needs it (the later-bin scan in hcloud_write_blocked)."""
1097
+ result = _leading_segment_core(tokens)
1098
+ _LEADING_WINDOWS_PAYLOAD[0] = result[1]
1099
+ return result[0]
1100
+
1101
+
1102
+ # Scratch slot for the windows-payload context of the last
1103
+ # hcloud_leading_segment call (single-threaded hook process).
1104
+ _LEADING_WINDOWS_PAYLOAD = [False]
1105
+
1106
+
1107
+ def _leading_segment_core(tokens):
1108
+ """(leading token list or None, entered-windows-payload flag)."""
1109
+ in_windows_payload = False
1110
+ # Env assignments strip UNBOUNDED before the loop (interrogate round
1111
+ # 13: `X1=1 … X19=1 hcloud …` executes — assignments are linear, no
1112
+ # nesting, so no budget is charged).
1113
+ while tokens and re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", str(tokens[0])):
1114
+ tokens = tokens[1:]
1115
+ for _ in range(18):
1116
+ if not tokens:
1117
+ return None, in_windows_payload
1118
+ first = tokens[0].lower()
1119
+ # `-c`, `-lc`, `-xc` … any option cluster ending in c takes the
1120
+ # script; the script argument's `\"` pairs are span-internal
1121
+ # escapes, resolved HERE (consumption point). When the script is
1122
+ # ITSELF a wrapper head (`bash -c bash -c '…'` — the flattened
1123
+ # join of the real `bash -c "bash -c '…'"` nesting), the tail
1124
+ # tokens are concatenated and unwrapping continues (fail-closed).
1125
+ if first in SHELL_FIRST and len(tokens) > 2 and re.match(r"^-[a-z]*c$", tokens[1], re.I):
1126
+ script_tokens = split_tokens(str(tokens[2]).replace('\\"', '"').replace('\\\\', '\\'))
1127
+ script_head = str(script_tokens[0] or "").lower() if script_tokens else ""
1128
+ head_is_wrapperish = (
1129
+ script_head in SHELL_FIRST
1130
+ or script_head == "eval"
1131
+ or script_head in COMMAND_PREFIXES
1132
+ or _windows_script_arg_at(script_tokens, 0) is not None
1133
+ or (script_tokens and _is_hcloud_head(script_tokens[0]))
1134
+ )
1135
+ if head_is_wrapperish:
1136
+ tokens = script_tokens + [str(t) for t in tokens[3:]]
1137
+ continue
1138
+ tokens = script_tokens
1139
+ continue
1140
+ # Real eval CONCATENATES all its arguments and evaluates the
1141
+ # joined string, so the remaining arguments are always part of the
1142
+ # command (an unquoted `eval cmd /c "hcloud …"` runs the write).
1143
+ if first == "eval" and len(tokens) > 1:
1144
+ script_tokens = split_tokens(str(tokens[1]).replace('\\"', '"').replace('\\\\', '\\'))
1145
+ tokens = script_tokens + [str(t) for t in tokens[2:]]
1146
+ continue
1147
+ # bash/PS function definitions: the NAME follows the keyword before
1148
+ # the body (`function f { hcloud … }`) — strip keyword + name.
1149
+ if first in ("function", "filter") and len(tokens) > 2:
1150
+ tokens = tokens[2:]
1151
+ continue
1152
+ win_script = _windows_script_arg_at(tokens, 0)
1153
+ if win_script is not None:
1154
+ tokens = split_tokens(win_script)
1155
+ in_windows_payload = True
1156
+ continue
1157
+ if is_redirection_token(tokens[0]):
1158
+ tokens = tokens[1:]
1159
+ continue
1160
+ # Round 19 F3/F4: the prefix comparison strips quote-mangling.
1161
+ _nf = re.sub(r"['\"\\$]", "", first)
1162
+ _nb = re.sub(r"['\"\\$]", "", basename_of(tokens[0].lower()))
1163
+ if _nf in COMMAND_PREFIXES or _nb in COMMAND_PREFIXES:
1164
+ prefix = _nf if _nf in COMMAND_PREFIXES else _nb
1165
+ # Locator carve-out: `where hcloud`, `if exist hcloud` probe
1166
+ # the bin's PRESENCE (cmd builtins) — a bare bin with no argv
1167
+ # is the probe shape, not a command; stripping the locator
1168
+ # would hit the empty-args fail-closed and deny a read-only
1169
+ # lookup.
1170
+ if prefix in ("where", "exist", "defined") and len(tokens) == 2 and _is_hcloud_head(tokens[1]):
1171
+ break
1172
+ if prefix == "start":
1173
+ # cmd.exe's `start` consumes an optional quoted TITLE before
1174
+ # the child (`start "t" hcloud …`); quoting is lost in the
1175
+ # token stream, so when the token after start's flags is
1176
+ # not itself a command head and the one after it is, the
1177
+ # title is skipped (fail-closed toward the child).
1178
+ probe = _skip_prefix_args("start", tokens[1:])
1179
+ if len(probe) > 1:
1180
+ def _is_headish(cand_tokens, at):
1181
+ tok = str(cand_tokens[at]).lower()
1182
+ return (
1183
+ _is_hcloud_head(cand_tokens[at])
1184
+ or _windows_script_arg_at(cand_tokens, at) is not None
1185
+ or tok in COMMAND_PREFIXES
1186
+ or tok in SHELL_FIRST
1187
+ or tok == "eval"
1188
+ )
1189
+ if not _is_headish(probe, 0) and _is_headish(probe, 1):
1190
+ tokens = probe[1:]
1191
+ continue
1192
+ # The (lowercased) basename resolves the prefix key for the
1193
+ # value-flag grammar too: a path-qualified `/usr/bin/sudo -u
1194
+ # root hcloud …` must consult sudo's value flags.
1195
+ tokens = _skip_prefix_args(prefix, tokens[1:])
1196
+ continue
1197
+ if re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", tokens[0]):
1198
+ tokens = tokens[1:]
1199
+ continue
1200
+ child = _unwrap_secret_exec(tokens)
1201
+ if child is not None:
1202
+ tokens = child
1203
+ continue
1204
+ child = _unwrap_skill_quality(tokens)
1205
+ if child is not None:
1206
+ tokens = child
1207
+ continue
1208
+ if in_windows_payload and not _is_hcloud_head(tokens[0]):
1209
+ rebased = None
1210
+ for i in range(1, len(tokens)):
1211
+ piece_stream = _hcloud_piece_at(tokens, i)
1212
+ if piece_stream is not None and len(piece_stream) > 1:
1213
+ rebased = piece_stream
1214
+ break
1215
+ if rebased is not None:
1216
+ tokens = rebased
1217
+ continue
1218
+ break
1219
+ if not tokens:
1220
+ return None, in_windows_payload
1221
+ if _is_hcloud_head(tokens[0]):
1222
+ return tokens, in_windows_payload
1223
+ return None, in_windows_payload
1224
+
1225
+
1226
+ def _is_windows_path_word(current):
1227
+ """A word that began as a Windows drive prefix (`X:` or `X:\\…`): every
1228
+ backslash inside it is a path separator, never a POSIX escape. The
1229
+ opening quote is stripped so the check works inside quoted spans."""
1230
+ last_word = current.rsplit(" ", 1)[-1]
1231
+ if last_word[:1] in ("'", '"'):
1232
+ last_word = last_word[1:]
1233
+ return bool(re.match(r"^[A-Za-z]:[\\/]", last_word) or re.match(r"^[A-Za-z]:$", last_word))
1234
+
1235
+
1236
+ def split_shell_segments(text, seps_out=None):
1237
+ """Quote/heredoc-aware segment split mirroring the TS splitShellSegments:
1238
+ separators count only OUTSIDE quotes and heredoc bodies; a trailing
1239
+ backslash joins lines; `$(`, `<(`, backtick, and `)` split too. The rest
1240
+ of a heredoc's STARTING line stays live command text (bash semantics);
1241
+ the body begins at the next newline and ends at the delimiter line."""
1242
+ segments = []
1243
+ current = ""
1244
+ quote = None
1245
+ pending_heredoc = None
1246
+ heredoc_delim = None
1247
+ heredoc_line = ""
1248
+ i, n = 0, len(text)
1249
+ while i < n:
1250
+ ch = text[i]
1251
+ if heredoc_delim is not None:
1252
+ current += ch
1253
+ if ch == "\n":
1254
+ if heredoc_line.strip() == heredoc_delim:
1255
+ heredoc_delim = None
1256
+ segments.append(current)
1257
+ if seps_out is not None:
1258
+ seps_out.append("\n")
1259
+ current = ""
1260
+ heredoc_line = ""
1261
+ else:
1262
+ heredoc_line += ch
1263
+ i += 1
1264
+ continue
1265
+ if quote is not None:
1266
+ if ch == "\\" and i + 1 < n:
1267
+ # Backslash escapes the next char — BOTH chars stay in the
1268
+ # segment (the downstream escape-aware tokenizer can regroup
1269
+ # the span, `bash -c "cmd /c \"hcloud …\""`), EXCEPT the
1270
+ # line continuation: bash removes the \<newline> PAIR at
1271
+ # parser level inside double quotes too (interrogate round
1272
+ # 4: `hcloud ECS "De\<LF>leteServers"` hid the operation
1273
+ # from every shadow); the single-quote span keeps the pair
1274
+ # (literal there).
1275
+ if quote == '"' and text[i + 1] == "\n":
1276
+ i += 2
1277
+ continue
1278
+ current += ch
1279
+ current += text[i + 1]
1280
+ i += 2
1281
+ continue
1282
+ current += ch
1283
+ if ch == quote:
1284
+ quote = None
1285
+ i += 1
1286
+ continue
1287
+ if ch == "\\" and i + 1 < n:
1288
+ # Same drive-path preservation as the quoted branch — and the
1289
+ # line-continuation drop: bash removes the \<newline> PAIR, so
1290
+ # the newline is dropped entirely (interrogate round 4:
1291
+ # `h\<LF>cloud` hid the bin from every shadow — routing, vocab,
1292
+ # and decode all saw a newline inside the token).
1293
+ if text[i + 1] == "\n":
1294
+ i += 2
1295
+ continue
1296
+ current += (ch if _is_windows_path_word(current) else "") + text[i + 1]
1297
+ i += 2
1298
+ continue
1299
+ if ch in "\"'":
1300
+ quote = ch
1301
+ current += ch
1302
+ i += 1
1303
+ continue
1304
+ if ch == "$" and i + 1 < n and text[i + 1] == "(":
1305
+ segments.append(current)
1306
+ if seps_out is not None:
1307
+ seps_out.append("$(")
1308
+ current = ""
1309
+ i += 2
1310
+ continue
1311
+ if ch == "<" and i + 1 < n and text[i + 1] == "(":
1312
+ segments.append(current)
1313
+ if seps_out is not None:
1314
+ seps_out.append("<(")
1315
+ current = ""
1316
+ i += 2
1317
+ continue
1318
+ if ch == ">" and i + 1 < n and text[i + 1] == "(":
1319
+ segments.append(current)
1320
+ if seps_out is not None:
1321
+ seps_out.append(">(")
1322
+ current = ""
1323
+ i += 2
1324
+ continue
1325
+ if ch == "`":
1326
+ segments.append(current)
1327
+ if seps_out is not None:
1328
+ seps_out.append("`")
1329
+ current = ""
1330
+ i += 1
1331
+ continue
1332
+ if ch in ";&|\n\r)":
1333
+ # `&` directly after `>`/`<` is the redirection-dup operator
1334
+ # (`2>&1`, `<&0`) — part of the redirection token, not a
1335
+ # separator (interrogate round 11: `2>&1 bash -c '…'` split
1336
+ # mid-redirection and the script never reached _script_of).
1337
+ if ch == "&" and i > 0 and text[i - 1] in "><":
1338
+ current += ch
1339
+ i += 1
1340
+ continue
1341
+ if ch == "\n" and pending_heredoc is not None:
1342
+ heredoc_delim = pending_heredoc
1343
+ pending_heredoc = None
1344
+ heredoc_line = ""
1345
+ current += ch
1346
+ i += 1
1347
+ continue
1348
+ segments.append(current)
1349
+ if seps_out is not None:
1350
+ seps_out.append(ch)
1351
+ current = ""
1352
+ i += 1
1353
+ continue
1354
+ if ch == "<" and i + 1 < n and text[i + 1] == "<":
1355
+ prev = text[i - 1] if i > 0 else ""
1356
+ at_word_start = i == 0 or prev.isspace() or prev in ";&|\n\r)\"'" or prev.isdigit()
1357
+ if at_word_start:
1358
+ j = i + 2
1359
+ saw_dash = False
1360
+ while j < n and text[j] == "-":
1361
+ saw_dash = True
1362
+ j += 1
1363
+ # bash allows whitespace between the operator and the
1364
+ # delimiter (`<< EOF`).
1365
+ while j < n and text[j] in " \t":
1366
+ j += 1
1367
+ delim_quote = ""
1368
+ if j < n and text[j] in "\"'":
1369
+ delim_quote = text[j]
1370
+ j += 1
1371
+ # A backslash-escaped delimiter (`<<\EOF`) and a
1372
+ # `$`-prefixed one (`<<$EOF`, `<<${EOF}`) open heredocs
1373
+ # too — the escaped/expanded word is the delimiter bash
1374
+ # waits for; fail-closed, the raw word serves.
1375
+ delim = ""
1376
+ if j < n and text[j] == "\\":
1377
+ j += 1
1378
+ k2 = j
1379
+ while k2 < n and re.match(r"[A-Za-z0-9_]", text[k2]):
1380
+ k2 += 1
1381
+ delim = text[j:k2] or "\\"
1382
+ j = k2
1383
+ elif j < n and text[j] == "$":
1384
+ delim = "$"
1385
+ j += 1
1386
+ if j < n and text[j] == "{":
1387
+ delim += "{"
1388
+ j += 1
1389
+ k2 = j
1390
+ while k2 < n and re.match(r"[A-Za-z0-9_]", text[k2]):
1391
+ k2 += 1
1392
+ delim += text[j:k2]
1393
+ j = k2
1394
+ if delim.endswith("{"):
1395
+ if j < n and text[j] == "}":
1396
+ delim += "}"
1397
+ j += 1
1398
+ else:
1399
+ delim = ""
1400
+ else:
1401
+ k2 = j
1402
+ while k2 < n and re.match(r"[A-Za-z0-9_]", text[k2]):
1403
+ k2 += 1
1404
+ delim = text[j:k2]
1405
+ j = k2
1406
+ if not delim and j < n and text[j] not in " \t\"'":
1407
+ # A punctuation-leading delimiter (`<< -EOF`,
1408
+ # `<< .D`) — bash's delimiter is the entire
1409
+ # following word; fail-closed, the raw word serves.
1410
+ k2 = j
1411
+ while k2 < n and text[k2] not in " \t\"'":
1412
+ k2 += 1
1413
+ delim = text[j:k2]
1414
+ j = k2
1415
+ if not delim and (delim_quote or saw_dash):
1416
+ # An empty quoted (`<< ""`) or dash-only (`<< -`)
1417
+ # delimiter — never matches a body line: a fail-closed
1418
+ # sentinel delimiter.
1419
+ delim = "\x00heredoc-sentinel"
1420
+ if delim and (delim_quote == "" or (j < n and text[j] == delim_quote)):
1421
+ # Render the marker and align i to the scan position
1422
+ # (the spaced forms double-consumed the last delimiter
1423
+ # char).
1424
+ current += "<<"
1425
+ k3 = i + 2
1426
+ while k3 < n and text[k3] == "-":
1427
+ current += "-"
1428
+ k3 += 1
1429
+ if delim_quote:
1430
+ quote = delim_quote
1431
+ current += delim_quote
1432
+ current += delim
1433
+ i = j
1434
+ pending_heredoc = delim
1435
+ continue
1436
+ current += ch
1437
+ i += 1
1438
+ segments.append(current)
1439
+ if seps_out is None:
1440
+ return [s.strip() for s in segments if s.strip()]
1441
+ seps_out.append("")
1442
+ kept = []
1443
+ kept_seps = []
1444
+ for i, seg in enumerate(segments):
1445
+ t = seg.strip()
1446
+ if t:
1447
+ kept.append(t)
1448
+ kept_seps.append(seps_out[i] if i < len(seps_out) else "")
1449
+ seps_out[:] = kept_seps
1450
+ return kept
1451
+
1452
+
1453
+ # TS routing parity: classification (and its empty-args fail-closed)
1454
+ # engages only when the shadow text carries `hcloud` followed by more
1455
+ # input — a bare trailing `hcloud` mention never classifies. The bin's
1456
+ # TAIL accepts closers (`&('hcloud')`, `(hcloud)`) as well as whitespace.
1457
+ # The RAW text is tested too (TS parity): the shadow strips quotes and
1458
+ # backslashes, which glues the bin into the preceding word
1459
+ # (`cmd /c"hcloud …`, `C:\hcloud.exe …`) while the raw text still
1460
+ # carries the boundary character itself.
1461
+ HCLOUD_ROUTE_RE = re.compile(r"(^|[^a-z0-9.-])hcloud(\.exe)?[\s)\]}'\"<]", re.I)
1462
+ # The BROAD routing tail (the TS broadRouted twin, interrogate round 8): also
1463
+ # `;`, `&`, `|`, `>`, and end-of-string, so `xargs hcloud` at EOF and
1464
+ # glued-separator bins route for the over-cap latency guard below.
1465
+ HCLOUD_ROUTE_BROAD_RE = re.compile(r"(^|[^a-z0-9.-])hcloud(\.exe)?([\s)\]}'\";&|<>]|$)", re.I)
1466
+
1467
+ WRITE_BLOCK_REASON = (
1468
+ "unapproved Huawei Cloud write operations must be planned first and explicitly approved by the user."
1469
+ )
1470
+ EMPTY_ARGS_REASON = (
1471
+ "empty hcloud command arguments are not executable (malformed or truncated payload); write the command in plain form."
1472
+ )
1473
+
1474
+
1475
+ def _stripped_write_deny(stripped, argv):
1476
+ """Write-gate vocabulary for one hcloud-leading token stream: local
1477
+ help/version exemption, configure/OBS util subcommands, then the
1478
+ write/read prefix test on the quote-stripped operation. Dash tokens
1479
+ are filtered BEFORE the operation slot (TS commandOperation's
1480
+ nonFlags parity) — a flag between the service and the feeder word
1481
+ must not mask the operation."""
1482
+ if any(t.lower() in ("--help", "-h", "help", "version", "--version") for t in stripped[1:]):
1483
+ return False
1484
+ if not argv:
1485
+ return False
1486
+ non_flags = [_peel_glued_redirect(t) for t in argv if not str(t).startswith("-")]
1487
+ service = strip_shell_quotes(non_flags[0] if non_flags else argv[0])
1488
+ operation = strip_shell_quotes(non_flags[1]) if len(non_flags) > 1 else service
1489
+ if service.lower() == "configure" and BLOCKED_CONFIGURE_SUBCOMMANDS and operation.lower() in BLOCKED_CONFIGURE_SUBCOMMANDS:
1490
+ return True
1491
+ if service.lower() == "obs" and operation.lower() in OBSUTIL_WRITES:
1492
+ return True
1493
+ # The read exemption anchors at the operation token's START via
1494
+ # re.match (interrogate round 1 — TS hasReadPrefix's ^prefix parity;
1495
+ # \b at position 0 is equivalent): a write-prefixed operation with an
1496
+ # embedded read word (`Update-Show-x`) is the write it is on both
1497
+ # layers. The exact-name arm (READ_OPERATION_EXCEPTIONS) additionally
1498
+ # exempts query-result operations whose head word is a write prefix
1499
+ # (MigrateResults/ImportResult). Unavailable vocabulary cannot prove a
1500
+ # read — the exemption does not apply (fail-closed, the empty-list
1501
+ # parity: TS hasReadPrefix over [] is always false).
1502
+ read_exempt = (READ_OPERATION_RE is not None and READ_OPERATION_RE.match(operation)) or (
1503
+ operation.lower() in READ_OPERATION_EXCEPTIONS
1504
+ )
1505
+ return bool(WRITE_OPERATION_RE.search(operation) and not read_exempt)
1506
+
1507
+
1508
+ def _classify_leading(stripped, argv, routed):
1509
+ """Verdict reason (or None) for one hcloud-leading token stream: the
1510
+ empty-args fail-closed (an unwrapped stream that is JUST the bin with
1511
+ no argv — e.g. `bash -c hcloud ECS Delete`, where real bash runs bare
1512
+ `hcloud` — is not an executable read; the argv is POST-merge so an
1513
+ `xargs hcloud` segment fed by a pipe classifies its feeder instead of
1514
+ denying; gated on routing so a bare trailing `hcloud` mention stays
1515
+ allowed), then the write-gate vocabulary."""
1516
+ if routed and len(stripped) == 1 and not argv:
1517
+ return EMPTY_ARGS_REASON
1518
+ return WRITE_BLOCK_REASON if _stripped_write_deny(stripped, argv) else None
1519
+
1520
+
1521
+ def _heredoc_script_text(segment):
1522
+ """The body of a heredoc/herestring a SHELL bin reads as its script
1523
+ (interrogate round 11: `bash <<EOF\\n"hcl"oud ECS Delete\\nEOF` executes
1524
+ the body — the -c machinery never fires without the flag). Round 12
1525
+ completions: the head's FIRST word (after optional redirections) must
1526
+ be the shell bin — flags and stdin-redirects may sit between it and
1527
+ the marker (`bash -s <<EOF`, `bash < in <<EOF`), and an
1528
+ argument-position shell word (`echo sh <<EOF`) does NOT make the body
1529
+ a script; the marker line may carry trailing live text (`bash <<EOF
1530
+ 2>/dev/null`, `bash <<EOF; echo hi`); the delimiter may be
1531
+ double-quoted. Mirrored by heredocScriptText in classify-text.ts."""
1532
+ m = re.search(r"<<<?", segment)
1533
+ if m is None:
1534
+ return None
1535
+ # Round 15 C-A: prefixes/env assignments/redirections may sit before
1536
+ # the shell head (`env bash <<EOF`, `X=1 bash <<EOF`, `timeout 5 bash
1537
+ # <<EOF`, `< in bash <<EOF`) — strip them with the walk's own probe
1538
+ # grammar (prefix + value-flag aware; a greedy regex ate the shell word
1539
+ # as a prefix argument). The head's first non-strippable word must be
1540
+ # the shell bin; an argument-position shell word (`echo sh <<EOF`)
1541
+ # does not make the body a script.
1542
+ head_probe = split_tokens(segment[: m.start()])
1543
+ for _ in range(18):
1544
+ if not head_probe:
1545
+ break
1546
+ head_tok = str(head_probe[0])
1547
+ if is_redirection_token(head_tok):
1548
+ # A BARE operator carries its operand as the NEXT token.
1549
+ head_probe = head_probe[2:] if re.match(r"^[<>]&?$", head_tok) else head_probe[1:]
1550
+ continue
1551
+ if re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", head_tok):
1552
+ head_probe = head_probe[1:]
1553
+ continue
1554
+ # Round 19 F2: the prefix comparison strips quote-mangling.
1555
+ head_lower = re.sub(r"['\"\\$]", "", head_tok.lower())
1556
+ head_base = basename_of(head_lower)
1557
+ if head_lower in COMMAND_PREFIXES or head_base in COMMAND_PREFIXES:
1558
+ head_probe = _skip_prefix_args(head_base or head_lower, head_probe[1:])
1559
+ continue
1560
+ break
1561
+ # Round 16 C1: closed-quote mid-token mangling (`ba'sh'`) — strip
1562
+ # quotes/backslashes/dollars from the head word before matching.
1563
+ if not head_probe or not re.match(
1564
+ r"^(bash|sh|zsh|dash)(\.exe)?$",
1565
+ re.sub(r"['\"\\$]", "", basename_of(str(head_probe[0]).lower())),
1566
+ ):
1567
+ return None
1568
+ rest = segment[m.start():]
1569
+ hs = re.match(r"^<<<\s*(.+)$", rest)
1570
+ if hs:
1571
+ # The herestring word is ONE argv-ish blob bash parses as a script:
1572
+ # strip the edge quotes so the walk's tokenizers see the command.
1573
+ return re.sub(r"^['\"]|['\"]$", "", hs.group(1))
1574
+ mm = re.match(r"^<<-?\s*(['\"]?)([A-Za-z0-9_]+)\1?[^\n]*\n", rest)
1575
+ if not mm:
1576
+ return None
1577
+ delim = mm.group(2)
1578
+ body = rest[mm.end():]
1579
+ end = body.find("\n" + delim)
1580
+ return body if end < 0 else body[:end]
1581
+
1582
+
1583
+ def _interpreter_system_commands(code):
1584
+ """The shell command(s) embedded in interpreter code via system("…") /
1585
+ os.system('…') (interrogate rounds 12-13) — ALL matches at STATEMENT
1586
+ position (preceded by start/;/newline/} — ``print("system('…')")`` is
1587
+ a printed string, not a call), joined with ';' so the walk classifies
1588
+ each as its own segment. Direct-string form only; variable
1589
+ indirection and other invocation APIs are the documented residual —
1590
+ for those, the deny-opaque gate is the closure. Mirrored by
1591
+ interpreterSystemCommands in classify-text.ts."""
1592
+ commands = []
1593
+ for m in re.finditer(r"(?:^|[;\n}])\s*(?:os\.)?system\(\s*(['\"])([\s\S]*?)\1\s*\)", code):
1594
+ commands.append(m.group(2))
1595
+ return ";\n".join(commands) if commands else None
1596
+
1597
+
1598
+ def _normalize_flag_token(token):
1599
+ """Round 16 C4: closed-quote-mangled code flags (`-'c'`) — strip
1600
+ quotes/backslashes/dollars from a flag token before the code-flag
1601
+ class tests (the word-gluing doctrine). Mirrored by
1602
+ normalizeFlagToken in classify-text.ts."""
1603
+ return re.sub(r"['\"\\$]", "", str(token))
1604
+
1605
+
1606
+ def _interpreter_head_of(head):
1607
+ """Interpreter head normalization (interrogate round 13): basename +
1608
+ version-suffix collapse — python3.11 -> python, gawk/mawk/nawk -> awk,
1609
+ perl5 -> perl, nodejs -> node, raku -> ruby. Mirrored by
1610
+ interpreterHeadOf in classify-text.ts."""
1611
+ # Round 15 C-B: closed-quote mangling (`pyth'on3'`) — strip quotes,
1612
+ # backslashes, and dollars before matching (the round-9 word-gluing
1613
+ # doctrine).
1614
+ h = re.sub(r"[\d.]+$", "", re.sub(r"['\"\\$]", "", str(head).lower()))
1615
+ if re.match(r"^(python|pypy)$", h):
1616
+ return "python"
1617
+ if h == "perl":
1618
+ return "perl"
1619
+ if re.match(r"^(ruby|raku)$", h):
1620
+ return "ruby"
1621
+ if h == "node":
1622
+ return "node"
1623
+ if re.match(r"^(awk|gawk|mawk|nawk)$", h):
1624
+ return "awk"
1625
+ return None
1626
+
1627
+
1628
+ OPAQUE_BINS = (
1629
+ "hcloud",
1630
+ "hcloud.exe",
1631
+ "huaweicloud-devkit",
1632
+ "setup-cli.js",
1633
+ "setup-cli.mjs",
1634
+ "setup-cli.ts",
1635
+ "setup-cli.cjs",
1636
+ "setup.cjs",
1637
+ )
1638
+
1639
+
1640
+ def _opaque_word_in(text, bin_name):
1641
+ return re.search(r"(^|[^a-z0-9.-])" + re.escape(bin_name) + r"([^a-z0-9.-]|$)", text, re.I) is not None
1642
+
1643
+
1644
+ def _leading_segment_probe(tokens):
1645
+ """The effective head stream after stripping redirections, env
1646
+ assignments, and command-position prefixes (a light probe — NOT
1647
+ _leading_segment_core, which returns None unless the head is hcloud).
1648
+ Round 14's shared shape for the interpreter-code checks."""
1649
+ probe = list(tokens)
1650
+ for _ in range(18):
1651
+ if not probe:
1652
+ break
1653
+ head_tok = str(probe[0])
1654
+ if is_redirection_token(head_tok) or re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", head_tok):
1655
+ probe = probe[1:]
1656
+ continue
1657
+ # Round 19 F4: the prefix comparison strips quote-mangling.
1658
+ head_lower = re.sub(r"['\"\\$]", "", head_tok.lower())
1659
+ head_base = basename_of(head_lower)
1660
+ if head_lower in COMMAND_PREFIXES or head_base in COMMAND_PREFIXES:
1661
+ probe = _skip_prefix_args(head_base or head_lower, probe[1:])
1662
+ continue
1663
+ break
1664
+ return probe, None
1665
+
1666
+
1667
+ def _opaque_carrier_denied(segment, tokens, whole_text):
1668
+ """The DENY-OPAQUE pivot (interrogate round 13, the coordinator's design
1669
+ boundary): enumerating bash's carrier grammar to SEE THROUGH it is
1670
+ non-convergent — the carrier space is unbounded. When the walk hits a
1671
+ context it cannot fully traverse AND one of OUR tokens appears in the
1672
+ line in any walkable form, deny fail-closed with the sanctioned-paths
1673
+ remediation instead of vision. The three opacity signals: (a) FRAGMENTED
1674
+ token (a glued/decoded re-join reveals the bin the raw segment hides),
1675
+ (b) EXPANSION marker ($'/$"/$(/backtick/<(>( anywhere in the payload),
1676
+ (c) INTERPRETER CODE context (a code-flag argument / awk program).
1677
+ Lines with no token stay allowed; plain contiguous tokens inside plain
1678
+ quoting with no markers stay allowed (prose). Mirrored by
1679
+ opaqueCarrierDenied in classify-text.ts."""
1680
+ glued = " ".join(split_tokens_glued(segment))
1681
+ decoded = strip_shell_quotes(decode_ansi_c_spans(segment))
1682
+ # Presence is CONTIGUOUS-includes (round 14 C1: `${X:-hcloud}` — the
1683
+ # wordIn boundary excludes `-`, so the default-expanded token was
1684
+ # invisible; the coordinator's rule is "appears ANYWHERE in the line").
1685
+ present = [
1686
+ b
1687
+ for b in OPAQUE_BINS
1688
+ if b.lower() in segment.lower() or _opaque_word_in(glued, b) or _opaque_word_in(decoded, b)
1689
+ ]
1690
+ if not present:
1691
+ return None
1692
+ fragmented = any(
1693
+ (_opaque_word_in(glued, b) or _opaque_word_in(decoded, b)) and b.lower() not in segment.lower()
1694
+ for b in present
1695
+ )
1696
+ # Round 14 (C1): ${ parameter expansion joins the marker set.
1697
+ marker = re.search(r"\$['\"]|\$\(|\$\{|`|<\(|>\(", whole_text) is not None
1698
+ code_context = False
1699
+ # The effective head: strip redirections/env/prefixes (a light
1700
+ # probe — NOT _leading_segment_core, which returns None unless the
1701
+ # head is hcloud itself).
1702
+ probe = list(tokens)
1703
+ for _ in range(18):
1704
+ if not probe:
1705
+ break
1706
+ head_tok = str(probe[0])
1707
+ if is_redirection_token(head_tok) or re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", head_tok):
1708
+ probe = probe[1:]
1709
+ continue
1710
+ # Round 19 F4: the prefix comparison strips quote-mangling.
1711
+ head_lower = re.sub(r"['\"\\$]", "", head_tok.lower())
1712
+ head_base = basename_of(head_lower)
1713
+ if head_lower in COMMAND_PREFIXES or head_base in COMMAND_PREFIXES:
1714
+ probe = _skip_prefix_args(head_base or head_lower, probe[1:])
1715
+ continue
1716
+ break
1717
+ head = _interpreter_head_of(basename_of(str(probe[0]).lower())) if probe else None
1718
+ if head is not None:
1719
+ rest = [str(t) for t in probe[1:]]
1720
+ if head == "awk":
1721
+ code_context = any(not t.startswith("-") for t in rest) or "-v" in rest or "-f" in rest
1722
+ else:
1723
+ # Round 14 C4: a stdin heredoc (`python3 <<'EOF' … body … EOF`)
1724
+ # is code context too — the body is interpreter code.
1725
+ code_context = (
1726
+ any(
1727
+ (lambda f: re.match(r"^-[a-z]*c[a-z]*$", f, re.I) if head == "python" else (re.match(r"^-[a-z]*e[a-z]*$", f, re.I) or f == "--eval"))(_normalize_flag_token(t))
1728
+ for t in rest
1729
+ )
1730
+ or re.search(r"<<<?", segment) is not None
1731
+ )
1732
+ if not fragmented and not marker and not code_context:
1733
+ return None
1734
+ return (
1735
+ "an opaque command carrier (script/interpreter/exec context) mentions Huawei Cloud "
1736
+ "commands but cannot be safely classified. Write the command in plain form, or use "
1737
+ "the sanctioned MCP paths (huaweicloud_run_readonly_command for reads / "
1738
+ "huaweicloud_run_approved_command for writes)."
1739
+ )
1740
+
1741
+
1742
+ def _script_of(tokens):
1743
+ """The quoted script argument of a shell -c / eval / Windows script
1744
+ wrapper (cmd /c, powershell -Command) token stream, or None."""
1745
+ if not tokens:
1746
+ return None
1747
+ first = tokens[0].lower()
1748
+ base = basename_of(tokens[0]).lower()
1749
+ shell_like = first in SHELL_FIRST or (base != first and base in SHELL_FIRST)
1750
+ if shell_like:
1751
+ # Flags may precede -c (interrogate round 12: `bash -e -c '…'`
1752
+ # executes the script) — skip non-c flag clusters, then require
1753
+ # the c-cluster.
1754
+ i = 1
1755
+ while i < len(tokens):
1756
+ tok = _normalize_flag_token(tokens[i])
1757
+ if re.match(r"^--[a-z-]+$", tok, re.I):
1758
+ i += 1
1759
+ continue
1760
+ # Value-bearing flags FIRST (o is inside [a-bd-z] — the generic
1761
+ # skip must not eat their values): -o pipefail -> skip 2.
1762
+ if re.match(r"^-o$", tok, re.I) or re.match(r"^--option$", tok, re.I):
1763
+ i += 2
1764
+ continue
1765
+ if re.match(r"^-[a-bd-z]+$", tok, re.I):
1766
+ i += 1
1767
+ continue
1768
+ break
1769
+ if i + 1 < len(tokens) and re.match(r"^-[a-z]*c[a-z]*$", _normalize_flag_token(tokens[i]), re.I):
1770
+ script = str(tokens[i + 1]).replace('\\"', '"').replace('\\\\', '\\')
1771
+ # When the script word is ITSELF a bin or wrapper head (the
1772
+ # flattened join of a quoted original), the tail tokens belong
1773
+ # to the same command: return them joined, or the nested scan
1774
+ # sees a bare bin and hits the empty-args guard on a
1775
+ # legitimate read.
1776
+ head_tok = split_tokens(script)[0] if split_tokens(script) else None
1777
+ head_is_commandish = (
1778
+ head_tok is not None
1779
+ and (
1780
+ _is_hcloud_head(head_tok)
1781
+ or str(head_tok).lower() in SHELL_FIRST
1782
+ or str(head_tok).lower() == "eval"
1783
+ or str(head_tok).lower() in COMMAND_PREFIXES
1784
+ )
1785
+ )
1786
+ if head_is_commandish and i + 2 < len(tokens):
1787
+ return " ".join([script] + [str(t) for t in tokens[i + 2:]])
1788
+ return script
1789
+ # eval evaluates the JOIN of all its arguments — the script string
1790
+ # is the whole tail, not just the first word.
1791
+ if first == "eval" and len(tokens) > 1:
1792
+ return " ".join(str(t).replace('\\"', '"').replace('\\\\', '\\') for t in tokens[1:])
1793
+ # watch runs its command arguments as an sh -c SCRIPT (the join of the
1794
+ # words after its own flags — interrogate round 11: `watch -n1
1795
+ # '"hcl"oud ECS Delete'` executes the glued bin through that join).
1796
+ # Round 17 C3: the watch head strips quote-mangling (`wat'ch'`).
1797
+ if re.sub(r"['\"\\$]", "", first) == "watch" and len(tokens) > 1:
1798
+ rest = _skip_prefix_args("watch", tokens[1:])
1799
+ return " ".join(str(t) for t in rest)
1800
+ # Interpreter carriers (interrogate rounds 12-13): the head is
1801
+ # NORMALIZED (_interpreter_head_of — version-suffix collapse, awk
1802
+ # family), benign flags before the code flag are skipped, awk's -v/-f
1803
+ # value flags are skipped, and the flag table is per-interpreter
1804
+ # (perl/ruby/node: -e only — their -c is syntax-check; python: -c).
1805
+ interp = _interpreter_head_of(first)
1806
+ if interp is not None and len(tokens) > 1:
1807
+ i = 1
1808
+ while i < len(tokens) and re.match(r"^-[a-bd-z][a-z]*$", _normalize_flag_token(tokens[i]), re.I):
1809
+ i += 1
1810
+ flag = _normalize_flag_token(tokens[i]) if i < len(tokens) else ""
1811
+ code_flag = (
1812
+ re.match(r"^-[a-z]*c[a-z]*$", flag, re.I)
1813
+ if interp == "python"
1814
+ else (re.match(r"^-[a-z]*e[a-z]*$", flag, re.I) or flag == "--eval")
1815
+ )
1816
+ if code_flag and i + 1 < len(tokens):
1817
+ return _interpreter_system_commands(" ".join(str(t) for t in tokens[i + 1:]))
1818
+ if interp == "awk":
1819
+ j = 1
1820
+ while j < len(tokens):
1821
+ tok = str(tokens[j])
1822
+ if tok in ("-v", "-f", "--file", "--assign"):
1823
+ j += 2
1824
+ continue
1825
+ if re.match(r"^-[a-z]+$", tok, re.I):
1826
+ j += 1
1827
+ continue
1828
+ break
1829
+ if j < len(tokens):
1830
+ return _interpreter_system_commands(str(tokens[j]))
1831
+ return _windows_script_arg_at(tokens, 0)
1832
+
1833
+
1834
+ def hcloud_write_blocked(text, depth=0, routed=None, inherited_feeder=None, saw=None):
1835
+ """Block reason (or None to allow) when any hcloud-leading command
1836
+ segment in the payload carries a write operation and no read prefix.
1837
+ `saw` (a one-element list) accumulates whether ANY level of the walk
1838
+ ever saw our bin at a classifiable command position — the deny-opaque
1839
+ gate's traversal signal (interrogate round 13).
1840
+ Positional like the TS layer; nested `bash -c`/`eval` scripts re-scan
1841
+ recursively with the TOP-LEVEL routing verdict threaded through (TS
1842
+ computes routing once at text entry); `xargs hcloud` merges the
1843
+ preceding piped segment's tokens as candidate operations; OBS util
1844
+ subcommands classify through the same write list; `hcloud configure
1845
+ show/get/list/…` is a credential read (policy vocabulary, TS parity)."""
1846
+ if saw is None:
1847
+ saw = [False]
1848
+ if not WRITE_OPERATION_RE:
1849
+ # Fail-closed (interrogate round 1): an unavailable write
1850
+ # vocabulary must not reopen PLAIN writes while their mangled
1851
+ # forms still deny through the obfuscation gate — an incoherent
1852
+ # posture where only the honest spelling sails through.
1853
+ # Invocation-scoped (interrogate rounds 2-3): the leading-segment
1854
+ # walk runs UNCONDITIONALLY — the narrow routing tail
1855
+ # ([\s)\]}'\"]) missed `xargs hcloud;|>&&&` tails (round 3), and
1856
+ # the walk itself is the scope (prose never yields a leading
1857
+ # segment). Prose that merely MENTIONS hcloud stays allowed; a
1858
+ # corrupt policy.json must not block every Bash command that names
1859
+ # the CLI. hcloud-leading invocations all deny, reads and --help
1860
+ # included: with no vocabulary there is nothing to prove safety
1861
+ # with (the recorded trade). The length cap mirrors the healthy
1862
+ # gate's (no routing to scope it — every oversized payload denies).
1863
+ if len(text) > 262144:
1864
+ return "command payload too large to classify safely; denied fail-closed"
1865
+ leading = [
1866
+ segment
1867
+ for segment in split_shell_segments(text)
1868
+ if hcloud_leading_segment(split_tokens(segment)) is not None
1869
+ ] or ([text] if hcloud_leading_segment(split_tokens(text)) is not None else [])
1870
+ if leading:
1871
+ return (
1872
+ "the safety policy could not be loaded or carries no write vocabulary; "
1873
+ "hcloud commands are denied fail-closed. Fix or reinstall the plugin's "
1874
+ "safety/policy.json."
1875
+ )
1876
+ return None
1877
+ if routed is None:
1878
+ routed = (
1879
+ HCLOUD_ROUTE_RE.search(strip_shell_quotes(text)) is not None
1880
+ or HCLOUD_ROUTE_RE.search(text) is not None
1881
+ )
1882
+ # Over-cap latency guard (interrogate round 8): a benign-looking
1883
+ # oversized payload paid the full segment/token walk here (measured
1884
+ # 32s+ on 10 MB — a harness timeout swallows the verdict, which
1885
+ # reads as allow) while the TS twin gates entry on routing and never
1886
+ # segments. Every hcloud-head spelling the tokenizers admit also
1887
+ # appears contiguously in the raw or stripped text (the shadow drops
1888
+ # exactly the characters the tokenizers strip — recorded round-9
1889
+ # exceptions: the head predicates' paren-stripped and BOM-glued
1890
+ # normalized spellings, both non-executable in bash), so a payload
1891
+ # that is over-cap AND broad-unrouted has nothing this walk can
1892
+ # classify — the expansion-bearing and routed over-cap shapes
1893
+ # already denied at evaluate()'s head cap.
1894
+ if len(text) > 262144 and not (
1895
+ HCLOUD_ROUTE_BROAD_RE.search(strip_shell_quotes(text)) is not None
1896
+ or HCLOUD_ROUTE_BROAD_RE.search(text) is not None
1897
+ ):
1898
+ return None
1899
+ # Length cap (TS parity): a routed payload past 256 KiB cannot
1900
+ # execute through any wrapper chain, and classifying pathological
1901
+ # nests at that size costs minutes — a hook DoS. Fail-closed.
1902
+ if routed and len(text) > 262144:
1903
+ return "command payload too large to classify safely; denied fail-closed"
1904
+ # (the routed value computed above is authoritative — the historical
1905
+ # second recompute here was dead code, removed in interrogate
1906
+ # round 9)
1907
+ segment_seps = []
1908
+ segments = split_shell_segments(text, segment_seps)
1909
+ saw_leading = False
1910
+ # The glued walk's scope (interrogate round 11): BROAD routing — the
1911
+ # narrow tail's end-of-string exclusion left `echo ECS Delete | xargs
1912
+ # "hcl"oud` (the glued bin at EOF) outside the glued fallback entirely.
1913
+ # Narrow implies broad, so this is a superset of `routed`; the
1914
+ # empty-args arm stays narrow-gated (the pinned bare-hcloud allows).
1915
+ glued_scope = (
1916
+ HCLOUD_ROUTE_BROAD_RE.search(strip_shell_quotes(text)) is not None
1917
+ or HCLOUD_ROUTE_BROAD_RE.search(text) is not None
1918
+ )
1919
+ for s, segment in enumerate(segments):
1920
+ # Per-segment traversal scope (interrogate round 14 C2): a read
1921
+ # classified in ONE segment's subtree must not switch the opaque
1922
+ # gate off for LATER segments. seg_saw resets per segment and ORs
1923
+ # into the caller's accumulator.
1924
+ seg_saw = [False]
1925
+ tokens = split_tokens(segment)
1926
+ # Interpreter-code opacity, UNCONDITIONAL (round 14 C2's leak
1927
+ # within the code itself: `system("read"); subprocess.run("write")`
1928
+ # — the system()-read masked the subprocess write). Code context is
1929
+ # definitionally opaque: ANY token in the segment denies, before
1930
+ # any extraction (the -c/-e flag, an awk program, or a stdin
1931
+ # heredoc — round 14 C4: `python3 <<'EOF'`).
1932
+ _probe_stream, _ = _leading_segment_probe(tokens)
1933
+ _interp = _interpreter_head_of(basename_of(str(_probe_stream[0]).lower())) if _probe_stream else None
1934
+ if _interp is not None:
1935
+ _rest = [str(t) for t in _probe_stream[1:]]
1936
+ _code_form = (
1937
+ any(
1938
+ (lambda f: re.match(r"^-[a-z]*c[a-z]*$", f, re.I) if _interp == "python" else (re.match(r"^-[a-z]*e[a-z]*$", f, re.I) or f == "--eval"))(_normalize_flag_token(t))
1939
+ for t in _rest
1940
+ )
1941
+ or (_interp == "awk" and any(not t.startswith("-") for t in _rest))
1942
+ or re.search(r"<<<?", segment)
1943
+ )
1944
+ if _code_form:
1945
+ _opaque = _opaque_carrier_denied(segment, tokens, segment)
1946
+ if _opaque:
1947
+ return _opaque
1948
+ # Nested scripts, BEFORE unwrapping flattens them. Wrapper
1949
+ # unwrapping runs to a FIXPOINT (same-wrapper compositions with
1950
+ # compound inner scripts reach their innermost script too). The
1951
+ # depth budget is 18 (TS parity, one past the Linux
1952
+ # executability ceiling): adversarial nests five-plus deep
1953
+ # genuinely execute, and beyond the budget the unwrap path
1954
+ # re-tokenizes WITHOUT re-splitting `;` — the write launders.
1955
+ carrier_traversed = False
1956
+ if depth < 18:
1957
+ candidates = [tokens]
1958
+ cursor = tokens
1959
+ for _ in range(4):
1960
+ nxt = _unwrap_secret_exec(cursor)
1961
+ if nxt is None:
1962
+ nxt = _unwrap_skill_quality(cursor)
1963
+ if nxt is None:
1964
+ break
1965
+ candidates.append(nxt)
1966
+ cursor = nxt
1967
+ # A command-position prefix in front of a shell head
1968
+ # (`sudo bash -c "…"`) hides the script from _script_of's
1969
+ # head check — probe PAST the prefixes (and their value
1970
+ # flags) so the nested segment/feeder semantics fire.
1971
+ probe = list(tokens)
1972
+ for _ in range(18):
1973
+ if not probe:
1974
+ break
1975
+ head = str(probe[0]).lower()
1976
+ base = basename_of(head)
1977
+ is_env_assignment = bool(re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", str(probe[0])))
1978
+ # Redirection tokens strip too (interrogate round 11):
1979
+ # `2>/dev/null bash -c '…'` never reached _script_of while
1980
+ # bash executes the script.
1981
+ if is_redirection_token(str(probe[0])):
1982
+ probe = probe[1:]
1983
+ elif (
1984
+ re.sub(r"['\"\\$]", "", head) not in COMMAND_PREFIXES
1985
+ and re.sub(r"['\"\\$]", "", base) not in COMMAND_PREFIXES
1986
+ and not is_env_assignment
1987
+ ):
1988
+ break
1989
+ elif is_env_assignment:
1990
+ probe = probe[1:]
1991
+ else:
1992
+ probe = _skip_prefix_args(
1993
+ re.sub(r"['\"\\$]", "", base) or re.sub(r"['\"\\$]", "", head), probe[1:]
1994
+ )
1995
+ candidates.append(probe)
1996
+ for candidate in candidates:
1997
+ nested = _script_of(candidate)
1998
+ if nested is not None:
1999
+ # The nested script's stdin is THIS segment's stdin: a
2000
+ # piped context feeds it, so the outer feeder threads
2001
+ # down (an xargs inside the script inherits the pipe).
2002
+ nested_feeder = split_tokens(segments[s - 1])[1:] if s > 0 else inherited_feeder
2003
+ reason = hcloud_write_blocked(nested, depth + 1, routed, nested_feeder, seg_saw)
2004
+ if reason:
2005
+ return reason
2006
+ carrier_traversed = True
2007
+ # (The round-12 SCRIPT-SHADOW pass was REMOVED in the
2008
+ # round-13 pivot: it un-quoted PROSE inside carrier
2009
+ # scripts — `bash -c 'echo "step1; hcloud …"'` denied a
2010
+ # benign echo — and its purpose (the deep-nest `'\''`
2011
+ # idiom) is closed by the deny-opaque gate's
2012
+ # fragmented-token signal, with strictly less
2013
+ # false-positive surface.)
2014
+ # Heredoc/herestring SCRIPT bodies (interrogate round 11): a
2015
+ # shell bin reading its script from stdin — `bash <<EOF
2016
+ # <body> EOF` executes the body; the -c machinery never fires
2017
+ # without the flag. The segment keeps the body inline
2018
+ # (split_shell_segments models heredocs).
2019
+ heredoc_script = _heredoc_script_text(segment)
2020
+ if heredoc_script is not None:
2021
+ nested_feeder = split_tokens(segments[s - 1])[1:] if s > 0 else inherited_feeder
2022
+ reason = hcloud_write_blocked(heredoc_script, depth + 1, routed, nested_feeder, seg_saw)
2023
+ if reason:
2024
+ return reason
2025
+ carrier_traversed = True
2026
+ # A DANGLING heredoc marker (interrogate round 12): `bash
2027
+ # <<EOF; echo hi` splits the segment at the `;` mid-line, so
2028
+ # the marker segment carries no body — bash starts the body at
2029
+ # the LINE's newline, which lands in the NEXT segment. The
2030
+ # next segment's text after its first newline, up to the
2031
+ # delimiter line, is the script.
2032
+ dangling = re.search(r"<<-?\s*(['\"]?)([A-Za-z0-9_]+)\1?[^\n]*$", segment)
2033
+ if dangling is not None and s + 1 < len(segments):
2034
+ # Round 15 C-A: the probe grammar (prefix/env/redirection
2035
+ # aware — a greedy regex ate the shell word).
2036
+ dangling_probe = split_tokens(segment[: dangling.start()])
2037
+ for _ in range(18):
2038
+ if not dangling_probe:
2039
+ break
2040
+ dtok = str(dangling_probe[0])
2041
+ if is_redirection_token(dtok):
2042
+ dangling_probe = dangling_probe[2:] if re.match(r"^[<>]&?$", dtok) else dangling_probe[1:]
2043
+ continue
2044
+ if re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", dtok):
2045
+ dangling_probe = dangling_probe[1:]
2046
+ continue
2047
+ dlower = dtok.lower()
2048
+ dbase = basename_of(dlower)
2049
+ if dlower in COMMAND_PREFIXES or dbase in COMMAND_PREFIXES:
2050
+ dangling_probe = _skip_prefix_args(dbase or dlower, dangling_probe[1:])
2051
+ continue
2052
+ break
2053
+ if not dangling_probe or not re.match(
2054
+ r"^(bash|sh|zsh|dash)(\.exe)?$",
2055
+ re.sub(r"['\"\\$]", "", basename_of(str(dangling_probe[0]).lower())),
2056
+ ):
2057
+ continue
2058
+ if True:
2059
+ delim = dangling.group(2)
2060
+ nxt = segments[s + 1]
2061
+ nl = nxt.find("\n")
2062
+ if nl >= 0:
2063
+ body = nxt[nl + 1:]
2064
+ end = body.find("\n" + delim)
2065
+ if end >= 0:
2066
+ reason = hcloud_write_blocked(body[:end], depth + 1, routed, None, seg_saw)
2067
+ if reason:
2068
+ return reason
2069
+ carrier_traversed = True
2070
+ # find -exec/-execdir carriers (interrogate rounds 12-13): the
2071
+ # argv between the flag and the `\;`/`;`/`+` terminator is a
2072
+ # command position — extracted from BOTH tokenizations (the
2073
+ # plain one fragments a glued bin) and GATED ON THE HEAD BEING
2074
+ # FIND (round 13: `echo -exec hcloud …` is an echo argument,
2075
+ # not a carrier — the over-deny class).
2076
+ head_probe = list(tokens)
2077
+ for _ in range(18):
2078
+ if not head_probe:
2079
+ break
2080
+ head_tok = str(head_probe[0])
2081
+ if is_redirection_token(head_tok) or re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", head_tok):
2082
+ head_probe = head_probe[1:]
2083
+ continue
2084
+ head_lower = head_tok.lower()
2085
+ head_base = basename_of(head_lower)
2086
+ if head_lower in COMMAND_PREFIXES or head_base in COMMAND_PREFIXES:
2087
+ head_probe = _skip_prefix_args(head_base or head_lower, head_probe[1:])
2088
+ continue
2089
+ break
2090
+ head_is_find = head_probe and basename_of(str(head_probe[0]).lower()) == "find"
2091
+ if head_is_find:
2092
+ for token_source in (tokens, split_tokens_glued(segment)):
2093
+ for e, t in enumerate(token_source):
2094
+ if str(t).lower() in ("-exec", "-execdir"):
2095
+ end = next(
2096
+ (k for k in range(e + 1, len(token_source)) if str(token_source[k]) in ("\\;", ";", "+")),
2097
+ len(token_source),
2098
+ )
2099
+ payload = token_source[e + 1:end]
2100
+ if payload:
2101
+ reason = hcloud_write_blocked(" ".join(str(x) for x in payload), depth + 1, routed, None, seg_saw)
2102
+ if reason:
2103
+ return reason
2104
+ carrier_traversed = True
2105
+ # Round 16 C3 + round 17 C4/C5/C6: a pipe-fed SHELL or INTERPRETER
2106
+ # reads its stdin as a SCRIPT/CODE — the xargs-feeder doctrine,
2107
+ # completed: the WALK-BACK through pass-through middles, PER-WORD
2108
+ # feeder classification (printf's format arg precedes the data),
2109
+ # and INTERPRETER consumers (the code-context deny when the
2110
+ # walked-back feeder carries our token).
2111
+ _pipe_pass_through = {"cat", "sort", "tee", "head", "tail", "uniq", "wc", "tr"}
2112
+
2113
+ # Round 18 C1/C2/C3: the head comparison uses the recognition
2114
+ # grammar — quote-strip + basename + prefix/env probe; CONTROL
2115
+ # heads flow through BEFORE the probe (the pipe data reaches the
2116
+ # body; probing would strip the `if` and misread `true`).
2117
+ _pipe_control = {
2118
+ "if", "while", "until", "for", "case", "then", "do", "else",
2119
+ "elif", "fi", "done", "esac", "{", "}", "(", ")", "!",
2120
+ }
2121
+
2122
+ def _pipe_walk_back_feeder():
2123
+ k = s - 1
2124
+ while k >= 0:
2125
+ seg_toks = split_tokens(segments[k])
2126
+ raw_head = basename_of(re.sub(r"['\"\\$]", "", str(seg_toks[0] or "").lower())) if seg_toks else ""
2127
+ if raw_head in _pipe_control:
2128
+ k -= 1
2129
+ continue
2130
+ # Prefix/env probe (bounded) — `command cat`, `env cat`;
2131
+ # the prefix comparison strips quote-mangling (round 19 F1).
2132
+ probe = list(seg_toks)
2133
+ for _ in range(18):
2134
+ if not probe:
2135
+ break
2136
+ t0 = str(probe[0])
2137
+ if is_redirection_token(t0) or re.match(r"^[A-Za-z_][A-Za-z0-9_]*=", t0):
2138
+ probe = probe[1:]
2139
+ continue
2140
+ lower = re.sub(r"['\"\\$]", "", t0.lower())
2141
+ base = basename_of(lower)
2142
+ if lower in COMMAND_PREFIXES or base in COMMAND_PREFIXES:
2143
+ probe = _skip_prefix_args(base or lower, probe[1:])
2144
+ continue
2145
+ break
2146
+ head = basename_of(re.sub(r"['\"\\$]", "", str(probe[0] or "").lower())) if probe else ""
2147
+ if head in _pipe_pass_through or head in _pipe_control:
2148
+ k -= 1
2149
+ continue
2150
+ return [str(t) for t in probe[1:]]
2151
+ return []
2152
+
2153
+ _shell_stream, _ = _leading_segment_probe(tokens)
2154
+ _consumer_head = (
2155
+ re.sub(r"['\"\\$]", "", basename_of(str(_shell_stream[0]).lower())) if _shell_stream else ""
2156
+ )
2157
+ _shell_head_ok = bool(_shell_stream and re.match(r"^(bash|sh|zsh|dash)(\.exe)?$", _consumer_head))
2158
+ _interp_head_ok = _interpreter_head_of(_consumer_head) if _consumer_head else None
2159
+ if (
2160
+ (_shell_head_ok or _interp_head_ok)
2161
+ and s > 0
2162
+ and not any(re.match(r"^-[a-z]*c$", _normalize_flag_token(t), re.I) for t in tokens[1:])
2163
+ and not re.search(r"<<<?", segment)
2164
+ ):
2165
+ _feeder_args = _pipe_walk_back_feeder()
2166
+ if _interp_head_ok:
2167
+ _feeder_text = " ".join(_feeder_args)
2168
+ if any(b.lower() in _feeder_text.lower() for b in OPAQUE_BINS):
2169
+ return (
2170
+ "an opaque command carrier (script/interpreter/exec context) mentions Huawei Cloud "
2171
+ "commands but cannot be safely classified. Write the command in plain form, or use "
2172
+ "the sanctioned MCP paths (huaweicloud_run_readonly_command for reads / "
2173
+ "huaweicloud_run_approved_command for writes)."
2174
+ )
2175
+ elif _shell_head_ok:
2176
+ _feeder_words = [
2177
+ re.sub(r"^['\"]|['\"]$", "", w) for t in _feeder_args for w in str(t).split()
2178
+ ]
2179
+ for word in _feeder_words:
2180
+ _pv = hcloud_write_blocked("hcloud " + str(word), depth + 1, routed, None, seg_saw)
2181
+ if _pv:
2182
+ return _pv
2183
+ if _feeder_args:
2184
+ reason = hcloud_write_blocked(" ".join(str(t) for t in _feeder_args), depth + 1, routed, None, seg_saw)
2185
+ if reason:
2186
+ return reason
2187
+ _inline_nl = segment.find("\n")
2188
+ if _inline_nl >= 0:
2189
+ reason = hcloud_write_blocked(segment[_inline_nl + 1:], depth + 1, routed, None, seg_saw)
2190
+ if reason:
2191
+ return reason
2192
+ stripped = hcloud_leading_segment(tokens)
2193
+ if stripped is None:
2194
+ # Glued-bin fallback, PER SEGMENT (interrogate round 10): bash
2195
+ # glues adjacent quoted spans and word characters into ONE word
2196
+ # — `"hcl"oud ECS Delete` runs hcloud with full argv — while
2197
+ # split_tokens keeps the span/fragment distinction, so a
2198
+ # quote-INITIAL mangled bin never yields a leading token stream.
2199
+ # Tried HERE (not after the loop) so a leading READ in another
2200
+ # segment can never mask a later glued write (round 10's C3) and
2201
+ # the standard xargs machinery keeps handling the segments it
2202
+ # already classifies (the whole-text re-run denied a pinned
2203
+ # xargs allow through the empty-args arm).
2204
+ glued_stripped = None
2205
+ if glued_scope:
2206
+ glued_stripped = hcloud_leading_segment(split_tokens_glued(segment))
2207
+ if glued_stripped is not None:
2208
+ saw[0] = True
2209
+ seg_saw[0] = True
2210
+ glued_argv = [t for t in glued_stripped[1:] if not t.startswith("-")]
2211
+ # Round 16 C2: the expansion SLOT rule on the glued path
2212
+ # (TS parity — `"hcl"oud ${X:-ECS} ${X:-Delete}`
2213
+ # executed while the plain-path-only rule missed it).
2214
+ _gslot_argv = [t for t in glued_stripped[1:] if not str(t).startswith("-")]
2215
+ if any(re.search(r"\$\{", str(t)) for t in _gslot_argv[:2]):
2216
+ _opaque = _opaque_carrier_denied(segment, tokens, segment)
2217
+ if _opaque:
2218
+ return _opaque
2219
+ # Round 17 C2: the xargs head comparison strips
2220
+ # quote-mangling (`x'args'`) on BOTH token streams.
2221
+ segment_has_xargs = any(
2222
+ re.sub(r"['\"\\$]", "", str(t).lower()) == "xargs"
2223
+ or basename_of(re.sub(r"['\"\\$]", "", str(t).lower())) == "xargs"
2224
+ for t in list(tokens) + split_tokens_glued(segment)
2225
+ )
2226
+ if (
2227
+ not glued_argv
2228
+ and s > 0
2229
+ and segment_has_xargs
2230
+ ):
2231
+ # A glued bin the standard machinery never saw, fed
2232
+ # by the pipe (interrogate round 11): the previous
2233
+ # segment's words are the argv — any write-shaped
2234
+ # feeder word denies (the xargs doctrine).
2235
+ feeder_words = [
2236
+ re.sub(r"^['\"]|['\"]$", "", w)
2237
+ for t in _pipe_walk_back_feeder()
2238
+ for w in str(t).split()
2239
+ ]
2240
+ for word in feeder_words:
2241
+ reason = _classify_leading(glued_stripped, [str(word)], routed)
2242
+ if reason:
2243
+ return reason
2244
+ elif (
2245
+ glued_argv
2246
+ and segment_has_xargs
2247
+ and s > 0
2248
+ ):
2249
+ # A glued xargs bin with its OWN argv (interrogate
2250
+ # round 12: `echo DeleteServers | xargs "hcl"oud
2251
+ # ECS` — xargs appends the stdin AFTER the own
2252
+ # args): merge the feeder into the glued argv, the
2253
+ # standard machinery's xargs semantics.
2254
+ feeder_words = [
2255
+ re.sub(r"^['\"]|['\"]$", "", w)
2256
+ for t in _pipe_walk_back_feeder()
2257
+ for w in str(t).split()
2258
+ ]
2259
+ reason = _classify_leading(glued_stripped, glued_argv + feeder_words, routed)
2260
+ if reason:
2261
+ return reason
2262
+ else:
2263
+ reason = _classify_leading(glued_stripped, glued_argv, routed)
2264
+ if reason:
2265
+ return reason
2266
+ # The DENY-OPAQUE gate (interrogate round 13, the pivot): this
2267
+ # segment was NOT a plain-leading hcloud command AND its glued
2268
+ # re-join was not hcloud-leading either (either the standard
2269
+ # machinery classified one of those forms, or the segment
2270
+ # carries something we could not traverse). If our token hides
2271
+ # in it fragmented/marked/code-context form, deny fail-closed.
2272
+ # Round 14 C1: the gate runs UN-gated on glued_scope — the
2273
+ # routing boundary excludes `-`, so `${X:-hcloud} …` (the
2274
+ # default-expanded bin) never routed and the marker signal
2275
+ # never ran. The gate's own signals are the scope.
2276
+ if not seg_saw[0]:
2277
+ opaque_reason = _opaque_carrier_denied(segment, tokens, text)
2278
+ if opaque_reason:
2279
+ return opaque_reason
2280
+ saw[0] = saw[0] or seg_saw[0]
2281
+ continue
2282
+ saw_leading = True
2283
+ saw[0] = True
2284
+ seg_saw[0] = True
2285
+ windows_payload = _LEADING_WINDOWS_PAYLOAD[0]
2286
+ argv = [t for t in stripped[1:] if not t.startswith("-")]
2287
+ # xargs feed: the preceding segment's tokens become argv after the
2288
+ # segment's own arguments.
2289
+ # xargs is detected on the PRE-unwrap segment tokens, the
2290
+ # unwrapped stream, and span tokens whose FIRST word is xargs
2291
+ # (inside a quoted windows payload the whole command is one
2292
+ # token; the child inherits the pipe and executes the merge).
2293
+ def _is_xargs_token(t):
2294
+ # Round 19: the xargs comparison strips quote-mangling
2295
+ # (`x'args'`) — round 17 fixed the GLUED arms' key but this
2296
+ # (the standard path's detector) read the raw token.
2297
+ tl = re.sub(r"['\"\\$]", "", str(t).lower())
2298
+ if tl == "xargs" or basename_of(tl) == "xargs":
2299
+ return True
2300
+ if re.search(r"\s", str(t)):
2301
+ words = split_tokens(str(t))
2302
+ return bool(words) and re.sub(r"['\"\\$]", "", str(words[0]).lower()) == "xargs"
2303
+ return False
2304
+
2305
+ # Trailing redirection feeders: herestring words and a
2306
+ # `<`-terminated segment's NEXT segment are inline-visible feeder
2307
+ # content, same standard as the pipe.
2308
+ herestring_at = -1
2309
+ for ti, t in enumerate(tokens):
2310
+ if re.match(r"^0*<{3,}", str(t)):
2311
+ herestring_at = ti
2312
+ break
2313
+ # A heredoc marker (`<<EOF`, `<<-EOF`, `<< EOF`) — the body words
2314
+ # are stdin feeder content for the xargs-bearing opening segment.
2315
+ heredoc_at = -1
2316
+ for ti, t in enumerate(tokens):
2317
+ if re.match(r"^0*<<-?(?!<)", str(t)):
2318
+ heredoc_at = ti
2319
+ break
2320
+ trailing_redirect = bool(re.search(r"<\s*$", segments[s] or "")) and s + 1 < len(segments)
2321
+ if (
2322
+ any(_is_xargs_token(t) for t in tokens)
2323
+ or any(_is_xargs_token(t) for t in stripped)
2324
+ ) and (s > 0 or inherited_feeder is not None or herestring_at >= 0 or heredoc_at >= 0 or trailing_redirect):
2325
+ # The feeder is the UNION of every visible source: inner
2326
+ # pipe, inherited outer pipe (the script's stdin), herestring
2327
+ # words, and redirection-substitution words. Union is
2328
+ # fail-closed: any write-shaped word reaching the argv denies.
2329
+ # Pipeline WALK-BACK: through control headers, group
2330
+ # braces, and argless pass-through filters the pipe's data
2331
+ # reaches the xargs body (`echo Delete | if true; then xargs
2332
+ # hcloud ECS; fi`); a `;`-separated consuming command stops
2333
+ # the walk.
2334
+ control_head_words = {
2335
+ "if", "while", "until", "for", "case", "then", "do", "else", "elif",
2336
+ "fi", "done", "esac", "{", "}", "(", ")", "!",
2337
+ }
2338
+ pass_through_bins = {"cat", "sort", "tee", "head", "tail", "uniq", "wc", "tr"}
2339
+
2340
+ def _walk_back_feeder():
2341
+ words = []
2342
+ k = s - 1
2343
+ while k >= 0:
2344
+ seg_toks = split_tokens(segments[k])
2345
+ head_tok = str(seg_toks[0] or "").lower() if seg_toks else ""
2346
+ args = [str(t) for t in seg_toks[1:]]
2347
+ # Round 18 C3: the control/pass-through comparison strips
2348
+ # quote-mangling (`i'f'`, `the'n'`).
2349
+ _nh = re.sub(r"['\"\\\\$]", "", head_tok)
2350
+ is_ctrl = _nh in control_head_words or (_nh in pass_through_bins and not args)
2351
+ sep_after = segment_seps[k] if k < len(segment_seps) else ""
2352
+ sep_before = segment_seps[k - 1] if k > 0 and k - 1 < len(segment_seps) else ""
2353
+ # `)` (substitution body) and `>(` (process
2354
+ # substitution) flow like `|`.
2355
+ flows = sep_after in ("|", ")", ">(")
2356
+ if not is_ctrl and not flows:
2357
+ if k == s - 1:
2358
+ return words
2359
+ break
2360
+ words.extend(args)
2361
+ if not is_ctrl and sep_before not in ("|", ")", ">("):
2362
+ break
2363
+ k -= 1
2364
+ return words
2365
+
2366
+ def _expand_words(ts):
2367
+ # xargs splits stdin on IFS: a QUOTED feeder token carries
2368
+ # multiple words — expand every token into its
2369
+ # whitespace-separated words (quotes stripped).
2370
+ out = []
2371
+ for t in ts:
2372
+ for w in str(t).split():
2373
+ out.append(re.sub(r"^['\"]|['\"]$", "", w))
2374
+ return out
2375
+
2376
+ feeder = _expand_words(_walk_back_feeder() + list(inherited_feeder or []))
2377
+ # A BARE `<<<` marker: following tokens are the payload; a
2378
+ # GLUED marker is handled by the redirect-marker branch below.
2379
+ if herestring_at >= 0 and re.match(r"^0*<{3,}$", str(tokens[herestring_at])):
2380
+ feeder = feeder + _expand_words([str(t) for t in tokens[herestring_at + 1:]])
2381
+ if trailing_redirect:
2382
+ feeder = feeder + _expand_words([str(t) for t in split_tokens(segments[s + 1])[1:]])
2383
+ # Placeholders: literal {} / % runs AND the declared -I/--replace
2384
+ # value (any replstr spelling).
2385
+ replstr = None
2386
+ for t in range(len(tokens)):
2387
+ token = str(tokens[t])
2388
+ if token in ("-I", "--replace", "--delimiter") and t + 1 < len(tokens):
2389
+ replstr = str(tokens[t + 1])
2390
+ break
2391
+ m = re.match(r"^(?:-I|--replace(?:=)?|--delimiter=)(.+)$", token)
2392
+ if m:
2393
+ replstr = m.group(1)
2394
+ break
2395
+ # Redirection tokens are not argv — input (`<<<`, `<`,
2396
+ # glued `<<<Delete`), output (`>`, `>>`, `2>`, `1>`, `>&2`,
2397
+ # `2>&1`), and heredoc markers (`<<EOF`, `<< EOF`) — and the
2398
+ # words after a herestring/heredoc join the feeder.
2399
+ def _is_redirect_token(t):
2400
+ return (
2401
+ str(t) == "<"
2402
+ or bool(re.match(r"^0+$", str(t)))
2403
+ or bool(re.match(r"^0+<$", str(t)))
2404
+ or bool(re.match(r"^(?:\d*)>+<?&?", str(t)))
2405
+ or bool(re.match(r"^0*<{3,}", str(t)))
2406
+ or bool(re.match(r"^0*<<-?(?!<)", str(t)))
2407
+ )
2408
+
2409
+ redir_at = -1
2410
+ for ai, t in enumerate(unwrapped_tail := [t for t in stripped[1:]]):
2411
+ if _is_redirect_token(t):
2412
+ redir_at = ai
2413
+ break
2414
+ if redir_at >= 0:
2415
+ marker = str(unwrapped_tail[redir_at])
2416
+ rest_tokens = [str(t) for t in unwrapped_tail[redir_at + 1:]]
2417
+ if re.match(r"^0*<{3,}", marker):
2418
+ feeder = feeder + _expand_words([re.sub(r"^0*<{3,}", "", marker, count=1)] + rest_tokens)
2419
+ elif re.match(r"^0*<<-?", marker):
2420
+ delim = re.sub(r"^0*<<-?", "", marker)
2421
+ if delim:
2422
+ end_i = next((i for i, t in enumerate(rest_tokens) if t == delim and i > 0), len(rest_tokens))
2423
+ body = rest_tokens[:end_i]
2424
+ else:
2425
+ first = rest_tokens[0] if rest_tokens else ""
2426
+ end_i = next((i for i, t in enumerate(rest_tokens) if t == first and i > 0), len(rest_tokens))
2427
+ body = rest_tokens[1:end_i]
2428
+ feeder = feeder + (body if body else rest_tokens)
2429
+ own = [t for t in (unwrapped_tail if redir_at < 0 else unwrapped_tail[:redir_at]) if not re.match(r"^[{}%]+$", str(t)) and str(t) != replstr]
2430
+ # The MERGED classification uses the redirect-trimmed own
2431
+ # list (TS ownTail parity) — a stale argv keeps `>` in the
2432
+ # service slot.
2433
+ argv = own + feeder
2434
+ # Fail-closed per-word candidates: any single feeder word in
2435
+ # the operation slot denies (xargs appends stdin in order).
2436
+ for word in feeder:
2437
+ reason = _classify_leading(["hcloud"] + own + [str(word)], own + [str(word)], routed)
2438
+ if reason:
2439
+ return reason
2440
+ # Round 16 C3: a pipe-fed SHELL reads its stdin as a SCRIPT —
2441
+ # `echo 'hcloud …' | bash` executes the piped line. The xargs-feeder
2442
+ # doctrine: the previous segment's ARGS reaching a listed shell
2443
+ # consumer are the script; a heredoc-to-pipe composition lands the
2444
+ # body inline in the shell's own segment (post-newline text too).
2445
+ _shell_stream, _ = _leading_segment_probe(tokens)
2446
+ _shell_head = (
2447
+ re.match(r"^(bash|sh|zsh|dash)(\.exe)?$", re.sub(r"['\"\\$]", "", basename_of(str(_shell_stream[0]).lower())))
2448
+ if _shell_stream
2449
+ else None
2450
+ )
2451
+ if _shell_head and s > 0 and stripped is not None and not argv:
2452
+ _feeder_args = split_tokens(segments[s - 1])[1:]
2453
+ if _feeder_args:
2454
+ reason = hcloud_write_blocked(" ".join(str(t) for t in _feeder_args), depth + 1, routed, None, seg_saw)
2455
+ if reason:
2456
+ return reason
2457
+ _inline_nl = segment.find("\n")
2458
+ if _inline_nl >= 0:
2459
+ reason = hcloud_write_blocked(segment[_inline_nl + 1:], depth + 1, routed, None, seg_saw)
2460
+ if reason:
2461
+ return reason
2462
+ # Round 15 C-X: an expansion-built OPERATION/SERVICE/SUBCOMMAND
2463
+ # slot (`hcloud ECS ${X:-DeleteServers}`) — the bin IS seen, but the
2464
+ # classification is unprovable (the write vocabulary cannot match
2465
+ # `:-Delete`). The slot rule: the first two non-flag argv entries
2466
+ # carrying `${` deny opaque. Flag-position expansions
2467
+ # (`--cli-region=${REGION}`) stay allowed.
2468
+ _slot_argv = [t for t in stripped[1:] if not str(t).startswith("-")]
2469
+ if any(re.search(r"\$\{", str(t)) for t in _slot_argv[:2]):
2470
+ _opaque = _opaque_carrier_denied(segment, tokens, segment)
2471
+ if _opaque:
2472
+ return _opaque
2473
+ reason = _classify_leading(stripped, argv, routed)
2474
+ if reason:
2475
+ return reason
2476
+ # Glued comparison for PLAIN-LEADING segments (interrogate round
2477
+ # 11): the glued argv differs from plain exactly when quotes
2478
+ # fragmented an argv word — `hcloud ECS "De"leteServers` is the
2479
+ # write DeleteServers to bash and a read-looking `De` to the plain
2480
+ # tokenizer. The ownership is the VERDICT COMPARISON, not a skip:
2481
+ # classify the glued re-join too (the empty-argv shape stays owned
2482
+ # by the standard machinery above — xargs-feeder context).
2483
+ if glued_scope:
2484
+ glued_stripped = hcloud_leading_segment(split_tokens_glued(segment))
2485
+ if glued_stripped is not None:
2486
+ glued_argv = [t for t in glued_stripped[1:] if not t.startswith("-")]
2487
+ if glued_argv or len(stripped) > 1:
2488
+ reason = _classify_leading(glued_stripped, glued_argv, routed)
2489
+ if reason:
2490
+ return reason
2491
+ # A windows payload's brace grammar makes every LATER hcloud
2492
+ # occurrence a live command site (`try { read } finally { write }` —
2493
+ # `}` is not a segment separator, so the blocks stay one segment):
2494
+ # classify each further bin + following words, including bins GLUED
2495
+ # to separator runs (`ListServers}catch{hcloud`).
2496
+ if windows_payload:
2497
+ for i in range(1, len(stripped)):
2498
+ piece_stream = _hcloud_piece_at(stripped, i)
2499
+ if piece_stream is not None and len(piece_stream) > 1:
2500
+ tail_argv = [t for t in piece_stream[1:] if not t.startswith("-")]
2501
+ reason = _classify_leading(piece_stream, tail_argv, routed)
2502
+ if reason:
2503
+ return reason
2504
+ # TS argv-face fallback: split_shell_segments eats backslash escapes
2505
+ # (POSIX semantics), so a Windows path-qualified wrapper
2506
+ # (`C:\Windows\System32\cmd.exe /c "hcloud …"`) mangles in the segment
2507
+ # pass while the plain token stream keeps the path intact. The TS face
2508
+ # classifies those tokens when no segment was hcloud-leading.
2509
+ if not saw_leading:
2510
+ stripped = hcloud_leading_segment(split_tokens(text))
2511
+ if stripped is not None:
2512
+ argv = [t for t in stripped[1:] if not t.startswith("-")]
2513
+ reason = _classify_leading(stripped, argv, routed)
2514
+ if reason:
2515
+ return reason
2516
+ # Glued-bin fallback, WHOLE TEXT (interrogate rounds 9-10): the last
2517
+ # resort for wrapper-qualified shapes where no segment was leading —
2518
+ # the per-segment fallback above handles everything else. Gated on `not
2519
+ # saw_leading` (the standard machinery classified those segments with
2520
+ # full context); routed-only (benign unrouted commands skip it).
2521
+ if not saw_leading and glued_scope:
2522
+ stripped = hcloud_leading_segment(split_tokens_glued(text))
2523
+ if stripped is not None:
2524
+ argv = [t for t in stripped[1:] if not t.startswith("-")]
2525
+ reason = _classify_leading(stripped, argv, routed)
2526
+ if reason:
2527
+ return reason
2528
+ return None
2529
+
2530
+
182
2531
  def evaluate(tool_name, tool_input):
183
2532
  """Run the full safety check and return a raw block reason, or None to allow.
184
2533
 
@@ -188,20 +2537,157 @@ def evaluate(tool_name, tool_input):
188
2537
  callers decide the exact output shape.
189
2538
  """
190
2539
  text = command_text(tool_input)
191
-
192
- if CONFIG_FILE_RE and CONFIG_FILE_RE.search(text):
2540
+ # Whitespace-only commands deny (interrogate rounds 8-9): the TS twin's
2541
+ # risk-rule engine rejects them ("command must be a non-empty string").
2542
+ # The strip set is the EXACT JS trim() character set — round 8's bare
2543
+ # str.strip() also stripped \x85 (NEL) and \x1c-\x1f, which JS trim does
2544
+ # NOT, denying py-side what TS allowed (a one-directional drift); py's
2545
+ # strip() misses \ufeff, which JS trim DOES strip, so it rides the set
2546
+ # explicitly.
2547
+ if not text.strip(" \t\n\v\f\r             

   "):
2548
+ return "command must be a non-empty string. Remediation: Provide a valid, non-empty input before re-running the check."
2549
+ unquoted = strip_shell_quotes(text)
2550
+ # Length cap (interrogate round 5): BYTES on both twins (UTF-16 units on
2551
+ # TS vs code points here disagreed at the boundary on astral-plane
2552
+ # padding — same payload, different verdicts; bytes are also the honest
2553
+ # reading of "256 KiB payload"). The surrogate-safe chain (round 7 — a
2554
+ # bare .encode("utf-8") raised UnicodeEncodeError on the lone \ud800 the
2555
+ # JSON parser accepts, killing the hook verdict-less, and round 6's
2556
+ # "replace" counted a lone surrogate as 1 byte where TS's
2557
+ # Buffer.byteLength counts 3 as U+FFFD — an 87k-surrogate payload sat
2558
+ # under this cap and over TS's, an executable write allowing here while
2559
+ # denying there): the utf-16-surrogatepass round-trip pairs valid
2560
+ # surrogate pairs, replaces lone ones with U+FFFD, and the final utf-8
2561
+ # length is byte-identical to Node's.
2562
+ text_bytes = len(
2563
+ text.encode("utf-16", "surrogatepass").decode("utf-16", "replace").encode("utf-8")
2564
+ )
2565
+ # Continuation-dropped text (interrogate round 6): bash removes the
2566
+ # \<newline> pair before tokenization OUTSIDE single-quoted and $'…'
2567
+ # spans (inside those the pair is literal — the drop here is
2568
+ # deliberately blunter and only ever over-denies), reassembling
2569
+ # $'/$(/backtick across the break — the raw text of
2570
+ # h$\<LF>'\x63'loud … carries only $\, so every raw-text expansion check
2571
+ # and the decode must run on the reassembled form or a composed mangled
2572
+ # write sails through. Dropping pairs can only ever CREATE markers (a
2573
+ # real $' survives the drop untouched), so the dropped form subsumes the
2574
+ # raw one — with the recorded round-7 caveat that a created marker can
2575
+ # be PHANTOM ($$\<LF>' glues to a $' bash never builds, and a
2576
+ # single-quote interior's closing quote can compose one): fail-closed
2577
+ # false denies, never a miss.
2578
+ text_cont = re.sub(r"\\\n", "", text)
2579
+ # A routed OR EXPANSION-BEARING over-cap payload denies fail-closed: the
2580
+ # round-4 decode skip must not make the over-cap slice the one place a
2581
+ # mangled write sails through (the marker check on the dropped text is a
2582
+ # single linear scan; no legitimate oversized expansion-bearing Bash
2583
+ # payload exists).
2584
+ if text_bytes > 262144 and (
2585
+ OBFUSCATION_RE.search(text_cont)
2586
+ or re.search(r"\$\{", text_cont)
2587
+ or HCLOUD_ROUTE_RE.search(unquoted)
2588
+ or HCLOUD_ROUTE_RE.search(text)
2589
+ ):
2590
+ return "command payload too large to classify safely; denied fail-closed"
2591
+ # The ANSI-C-decoded shadow (interrogate round 3): the argv letters $'…'
2592
+ # spans build, reconstructed — h$'\x63'loud is the hcloud the shell
2593
+ # executes. Presence gates below that bear on cloud-command or
2594
+ # secret-reveal detection search BOTH shadows; with no $' span the
2595
+ # decoded candidate is the original text. Decoded from the
2596
+ # CONTINUATION-DROPPED text (round 6: the pair removal is part of bash's
2597
+ # own first pass, and the decode's outside-quote backslash branch would
2598
+ # otherwise consume the \ of a composed $\<LF>' without opening the
2599
+ # span). Skipped for over-cap payloads (round 4: an unrouted 10 MB
2600
+ # escape flood must not pay the decode's linear pass — and the
2601
+ # expansion-bearing cap deny above closes the skip's mangled-write
2602
+ # window at the same size).
2603
+ decoded_unquoted = (
2604
+ unquoted if text_bytes > 262144 else strip_shell_quotes(decode_ansi_c_spans(text_cont))
2605
+ )
2606
+ candidates = (unquoted, decoded_unquoted)
2607
+ normalized = re.sub(r"/{2,}", "/", text)
2608
+ normalized = re.sub(r"/\./", "/", normalized)
2609
+ normalized_unquoted = re.sub(r"/{2,}", "/", unquoted)
2610
+ normalized_unquoted = re.sub(r"/\./", "/", normalized_unquoted)
2611
+ # Raw, shadow, and their path-normalized forms: a quote pair inside the
2612
+ # path or a redundant `//`/`/./` segment defeats the contiguous-substring
2613
+ # patterns while the shell reads the canonical path.
2614
+ if CONFIG_FILE_RE and any(
2615
+ CONFIG_FILE_RE.search(candidate)
2616
+ for candidate in (text, unquoted, normalized, normalized_unquoted)
2617
+ ):
193
2618
  return "reading Huawei Cloud credential/profile files can expose AK/SK or tokens. Use redacted toolkit tools."
194
- if ENV_DUMP_RE.search(text):
2619
+ if SECRET_CLI_RE and any(SECRET_CLI_RE.search(candidate) for candidate in candidates):
2620
+ return "printing vault secrets into the agent context is blocked. Use secret exec so the value reaches only the child process environment."
2621
+ if APPROVAL_CLI_RE and any(APPROVAL_CLI_RE.search(candidate) for candidate in candidates):
2622
+ return "running the approval CLI from the agent Bash face is blocked: the confirmation must come from the user's own interactive terminal, where the PIN is checked. Ask the user to run the printed npx huaweicloud-devkit approve <token> line themselves (first use: npx huaweicloud-devkit pin, once), then retry the same call."
2623
+ # Order-independent reveal pair: xargs reorders the argv while every word
2624
+ # stays literal — a devkit bin plus a `secret get` pair anywhere is a
2625
+ # reveal regardless of order (both shadow candidates — the decoded one
2626
+ # catches ANSI-C-mangled spellings).
2627
+ if any(DEVKIT_BIN_RE.search(candidate) for candidate in candidates) and any(
2628
+ REVEAL_PAIR_RE.search(candidate) for candidate in candidates
2629
+ ):
2630
+ return "printing vault secrets into the agent context is blocked. Use secret exec so the value reaches only the child process environment."
2631
+ # Obfuscated cloud-command invocation: ANSI-C escapes and command
2632
+ # substitution build argv the shadow cannot reconstruct. Canonical
2633
+ # devkit/hcloud commands never carry them. The WRITE_VOCAB_RE clause
2634
+ # closes ANSI-C KEYWORD mangling ($'\x68'cloud — the h exists only inside
2635
+ # the escape, so no layer sees 'hcloud', but the unquoted text still
2636
+ # carries 'deleteservers'): expansion + a write-op word denies fail-closed.
2637
+ # Mirrors the TS gate's writeVocabHit clause (the #927 audit bypass fix);
2638
+ # the vocabulary is the policy.json writeOperationPrefixes list derived
2639
+ # by load_policy from the same read as WRITE_OPERATION_RE — one list,
2640
+ # both gates — plus the marker-gated OBS_VOCAB_RE arm: the OBS subcommand
2641
+ # words fire only when a shadow also carries the OBS service token, so
2642
+ # routine expansion-bearing shell idioms (`docker rm $(docker ps -aq)`,
2643
+ # `mkdir -p $(pwd)/build`) stay legitimate. Interrogate round 3 adds the
2644
+ # DECODED candidate: mangling past the marker (h$'\x63'loud $'\x4f'BS rm —
2645
+ # no 'cloud', no 'OBS' in the stripped shadow) can no longer hide the
2646
+ # bin, the service token, or the operation word, and mangled READS deny
2647
+ # too (deny rather than parse — the same verdict an op-mangled read with
2648
+ # a literal bin already gets). The `is None` arm is the vocabulary's
2649
+ # failure mode, chosen FAIL-CLOSED: when the derivation is unavailable
2650
+ # (policy.json missing or corrupt JSON, or the list empty or non-list —
2651
+ # load_policy normalizes non-lists to empty) the clause treats the
2652
+ # vocabulary as hit, so an expansion-bearing command denies instead of
2653
+ # the unavailable word list re-opening the mangled-write hole the gate
2654
+ # exists to close.
2655
+ if (
2656
+ any(CLOUD_BIN_RE.search(candidate) for candidate in candidates)
2657
+ or any(re.search(r"secret://", candidate) for candidate in candidates)
2658
+ or WRITE_VOCAB_RE is None
2659
+ or any(WRITE_VOCAB_RE.search(candidate) for candidate in candidates)
2660
+ or (
2661
+ any(OBS_MARKER_RE.search(candidate) for candidate in candidates)
2662
+ and any(OBS_VOCAB_RE.search(candidate) for candidate in candidates)
2663
+ )
2664
+ # The right conjunct runs on the CONTINUATION-DROPPED text (round 6): a
2665
+ # composed $\<LF>' carries the marker only after the pair drop, and the
2666
+ # drop never destroys a real one.
2667
+ ) and OBFUSCATION_RE.search(text_cont):
2668
+ return "an obfuscated cloud CLI invocation (shell expansion inside the command) is blocked. Write the command in plain form."
2669
+ if (
2670
+ ENV_DUMP_RE.search(unquoted)
2671
+ or ARGLESS_DUMP_RE.search(unquoted)
2672
+ or BARE_SET_RE.search(unquoted)
2673
+ or DUMP_PIPE_RE.search(unquoted)
2674
+ ):
195
2675
  return "dumping cloud credential environment variables is not allowed."
196
- if CRED_VAR_REF_RE.search(text):
2676
+ # Single-quoted spans removed before the expansion test: the shell never
2677
+ # expands inside them, but a CLOSING quote before an unquoted $HW_ still
2678
+ # expands (`echo 'a'$HW_SECRET_KEY`).
2679
+ un_single_quoted = re.sub(r"'[^']*'", "", text)
2680
+ if CRED_EXPANSION_RE.search(un_single_quoted) or PRINTENV_CRED_RE.search(unquoted):
197
2681
  return "printing cloud credential environment variables is not allowed."
198
- if SECRET_READ_RE and SECRET_READ_RE.search(text):
2682
+ if SECRET_READ_RE and (SECRET_READ_RE.search(text) or SECRET_READ_RE.search(unquoted)):
199
2683
  return "direct secret value retrieval would put plaintext secrets into the agent context."
200
2684
  denied_rule = first_denied_command_rule(text)
201
2685
  if denied_rule:
202
2686
  return f"{denied_rule.get('message')} Remediation: {denied_rule.get('remediation')}"
203
- if tool_name in ("Bash", "terminal") and HCLOUD_RE.search(text) and WRITE_OPERATION_RE.search(text) and not READ_OPERATION_RE.search(text):
204
- return "unapproved Huawei Cloud write operations must be planned first and explicitly approved by the user."
2687
+ if tool_name in ("Bash", "terminal"):
2688
+ reason = hcloud_write_blocked(text)
2689
+ if reason:
2690
+ return reason
205
2691
 
206
2692
  return None
207
2693