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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +3 -1
  2. package/package.json +3 -1
  3. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +1 -1
  4. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +1 -1
  5. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +1 -1
  6. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +1 -1
  7. package/plugins/huaweicloud-core/.mcp.json +55 -1
  8. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +1 -1
  9. package/plugins/huaweicloud-core/dist/agents/codex-config.js +374 -0
  10. package/plugins/huaweicloud-core/dist/agents/codex-desktop.js +8 -1
  11. package/plugins/huaweicloud-core/dist/agents/codex.js +9 -0
  12. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +141 -86
  13. package/plugins/huaweicloud-core/dist/agents/opencode.js +106 -39
  14. package/plugins/huaweicloud-core/dist/approval-gate.js +1185 -0
  15. package/plugins/huaweicloud-core/dist/approval-ledger.js +2331 -0
  16. package/plugins/huaweicloud-core/dist/approval-roster.js +89 -0
  17. package/plugins/huaweicloud-core/dist/approval-types.js +1 -0
  18. package/plugins/huaweicloud-core/dist/approvals-cli.js +4 -4
  19. package/plugins/huaweicloud-core/dist/data/icons-manifest.v1.json +23 -5
  20. package/plugins/huaweicloud-core/dist/dep/receipts.js +65 -5
  21. package/plugins/huaweicloud-core/dist/explain-error.js +9 -1
  22. package/plugins/huaweicloud-core/dist/hcloud-cli.js +1 -1
  23. package/plugins/huaweicloud-core/dist/hcloud-plan.js +68 -62
  24. package/plugins/huaweicloud-core/dist/lib/approval-mode.js +7 -5
  25. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +18 -4
  26. package/plugins/huaweicloud-core/dist/lib/call-trace.js +7 -14
  27. package/plugins/huaweicloud-core/dist/lib/confirm-language.js +50 -0
  28. package/plugins/huaweicloud-core/dist/lib/credentials.js +9 -9
  29. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkit-gate.js +1398 -0
  30. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +371 -32
  31. package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +6 -16
  32. package/plugins/huaweicloud-core/dist/lib/opencode-ask-rule.js +224 -78
  33. package/plugins/huaweicloud-core/dist/lib/opencode-saved-perms.js +282 -0
  34. package/plugins/huaweicloud-core/dist/lib/supplemental-redaction.js +116 -0
  35. package/plugins/huaweicloud-core/dist/lib/tool-schema-parts.js +31 -0
  36. package/plugins/huaweicloud-core/dist/lib/workspace-glob.js +442 -0
  37. package/plugins/huaweicloud-core/dist/mcp-config-io.js +28 -1
  38. package/plugins/huaweicloud-core/dist/mcp-protocol.js +68 -16
  39. package/plugins/huaweicloud-core/dist/mcp-server.js +6933 -1186
  40. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  41. package/plugins/huaweicloud-core/dist/mcp-stdio-transport.js +14 -4
  42. package/plugins/huaweicloud-core/dist/packs/auth/approval.js +249 -0
  43. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +44 -44
  44. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +85 -130
  45. package/plugins/huaweicloud-core/dist/packs/obs/approval.js +110 -0
  46. package/plugins/huaweicloud-core/dist/packs/obs/tools.js +7 -2
  47. package/plugins/huaweicloud-core/dist/packs/registry.js +20 -1
  48. package/plugins/huaweicloud-core/dist/packs/sandbox/approval.js +245 -0
  49. package/plugins/huaweicloud-core/dist/packs/sandbox/expose-task.js +71 -0
  50. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +180 -23
  51. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +13 -1
  52. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-hwexec.js +136 -0
  53. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +11 -1
  54. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +29 -3
  55. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +93 -9
  56. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +37 -10
  57. package/plugins/huaweicloud-core/dist/packs/secrets/approval.js +46 -0
  58. package/plugins/huaweicloud-core/dist/packs/secrets/tools.js +4 -1
  59. package/plugins/huaweicloud-core/dist/packs/update/approval.js +79 -0
  60. package/plugins/huaweicloud-core/dist/packs/update/tools.js +8 -1
  61. package/plugins/huaweicloud-core/dist/packs/voucher/tools.js +1 -1
  62. package/plugins/huaweicloud-core/dist/packs-configure.js +74 -0
  63. package/plugins/huaweicloud-core/dist/risk-rule-engine.js +20 -4
  64. package/plugins/huaweicloud-core/dist/safety/classify-hcloud.js +6 -6
  65. package/plugins/huaweicloud-core/dist/safety/classify-text.js +36 -0
  66. package/plugins/huaweicloud-core/dist/safety/policy.js +2 -0
  67. package/plugins/huaweicloud-core/dist/safety/redact.js +21 -3
  68. package/plugins/huaweicloud-core/dist/safety/risk-merge.js +24 -4
  69. package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +1 -1
  70. package/plugins/huaweicloud-core/dist/sandbox/devbridge-auth.js +65 -14
  71. package/plugins/huaweicloud-core/dist/sandbox/devbridge-cleanup.js +422 -0
  72. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose-flow.js +66 -16
  73. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose.js +13 -10
  74. package/plugins/huaweicloud-core/dist/sandbox/devbridge-keepalive.js +42 -2
  75. package/plugins/huaweicloud-core/dist/sandbox/devbridge-key.js +11 -3
  76. package/plugins/huaweicloud-core/dist/sandbox/devbridge-tunnel.js +6 -0
  77. package/plugins/huaweicloud-core/dist/sandbox/devbridge-validation.js +10 -1
  78. package/plugins/huaweicloud-core/dist/sandbox/hwexec-task.js +244 -0
  79. package/plugins/huaweicloud-core/dist/setup-cli.js +36 -1
  80. package/plugins/huaweicloud-core/dist/tool-definitions.js +13 -1
  81. package/plugins/huaweicloud-core/dist/tool-schemas.js +32 -6
  82. package/plugins/huaweicloud-core/dist/tools.js +76 -9
  83. package/plugins/huaweicloud-core/dist/update-registry.js +358 -5
  84. package/plugins/huaweicloud-core/dist/update-upgrade.js +1083 -14
  85. package/plugins/huaweicloud-core/dist/vendor-gate.js +2 -2
  86. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +150 -1
  87. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +67 -4
  88. package/plugins/huaweicloud-core/openclaw.plugin.json +2 -2
  89. package/plugins/huaweicloud-core/safety/policy.json +18 -11
  90. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +115 -11
  91. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +198 -143
  92. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +36 -12
  93. package/plugins/huaweicloud-core/skills/huawei-voucher/SKILL.md +2 -0
  94. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +2 -2
  95. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +11 -7
  96. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +74 -29
  97. package/plugins/huaweicloud-core/skills/huaweicloud-troubleshooting/SKILL.md +21 -19
  98. package/plugins/huaweicloud-core/src/agents/codex-config.ts +432 -0
  99. package/plugins/huaweicloud-core/src/agents/codex-desktop.ts +8 -1
  100. package/plugins/huaweicloud-core/src/agents/codex.ts +10 -0
  101. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +176 -88
  102. package/plugins/huaweicloud-core/src/agents/opencode.ts +125 -54
  103. package/plugins/huaweicloud-core/src/approval-gate.ts +1306 -0
  104. package/plugins/huaweicloud-core/src/approval-ledger.ts +2446 -0
  105. package/plugins/huaweicloud-core/src/approval-roster.ts +127 -0
  106. package/plugins/huaweicloud-core/src/approval-types.ts +237 -0
  107. package/plugins/huaweicloud-core/src/approvals-cli.ts +4 -4
  108. package/plugins/huaweicloud-core/src/data/icons-manifest.v1.json +23 -5
  109. package/plugins/huaweicloud-core/src/dep/receipts.ts +84 -5
  110. package/plugins/huaweicloud-core/src/explain-error.ts +9 -1
  111. package/plugins/huaweicloud-core/src/hcloud-cli.ts +3 -0
  112. package/plugins/huaweicloud-core/src/hcloud-plan.ts +74 -71
  113. package/plugins/huaweicloud-core/src/lib/approval-mode.ts +7 -5
  114. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +19 -4
  115. package/plugins/huaweicloud-core/src/lib/call-trace.ts +7 -17
  116. package/plugins/huaweicloud-core/src/lib/confirm-language.ts +51 -0
  117. package/plugins/huaweicloud-core/src/lib/credentials.ts +9 -8
  118. package/plugins/huaweicloud-core/src/lib/hdkit/hdkit-gate.ts +1428 -0
  119. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +408 -30
  120. package/plugins/huaweicloud-core/src/lib/hdkit/sandbox-pool.ts +8 -15
  121. package/plugins/huaweicloud-core/src/lib/opencode-ask-rule.ts +302 -83
  122. package/plugins/huaweicloud-core/src/lib/opencode-saved-perms.ts +354 -0
  123. package/plugins/huaweicloud-core/src/lib/supplemental-redaction.ts +129 -0
  124. package/plugins/huaweicloud-core/src/lib/tool-schema-parts.ts +40 -0
  125. package/plugins/huaweicloud-core/src/lib/workspace-glob.ts +414 -0
  126. package/plugins/huaweicloud-core/src/mcp-config-io.ts +27 -1
  127. package/plugins/huaweicloud-core/src/mcp-protocol.ts +81 -17
  128. package/plugins/huaweicloud-core/src/mcp-server.ts +7 -7
  129. package/plugins/huaweicloud-core/src/mcp-stdio-transport.ts +14 -4
  130. package/plugins/huaweicloud-core/src/packs/auth/approval.ts +302 -0
  131. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +54 -45
  132. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +99 -137
  133. package/plugins/huaweicloud-core/src/packs/obs/approval.ts +122 -0
  134. package/plugins/huaweicloud-core/src/packs/obs/tools.ts +7 -2
  135. package/plugins/huaweicloud-core/src/packs/registry.ts +43 -1
  136. package/plugins/huaweicloud-core/src/packs/sandbox/approval.ts +296 -0
  137. package/plugins/huaweicloud-core/src/packs/sandbox/expose-task.ts +105 -0
  138. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +195 -23
  139. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +11 -1
  140. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-hwexec.ts +228 -0
  141. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +11 -1
  142. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +41 -14
  143. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +120 -8
  144. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +42 -9
  145. package/plugins/huaweicloud-core/src/packs/secrets/approval.ts +50 -0
  146. package/plugins/huaweicloud-core/src/packs/secrets/tools.ts +4 -1
  147. package/plugins/huaweicloud-core/src/packs/update/approval.ts +87 -0
  148. package/plugins/huaweicloud-core/src/packs/update/tools.ts +8 -1
  149. package/plugins/huaweicloud-core/src/packs/voucher/tools.ts +1 -1
  150. package/plugins/huaweicloud-core/src/packs-configure.ts +75 -0
  151. package/plugins/huaweicloud-core/src/risk-rule-engine.ts +20 -7
  152. package/plugins/huaweicloud-core/src/safety/classify-hcloud.ts +28 -16
  153. package/plugins/huaweicloud-core/src/safety/classify-text.ts +40 -0
  154. package/plugins/huaweicloud-core/src/safety/policy.ts +7 -0
  155. package/plugins/huaweicloud-core/src/safety/redact.ts +24 -6
  156. package/plugins/huaweicloud-core/src/safety/risk-merge.ts +26 -5
  157. package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +1 -1
  158. package/plugins/huaweicloud-core/src/sandbox/devbridge-auth.ts +74 -14
  159. package/plugins/huaweicloud-core/src/sandbox/devbridge-cleanup.ts +511 -0
  160. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose-flow.ts +70 -18
  161. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose.ts +26 -10
  162. package/plugins/huaweicloud-core/src/sandbox/devbridge-keepalive.ts +41 -2
  163. package/plugins/huaweicloud-core/src/sandbox/devbridge-key.ts +9 -3
  164. package/plugins/huaweicloud-core/src/sandbox/devbridge-tunnel.ts +24 -0
  165. package/plugins/huaweicloud-core/src/sandbox/devbridge-validation.ts +11 -1
  166. package/plugins/huaweicloud-core/src/sandbox/hwexec-task.ts +304 -0
  167. package/plugins/huaweicloud-core/src/setup-cli.ts +39 -1
  168. package/plugins/huaweicloud-core/src/tool-definitions.ts +13 -1
  169. package/plugins/huaweicloud-core/src/tool-schemas.ts +39 -6
  170. package/plugins/huaweicloud-core/src/tools.ts +124 -10
  171. package/plugins/huaweicloud-core/src/update-registry.ts +340 -5
  172. package/plugins/huaweicloud-core/src/update-upgrade.ts +1130 -14
  173. package/plugins/huaweicloud-core/src/vendor-gate.ts +2 -2
@@ -0,0 +1,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 {
@@ -1,6 +1,8 @@
1
1
  import { exposeTunnel, renewTunnel, installKeepaliveWatchdog, validateTunnelId, } from "../../sandbox/devbridge-tunnel.js";
2
2
  import { getCurrentWorkspaceId } from "../../sandbox/session-manager.js";
3
+ import { validateTunnelPort } from "../../sandbox/devbridge-validation.js";
3
4
  import { poolContextFor } from "../../lib/hdkit/sandbox-pool.js";
5
+ import { startExposeTask, pollExposeTask } from "./expose-task.js";
4
6
  import { buildKeyringInjectScript, ensureDevbridgeKey, listKeysForQuotaHint, recreateDevbridgeKey, } from "../../sandbox/devbridge-key.js";
5
7
  import { SANDBOX_TIMEOUT_MS } from "./schemas.js";
6
8
  // Tunnel handlers (expose/renew/keepalive-watchdog) for the sandbox pack,
@@ -18,15 +20,39 @@ export async function handleExposeTunnel(args = {}, _opts = {}) {
18
20
  const sandboxUser9 = args.username || 'root';
19
21
  const sandboxTimeout9 = args.timeout_ms || SANDBOX_TIMEOUT_MS.expose_tunnel;
20
22
  const exposePoolContext = poolContextFor(sandboxWsId9);
21
- return await exposeTunnel(sandboxWsId9, {
22
- port: args.port,
23
+ const exposeArgs = {
24
+ port: validateTunnelPort(args.port),
23
25
  expiryHours: typeof args.expiry_hours === 'number' ? args.expiry_hours : undefined,
24
26
  keepalive: typeof args.keepalive === 'boolean' ? args.keepalive : undefined,
27
+ cleanupMode: args.cleanup_mode,
25
28
  // DevBridge API Key 自动创建兜底(认证固定 apikey,AK/SK 已移除)
26
29
  poolType: exposePoolContext?.poolMode || 'ephemeral',
27
30
  poolContext: exposePoolContext,
28
31
  keyUpgrade: { ensureDevbridgeKey, recreateDevbridgeKey, buildKeyringInjectScript, listKeysForQuotaHint },
29
- }, sandboxUser9, sandboxTimeout9);
32
+ };
33
+ // AX N-SB.1: the chain can outlive the host's request timeout while the
34
+ // server completes it — async starts it detached and the poll tool delivers
35
+ // the URL in-band. The fast parameter checks above stay synchronous, so a
36
+ // bad port is an immediate error, not a deferred task failure.
37
+ if (args.mode === 'async') {
38
+ const { taskId } = startExposeTask(sandboxWsId9, exposeArgs.port, () => exposeTunnel(sandboxWsId9, exposeArgs, sandboxUser9, sandboxTimeout9));
39
+ return {
40
+ started: true,
41
+ mode: 'async',
42
+ taskId,
43
+ hint: 'The expose chain is running in the background. Poll huaweicloud_sandbox_expose_poll with this taskId until ' +
44
+ 'state is done — the publicUrl and urlLifetimeHint are delivered there (the task receipt lives 30 minutes in ' +
45
+ 'this MCP server process).',
46
+ };
47
+ }
48
+ return await exposeTunnel(sandboxWsId9, exposeArgs, sandboxUser9, sandboxTimeout9);
49
+ }
50
+ export async function handleExposePoll(args = {}, _opts = {}) {
51
+ const taskId = args.task_id;
52
+ if (typeof taskId !== 'string' || taskId === '') {
53
+ throw new Error('task_id is required — pass the taskId returned by huaweicloud_sandbox_expose_tunnel mode:"async".');
54
+ }
55
+ return pollExposeTask(taskId);
30
56
  }
31
57
  export async function handleRenewTunnel(args = {}, _opts = {}) {
32
58
  if (!args.tunnel_id) {
@@ -1,5 +1,7 @@
1
1
  import { z } from 'zod';
2
- import { numericArg, looseObject, gitConfig, workspaceId, username, vendorConfirmed, } from "../../lib/tool-schema-parts.js";
2
+ import { HWEXEC_POLL_HEADROOM_MS, HWEXEC_TAIL_BYTES_DEFAULT, HWEXEC_TAIL_BYTES_MAX, HWEXEC_TASK_ID_PATTERN, HWEXEC_WAIT_MS_MAX, } from "../../sandbox/hwexec-task.js";
3
+ import { numericArg, looseObject, gitConfig, workspaceId, username, vendorConfirmed, approvalTokenArg, approvedByUserArg, } from "../../lib/tool-schema-parts.js";
4
+ import { EXPOSE_TASK_ID_PATTERN } from "./expose-task.js";
3
5
  // The sandbox pack's zod schema family, extracted from tools.ts in the
4
6
  // within-pack split for the jscpd complex-file bar. tools.ts stays the stable
5
7
  // face: it imports every schema here for the SANDBOX_TOOLS /
@@ -12,6 +14,16 @@ import { numericArg, looseObject, gitConfig, workspaceId, username, vendorConfir
12
14
  export const SANDBOX_TIMEOUT_MS = {
13
15
  exec_with_session: 120000,
14
16
  exec_one_shot: 120000,
17
+ // The async start's exec budget: the start script itself is fast (claim +
18
+ // spawn + receipt echo); a timeout here folds into the 'uncertain'
19
+ // receipt — the claim may have landed, and the same-task_id retry is
20
+ // structurally safe, so the short bound is honest, not lossy.
21
+ exec_one_shot_async: 30000,
22
+ // The poll's exec budget floor: the bounded wait loop (wait_ms, capped at
23
+ // 60000) plus the field round-trips must sit inside the timeout — the
24
+ // handler folds wait_ms + 15000 headroom via resolveHwexecPollTimeoutMs
25
+ // (the devbridge-expose-flow A2 doctrine), never below this floor.
26
+ exec_poll: 30000,
15
27
  upload_file: 120000,
16
28
  upload_project: 120000,
17
29
  deploy_nginx: 60000,
@@ -20,10 +32,11 @@ export const SANDBOX_TIMEOUT_MS = {
20
32
  // of dying as a ws-exec timeout (the pre-probing 30s default did not).
21
33
  deploy_check: 60000,
22
34
  // The expose script's A2 (#935) bounded waits can spend ~63s in one exec
23
- // (2s settle + up to 9s URL-extraction retries + 4 × 10s probes + 3 × 5s
24
- // backoff) plus the delete-all round-trip — the headroom exists for the
25
- // slow-gateway days the probe loop exists for, and a timeout still folds
26
- // into the structured unreachable envelope (never a raw ws error).
35
+ // (up to 9s URL-extraction retries + 4 × 10s probes + 3 × 5s backoff) — the
36
+ // headroom exists for the slow-gateway days the probe loop exists for, and
37
+ // a timeout still folds into the structured unreachable envelope (never a
38
+ // raw ws error). The selective pre-clean execs run outside this budget,
39
+ // each with its own bounded one-shot (devbridge-cleanup.ts).
27
40
  expose_tunnel: 90000,
28
41
  renew_tunnel: 60000,
29
42
  keepalive_watchdog: 60000,
@@ -35,14 +48,42 @@ export const execWithSessionSchema = z.looseObject({
35
48
  timeout_ms: numericArg
36
49
  .optional()
37
50
  .describe(`Execution timeout in milliseconds (default: ${SANDBOX_TIMEOUT_MS.exec_with_session})`),
51
+ approvalToken: approvalTokenArg,
52
+ approvedByUser: approvedByUserArg,
38
53
  });
39
54
  export const execOneShotSchema = z.looseObject({
40
55
  command: z.string().describe('The shell command to execute on the remote workspace'),
56
+ mode: z
57
+ .enum(['sync', 'async'])
58
+ .optional()
59
+ .describe('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.'),
60
+ task_id: z
61
+ .string()
62
+ .optional()
63
+ .describe(`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.`),
41
64
  workspace_id: workspaceId,
42
65
  username,
43
66
  timeout_ms: numericArg
44
67
  .optional()
45
- .describe(`Execution timeout in milliseconds (default: ${SANDBOX_TIMEOUT_MS.exec_one_shot})`),
68
+ .describe(`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)`),
69
+ approvalToken: approvalTokenArg,
70
+ approvedByUser: approvedByUserArg,
71
+ });
72
+ export const execPollSchema = z.looseObject({
73
+ task_id: z
74
+ .string()
75
+ .describe(`The task id from huaweicloud_sandbox_exec_one_shot async mode, ${HWEXEC_TASK_ID_PATTERN.source}.`),
76
+ workspace_id: workspaceId,
77
+ username,
78
+ wait_ms: numericArg
79
+ .optional()
80
+ .describe(`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.`),
81
+ tail_bytes: numericArg
82
+ .optional()
83
+ .describe(`Log tail size in bytes, 1-${HWEXEC_TAIL_BYTES_MAX} (default: ${HWEXEC_TAIL_BYTES_DEFAULT}).`),
84
+ timeout_ms: numericArg
85
+ .optional()
86
+ .describe(`Execution timeout in milliseconds (default: ${SANDBOX_TIMEOUT_MS.exec_poll}; auto-raised to wait_ms + ${HWEXEC_POLL_HEADROOM_MS} headroom, never below the default)`),
46
87
  });
47
88
  export const closeSessionSchema = z.looseObject({
48
89
  workspace_id: workspaceId,
@@ -125,11 +166,30 @@ export const exposeTunnelSchema = z.looseObject({
125
166
  .boolean()
126
167
  .optional()
127
168
  .describe('Enroll the tunnel into the keepalive watchdog (default true — pass false to opt out). Returns keepalive.enrolled/tunnelCount/watchdogPid.'),
169
+ cleanup_mode: z
170
+ .enum(['stale', 'all', 'none'])
171
+ .optional()
172
+ .describe("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)."),
173
+ mode: z
174
+ .enum(['sync', 'async'])
175
+ .optional()
176
+ .describe('sync (default): run the whole expose chain and return its result. async: start the chain in the background and return ' +
177
+ '{started:true, taskId, hint} immediately — use it on MCP hosts whose per-request timeout is shorter than the expose ' +
178
+ 'chain (auth + selective cleanup + up to four ~63s expose attempts + re-verify + keepalive enrollment), then poll ' +
179
+ 'huaweicloud_sandbox_expose_poll with taskId. The task receipt lives in this MCP server process (30 min).'),
128
180
  workspace_id: workspaceId,
129
181
  username,
130
182
  timeout_ms: numericArg
131
183
  .optional()
132
184
  .describe(`Execution timeout in milliseconds (default: ${SANDBOX_TIMEOUT_MS.expose_tunnel})`),
185
+ approvalToken: approvalTokenArg,
186
+ approvedByUser: approvedByUserArg,
187
+ });
188
+ export const exposePollSchema = z.looseObject({
189
+ task_id: z
190
+ .string()
191
+ .regex(EXPOSE_TASK_ID_PATTERN, 'task_id must be the exp-<uuid> from huaweicloud_sandbox_expose_tunnel mode:"async".')
192
+ .describe('The taskId returned by huaweicloud_sandbox_expose_tunnel with mode:"async".'),
133
193
  });
134
194
  export const renewTunnelSchema = z.looseObject({
135
195
  tunnel_id: z
@@ -143,6 +203,8 @@ export const renewTunnelSchema = z.looseObject({
143
203
  timeout_ms: numericArg
144
204
  .optional()
145
205
  .describe(`Execution timeout in milliseconds (default: ${SANDBOX_TIMEOUT_MS.renew_tunnel})`),
206
+ approvalToken: approvalTokenArg,
207
+ approvedByUser: approvedByUserArg,
146
208
  });
147
209
  export const keepaliveWatchdogSchema = z.looseObject({
148
210
  tunnels: z
@@ -159,8 +221,13 @@ export const keepaliveWatchdogSchema = z.looseObject({
159
221
  timeout_ms: numericArg
160
222
  .optional()
161
223
  .describe(`Execution timeout in milliseconds (default: ${SANDBOX_TIMEOUT_MS.keepalive_watchdog})`),
224
+ approvalToken: approvalTokenArg,
225
+ approvedByUser: approvedByUserArg,
226
+ });
227
+ export const signAgreementSchema = z.looseObject({
228
+ approvalToken: approvalTokenArg,
229
+ approvedByUser: approvedByUserArg,
162
230
  });
163
- export const signAgreementSchema = z.looseObject({});
164
231
  export const connectSchema = z.looseObject({
165
232
  vendorConfirmed,
166
233
  source: z
@@ -170,11 +237,12 @@ export const connectSchema = z.looseObject({
170
237
  pool_type: z
171
238
  .enum(['ephemeral', 'persistent'])
172
239
  .optional()
173
- .describe('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.'),
174
- template_id: z.string().optional().describe('Template ID; overrides server default (only for new sandbox)'),
240
+ .describe('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.'),
175
241
  flavor_id: z.string().optional().describe('Flavor ID; overrides server default (only for new sandbox)'),
176
242
  env: looseObject.optional().describe('Environment variables to set in the sandbox (only for new sandbox)'),
177
243
  git: gitConfig.optional().describe('Git repo config (only for new sandbox)'),
244
+ approvalToken: approvalTokenArg,
245
+ approvedByUser: approvedByUserArg,
178
246
  });
179
247
  export const credentialsSchema = z.looseObject({
180
248
  session_id: z.string().optional().describe('Session ID from huaweicloud_sandbox_connect'),
@@ -188,4 +256,20 @@ export const credentialsSchema = z.looseObject({
188
256
  .string()
189
257
  .optional()
190
258
  .describe('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.'),
259
+ approvalToken: approvalTokenArg,
260
+ approvedByUser: approvedByUserArg,
261
+ });
262
+ // 关机(dev 5d89c880):不可逆写类工具,走审批门(always 面);token 与
263
+ // attestation 与其余门面工具同型——schema 可选,门是执行者,首个无 token
264
+ // 调用必须能到达门以领取 mint 信封。
265
+ export const shutdownSchema = z.looseObject({
266
+ session_id: z.string().optional().describe('Session ID from huaweicloud_sandbox_connect (optional)'),
267
+ dev_stage_id: z.string().optional().describe('DevStation environment ID (alternative to session_id)'),
268
+ workspace_id: z
269
+ .string()
270
+ .optional()
271
+ .describe('Workspace ID; defaults to the current workspace (an alternative to session_id/dev_stage_id)'),
272
+ username,
273
+ approvalToken: approvalTokenArg,
274
+ approvedByUser: approvedByUserArg,
191
275
  });
@@ -1,9 +1,10 @@
1
- import { execWithSessionSchema, execOneShotSchema, closeSessionSchema, uploadFileSchema, uploadProjectSchema, deployNginxSchema, deployCheckSchema, checkUserSchema, exposeTunnelSchema, renewTunnelSchema, keepaliveWatchdogSchema, signAgreementSchema, connectSchema, credentialsSchema, } from "./schemas.js";
1
+ import { execWithSessionSchema, execOneShotSchema, execPollSchema, closeSessionSchema, uploadFileSchema, uploadProjectSchema, deployNginxSchema, deployCheckSchema, checkUserSchema, exposeTunnelSchema, exposePollSchema, renewTunnelSchema, keepaliveWatchdogSchema, signAgreementSchema, connectSchema, credentialsSchema, shutdownSchema, } from "./schemas.js";
2
2
  import { handleExecWithSession, handleExecOneShot, handleCloseSession } from "./handlers-session.js";
3
+ import { handleHwexecPoll } from "./handlers-hwexec.js";
3
4
  import { handleUploadFile, handleUploadProject } from "./handlers-upload.js";
4
5
  import { handleDeployNginx, handleDeployCheck } from "./handlers-deploy.js";
5
- import { handleExposeTunnel, handleRenewTunnel, handleKeepaliveWatchdog } from "./handlers-tunnel.js";
6
- import { handleCheckUser, handleSignAgreement, handleConnect } from "./handlers-account.js";
6
+ import { handleExposeTunnel, handleExposePoll, handleRenewTunnel, handleKeepaliveWatchdog } from "./handlers-tunnel.js";
7
+ import { handleCheckUser, handleSignAgreement, handleConnect, handleShutdown } from "./handlers-account.js";
7
8
  import { handleCredentials } from "./handlers-credentials.js";
8
9
  // The sandbox pack's stable face (split from the former 879-line monolith
9
10
  // for the jscpd complex-file bar, cx < 50 per file; the safety-policy.ts
@@ -15,10 +16,12 @@ import { handleCredentials } from "./handlers-credentials.js";
15
16
  // here. The family behind it (all siblings inside src/packs/sandbox/,
16
17
  // joining the pack-boundaries walk automatically): schemas.ts (the zod
17
18
  // schema block + the timeout table), git-transfer.ts (the repo transfer
18
- // trio), handlers-session.ts / handlers-upload.ts / handlers-deploy.ts /
19
- // handlers-tunnel.ts / handlers-account.ts / handlers-credentials.ts (the
20
- // tool handlers, migrated verbatim from src/tools.ts with the P2 pack
21
- // program).
19
+ // trio), handlers-session.ts / handlers-hwexec.ts / handlers-upload.ts /
20
+ // handlers-deploy.ts / handlers-tunnel.ts / handlers-account.ts /
21
+ // handlers-credentials.ts (the tool handlers, migrated verbatim from
22
+ // src/tools.ts with the P2 pack program; handlers-hwexec.ts carries the
23
+ // async-exec claim protocol — the exec_one_shot async branch and the
24
+ // exec_poll tool).
22
25
  export { SANDBOX_TIMEOUT_MS } from "./schemas.js";
23
26
  export const SANDBOX_TOOLS = [
24
27
  {
@@ -29,10 +32,16 @@ export const SANDBOX_TOOLS = [
29
32
  },
30
33
  {
31
34
  name: 'huaweicloud_sandbox_exec_one_shot',
32
- description: '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.',
35
+ description: '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.',
33
36
  schema: execOneShotSchema,
34
37
  handler: handleExecOneShot,
35
38
  },
39
+ {
40
+ name: 'huaweicloud_sandbox_exec_poll',
41
+ description: '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.',
42
+ schema: execPollSchema,
43
+ handler: handleHwexecPoll,
44
+ },
36
45
  {
37
46
  name: 'huaweicloud_sandbox_close_session',
38
47
  description: 'Close the persistent terminal session for a workspace. This closes the agent-side terminal session only — it does NOT delete the sandbox instance. Resource-pool sandbox deletion is developer-initiated (always ask for a second confirmation before guiding a delete) or handled by the platform resource-group idle-reclaim policy within the 7-day cap (v3 caliber); devkit never defers or performs deletion on the user behalf.',
@@ -65,10 +74,16 @@ export const SANDBOX_TOOLS = [
65
74
  },
66
75
  {
67
76
  name: 'huaweicloud_sandbox_expose_tunnel',
68
- description: '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.',
77
+ description: '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.',
69
78
  schema: exposeTunnelSchema,
70
79
  handler: handleExposeTunnel,
71
80
  },
81
+ {
82
+ name: 'huaweicloud_sandbox_expose_poll',
83
+ description: 'Poll an async expose task started by huaweicloud_sandbox_expose_tunnel with mode: "async". Returns state: running (the chain is still working — call again), done (result carries the full expose envelope: ok, publicUrl, port, tunnelId, expiresAt, urlLifetimeHint, keepalive, warnings), failed (an unexpected throw escaped the chain, with error), or unknown (no receipt in this MCP server process — it never started here, the session restarted, or the 30-minute receipt expired; the tunnel may already exist, so check huaweicloud_sandbox_deploy_check or re-expose — never assume success without a URL). The urlLifetimeHint MUST be relayed with the URL: the tunnel expiry is not the sandbox lifetime.',
84
+ schema: exposePollSchema,
85
+ handler: handleExposePoll,
86
+ },
72
87
  {
73
88
  name: 'huaweicloud_sandbox_renew_tunnel',
74
89
  description: "Renew a DevBridge tunnel's lifetime (devbridge update <id> -e <hours>) — a ROLLING window: expiration = now + hours regardless of remaining time, so renewing before expiry keeps the SAME public URL alive indefinitely (the URL is bound to the tunnel ID and never changes). Default 720h = the 30-day maximum. Returns ok, tunnelId, expiresAt (absolute ISO timestamp read back via show -v — a management-plane loss (10002 tunnel not found) is NOT misread as success), renewedForHours. Use the tunnelId from huaweicloud_sandbox_expose_tunnel or extract it from the URL. The keepalive watchdog renews automatically; this tool is the manual/one-off path.",
@@ -95,7 +110,7 @@ export const SANDBOX_TOOLS = [
95
110
  },
96
111
  {
97
112
  name: 'huaweicloud_sandbox_connect',
98
- description: '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.',
113
+ description: '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 return a pending receipt (ok:false, pending:true, retryAfter, hint) instead of holding the call through the backoff — the server may already have created the instance; re-call this tool with the SAME parameters after retryAfter and a created instance is reused. 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.',
99
114
  schema: connectSchema,
100
115
  handler: handleConnect,
101
116
  },
@@ -105,6 +120,12 @@ export const SANDBOX_TOOLS = [
105
120
  schema: credentialsSchema,
106
121
  handler: handleCredentials,
107
122
  },
123
+ {
124
+ name: 'huaweicloud_sandbox_shutdown',
125
+ description: '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.',
126
+ schema: shutdownSchema,
127
+ handler: handleShutdown,
128
+ },
108
129
  ];
109
130
  // Schema map keyed by tool name for src/tool-schemas.ts: TOOL_SCHEMAS spreads
110
131
  // it in place, keeping the satisfies Record<ToolName, LooseToolSchema>
@@ -112,18 +133,21 @@ export const SANDBOX_TOOLS = [
112
133
  export const SANDBOX_TOOL_SCHEMAS = {
113
134
  huaweicloud_sandbox_exec_with_session: execWithSessionSchema,
114
135
  huaweicloud_sandbox_exec_one_shot: execOneShotSchema,
136
+ huaweicloud_sandbox_exec_poll: execPollSchema,
115
137
  huaweicloud_sandbox_close_session: closeSessionSchema,
116
138
  huaweicloud_sandbox_upload_file: uploadFileSchema,
117
139
  huaweicloud_sandbox_upload_project: uploadProjectSchema,
118
140
  huaweicloud_sandbox_deploy_nginx: deployNginxSchema,
119
141
  huaweicloud_sandbox_deploy_check: deployCheckSchema,
120
142
  huaweicloud_sandbox_expose_tunnel: exposeTunnelSchema,
143
+ huaweicloud_sandbox_expose_poll: exposePollSchema,
121
144
  huaweicloud_sandbox_renew_tunnel: renewTunnelSchema,
122
145
  huaweicloud_sandbox_keepalive_watchdog: keepaliveWatchdogSchema,
123
146
  huaweicloud_sandbox_check_user: checkUserSchema,
124
147
  huaweicloud_sandbox_sign_agreement: signAgreementSchema,
125
148
  huaweicloud_sandbox_connect: connectSchema,
126
149
  huaweicloud_sandbox_credentials: credentialsSchema,
150
+ huaweicloud_sandbox_shutdown: shutdownSchema,
127
151
  };
128
152
  // Dispatch map merged into PACK_TOOL_HANDLERS in packs/registry.ts. Typed over
129
153
  // SandboxToolName, so a tool added to SANDBOX_TOOLS without a handler entry
@@ -131,16 +155,19 @@ export const SANDBOX_TOOL_SCHEMAS = {
131
155
  export const SANDBOX_TOOL_HANDLERS = {
132
156
  huaweicloud_sandbox_exec_with_session: handleExecWithSession,
133
157
  huaweicloud_sandbox_exec_one_shot: handleExecOneShot,
158
+ huaweicloud_sandbox_exec_poll: handleHwexecPoll,
134
159
  huaweicloud_sandbox_close_session: handleCloseSession,
135
160
  huaweicloud_sandbox_upload_file: handleUploadFile,
136
161
  huaweicloud_sandbox_upload_project: handleUploadProject,
137
162
  huaweicloud_sandbox_deploy_nginx: handleDeployNginx,
138
163
  huaweicloud_sandbox_deploy_check: handleDeployCheck,
139
164
  huaweicloud_sandbox_expose_tunnel: handleExposeTunnel,
165
+ huaweicloud_sandbox_expose_poll: handleExposePoll,
140
166
  huaweicloud_sandbox_renew_tunnel: handleRenewTunnel,
141
167
  huaweicloud_sandbox_keepalive_watchdog: handleKeepaliveWatchdog,
142
168
  huaweicloud_sandbox_check_user: handleCheckUser,
143
169
  huaweicloud_sandbox_sign_agreement: handleSignAgreement,
144
170
  huaweicloud_sandbox_connect: handleConnect,
145
171
  huaweicloud_sandbox_credentials: handleCredentials,
172
+ huaweicloud_sandbox_shutdown: handleShutdown,
146
173
  };
@@ -0,0 +1,46 @@
1
+ import { hashArgs } from "../../lib/approval-tokens.js";
2
+ import { redactSecrets } from "../../safety-policy.js";
3
+ import { parseSecretRef } from "../../lib/secret-vault/refs.js";
4
+ // The secrets pack's approval registration (PR-3c): secret_delete is
5
+ // ALWAYS gated — it destroys the stored ciphertext with no version
6
+ // history, so a deleted ref is gone until its owner re-stores it. The
7
+ // binding and the confirmation view name the ref, because the ref is the
8
+ // entire consequence of the call. secret_set stays UNREGISTERED: the
9
+ // plaintext arrives from the user (channel=value is the user pasting it,
10
+ // file/envVar are user-designated sources), so the human is present by
11
+ // construction and a second confirmation would confirm nothing new.
12
+ // secret_list is the read-only inventory and stays ungated the same way.
13
+ function deleteBinding(args) {
14
+ return { ref: args.ref };
15
+ }
16
+ export const SECRETS_APPROVAL_SPECS = {
17
+ huaweicloud_secret_delete: {
18
+ domain: 'secrets',
19
+ flavor: 'always',
20
+ tokenSource: 'gate',
21
+ normalizeArgs: deleteBinding,
22
+ // NoDoomedToken (interrogate round 2, fix-in-pass i): vaultDelete
23
+ // refuses an unparseable ref outright, so an approval minted for one is
24
+ // doomed — the retry would hit the same refusal forever. The ref must
25
+ // parse before any mint; the message mirrors vaultDelete's own
26
+ // VAULT_BAD_REF text so the two layers teach identically.
27
+ assertArgsExecutable: (value) => {
28
+ const ref = value.ref;
29
+ const parsed = typeof ref === 'string' ? parseSecretRef(ref) : null;
30
+ if (parsed === null) {
31
+ throw new Error(`"${String(ref)}" is not a valid secret ref (secret://<scope>/<name>, segments [a-z0-9-]).`);
32
+ }
33
+ },
34
+ // The view folds through the shared redaction vocabulary before any
35
+ // field reaches the summary or pin view (the ApprovalSpec contract);
36
+ // the hash binds the raw content.
37
+ summarize: (value) => {
38
+ const safe = redactSecrets(value);
39
+ return {
40
+ summary: `huaweicloud_secret_delete: delete secret ${String(safe.ref)} from the local vault (no version history)`,
41
+ argsHash: hashArgs(value),
42
+ pinView: safe,
43
+ };
44
+ },
45
+ },
46
+ };
@@ -3,6 +3,7 @@ import { z } from 'zod';
3
3
  import { vaultDelete, vaultList, vaultSet } from "../../lib/secret-vault/store.js";
4
4
  import { isCredentialEnvVarName, SECRET_REF_PATTERN } from "../../lib/secret-vault/refs.js";
5
5
  import { isCredentialFilePath } from "../../safety-policy.js";
6
+ import { approvalTokenArg, approvedByUserArg } from "../../lib/tool-schema-parts.js";
6
7
  // The secrets pack: vault writes and inventory through MCP. There is
7
8
  // deliberately NO value-retrieval tool — plaintext never crosses the MCP
8
9
  // face; the Bash-side `secret exec` (child-process env only) is the
@@ -93,6 +94,8 @@ const secretListSchema = z.looseObject({
93
94
  });
94
95
  const secretDeleteSchema = z.looseObject({
95
96
  ref: secretRefField.describe('Vault ref to delete.'),
97
+ approvalToken: approvalTokenArg,
98
+ approvedByUser: approvedByUserArg,
96
99
  });
97
100
  export const SECRETS_TOOLS = [
98
101
  {
@@ -109,7 +112,7 @@ export const SECRETS_TOOLS = [
109
112
  },
110
113
  {
111
114
  name: 'huaweicloud_secret_delete',
112
- description: 'Delete one secret from the local vault by ref. Idempotent: removed=1 when a secret was deleted, removed=0 when the ref was not stored (usually a typo in the ref — check with huaweicloud_secret_list).',
115
+ description: 'Delete one secret from the local vault by ref. Destructive with no version history, so the approval gate mediates every call: in the default token mode a no-token call returns USER_CONFIRMATION_REQUIRED with the approve command line for the user\u2019s own terminal, and under DEVKIT_APPROVAL_MODE=ask the server raises the confirmation itself (form, or an ASK_CONFIRMATION_REQUIRED chat round-trip). Deleting a ref that S1 credentials.json points at breaks those credential reads until the operator re-stores it (the strict vault seam fails closed on the unresolvable ref). Idempotent: removed=1 when a secret was deleted, removed=0 when the ref was not stored (usually a typo in the ref — check with huaweicloud_secret_list).',
113
116
  schema: secretDeleteSchema,
114
117
  handler: handleSecretDelete,
115
118
  },