huaweicloud-devkit 2.0.0-next.2 → 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 +157 -31
  13. package/plugins/huaweicloud-core/dist/agents/opencode.js +129 -1
  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 +77 -56
  23. package/plugins/huaweicloud-core/dist/lib/approval-mode.js +32 -0
  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 +262 -0
  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 +75 -4
  38. package/plugins/huaweicloud-core/dist/mcp-server.js +6560 -898
  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 +119 -112
  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 +42 -4
  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 +5 -5
  89. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +13 -8
  90. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +78 -23
  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 +198 -30
  96. package/plugins/huaweicloud-core/src/agents/opencode.ts +157 -1
  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 +93 -63
  106. package/plugins/huaweicloud-core/src/lib/approval-mode.ts +34 -0
  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 +350 -0
  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 +88 -5
  121. package/plugins/huaweicloud-core/src/mcp-server.ts +13 -0
  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 +139 -120
  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 +45 -3
  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,245 @@
1
+ import { asText } from "../../lib/as-text.js";
2
+ import { hashArgs } from "../../lib/approval-tokens.js";
3
+ import { classifyTextCommand, redactSecrets } from "../../safety-policy.js";
4
+ import { evaluateCommandRisk, loadRiskRules } from "../../risk-rule-engine.js";
5
+ import { redactWithSupplementalKeys } from "../../lib/supplemental-redaction.js";
6
+ import { isSecretRef } from "../../lib/secret-vault/refs.js";
7
+ // The sandbox pack's approval spec table. Nine tools join the gate: the two
8
+ // exec faces are CLASSIFIED (content decides — a benign command runs with no
9
+ // confirmation surface at all, a write-classified one confirms on every
10
+ // call), the seven mutating lifecycle faces are ALWAYS (a human present per
11
+ // call, no content rule ever exempts them). The strict classification runs
12
+ // on the exec faces' `command` argument through the SAME engines the Bash
13
+ // face uses — classifyTextCommand plus the cloud-risk-rules catalog — so a
14
+ // destructive command is a disabled guard at the gate face (never a minted
15
+ // token the run then denies, ApprovalCoreMint's NoDoomedToken) and the deny
16
+ // survives every confirmation channel.
17
+ //
18
+ // The binding value is the call's own arguments with the approval carriers
19
+ // (approvalToken, approvedByUser, vendorConfirmed) stripped: the hash the
20
+ // token binds and the ledger records is the CONTENT the user confirms, so a
21
+ // retry that only drifts on a carrier rides the same consent key.
22
+ // Approval-chain carrier fields: never part of the content the user
23
+ // confirms. `command` stays IN the binding — on the exec faces it is the
24
+ // content itself, not a display anchor (the commandAnchor machinery is the
25
+ // hcloud pair's; these tools declare none).
26
+ const APPROVAL_CARRIER_KEYS = new Set(['approvalToken', 'approvedByUser', 'vendorConfirmed']);
27
+ export function bindingArgs(args) {
28
+ const out = {};
29
+ for (const [key, value] of Object.entries(args ?? {})) {
30
+ if (APPROVAL_CARRIER_KEYS.has(key))
31
+ continue;
32
+ out[key] = value;
33
+ }
34
+ return out;
35
+ }
36
+ // The pin view: the binding value through the product's redaction pipeline
37
+ // plus the supplemental key vocabulary the trace face shares (api_key and
38
+ // the value channel — sandbox_credentials' long-lived DevBridge key rides
39
+ // api_key; no sandbox tool uses `value`, so the entry is collision-free).
40
+ function pinViewOf(bindingValue) {
41
+ return redactWithSupplementalKeys(redactSecrets(bindingValue));
42
+ }
43
+ const rulingMemo = new WeakMap();
44
+ function computeRuling(command) {
45
+ // The catalog is file-backed; read it once per process (classify stays a
46
+ // pure function of its input — same command, same ruling).
47
+ const catalog = loadRiskRules();
48
+ const rulesDeny = evaluateCommandRisk(command, { catalog }).findings.find((finding) => finding.severity === 'deny');
49
+ if (rulesDeny) {
50
+ return {
51
+ verdict: 'none',
52
+ denyReason: `rule ${rulesDeny.ruleId}: ${rulesDeny.message} Remediation: ${rulesDeny.remediation}`,
53
+ };
54
+ }
55
+ const text = classifyTextCommand(command);
56
+ if (text.decision === 'deny' && (text.risk === 'write' || text.risk === 'execution')) {
57
+ return { verdict: 'required' };
58
+ }
59
+ if (text.decision === 'deny') {
60
+ return { verdict: 'none', denyReason: text.reason ?? 'the command is blocked by strict classification.' };
61
+ }
62
+ return { verdict: 'none' };
63
+ }
64
+ function rulingForBinding(bindingValue) {
65
+ if (bindingValue && typeof bindingValue === 'object' && !Array.isArray(bindingValue)) {
66
+ const cached = rulingMemo.get(bindingValue);
67
+ if (cached)
68
+ return cached;
69
+ const ruling = computeRuling(asText(bindingValue.command ?? ''));
70
+ rulingMemo.set(bindingValue, ruling);
71
+ return ruling;
72
+ }
73
+ return computeRuling(asText(bindingValue));
74
+ }
75
+ // The execution floor: a strict deny refuses in BOTH modes, before any mint,
76
+ // consent record, or token consume — destructive content is never
77
+ // unlockable, so the refusal names the rule and nothing burns.
78
+ function assertCommandAllowed(bindingValue) {
79
+ const ruling = rulingForBinding(bindingValue);
80
+ if (ruling.denyReason === undefined)
81
+ return;
82
+ throw new Error('Sandbox command denied by strict classification (no confirmation unlocks it). ' + `${ruling.denyReason}`);
83
+ }
84
+ // One summarized view per tool family. Every string the view carries is
85
+ // built from the REDACTED pin view — the summarize contract forbids the raw
86
+ // argument stream in any popup surface.
87
+ function asRecordView(bindingValue) {
88
+ return bindingValue && typeof bindingValue === 'object' && !Array.isArray(bindingValue)
89
+ ? bindingValue
90
+ : {};
91
+ }
92
+ function viewOf(bindingValue, summary) {
93
+ const record = asRecordView(bindingValue);
94
+ return {
95
+ summary: summary(record),
96
+ argsHash: hashArgs(bindingValue),
97
+ pinView: pinViewOf(bindingValue),
98
+ };
99
+ }
100
+ // A short redacted field echo for the summary line: "port 8080" style, never
101
+ // the whole JSON blob.
102
+ function fieldEcho(view, keys) {
103
+ const parts = [];
104
+ for (const key of keys) {
105
+ const value = view[key];
106
+ if (value === undefined || value === null || value === '')
107
+ continue;
108
+ const text = asText(pinViewOf(value));
109
+ parts.push(`${key} ${text}`);
110
+ }
111
+ return parts.join(', ');
112
+ }
113
+ function execView(toolShortName, bindingValue) {
114
+ const record = asRecordView(bindingValue);
115
+ const command = typeof record.command === 'string' ? asText(pinViewOf(record.command)) : '';
116
+ const where = fieldEcho(record, ['workspace_id', 'username']);
117
+ const summary = `huaweicloud_sandbox_${toolShortName}${where !== '' ? ` (${where})` : ''}: ` +
118
+ (command !== '' ? command : '(no command)');
119
+ return {
120
+ summary,
121
+ argsHash: hashArgs(bindingValue),
122
+ pinView: pinViewOf(bindingValue),
123
+ ...(command !== '' ? { command } : {}),
124
+ };
125
+ }
126
+ // One shared spec line for every sandbox registration: the binding value is
127
+ // the call's own arguments with the approval carriers stripped (see
128
+ // bindingArgs). Without this the carriers ride into the hash — a retry
129
+ // carrying the token would bind differently from the mint, and every
130
+ // confirmation would be single-use-by-construction.
131
+ function sandboxBinding() {
132
+ return { domain: 'sandbox', tokenSource: 'gate', normalizeArgs: (args) => bindingArgs(args) };
133
+ }
134
+ function execSpec(toolShortName) {
135
+ return {
136
+ ...sandboxBinding(),
137
+ flavor: 'classified',
138
+ classify: (bindingValue) => rulingForBinding(bindingValue).verdict,
139
+ assertArgsExecutable: (bindingValue) => assertCommandAllowed(bindingValue),
140
+ // The command IS the content, and the confirmation surfaces display it,
141
+ // so it anchors itself: provided must equal the binding's own command
142
+ // (it always does when the call is honest — the binding derives from
143
+ // the args). The anchor exists so the no-anchor refusal shape (a
144
+ // stuffed command on a tool that declares no displayable line) never
145
+ // kills the exec faces after the serial landing (the anchor-collision
146
+ // decision): the exec calls are anchored, the seven lifecycle faces are
147
+ // not and refuse a stuffed command.
148
+ commandAnchor: (bindingValue) => {
149
+ const command = bindingValue.command;
150
+ return typeof command === 'string' && command !== '' ? [command] : [];
151
+ },
152
+ summarize: (bindingValue) => execView(toolShortName, bindingValue),
153
+ };
154
+ }
155
+ const connectSpec = {
156
+ ...sandboxBinding(),
157
+ flavor: 'always',
158
+ summarize: (bindingValue) => viewOf(bindingValue, (view) => {
159
+ const target = fieldEcho(view, ['pool_type']);
160
+ return `huaweicloud_sandbox_connect: connect a sandbox${target !== '' ? ` (${target})` : ''}`;
161
+ }),
162
+ };
163
+ const exposeTunnelSpec = {
164
+ ...sandboxBinding(),
165
+ flavor: 'always',
166
+ summarize: (bindingValue) => viewOf(bindingValue, (view) => {
167
+ const target = fieldEcho(view, ['port', 'expiry_hours']);
168
+ return `huaweicloud_sandbox_expose_tunnel: expose a public tunnel URL${target !== '' ? ` (${target})` : ''}`;
169
+ }),
170
+ };
171
+ const renewTunnelSpec = {
172
+ ...sandboxBinding(),
173
+ flavor: 'always',
174
+ summarize: (bindingValue) => viewOf(bindingValue, (view) => {
175
+ const target = fieldEcho(view, ['tunnel_id', 'expiry_hours']);
176
+ return `huaweicloud_sandbox_renew_tunnel: renew a tunnel's lifetime${target !== '' ? ` (${target})` : ''}`;
177
+ }),
178
+ };
179
+ const keepaliveWatchdogSpec = {
180
+ ...sandboxBinding(),
181
+ flavor: 'always',
182
+ summarize: (bindingValue) => viewOf(bindingValue, (view) => {
183
+ const count = Array.isArray(view.tunnels) ? view.tunnels.length : 0;
184
+ const ids = Array.isArray(view.tunnels)
185
+ ? view.tunnels
186
+ .map((tunnel) => tunnel && typeof tunnel === 'object' ? asText(tunnel.tunnel_id ?? '') : '')
187
+ .filter((id) => id !== '')
188
+ : [];
189
+ return `huaweicloud_sandbox_keepalive_watchdog: install/replace the keepalive watchdog over ${count} tunnel(s)${ids.length > 0 ? ` (${ids.join(', ')})` : ''}`;
190
+ }),
191
+ };
192
+ const signAgreementSpec = {
193
+ ...sandboxBinding(),
194
+ flavor: 'always',
195
+ summarize: (bindingValue) => viewOf(bindingValue, () => 'huaweicloud_sandbox_sign_agreement: sign all unsigned or outdated Huawei Cloud developer service agreements for the current user'),
196
+ };
197
+ const credentialsSpec = {
198
+ ...sandboxBinding(),
199
+ flavor: 'always',
200
+ summarize: (bindingValue) => {
201
+ // Name the api_key channel the HANDLER will actually use, never the
202
+ // value (interrogate F1 round 3, F2): handlers-credentials resolves
203
+ // env-first (process.env.HW_API_KEY || args.api_key), so the view
204
+ // mirrors that precedence — an env tier set makes the parameter or ref
205
+ // beside it a dead letter the confirmation must not claim. A vault ref
206
+ // is itself conversation-safe (that is the ref doctrine), and the
207
+ // parameter channel is named with the value redacted by the pin-view
208
+ // pass.
209
+ const rawApiKey = asText(asRecordView(bindingValue).api_key ?? '');
210
+ const channel = process.env.HW_API_KEY
211
+ ? 'api_key via environment (value redacted)'
212
+ : rawApiKey !== ''
213
+ ? isSecretRef(rawApiKey)
214
+ ? `api_key via vault ref ${rawApiKey}`
215
+ : 'api_key via parameter (value redacted)'
216
+ : '';
217
+ return viewOf(bindingValue, (view) => {
218
+ const target = fieldEcho(view, ['session_id', 'dev_stage_id', 'enable_sts']);
219
+ const scope = target !== '' ? ` (${target})` : '';
220
+ return (`huaweicloud_sandbox_credentials: validate and inject temporary credentials into the sandbox${scope}` +
221
+ (channel !== '' ? `; ${channel}` : ''));
222
+ });
223
+ },
224
+ };
225
+ // 关机(port-pr6):不可逆生命周期面,always。确认视图点名目标 id 与
226
+ // close-not-delete 事实——确认面显示的是开发者要关哪台沙箱,不是参数流。
227
+ const shutdownSpec = {
228
+ ...sandboxBinding(),
229
+ flavor: 'always',
230
+ summarize: (bindingValue) => viewOf(bindingValue, (view) => {
231
+ const target = fieldEcho(view, ['session_id', 'dev_stage_id', 'workspace_id']);
232
+ return `huaweicloud_sandbox_shutdown: shut down the sandbox (close only — instance retained, reconnect wakes it)${target !== '' ? ` (${target})` : ''}`;
233
+ }),
234
+ };
235
+ export const SANDBOX_APPROVAL_SPECS = {
236
+ huaweicloud_sandbox_connect: connectSpec,
237
+ huaweicloud_sandbox_exec_with_session: execSpec('exec_with_session'),
238
+ huaweicloud_sandbox_exec_one_shot: execSpec('exec_one_shot'),
239
+ huaweicloud_sandbox_expose_tunnel: exposeTunnelSpec,
240
+ huaweicloud_sandbox_renew_tunnel: renewTunnelSpec,
241
+ huaweicloud_sandbox_keepalive_watchdog: keepaliveWatchdogSpec,
242
+ huaweicloud_sandbox_sign_agreement: signAgreementSpec,
243
+ huaweicloud_sandbox_credentials: credentialsSpec,
244
+ huaweicloud_sandbox_shutdown: shutdownSpec,
245
+ };
@@ -1,17 +1,39 @@
1
- import { execOneShot, execWithSession, setWorkspaceId } from "../../sandbox/session-manager.js";
2
- import { hdkitCheckUser, hdkitSignAgreement, hdkitConnect } from "../../lib/hdkit/hdkitservice-api.js";
1
+ import { execWithSession, closeSession, getCurrentWorkspaceId, setWorkspaceId } from "../../sandbox/session-manager.js";
2
+ import { cleanupDevbridgeTunnels } from "../../sandbox/devbridge-tunnel.js";
3
+ import { hdkitCheckUser, hdkitSignAgreement, hdkitConnectWithRetry, hdkitShutdown, } from "../../lib/hdkit/hdkitservice-api.js";
4
+ import { MANUFACTURED_FAMILY, manufacturedPrefixPattern, canonCode, chainDataValue, cleanMessage, ownDataValue, safeMessageText, safeReadField, serializableRemediation, transientExhaustionResult, versionGateResult, } from "../../lib/hdkit/hdkit-gate.js";
5
+ import { asString } from "../../lib/as-text.js";
3
6
  import { validatePoolType, rememberWorkspacePool, shouldAnnounceConnect, enrichConnectResult, } from "../../lib/hdkit/sandbox-pool.js";
4
7
  import { transferGitRepo } from "./git-transfer.js";
5
- // Account/session-gate handlers (check_user, sign_agreement, connect) for
6
- // the sandbox pack, extracted verbatim from tools.ts in the within-pack
7
- // split for the jscpd complex-file bar; the tools.ts face imports them for
8
- // SANDBOX_TOOL_HANDLERS. handleConnect owns the git repo transfer chain
9
- // invocation (git-transfer.ts).
8
+ // Account/session-gate handlers (check_user, sign_agreement, connect,
9
+ // shutdown) for the sandbox pack, extracted verbatim from tools.ts in the
10
+ // within-pack split for the jscpd complex-file bar; the tools.ts face imports
11
+ // them for SANDBOX_TOOL_HANDLERS. handleConnect owns the git repo transfer
12
+ // chain invocation (git-transfer.ts); handleShutdown owns the DevStation
13
+ // close face (dev 5d89c880 + 3bfc1f53 tip state).
10
14
  export async function handleCheckUser(_args = {}, _opts = {}) {
11
- return await hdkitCheckUser();
15
+ try {
16
+ return await hdkitCheckUser();
17
+ }
18
+ catch (error) {
19
+ // 409 版本门禁按出口折叠(dev e1255a4b):MCP 错误信封只携带 code+message,
20
+ // clientVersion/minVersion/remediation 必须展开为结构化返回才能穿透
21
+ const gate = versionGateResult(error);
22
+ if (gate)
23
+ return gate;
24
+ throw error;
25
+ }
12
26
  }
13
27
  export async function handleSignAgreement(_args = {}, _opts = {}) {
14
- return await hdkitSignAgreement();
28
+ try {
29
+ return await hdkitSignAgreement();
30
+ }
31
+ catch (error) {
32
+ const gate = versionGateResult(error);
33
+ if (gate)
34
+ return gate;
35
+ throw error;
36
+ }
15
37
  }
16
38
  export async function handleConnect(args = {}, _opts = {}) {
17
39
  // 两池:客户端校验 pool_type(非法值在本地即报错,不发无效请求);未传交由服务端默认 ephemeral
@@ -28,23 +50,80 @@ export async function handleConnect(args = {}, _opts = {}) {
28
50
  }
29
51
  let connectResult;
30
52
  try {
31
- connectResult = await hdkitConnect(connectArgs);
53
+ connectResult = await hdkitConnectWithRetry(connectArgs);
32
54
  }
33
55
  catch (error) {
34
- // 业务预期失败(429 双码 / 烧核 / 凭证失效)转结构化返回,remediation 才能穿透 MCP 边界;
35
- // 其余错误维持抛出(MCP 层透传 code+message)
56
+ // 业务预期失败(429 三码 / 烧核 / 凭证失效)转结构化返回,remediation 才能穿透 MCP 边界;
57
+ // 其余错误维持抛出(MCP 层透传 code+message)。
58
+ // 409 版本门禁(dev e1255a4b)与网关 502/504 重试耗尽(v2 扩展)同样在此折叠。
36
59
  const err = error;
37
- if (err.code === 'HDKIT_QUOTA_EXCEEDED' ||
38
- err.code === 'HDKIT_CAPACITY_INSUFFICIENT' ||
39
- err.code === 'HDKIT_CRED_INVALID' ||
40
- err.coreHoursExhausted) {
60
+ const gate = versionGateResult(err);
61
+ if (gate)
62
+ return gate;
63
+ const exhausted = transientExhaustionResult(err);
64
+ if (exhausted)
65
+ return exhausted;
66
+ // 业务折叠的字段读全过安全卫队与窄化(round 15 建、round 16 深验、
67
+ // round 17 嵌套上下文+快照往返、round 18 快照形态窄化):抛出型 getter/
68
+ // 撤销代理按缺失——缺失的码不进业务分支,原错误原样抛出;remediation 经
69
+ // serializableRemediation 深验——非对象、嵌套 BigInt、循环引用、判别器、
70
+ // 有状态换值、非对象 JSON 视图一并不骑信封
71
+ // 判等口径 vs 渲染口径(round 26/MUST 3):canonCode 只作判等——织入/垫
72
+ // 码的业务码仍按 round-12 教义识别(传输噪声下的真服务码);渲染对齐
73
+ // voucher 谓词——服务端亲署码不含空白渲染字符,原始拼写带空白渲染字
74
+ // 符即非亲署,渲染其清洗形会把伪造码洗成亲署拼写的字节等价物(
75
+ // HDKIT_QUOTA\u200b_EXCEEDED 洗成签名 HDKIT_QUOTA_EXCEEDED——真实 wire
76
+ // 路径可经网关/代理注入织入拼写)——一律省略(码字段与前缀同判);
77
+ // 空白码同样省略(never-blank-code 教义——此前渲染 code:'')
78
+ const rawBusinessCode = safeReadField(error, 'code');
79
+ const businessCode = canonCode(rawBusinessCode);
80
+ // 伪造码不渲染(round 30/MUST 3,round 8 教义在业务折叠落地):
81
+ // 无码烧核 502/504 经请求层制造了 HTTP_502/504——分发追踪靠标记
82
+ // (r29),信封的码字段与前缀不得渲染客户端制造拼写
83
+ const renderCode = typeof rawBusinessCode === 'string' &&
84
+ businessCode !== '' &&
85
+ businessCode === rawBusinessCode &&
86
+ !MANUFACTURED_FAMILY.test(businessCode)
87
+ ? rawBusinessCode
88
+ : undefined;
89
+ // 伪造码的消息前缀一并剥除(round 30/MUST 3,与耗尽装饰同法:
90
+ // 请求层把 "HTTP_x: " 合进了消息——客户端制造拼写不得以任何表面(码字段或
91
+ // 可见消息)渲染上信封;循环剥除(页面消息可翻倍),剥后为空则走设计兜底
92
+ let businessMessage = cleanMessage(safeMessageText(error)) || '';
93
+ if (businessCode !== '' && MANUFACTURED_FAMILY.test(businessCode)) {
94
+ const stripPattern = manufacturedPrefixPattern(businessCode);
95
+ while (stripPattern) {
96
+ const hit = stripPattern.exec(businessMessage);
97
+ if (!hit)
98
+ break;
99
+ businessMessage = businessMessage.slice(hit[0].length);
100
+ }
101
+ businessMessage = cleanMessage(businessMessage);
102
+ }
103
+ // 转向字段改自有数据描述符读(round 26/MUST 3):[[Get]] 读让立着访问
104
+ // 器注入任意文案(pay-here URL);与门禁/耗尽折叠的 ownDataValue 同标
105
+ // 准(round 25 漏掉了本折叠)
106
+ const coreHoursExhausted = chainDataValue(error, 'coreHoursExhausted');
107
+ if (businessCode === 'HDKIT_QUOTA_EXCEEDED' ||
108
+ businessCode === 'HDKIT_TEMPLATE_QUOTA_EXCEEDED' ||
109
+ businessCode === 'HDKIT_CAPACITY_INSUFFICIENT' ||
110
+ businessCode === 'HDKIT_CRED_INVALID' ||
111
+ coreHoursExhausted) {
112
+ // retryAfter 窄到字符串、remediation 深验(round 16):BigInt 等敌意值
113
+ // 不骑信封(MCP 序列化边界,与门禁/耗尽折叠同口径)
114
+ const rawRetryAfter = ownDataValue(error, 'retryAfter');
115
+ const retryAfter = typeof rawRetryAfter === 'string' ? rawRetryAfter : undefined;
116
+ const remediation = serializableRemediation(ownDataValue(error, 'remediation'));
117
+ // 空白/缺失消息走构建口同款代码前缀兜底(round 20):其余折叠口从不
118
+ // 渲染空 message,此处对齐——纯不可见消息按缺失
119
+ const fallbackMessage = renderCode ? `${renderCode}: hdkitservice error` : 'hdkitservice error';
41
120
  return {
42
121
  ok: false,
43
- code: err.code,
44
- message: err.message,
45
- ...(err.retryAfter !== undefined ? { retryAfter: err.retryAfter } : {}),
46
- ...(err.coreHoursExhausted ? { coreHoursExhausted: true } : {}),
47
- ...(err.remediation ? { remediation: err.remediation } : {}),
122
+ ...(renderCode ? { code: renderCode } : {}),
123
+ message: businessMessage || fallbackMessage,
124
+ ...(retryAfter ? { retryAfter } : {}),
125
+ ...(coreHoursExhausted ? { coreHoursExhausted: true } : {}),
126
+ ...(remediation ? { remediation } : {}),
48
127
  };
49
128
  }
50
129
  throw error;
@@ -59,11 +138,14 @@ export async function handleConnect(args = {}, _opts = {}) {
59
138
  // 池归属 + 生命周期口径缓存(服务端回显优先,缺失时客户端默认兜底)。
60
139
  // 双读兜底与 devStageId 同型(防服务端 wire 命名漂移,QA #1082 配对复审教训)
61
140
  rememberWorkspacePool(devStageId, connectResult?.pool_type || connectResult?.poolType, connectResult || {});
141
+ // 连接后的选择性隧道清理(dev 97c4bc8a):只清孤儿记录/宿主;保留其他
142
+ // 端口、其他会话与 keepalive 名单内的隧道。best-effort —— 清理失败不得
143
+ // 阻断 connect 本身。
62
144
  try {
63
- await execOneShot(devStageId, 'devbridge delete-all 2>/dev/null || true', 'root', 15000);
145
+ await cleanupDevbridgeTunnels(devStageId, { mode: 'stale' });
64
146
  }
65
147
  catch {
66
- // best-effort: a fresh sandbox may have no tunnels (or no devbridge) to delete
148
+ // best-effort: a fresh sandbox may have no tunnels (or no devbridge) to clean
67
149
  }
68
150
  try {
69
151
  // #999: /workspace/.local/bin first — the data-disk install survives
@@ -78,3 +160,54 @@ export async function handleConnect(args = {}, _opts = {}) {
78
160
  // 生命周期提示:仅首次连接 / 关机唤醒时播报(服务端回显 pool_type 才生成)
79
161
  return enrichConnectResult(connectResult, { announce: announceConnect });
80
162
  }
163
+ // 关机错误的结构化折叠(dev 5d89c880 的 toVersionGateResult 面,去掉 v2 未
164
+ // 移植的 autoUpgrade 字段):MCP 错误信封只携带 code+message,指引与版本字段
165
+ // 必须展开为结构化返回才能穿透边界——404 HDKIT_SANDBOX_NOT_FOUND、烧核、
166
+ // 版本门禁与传输层失败一律 ok:false 返回,不再裸抛。
167
+ function shutdownErrorResult(error) {
168
+ const err = error;
169
+ return {
170
+ ok: false,
171
+ code: err.code,
172
+ message: err instanceof Error ? err.message : String(error),
173
+ ...(err.retryAfter !== undefined ? { retryAfter: err.retryAfter } : {}),
174
+ ...(err.coreHoursExhausted ? { coreHoursExhausted: true } : {}),
175
+ ...(err.clientVersion ? { clientVersion: err.clientVersion } : {}),
176
+ ...(err.minVersion ? { minVersion: err.minVersion } : {}),
177
+ ...(err.remediation ? { remediation: err.remediation } : {}),
178
+ };
179
+ }
180
+ export async function handleShutdown(args = {}, _opts = {}) {
181
+ const sessionId = args.session_id;
182
+ // 3bfc1f53:workspaceId 与 devStageId 分开解析。仅 session_id 时 devStageId
183
+ // 留空(不把 session_id 字符串当 workspace 用),终端会话以服务端回传的
184
+ // devStageId 为准关闭。
185
+ const workspaceId = args.dev_stage_id || args.workspace_id || getCurrentWorkspaceId();
186
+ const devStageId = args.dev_stage_id || args.workspace_id || (sessionId ? undefined : workspaceId);
187
+ const id = sessionId || devStageId;
188
+ if (!id) {
189
+ return {
190
+ ok: false,
191
+ code: 'HDKIT_INVALID_REQUEST',
192
+ message: 'session_id or dev_stage_id is required. No sandbox connected — call huaweicloud_sandbox_connect first, or pass workspace_id.',
193
+ };
194
+ }
195
+ try {
196
+ const shutdown = await hdkitShutdown(sessionId, devStageId);
197
+ try {
198
+ // 3bfc1f53 终态:仅 session_id 时以服务端回传的 devStageId 关终端会话。
199
+ // 与 dev 同形的 || 穿透(dev 3bfc1f53):空串回显不截停链——asString 只
200
+ // 收窄类型,真值判定仍按 ||(id 检查已保证链上有真值,'' 尾仅为类型
201
+ // 完备)。
202
+ const wsForClose = asString(shutdown.devStageId) || asString(workspaceId) || asString(sessionId) || '';
203
+ await closeSession(wsForClose, args.username || 'root');
204
+ }
205
+ catch {
206
+ // best-effort: 关机已受理,终端会话随沙箱停止一并消亡
207
+ }
208
+ return { ok: true, ...shutdown };
209
+ }
210
+ catch (error) {
211
+ return shutdownErrorResult(error);
212
+ }
213
+ }
@@ -1,6 +1,7 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { execOneShot, execWithSession, getCurrentWorkspaceId } from "../../sandbox/session-manager.js";
3
3
  import { hdkitCredentials } from "../../lib/hdkit/hdkitservice-api.js";
4
+ import { versionGateResult } from "../../lib/hdkit/hdkit-gate.js";
4
5
  import { getCredentials } from "../../lib/hdkit/hwlink-api.js";
5
6
  import { validateIamCredentials } from "../../auth/credential-validator.js";
6
7
  import { resolveCredentialsWithRuntime } from "../../auth/credentials.js";
@@ -58,7 +59,18 @@ export async function handleCredentials(args = {}, _opts = {}) {
58
59
  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.',
59
60
  };
60
61
  }
61
- const credResult = await hdkitCredentials(args.session_id, devStageId, args.enable_sts !== false);
62
+ // 409 版本门禁同样拦截 credentials 出口:结构化折叠(dev e1255a4b),
63
+ // clientVersion/minVersion/remediation 才能穿透 MCP 边界
64
+ let credResult;
65
+ try {
66
+ credResult = await hdkitCredentials(args.session_id, devStageId, args.enable_sts !== false);
67
+ }
68
+ catch (error) {
69
+ const gate = versionGateResult(error);
70
+ if (gate)
71
+ return gate;
72
+ throw error;
73
+ }
62
74
  const sandboxWsIdCred = args.dev_stage_id || getCurrentWorkspaceId();
63
75
  // The DevBridge API Key is a LONG-LIVED account-level credential (no expiry, manual
64
76
  // revocation only) — unlike the temporary STS AK/SK. It is stored in its own file
@@ -0,0 +1,136 @@
1
+ import { execOneShot, getCurrentWorkspaceId } from "../../sandbox/session-manager.js";
2
+ import { SANDBOX_TIMEOUT_MS } from "./schemas.js";
3
+ import { HWEXEC_TAIL_BYTES_DEFAULT, buildHwexecPollScript, buildHwexecStartScript, classifyHwexecStartOutput, deriveHwexecVerdict, generateHwexecTaskId, hwexecTaskDir, parseHwexecPollOutput, resolveHwexecPollTimeoutMs, validateHwexecTailBytes, validateHwexecTaskId, validateHwexecWaitMs, } from "../../sandbox/hwexec-task.js";
4
+ let oneShotForTests = null;
5
+ export function _setOneShotForTests(fn) {
6
+ oneShotForTests = fn;
7
+ }
8
+ async function runOneShot(workspaceId, command, username, timeoutMs) {
9
+ return (oneShotForTests ?? execOneShot)(workspaceId, command, username, timeoutMs);
10
+ }
11
+ // The client's advisory task memory (process lifetime — an agent restart
12
+ // forgets it by design). Poll correctness NEVER depends on it: it only
13
+ // separates lost (this process remembers the task, the directory is gone →
14
+ // the sandbox rebooted) from unknown (no memory of it), and enriches the
15
+ // poll receipt with firstStartedAt. The durable half is the caller's own
16
+ // task_id knowledge.
17
+ const hwexecTaskMemory = new Map();
18
+ function rememberHwexecTask(taskId, workspaceId, username) {
19
+ hwexecTaskMemory.set(taskId, { workspaceId, username, startedAt: new Date().toISOString() });
20
+ }
21
+ // The ws-exec timeout path (hwlink-exec-session.ts) throws its
22
+ // WebSocketExecError with exitCode 124 — both the ready-phase and the
23
+ // exec-phase timeout. Duck-typed: the number is the contract.
24
+ function isHwexecExecTimeout(error) {
25
+ return error instanceof Error && error.exitCode === 124;
26
+ }
27
+ // One poll of the task's current verdict, shared by the poll tool and the
28
+ // dup receipt (wait 0 — a snapshot, never a wait).
29
+ async function pollHwexecVerdict(taskId, workspaceId, username) {
30
+ const script = buildHwexecPollScript(taskId, 0, HWEXEC_TAIL_BYTES_DEFAULT);
31
+ const result = await runOneShot(workspaceId, script, username, resolveHwexecPollTimeoutMs(0, SANDBOX_TIMEOUT_MS.exec_poll));
32
+ return deriveHwexecVerdict(parseHwexecPollOutput(result.stdout), hwexecTaskMemory.has(taskId));
33
+ }
34
+ // The async branch of huaweicloud_sandbox_exec_one_shot: validate (or
35
+ // generate) the task id, build the claim-protocol start script, run it as
36
+ // one short exec, and fold the output (or a timeout) into the receipt.
37
+ export async function startHwexecTask(args, workspaceId, username) {
38
+ const taskId = args.task_id ? validateHwexecTaskId(args.task_id) : generateHwexecTaskId();
39
+ const taskDir = hwexecTaskDir(taskId);
40
+ const script = buildHwexecStartScript(taskId, String(args.command ?? ''));
41
+ const timeoutMs = args.timeout_ms || SANDBOX_TIMEOUT_MS.exec_one_shot_async;
42
+ let stdout;
43
+ try {
44
+ const result = await runOneShot(workspaceId, script, username, timeoutMs);
45
+ stdout = result.stdout;
46
+ }
47
+ catch (error) {
48
+ if (!isHwexecExecTimeout(error))
49
+ throw error;
50
+ rememberHwexecTask(taskId, workspaceId, username);
51
+ return {
52
+ started: 'uncertain',
53
+ taskId,
54
+ taskDir,
55
+ hint: 'The start exec timed out — the claim may already be placed. Retry with the SAME task_id: the claim file structurally prevents a second copy from ever spawning. If the retry returns started:"dup" with verdict "never", start over with a NEW task_id.',
56
+ };
57
+ }
58
+ const outcome = classifyHwexecStartOutput(stdout, taskId);
59
+ if (outcome === 'claim_error') {
60
+ return {
61
+ started: false,
62
+ ok: false,
63
+ taskId,
64
+ taskDir,
65
+ error: 'The task claim failed (the task directory could not be created, or the claim file could not be claimed) — the command was not started.',
66
+ hint: 'Check the sandbox /tmp state and retry; a stale /tmp/.hwexec directory with wrong permissions is the usual cause.',
67
+ };
68
+ }
69
+ rememberHwexecTask(taskId, workspaceId, username);
70
+ if (outcome === 'started') {
71
+ return {
72
+ started: true,
73
+ taskId,
74
+ taskDir,
75
+ hint: 'The task is claimed and the command is spawning detached. Poll with huaweicloud_sandbox_exec_poll (task_id, wait_ms up to 60000) until the verdict is done.',
76
+ };
77
+ }
78
+ // outcome === 'dup': the claim already existed. The receipt carries the
79
+ // current verdict — a done verdict hands the result over immediately; a
80
+ // never verdict is the claim protocol's trade teaching a NEW task_id.
81
+ let verdict = { verdict: 'unknown' };
82
+ try {
83
+ verdict = await pollHwexecVerdict(taskId, workspaceId, username);
84
+ }
85
+ catch {
86
+ // The dup fact is already certain; a failed verdict poll degrades to
87
+ // 'unknown' — the caller can poll again with the tool directly.
88
+ }
89
+ return {
90
+ started: 'dup',
91
+ taskId,
92
+ taskDir,
93
+ verdict: verdict.verdict,
94
+ exitCode: verdict.verdict === 'done' ? verdict.exitCode : undefined,
95
+ logTail: 'logTail' in verdict ? verdict.logTail : undefined,
96
+ hint: verdict.verdict === 'never'
97
+ ? 'The task was claimed but never launched (the start exec died between claim and spawn). Start over with a NEW task_id — a same-id retry can never spawn.'
98
+ : undefined,
99
+ };
100
+ }
101
+ const HWEXEC_VERDICT_HINTS = {
102
+ done: 'The command finished: exitCode is the command\u2019s exit status, logTail its captured stdout+stderr.',
103
+ running: 'Still running — poll again; pass wait_ms (up to 60000) to wait inside the poll.',
104
+ lost: 'The task is unrecoverable: the wrapper died without writing an exit status, or the task directory vanished (a sandbox reboot) while this process remembered the task. Restart the command with a NEW task_id if it still needs to run.',
105
+ never: 'The task was claimed but never launched (the start exec died between claim and spawn). Start over with a NEW task_id — a same-id retry can never spawn.',
106
+ unknown: 'No task directory and this process has no memory of this task_id — it never started here, or both the sandbox and this agent restarted since. Start the command with a NEW task_id.',
107
+ };
108
+ // huaweicloud_sandbox_exec_poll: run the bounded-wait poll script once and
109
+ // return the parsed verdict — never raw stdout. The exec timeout folds to
110
+ // wait_ms + 15s so the bounded wait always fits inside it.
111
+ export async function handleHwexecPoll(args = {}, _opts = {}) {
112
+ const workspaceId = args.workspace_id || getCurrentWorkspaceId();
113
+ if (!workspaceId) {
114
+ throw new Error('workspace_id is required. No sandbox connected — call huaweicloud_sandbox_connect first, ' +
115
+ 'or set HW_WORKSPACE_ID environment variable, before polling an async task.');
116
+ }
117
+ const username = args.username || 'root';
118
+ const taskId = validateHwexecTaskId(args.task_id);
119
+ const waitMs = validateHwexecWaitMs(args.wait_ms);
120
+ const tailBytes = validateHwexecTailBytes(args.tail_bytes);
121
+ const script = buildHwexecPollScript(taskId, waitMs, tailBytes);
122
+ const timeoutMs = resolveHwexecPollTimeoutMs(waitMs, args.timeout_ms || SANDBOX_TIMEOUT_MS.exec_poll);
123
+ const result = await runOneShot(workspaceId, script, username, timeoutMs);
124
+ const facts = parseHwexecPollOutput(result.stdout);
125
+ const memory = hwexecTaskMemory.get(taskId);
126
+ const verdict = deriveHwexecVerdict(facts, memory !== undefined);
127
+ return {
128
+ taskId,
129
+ taskDir: hwexecTaskDir(taskId),
130
+ verdict: verdict.verdict,
131
+ exitCode: verdict.verdict === 'done' ? verdict.exitCode : undefined,
132
+ logTail: 'logTail' in verdict ? verdict.logTail : undefined,
133
+ firstStartedAt: memory?.startedAt,
134
+ hint: HWEXEC_VERDICT_HINTS[verdict.verdict],
135
+ };
136
+ }
@@ -1,9 +1,12 @@
1
1
  import { execWithSession, execOneShot, closeSession, getCurrentWorkspaceId } from "../../sandbox/session-manager.js";
2
2
  import { forgetWorkspacePool } from "../../lib/hdkit/sandbox-pool.js";
3
3
  import { SANDBOX_TIMEOUT_MS } from "./schemas.js";
4
+ import { startHwexecTask } from "./handlers-hwexec.js";
4
5
  // Session/exec handlers for the sandbox pack, extracted verbatim from
5
6
  // tools.ts in the within-pack split for the jscpd complex-file bar; the
6
- // tools.ts face imports them for SANDBOX_TOOL_HANDLERS.
7
+ // tools.ts face imports them for SANDBOX_TOOL_HANDLERS. The exec_one_shot
8
+ // async branch (mode: "async", the claim protocol) delegates to
9
+ // handlers-hwexec.ts — the poll tool handler lives there whole.
7
10
  export async function handleExecWithSession(args = {}, _opts = {}) {
8
11
  const sandboxWsId2 = args.workspace_id || getCurrentWorkspaceId();
9
12
  if (!sandboxWsId2) {
@@ -25,6 +28,13 @@ export async function handleExecOneShot(args = {}, _opts = {}) {
25
28
  'or set HW_WORKSPACE_ID environment variable before starting the agent.');
26
29
  }
27
30
  const sandboxUser3 = args.username || 'root';
31
+ // mode: "async" routes into the claim protocol (claim + detached spawn +
32
+ // receipt, then huaweicloud_sandbox_exec_poll); every other mode value
33
+ // (the default sync, or a direct callTool caller's omission) runs the
34
+ // synchronous exec below unchanged.
35
+ if (args.mode === 'async') {
36
+ return startHwexecTask(args, sandboxWsId3, sandboxUser3);
37
+ }
28
38
  const sandboxTimeout3 = args.timeout_ms || SANDBOX_TIMEOUT_MS.exec_one_shot;
29
39
  const sandboxResult3 = await execOneShot(sandboxWsId3, args.command || '', sandboxUser3, sandboxTimeout3);
30
40
  return {