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

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 (161) hide show
  1. package/README.md +3 -1
  2. package/package.json +3 -1
  3. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +16 -3
  4. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +16 -3
  5. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +16 -3
  6. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +16 -3
  7. package/plugins/huaweicloud-core/.mcp.json +55 -1
  8. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +16 -3
  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/hcloud-cli.js +1 -1
  22. package/plugins/huaweicloud-core/dist/hcloud-plan.js +62 -61
  23. package/plugins/huaweicloud-core/dist/lib/approval-mode.js +7 -5
  24. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +18 -4
  25. package/plugins/huaweicloud-core/dist/lib/call-trace.js +7 -14
  26. package/plugins/huaweicloud-core/dist/lib/confirm-language.js +50 -0
  27. package/plugins/huaweicloud-core/dist/lib/credentials.js +9 -9
  28. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkit-gate.js +1398 -0
  29. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +362 -32
  30. package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +6 -16
  31. package/plugins/huaweicloud-core/dist/lib/opencode-ask-rule.js +224 -78
  32. package/plugins/huaweicloud-core/dist/lib/opencode-saved-perms.js +282 -0
  33. package/plugins/huaweicloud-core/dist/lib/supplemental-redaction.js +116 -0
  34. package/plugins/huaweicloud-core/dist/lib/tool-schema-parts.js +31 -0
  35. package/plugins/huaweicloud-core/dist/lib/workspace-glob.js +442 -0
  36. package/plugins/huaweicloud-core/dist/mcp-config-io.js +28 -1
  37. package/plugins/huaweicloud-core/dist/mcp-protocol.js +68 -16
  38. package/plugins/huaweicloud-core/dist/mcp-server.js +6506 -912
  39. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  40. package/plugins/huaweicloud-core/dist/mcp-stdio-transport.js +14 -4
  41. package/plugins/huaweicloud-core/dist/packs/auth/approval.js +249 -0
  42. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +44 -44
  43. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +85 -130
  44. package/plugins/huaweicloud-core/dist/packs/obs/approval.js +110 -0
  45. package/plugins/huaweicloud-core/dist/packs/obs/tools.js +7 -2
  46. package/plugins/huaweicloud-core/dist/packs/registry.js +19 -1
  47. package/plugins/huaweicloud-core/dist/packs/sandbox/approval.js +245 -0
  48. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +156 -23
  49. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +13 -1
  50. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-hwexec.js +136 -0
  51. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +11 -1
  52. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +1 -0
  53. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +79 -9
  54. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +28 -9
  55. package/plugins/huaweicloud-core/dist/packs/secrets/approval.js +46 -0
  56. package/plugins/huaweicloud-core/dist/packs/secrets/tools.js +4 -1
  57. package/plugins/huaweicloud-core/dist/packs/update/approval.js +79 -0
  58. package/plugins/huaweicloud-core/dist/packs/update/tools.js +8 -1
  59. package/plugins/huaweicloud-core/dist/packs/voucher/tools.js +1 -1
  60. package/plugins/huaweicloud-core/dist/packs-configure.js +74 -0
  61. package/plugins/huaweicloud-core/dist/safety/classify-text.js +36 -0
  62. package/plugins/huaweicloud-core/dist/safety/policy.js +2 -0
  63. package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +1 -1
  64. package/plugins/huaweicloud-core/dist/sandbox/devbridge-auth.js +65 -14
  65. package/plugins/huaweicloud-core/dist/sandbox/devbridge-cleanup.js +422 -0
  66. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose-flow.js +66 -16
  67. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose.js +13 -10
  68. package/plugins/huaweicloud-core/dist/sandbox/devbridge-keepalive.js +42 -2
  69. package/plugins/huaweicloud-core/dist/sandbox/devbridge-key.js +11 -3
  70. package/plugins/huaweicloud-core/dist/sandbox/devbridge-tunnel.js +6 -0
  71. package/plugins/huaweicloud-core/dist/sandbox/devbridge-validation.js +10 -1
  72. package/plugins/huaweicloud-core/dist/sandbox/hwexec-task.js +244 -0
  73. package/plugins/huaweicloud-core/dist/setup-cli.js +36 -1
  74. package/plugins/huaweicloud-core/dist/tool-definitions.js +9 -1
  75. package/plugins/huaweicloud-core/dist/tool-schemas.js +32 -6
  76. package/plugins/huaweicloud-core/dist/tools.js +76 -9
  77. package/plugins/huaweicloud-core/dist/update-registry.js +358 -5
  78. package/plugins/huaweicloud-core/dist/update-upgrade.js +1083 -14
  79. package/plugins/huaweicloud-core/dist/vendor-gate.js +2 -2
  80. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +150 -1
  81. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +53 -3
  82. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  83. package/plugins/huaweicloud-core/safety/policy.json +18 -11
  84. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +114 -10
  85. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +190 -138
  86. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +36 -12
  87. package/plugins/huaweicloud-core/skills/huawei-voucher/SKILL.md +2 -0
  88. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +2 -2
  89. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +11 -7
  90. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +74 -29
  91. package/plugins/huaweicloud-core/skills/huaweicloud-troubleshooting/SKILL.md +21 -19
  92. package/plugins/huaweicloud-core/src/agents/codex-config.ts +432 -0
  93. package/plugins/huaweicloud-core/src/agents/codex-desktop.ts +8 -1
  94. package/plugins/huaweicloud-core/src/agents/codex.ts +10 -0
  95. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +176 -88
  96. package/plugins/huaweicloud-core/src/agents/opencode.ts +125 -54
  97. package/plugins/huaweicloud-core/src/approval-gate.ts +1306 -0
  98. package/plugins/huaweicloud-core/src/approval-ledger.ts +2446 -0
  99. package/plugins/huaweicloud-core/src/approval-roster.ts +127 -0
  100. package/plugins/huaweicloud-core/src/approval-types.ts +237 -0
  101. package/plugins/huaweicloud-core/src/approvals-cli.ts +4 -4
  102. package/plugins/huaweicloud-core/src/data/icons-manifest.v1.json +23 -5
  103. package/plugins/huaweicloud-core/src/dep/receipts.ts +84 -5
  104. package/plugins/huaweicloud-core/src/hcloud-cli.ts +3 -0
  105. package/plugins/huaweicloud-core/src/hcloud-plan.ts +68 -70
  106. package/plugins/huaweicloud-core/src/lib/approval-mode.ts +7 -5
  107. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +19 -4
  108. package/plugins/huaweicloud-core/src/lib/call-trace.ts +7 -17
  109. package/plugins/huaweicloud-core/src/lib/confirm-language.ts +51 -0
  110. package/plugins/huaweicloud-core/src/lib/credentials.ts +9 -8
  111. package/plugins/huaweicloud-core/src/lib/hdkit/hdkit-gate.ts +1428 -0
  112. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +377 -30
  113. package/plugins/huaweicloud-core/src/lib/hdkit/sandbox-pool.ts +8 -15
  114. package/plugins/huaweicloud-core/src/lib/opencode-ask-rule.ts +302 -83
  115. package/plugins/huaweicloud-core/src/lib/opencode-saved-perms.ts +354 -0
  116. package/plugins/huaweicloud-core/src/lib/supplemental-redaction.ts +129 -0
  117. package/plugins/huaweicloud-core/src/lib/tool-schema-parts.ts +40 -0
  118. package/plugins/huaweicloud-core/src/lib/workspace-glob.ts +414 -0
  119. package/plugins/huaweicloud-core/src/mcp-config-io.ts +27 -1
  120. package/plugins/huaweicloud-core/src/mcp-protocol.ts +81 -17
  121. package/plugins/huaweicloud-core/src/mcp-server.ts +7 -7
  122. package/plugins/huaweicloud-core/src/mcp-stdio-transport.ts +14 -4
  123. package/plugins/huaweicloud-core/src/packs/auth/approval.ts +302 -0
  124. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +54 -45
  125. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +99 -137
  126. package/plugins/huaweicloud-core/src/packs/obs/approval.ts +122 -0
  127. package/plugins/huaweicloud-core/src/packs/obs/tools.ts +7 -2
  128. package/plugins/huaweicloud-core/src/packs/registry.ts +42 -1
  129. package/plugins/huaweicloud-core/src/packs/sandbox/approval.ts +296 -0
  130. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +168 -23
  131. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +11 -1
  132. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-hwexec.ts +228 -0
  133. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +11 -1
  134. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +1 -0
  135. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +100 -8
  136. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +31 -8
  137. package/plugins/huaweicloud-core/src/packs/secrets/approval.ts +50 -0
  138. package/plugins/huaweicloud-core/src/packs/secrets/tools.ts +4 -1
  139. package/plugins/huaweicloud-core/src/packs/update/approval.ts +87 -0
  140. package/plugins/huaweicloud-core/src/packs/update/tools.ts +8 -1
  141. package/plugins/huaweicloud-core/src/packs/voucher/tools.ts +1 -1
  142. package/plugins/huaweicloud-core/src/packs-configure.ts +75 -0
  143. package/plugins/huaweicloud-core/src/safety/classify-text.ts +40 -0
  144. package/plugins/huaweicloud-core/src/safety/policy.ts +7 -0
  145. package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +1 -1
  146. package/plugins/huaweicloud-core/src/sandbox/devbridge-auth.ts +74 -14
  147. package/plugins/huaweicloud-core/src/sandbox/devbridge-cleanup.ts +509 -0
  148. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose-flow.ts +70 -18
  149. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose.ts +26 -10
  150. package/plugins/huaweicloud-core/src/sandbox/devbridge-keepalive.ts +41 -2
  151. package/plugins/huaweicloud-core/src/sandbox/devbridge-key.ts +9 -3
  152. package/plugins/huaweicloud-core/src/sandbox/devbridge-tunnel.ts +24 -0
  153. package/plugins/huaweicloud-core/src/sandbox/devbridge-validation.ts +11 -1
  154. package/plugins/huaweicloud-core/src/sandbox/hwexec-task.ts +304 -0
  155. package/plugins/huaweicloud-core/src/setup-cli.ts +39 -1
  156. package/plugins/huaweicloud-core/src/tool-definitions.ts +9 -1
  157. package/plugins/huaweicloud-core/src/tool-schemas.ts +39 -6
  158. package/plugins/huaweicloud-core/src/tools.ts +124 -10
  159. package/plugins/huaweicloud-core/src/update-registry.ts +340 -5
  160. package/plugins/huaweicloud-core/src/update-upgrade.ts +1130 -14
  161. package/plugins/huaweicloud-core/src/vendor-gate.ts +2 -2
@@ -0,0 +1,296 @@
1
+ import { asText } from '../../lib/as-text.ts';
2
+ import { hashArgs } from '../../lib/approval-tokens.ts';
3
+ import { classifyTextCommand, redactSecrets } from '../../safety-policy.ts';
4
+ import { evaluateCommandRisk, loadRiskRules, type RiskCatalog } from '../../risk-rule-engine.ts';
5
+ import { redactWithSupplementalKeys } from '../../lib/supplemental-redaction.ts';
6
+ import { isSecretRef } from '../../lib/secret-vault/refs.ts';
7
+ import type { ApprovalSpec } from '../../approval-types.ts';
8
+ import type { ToolArgs } from '../../tools.ts';
9
+
10
+ // The sandbox pack's approval spec table. Nine tools join the gate: the two
11
+ // exec faces are CLASSIFIED (content decides — a benign command runs with no
12
+ // confirmation surface at all, a write-classified one confirms on every
13
+ // call), the seven mutating lifecycle faces are ALWAYS (a human present per
14
+ // call, no content rule ever exempts them). The strict classification runs
15
+ // on the exec faces' `command` argument through the SAME engines the Bash
16
+ // face uses — classifyTextCommand plus the cloud-risk-rules catalog — so a
17
+ // destructive command is a disabled guard at the gate face (never a minted
18
+ // token the run then denies, ApprovalCoreMint's NoDoomedToken) and the deny
19
+ // survives every confirmation channel.
20
+ //
21
+ // The binding value is the call's own arguments with the approval carriers
22
+ // (approvalToken, approvedByUser, vendorConfirmed) stripped: the hash the
23
+ // token binds and the ledger records is the CONTENT the user confirms, so a
24
+ // retry that only drifts on a carrier rides the same consent key.
25
+
26
+ // Approval-chain carrier fields: never part of the content the user
27
+ // confirms. `command` stays IN the binding — on the exec faces it is the
28
+ // content itself, not a display anchor (the commandAnchor machinery is the
29
+ // hcloud pair's; these tools declare none).
30
+ const APPROVAL_CARRIER_KEYS = new Set(['approvalToken', 'approvedByUser', 'vendorConfirmed']);
31
+
32
+ export function bindingArgs(args: ToolArgs): Record<string, unknown> {
33
+ const out: Record<string, unknown> = {};
34
+ for (const [key, value] of Object.entries(args ?? {})) {
35
+ if (APPROVAL_CARRIER_KEYS.has(key)) continue;
36
+ out[key] = value;
37
+ }
38
+ return out;
39
+ }
40
+
41
+ // The pin view: the binding value through the product's redaction pipeline
42
+ // plus the supplemental key vocabulary the trace face shares (api_key and
43
+ // the value channel — sandbox_credentials' long-lived DevBridge key rides
44
+ // api_key; no sandbox tool uses `value`, so the entry is collision-free).
45
+ function pinViewOf(bindingValue: unknown): unknown {
46
+ return redactWithSupplementalKeys(redactSecrets(bindingValue));
47
+ }
48
+
49
+ // The strict ruling over an exec command, one evaluation shared by the
50
+ // spec's classify (the confirmation question) and its execution floor (the
51
+ // never-unlockable denies): write/execution content confirms, every other
52
+ // deny — destructive, secret, credential, invalid — refuses outright
53
+ // whatever the channel, and the rules engine's own deny findings win over a
54
+ // text-classifier pass. The WeakMap collapses the two evaluations the gate
55
+ // performs per arrival (classify, then the floor) onto one.
56
+ export interface SandboxCommandRuling {
57
+ verdict: 'required' | 'none';
58
+ denyReason?: string;
59
+ }
60
+
61
+ const rulingMemo = new WeakMap<object, SandboxCommandRuling>();
62
+
63
+ function computeRuling(command: string): SandboxCommandRuling {
64
+ // The catalog is file-backed; read it once per process (classify stays a
65
+ // pure function of its input — same command, same ruling).
66
+ const catalog: RiskCatalog = loadRiskRules();
67
+ const rulesDeny = evaluateCommandRisk(command, { catalog }).findings.find((finding) => finding.severity === 'deny');
68
+ if (rulesDeny) {
69
+ return {
70
+ verdict: 'none',
71
+ denyReason: `rule ${rulesDeny.ruleId}: ${rulesDeny.message} Remediation: ${rulesDeny.remediation}`,
72
+ };
73
+ }
74
+ const text = classifyTextCommand(command);
75
+ if (text.decision === 'deny' && (text.risk === 'write' || text.risk === 'execution')) {
76
+ return { verdict: 'required' };
77
+ }
78
+ if (text.decision === 'deny') {
79
+ return { verdict: 'none', denyReason: text.reason ?? 'the command is blocked by strict classification.' };
80
+ }
81
+ return { verdict: 'none' };
82
+ }
83
+
84
+ function rulingForBinding(bindingValue: unknown): SandboxCommandRuling {
85
+ if (bindingValue && typeof bindingValue === 'object' && !Array.isArray(bindingValue)) {
86
+ const cached = rulingMemo.get(bindingValue);
87
+ if (cached) return cached;
88
+ const ruling = computeRuling(asText((bindingValue as Record<string, unknown>).command ?? ''));
89
+ rulingMemo.set(bindingValue, ruling);
90
+ return ruling;
91
+ }
92
+ return computeRuling(asText(bindingValue));
93
+ }
94
+
95
+ // The execution floor: a strict deny refuses in BOTH modes, before any mint,
96
+ // consent record, or token consume — destructive content is never
97
+ // unlockable, so the refusal names the rule and nothing burns.
98
+ function assertCommandAllowed(bindingValue: unknown): void {
99
+ const ruling = rulingForBinding(bindingValue);
100
+ if (ruling.denyReason === undefined) return;
101
+ throw new Error(
102
+ 'Sandbox command denied by strict classification (no confirmation unlocks it). ' + `${ruling.denyReason}`,
103
+ );
104
+ }
105
+
106
+ // One summarized view per tool family. Every string the view carries is
107
+ // built from the REDACTED pin view — the summarize contract forbids the raw
108
+ // argument stream in any popup surface.
109
+ function asRecordView(bindingValue: unknown): Record<string, unknown> {
110
+ return bindingValue && typeof bindingValue === 'object' && !Array.isArray(bindingValue)
111
+ ? (bindingValue as Record<string, unknown>)
112
+ : {};
113
+ }
114
+
115
+ function viewOf(bindingValue: unknown, summary: (view: Record<string, unknown>) => string) {
116
+ const record = asRecordView(bindingValue);
117
+ return {
118
+ summary: summary(record),
119
+ argsHash: hashArgs(bindingValue),
120
+ pinView: pinViewOf(bindingValue),
121
+ };
122
+ }
123
+
124
+ // A short redacted field echo for the summary line: "port 8080" style, never
125
+ // the whole JSON blob.
126
+ function fieldEcho(view: Record<string, unknown>, keys: string[]): string {
127
+ const parts: string[] = [];
128
+ for (const key of keys) {
129
+ const value = view[key];
130
+ if (value === undefined || value === null || value === '') continue;
131
+ const text = asText(pinViewOf(value));
132
+ parts.push(`${key} ${text}`);
133
+ }
134
+ return parts.join(', ');
135
+ }
136
+
137
+ function execView(toolShortName: string, bindingValue: unknown) {
138
+ const record = asRecordView(bindingValue);
139
+ const command = typeof record.command === 'string' ? asText(pinViewOf(record.command)) : '';
140
+ const where = fieldEcho(record, ['workspace_id', 'username']);
141
+ const summary =
142
+ `huaweicloud_sandbox_${toolShortName}${where !== '' ? ` (${where})` : ''}: ` +
143
+ (command !== '' ? command : '(no command)');
144
+ return {
145
+ summary,
146
+ argsHash: hashArgs(bindingValue),
147
+ pinView: pinViewOf(bindingValue),
148
+ ...(command !== '' ? { command } : {}),
149
+ };
150
+ }
151
+
152
+ // One shared spec line for every sandbox registration: the binding value is
153
+ // the call's own arguments with the approval carriers stripped (see
154
+ // bindingArgs). Without this the carriers ride into the hash — a retry
155
+ // carrying the token would bind differently from the mint, and every
156
+ // confirmation would be single-use-by-construction.
157
+ function sandboxBinding(): Pick<ApprovalSpec, 'domain' | 'tokenSource' | 'normalizeArgs'> {
158
+ return { domain: 'sandbox', tokenSource: 'gate', normalizeArgs: (args) => bindingArgs(args) };
159
+ }
160
+
161
+ function execSpec(toolShortName: 'exec_with_session' | 'exec_one_shot'): ApprovalSpec {
162
+ return {
163
+ ...sandboxBinding(),
164
+ flavor: 'classified',
165
+ classify: (bindingValue) => rulingForBinding(bindingValue).verdict,
166
+ assertArgsExecutable: (bindingValue) => assertCommandAllowed(bindingValue),
167
+ // The command IS the content, and the confirmation surfaces display it,
168
+ // so it anchors itself: provided must equal the binding's own command
169
+ // (it always does when the call is honest — the binding derives from
170
+ // the args). The anchor exists so the no-anchor refusal shape (a
171
+ // stuffed command on a tool that declares no displayable line) never
172
+ // kills the exec faces after the serial landing (the anchor-collision
173
+ // decision): the exec calls are anchored, the seven lifecycle faces are
174
+ // not and refuse a stuffed command.
175
+ commandAnchor: (bindingValue) => {
176
+ const command = (bindingValue as Record<string, unknown>).command;
177
+ return typeof command === 'string' && command !== '' ? [command] : [];
178
+ },
179
+ summarize: (bindingValue) => execView(toolShortName, bindingValue),
180
+ };
181
+ }
182
+
183
+ const connectSpec: ApprovalSpec = {
184
+ ...sandboxBinding(),
185
+ flavor: 'always',
186
+ summarize: (bindingValue) =>
187
+ viewOf(bindingValue, (view) => {
188
+ const target = fieldEcho(view, ['pool_type']);
189
+ return `huaweicloud_sandbox_connect: connect a sandbox${target !== '' ? ` (${target})` : ''}`;
190
+ }),
191
+ };
192
+
193
+ const exposeTunnelSpec: ApprovalSpec = {
194
+ ...sandboxBinding(),
195
+ flavor: 'always',
196
+ summarize: (bindingValue) =>
197
+ viewOf(bindingValue, (view) => {
198
+ const target = fieldEcho(view, ['port', 'expiry_hours']);
199
+ return `huaweicloud_sandbox_expose_tunnel: expose a public tunnel URL${target !== '' ? ` (${target})` : ''}`;
200
+ }),
201
+ };
202
+
203
+ const renewTunnelSpec: ApprovalSpec = {
204
+ ...sandboxBinding(),
205
+ flavor: 'always',
206
+ summarize: (bindingValue) =>
207
+ viewOf(bindingValue, (view) => {
208
+ const target = fieldEcho(view, ['tunnel_id', 'expiry_hours']);
209
+ return `huaweicloud_sandbox_renew_tunnel: renew a tunnel's lifetime${target !== '' ? ` (${target})` : ''}`;
210
+ }),
211
+ };
212
+
213
+ const keepaliveWatchdogSpec: ApprovalSpec = {
214
+ ...sandboxBinding(),
215
+ flavor: 'always',
216
+ summarize: (bindingValue) =>
217
+ viewOf(bindingValue, (view) => {
218
+ const count = Array.isArray(view.tunnels) ? view.tunnels.length : 0;
219
+ const ids = Array.isArray(view.tunnels)
220
+ ? view.tunnels
221
+ .map((tunnel) =>
222
+ tunnel && typeof tunnel === 'object' ? asText((tunnel as Record<string, unknown>).tunnel_id ?? '') : '',
223
+ )
224
+ .filter((id) => id !== '')
225
+ : [];
226
+ return `huaweicloud_sandbox_keepalive_watchdog: install/replace the keepalive watchdog over ${count} tunnel(s)${
227
+ ids.length > 0 ? ` (${ids.join(', ')})` : ''
228
+ }`;
229
+ }),
230
+ };
231
+
232
+ const signAgreementSpec: ApprovalSpec = {
233
+ ...sandboxBinding(),
234
+ flavor: 'always',
235
+ summarize: (bindingValue) =>
236
+ viewOf(
237
+ bindingValue,
238
+ () =>
239
+ 'huaweicloud_sandbox_sign_agreement: sign all unsigned or outdated Huawei Cloud developer service agreements for the current user',
240
+ ),
241
+ };
242
+
243
+ const credentialsSpec: ApprovalSpec = {
244
+ ...sandboxBinding(),
245
+ flavor: 'always',
246
+ summarize: (bindingValue) => {
247
+ // Name the api_key channel the HANDLER will actually use, never the
248
+ // value (interrogate F1 round 3, F2): handlers-credentials resolves
249
+ // env-first (process.env.HW_API_KEY || args.api_key), so the view
250
+ // mirrors that precedence — an env tier set makes the parameter or ref
251
+ // beside it a dead letter the confirmation must not claim. A vault ref
252
+ // is itself conversation-safe (that is the ref doctrine), and the
253
+ // parameter channel is named with the value redacted by the pin-view
254
+ // pass.
255
+ const rawApiKey = asText(asRecordView(bindingValue).api_key ?? '');
256
+ const channel = process.env.HW_API_KEY
257
+ ? 'api_key via environment (value redacted)'
258
+ : rawApiKey !== ''
259
+ ? isSecretRef(rawApiKey)
260
+ ? `api_key via vault ref ${rawApiKey}`
261
+ : 'api_key via parameter (value redacted)'
262
+ : '';
263
+ return viewOf(bindingValue, (view) => {
264
+ const target = fieldEcho(view, ['session_id', 'dev_stage_id', 'enable_sts']);
265
+ const scope = target !== '' ? ` (${target})` : '';
266
+ return (
267
+ `huaweicloud_sandbox_credentials: validate and inject temporary credentials into the sandbox${scope}` +
268
+ (channel !== '' ? `; ${channel}` : '')
269
+ );
270
+ });
271
+ },
272
+ };
273
+
274
+ // 关机(port-pr6):不可逆生命周期面,always。确认视图点名目标 id 与
275
+ // close-not-delete 事实——确认面显示的是开发者要关哪台沙箱,不是参数流。
276
+ const shutdownSpec: ApprovalSpec = {
277
+ ...sandboxBinding(),
278
+ flavor: 'always',
279
+ summarize: (bindingValue) =>
280
+ viewOf(bindingValue, (view) => {
281
+ const target = fieldEcho(view, ['session_id', 'dev_stage_id', 'workspace_id']);
282
+ return `huaweicloud_sandbox_shutdown: shut down the sandbox (close only — instance retained, reconnect wakes it)${target !== '' ? ` (${target})` : ''}`;
283
+ }),
284
+ };
285
+
286
+ export const SANDBOX_APPROVAL_SPECS = {
287
+ huaweicloud_sandbox_connect: connectSpec,
288
+ huaweicloud_sandbox_exec_with_session: execSpec('exec_with_session'),
289
+ huaweicloud_sandbox_exec_one_shot: execSpec('exec_one_shot'),
290
+ huaweicloud_sandbox_expose_tunnel: exposeTunnelSpec,
291
+ huaweicloud_sandbox_renew_tunnel: renewTunnelSpec,
292
+ huaweicloud_sandbox_keepalive_watchdog: keepaliveWatchdogSpec,
293
+ huaweicloud_sandbox_sign_agreement: signAgreementSpec,
294
+ huaweicloud_sandbox_credentials: credentialsSpec,
295
+ huaweicloud_sandbox_shutdown: shutdownSpec,
296
+ } as const satisfies Record<string, ApprovalSpec>;
@@ -1,6 +1,26 @@
1
- import { execOneShot, execWithSession, setWorkspaceId } from '../../sandbox/session-manager.ts';
2
- import { hdkitCheckUser, hdkitSignAgreement, hdkitConnect } from '../../lib/hdkit/hdkitservice-api.ts';
1
+ import { execWithSession, closeSession, getCurrentWorkspaceId, setWorkspaceId } from '../../sandbox/session-manager.ts';
2
+ import { cleanupDevbridgeTunnels } from '../../sandbox/devbridge-tunnel.ts';
3
+ import {
4
+ hdkitCheckUser,
5
+ hdkitSignAgreement,
6
+ hdkitConnectWithRetry,
7
+ hdkitShutdown,
8
+ } from '../../lib/hdkit/hdkitservice-api.ts';
9
+ import {
10
+ MANUFACTURED_FAMILY,
11
+ manufacturedPrefixPattern,
12
+ canonCode,
13
+ chainDataValue,
14
+ cleanMessage,
15
+ ownDataValue,
16
+ safeMessageText,
17
+ safeReadField,
18
+ serializableRemediation,
19
+ transientExhaustionResult,
20
+ versionGateResult,
21
+ } from '../../lib/hdkit/hdkit-gate.ts';
3
22
  import type { HdkitError } from '../../lib/hdkit/hdkitservice-api.ts';
23
+ import { asString } from '../../lib/as-text.ts';
4
24
  import {
5
25
  validatePoolType,
6
26
  rememberWorkspacePool,
@@ -10,18 +30,33 @@ import {
10
30
  import type { CallToolOptions, ToolArgs } from '../../tools.ts';
11
31
  import { transferGitRepo } from './git-transfer.ts';
12
32
 
13
- // Account/session-gate handlers (check_user, sign_agreement, connect) for
14
- // the sandbox pack, extracted verbatim from tools.ts in the within-pack
15
- // split for the jscpd complex-file bar; the tools.ts face imports them for
16
- // SANDBOX_TOOL_HANDLERS. handleConnect owns the git repo transfer chain
17
- // invocation (git-transfer.ts).
33
+ // Account/session-gate handlers (check_user, sign_agreement, connect,
34
+ // shutdown) for the sandbox pack, extracted verbatim from tools.ts in the
35
+ // within-pack split for the jscpd complex-file bar; the tools.ts face imports
36
+ // them for SANDBOX_TOOL_HANDLERS. handleConnect owns the git repo transfer
37
+ // chain invocation (git-transfer.ts); handleShutdown owns the DevStation
38
+ // close face (dev 5d89c880 + 3bfc1f53 tip state).
18
39
 
19
40
  export async function handleCheckUser(_args: ToolArgs = {}, _opts: CallToolOptions = {}) {
20
- return await hdkitCheckUser();
41
+ try {
42
+ return await hdkitCheckUser();
43
+ } catch (error) {
44
+ // 409 版本门禁按出口折叠(dev e1255a4b):MCP 错误信封只携带 code+message,
45
+ // clientVersion/minVersion/remediation 必须展开为结构化返回才能穿透
46
+ const gate = versionGateResult(error);
47
+ if (gate) return gate;
48
+ throw error;
49
+ }
21
50
  }
22
51
 
23
52
  export async function handleSignAgreement(_args: ToolArgs = {}, _opts: CallToolOptions = {}) {
24
- return await hdkitSignAgreement();
53
+ try {
54
+ return await hdkitSignAgreement();
55
+ } catch (error) {
56
+ const gate = versionGateResult(error);
57
+ if (gate) return gate;
58
+ throw error;
59
+ }
25
60
  }
26
61
 
27
62
  export async function handleConnect(args: ToolArgs = {}, _opts: CallToolOptions = {}) {
@@ -37,24 +72,79 @@ export async function handleConnect(args: ToolArgs = {}, _opts: CallToolOptions
37
72
  }
38
73
  let connectResult: Record<string, unknown>;
39
74
  try {
40
- connectResult = await hdkitConnect(connectArgs);
75
+ connectResult = await hdkitConnectWithRetry(connectArgs);
41
76
  } catch (error) {
42
- // 业务预期失败(429 双码 / 烧核 / 凭证失效)转结构化返回,remediation 才能穿透 MCP 边界;
43
- // 其余错误维持抛出(MCP 层透传 code+message)
77
+ // 业务预期失败(429 三码 / 烧核 / 凭证失效)转结构化返回,remediation 才能穿透 MCP 边界;
78
+ // 其余错误维持抛出(MCP 层透传 code+message)。
79
+ // 409 版本门禁(dev e1255a4b)与网关 502/504 重试耗尽(v2 扩展)同样在此折叠。
44
80
  const err = error as HdkitError;
81
+ const gate = versionGateResult(err);
82
+ if (gate) return gate;
83
+ const exhausted = transientExhaustionResult(err);
84
+ if (exhausted) return exhausted;
85
+ // 业务折叠的字段读全过安全卫队与窄化(round 15 建、round 16 深验、
86
+ // round 17 嵌套上下文+快照往返、round 18 快照形态窄化):抛出型 getter/
87
+ // 撤销代理按缺失——缺失的码不进业务分支,原错误原样抛出;remediation 经
88
+ // serializableRemediation 深验——非对象、嵌套 BigInt、循环引用、判别器、
89
+ // 有状态换值、非对象 JSON 视图一并不骑信封
90
+ // 判等口径 vs 渲染口径(round 26/MUST 3):canonCode 只作判等——织入/垫
91
+ // 码的业务码仍按 round-12 教义识别(传输噪声下的真服务码);渲染对齐
92
+ // voucher 谓词——服务端亲署码不含空白渲染字符,原始拼写带空白渲染字
93
+ // 符即非亲署,渲染其清洗形会把伪造码洗成亲署拼写的字节等价物(
94
+ // HDKIT_QUOTA\u200b_EXCEEDED 洗成签名 HDKIT_QUOTA_EXCEEDED——真实 wire
95
+ // 路径可经网关/代理注入织入拼写)——一律省略(码字段与前缀同判);
96
+ // 空白码同样省略(never-blank-code 教义——此前渲染 code:'')
97
+ const rawBusinessCode = safeReadField(error, 'code');
98
+ const businessCode = canonCode(rawBusinessCode);
99
+ // 伪造码不渲染(round 30/MUST 3,round 8 教义在业务折叠落地):
100
+ // 无码烧核 502/504 经请求层制造了 HTTP_502/504——分发追踪靠标记
101
+ // (r29),信封的码字段与前缀不得渲染客户端制造拼写
102
+ const renderCode =
103
+ typeof rawBusinessCode === 'string' &&
104
+ businessCode !== '' &&
105
+ businessCode === rawBusinessCode &&
106
+ !MANUFACTURED_FAMILY.test(businessCode)
107
+ ? rawBusinessCode
108
+ : undefined;
109
+ // 伪造码的消息前缀一并剥除(round 30/MUST 3,与耗尽装饰同法:
110
+ // 请求层把 "HTTP_x: " 合进了消息——客户端制造拼写不得以任何表面(码字段或
111
+ // 可见消息)渲染上信封;循环剥除(页面消息可翻倍),剥后为空则走设计兜底
112
+ let businessMessage = cleanMessage(safeMessageText(error)) || '';
113
+ if (businessCode !== '' && MANUFACTURED_FAMILY.test(businessCode)) {
114
+ const stripPattern = manufacturedPrefixPattern(businessCode);
115
+ while (stripPattern) {
116
+ const hit = stripPattern.exec(businessMessage);
117
+ if (!hit) break;
118
+ businessMessage = businessMessage.slice(hit[0].length);
119
+ }
120
+ businessMessage = cleanMessage(businessMessage);
121
+ }
122
+ // 转向字段改自有数据描述符读(round 26/MUST 3):[[Get]] 读让立着访问
123
+ // 器注入任意文案(pay-here URL);与门禁/耗尽折叠的 ownDataValue 同标
124
+ // 准(round 25 漏掉了本折叠)
125
+ const coreHoursExhausted = chainDataValue(error, 'coreHoursExhausted');
45
126
  if (
46
- err.code === 'HDKIT_QUOTA_EXCEEDED' ||
47
- err.code === 'HDKIT_CAPACITY_INSUFFICIENT' ||
48
- err.code === 'HDKIT_CRED_INVALID' ||
49
- err.coreHoursExhausted
127
+ businessCode === 'HDKIT_QUOTA_EXCEEDED' ||
128
+ businessCode === 'HDKIT_TEMPLATE_QUOTA_EXCEEDED' ||
129
+ businessCode === 'HDKIT_CAPACITY_INSUFFICIENT' ||
130
+ businessCode === 'HDKIT_CRED_INVALID' ||
131
+ coreHoursExhausted
50
132
  ) {
133
+ // retryAfter 窄到字符串、remediation 深验(round 16):BigInt 等敌意值
134
+ // 不骑信封(MCP 序列化边界,与门禁/耗尽折叠同口径)
135
+ const rawRetryAfter = ownDataValue(error, 'retryAfter');
136
+ const retryAfter = typeof rawRetryAfter === 'string' ? rawRetryAfter : undefined;
137
+ const remediation = serializableRemediation(ownDataValue(error, 'remediation'));
138
+ // 空白/缺失消息走构建口同款代码前缀兜底(round 20):其余折叠口从不
139
+ // 渲染空 message,此处对齐——纯不可见消息按缺失
140
+ const fallbackMessage = renderCode ? `${renderCode}: hdkitservice error` : 'hdkitservice error';
51
141
  return {
52
142
  ok: false,
53
- code: err.code,
54
- message: err.message,
55
- ...(err.retryAfter !== undefined ? { retryAfter: err.retryAfter } : {}),
56
- ...(err.coreHoursExhausted ? { coreHoursExhausted: true } : {}),
57
- ...(err.remediation ? { remediation: err.remediation } : {}),
143
+ ...(renderCode ? { code: renderCode } : {}),
144
+ message: businessMessage || fallbackMessage,
145
+ ...(retryAfter ? { retryAfter } : {}),
146
+ ...(coreHoursExhausted ? { coreHoursExhausted: true } : {}),
147
+ ...(remediation ? { remediation } : {}),
58
148
  };
59
149
  }
60
150
  throw error;
@@ -69,10 +159,13 @@ export async function handleConnect(args: ToolArgs = {}, _opts: CallToolOptions
69
159
  // 池归属 + 生命周期口径缓存(服务端回显优先,缺失时客户端默认兜底)。
70
160
  // 双读兜底与 devStageId 同型(防服务端 wire 命名漂移,QA #1082 配对复审教训)
71
161
  rememberWorkspacePool(devStageId, connectResult?.pool_type || connectResult?.poolType, connectResult || {});
162
+ // 连接后的选择性隧道清理(dev 97c4bc8a):只清孤儿记录/宿主;保留其他
163
+ // 端口、其他会话与 keepalive 名单内的隧道。best-effort —— 清理失败不得
164
+ // 阻断 connect 本身。
72
165
  try {
73
- await execOneShot(devStageId, 'devbridge delete-all 2>/dev/null || true', 'root', 15000);
166
+ await cleanupDevbridgeTunnels(devStageId, { mode: 'stale' });
74
167
  } catch {
75
- // best-effort: a fresh sandbox may have no tunnels (or no devbridge) to delete
168
+ // best-effort: a fresh sandbox may have no tunnels (or no devbridge) to clean
76
169
  }
77
170
  try {
78
171
  // #999: /workspace/.local/bin first — the data-disk install survives
@@ -91,3 +184,55 @@ export async function handleConnect(args: ToolArgs = {}, _opts: CallToolOptions
91
184
  // 生命周期提示:仅首次连接 / 关机唤醒时播报(服务端回显 pool_type 才生成)
92
185
  return enrichConnectResult(connectResult, { announce: announceConnect });
93
186
  }
187
+
188
+ // 关机错误的结构化折叠(dev 5d89c880 的 toVersionGateResult 面,去掉 v2 未
189
+ // 移植的 autoUpgrade 字段):MCP 错误信封只携带 code+message,指引与版本字段
190
+ // 必须展开为结构化返回才能穿透边界——404 HDKIT_SANDBOX_NOT_FOUND、烧核、
191
+ // 版本门禁与传输层失败一律 ok:false 返回,不再裸抛。
192
+ function shutdownErrorResult(error: unknown): Record<string, unknown> {
193
+ const err = error as HdkitError;
194
+ return {
195
+ ok: false,
196
+ code: err.code,
197
+ message: err instanceof Error ? err.message : String(error),
198
+ ...(err.retryAfter !== undefined ? { retryAfter: err.retryAfter } : {}),
199
+ ...(err.coreHoursExhausted ? { coreHoursExhausted: true } : {}),
200
+ ...(err.clientVersion ? { clientVersion: err.clientVersion } : {}),
201
+ ...(err.minVersion ? { minVersion: err.minVersion } : {}),
202
+ ...(err.remediation ? { remediation: err.remediation } : {}),
203
+ };
204
+ }
205
+
206
+ export async function handleShutdown(args: ToolArgs = {}, _opts: CallToolOptions = {}) {
207
+ const sessionId = args.session_id;
208
+ // 3bfc1f53:workspaceId 与 devStageId 分开解析。仅 session_id 时 devStageId
209
+ // 留空(不把 session_id 字符串当 workspace 用),终端会话以服务端回传的
210
+ // devStageId 为准关闭。
211
+ const workspaceId = args.dev_stage_id || args.workspace_id || getCurrentWorkspaceId();
212
+ const devStageId = args.dev_stage_id || args.workspace_id || (sessionId ? undefined : workspaceId);
213
+ const id = sessionId || devStageId;
214
+ if (!id) {
215
+ return {
216
+ ok: false,
217
+ code: 'HDKIT_INVALID_REQUEST',
218
+ message:
219
+ 'session_id or dev_stage_id is required. No sandbox connected — call huaweicloud_sandbox_connect first, or pass workspace_id.',
220
+ };
221
+ }
222
+ try {
223
+ const shutdown = await hdkitShutdown(sessionId, devStageId);
224
+ try {
225
+ // 3bfc1f53 终态:仅 session_id 时以服务端回传的 devStageId 关终端会话。
226
+ // 与 dev 同形的 || 穿透(dev 3bfc1f53):空串回显不截停链——asString 只
227
+ // 收窄类型,真值判定仍按 ||(id 检查已保证链上有真值,'' 尾仅为类型
228
+ // 完备)。
229
+ const wsForClose = asString(shutdown.devStageId) || asString(workspaceId) || asString(sessionId) || '';
230
+ await closeSession(wsForClose, args.username || 'root');
231
+ } catch {
232
+ // best-effort: 关机已受理,终端会话随沙箱停止一并消亡
233
+ }
234
+ return { ok: true, ...shutdown };
235
+ } catch (error) {
236
+ return shutdownErrorResult(error);
237
+ }
238
+ }
@@ -2,6 +2,7 @@ import { randomBytes } from 'node:crypto';
2
2
 
3
3
  import { execOneShot, execWithSession, getCurrentWorkspaceId } from '../../sandbox/session-manager.ts';
4
4
  import { hdkitCredentials } from '../../lib/hdkit/hdkitservice-api.ts';
5
+ import { versionGateResult } from '../../lib/hdkit/hdkit-gate.ts';
5
6
  import { getCredentials } from '../../lib/hdkit/hwlink-api.ts';
6
7
  import { validateIamCredentials } from '../../auth/credential-validator.ts';
7
8
  import { resolveCredentialsWithRuntime } from '../../auth/credentials.ts';
@@ -62,7 +63,16 @@ export async function handleCredentials(args: ToolArgs = {}, _opts: CallToolOpti
62
63
  hint: 'Credentials were NOT injected into the sandbox. Fix AK/SK first: run "npx huaweicloud-devkit auth init" or correct HW_ACCESS_KEY/HW_SECRET_KEY, then retry.',
63
64
  };
64
65
  }
65
- const credResult = await hdkitCredentials(args.session_id, devStageId, args.enable_sts !== false);
66
+ // 409 版本门禁同样拦截 credentials 出口:结构化折叠(dev e1255a4b),
67
+ // clientVersion/minVersion/remediation 才能穿透 MCP 边界
68
+ let credResult: Record<string, unknown>;
69
+ try {
70
+ credResult = await hdkitCredentials(args.session_id, devStageId, args.enable_sts !== false);
71
+ } catch (error) {
72
+ const gate = versionGateResult(error);
73
+ if (gate) return gate;
74
+ throw error;
75
+ }
66
76
  const sandboxWsIdCred = args.dev_stage_id || getCurrentWorkspaceId();
67
77
  // The DevBridge API Key is a LONG-LIVED account-level credential (no expiry, manual
68
78
  // revocation only) — unlike the temporary STS AK/SK. It is stored in its own file