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

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 (72) hide show
  1. package/README.md +1 -1
  2. package/integrations/opencode/commands/huaweicloud-doctor.md +1 -1
  3. package/integrations/opencode/hooks/safety-gate.js +235 -0
  4. package/package.json +1 -1
  5. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +3 -16
  6. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +3 -16
  7. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +3 -16
  8. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +3 -16
  9. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +3 -16
  10. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +29 -4
  11. package/plugins/huaweicloud-core/dist/agents/opencode.js +55 -14
  12. package/plugins/huaweicloud-core/dist/approval-gate.js +23 -5
  13. package/plugins/huaweicloud-core/dist/doctor-payload.js +29 -0
  14. package/plugins/huaweicloud-core/dist/explain-error.js +9 -1
  15. package/plugins/huaweicloud-core/dist/hcloud-plan.js +6 -1
  16. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +18 -9
  17. package/plugins/huaweicloud-core/dist/lib/opencode-permission-seam.js +51 -20
  18. package/plugins/huaweicloud-core/dist/mcp-server.js +520 -290
  19. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  20. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +5 -1
  21. package/plugins/huaweicloud-core/dist/packs/registry.js +1 -0
  22. package/plugins/huaweicloud-core/dist/packs/sandbox/expose-task.js +71 -0
  23. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +25 -1
  24. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +28 -3
  25. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +14 -0
  26. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +11 -3
  27. package/plugins/huaweicloud-core/dist/payload-placement.js +8 -0
  28. package/plugins/huaweicloud-core/dist/risk-rule-engine.js +20 -4
  29. package/plugins/huaweicloud-core/dist/safety/classify-hcloud.js +6 -6
  30. package/plugins/huaweicloud-core/dist/safety/classify-text.js +10 -0
  31. package/plugins/huaweicloud-core/dist/safety/policy.js +12 -0
  32. package/plugins/huaweicloud-core/dist/safety/protected-payload.js +93 -0
  33. package/plugins/huaweicloud-core/dist/safety/redact.js +21 -3
  34. package/plugins/huaweicloud-core/dist/safety/risk-merge.js +24 -4
  35. package/plugins/huaweicloud-core/dist/safety-integrity.js +122 -0
  36. package/plugins/huaweicloud-core/dist/sandbox/devbridge-cleanup.js +1 -1
  37. package/plugins/huaweicloud-core/dist/setup-cli.js +8 -1
  38. package/plugins/huaweicloud-core/dist/tool-definitions.js +4 -0
  39. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +44 -1
  40. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +75 -2
  41. package/plugins/huaweicloud-core/openclaw.plugin.json +2 -2
  42. package/plugins/huaweicloud-core/safety/policy.json +5 -0
  43. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +1 -1
  44. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +42 -39
  45. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +1 -1
  46. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +33 -3
  47. package/plugins/huaweicloud-core/src/agents/opencode.ts +66 -15
  48. package/plugins/huaweicloud-core/src/approval-gate.ts +29 -4
  49. package/plugins/huaweicloud-core/src/doctor-payload.ts +40 -2
  50. package/plugins/huaweicloud-core/src/explain-error.ts +9 -1
  51. package/plugins/huaweicloud-core/src/hcloud-plan.ts +6 -1
  52. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +32 -1
  53. package/plugins/huaweicloud-core/src/lib/opencode-permission-seam.ts +60 -19
  54. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +7 -1
  55. package/plugins/huaweicloud-core/src/packs/registry.ts +1 -0
  56. package/plugins/huaweicloud-core/src/packs/sandbox/expose-task.ts +105 -0
  57. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +28 -1
  58. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +41 -15
  59. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +20 -0
  60. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +12 -2
  61. package/plugins/huaweicloud-core/src/payload-placement.ts +8 -0
  62. package/plugins/huaweicloud-core/src/risk-rule-engine.ts +20 -7
  63. package/plugins/huaweicloud-core/src/safety/classify-hcloud.ts +28 -16
  64. package/plugins/huaweicloud-core/src/safety/classify-text.ts +10 -0
  65. package/plugins/huaweicloud-core/src/safety/policy.ts +13 -0
  66. package/plugins/huaweicloud-core/src/safety/protected-payload.ts +97 -0
  67. package/plugins/huaweicloud-core/src/safety/redact.ts +24 -6
  68. package/plugins/huaweicloud-core/src/safety/risk-merge.ts +26 -5
  69. package/plugins/huaweicloud-core/src/safety-integrity.ts +132 -0
  70. package/plugins/huaweicloud-core/src/sandbox/devbridge-cleanup.ts +7 -5
  71. package/plugins/huaweicloud-core/src/setup-cli.ts +8 -0
  72. package/plugins/huaweicloud-core/src/tool-definitions.ts +4 -0
@@ -12,6 +12,7 @@ import { join } from 'node:path';
12
12
  import type { DoctorReporter } from './doctor-report.ts';
13
13
  import { nativeFreshnessChecks } from './doctor-native.ts';
14
14
  import { mcpServerInstalled, serverSkillDirNames } from './install-payload.ts';
15
+ import { verifyIntegrity } from './safety-integrity.ts';
15
16
 
16
17
  // The structural slice of a PAYLOAD_TARGETS row the doctor sections consume.
17
18
  export interface PayloadDoctorRow {
@@ -41,11 +42,14 @@ export interface PayloadTriple {
41
42
  }
42
43
 
43
44
  // One row's doctor section: the pure triple probes (run early — their
44
- // results print in the shell's opening checks) and the deferred
45
- // native-freshness checks (run late, after the stale-copy scan).
45
+ // results print in the shell's opening checks), the deferred
46
+ // native-freshness checks (run late, after the stale-copy scan), and the
47
+ // integrity receipt comparison (the integrity unit's layer 3 — run beside
48
+ // the triple, where the payload health prints).
46
49
  export interface PayloadDoctorSection {
47
50
  triple: PayloadTriple;
48
51
  nativeFreshness(ctx: DoctorReporter): void;
52
+ integrity(ctx: DoctorReporter): void;
49
53
  }
50
54
 
51
55
  // What a PAYLOAD_TARGETS row binds as its doctor section.
@@ -63,6 +67,12 @@ export function skillsTreeMatches(dir: string, expectedSkills: readonly string[]
63
67
 
64
68
  // The generic per-row section: the triple over the row's plugin dir plus the
65
69
  // receipt-gated native-freshness checks over the row's native dirs.
70
+ // The generic per-row section: the triple over the row's plugin dir plus
71
+ // the receipt-gated native-freshness checks over the row's native dirs,
72
+ // plus the deployed-classifier integrity comparison (layer 3). Rows
73
+ // without a deployed safety payload stay silent; a payload without a
74
+ // receipt (a pre-integrity install) WARNs — backward compatibility, never
75
+ // a false red; drift FAILs with the reinstall remediation.
66
76
  export function payloadDoctorSection(row: PayloadDoctorRow, shared: DoctorSharedState): PayloadDoctorSection {
67
77
  const dir = row.dir();
68
78
  return {
@@ -73,5 +83,33 @@ export function payloadDoctorSection(row: PayloadDoctorRow, shared: DoctorShared
73
83
  skillsTree: skillsTreeMatches(dir, shared.expectedSkills),
74
84
  },
75
85
  nativeFreshness: (ctx) => nativeFreshnessChecks(ctx, row, shared.corePack),
86
+ integrity: (ctx) => payloadIntegrityCheck(ctx, row.label, dir),
76
87
  };
77
88
  }
89
+
90
+ export function payloadIntegrityCheck(ctx: DoctorReporter, label: string, dir: string): void {
91
+ const status = verifyIntegrity(dir);
92
+ if (status.status === 'no-payload') return;
93
+ if (status.status === 'match') {
94
+ ctx.pass(`Safety policy integrity (${label})`);
95
+ return;
96
+ }
97
+ if (status.status === 'no-receipt') {
98
+ ctx.warn(
99
+ `Safety policy integrity (${label}) — integrity receipt missing (payload predates integrity tracking); re-run: npx huaweicloud-devkit install`,
100
+ );
101
+ return;
102
+ }
103
+ const all = [...status.drifted, ...status.missing, ...status.unrecorded];
104
+ const parts = [
105
+ status.drifted.length > 0 ? `${status.drifted.length} changed` : '',
106
+ status.missing.length > 0 ? `${status.missing.length} missing` : '',
107
+ status.unrecorded.length > 0 ? `${status.unrecorded.length} unrecorded` : '',
108
+ ].filter(Boolean);
109
+ const names = `${all.slice(0, 3).join(', ')}${all.length > 3 ? ', …' : ''}`;
110
+ ctx.check(
111
+ `Safety policy integrity (${label})`,
112
+ false,
113
+ `${parts.join(', ')} classifier file(s) (${names}) — Run: npx huaweicloud-devkit install`,
114
+ );
115
+ }
@@ -237,8 +237,16 @@ export function explainError({
237
237
  return !arr.slice(0, i).some((prev) => prev.substring(0, 50).toLowerCase() === s.substring(0, 50).toLowerCase());
238
238
  });
239
239
 
240
+ // The response names the service the error was RESOLVED to, not a raw
241
+ // `unknown`/wrong pasted name: `code`-only calls and a pasted service whose
242
+ // own pattern table is empty derive their key from the code prefix (the
243
+ // suggestions already walked that table). A valid explicit service keeps
244
+ // its exact spelling — the pre-existing contract and its #935 regression
245
+ // pin (AX report D-05).
246
+ const providedKnown = Boolean(service) && svc !== 'unknown';
247
+ const responseService = !providedKnown || !hwErrorPatterns[patternKey] ? effectiveKey : service;
240
248
  return {
241
- service,
249
+ service: responseService,
242
250
  errorCode: resolvedCode,
243
251
  requestId,
244
252
  suggestions: uniqueSuggestions,
@@ -408,6 +408,11 @@ export function planHcloudCommand(args: unknown, options: HcloudPlanOptions = {}
408
408
  ...(approvalToken !== undefined ? { command: `npx huaweicloud-devkit approve ${approvalToken}` } : {}),
409
409
  }
410
410
  : { needed: false },
411
- safeToRun: effectiveClassification.decision === 'allow',
411
+ // "Safe to run NOW": a caller-supplied allowWrites:true only unlocks the
412
+ // classification — the strict view still demands the user's confirmation
413
+ // (the approval token/form), so a plan showing decision:"allow" must not
414
+ // also read as runnable while userConfirmation.needed is true (AX D-02
415
+ // display-layer alignment).
416
+ safeToRun: effectiveClassification.decision === 'allow' && !needsConfirmation,
412
417
  };
413
418
  }
@@ -432,8 +432,24 @@ export async function hdkitConnect(options: Record<string, unknown> = {}): Promi
432
432
  * 重试表经 HW_SANDBOX_CONNECT_RETRY_DELAYS_MS 针脚可覆写(v2 扩展)。
433
433
  * 成功路径回显 connect_retries(v2 扩展;dev 仅在错误路径带尝试次数)。
434
434
  */
435
- export async function hdkitConnectWithRetry(options: Record<string, unknown> = {}): Promise<Record<string, unknown>> {
435
+ export interface HdkitConnectRetryOptions {
436
+ // MCP tool faces must answer inside the host's request budget. A backoff
437
+ // longer than maxInlineDelayMs returns a `pending` receipt instead of
438
+ // sleeping: the server may already have created the instance, and the
439
+ // agent's next huaweicloud_sandbox_connect call re-attempts the same
440
+ // request and reuses it. inlineRetry:false disables the inline ladder
441
+ // outright (both knobs default to the dev behavior: inline, unbounded).
442
+ inlineRetry?: boolean;
443
+ maxInlineDelayMs?: number;
444
+ }
445
+
446
+ export async function hdkitConnectWithRetry(
447
+ options: Record<string, unknown> = {},
448
+ retryOptions: HdkitConnectRetryOptions = {},
449
+ ): Promise<Record<string, unknown>> {
436
450
  const delays = connectRetryDelaysMs();
451
+ const inlineRetry = retryOptions.inlineRetry !== false;
452
+ const maxInlineDelayMs = retryOptions.maxInlineDelayMs ?? Number.POSITIVE_INFINITY;
437
453
  let retries = 0;
438
454
  for (;;) {
439
455
  try {
@@ -454,6 +470,21 @@ export async function hdkitConnectWithRetry(options: Record<string, unknown> = {
454
470
  if (transient) throw decorateExhaustedConnect(error, retries);
455
471
  throw error;
456
472
  }
473
+ if (!inlineRetry || (delays[retries] ?? Number.POSITIVE_INFINITY) > maxInlineDelayMs) {
474
+ // AX N-SB.2: never hold the tool call through a backoff longer than
475
+ // the host's request budget — a host request timeout would abandon
476
+ // the call while the server completed the create. The retry moves to
477
+ // the next tool call (same params). Short test/operator backoffs keep
478
+ // the inline ladder.
479
+ const pendingCode = asString(safeReadField(error, 'code'));
480
+ return {
481
+ pending: true,
482
+ connectRetries: retries,
483
+ retryAfterMs: delays[retries] ?? delays[0] ?? 0,
484
+ ...(pendingCode ? { code: pendingCode } : {}),
485
+ message: safeMessageText(error),
486
+ };
487
+ }
457
488
  await new Promise((resolve) => setTimeout(resolve, delays[retries]));
458
489
  retries += 1;
459
490
  }
@@ -13,6 +13,17 @@
13
13
  // Mitigations: the tree is regenerated by every install/update
14
14
  // (copyServerPayload), and the PreToolUse hook still denies hcloud writes.
15
15
  //
16
+ // The payload root is the seam's EDIT-ONLY class (the interrogate round's
17
+ // classifier-rewrite finding): the deployed dist/safety-policy.js is what
18
+ // the in-process evaluate gate imports at runtime, so an edit-tool rewrite
19
+ // disarms the gate mid-session. The edit deny closes that tool vector; the
20
+ // external_directory allow is deliberately NOT extended to the payload —
21
+ // an allowed external directory inherits workspace defaults where bash is
22
+ // allowed, and the payload must not become a no-prompt bash write target.
23
+ // The bash-face residual is disclosed in the approvals reference and the
24
+ // changelog (the architectural fix direction is install-time integrity
25
+ // verification, out of scope here).
26
+ //
16
27
  // Ownership rules (no receipt, by judgment recorded in the changelog): two
17
28
  // keys over devkit-only globs — any rule on these globs is devkit-domain by
18
29
  // construction, so add-only-if-absent (a pre-existing rule with ANY value is
@@ -55,6 +66,14 @@ export function skillTreePermissionGlobs(
55
66
  return globs;
56
67
  }
57
68
 
69
+ // The edit-only class: the payload root (dist/, safety/, node_modules —
70
+ // everything the deployed gate imports or executes). Edit/write/patch tools
71
+ // deny there, but the external_directory allow is deliberately NOT
72
+ // extended: the payload must not become a no-prompt bash write target.
73
+ export function payloadEditDenyGlobs(pluginDir: string): string[] {
74
+ return [`${pluginDir.replace(/\\/g, '/')}/**`];
75
+ }
76
+
58
77
  export interface SeamApplyResult {
59
78
  changed: boolean;
60
79
  // Section names whose shape was not an object ('permission' for the
@@ -63,14 +82,39 @@ export interface SeamApplyResult {
63
82
  skipped: string[];
64
83
  }
65
84
 
85
+ // The per-section resolver shared by apply and remove: the section record
86
+ // (fresh when absent, so the caller's writes land and are assigned back),
87
+ // or null when the user owns a scalar shape there — one ownership check in
88
+ // one place for both directions of the seam.
89
+ function sectionFor(permission: Record<string, unknown>, key: string): Record<string, unknown> | null {
90
+ if (permission[key] !== undefined && !isRecord(permission[key])) return null;
91
+ return asRecord(permission[key]);
92
+ }
93
+
94
+ // The two-class section table shared by apply and remove: the external
95
+ // allow covers the skills globs only, the edit deny covers them plus the
96
+ // edit-only payload class.
97
+ function seamSections(
98
+ globs: readonly string[],
99
+ editOnlyGlobs: readonly string[],
100
+ ): Array<readonly [key: string, value: 'allow' | 'deny', list: readonly string[]]> {
101
+ return [
102
+ ['external_directory', 'allow', globs],
103
+ ['edit', 'deny', [...globs, ...editOnlyGlobs]],
104
+ ];
105
+ }
106
+
66
107
  // Mutates config in place. Add-only-if-absent per section: a glob already
67
108
  // present with ANY value keeps the user's rule; only missing globs get the
68
109
  // devkit value. Appended keys win under OpenCode's last-matching-rule-wins
69
110
  // evaluation — deliberate, so the devkit's specific allow beats an earlier
70
- // broader user pattern (e.g. "~/.config/opencode/**": "ask").
111
+ // broader user pattern (e.g. "~/.config/opencode/**": "ask"). The edit-only
112
+ // class writes the edit section alone; the external allow deliberately
113
+ // never covers it (see the module header).
71
114
  export function applySkillTreePermissionSeam(
72
115
  config: Record<string, unknown>,
73
116
  globs: readonly string[],
117
+ editOnlyGlobs: readonly string[] = [],
74
118
  ): SeamApplyResult {
75
119
  if (config.permission !== undefined && !isRecord(config.permission)) {
76
120
  // The whole-config string form ("permission": "allow") is the user's
@@ -81,17 +125,13 @@ export function applySkillTreePermissionSeam(
81
125
  const permission = asRecord(config.permission);
82
126
  const skipped: string[] = [];
83
127
  let changed = false;
84
- const sections: Array<readonly [key: string, value: 'allow' | 'deny']> = [
85
- ['external_directory', 'allow'],
86
- ['edit', 'deny'],
87
- ];
88
- for (const [key, value] of sections) {
89
- if (permission[key] !== undefined && !isRecord(permission[key])) {
128
+ for (const [key, value, list] of seamSections(globs, editOnlyGlobs)) {
129
+ const section = sectionFor(permission, key);
130
+ if (section === null) {
90
131
  skipped.push(key);
91
132
  continue;
92
133
  }
93
- const section = asRecord(permission[key]);
94
- const missing = globs.filter((glob) => !Object.hasOwn(section, glob));
134
+ const missing = list.filter((glob) => !Object.hasOwn(section, glob));
95
135
  if (missing.length === 0) continue;
96
136
  for (const glob of missing) section[glob] = value;
97
137
  permission[key] = section;
@@ -104,20 +144,21 @@ export function applySkillTreePermissionSeam(
104
144
  // Mutates config in place. Value-exact deletion only — a user-modified value
105
145
  // on a devkit glob survives. Sections emptied by OUR deletions are pruned
106
146
  // (a pre-existing empty section is left untouched), and the permission
107
- // object itself is pruned only when the seam emptied it.
108
- export function removeSkillTreePermissionSeam(config: Record<string, unknown>, globs: readonly string[]): boolean {
147
+ // object itself is pruned only when the seam emptied it. The edit-only
148
+ // class is removed from the edit section under the same value-exact rule.
149
+ export function removeSkillTreePermissionSeam(
150
+ config: Record<string, unknown>,
151
+ globs: readonly string[],
152
+ editOnlyGlobs: readonly string[] = [],
153
+ ): boolean {
109
154
  if (!isRecord(config.permission)) return false;
110
155
  const permission = asRecord(config.permission);
111
156
  let changed = false;
112
- const sections: Array<readonly [key: string, value: 'allow' | 'deny']> = [
113
- ['external_directory', 'allow'],
114
- ['edit', 'deny'],
115
- ];
116
- for (const [key, value] of sections) {
117
- if (!isRecord(permission[key])) continue;
118
- const section = asRecord(permission[key]);
157
+ for (const [key, value, list] of seamSections(globs, editOnlyGlobs)) {
158
+ const section = sectionFor(permission, key);
159
+ if (section === null) continue;
119
160
  let removedHere = false;
120
- for (const glob of globs) {
161
+ for (const glob of list) {
121
162
  if (section[glob] === value) {
122
163
  delete section[glob];
123
164
  removedHere = true;
@@ -158,6 +158,12 @@ async function handleAuthSwitch(args: ToolArgs = {}, opts: CallToolOptions = {})
158
158
  return persisted;
159
159
  }
160
160
 
161
+ // F-APV-1: the confirm-token rejection spells its way out (exported for the
162
+ // test that pins the envelope). Confirm tokens share the approval tokens'
163
+ // process-scoped lifetime: a restart drops every pending confirm.
164
+ export const AUTH_CONFIRM_TOKEN_NOT_FOUND_NEXT_STEP =
165
+ 'This confirmation token was never minted in this process — mistyped, or dropped by a server restart (confirm tokens are process-scoped and never persisted). Re-run the huaweicloud_auth_switch action that returned needs_confirmation to mint a fresh token, then call huaweicloud_auth_confirm with it.';
166
+
161
167
  async function handleAuthConfirm(args: ToolArgs = {}, _opts: CallToolOptions = {}) {
162
168
  // D4-24 precise JSON contract (#745): a missing or already-consumed confirm
163
169
  // token returns a structured result instead of throwing a generic Error
@@ -173,7 +179,7 @@ async function handleAuthConfirm(args: ToolArgs = {}, _opts: CallToolOptions = {
173
179
  if (token && consumedConfirms.has(token)) {
174
180
  return { status: 'ok', outcome: 'already_processed' };
175
181
  }
176
- return { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND' };
182
+ return { status: 'rejected', code: 'CONFIRM_TOKEN_NOT_FOUND', nextStep: AUTH_CONFIRM_TOKEN_NOT_FOUND_NEXT_STEP };
177
183
  }
178
184
  if (args.decision === 's1') {
179
185
  pendingConfirms.delete(token);
@@ -74,6 +74,7 @@ export const PACK_OF = {
74
74
  huaweicloud_sandbox_deploy_nginx: 'sandbox',
75
75
  huaweicloud_sandbox_deploy_check: 'sandbox',
76
76
  huaweicloud_sandbox_expose_tunnel: 'sandbox',
77
+ huaweicloud_sandbox_expose_poll: 'sandbox',
77
78
  huaweicloud_sandbox_renew_tunnel: 'sandbox',
78
79
  huaweicloud_sandbox_keepalive_watchdog: 'sandbox',
79
80
  huaweicloud_sandbox_check_user: 'sandbox',
@@ -0,0 +1,105 @@
1
+ import { randomUUID } from 'node:crypto';
2
+
3
+ import type { ExposeTunnelResult } from '../../sandbox/devbridge-expose.ts';
4
+
5
+ // The async expose-task registry (AX N-SB.1). An expose chain can outlive
6
+ // the host's MCP request timeout (auth gate + selective cleanups + up to
7
+ // four ~63s expose execs + the persistence re-verify + keepalive enrollment)
8
+ // while the server completes it — the synchronous tool then loses the
9
+ // publicUrl. An async start returns immediately and the poll tool delivers
10
+ // the finished result in-band.
11
+ //
12
+ // The registry is process-scoped (the stdio MCP server owns one). A restart
13
+ // loses the receipt while the tunnel may already live; the unknown hint
14
+ // therefore teaches recovery (re-expose / deploy_check) and never fabricates
15
+ // a URL. Entries are swept after the TTL so a long session cannot grow the
16
+ // map unbounded.
17
+
18
+ export const EXPOSE_TASK_ID_PATTERN = /^exp-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
19
+
20
+ const EXPOSE_TASK_TTL_MS = 30 * 60_000;
21
+
22
+ export interface ExposeTaskSnapshot {
23
+ startedAt: number;
24
+ workspaceId: string;
25
+ port: number;
26
+ }
27
+
28
+ type ExposeTask =
29
+ | (ExposeTaskSnapshot & { state: 'running' })
30
+ | (ExposeTaskSnapshot & { state: 'done'; result: ExposeTunnelResult })
31
+ | (ExposeTaskSnapshot & { state: 'failed'; error: string });
32
+
33
+ const tasks = new Map<string, ExposeTask>();
34
+
35
+ function sweep(now: number): void {
36
+ for (const [taskId, task] of tasks) {
37
+ if (now - task.startedAt > EXPOSE_TASK_TTL_MS) tasks.delete(taskId);
38
+ }
39
+ }
40
+
41
+ export function startExposeTask(
42
+ workspaceId: string,
43
+ port: number,
44
+ run: () => Promise<ExposeTunnelResult>,
45
+ ): { taskId: string; startedAt: number } {
46
+ const now = Date.now();
47
+ sweep(now);
48
+ const taskId = `exp-${randomUUID()}`;
49
+ const snapshot: ExposeTaskSnapshot = { startedAt: now, workspaceId, port };
50
+ tasks.set(taskId, { ...snapshot, state: 'running' });
51
+ // The chain runs detached from the tool call: the client may time out or
52
+ // cancel the start request, but the server-side work (and the tunnel it
53
+ // creates) must continue. Both settle paths are recorded, so the promise
54
+ // is never an unhandled rejection.
55
+ void run().then(
56
+ (result) => {
57
+ tasks.set(taskId, { ...snapshot, state: 'done', result });
58
+ },
59
+ (error: unknown) => {
60
+ tasks.set(taskId, {
61
+ ...snapshot,
62
+ state: 'failed',
63
+ error: error instanceof Error ? error.message : String(error),
64
+ });
65
+ },
66
+ );
67
+ return { taskId, startedAt: now };
68
+ }
69
+
70
+ export type ExposePollResult =
71
+ | { state: 'running'; elapsedMs: number; hint: string }
72
+ | { state: 'done'; result: ExposeTunnelResult }
73
+ | { state: 'failed'; error: string }
74
+ | { state: 'unknown'; hint: string };
75
+
76
+ export function pollExposeTask(taskId: string): ExposePollResult {
77
+ const now = Date.now();
78
+ sweep(now);
79
+ const task = tasks.get(taskId);
80
+ if (!task) {
81
+ return {
82
+ state: 'unknown',
83
+ hint:
84
+ 'No task with this id is known to this MCP server process (it never started here, the session restarted, or the ' +
85
+ '30-minute receipt expired). The tunnel may already exist: run huaweicloud_sandbox_deploy_check to read it, or ' +
86
+ 're-run huaweicloud_sandbox_expose_tunnel (same port) — do not assume success without a URL.',
87
+ };
88
+ }
89
+ if (task.state === 'running') {
90
+ return {
91
+ state: 'running',
92
+ elapsedMs: now - task.startedAt,
93
+ hint: 'The expose chain is running in the background (auth, cleanup, host start, health check, keepalive). Call again.',
94
+ };
95
+ }
96
+ if (task.state === 'done') {
97
+ return { state: 'done', result: task.result };
98
+ }
99
+ return { state: 'failed', error: task.error };
100
+ }
101
+
102
+ // Test seam: isolate a process-global registry between cases.
103
+ export function _resetExposeTasksForTests(): void {
104
+ tasks.clear();
105
+ }
@@ -72,7 +72,12 @@ export async function handleConnect(args: ToolArgs = {}, _opts: CallToolOptions
72
72
  }
73
73
  let connectResult: Record<string, unknown>;
74
74
  try {
75
- connectResult = await hdkitConnectWithRetry(connectArgs);
75
+ // AX N-SB.2: the MCP tool answers inside the host's request budget — a
76
+ // transient gateway timeout returns a pending receipt instead of sleeping
77
+ // through the 30s/45s table (the next call re-attempts and reuses any
78
+ // instance the server already created). Short backoffs (tests/operators)
79
+ // keep the inline ladder.
80
+ connectResult = await hdkitConnectWithRetry(connectArgs, { maxInlineDelayMs: 1000 });
76
81
  } catch (error) {
77
82
  // 业务预期失败(429 三码 / 烧核 / 凭证失效)转结构化返回,remediation 才能穿透 MCP 边界;
78
83
  // 其余错误维持抛出(MCP 层透传 code+message)。
@@ -149,6 +154,28 @@ export async function handleConnect(args: ToolArgs = {}, _opts: CallToolOptions
149
154
  }
150
155
  throw error;
151
156
  }
157
+ if (connectResult?.pending === true) {
158
+ const retryAfterMs =
159
+ typeof connectResult.retryAfterMs === 'number' && Number.isFinite(connectResult.retryAfterMs)
160
+ ? connectResult.retryAfterMs
161
+ : 30000;
162
+ const retryAfter = `${Math.max(1, Math.ceil(retryAfterMs / 1000))}s`;
163
+ return {
164
+ ok: false,
165
+ pending: true,
166
+ retryAfter,
167
+ retryAfterMs,
168
+ ...(typeof connectResult.code === 'string' ? { code: connectResult.code } : {}),
169
+ message:
170
+ typeof connectResult.message === 'string' && connectResult.message
171
+ ? connectResult.message
172
+ : 'the hdkitservice gateway timed out during orchestration.',
173
+ hint:
174
+ `The sandbox instance may already exist on the server. Re-call huaweicloud_sandbox_connect with the SAME ` +
175
+ `parameters after ~${retryAfter} — a created instance is reused. Do not start a second sandbox and do not ` +
176
+ `debug this as a credential failure.`,
177
+ };
178
+ }
152
179
  const rawDevStageId = connectResult?.dev_stage_id || connectResult?.devStageId;
153
180
  const devStageId = typeof rawDevStageId === 'string' ? rawDevStageId : undefined;
154
181
  let announceConnect = true;
@@ -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,21 +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
- 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
- sandboxUser9,
51
- sandboxTimeout9,
52
- );
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);
53
79
  }
54
80
 
55
81
  export async function handleRenewTunnel(args: ToolArgs = {}, _opts: CallToolOptions = {}) {
@@ -17,6 +17,7 @@ import {
17
17
  approvalTokenArg,
18
18
  approvedByUserArg,
19
19
  } from '../../lib/tool-schema-parts.ts';
20
+ import { EXPOSE_TASK_ID_PATTERN } from './expose-task.ts';
20
21
 
21
22
  // The sandbox pack's zod schema family, extracted from tools.ts in the
22
23
  // within-pack split for the jscpd complex-file bar. tools.ts stays the stable
@@ -229,6 +230,15 @@ export const exposeTunnelSchema = z.looseObject({
229
230
  .describe(
230
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).",
231
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
+ ),
232
242
  workspace_id: workspaceId,
233
243
  username,
234
244
  timeout_ms: numericArg
@@ -238,6 +248,16 @@ export const exposeTunnelSchema = z.looseObject({
238
248
  approvedByUser: approvedByUserArg,
239
249
  });
240
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".'),
259
+ });
260
+
241
261
  export const renewTunnelSchema = z.looseObject({
242
262
  tunnel_id: z
243
263
  .string()
@@ -9,6 +9,7 @@ import {
9
9
  deployCheckSchema,
10
10
  checkUserSchema,
11
11
  exposeTunnelSchema,
12
+ exposePollSchema,
12
13
  renewTunnelSchema,
13
14
  keepaliveWatchdogSchema,
14
15
  signAgreementSchema,
@@ -20,7 +21,7 @@ import { handleExecWithSession, handleExecOneShot, handleCloseSession } from './
20
21
  import { handleHwexecPoll } from './handlers-hwexec.ts';
21
22
  import { handleUploadFile, handleUploadProject } from './handlers-upload.ts';
22
23
  import { handleDeployNginx, handleDeployCheck } from './handlers-deploy.ts';
23
- import { handleExposeTunnel, handleRenewTunnel, handleKeepaliveWatchdog } from './handlers-tunnel.ts';
24
+ import { handleExposeTunnel, handleExposePoll, handleRenewTunnel, handleKeepaliveWatchdog } from './handlers-tunnel.ts';
24
25
  import { handleCheckUser, handleSignAgreement, handleConnect, handleShutdown } from './handlers-account.ts';
25
26
  import { handleCredentials } from './handlers-credentials.ts';
26
27
  import type { PackToolDefinition, LooseToolSchema } from '../../lib/pack-types.ts';
@@ -108,6 +109,13 @@ export const SANDBOX_TOOLS = [
108
109
  schema: exposeTunnelSchema,
109
110
  handler: handleExposeTunnel,
110
111
  },
112
+ {
113
+ name: 'huaweicloud_sandbox_expose_poll',
114
+ description:
115
+ '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.',
116
+ schema: exposePollSchema,
117
+ handler: handleExposePoll,
118
+ },
111
119
  {
112
120
  name: 'huaweicloud_sandbox_renew_tunnel',
113
121
  description:
@@ -139,7 +147,7 @@ export const SANDBOX_TOOLS = [
139
147
  {
140
148
  name: 'huaweicloud_sandbox_connect',
141
149
  description:
142
- 'Connect to a sandbox via hdkitservice. One instance per user per pool — reuses the same-pool sandbox if available, otherwise creates a new one. Quota: 1 instance per pool type (a user may hold 1 ephemeral AND 1 persistent simultaneously; same-type requests reuse the existing instance). On quota exhaustion the API returns HTTP 429 with one of three codes: HDKIT_QUOTA_EXCEEDED (retry useless — release or reuse the existing instance; Retry-After 60), HDKIT_TEMPLATE_QUOTA_EXCEEDED (the running instances of this account for this sandbox type are at the limit — shut down or release an instance of the same type and retry; no Retry-After), or HDKIT_CAPACITY_INSUFFICIENT (pool capacity; retry later / off-peak; Retry-After 60). Gateway 502/504 timeouts during orchestration are retried automatically (30s/45s backoff) — the server may already have created the instance, so a retry reuses it. An outdated plugin version is rejected by the 409 HDKIT_VERSION_TOO_OLD version gate, surfaced by the sandbox tools (connect/check_user/sign_agreement/credentials) as ok:false and by the voucher trio as claimed:false, always carrying code, message, and remediation naming the upgrade act (npx --yes huaweicloud-devkit@latest update --target <agent>, restart the agent session, or huaweicloud_upgrade), with clientVersion and minVersion present when the service sends them. Returns session_id, dev_stage_id, connection_id, connection_address, expiresAt (STS credential expiry), pool_type/resolved template_id echo, server-configured lifecycle numbers (pool_idle_shutdown_minutes / pool_idle_delete_minutes / pool_reclaim_minutes) and started (true when a reused instance was woken from shutdown). Lifecycle hints are announced only on the first connect of a session or when started=true. Ephemeral pool (default): idle auto-shutdown after 30min, auto-delete after 1h — do not keep important data there. Persistent pool: data disk retained (EVS 32G), idle shutdown after 1h, idle reclaim capped at 7 days. Numbers are configured by hdkitservice; the text follows the server echo and falls back to these defaults. Vendor-gated (vendorConfirmed): call only when the vendor is established — see the vendorConfirmed parameter description; when unknown, ask which cloud the user means first.',
150
+ '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.',
143
151
  schema: connectSchema,
144
152
  handler: handleConnect,
145
153
  },
@@ -174,6 +182,7 @@ export const SANDBOX_TOOL_SCHEMAS: Readonly<Record<SandboxToolName, LooseToolSch
174
182
  huaweicloud_sandbox_deploy_nginx: deployNginxSchema,
175
183
  huaweicloud_sandbox_deploy_check: deployCheckSchema,
176
184
  huaweicloud_sandbox_expose_tunnel: exposeTunnelSchema,
185
+ huaweicloud_sandbox_expose_poll: exposePollSchema,
177
186
  huaweicloud_sandbox_renew_tunnel: renewTunnelSchema,
178
187
  huaweicloud_sandbox_keepalive_watchdog: keepaliveWatchdogSchema,
179
188
  huaweicloud_sandbox_check_user: checkUserSchema,
@@ -196,6 +205,7 @@ export const SANDBOX_TOOL_HANDLERS: Readonly<Record<SandboxToolName, PackToolDef
196
205
  huaweicloud_sandbox_deploy_nginx: handleDeployNginx,
197
206
  huaweicloud_sandbox_deploy_check: handleDeployCheck,
198
207
  huaweicloud_sandbox_expose_tunnel: handleExposeTunnel,
208
+ huaweicloud_sandbox_expose_poll: handleExposePoll,
199
209
  huaweicloud_sandbox_renew_tunnel: handleRenewTunnel,
200
210
  huaweicloud_sandbox_keepalive_watchdog: handleKeepaliveWatchdog,
201
211
  huaweicloud_sandbox_check_user: handleCheckUser,