huaweicloud-devkit 2.0.0-next.3 → 2.0.0-next.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +3 -1
  2. package/package.json +3 -1
  3. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +1 -1
  4. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +1 -1
  5. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +1 -1
  6. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +1 -1
  7. package/plugins/huaweicloud-core/.mcp.json +55 -1
  8. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +1 -1
  9. package/plugins/huaweicloud-core/dist/agents/codex-config.js +374 -0
  10. package/plugins/huaweicloud-core/dist/agents/codex-desktop.js +8 -1
  11. package/plugins/huaweicloud-core/dist/agents/codex.js +9 -0
  12. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +141 -86
  13. package/plugins/huaweicloud-core/dist/agents/opencode.js +106 -39
  14. package/plugins/huaweicloud-core/dist/approval-gate.js +1185 -0
  15. package/plugins/huaweicloud-core/dist/approval-ledger.js +2331 -0
  16. package/plugins/huaweicloud-core/dist/approval-roster.js +89 -0
  17. package/plugins/huaweicloud-core/dist/approval-types.js +1 -0
  18. package/plugins/huaweicloud-core/dist/approvals-cli.js +4 -4
  19. package/plugins/huaweicloud-core/dist/data/icons-manifest.v1.json +23 -5
  20. package/plugins/huaweicloud-core/dist/dep/receipts.js +65 -5
  21. package/plugins/huaweicloud-core/dist/explain-error.js +9 -1
  22. package/plugins/huaweicloud-core/dist/hcloud-cli.js +1 -1
  23. package/plugins/huaweicloud-core/dist/hcloud-plan.js +68 -62
  24. package/plugins/huaweicloud-core/dist/lib/approval-mode.js +7 -5
  25. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +18 -4
  26. package/plugins/huaweicloud-core/dist/lib/call-trace.js +7 -14
  27. package/plugins/huaweicloud-core/dist/lib/confirm-language.js +50 -0
  28. package/plugins/huaweicloud-core/dist/lib/credentials.js +9 -9
  29. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkit-gate.js +1398 -0
  30. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +371 -32
  31. package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +6 -16
  32. package/plugins/huaweicloud-core/dist/lib/opencode-ask-rule.js +224 -78
  33. package/plugins/huaweicloud-core/dist/lib/opencode-saved-perms.js +282 -0
  34. package/plugins/huaweicloud-core/dist/lib/supplemental-redaction.js +116 -0
  35. package/plugins/huaweicloud-core/dist/lib/tool-schema-parts.js +31 -0
  36. package/plugins/huaweicloud-core/dist/lib/workspace-glob.js +442 -0
  37. package/plugins/huaweicloud-core/dist/mcp-config-io.js +28 -1
  38. package/plugins/huaweicloud-core/dist/mcp-protocol.js +68 -16
  39. package/plugins/huaweicloud-core/dist/mcp-server.js +6933 -1186
  40. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  41. package/plugins/huaweicloud-core/dist/mcp-stdio-transport.js +14 -4
  42. package/plugins/huaweicloud-core/dist/packs/auth/approval.js +249 -0
  43. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +44 -44
  44. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +85 -130
  45. package/plugins/huaweicloud-core/dist/packs/obs/approval.js +110 -0
  46. package/plugins/huaweicloud-core/dist/packs/obs/tools.js +7 -2
  47. package/plugins/huaweicloud-core/dist/packs/registry.js +20 -1
  48. package/plugins/huaweicloud-core/dist/packs/sandbox/approval.js +245 -0
  49. package/plugins/huaweicloud-core/dist/packs/sandbox/expose-task.js +71 -0
  50. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +180 -23
  51. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +13 -1
  52. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-hwexec.js +136 -0
  53. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +11 -1
  54. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +29 -3
  55. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +93 -9
  56. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +37 -10
  57. package/plugins/huaweicloud-core/dist/packs/secrets/approval.js +46 -0
  58. package/plugins/huaweicloud-core/dist/packs/secrets/tools.js +4 -1
  59. package/plugins/huaweicloud-core/dist/packs/update/approval.js +79 -0
  60. package/plugins/huaweicloud-core/dist/packs/update/tools.js +8 -1
  61. package/plugins/huaweicloud-core/dist/packs/voucher/tools.js +1 -1
  62. package/plugins/huaweicloud-core/dist/packs-configure.js +74 -0
  63. package/plugins/huaweicloud-core/dist/risk-rule-engine.js +20 -4
  64. package/plugins/huaweicloud-core/dist/safety/classify-hcloud.js +6 -6
  65. package/plugins/huaweicloud-core/dist/safety/classify-text.js +36 -0
  66. package/plugins/huaweicloud-core/dist/safety/policy.js +2 -0
  67. package/plugins/huaweicloud-core/dist/safety/redact.js +21 -3
  68. package/plugins/huaweicloud-core/dist/safety/risk-merge.js +24 -4
  69. package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +1 -1
  70. package/plugins/huaweicloud-core/dist/sandbox/devbridge-auth.js +65 -14
  71. package/plugins/huaweicloud-core/dist/sandbox/devbridge-cleanup.js +422 -0
  72. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose-flow.js +66 -16
  73. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose.js +13 -10
  74. package/plugins/huaweicloud-core/dist/sandbox/devbridge-keepalive.js +42 -2
  75. package/plugins/huaweicloud-core/dist/sandbox/devbridge-key.js +11 -3
  76. package/plugins/huaweicloud-core/dist/sandbox/devbridge-tunnel.js +6 -0
  77. package/plugins/huaweicloud-core/dist/sandbox/devbridge-validation.js +10 -1
  78. package/plugins/huaweicloud-core/dist/sandbox/hwexec-task.js +244 -0
  79. package/plugins/huaweicloud-core/dist/setup-cli.js +36 -1
  80. package/plugins/huaweicloud-core/dist/tool-definitions.js +13 -1
  81. package/plugins/huaweicloud-core/dist/tool-schemas.js +32 -6
  82. package/plugins/huaweicloud-core/dist/tools.js +76 -9
  83. package/plugins/huaweicloud-core/dist/update-registry.js +358 -5
  84. package/plugins/huaweicloud-core/dist/update-upgrade.js +1083 -14
  85. package/plugins/huaweicloud-core/dist/vendor-gate.js +2 -2
  86. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +150 -1
  87. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +67 -4
  88. package/plugins/huaweicloud-core/openclaw.plugin.json +2 -2
  89. package/plugins/huaweicloud-core/safety/policy.json +18 -11
  90. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +115 -11
  91. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +198 -143
  92. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +36 -12
  93. package/plugins/huaweicloud-core/skills/huawei-voucher/SKILL.md +2 -0
  94. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +2 -2
  95. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +11 -7
  96. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +74 -29
  97. package/plugins/huaweicloud-core/skills/huaweicloud-troubleshooting/SKILL.md +21 -19
  98. package/plugins/huaweicloud-core/src/agents/codex-config.ts +432 -0
  99. package/plugins/huaweicloud-core/src/agents/codex-desktop.ts +8 -1
  100. package/plugins/huaweicloud-core/src/agents/codex.ts +10 -0
  101. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +176 -88
  102. package/plugins/huaweicloud-core/src/agents/opencode.ts +125 -54
  103. package/plugins/huaweicloud-core/src/approval-gate.ts +1306 -0
  104. package/plugins/huaweicloud-core/src/approval-ledger.ts +2446 -0
  105. package/plugins/huaweicloud-core/src/approval-roster.ts +127 -0
  106. package/plugins/huaweicloud-core/src/approval-types.ts +237 -0
  107. package/plugins/huaweicloud-core/src/approvals-cli.ts +4 -4
  108. package/plugins/huaweicloud-core/src/data/icons-manifest.v1.json +23 -5
  109. package/plugins/huaweicloud-core/src/dep/receipts.ts +84 -5
  110. package/plugins/huaweicloud-core/src/explain-error.ts +9 -1
  111. package/plugins/huaweicloud-core/src/hcloud-cli.ts +3 -0
  112. package/plugins/huaweicloud-core/src/hcloud-plan.ts +74 -71
  113. package/plugins/huaweicloud-core/src/lib/approval-mode.ts +7 -5
  114. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +19 -4
  115. package/plugins/huaweicloud-core/src/lib/call-trace.ts +7 -17
  116. package/plugins/huaweicloud-core/src/lib/confirm-language.ts +51 -0
  117. package/plugins/huaweicloud-core/src/lib/credentials.ts +9 -8
  118. package/plugins/huaweicloud-core/src/lib/hdkit/hdkit-gate.ts +1428 -0
  119. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +408 -30
  120. package/plugins/huaweicloud-core/src/lib/hdkit/sandbox-pool.ts +8 -15
  121. package/plugins/huaweicloud-core/src/lib/opencode-ask-rule.ts +302 -83
  122. package/plugins/huaweicloud-core/src/lib/opencode-saved-perms.ts +354 -0
  123. package/plugins/huaweicloud-core/src/lib/supplemental-redaction.ts +129 -0
  124. package/plugins/huaweicloud-core/src/lib/tool-schema-parts.ts +40 -0
  125. package/plugins/huaweicloud-core/src/lib/workspace-glob.ts +414 -0
  126. package/plugins/huaweicloud-core/src/mcp-config-io.ts +27 -1
  127. package/plugins/huaweicloud-core/src/mcp-protocol.ts +81 -17
  128. package/plugins/huaweicloud-core/src/mcp-server.ts +7 -7
  129. package/plugins/huaweicloud-core/src/mcp-stdio-transport.ts +14 -4
  130. package/plugins/huaweicloud-core/src/packs/auth/approval.ts +302 -0
  131. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +54 -45
  132. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +99 -137
  133. package/plugins/huaweicloud-core/src/packs/obs/approval.ts +122 -0
  134. package/plugins/huaweicloud-core/src/packs/obs/tools.ts +7 -2
  135. package/plugins/huaweicloud-core/src/packs/registry.ts +43 -1
  136. package/plugins/huaweicloud-core/src/packs/sandbox/approval.ts +296 -0
  137. package/plugins/huaweicloud-core/src/packs/sandbox/expose-task.ts +105 -0
  138. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +195 -23
  139. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +11 -1
  140. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-hwexec.ts +228 -0
  141. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +11 -1
  142. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +41 -14
  143. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +120 -8
  144. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +42 -9
  145. package/plugins/huaweicloud-core/src/packs/secrets/approval.ts +50 -0
  146. package/plugins/huaweicloud-core/src/packs/secrets/tools.ts +4 -1
  147. package/plugins/huaweicloud-core/src/packs/update/approval.ts +87 -0
  148. package/plugins/huaweicloud-core/src/packs/update/tools.ts +8 -1
  149. package/plugins/huaweicloud-core/src/packs/voucher/tools.ts +1 -1
  150. package/plugins/huaweicloud-core/src/packs-configure.ts +75 -0
  151. package/plugins/huaweicloud-core/src/risk-rule-engine.ts +20 -7
  152. package/plugins/huaweicloud-core/src/safety/classify-hcloud.ts +28 -16
  153. package/plugins/huaweicloud-core/src/safety/classify-text.ts +40 -0
  154. package/plugins/huaweicloud-core/src/safety/policy.ts +7 -0
  155. package/plugins/huaweicloud-core/src/safety/redact.ts +24 -6
  156. package/plugins/huaweicloud-core/src/safety/risk-merge.ts +26 -5
  157. package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +1 -1
  158. package/plugins/huaweicloud-core/src/sandbox/devbridge-auth.ts +74 -14
  159. package/plugins/huaweicloud-core/src/sandbox/devbridge-cleanup.ts +511 -0
  160. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose-flow.ts +70 -18
  161. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose.ts +26 -10
  162. package/plugins/huaweicloud-core/src/sandbox/devbridge-keepalive.ts +41 -2
  163. package/plugins/huaweicloud-core/src/sandbox/devbridge-key.ts +9 -3
  164. package/plugins/huaweicloud-core/src/sandbox/devbridge-tunnel.ts +24 -0
  165. package/plugins/huaweicloud-core/src/sandbox/devbridge-validation.ts +11 -1
  166. package/plugins/huaweicloud-core/src/sandbox/hwexec-task.ts +304 -0
  167. package/plugins/huaweicloud-core/src/setup-cli.ts +39 -1
  168. package/plugins/huaweicloud-core/src/tool-definitions.ts +13 -1
  169. package/plugins/huaweicloud-core/src/tool-schemas.ts +39 -6
  170. package/plugins/huaweicloud-core/src/tools.ts +124 -10
  171. package/plugins/huaweicloud-core/src/update-registry.ts +340 -5
  172. package/plugins/huaweicloud-core/src/update-upgrade.ts +1130 -14
  173. package/plugins/huaweicloud-core/src/vendor-gate.ts +2 -2
@@ -0,0 +1,79 @@
1
+ import { hashArgs } from "../../lib/approval-tokens.js";
2
+ import { redactSecrets } from "../../safety-policy.js";
3
+ import { asString } from "../../lib/as-text.js";
4
+ import { SUPPORTED_AGENT_TARGETS } from "../../auth/agent-registration.js";
5
+ // The update pack's approval registration (PR-3c): huaweicloud_upgrade is
6
+ // ALWAYS gated — it replaces the package on disk for every installed
7
+ // target, which redirects every later tool call onto code the operator
8
+ // never reviewed, so the trunk's description-level consent line
9
+ // ("执行前必须先征得用户同意") becomes a mechanical gate. The binding is
10
+ // the {target, version} projection (never the gate fields), so the
11
+ // confirmation pins exactly what will be upgraded. check_update stays
12
+ // unregistered: it is the read-only face of the pair.
13
+ //
14
+ // Interrogate round 2, finding 2 — display/binding integrity:
15
+ // (a) An ABSENT version normalizes to the literal 'latest' INSIDE the
16
+ // binding, so the value the popup displays is the value the token
17
+ // binds: the natural retry with version:'latest' (what the user read)
18
+ // hashes identically to the unversioned mint and executes, instead
19
+ // of mismatch-burning the token.
20
+ // (b) assertArgsExecutable refuses every version shape the handler's own
21
+ // chain refuses (upgradePackage accepts 'latest' only): a concrete
22
+ // version and an empty string never mint a doomed approval.
23
+ // (c) 'latest' names the CHANNEL, not an artifact: the handler elects
24
+ // the actual tag after consent (a stable current → @latest, a
25
+ // prerelease current → @next). The summarize view says so. Residual,
26
+ // recorded: the tag can move between consent and execution (a
27
+ // registry publish lands mid-cycle); the consent pins the channel
28
+ // and the target, never the resolved artifact.
29
+ //
30
+ // Interrogate round 3, finding — the target half of the same doctrine:
31
+ // (a) An absent AND an empty target normalize to the literal 'all'
32
+ // (the handler's own default for both), so the displayed '(target
33
+ // all)' is the bound value and the natural retry with target:'all'
34
+ // consumes instead of mismatch-burning the confirmed token.
35
+ // (b) assertArgsExecutable also refuses targets outside the handler's
36
+ // SUPPORTED_AGENT_TARGETS allowlist (upgradePackage answers
37
+ // '不支持的升级目标' after the gate, review #717's shell-interpolation
38
+ // guard), so a bogus or case-variant target never mints a doomed
39
+ // approval.
40
+ function upgradeBinding(args) {
41
+ return {
42
+ target: args.target === undefined || args.target === '' ? 'all' : args.target,
43
+ version: args.version === undefined ? 'latest' : args.version,
44
+ };
45
+ }
46
+ function assertUpgradeExecutable(value) {
47
+ const { target, version } = value;
48
+ if (version !== 'latest') {
49
+ throw new Error(`version must be "latest" (got ${JSON.stringify(version)}): the handler elects the actual dist tag from the channel. Send version: "latest" or omit it.`);
50
+ }
51
+ const targetStr = String(target);
52
+ if (targetStr !== 'all' && !SUPPORTED_AGENT_TARGETS.includes(targetStr)) {
53
+ throw new Error(`不支持的升级目标:${targetStr}(有效目标:all,或 ${SUPPORTED_AGENT_TARGETS.join(', ')} 之一)`);
54
+ }
55
+ }
56
+ export const UPDATE_APPROVAL_SPECS = {
57
+ huaweicloud_upgrade: {
58
+ domain: 'update',
59
+ flavor: 'always',
60
+ tokenSource: 'gate',
61
+ normalizeArgs: upgradeBinding,
62
+ assertArgsExecutable: assertUpgradeExecutable,
63
+ // The view folds through the shared redaction vocabulary before any
64
+ // field reaches the summary or pin view (the ApprovalSpec contract:
65
+ // never the raw argument stream); the hash binds the raw content —
66
+ // here the normalized content, so the displayed value IS the bound
67
+ // value.
68
+ summarize: (value) => {
69
+ const safe = redactSecrets(value);
70
+ return {
71
+ summary: `huaweicloud_upgrade: upgrade huaweicloud-devkit to version ${asString(safe.version) ?? 'latest'} ` +
72
+ `(target ${asString(safe.target) ?? 'all'}) — "latest" names the channel: the handler elects the stable ` +
73
+ 'or prerelease dist tag (a stable current upgrades to @latest, a prerelease current to @next) after consent',
74
+ argsHash: hashArgs(value),
75
+ pinView: safe,
76
+ };
77
+ },
78
+ },
79
+ };
@@ -1,5 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { getCachedUpdateInfo, getUpdateDistTags, invalidateUpdateCache, judgeUpdate, determineTarget, readInstalledVersion, writeSkipState, resolveSkipFilePath, upgradePackage, } from "../../update-check.js";
3
+ import { approvalTokenArg, approvedByUserArg } from "../../lib/tool-schema-parts.js";
3
4
  // Handlers migrated verbatim from src/tools.ts; the doQuery injection seam on
4
5
  // CallToolOptions is passed through unchanged (test/upgrade-session.test.ts
5
6
  // #607 depends on it reaching getUpdateDistTags/getCachedUpdateInfo).
@@ -51,6 +52,8 @@ const upgradeSchema = z.looseObject({
51
52
  .string()
52
53
  .optional()
53
54
  .describe('agent 目标(opencode/codex/codearts/.../all)。缺省时用 all(仅更新已安装的)。'),
55
+ approvalToken: approvalTokenArg,
56
+ approvedByUser: approvedByUserArg,
54
57
  });
55
58
  export const UPDATE_TOOLS = [
56
59
  {
@@ -61,7 +64,11 @@ export const UPDATE_TOOLS = [
61
64
  },
62
65
  {
63
66
  name: 'huaweicloud_upgrade',
64
- description: '升级 huaweicloud-devkit 到最新版本。执行前必须先征得用户同意。version 仅支持 "latest"。完成后需重启会话生效。',
67
+ // The mechanical approval gate enforces the consent this line used to
68
+ // only ask for (PR-3c): token mode runs the approve command from the
69
+ // gate's rejection envelope in the user's own terminal, ask mode lets
70
+ // the server raise the confirmation itself.
71
+ description: '升级 huaweicloud-devkit 到最新版本。升级会改写磁盘上的插件本体,因此由审批门机械把关:默认 token 模式下,无 token 调用会返回 USER_CONFIRMATION_REQUIRED 与 approve 命令行,用户在自己的终端确认后才可重试;DEVKIT_APPROVAL_MODE=ask 时由服务器在调用内弹出确认(表单或聊天往返)。version 仅支持 "latest"。完成后需重启会话生效。',
65
72
  schema: upgradeSchema,
66
73
  handler: handleUpgrade,
67
74
  },
@@ -56,7 +56,7 @@ const voucherClaimSchema = z.looseObject({
56
56
  export const VOUCHER_TOOLS = [
57
57
  {
58
58
  name: 'huaweicloud_voucher_status',
59
- description: '查询代金券领取状态。当会话已处于华为云任务上下文(用户已指明华为云,或先前轮次已确认)且用户首次使用或询问插件能力时,主动调用本工具检查:未领取(claimed=false)则主动提示可领取一张代金券;已领取(claimed=true)则不提示、不打扰。厂商未定(用户未指明、上下文无法推断)时不要调用——先问用户用的是哪家云。',
59
+ description: '查询代金券领取状态。当会话已处于华为云任务上下文(用户已指明华为云,或先前轮次已确认)且用户首次使用或询问插件能力时,主动调用本工具检查:未领取(claimed=false)则主动提示可领取一张代金券;已领取(claimed=true)则不提示、不打扰;claimed=false 且 code=HDKIT_VERSION_TOO_OLD 表示客户端版本过旧——转述 remediation 升级引导,绝不提示领券。厂商未定(用户未指明、上下文无法推断)时不要调用——先问用户用的是哪家云。',
60
60
  schema: voucherStatusSchema,
61
61
  handler: handleVoucherStatus,
62
62
  },
@@ -1,6 +1,9 @@
1
1
  import { resolveEnabledPacks, setRuntimePacksOverride, clearRuntimePacksOverride, runtimePacksOverride, } from "./packs/enable.js";
2
2
  import { PACK_IDS } from "./lib/pack-types.js";
3
3
  import { closePackEnablement } from "./lib/dependency-model.js";
4
+ import { hashArgs } from "./lib/approval-tokens.js";
5
+ import { redactSecrets } from "./safety-policy.js";
6
+ import { asString } from "./lib/as-text.js";
4
7
  export function configurePacks(args, opts) {
5
8
  const enable = (args.enable ?? []).map((id) => String(id));
6
9
  const disable = (args.disable ?? []).map((id) => String(id));
@@ -79,3 +82,74 @@ export function configurePacks(args, opts) {
79
82
  : 'The requested surface already applies.',
80
83
  };
81
84
  }
85
+ // The packs_configure approval registration (PR-3c). ALWAYS gated, because
86
+ // widening the session's disclosure face is the actual consequence — an
87
+ // enabled pack materializes its tools and skills for every later call — and
88
+ // the summarize view names the exact ids so the confirmation surface shows
89
+ // the consequence itself. requiresSessionSeam mirrors this handler's own
90
+ // stdio-only refusal: the gate checks opts.onPacksChanged BEFORE engaging
91
+ // (the refusal lives here, downstream of any dispatch-layer gate), so a
92
+ // no-seam call refuses with no token minted and no ledger entry — the
93
+ // ordering the gate's precheck exists to enforce. The binding is the
94
+ // {enable, disable, reset} projection, never the gate fields.
95
+ export const PACKS_CONFIGURE_APPROVAL_SPEC = {
96
+ domain: 'packs',
97
+ flavor: 'always',
98
+ tokenSource: 'gate',
99
+ requiresSessionSeam: true,
100
+ normalizeArgs: (args) => ({
101
+ enable: args.enable,
102
+ disable: args.disable,
103
+ reset: args.reset,
104
+ }),
105
+ summarize: (value) => {
106
+ // The view folds through the shared redaction vocabulary before any
107
+ // field reaches the summary or pin view (the ApprovalSpec contract);
108
+ // the hash binds the raw content.
109
+ const safe = redactSecrets(value);
110
+ const list = (ids) => Array.isArray(ids) ? ids.map((id) => String(id)).join(', ') : (asString(ids) ?? '');
111
+ const parts = [];
112
+ if (Array.isArray(safe.enable) && safe.enable.length > 0)
113
+ parts.push(`enable pack(s) ${list(safe.enable)}`);
114
+ if (Array.isArray(safe.disable) && safe.disable.length > 0)
115
+ parts.push(`disable pack(s) ${list(safe.disable)}`);
116
+ if (safe.reset === true)
117
+ parts.push('reset the session override (restore the operator DEVKIT_PACKS posture)');
118
+ if (parts.length === 0)
119
+ parts.push('no-op: provide enable, disable, or reset');
120
+ return {
121
+ summary: `huaweicloud_packs_configure: ${parts.join('; ')}`,
122
+ argsHash: hashArgs(value),
123
+ pinView: safe,
124
+ };
125
+ },
126
+ // NoDoomedToken (interrogate round 2, fix-in-pass i): the handler's own
127
+ // five pure validations, hoisted BEFORE the mint — a shape the handler
128
+ // refuses would burn the user's approval on a guaranteed refusal, so it
129
+ // never mints. Message texts mirror the handler's exactly, so the two
130
+ // layers can never drift into different teachings; the handler keeps its
131
+ // own copies as the belt behind this floor.
132
+ assertArgsExecutable: (value) => {
133
+ const { enable, disable, reset } = value;
134
+ const enableIds = Array.isArray(enable) ? enable.map((id) => String(id)) : [];
135
+ const disableIds = Array.isArray(disable) ? disable.map((id) => String(id)) : [];
136
+ const resetIs = reset === true;
137
+ if (!resetIs && enableIds.length === 0 && disableIds.length === 0) {
138
+ throw new Error('Provide at least one of enable, disable, or reset.');
139
+ }
140
+ const bogus = [...enableIds, ...disableIds].filter((id) => !PACK_IDS.includes(id));
141
+ if (bogus.length > 0) {
142
+ throw new Error('Unknown pack id(s): ' + bogus.join(', ') + '. Valid pack ids: ' + PACK_IDS.join(', ') + '.');
143
+ }
144
+ if (disableIds.includes('core')) {
145
+ throw new Error('core is always enabled (the pack meta, safety, and discovery surface is force-included) and cannot be disabled.');
146
+ }
147
+ const overlap = enableIds.filter((id) => disableIds.includes(id));
148
+ if (overlap.length > 0) {
149
+ throw new Error('Pack id(s) cannot be both enabled and disabled in one call: ' + overlap.join(', ') + '.');
150
+ }
151
+ if (resetIs && (enableIds.length > 0 || disableIds.length > 0)) {
152
+ throw new Error('reset drops the whole session override and cannot be combined with enable or disable.');
153
+ }
154
+ },
155
+ };
@@ -3,6 +3,7 @@ import { dirname, join } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { asText } from "./lib/as-text.js";
5
5
  import { asRecord } from "./lib/as-record.js";
6
+ import { redactEvidenceText } from "./safety/redact.js";
6
7
  const __dirname = dirname(fileURLToPath(import.meta.url));
7
8
  const defaultRulesPath = join(__dirname, '..', 'safety', 'rules', 'cloud-risk-rules.json');
8
9
  const SEVERITY_RANK = {
@@ -58,9 +59,7 @@ export function loadRiskRules(options = {}) {
58
59
  return toCatalog(JSON.parse(readFileSync(path, 'utf8')));
59
60
  }
60
61
  function redactEvidence(text) {
61
- return String(text)
62
- .replace(/((?:access[_-]?key(?:[_-]?(?:id|secret))?|secret[_-]?key|secret[_-]?string|secret[_-]?binary|secret(?!:\/)|security[_-]?token|x[_-]?auth[_-]?token|token|authorization|password|passwd|admin[_-]?pass|credential)\\*["']?\s*[:=]\s*[\\"'\\]*\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1<redacted>')
63
- .replace(/\b(AK|SK)\\*["']?\s*[:=]\s*("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1=<redacted>');
62
+ return redactEvidenceText(text);
64
63
  }
65
64
  function normalizeText(value) {
66
65
  if (typeof value === 'string')
@@ -84,10 +83,27 @@ function evaluationContext(stage, input) {
84
83
  }
85
84
  return { text: normalizeText(input) };
86
85
  }
86
+ // Shell-transcribed commands and nested JSON artifacts arrive with escaped
87
+ // quotes (`\"Action\":` / `{\"privileged\":true}`) — the spelling a shell or
88
+ // an embedded JSON string actually produces. The catalog's JSON-shaped rules
89
+ // were authored against the unescaped spelling, so a backslash between the
90
+ // key and the quote made deny-severity rules (IAM administrator grants, OBS
91
+ // anonymous writes, privileged containers) silently miss. Matching therefore
92
+ // tests the raw value AND a quote-unescaped shadow; evidence/display keep the
93
+ // raw text. Only quote-adjacent backslashes are folded, so Windows paths are
94
+ // untouched.
95
+ function normalizeRuleText(text) {
96
+ return text.replace(/\\+(["'])/g, '$1');
97
+ }
87
98
  function conditionMatches(condition, context) {
88
99
  const field = condition.field || 'text';
89
100
  const value = Object.hasOwn(context, field) ? context[field] : context.text;
90
- return new RegExp(condition.regex, 'ims').test(String(value || ''));
101
+ const raw = String(value || '');
102
+ const regex = new RegExp(condition.regex, 'ims');
103
+ if (regex.test(raw))
104
+ return true;
105
+ const normalized = normalizeRuleText(raw);
106
+ return normalized !== raw && regex.test(normalized);
91
107
  }
92
108
  function ruleMatches(rule, context) {
93
109
  const match = rule.match || {};
@@ -101,18 +101,18 @@ export function classifyHcloudArgs(args, options = {}) {
101
101
  const isExecution = executionOps.test(operation) && !readOnly;
102
102
  const isWrite = !readOnly && hasWritePrefix(operation, policy);
103
103
  if (isExecution && !options.allowWrites) {
104
- return {
104
+ return applyCommandRiskRules({
105
105
  decision: 'deny',
106
106
  risk: 'execution',
107
107
  reason: 'Huawei Cloud execution/trigger operation blocked until approved.',
108
- };
108
+ }, normalizedArgs, options);
109
109
  }
110
110
  if (isWrite && !options.allowWrites) {
111
- return {
111
+ return applyCommandRiskRules({
112
112
  decision: 'deny',
113
113
  risk: 'write',
114
114
  reason: 'Huawei Cloud write operation blocked until the agent presents a plan and receives explicit user approval.',
115
- };
115
+ }, normalizedArgs, options);
116
116
  }
117
117
  const obsutilWrites = OBSUTIL_WRITES;
118
118
  const obsutilReads = ['ls', 'stat', 'cat', 'help', 'version'];
@@ -123,11 +123,11 @@ export function classifyHcloudArgs(args, options = {}) {
123
123
  const isObsWrite = isObs && obsutilWrites.has(operation.toLowerCase());
124
124
  const isObsRead = isObs && obsutilReads.includes(operation.toLowerCase());
125
125
  if (isObsWrite && !options.allowWrites) {
126
- return {
126
+ return applyCommandRiskRules({
127
127
  decision: 'deny',
128
128
  risk: 'write',
129
129
  reason: 'OBS write operation blocked until the agent presents a plan and receives explicit user approval.',
130
- };
130
+ }, normalizedArgs, options);
131
131
  }
132
132
  if (isObsRead) {
133
133
  return applyCommandRiskRules({
@@ -831,6 +831,42 @@ export function classifyTextCommand(command, options = {}) {
831
831
  reason: "Running the approval CLI from the agent Bash face is blocked: the confirmation must come from the user's own interactive terminal, where the PIN is checked. Ask the user to run the printed npx huaweicloud-devkit approve <token> line themselves (first use: npx huaweicloud-devkit pin, once), then retry the same call.",
832
832
  };
833
833
  }
834
+ // The account-switch CLI verbs (interrogate round 1, finding 1): `auth
835
+ // init`/`auth sync` write S1, the OBS config, and the KooCLI profile —
836
+ // the same account switch the MCP tools gate behind a human present
837
+ // (PR-3b). The hook blocks raw `hcloud configure set`, but the devkit's
838
+ // own wrapper was an open bypass: an agent that shells out to
839
+ // `npx huaweicloud-devkit auth init` switches every downstream approved
840
+ // write's account with no confirmation at all. Same anchoring doctrine
841
+ // as approve/pin: the patterns require a devkit binary spelling, so an
842
+ // hcloud operation or a plain file named auth-init never trips, and the
843
+ // read-only `auth status` stays allowed for the agent.
844
+ if (shadowCandidates.some((candidate) => matchesAny(candidate, policy.blockedAccountSwitchCliPatterns))) {
845
+ return {
846
+ decision: 'deny',
847
+ risk: 'approval',
848
+ reason: "Running the account-switch CLI from the agent Bash face is blocked: switching the Huawei Cloud account is approval-gated, and the devkit's own confirmation must come from the user's own interactive terminal. Ask the user to run the auth init / auth sync command themselves, or use the gated MCP tools (huaweicloud_auth_init / huaweicloud_auth_switch), which confirm the target account with the user before switching.",
849
+ };
850
+ }
851
+ // The devkit's gated-mutation CLI twins (interrogate round 1, finding 1):
852
+ // `update`/`upgrade` rewrite the installed package, `secret rm` deletes a
853
+ // vault entry, and `packs enable|disable|all` rewrites the operator
854
+ // DEVKIT_PACKS posture — the exact mutations the MCP approval gate
855
+ // mediates on huaweicloud_upgrade, huaweicloud_secret_delete, and
856
+ // huaweicloud_packs_configure. The CLI path carries no gate at all, so an
857
+ // agent shelling to it performs the mutation with zero confirmation —
858
+ // the same bypass class the auth verbs established. The row shape mirrors
859
+ // the approve/pin family (a devkit bin spelling must be present, so a
860
+ // Huawei Cloud operation or a benign sentence containing the verb never
861
+ // trips), matched against the same two shadows. A human at their own
862
+ // terminal is unaffected: this is the agent Bash face.
863
+ if (shadowCandidates.some((candidate) => matchesAny(candidate, policy.blockedGatedCliPatterns))) {
864
+ return {
865
+ decision: 'deny',
866
+ risk: 'approval',
867
+ reason: 'Running the devkit update/upgrade, secret rm, and packs enable/disable CLI verbs from the agent Bash face is blocked: they perform the same mutations the MCP approval gate mediates (huaweicloud_upgrade, huaweicloud_secret_delete, huaweicloud_packs_configure), with no confirmation on this path. Call the MCP tool instead — its gate raises the confirmation (token, form, or chat round-trip) — or let the user run the CLI command in their own terminal.',
868
+ };
869
+ }
834
870
  // Order-independent reveal pair: `echo secret get <ref> --stdout | xargs
835
871
  // npx huaweicloud-devkit` reorders the argv through xargs while every word
836
872
  // is literal in the text — the patterns above assume bin-before-
@@ -38,6 +38,8 @@ export function loadPolicy(path) {
38
38
  blockedSecretOperations: toStringArray(raw.blockedSecretOperations, 'blockedSecretOperations'),
39
39
  blockedSecretCliPatterns: toStringArray(raw.blockedSecretCliPatterns, 'blockedSecretCliPatterns'),
40
40
  blockedApprovalCliPatterns: toStringArray(raw.blockedApprovalCliPatterns, 'blockedApprovalCliPatterns'),
41
+ blockedAccountSwitchCliPatterns: toStringArray(raw.blockedAccountSwitchCliPatterns, 'blockedAccountSwitchCliPatterns'),
42
+ blockedGatedCliPatterns: toStringArray(raw.blockedGatedCliPatterns, 'blockedGatedCliPatterns'),
41
43
  writeOperationPrefixes,
42
44
  readOperationPrefixes: toStringArray(raw.readOperationPrefixes, 'readOperationPrefixes'),
43
45
  readOperationExceptions: toStringArray(raw.readOperationExceptions, 'readOperationExceptions'),
@@ -4,11 +4,18 @@ function isSecretKeyName(key, policy = DEFAULT_POLICY) {
4
4
  const normalized = String(key)
5
5
  .toLowerCase()
6
6
  .replace(/[^a-z0-9]/g, '');
7
- if (/access.*key|secret.*key|security.*token|xauth.*token|authorization|password|passwd|adminpass|credential|private.*key|userdata|metadata|inputvalue/.test(normalized)) {
7
+ if (/access.*key|secret.*key|secret.*string|secret.*binary|secret.*text|api.*key|security.*token|xauth.*token|authorization|password|passwd|adminpass|credential|private.*key|userdata|metadata|inputvalue/.test(normalized)) {
8
8
  return true;
9
9
  }
10
10
  return policy.secretKeyNamePatterns.some((pattern) => regexFrom(`^(${pattern})$`).test(String(key)));
11
11
  }
12
+ // The key vocabulary is shared by every evidence/command redaction face.
13
+ // Backslashes around the key/value are tolerated because shell-transcribed
14
+ // commands and nested JSON carry `\"password\":\"…\"` spellings; `secret://`
15
+ // refs are exempt (the ref is conversation-safe by doctrine). `secret_text`
16
+ // and `api_key` joined the family with the AX N-R4.1 fix — DEW's plaintext
17
+ // secret and the DevBridge key were crossing every evidence surface.
18
+ const SECRET_KEY_VALUE_RE = /((?:access[_-]?key(?:[_-]?(?:id|secret))?|secret[_-]?key|secret[_-]?string|secret[_-]?binary|secret[_-]?text|api[_-]?key|secret(?!:\/)|security[_-]?token|x[_-]?auth[_-]?token|token|authorization|password|passwd|admin[_-]?pass|credential|input[_-]?value)\\*["']?\s*[:=]\s*[\\"']*\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi;
12
19
  function redactString(text) {
13
20
  return (String(text)
14
21
  // Opaque blob keys (cloud-init user_data, metadata, private_key) carry
@@ -22,8 +29,19 @@ function redactString(text) {
22
29
  // credential itself, so this family consumes to end-of-line like the
23
30
  // blob-key branch above.
24
31
  .replace(/(["']?(?:user[_-]?data|metadata|private[_-]?key|authorization|x[_-]?auth[_-]?token)["']?\s*[:=]\s*).*/gi, '$1<redacted>')
25
- .replace(/(["']?(?:access[_-]?key(?:[_-]?(?:id|secret))?|secret[_-]?key|secret[_-]?string|secret[_-]?binary|security[_-]?token|token|password|passwd|admin[_-]?pass|credential|input[_-]?value)["']?\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1<redacted>')
26
- .replace(/\b(["']?(?:AK|SK)["']?\s*[:=]\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1<redacted>'));
32
+ .replace(SECRET_KEY_VALUE_RE, '$1<redacted>')
33
+ // XML settings shapes (`<password>value</password>`, the settings.xml
34
+ // deploy idiom) carry no `:`/`=` separator, so the key-value family
35
+ // never saw them — the artifact evidence echoed the password verbatim
36
+ // (AX N-R4.1). The tag name is backreferenced so a mismatched close
37
+ // tag is not half-redacted.
38
+ .replace(/<(password|passwd|pwd)>[^<]*<\/\1>/gi, '<$1><redacted></$1>')
39
+ .replace(/\b(["']?(?:AK|SK)\\*["']?\s*[:=]\s*[\\"']*\s*)("[^"]*"|'[^']*'|[^\s,;]+)/gi, '$1<redacted>'));
40
+ }
41
+ // The string-level evidence redaction entry (risk-rule-engine's excerpt and
42
+ // any future evidence face): one vocabulary, no second drift-prone copy.
43
+ export function redactEvidenceText(text) {
44
+ return redactString(text);
27
45
  }
28
46
  export function redactSecrets(value, policy = DEFAULT_POLICY) {
29
47
  if (Array.isArray(value)) {
@@ -6,17 +6,37 @@ import { evaluateCommandRisk, mergeRiskDecision } from "../risk-rule-engine.js";
6
6
  function commandRiskText(normalizedArgs, options) {
7
7
  return options.rawCommand || ['hcloud', ...normalizedArgs].join(' ');
8
8
  }
9
+ // A deny-severity base (the generic write/execution gate) still carries the
10
+ // catalog's specialized findings: the approval decision the developer reads
11
+ // must show WHY the command is risky (broad administrator grant, anonymous
12
+ // write, high-cost shape), not only the generic "write must be approved".
13
+ // Only findings/warnings are attached — decision, risk, and reason stay the
14
+ // base's, so the PreToolUse hook's risk-shaped exemption logic does not
15
+ // drift.
16
+ function attachRiskFindings(base, risk) {
17
+ if (!risk.findings || risk.findings.length === 0)
18
+ return base;
19
+ const warnFindings = risk.findings.filter((finding) => finding.severity !== 'deny');
20
+ return {
21
+ ...base,
22
+ findings: [...(base.findings || []), ...risk.findings],
23
+ ...(warnFindings.length > 0 ? { warnings: [...(base.warnings || []), ...warnFindings] } : {}),
24
+ };
25
+ }
26
+ function mergeRisk(base, risk) {
27
+ return base.decision === 'deny' ? attachRiskFindings(base, risk) : mergeRiskDecision(base, risk);
28
+ }
9
29
  export function applyCommandRiskRules(base, normalizedArgs, options) {
10
- if (base.decision === 'deny' || options.skipRiskRules === true) {
30
+ if (options.skipRiskRules === true) {
11
31
  return base;
12
32
  }
13
33
  const risk = evaluateCommandRisk(commandRiskText(normalizedArgs, options));
14
- return mergeRiskDecision(base, risk);
34
+ return mergeRisk(base, risk);
15
35
  }
16
36
  export function applyRawCommandRiskRules(base, command, options) {
17
- if (base.decision === 'deny' || options.skipRiskRules === true) {
37
+ if (options.skipRiskRules === true) {
18
38
  return base;
19
39
  }
20
40
  const risk = evaluateCommandRisk(command);
21
- return mergeRiskDecision(base, risk);
41
+ return mergeRisk(base, risk);
22
42
  }
@@ -11,7 +11,7 @@ import { DEVBRIDGE_BAD_GATEWAY_MARKER, DEVBRIDGE_PORT_NOT_CONFIGURED_MARKER, DEV
11
11
  import { stripTerminalEscapes } from "./sandbox-output.js";
12
12
  export const TUNNEL_URL_PATTERN = /TUNNEL_URL:(https:\/\/[A-Za-z0-9_-]+-\d+\.devbridge-s2\.hwtunnel\.com)/;
13
13
  export function buildExposeRemediation(port) {
14
- return `In the sandbox: source /tmp/hw_api_key 2>/dev/null; devbridge delete-all; devbridge create <name>; devbridge port create <tunnelId> -p ${port} --protocol http -a; if command -v setsid >/dev/null 2>&1; then setsid nohup devbridge host <tunnelId> -p ${port} -e 72 > /tmp/host.log 2>&1 < /dev/null & else nohup devbridge host <tunnelId> -p ${port} -e 72 > /tmp/host.log 2>&1 < /dev/null & fi; disown 2>/dev/null || true; If deploy_nginx reported a different (auto-incremented) port in its "port" field, use THAT port instead of the one shown here. Full procedure in huawei-sandbox skill, Step 7 (Expose via DevBridge).`;
14
+ return `In the sandbox: source /tmp/hw_api_key 2>/dev/null; for T in $(devbridge list 2>/dev/null | awk '{gsub(/\\033\\]133;C\\007/, ""); if ($1 !~ /^Tunnel/ && $1 !~ /^No$/) print $1}'); do devbridge port list "$T" 2>/dev/null | awk -v P=${port} '{gsub(/\\033\\]133;C\\007/, ""); if ($1 == P) f=1} END {exit f ? 0 : 1}' && devbridge delete "$T" 2>/dev/null || true; done; devbridge create <name>; devbridge port create <tunnelId> -p ${port} --protocol http -a; if command -v setsid >/dev/null 2>&1; then setsid nohup devbridge host <tunnelId> -p ${port} -e 72 > /tmp/host.log 2>&1 < /dev/null & else nohup devbridge host <tunnelId> -p ${port} -e 72 > /tmp/host.log 2>&1 < /dev/null & fi; disown 2>/dev/null || true; the loop deletes ONLY the tunnels whose port list contains ${port} (any tunnel name — query each tunnel's ports with devbridge port list; a name-based match would miss the custom-named tunnels this flow itself creates), INCLUDING a keepalive-protected tunnel bound to THIS port — a port cannot have two tunnels, so the same-port tunnel is always replaced; all OTHER ports, other sessions and keepalive-protected tunnels on other ports are preserved (never wipe every tunnel here — a global delete kills every session's tunnels). The gsub strips OSC 133 shell-integration markers that wrap every output line on integration-enabled terminals — without it the CLI receives glued tunnel IDs it rejects and the delete silently no-ops. If deploy_nginx reported a different (auto-incremented) port in its "port" field, use THAT port instead of the one shown here. Full procedure in huawei-sandbox skill, Step 7 (Expose via DevBridge).`;
15
15
  }
16
16
  export function parseDeployCheckOutput(stdout) {
17
17
  // Strip ANSI escape sequences (CSI color/cursor codes and OSC shell-integration markers)
@@ -1,6 +1,27 @@
1
1
  import { stripTerminalEscapes } from "./sandbox-output.js";
2
2
  import { runOneShot } from "./devbridge-exec.js";
3
3
  import { evaluateDevbridgeVersion } from "./devbridge-validation.js";
4
+ import { canonCode, cleanMessage, gateFoldPayload, isVersionGateError, safeMessageText, safeReadField, } from "../lib/hdkit/hdkit-gate.js";
5
+ // 409 门禁在 relay 出口的统一折叠(v2 扩展,台账记录):三个 catch 位共用——
6
+ // 自动创建、自愈重建、配额清单读取。authMode/attempts 保留(探测到的真实状态,
7
+ // 与配额失败信封同款,台账记录该取舍)。
8
+ function versionGateFailure(error, port, authMode, attempts) {
9
+ const fold = gateFoldPayload(error);
10
+ return {
11
+ ok: false,
12
+ failure: {
13
+ ok: false,
14
+ port,
15
+ error: fold.message,
16
+ error_code: fold.code,
17
+ ...(fold.clientVersion ? { clientVersion: fold.clientVersion } : {}),
18
+ ...(fold.minVersion ? { minVersion: fold.minVersion } : {}),
19
+ gateRemediation: fold.remediation,
20
+ authMode: authMode || 'UNKNOWN',
21
+ attempts,
22
+ },
23
+ };
24
+ }
4
25
  // The DevBridge auth waterfall, extracted from devbridge-tunnel so the auth
5
26
  // probe script, its stdout parser, and (with the devbridge-tunnel
6
27
  // modularization) the expose flow's auth/version gate form one cohesive auth
@@ -16,8 +37,12 @@ import { evaluateDevbridgeVersion } from "./devbridge-validation.js";
16
37
  // fallback (devbridge-key.ts) when keyring injection is unavailable.
17
38
  // AK/SK login (--access-key/--secret-key) was REMOVED: devbridge authentication is
18
39
  // now fixed to API Key only (定稿决策,2026-11-04).
19
- // Every tier performs a real `devbridge auth login --api-key` and verifies with
20
- // `auth status` (must print "Logged in"); on failure the waterfall falls through.
40
+ // Every tier performs a real `devbridge auth login --api-key` (exit code checked),
41
+ // then verifies with `auth status` AND a real authenticated API call
42
+ // (`devbridge list`); on failure the waterfall falls through. The list check is
43
+ // required because a stale key can leave a "Logged in" local token while
44
+ // server-side calls return 40100 — without it the probe reports a usable auth
45
+ // and the auto-create self-heal never triggers.
21
46
  // DB_ATTEMPT_* lines are non-sensitive diagnostics for support escalation.
22
47
  // The HOST orchestrates an auto-create fallback between probe rounds: when the
23
48
  // first probe returns NO_CREDENTIAL, the host calls ensureDevbridgeKey() and
@@ -37,7 +62,13 @@ export function buildDevbridgeAuthProbe() {
37
62
  `DB_VERSION=$(devbridge version 2>/dev/null | head -1)`,
38
63
  `echo "DB_VERSION=\${DB_VERSION}"`,
39
64
  `DB_OK=0`,
40
- `db_login_ok() { devbridge auth status 2>/dev/null | grep -q "Logged in"; }`,
65
+ `db_login_ok() {`,
66
+ // 本地 token 可能仍显示 Logged in,但 API key 已在服务端失效(实测
67
+ // list/renew 返回 40100)。因此额外做一次真实鉴权 API 调用,确保探针
68
+ // 结果可用(否则 auto-create 自愈不会触发)。
69
+ ` devbridge auth status 2>/dev/null | grep -q "Logged in" || return 1`,
70
+ ` devbridge list >/dev/null 2>&1`,
71
+ `}`,
41
72
  `db_diag() { echo "DB_ATTEMPT_$1=$2"; }`,
42
73
  ``,
43
74
  `# ---- Tier 1: API Key from the sandbox keyring (platform auto-injection) ----`,
@@ -67,8 +98,7 @@ export function buildDevbridgeAuthProbe() {
67
98
  ` db_diag KEYRING "hwcloud-not-installed"`,
68
99
  `fi`,
69
100
  `if [ -n "$HW_DB_KEY" ]; then`,
70
- ` devbridge auth login --api-key "$HW_DB_KEY" >/tmp/db_auth.log 2>&1`,
71
- ` if db_login_ok; then`,
101
+ ` if devbridge auth login --api-key "$HW_DB_KEY" >/tmp/db_auth.log 2>&1 && db_login_ok; then`,
72
102
  ` echo "DB_AUTH_MODE=API_KEY_KEYRING"`,
73
103
  ` DB_OK=1`,
74
104
  ` else`,
@@ -82,8 +112,7 @@ export function buildDevbridgeAuthProbe() {
82
112
  `if [ "$DB_OK" -eq 0 ]; then`,
83
113
  ` source /tmp/hw_api_key 2>/dev/null`,
84
114
  ` if [ -n "$HW_API_KEY" ]; then`,
85
- ` devbridge auth login --api-key "$HW_API_KEY" >/tmp/db_auth.log 2>&1`,
86
- ` if db_login_ok; then`,
115
+ ` if devbridge auth login --api-key "$HW_API_KEY" >/tmp/db_auth.log 2>&1 && db_login_ok; then`,
87
116
  ` echo "DB_AUTH_MODE=API_KEY_FILE"`,
88
117
  ` DB_OK=1`,
89
118
  ` else`,
@@ -188,8 +217,11 @@ export async function gateExposeAuth(workspaceId, username, port, { poolType, ke
188
217
  effectiveAuthMode = 'API_KEY_AUTO';
189
218
  }
190
219
  }
191
- catch {
192
- // 自愈失败 → 走泛化降级
220
+ catch (error) {
221
+ // 409 门禁即时折叠:自愈 catch 原样吞掉会多跑一轮泛化 relay 调用才折
222
+ // 叠(round 3);其余自愈失败仍走泛化降级
223
+ if (isVersionGateError(error))
224
+ return versionGateFailure(error, port, authMode, attempts);
193
225
  }
194
226
  }
195
227
  // keyring/文件均无 key → host 调 relay API 自动创建 → 注入沙箱 → 重跑 probe
@@ -204,15 +236,33 @@ export async function gateExposeAuth(workspaceId, username, port, { poolType, ke
204
236
  }
205
237
  }
206
238
  catch (error) {
207
- // 自动创建失败(含配额满 13002)→ 结构化降级
208
- if (error.code === 'HDKIT_DEVBRIDGE_KEY_QUOTA_EXCEEDED') {
209
- const keysHint = await keyUpgrade.listKeysForQuotaHint();
239
+ // 门禁先裁(round 25/MUST 4):配额比较此前先求值且自选分支——登记
240
+ // 过的载体 code 视图谎报配额码即被误路由进清 key 信封(配额 hint、空
241
+ // currentKeys、gateRemediation 丢失)。isVersionGateError 对登记载体零
242
+ // 读返回种类裁决(round 24),谎报视图无从介入;未登记载体照旧先经安
243
+ // 全读判配额——canonCode 读过卫队(round 14),抛出型 getter 按缺失
244
+ if (isVersionGateError(error))
245
+ return versionGateFailure(error, port, authMode, attempts);
246
+ if (canonCode(safeReadField(error, 'code')) === 'HDKIT_DEVBRIDGE_KEY_QUOTA_EXCEEDED') {
247
+ // 配额清单读取本身遭遇 409:门禁优先(清 key 引导拿不出 currentKeys);
248
+ // 其余读取失败仍降级为空清单
249
+ let keysHint = [];
250
+ try {
251
+ keysHint = await keyUpgrade.listKeysForQuotaHint();
252
+ }
253
+ catch (listError) {
254
+ if (isVersionGateError(listError))
255
+ return versionGateFailure(listError, port, authMode, attempts);
256
+ }
257
+ // 消息读同样过卫队与清洗口(round 14):拒读/空白按缺失——字段缺省,
258
+ // 信封的 error_code/hint/currentKeys 不受影响
259
+ const quotaMessage = cleanMessage(safeMessageText(error));
210
260
  return {
211
261
  ok: false,
212
262
  failure: {
213
263
  ok: false,
214
264
  port,
215
- error: error.message,
265
+ ...(quotaMessage ? { error: quotaMessage } : {}),
216
266
  error_code: 'HDKIT_DEVBRIDGE_KEY_QUOTA_EXCEEDED',
217
267
  authMode: authMode || 'UNKNOWN',
218
268
  attempts,
@@ -221,7 +271,8 @@ export async function gateExposeAuth(workspaceId, username, port, { poolType, ke
221
271
  },
222
272
  };
223
273
  }
224
- // 其他自动创建失败 → 继续走原有降级路径(可能 keyring/file 后续可用)
274
+ // 其他自动创建失败 → 继续走原有降级路径(可能 keyring/file 后续可用);
275
+ // 门禁折叠已在本 catch 顶部先裁(round 25/MUST 4)
225
276
  }
226
277
  }
227
278
  }