huaweicloud-devkit 1.1.14-next.0 → 2.0.0-next.0

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

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