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
@@ -2,6 +2,7 @@ import { randomBytes } from 'node:crypto';
2
2
 
3
3
  import { execOneShot, execWithSession, getCurrentWorkspaceId } from '../../sandbox/session-manager.ts';
4
4
  import { hdkitCredentials } from '../../lib/hdkit/hdkitservice-api.ts';
5
+ import { versionGateResult } from '../../lib/hdkit/hdkit-gate.ts';
5
6
  import { getCredentials } from '../../lib/hdkit/hwlink-api.ts';
6
7
  import { validateIamCredentials } from '../../auth/credential-validator.ts';
7
8
  import { resolveCredentialsWithRuntime } from '../../auth/credentials.ts';
@@ -62,7 +63,16 @@ export async function handleCredentials(args: ToolArgs = {}, _opts: CallToolOpti
62
63
  hint: 'Credentials were NOT injected into the sandbox. Fix AK/SK first: run "npx huaweicloud-devkit auth init" or correct HW_ACCESS_KEY/HW_SECRET_KEY, then retry.',
63
64
  };
64
65
  }
65
- const credResult = await hdkitCredentials(args.session_id, devStageId, args.enable_sts !== false);
66
+ // 409 版本门禁同样拦截 credentials 出口:结构化折叠(dev e1255a4b),
67
+ // clientVersion/minVersion/remediation 才能穿透 MCP 边界
68
+ let credResult: Record<string, unknown>;
69
+ try {
70
+ credResult = await hdkitCredentials(args.session_id, devStageId, args.enable_sts !== false);
71
+ } catch (error) {
72
+ const gate = versionGateResult(error);
73
+ if (gate) return gate;
74
+ throw error;
75
+ }
66
76
  const sandboxWsIdCred = args.dev_stage_id || getCurrentWorkspaceId();
67
77
  // The DevBridge API Key is a LONG-LIVED account-level credential (no expiry, manual
68
78
  // revocation only) — unlike the temporary STS AK/SK. It is stored in its own file
@@ -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 {
@@ -5,7 +5,9 @@ import {
5
5
  validateTunnelId,
6
6
  } from '../../sandbox/devbridge-tunnel.ts';
7
7
  import { getCurrentWorkspaceId } from '../../sandbox/session-manager.ts';
8
+ import { validateTunnelPort } from '../../sandbox/devbridge-validation.ts';
8
9
  import { poolContextFor } from '../../lib/hdkit/sandbox-pool.ts';
10
+ import { startExposeTask, pollExposeTask } from './expose-task.ts';
9
11
  import {
10
12
  buildKeyringInjectScript,
11
13
  ensureDevbridgeKey,
@@ -35,20 +37,45 @@ export async function handleExposeTunnel(args: ToolArgs = {}, _opts: CallToolOpt
35
37
  const sandboxUser9 = args.username || 'root';
36
38
  const sandboxTimeout9 = args.timeout_ms || SANDBOX_TIMEOUT_MS.expose_tunnel;
37
39
  const exposePoolContext = poolContextFor(sandboxWsId9);
38
- return await exposeTunnel(
39
- sandboxWsId9,
40
- {
41
- port: args.port,
42
- expiryHours: typeof args.expiry_hours === 'number' ? args.expiry_hours : undefined,
43
- keepalive: typeof args.keepalive === 'boolean' ? args.keepalive : undefined,
44
- // DevBridge API Key 自动创建兜底(认证固定 apikey,AK/SK 已移除)
45
- poolType: exposePoolContext?.poolMode || 'ephemeral',
46
- poolContext: exposePoolContext,
47
- keyUpgrade: { ensureDevbridgeKey, recreateDevbridgeKey, buildKeyringInjectScript, listKeysForQuotaHint },
48
- },
49
- sandboxUser9,
50
- sandboxTimeout9,
51
- );
40
+ const exposeArgs = {
41
+ port: validateTunnelPort(args.port),
42
+ expiryHours: typeof args.expiry_hours === 'number' ? args.expiry_hours : undefined,
43
+ keepalive: typeof args.keepalive === 'boolean' ? args.keepalive : undefined,
44
+ cleanupMode: args.cleanup_mode,
45
+ // DevBridge API Key 自动创建兜底(认证固定 apikey,AK/SK 已移除)
46
+ poolType: exposePoolContext?.poolMode || 'ephemeral',
47
+ poolContext: exposePoolContext,
48
+ keyUpgrade: { ensureDevbridgeKey, recreateDevbridgeKey, buildKeyringInjectScript, listKeysForQuotaHint },
49
+ };
50
+ // AX N-SB.1: the chain can outlive the host's request timeout while the
51
+ // server completes it — async starts it detached and the poll tool delivers
52
+ // the URL in-band. The fast parameter checks above stay synchronous, so a
53
+ // bad port is an immediate error, not a deferred task failure.
54
+ if (args.mode === 'async') {
55
+ const { taskId } = startExposeTask(sandboxWsId9, exposeArgs.port, () =>
56
+ exposeTunnel(sandboxWsId9, exposeArgs, sandboxUser9, sandboxTimeout9),
57
+ );
58
+ return {
59
+ started: true,
60
+ mode: 'async',
61
+ taskId,
62
+ hint:
63
+ 'The expose chain is running in the background. Poll huaweicloud_sandbox_expose_poll with this taskId until ' +
64
+ 'state is done — the publicUrl and urlLifetimeHint are delivered there (the task receipt lives 30 minutes in ' +
65
+ 'this MCP server process).',
66
+ };
67
+ }
68
+ return await exposeTunnel(sandboxWsId9, exposeArgs, sandboxUser9, sandboxTimeout9);
69
+ }
70
+
71
+ export async function handleExposePoll(args: ToolArgs = {}, _opts: CallToolOptions = {}) {
72
+ const taskId = args.task_id;
73
+ if (typeof taskId !== 'string' || taskId === '') {
74
+ throw new Error(
75
+ 'task_id is required — pass the taskId returned by huaweicloud_sandbox_expose_tunnel mode:"async".',
76
+ );
77
+ }
78
+ return pollExposeTask(taskId);
52
79
  }
53
80
 
54
81
  export async function handleRenewTunnel(args: ToolArgs = {}, _opts: CallToolOptions = {}) {
@@ -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,7 +14,10 @@ import {
7
14
  workspaceId,
8
15
  username,
9
16
  vendorConfirmed,
17
+ approvalTokenArg,
18
+ approvedByUserArg,
10
19
  } from '../../lib/tool-schema-parts.ts';
20
+ import { EXPOSE_TASK_ID_PATTERN } from './expose-task.ts';
11
21
 
12
22
  // The sandbox pack's zod schema family, extracted from tools.ts in the
13
23
  // within-pack split for the jscpd complex-file bar. tools.ts stays the stable
@@ -22,6 +32,16 @@ import {
22
32
  export const SANDBOX_TIMEOUT_MS = {
23
33
  exec_with_session: 120000,
24
34
  exec_one_shot: 120000,
35
+ // The async start's exec budget: the start script itself is fast (claim +
36
+ // spawn + receipt echo); a timeout here folds into the 'uncertain'
37
+ // receipt — the claim may have landed, and the same-task_id retry is
38
+ // structurally safe, so the short bound is honest, not lossy.
39
+ exec_one_shot_async: 30000,
40
+ // The poll's exec budget floor: the bounded wait loop (wait_ms, capped at
41
+ // 60000) plus the field round-trips must sit inside the timeout — the
42
+ // handler folds wait_ms + 15000 headroom via resolveHwexecPollTimeoutMs
43
+ // (the devbridge-expose-flow A2 doctrine), never below this floor.
44
+ exec_poll: 30000,
25
45
  upload_file: 120000,
26
46
  upload_project: 120000,
27
47
  deploy_nginx: 60000,
@@ -30,10 +50,11 @@ export const SANDBOX_TIMEOUT_MS = {
30
50
  // of dying as a ws-exec timeout (the pre-probing 30s default did not).
31
51
  deploy_check: 60000,
32
52
  // 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).
53
+ // (up to 9s URL-extraction retries + 4 × 10s probes + 3 × 5s backoff) — the
54
+ // headroom exists for the slow-gateway days the probe loop exists for, and
55
+ // a timeout still folds into the structured unreachable envelope (never a
56
+ // raw ws error). The selective pre-clean execs run outside this budget,
57
+ // each with its own bounded one-shot (devbridge-cleanup.ts).
37
58
  expose_tunnel: 90000,
38
59
  renew_tunnel: 60000,
39
60
  keepalive_watchdog: 60000,
@@ -46,15 +67,54 @@ export const execWithSessionSchema = z.looseObject({
46
67
  timeout_ms: numericArg
47
68
  .optional()
48
69
  .describe(`Execution timeout in milliseconds (default: ${SANDBOX_TIMEOUT_MS.exec_with_session})`),
70
+ approvalToken: approvalTokenArg,
71
+ approvedByUser: approvedByUserArg,
49
72
  });
50
73
 
51
74
  export const execOneShotSchema = z.looseObject({
52
75
  command: z.string().describe('The shell command to execute on the remote workspace'),
76
+ mode: z
77
+ .enum(['sync', 'async'])
78
+ .optional()
79
+ .describe(
80
+ '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.',
81
+ ),
82
+ task_id: z
83
+ .string()
84
+ .optional()
85
+ .describe(
86
+ `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.`,
87
+ ),
88
+ workspace_id: workspaceId,
89
+ username,
90
+ timeout_ms: numericArg
91
+ .optional()
92
+ .describe(
93
+ `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)`,
94
+ ),
95
+ approvalToken: approvalTokenArg,
96
+ approvedByUser: approvedByUserArg,
97
+ });
98
+
99
+ export const execPollSchema = z.looseObject({
100
+ task_id: z
101
+ .string()
102
+ .describe(`The task id from huaweicloud_sandbox_exec_one_shot async mode, ${HWEXEC_TASK_ID_PATTERN.source}.`),
53
103
  workspace_id: workspaceId,
54
104
  username,
105
+ wait_ms: numericArg
106
+ .optional()
107
+ .describe(
108
+ `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.`,
109
+ ),
110
+ tail_bytes: numericArg
111
+ .optional()
112
+ .describe(`Log tail size in bytes, 1-${HWEXEC_TAIL_BYTES_MAX} (default: ${HWEXEC_TAIL_BYTES_DEFAULT}).`),
55
113
  timeout_ms: numericArg
56
114
  .optional()
57
- .describe(`Execution timeout in milliseconds (default: ${SANDBOX_TIMEOUT_MS.exec_one_shot})`),
115
+ .describe(
116
+ `Execution timeout in milliseconds (default: ${SANDBOX_TIMEOUT_MS.exec_poll}; auto-raised to wait_ms + ${HWEXEC_POLL_HEADROOM_MS} headroom, never below the default)`,
117
+ ),
58
118
  });
59
119
 
60
120
  export const closeSessionSchema = z.looseObject({
@@ -164,11 +224,38 @@ export const exposeTunnelSchema = z.looseObject({
164
224
  .describe(
165
225
  'Enroll the tunnel into the keepalive watchdog (default true — pass false to opt out). Returns keepalive.enrolled/tunnelCount/watchdogPid.',
166
226
  ),
227
+ cleanup_mode: z
228
+ .enum(['stale', 'all', 'none'])
229
+ .optional()
230
+ .describe(
231
+ "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).",
232
+ ),
233
+ mode: z
234
+ .enum(['sync', 'async'])
235
+ .optional()
236
+ .describe(
237
+ 'sync (default): run the whole expose chain and return its result. async: start the chain in the background and return ' +
238
+ '{started:true, taskId, hint} immediately — use it on MCP hosts whose per-request timeout is shorter than the expose ' +
239
+ 'chain (auth + selective cleanup + up to four ~63s expose attempts + re-verify + keepalive enrollment), then poll ' +
240
+ 'huaweicloud_sandbox_expose_poll with taskId. The task receipt lives in this MCP server process (30 min).',
241
+ ),
167
242
  workspace_id: workspaceId,
168
243
  username,
169
244
  timeout_ms: numericArg
170
245
  .optional()
171
246
  .describe(`Execution timeout in milliseconds (default: ${SANDBOX_TIMEOUT_MS.expose_tunnel})`),
247
+ approvalToken: approvalTokenArg,
248
+ approvedByUser: approvedByUserArg,
249
+ });
250
+
251
+ export const exposePollSchema = z.looseObject({
252
+ task_id: z
253
+ .string()
254
+ .regex(
255
+ EXPOSE_TASK_ID_PATTERN,
256
+ 'task_id must be the exp-<uuid> from huaweicloud_sandbox_expose_tunnel mode:"async".',
257
+ )
258
+ .describe('The taskId returned by huaweicloud_sandbox_expose_tunnel with mode:"async".'),
172
259
  });
173
260
 
174
261
  export const renewTunnelSchema = z.looseObject({
@@ -187,6 +274,8 @@ export const renewTunnelSchema = z.looseObject({
187
274
  timeout_ms: numericArg
188
275
  .optional()
189
276
  .describe(`Execution timeout in milliseconds (default: ${SANDBOX_TIMEOUT_MS.renew_tunnel})`),
277
+ approvalToken: approvalTokenArg,
278
+ approvedByUser: approvedByUserArg,
190
279
  });
191
280
 
192
281
  export const keepaliveWatchdogSchema = z.looseObject({
@@ -208,9 +297,14 @@ export const keepaliveWatchdogSchema = z.looseObject({
208
297
  timeout_ms: numericArg
209
298
  .optional()
210
299
  .describe(`Execution timeout in milliseconds (default: ${SANDBOX_TIMEOUT_MS.keepalive_watchdog})`),
300
+ approvalToken: approvalTokenArg,
301
+ approvedByUser: approvedByUserArg,
211
302
  });
212
303
 
213
- export const signAgreementSchema = z.looseObject({});
304
+ export const signAgreementSchema = z.looseObject({
305
+ approvalToken: approvalTokenArg,
306
+ approvedByUser: approvedByUserArg,
307
+ });
214
308
 
215
309
  export const connectSchema = z.looseObject({
216
310
  vendorConfirmed,
@@ -222,12 +316,13 @@ export const connectSchema = z.looseObject({
222
316
  .enum(['ephemeral', 'persistent'])
223
317
  .optional()
224
318
  .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.',
319
+ '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
320
  ),
227
- template_id: z.string().optional().describe('Template ID; overrides server default (only for new sandbox)'),
228
321
  flavor_id: z.string().optional().describe('Flavor ID; overrides server default (only for new sandbox)'),
229
322
  env: looseObject.optional().describe('Environment variables to set in the sandbox (only for new sandbox)'),
230
323
  git: gitConfig.optional().describe('Git repo config (only for new sandbox)'),
324
+ approvalToken: approvalTokenArg,
325
+ approvedByUser: approvedByUserArg,
231
326
  });
232
327
 
233
328
  export const credentialsSchema = z.looseObject({
@@ -246,4 +341,21 @@ export const credentialsSchema = z.looseObject({
246
341
  .describe(
247
342
  '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
343
  ),
344
+ approvalToken: approvalTokenArg,
345
+ approvedByUser: approvedByUserArg,
346
+ });
347
+
348
+ // 关机(dev 5d89c880):不可逆写类工具,走审批门(always 面);token 与
349
+ // attestation 与其余门面工具同型——schema 可选,门是执行者,首个无 token
350
+ // 调用必须能到达门以领取 mint 信封。
351
+ export const shutdownSchema = z.looseObject({
352
+ session_id: z.string().optional().describe('Session ID from huaweicloud_sandbox_connect (optional)'),
353
+ dev_stage_id: z.string().optional().describe('DevStation environment ID (alternative to session_id)'),
354
+ workspace_id: z
355
+ .string()
356
+ .optional()
357
+ .describe('Workspace ID; defaults to the current workspace (an alternative to session_id/dev_stage_id)'),
358
+ username,
359
+ approvalToken: approvalTokenArg,
360
+ approvedByUser: approvedByUserArg,
249
361
  });