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,228 @@
1
+ import { execOneShot, getCurrentWorkspaceId } from '../../sandbox/session-manager.ts';
2
+ import type { CallToolOptions, ToolArgs } from '../../tools.ts';
3
+ import { SANDBOX_TIMEOUT_MS } from './schemas.ts';
4
+ import {
5
+ HWEXEC_TAIL_BYTES_DEFAULT,
6
+ buildHwexecPollScript,
7
+ buildHwexecStartScript,
8
+ classifyHwexecStartOutput,
9
+ deriveHwexecVerdict,
10
+ generateHwexecTaskId,
11
+ hwexecTaskDir,
12
+ parseHwexecPollOutput,
13
+ resolveHwexecPollTimeoutMs,
14
+ validateHwexecTailBytes,
15
+ validateHwexecTaskId,
16
+ validateHwexecWaitMs,
17
+ type HwexecVerdict,
18
+ type HwexecVerdictName,
19
+ } from '../../sandbox/hwexec-task.ts';
20
+
21
+ // The hwexec async-exec handlers (the claim protocol's tool face), split
22
+ // from handlers-session.ts per the within-pack family precedent: the
23
+ // exec_one_shot async branch delegates here (startHwexecTask), the poll
24
+ // tool lives here whole, and the module-local one-shot seam plus the
25
+ // advisory task memory are this module's state. tools.ts stays the stable
26
+ // face for registry.ts.
27
+
28
+ // Test seam: the hwexec flows are otherwise untestable end-to-end
29
+ // (execOneShot opens a real ws connection) — the module-local seam
30
+ // precedent (devbridge-exec.ts): every runOneShot call below resolves
31
+ // through the override; the pure helpers stay seam-free in hwexec-task.ts.
32
+ export interface HwexecOneShotResult {
33
+ stdout: string;
34
+ exitCode: number;
35
+ }
36
+ type HwexecOneShot = (
37
+ workspaceId: string,
38
+ command: string,
39
+ username: string,
40
+ timeoutMs: number,
41
+ ) => Promise<HwexecOneShotResult>;
42
+ let oneShotForTests: HwexecOneShot | null = null;
43
+
44
+ export function _setOneShotForTests(fn: HwexecOneShot | null): void {
45
+ oneShotForTests = fn;
46
+ }
47
+
48
+ async function runOneShot(workspaceId: string, command: string, username: string, timeoutMs: number) {
49
+ return (oneShotForTests ?? execOneShot)(workspaceId, command, username, timeoutMs);
50
+ }
51
+
52
+ // The client's advisory task memory (process lifetime — an agent restart
53
+ // forgets it by design). Poll correctness NEVER depends on it: it only
54
+ // separates lost (this process remembers the task, the directory is gone →
55
+ // the sandbox rebooted) from unknown (no memory of it), and enriches the
56
+ // poll receipt with firstStartedAt. The durable half is the caller's own
57
+ // task_id knowledge.
58
+ const hwexecTaskMemory = new Map<string, { workspaceId: string; username: string; startedAt: string }>();
59
+
60
+ function rememberHwexecTask(taskId: string, workspaceId: string, username: string): void {
61
+ hwexecTaskMemory.set(taskId, { workspaceId, username, startedAt: new Date().toISOString() });
62
+ }
63
+
64
+ // The ws-exec timeout path (hwlink-exec-session.ts) throws its
65
+ // WebSocketExecError with exitCode 124 — both the ready-phase and the
66
+ // exec-phase timeout. Duck-typed: the number is the contract.
67
+ function isHwexecExecTimeout(error: unknown): boolean {
68
+ return error instanceof Error && (error as { exitCode?: number }).exitCode === 124;
69
+ }
70
+
71
+ // One poll of the task's current verdict, shared by the poll tool and the
72
+ // dup receipt (wait 0 — a snapshot, never a wait).
73
+ async function pollHwexecVerdict(taskId: string, workspaceId: string, username: string): Promise<HwexecVerdict> {
74
+ const script = buildHwexecPollScript(taskId, 0, HWEXEC_TAIL_BYTES_DEFAULT);
75
+ const result = await runOneShot(
76
+ workspaceId,
77
+ script,
78
+ username,
79
+ resolveHwexecPollTimeoutMs(0, SANDBOX_TIMEOUT_MS.exec_poll),
80
+ );
81
+ return deriveHwexecVerdict(parseHwexecPollOutput(result.stdout), hwexecTaskMemory.has(taskId));
82
+ }
83
+
84
+ // The async-start receipt: the four shapes the claim protocol's start can
85
+ // produce, discriminated by `started` (the claim-error branch also carries
86
+ // ok:false per the protocol's receipt table). 'uncertain' means the
87
+ // receipt was lost to a start-exec timeout (the claim may already be
88
+ // placed); 'dup' carries the CURRENT verdict so a retry reads the task's
89
+ // real state in one call — retry safety is the protocol's reason to exist.
90
+ export type HwexecAsyncStartResult =
91
+ | { started: true; taskId: string; taskDir: string; hint: string }
92
+ | { started: 'uncertain'; taskId: string; taskDir: string; hint: string }
93
+ | {
94
+ started: 'dup';
95
+ taskId: string;
96
+ taskDir: string;
97
+ verdict: HwexecVerdictName;
98
+ exitCode?: number;
99
+ logTail?: string;
100
+ hint?: string;
101
+ }
102
+ | { started: false; ok: false; taskId: string; taskDir: string; error: string; hint: string };
103
+
104
+ // The async branch of huaweicloud_sandbox_exec_one_shot: validate (or
105
+ // generate) the task id, build the claim-protocol start script, run it as
106
+ // one short exec, and fold the output (or a timeout) into the receipt.
107
+ export async function startHwexecTask(
108
+ args: ToolArgs,
109
+ workspaceId: string,
110
+ username: string,
111
+ ): Promise<HwexecAsyncStartResult> {
112
+ const taskId = args.task_id ? validateHwexecTaskId(args.task_id) : generateHwexecTaskId();
113
+ const taskDir = hwexecTaskDir(taskId);
114
+ const script = buildHwexecStartScript(taskId, String(args.command ?? ''));
115
+ const timeoutMs = args.timeout_ms || SANDBOX_TIMEOUT_MS.exec_one_shot_async;
116
+ let stdout: string;
117
+ try {
118
+ const result = await runOneShot(workspaceId, script, username, timeoutMs);
119
+ stdout = result.stdout;
120
+ } catch (error) {
121
+ if (!isHwexecExecTimeout(error)) throw error;
122
+ rememberHwexecTask(taskId, workspaceId, username);
123
+ return {
124
+ started: 'uncertain',
125
+ taskId,
126
+ taskDir,
127
+ 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.',
128
+ };
129
+ }
130
+ const outcome = classifyHwexecStartOutput(stdout, taskId);
131
+ if (outcome === 'claim_error') {
132
+ return {
133
+ started: false,
134
+ ok: false,
135
+ taskId,
136
+ taskDir,
137
+ error:
138
+ 'The task claim failed (the task directory could not be created, or the claim file could not be claimed) — the command was not started.',
139
+ hint: 'Check the sandbox /tmp state and retry; a stale /tmp/.hwexec directory with wrong permissions is the usual cause.',
140
+ };
141
+ }
142
+ rememberHwexecTask(taskId, workspaceId, username);
143
+ if (outcome === 'started') {
144
+ return {
145
+ started: true,
146
+ taskId,
147
+ taskDir,
148
+ 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.',
149
+ };
150
+ }
151
+ // outcome === 'dup': the claim already existed. The receipt carries the
152
+ // current verdict — a done verdict hands the result over immediately; a
153
+ // never verdict is the claim protocol's trade teaching a NEW task_id.
154
+ let verdict: HwexecVerdict = { verdict: 'unknown' };
155
+ try {
156
+ verdict = await pollHwexecVerdict(taskId, workspaceId, username);
157
+ } catch {
158
+ // The dup fact is already certain; a failed verdict poll degrades to
159
+ // 'unknown' — the caller can poll again with the tool directly.
160
+ }
161
+ return {
162
+ started: 'dup',
163
+ taskId,
164
+ taskDir,
165
+ verdict: verdict.verdict,
166
+ exitCode: verdict.verdict === 'done' ? verdict.exitCode : undefined,
167
+ logTail: 'logTail' in verdict ? verdict.logTail : undefined,
168
+ hint:
169
+ verdict.verdict === 'never'
170
+ ? '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.'
171
+ : undefined,
172
+ };
173
+ }
174
+
175
+ const HWEXEC_VERDICT_HINTS: Record<HwexecVerdictName, string> = {
176
+ done: 'The command finished: exitCode is the command\u2019s exit status, logTail its captured stdout+stderr.',
177
+ running: 'Still running — poll again; pass wait_ms (up to 60000) to wait inside the poll.',
178
+ 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.',
179
+ never:
180
+ '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.',
181
+ unknown:
182
+ '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.',
183
+ };
184
+
185
+ export interface HwexecPollToolResult {
186
+ taskId: string;
187
+ taskDir: string;
188
+ verdict: HwexecVerdictName;
189
+ exitCode?: number;
190
+ logTail?: string;
191
+ firstStartedAt?: string;
192
+ hint: string;
193
+ }
194
+
195
+ // huaweicloud_sandbox_exec_poll: run the bounded-wait poll script once and
196
+ // return the parsed verdict — never raw stdout. The exec timeout folds to
197
+ // wait_ms + 15s so the bounded wait always fits inside it.
198
+ export async function handleHwexecPoll(
199
+ args: ToolArgs = {},
200
+ _opts: CallToolOptions = {},
201
+ ): Promise<HwexecPollToolResult> {
202
+ const workspaceId = args.workspace_id || getCurrentWorkspaceId();
203
+ if (!workspaceId) {
204
+ throw new Error(
205
+ 'workspace_id is required. No sandbox connected — call huaweicloud_sandbox_connect first, ' +
206
+ 'or set HW_WORKSPACE_ID environment variable, before polling an async task.',
207
+ );
208
+ }
209
+ const username = args.username || 'root';
210
+ const taskId = validateHwexecTaskId(args.task_id);
211
+ const waitMs = validateHwexecWaitMs(args.wait_ms);
212
+ const tailBytes = validateHwexecTailBytes(args.tail_bytes);
213
+ const script = buildHwexecPollScript(taskId, waitMs, tailBytes);
214
+ const timeoutMs = resolveHwexecPollTimeoutMs(waitMs, args.timeout_ms || SANDBOX_TIMEOUT_MS.exec_poll);
215
+ const result = await runOneShot(workspaceId, script, username, timeoutMs);
216
+ const facts = parseHwexecPollOutput(result.stdout);
217
+ const memory = hwexecTaskMemory.get(taskId);
218
+ const verdict = deriveHwexecVerdict(facts, memory !== undefined);
219
+ return {
220
+ taskId,
221
+ taskDir: hwexecTaskDir(taskId),
222
+ verdict: verdict.verdict,
223
+ exitCode: verdict.verdict === 'done' ? verdict.exitCode : undefined,
224
+ logTail: 'logTail' in verdict ? verdict.logTail : undefined,
225
+ firstStartedAt: memory?.startedAt,
226
+ hint: HWEXEC_VERDICT_HINTS[verdict.verdict],
227
+ };
228
+ }
@@ -2,10 +2,13 @@ import { execWithSession, execOneShot, closeSession, getCurrentWorkspaceId } fro
2
2
  import { forgetWorkspacePool } from '../../lib/hdkit/sandbox-pool.ts';
3
3
  import type { CallToolOptions, ToolArgs } from '../../tools.ts';
4
4
  import { SANDBOX_TIMEOUT_MS } from './schemas.ts';
5
+ import { startHwexecTask } from './handlers-hwexec.ts';
5
6
 
6
7
  // Session/exec handlers for the sandbox pack, extracted verbatim from
7
8
  // tools.ts in the within-pack split for the jscpd complex-file bar; the
8
- // tools.ts face imports them for SANDBOX_TOOL_HANDLERS.
9
+ // tools.ts face imports them for SANDBOX_TOOL_HANDLERS. The exec_one_shot
10
+ // async branch (mode: "async", the claim protocol) delegates to
11
+ // handlers-hwexec.ts — the poll tool handler lives there whole.
9
12
 
10
13
  export async function handleExecWithSession(args: ToolArgs = {}, _opts: CallToolOptions = {}) {
11
14
  const sandboxWsId2 = args.workspace_id || getCurrentWorkspaceId();
@@ -33,6 +36,13 @@ export async function handleExecOneShot(args: ToolArgs = {}, _opts: CallToolOpti
33
36
  );
34
37
  }
35
38
  const sandboxUser3 = args.username || 'root';
39
+ // mode: "async" routes into the claim protocol (claim + detached spawn +
40
+ // receipt, then huaweicloud_sandbox_exec_poll); every other mode value
41
+ // (the default sync, or a direct callTool caller's omission) runs the
42
+ // synchronous exec below unchanged.
43
+ if (args.mode === 'async') {
44
+ return startHwexecTask(args, sandboxWsId3, sandboxUser3);
45
+ }
36
46
  const sandboxTimeout3 = args.timeout_ms || SANDBOX_TIMEOUT_MS.exec_one_shot;
37
47
  const sandboxResult3 = await execOneShot(sandboxWsId3, args.command || '', sandboxUser3, sandboxTimeout3);
38
48
  return {
@@ -41,6 +41,7 @@ export async function handleExposeTunnel(args: ToolArgs = {}, _opts: CallToolOpt
41
41
  port: args.port,
42
42
  expiryHours: typeof args.expiry_hours === 'number' ? args.expiry_hours : undefined,
43
43
  keepalive: typeof args.keepalive === 'boolean' ? args.keepalive : undefined,
44
+ cleanupMode: args.cleanup_mode,
44
45
  // DevBridge API Key 自动创建兜底(认证固定 apikey,AK/SK 已移除)
45
46
  poolType: exposePoolContext?.poolMode || 'ephemeral',
46
47
  poolContext: exposePoolContext,
@@ -1,5 +1,12 @@
1
1
  import { z } from 'zod';
2
2
 
3
+ import {
4
+ HWEXEC_POLL_HEADROOM_MS,
5
+ HWEXEC_TAIL_BYTES_DEFAULT,
6
+ HWEXEC_TAIL_BYTES_MAX,
7
+ HWEXEC_TASK_ID_PATTERN,
8
+ HWEXEC_WAIT_MS_MAX,
9
+ } from '../../sandbox/hwexec-task.ts';
3
10
  import {
4
11
  numericArg,
5
12
  looseObject,
@@ -7,6 +14,8 @@ import {
7
14
  workspaceId,
8
15
  username,
9
16
  vendorConfirmed,
17
+ approvalTokenArg,
18
+ approvedByUserArg,
10
19
  } from '../../lib/tool-schema-parts.ts';
11
20
 
12
21
  // The sandbox pack's zod schema family, extracted from tools.ts in the
@@ -22,6 +31,16 @@ import {
22
31
  export const SANDBOX_TIMEOUT_MS = {
23
32
  exec_with_session: 120000,
24
33
  exec_one_shot: 120000,
34
+ // The async start's exec budget: the start script itself is fast (claim +
35
+ // spawn + receipt echo); a timeout here folds into the 'uncertain'
36
+ // receipt — the claim may have landed, and the same-task_id retry is
37
+ // structurally safe, so the short bound is honest, not lossy.
38
+ exec_one_shot_async: 30000,
39
+ // The poll's exec budget floor: the bounded wait loop (wait_ms, capped at
40
+ // 60000) plus the field round-trips must sit inside the timeout — the
41
+ // handler folds wait_ms + 15000 headroom via resolveHwexecPollTimeoutMs
42
+ // (the devbridge-expose-flow A2 doctrine), never below this floor.
43
+ exec_poll: 30000,
25
44
  upload_file: 120000,
26
45
  upload_project: 120000,
27
46
  deploy_nginx: 60000,
@@ -30,10 +49,11 @@ export const SANDBOX_TIMEOUT_MS = {
30
49
  // of dying as a ws-exec timeout (the pre-probing 30s default did not).
31
50
  deploy_check: 60000,
32
51
  // The expose script's A2 (#935) bounded waits can spend ~63s in one exec
33
- // (2s settle + up to 9s URL-extraction retries + 4 × 10s probes + 3 × 5s
34
- // backoff) plus the delete-all round-trip — the headroom exists for the
35
- // slow-gateway days the probe loop exists for, and a timeout still folds
36
- // into the structured unreachable envelope (never a raw ws error).
52
+ // (up to 9s URL-extraction retries + 4 × 10s probes + 3 × 5s backoff) — the
53
+ // headroom exists for the slow-gateway days the probe loop exists for, and
54
+ // a timeout still folds into the structured unreachable envelope (never a
55
+ // raw ws error). The selective pre-clean execs run outside this budget,
56
+ // each with its own bounded one-shot (devbridge-cleanup.ts).
37
57
  expose_tunnel: 90000,
38
58
  renew_tunnel: 60000,
39
59
  keepalive_watchdog: 60000,
@@ -46,15 +66,54 @@ export const execWithSessionSchema = z.looseObject({
46
66
  timeout_ms: numericArg
47
67
  .optional()
48
68
  .describe(`Execution timeout in milliseconds (default: ${SANDBOX_TIMEOUT_MS.exec_with_session})`),
69
+ approvalToken: approvalTokenArg,
70
+ approvedByUser: approvedByUserArg,
49
71
  });
50
72
 
51
73
  export const execOneShotSchema = z.looseObject({
52
74
  command: z.string().describe('The shell command to execute on the remote workspace'),
75
+ mode: z
76
+ .enum(['sync', 'async'])
77
+ .optional()
78
+ .describe(
79
+ 'sync (default): this exec waits for the command and returns its output. async: claim a per-task directory and spawn the command detached (it survives the exec session), return {started, taskId, taskDir} immediately, then poll with huaweicloud_sandbox_exec_poll. Use async for build/install-class commands that can outlive the sync timeout. Retry ladder: started:"uncertain" (start exec timed out, the claim may be placed) → retry the SAME task_id — the claim file blocks a second spawn; started:"dup" + verdict "never" → start over with a NEW task_id.',
80
+ ),
81
+ task_id: z
82
+ .string()
83
+ .optional()
84
+ .describe(
85
+ `async mode: the task id to claim, ${HWEXEC_TASK_ID_PATTERN.source} (path- and pgrep-safe). Defaults to a generated id. Reuse the SAME task_id when retrying an uncertain start — the claim file blocks a second copy.`,
86
+ ),
53
87
  workspace_id: workspaceId,
54
88
  username,
55
89
  timeout_ms: numericArg
56
90
  .optional()
57
- .describe(`Execution timeout in milliseconds (default: ${SANDBOX_TIMEOUT_MS.exec_one_shot})`),
91
+ .describe(
92
+ `Execution timeout in milliseconds (sync default: ${SANDBOX_TIMEOUT_MS.exec_one_shot}; async bounds only the start exec, default ${SANDBOX_TIMEOUT_MS.exec_one_shot_async} — the async command itself is unbounded and outlives the exec)`,
93
+ ),
94
+ approvalToken: approvalTokenArg,
95
+ approvedByUser: approvedByUserArg,
96
+ });
97
+
98
+ export const execPollSchema = z.looseObject({
99
+ task_id: z
100
+ .string()
101
+ .describe(`The task id from huaweicloud_sandbox_exec_one_shot async mode, ${HWEXEC_TASK_ID_PATTERN.source}.`),
102
+ workspace_id: workspaceId,
103
+ username,
104
+ wait_ms: numericArg
105
+ .optional()
106
+ .describe(
107
+ `Bounded in-poll wait: sleep-2 intervals checking the task status file, 0-${HWEXEC_WAIT_MS_MAX} (default 0 — snapshot only). The exec timeout auto-raises to wait_ms + ${HWEXEC_POLL_HEADROOM_MS} so the wait always fits.`,
108
+ ),
109
+ tail_bytes: numericArg
110
+ .optional()
111
+ .describe(`Log tail size in bytes, 1-${HWEXEC_TAIL_BYTES_MAX} (default: ${HWEXEC_TAIL_BYTES_DEFAULT}).`),
112
+ timeout_ms: numericArg
113
+ .optional()
114
+ .describe(
115
+ `Execution timeout in milliseconds (default: ${SANDBOX_TIMEOUT_MS.exec_poll}; auto-raised to wait_ms + ${HWEXEC_POLL_HEADROOM_MS} headroom, never below the default)`,
116
+ ),
58
117
  });
59
118
 
60
119
  export const closeSessionSchema = z.looseObject({
@@ -164,11 +223,19 @@ export const exposeTunnelSchema = z.looseObject({
164
223
  .describe(
165
224
  'Enroll the tunnel into the keepalive watchdog (default true — pass false to opt out). Returns keepalive.enrolled/tunnelCount/watchdogPid.',
166
225
  ),
226
+ cleanup_mode: z
227
+ .enum(['stale', 'all', 'none'])
228
+ .optional()
229
+ .describe(
230
+ "Tunnel cleanup before exposing. stale (default): delete same-port tunnels + orphan records/hosts; preserve other ports, other sessions and keepalive-protected tunnels — except a tunnel bound to THIS port, which is always replaced. all: wipe every tunnel/host (manual full reset only — a shared sandbox loses every session's tunnels). none: no cleanup (a stale same-port host can then conflict).",
231
+ ),
167
232
  workspace_id: workspaceId,
168
233
  username,
169
234
  timeout_ms: numericArg
170
235
  .optional()
171
236
  .describe(`Execution timeout in milliseconds (default: ${SANDBOX_TIMEOUT_MS.expose_tunnel})`),
237
+ approvalToken: approvalTokenArg,
238
+ approvedByUser: approvedByUserArg,
172
239
  });
173
240
 
174
241
  export const renewTunnelSchema = z.looseObject({
@@ -187,6 +254,8 @@ export const renewTunnelSchema = z.looseObject({
187
254
  timeout_ms: numericArg
188
255
  .optional()
189
256
  .describe(`Execution timeout in milliseconds (default: ${SANDBOX_TIMEOUT_MS.renew_tunnel})`),
257
+ approvalToken: approvalTokenArg,
258
+ approvedByUser: approvedByUserArg,
190
259
  });
191
260
 
192
261
  export const keepaliveWatchdogSchema = z.looseObject({
@@ -208,9 +277,14 @@ export const keepaliveWatchdogSchema = z.looseObject({
208
277
  timeout_ms: numericArg
209
278
  .optional()
210
279
  .describe(`Execution timeout in milliseconds (default: ${SANDBOX_TIMEOUT_MS.keepalive_watchdog})`),
280
+ approvalToken: approvalTokenArg,
281
+ approvedByUser: approvedByUserArg,
211
282
  });
212
283
 
213
- export const signAgreementSchema = z.looseObject({});
284
+ export const signAgreementSchema = z.looseObject({
285
+ approvalToken: approvalTokenArg,
286
+ approvedByUser: approvedByUserArg,
287
+ });
214
288
 
215
289
  export const connectSchema = z.looseObject({
216
290
  vendorConfirmed,
@@ -222,12 +296,13 @@ export const connectSchema = z.looseObject({
222
296
  .enum(['ephemeral', 'persistent'])
223
297
  .optional()
224
298
  .describe(
225
- 'Sandbox pool type (default ephemeral). ephemeral = non-persistent: idle auto-shutdown 30min + auto-delete 1h (platform scheduled task, verified) — save important data elsewhere; persistent = data disk retained, idle reclaim within 7 days. Each user may hold one instance per pool type (1+1). Explicit template_id overrides pool_type.',
299
+ 'Sandbox pool type (default ephemeral). ephemeral = non-persistent: idle auto-shutdown 30min + auto-delete 1h (platform scheduled task, verified) — save important data elsewhere; persistent = data disk retained, idle reclaim within 7 days. Each user may hold one instance per pool type (1+1); same-type requests reuse the existing instance. Custom templates are no longer supported.',
226
300
  ),
227
- template_id: z.string().optional().describe('Template ID; overrides server default (only for new sandbox)'),
228
301
  flavor_id: z.string().optional().describe('Flavor ID; overrides server default (only for new sandbox)'),
229
302
  env: looseObject.optional().describe('Environment variables to set in the sandbox (only for new sandbox)'),
230
303
  git: gitConfig.optional().describe('Git repo config (only for new sandbox)'),
304
+ approvalToken: approvalTokenArg,
305
+ approvedByUser: approvedByUserArg,
231
306
  });
232
307
 
233
308
  export const credentialsSchema = z.looseObject({
@@ -246,4 +321,21 @@ export const credentialsSchema = z.looseObject({
246
321
  .describe(
247
322
  'DevBridge API Key (devbridge_...), injected into the sandbox as HW_API_KEY for devbridge 0.2.x auth. Also accepts a vault ref (secret://<scope>/<name>), resolved locally so the key never enters the conversation. The local HW_API_KEY environment variable takes precedence over this param (preferred delivery — keeps the long-lived key out of the conversation). Users create one at https://devstation.connect.huaweicloud.com/space/devbridge/apikey (full value shown once at creation). Required for exposing web apps via devbridge 0.2.x; if missing, guide the user through creating one.',
248
323
  ),
324
+ approvalToken: approvalTokenArg,
325
+ approvedByUser: approvedByUserArg,
326
+ });
327
+
328
+ // 关机(dev 5d89c880):不可逆写类工具,走审批门(always 面);token 与
329
+ // attestation 与其余门面工具同型——schema 可选,门是执行者,首个无 token
330
+ // 调用必须能到达门以领取 mint 信封。
331
+ export const shutdownSchema = z.looseObject({
332
+ session_id: z.string().optional().describe('Session ID from huaweicloud_sandbox_connect (optional)'),
333
+ dev_stage_id: z.string().optional().describe('DevStation environment ID (alternative to session_id)'),
334
+ workspace_id: z
335
+ .string()
336
+ .optional()
337
+ .describe('Workspace ID; defaults to the current workspace (an alternative to session_id/dev_stage_id)'),
338
+ username,
339
+ approvalToken: approvalTokenArg,
340
+ approvedByUser: approvedByUserArg,
249
341
  });
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  execWithSessionSchema,
3
3
  execOneShotSchema,
4
+ execPollSchema,
4
5
  closeSessionSchema,
5
6
  uploadFileSchema,
6
7
  uploadProjectSchema,
@@ -13,12 +14,14 @@ import {
13
14
  signAgreementSchema,
14
15
  connectSchema,
15
16
  credentialsSchema,
17
+ shutdownSchema,
16
18
  } from './schemas.ts';
17
19
  import { handleExecWithSession, handleExecOneShot, handleCloseSession } from './handlers-session.ts';
20
+ import { handleHwexecPoll } from './handlers-hwexec.ts';
18
21
  import { handleUploadFile, handleUploadProject } from './handlers-upload.ts';
19
22
  import { handleDeployNginx, handleDeployCheck } from './handlers-deploy.ts';
20
23
  import { handleExposeTunnel, handleRenewTunnel, handleKeepaliveWatchdog } from './handlers-tunnel.ts';
21
- import { handleCheckUser, handleSignAgreement, handleConnect } from './handlers-account.ts';
24
+ import { handleCheckUser, handleSignAgreement, handleConnect, handleShutdown } from './handlers-account.ts';
22
25
  import { handleCredentials } from './handlers-credentials.ts';
23
26
  import type { PackToolDefinition, LooseToolSchema } from '../../lib/pack-types.ts';
24
27
 
@@ -32,10 +35,12 @@ import type { PackToolDefinition, LooseToolSchema } from '../../lib/pack-types.t
32
35
  // here. The family behind it (all siblings inside src/packs/sandbox/,
33
36
  // joining the pack-boundaries walk automatically): schemas.ts (the zod
34
37
  // schema block + the timeout table), git-transfer.ts (the repo transfer
35
- // trio), handlers-session.ts / handlers-upload.ts / handlers-deploy.ts /
36
- // handlers-tunnel.ts / handlers-account.ts / handlers-credentials.ts (the
37
- // tool handlers, migrated verbatim from src/tools.ts with the P2 pack
38
- // program).
38
+ // trio), handlers-session.ts / handlers-hwexec.ts / handlers-upload.ts /
39
+ // handlers-deploy.ts / handlers-tunnel.ts / handlers-account.ts /
40
+ // handlers-credentials.ts (the tool handlers, migrated verbatim from
41
+ // src/tools.ts with the P2 pack program; handlers-hwexec.ts carries the
42
+ // async-exec claim protocol — the exec_one_shot async branch and the
43
+ // exec_poll tool).
39
44
 
40
45
  export { SANDBOX_TIMEOUT_MS } from './schemas.ts';
41
46
 
@@ -50,10 +55,17 @@ export const SANDBOX_TOOLS = [
50
55
  {
51
56
  name: 'huaweicloud_sandbox_exec_one_shot',
52
57
  description:
53
- 'Execute a command on a workspace terminal with a fresh connection per call (no session state carries over). Each invocation opens a new WebSocket connection, executes one command, then disconnects. Use for long-running build/deploy/install commands (>30s) that do not need shell state persistence between calls. More stable than session-based execution for heavy workloads.',
58
+ 'Execute a command on a workspace terminal with a fresh connection per call (no session state carries over). Each invocation opens a new WebSocket connection, executes one command, then disconnects. Use for long-running build/deploy/install commands (>30s) that do not need shell state persistence between calls. More stable than session-based execution for heavy workloads. Commands that can outlive the sync timeout (default 120s) must run in mode: "async" instead: the tool claims a per-task directory with an atomic O_EXCL claim, spawns the command detached (setsid/nohup/disown — it survives the exec session), and returns immediately with {started, taskId, taskDir}; poll the verdict with huaweicloud_sandbox_exec_poll — that async + poll pair is the >30s long-command doctrine, and the same-task_id retry after started:"uncertain" is structurally double-spawn-safe. started:"dup" + verdict "never" → start over with a NEW task_id.',
54
59
  schema: execOneShotSchema,
55
60
  handler: handleExecOneShot,
56
61
  },
62
+ {
63
+ name: 'huaweicloud_sandbox_exec_poll',
64
+ description:
65
+ 'Poll an async sandbox task started by huaweicloud_sandbox_exec_one_shot with mode: "async". One call runs a bounded server-side wait (wait_ms 0-60000: sleep-2 intervals checking the task\'s status file; the exec timeout auto-folds to wait_ms + 15s so the wait always fits), then returns the task\'s verdict as a discriminated union — done (exitCode + logTail: the command finished), running (logTail: keep polling), lost (the wrapper died without an exit status, or the task directory vanished — a sandbox reboot — while this process remembered the task; restart with a new task_id if needed), never (the task was claimed but never launched — the start exec died between claim and spawn; start a NEW task_id, a same-id retry can never spawn), unknown (no task directory and no memory of the task_id — it never started here, or both the sandbox and this agent restarted). logTail is the last tail_bytes (default 4096) of the task\'s captured stdout+stderr. The retry ladder: started:"uncertain" → retry the SAME task_id (the claim file blocks a second copy); started:"dup" + verdict "never" → new task_id.',
66
+ schema: execPollSchema,
67
+ handler: handleHwexecPoll,
68
+ },
57
69
  {
58
70
  name: 'huaweicloud_sandbox_close_session',
59
71
  description:
@@ -92,7 +104,7 @@ export const SANDBOX_TOOLS = [
92
104
  {
93
105
  name: 'huaweicloud_sandbox_expose_tunnel',
94
106
  description:
95
- 'Expose a port on the sandbox to a public DevBridge tunnel URL (devbridge 0.2.x). Authenticates automatically (DevBridge auth is fixed to API Key — AK/SK login removed: the waterfall reads the sandbox keyring, then the /tmp/hw_api_key file channel; when both are empty it auto-creates the per-account × per-pool key (devkit-ephemeral/devkit-persistent) via the DevStation relay API and injects it, reporting authMode API_KEY_AUTO), pre-cleans stale tunnels to avoid quota errors, starts the host detached from the exec session (setsid/nohup/disown so it survives session teardown), extracts the public URL (https://<id>-<port>.devbridge-s2.hwtunnel.com), and health-checks it before returning. Use the ACTUAL port reported by huaweicloud_sandbox_deploy_nginx (its "port" field auto-increments on conflict) — never the originally requested port. This automates the manual "Expose the deployed app" flow (huawei-sandbox skill). Returns ok, publicUrl, port, tunnelId, authMode, expiresAt (expiry_hours lifetime, default 72h; 1-720), keepalive.enrolled/tunnelCount/watchdogPid, warnings, sandboxLifetime and urlLifetimeHint. The urlLifetimeHint MUST be relayed to the developer together with the URL: the tunnel expiry is NOT the sandbox lifetime — an idle sandbox shuts down (ephemeral also auto-deletes), which kills the URL. AUTO-ENROLLS the tunnel into the keepalive watchdog (unattended renewal + host re-attach + health check; pass keepalive:false to opt out). The URL is re-verified from a second independent exec session: persistent/verifyHttpCode distinguish a session-surviving URL from one that dies with the deploying session, and a non-persistent URL carries a 请勿分享 warning. Gateway-level tunnel errors (404 "tunnel not found" / "port not configured", 502 "bad gateway") are classified by exact body — an app\'s own 404/502 page is never mistaken for them. When no usable URL is reachable after retries it returns ok:false instead of a dead URL. When auto-creation hits the 20-key quota it returns ok:false with error_code HDKIT_DEVBRIDGE_KEY_QUOTA_EXCEEDED, the currentKeys list, and the console cleanup URL; a failed key invalidation self-heals by clearing the cache and recreating before the next probe.',
107
+ 'Expose a port on the sandbox to a public DevBridge tunnel URL (devbridge 0.2.x). Authenticates automatically (DevBridge auth is fixed to API Key — AK/SK login removed: the waterfall reads the sandbox keyring, then the /tmp/hw_api_key file channel; when both are empty it auto-creates the per-account × per-pool key (devkit-ephemeral/devkit-persistent) via the DevStation relay API and injects it, reporting authMode API_KEY_AUTO), selectively cleans only same-port/orphan tunnels before exposing (cleanup_mode=stale default — other ports, other sessions and keepalive-protected tunnels are preserved, except a tunnel bound to THIS port, which is always replaced; on 10006 quota it removes orphans first, then the oldest non-keepalive tunnel one at a time), starts the host detached from the exec session (setsid/nohup/disown so it survives session teardown), extracts the public URL (https://<id>-<port>.devbridge-s2.hwtunnel.com), and health-checks it before returning. Use the ACTUAL port reported by huaweicloud_sandbox_deploy_nginx (its "port" field auto-increments on conflict) — never the originally requested port. This automates the manual "Expose the deployed app" flow (huawei-sandbox skill). Returns ok, publicUrl, port, tunnelId, authMode, expiresAt (expiry_hours lifetime, default 72h; 1-720), keepalive.enrolled/tunnelCount/watchdogPid, warnings, sandboxLifetime and urlLifetimeHint. The urlLifetimeHint MUST be relayed to the developer together with the URL: the tunnel expiry is NOT the sandbox lifetime — an idle sandbox shuts down (ephemeral also auto-deletes), which kills the URL. AUTO-ENROLLS the tunnel into the keepalive watchdog (unattended renewal + host re-attach + health check; pass keepalive:false to opt out). The URL is re-verified from a second independent exec session: persistent/verifyHttpCode distinguish a session-surviving URL from one that dies with the deploying session, and a non-persistent URL carries a 请勿分享 warning. Gateway-level tunnel errors (404 "tunnel not found" / "port not configured", 502 "bad gateway") are classified by exact body — an app\'s own 404/502 page is never mistaken for them. When no usable URL is reachable after retries it returns ok:false instead of a dead URL; when the tunnel quota (10006) stays full after the selective cleanup it returns ok:false with error_code devbridge_tunnel_quota_exceeded (keepalive-protected tunnels are preserved — remove unused tunnels or retry with cleanup_mode=all for a full reset). When auto-creation hits the 20-key quota it returns ok:false with error_code HDKIT_DEVBRIDGE_KEY_QUOTA_EXCEEDED, the currentKeys list, and the console cleanup URL; a failed key invalidation self-heals by clearing the cache and recreating before the next probe. The auto-create relay goes through hdkitservice and inherits its 409 HDKIT_VERSION_TOO_OLD version gate: an outdated plugin fails auto-create the same way it fails connect, and the expose failure carries error_code HDKIT_VERSION_TOO_OLD with the upgrade remediation under gateRemediation, and clientVersion and minVersion when the service sends them — upgrade the plugin instead of creating a key by hand.',
96
108
  schema: exposeTunnelSchema,
97
109
  handler: handleExposeTunnel,
98
110
  },
@@ -127,7 +139,7 @@ export const SANDBOX_TOOLS = [
127
139
  {
128
140
  name: 'huaweicloud_sandbox_connect',
129
141
  description:
130
- 'Connect to a sandbox via hdkitservice. One instance per user per pool — reuses the same-pool sandbox if available, otherwise creates a new one. Quota: 1 instance per pool type (a user may hold 1 ephemeral AND 1 persistent simultaneously; same-type requests reuse the existing instance). On quota exhaustion the API returns HTTP 429 with a Retry-After header and a dual error code: HDKIT_QUOTA_EXCEEDED (retry useless — release or reuse the existing instance) vs HDKIT_CAPACITY_INSUFFICIENT (pool capacity; retry later / off-peak). Returns session_id, dev_stage_id, connection_id, connection_address, expiresAt (STS credential expiry), pool_type/template_id echo, server-configured lifecycle numbers (pool_idle_shutdown_minutes / pool_idle_delete_minutes / pool_reclaim_minutes) and started (true when a reused instance was woken from shutdown). Lifecycle hints are announced only on the first connect of a session or when started=true. Ephemeral pool (default): idle auto-shutdown after 30min, auto-delete after 1h — do not keep important data there. Persistent pool: data disk retained (EVS 32G), idle shutdown after 1h, idle reclaim capped at 7 days. Numbers are configured by hdkitservice; the text follows the server echo and falls back to these defaults. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.',
142
+ 'Connect to a sandbox via hdkitservice. One instance per user per pool — reuses the same-pool sandbox if available, otherwise creates a new one. Quota: 1 instance per pool type (a user may hold 1 ephemeral AND 1 persistent simultaneously; same-type requests reuse the existing instance). On quota exhaustion the API returns HTTP 429 with one of three codes: HDKIT_QUOTA_EXCEEDED (retry useless — release or reuse the existing instance; Retry-After 60), HDKIT_TEMPLATE_QUOTA_EXCEEDED (the running instances of this account for this sandbox type are at the limit — shut down or release an instance of the same type and retry; no Retry-After), or HDKIT_CAPACITY_INSUFFICIENT (pool capacity; retry later / off-peak; Retry-After 60). Gateway 502/504 timeouts during orchestration are retried automatically (30s/45s backoff) — the server may already have created the instance, so a retry reuses it. An outdated plugin version is rejected by the 409 HDKIT_VERSION_TOO_OLD version gate, surfaced by the sandbox tools (connect/check_user/sign_agreement/credentials) as ok:false and by the voucher trio as claimed:false, always carrying code, message, and remediation naming the upgrade act (npx --yes huaweicloud-devkit@latest update --target <agent>, restart the agent session, or huaweicloud_upgrade), with clientVersion and minVersion present when the service sends them. Returns session_id, dev_stage_id, connection_id, connection_address, expiresAt (STS credential expiry), pool_type/resolved template_id echo, server-configured lifecycle numbers (pool_idle_shutdown_minutes / pool_idle_delete_minutes / pool_reclaim_minutes) and started (true when a reused instance was woken from shutdown). Lifecycle hints are announced only on the first connect of a session or when started=true. Ephemeral pool (default): idle auto-shutdown after 30min, auto-delete after 1h — do not keep important data there. Persistent pool: data disk retained (EVS 32G), idle shutdown after 1h, idle reclaim capped at 7 days. Numbers are configured by hdkitservice; the text follows the server echo and falls back to these defaults. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.',
131
143
  schema: connectSchema,
132
144
  handler: handleConnect,
133
145
  },
@@ -138,6 +150,13 @@ export const SANDBOX_TOOLS = [
138
150
  schema: credentialsSchema,
139
151
  handler: handleCredentials,
140
152
  },
153
+ {
154
+ name: 'huaweicloud_sandbox_shutdown',
155
+ description:
156
+ 'Shut down a running sandbox via hdkitservice to stop core-hour consumption. This calls DevStation close, NOT delete: the instance is retained; for persistent sandboxes the EVS data disk is also retained. A later huaweicloud_sandbox_connect wakes it. Works for both ephemeral and persistent sandboxes. Only call when the developer explicitly asks to shut down; never auto-shutdown. Returns devStageId, status (stopped/shutting_down/already_stopped/close_requested) and message.',
157
+ schema: shutdownSchema,
158
+ handler: handleShutdown,
159
+ },
141
160
  ] as const satisfies readonly PackToolDefinition[];
142
161
 
143
162
  export type SandboxToolName = (typeof SANDBOX_TOOLS)[number]['name'];
@@ -148,6 +167,7 @@ export type SandboxToolName = (typeof SANDBOX_TOOLS)[number]['name'];
148
167
  export const SANDBOX_TOOL_SCHEMAS: Readonly<Record<SandboxToolName, LooseToolSchema>> = {
149
168
  huaweicloud_sandbox_exec_with_session: execWithSessionSchema,
150
169
  huaweicloud_sandbox_exec_one_shot: execOneShotSchema,
170
+ huaweicloud_sandbox_exec_poll: execPollSchema,
151
171
  huaweicloud_sandbox_close_session: closeSessionSchema,
152
172
  huaweicloud_sandbox_upload_file: uploadFileSchema,
153
173
  huaweicloud_sandbox_upload_project: uploadProjectSchema,
@@ -160,6 +180,7 @@ export const SANDBOX_TOOL_SCHEMAS: Readonly<Record<SandboxToolName, LooseToolSch
160
180
  huaweicloud_sandbox_sign_agreement: signAgreementSchema,
161
181
  huaweicloud_sandbox_connect: connectSchema,
162
182
  huaweicloud_sandbox_credentials: credentialsSchema,
183
+ huaweicloud_sandbox_shutdown: shutdownSchema,
163
184
  };
164
185
 
165
186
  // Dispatch map merged into PACK_TOOL_HANDLERS in packs/registry.ts. Typed over
@@ -168,6 +189,7 @@ export const SANDBOX_TOOL_SCHEMAS: Readonly<Record<SandboxToolName, LooseToolSch
168
189
  export const SANDBOX_TOOL_HANDLERS: Readonly<Record<SandboxToolName, PackToolDefinition['handler']>> = {
169
190
  huaweicloud_sandbox_exec_with_session: handleExecWithSession,
170
191
  huaweicloud_sandbox_exec_one_shot: handleExecOneShot,
192
+ huaweicloud_sandbox_exec_poll: handleHwexecPoll,
171
193
  huaweicloud_sandbox_close_session: handleCloseSession,
172
194
  huaweicloud_sandbox_upload_file: handleUploadFile,
173
195
  huaweicloud_sandbox_upload_project: handleUploadProject,
@@ -180,4 +202,5 @@ export const SANDBOX_TOOL_HANDLERS: Readonly<Record<SandboxToolName, PackToolDef
180
202
  huaweicloud_sandbox_sign_agreement: handleSignAgreement,
181
203
  huaweicloud_sandbox_connect: handleConnect,
182
204
  huaweicloud_sandbox_credentials: handleCredentials,
205
+ huaweicloud_sandbox_shutdown: handleShutdown,
183
206
  };
@@ -0,0 +1,50 @@
1
+ import { hashArgs } from '../../lib/approval-tokens.ts';
2
+ import { redactSecrets } from '../../safety-policy.ts';
3
+ import { parseSecretRef } from '../../lib/secret-vault/refs.ts';
4
+ import type { ApprovalSpec } from '../../approval-types.ts';
5
+ import type { ToolArgs } from '../../tools.ts';
6
+
7
+ // The secrets pack's approval registration (PR-3c): secret_delete is
8
+ // ALWAYS gated — it destroys the stored ciphertext with no version
9
+ // history, so a deleted ref is gone until its owner re-stores it. The
10
+ // binding and the confirmation view name the ref, because the ref is the
11
+ // entire consequence of the call. secret_set stays UNREGISTERED: the
12
+ // plaintext arrives from the user (channel=value is the user pasting it,
13
+ // file/envVar are user-designated sources), so the human is present by
14
+ // construction and a second confirmation would confirm nothing new.
15
+ // secret_list is the read-only inventory and stays ungated the same way.
16
+ function deleteBinding(args: ToolArgs): Record<string, unknown> {
17
+ return { ref: args.ref };
18
+ }
19
+
20
+ export const SECRETS_APPROVAL_SPECS: Readonly<Record<'huaweicloud_secret_delete', ApprovalSpec>> = {
21
+ huaweicloud_secret_delete: {
22
+ domain: 'secrets',
23
+ flavor: 'always',
24
+ tokenSource: 'gate',
25
+ normalizeArgs: deleteBinding,
26
+ // NoDoomedToken (interrogate round 2, fix-in-pass i): vaultDelete
27
+ // refuses an unparseable ref outright, so an approval minted for one is
28
+ // doomed — the retry would hit the same refusal forever. The ref must
29
+ // parse before any mint; the message mirrors vaultDelete's own
30
+ // VAULT_BAD_REF text so the two layers teach identically.
31
+ assertArgsExecutable: (value: unknown): void => {
32
+ const ref = (value as { ref?: unknown }).ref;
33
+ const parsed = typeof ref === 'string' ? parseSecretRef(ref) : null;
34
+ if (parsed === null) {
35
+ throw new Error(`"${String(ref)}" is not a valid secret ref (secret://<scope>/<name>, segments [a-z0-9-]).`);
36
+ }
37
+ },
38
+ // The view folds through the shared redaction vocabulary before any
39
+ // field reaches the summary or pin view (the ApprovalSpec contract);
40
+ // the hash binds the raw content.
41
+ summarize: (value) => {
42
+ const safe = redactSecrets(value) as { ref?: unknown };
43
+ return {
44
+ summary: `huaweicloud_secret_delete: delete secret ${String(safe.ref)} from the local vault (no version history)`,
45
+ argsHash: hashArgs(value),
46
+ pinView: safe,
47
+ };
48
+ },
49
+ },
50
+ };