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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +3 -1
  2. package/package.json +3 -1
  3. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +16 -3
  4. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +16 -3
  5. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +16 -3
  6. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +16 -3
  7. package/plugins/huaweicloud-core/.mcp.json +55 -1
  8. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +16 -3
  9. package/plugins/huaweicloud-core/dist/agents/codex-config.js +374 -0
  10. package/plugins/huaweicloud-core/dist/agents/codex-desktop.js +8 -1
  11. package/plugins/huaweicloud-core/dist/agents/codex.js +9 -0
  12. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +157 -31
  13. package/plugins/huaweicloud-core/dist/agents/opencode.js +129 -1
  14. package/plugins/huaweicloud-core/dist/approval-gate.js +1185 -0
  15. package/plugins/huaweicloud-core/dist/approval-ledger.js +2331 -0
  16. package/plugins/huaweicloud-core/dist/approval-roster.js +89 -0
  17. package/plugins/huaweicloud-core/dist/approval-types.js +1 -0
  18. package/plugins/huaweicloud-core/dist/approvals-cli.js +4 -4
  19. package/plugins/huaweicloud-core/dist/data/icons-manifest.v1.json +23 -5
  20. package/plugins/huaweicloud-core/dist/dep/receipts.js +65 -5
  21. package/plugins/huaweicloud-core/dist/hcloud-cli.js +1 -1
  22. package/plugins/huaweicloud-core/dist/hcloud-plan.js +77 -56
  23. package/plugins/huaweicloud-core/dist/lib/approval-mode.js +32 -0
  24. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +18 -4
  25. package/plugins/huaweicloud-core/dist/lib/call-trace.js +7 -14
  26. package/plugins/huaweicloud-core/dist/lib/confirm-language.js +50 -0
  27. package/plugins/huaweicloud-core/dist/lib/credentials.js +9 -9
  28. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkit-gate.js +1398 -0
  29. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +362 -32
  30. package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +6 -16
  31. package/plugins/huaweicloud-core/dist/lib/opencode-ask-rule.js +262 -0
  32. package/plugins/huaweicloud-core/dist/lib/opencode-saved-perms.js +282 -0
  33. package/plugins/huaweicloud-core/dist/lib/supplemental-redaction.js +116 -0
  34. package/plugins/huaweicloud-core/dist/lib/tool-schema-parts.js +31 -0
  35. package/plugins/huaweicloud-core/dist/lib/workspace-glob.js +442 -0
  36. package/plugins/huaweicloud-core/dist/mcp-config-io.js +28 -1
  37. package/plugins/huaweicloud-core/dist/mcp-protocol.js +75 -4
  38. package/plugins/huaweicloud-core/dist/mcp-server.js +6560 -898
  39. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  40. package/plugins/huaweicloud-core/dist/mcp-stdio-transport.js +14 -4
  41. package/plugins/huaweicloud-core/dist/packs/auth/approval.js +249 -0
  42. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +44 -44
  43. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +119 -112
  44. package/plugins/huaweicloud-core/dist/packs/obs/approval.js +110 -0
  45. package/plugins/huaweicloud-core/dist/packs/obs/tools.js +7 -2
  46. package/plugins/huaweicloud-core/dist/packs/registry.js +19 -1
  47. package/plugins/huaweicloud-core/dist/packs/sandbox/approval.js +245 -0
  48. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +156 -23
  49. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +13 -1
  50. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-hwexec.js +136 -0
  51. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +11 -1
  52. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +1 -0
  53. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +79 -9
  54. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +28 -9
  55. package/plugins/huaweicloud-core/dist/packs/secrets/approval.js +46 -0
  56. package/plugins/huaweicloud-core/dist/packs/secrets/tools.js +4 -1
  57. package/plugins/huaweicloud-core/dist/packs/update/approval.js +79 -0
  58. package/plugins/huaweicloud-core/dist/packs/update/tools.js +8 -1
  59. package/plugins/huaweicloud-core/dist/packs/voucher/tools.js +1 -1
  60. package/plugins/huaweicloud-core/dist/packs-configure.js +74 -0
  61. package/plugins/huaweicloud-core/dist/safety/classify-text.js +36 -0
  62. package/plugins/huaweicloud-core/dist/safety/policy.js +2 -0
  63. package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +1 -1
  64. package/plugins/huaweicloud-core/dist/sandbox/devbridge-auth.js +65 -14
  65. package/plugins/huaweicloud-core/dist/sandbox/devbridge-cleanup.js +422 -0
  66. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose-flow.js +66 -16
  67. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose.js +13 -10
  68. package/plugins/huaweicloud-core/dist/sandbox/devbridge-keepalive.js +42 -2
  69. package/plugins/huaweicloud-core/dist/sandbox/devbridge-key.js +11 -3
  70. package/plugins/huaweicloud-core/dist/sandbox/devbridge-tunnel.js +6 -0
  71. package/plugins/huaweicloud-core/dist/sandbox/devbridge-validation.js +10 -1
  72. package/plugins/huaweicloud-core/dist/sandbox/hwexec-task.js +244 -0
  73. package/plugins/huaweicloud-core/dist/setup-cli.js +42 -4
  74. package/plugins/huaweicloud-core/dist/tool-definitions.js +9 -1
  75. package/plugins/huaweicloud-core/dist/tool-schemas.js +32 -6
  76. package/plugins/huaweicloud-core/dist/tools.js +76 -9
  77. package/plugins/huaweicloud-core/dist/update-registry.js +358 -5
  78. package/plugins/huaweicloud-core/dist/update-upgrade.js +1083 -14
  79. package/plugins/huaweicloud-core/dist/vendor-gate.js +2 -2
  80. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +150 -1
  81. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +53 -3
  82. package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
  83. package/plugins/huaweicloud-core/safety/policy.json +18 -11
  84. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +114 -10
  85. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +190 -138
  86. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +36 -12
  87. package/plugins/huaweicloud-core/skills/huawei-voucher/SKILL.md +2 -0
  88. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +5 -5
  89. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +13 -8
  90. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +78 -23
  91. package/plugins/huaweicloud-core/skills/huaweicloud-troubleshooting/SKILL.md +21 -19
  92. package/plugins/huaweicloud-core/src/agents/codex-config.ts +432 -0
  93. package/plugins/huaweicloud-core/src/agents/codex-desktop.ts +8 -1
  94. package/plugins/huaweicloud-core/src/agents/codex.ts +10 -0
  95. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +198 -30
  96. package/plugins/huaweicloud-core/src/agents/opencode.ts +157 -1
  97. package/plugins/huaweicloud-core/src/approval-gate.ts +1306 -0
  98. package/plugins/huaweicloud-core/src/approval-ledger.ts +2446 -0
  99. package/plugins/huaweicloud-core/src/approval-roster.ts +127 -0
  100. package/plugins/huaweicloud-core/src/approval-types.ts +237 -0
  101. package/plugins/huaweicloud-core/src/approvals-cli.ts +4 -4
  102. package/plugins/huaweicloud-core/src/data/icons-manifest.v1.json +23 -5
  103. package/plugins/huaweicloud-core/src/dep/receipts.ts +84 -5
  104. package/plugins/huaweicloud-core/src/hcloud-cli.ts +3 -0
  105. package/plugins/huaweicloud-core/src/hcloud-plan.ts +93 -63
  106. package/plugins/huaweicloud-core/src/lib/approval-mode.ts +34 -0
  107. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +19 -4
  108. package/plugins/huaweicloud-core/src/lib/call-trace.ts +7 -17
  109. package/plugins/huaweicloud-core/src/lib/confirm-language.ts +51 -0
  110. package/plugins/huaweicloud-core/src/lib/credentials.ts +9 -8
  111. package/plugins/huaweicloud-core/src/lib/hdkit/hdkit-gate.ts +1428 -0
  112. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +377 -30
  113. package/plugins/huaweicloud-core/src/lib/hdkit/sandbox-pool.ts +8 -15
  114. package/plugins/huaweicloud-core/src/lib/opencode-ask-rule.ts +350 -0
  115. package/plugins/huaweicloud-core/src/lib/opencode-saved-perms.ts +354 -0
  116. package/plugins/huaweicloud-core/src/lib/supplemental-redaction.ts +129 -0
  117. package/plugins/huaweicloud-core/src/lib/tool-schema-parts.ts +40 -0
  118. package/plugins/huaweicloud-core/src/lib/workspace-glob.ts +414 -0
  119. package/plugins/huaweicloud-core/src/mcp-config-io.ts +27 -1
  120. package/plugins/huaweicloud-core/src/mcp-protocol.ts +88 -5
  121. package/plugins/huaweicloud-core/src/mcp-server.ts +13 -0
  122. package/plugins/huaweicloud-core/src/mcp-stdio-transport.ts +14 -4
  123. package/plugins/huaweicloud-core/src/packs/auth/approval.ts +302 -0
  124. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +54 -45
  125. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +139 -120
  126. package/plugins/huaweicloud-core/src/packs/obs/approval.ts +122 -0
  127. package/plugins/huaweicloud-core/src/packs/obs/tools.ts +7 -2
  128. package/plugins/huaweicloud-core/src/packs/registry.ts +42 -1
  129. package/plugins/huaweicloud-core/src/packs/sandbox/approval.ts +296 -0
  130. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +168 -23
  131. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +11 -1
  132. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-hwexec.ts +228 -0
  133. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +11 -1
  134. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +1 -0
  135. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +100 -8
  136. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +31 -8
  137. package/plugins/huaweicloud-core/src/packs/secrets/approval.ts +50 -0
  138. package/plugins/huaweicloud-core/src/packs/secrets/tools.ts +4 -1
  139. package/plugins/huaweicloud-core/src/packs/update/approval.ts +87 -0
  140. package/plugins/huaweicloud-core/src/packs/update/tools.ts +8 -1
  141. package/plugins/huaweicloud-core/src/packs/voucher/tools.ts +1 -1
  142. package/plugins/huaweicloud-core/src/packs-configure.ts +75 -0
  143. package/plugins/huaweicloud-core/src/safety/classify-text.ts +40 -0
  144. package/plugins/huaweicloud-core/src/safety/policy.ts +7 -0
  145. package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +1 -1
  146. package/plugins/huaweicloud-core/src/sandbox/devbridge-auth.ts +74 -14
  147. package/plugins/huaweicloud-core/src/sandbox/devbridge-cleanup.ts +509 -0
  148. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose-flow.ts +70 -18
  149. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose.ts +26 -10
  150. package/plugins/huaweicloud-core/src/sandbox/devbridge-keepalive.ts +41 -2
  151. package/plugins/huaweicloud-core/src/sandbox/devbridge-key.ts +9 -3
  152. package/plugins/huaweicloud-core/src/sandbox/devbridge-tunnel.ts +24 -0
  153. package/plugins/huaweicloud-core/src/sandbox/devbridge-validation.ts +11 -1
  154. package/plugins/huaweicloud-core/src/sandbox/hwexec-task.ts +304 -0
  155. package/plugins/huaweicloud-core/src/setup-cli.ts +45 -3
  156. package/plugins/huaweicloud-core/src/tool-definitions.ts +9 -1
  157. package/plugins/huaweicloud-core/src/tool-schemas.ts +39 -6
  158. package/plugins/huaweicloud-core/src/tools.ts +124 -10
  159. package/plugins/huaweicloud-core/src/update-registry.ts +340 -5
  160. package/plugins/huaweicloud-core/src/update-upgrade.ts +1130 -14
  161. package/plugins/huaweicloud-core/src/vendor-gate.ts +2 -2
@@ -10,6 +10,7 @@ import { DEVBRIDGE_HOST_EXPIRY_HOURS, evaluateDevbridgeVersion } from './devbrid
10
10
  import { stripTerminalEscapes } from './sandbox-output.ts';
11
11
  import { runOneShot, type OneShotResult } from './devbridge-exec.ts';
12
12
  import type { DevbridgeQuotaKeyHint } from './devbridge-key.ts';
13
+ import type { DevbridgeCleanupResult } from './devbridge-cleanup.ts';
13
14
 
14
15
  // The expose attempt contract, extracted from devbridge-tunnel: the script that
15
16
  // starts the host and probes reachability, the DB_* stdout grammar (readDbField
@@ -56,13 +57,27 @@ export interface ExposeTunnelResult {
56
57
  // failure only): masked keys with last_used_at so the caller can pick what
57
58
  // to clean up in the console.
58
59
  currentKeys?: DevbridgeQuotaKeyHint[];
60
+ // The selective-cleanup summary of the last quota-mode cleanup attempt (the
61
+ // devbridge_tunnel_quota_exceeded failure only): what the cleanup actually
62
+ // deleted/killed before the quota still came back full.
63
+ cleanup?: DevbridgeCleanupResult;
64
+ // The 409 version-gate fold (the HDKIT_VERSION_TOO_OLD relay failure only):
65
+ // the gate payload surfaced flat — `gateRemediation` keeps the structured
66
+ // {hint, steps} copy because `remediation` on this interface is the
67
+ // DevBridge 0.1.x install-migration string (expose-flow's Step-0 upgrade
68
+ // copy), not a structured remediation.
69
+ clientVersion?: string;
70
+ minVersion?: string;
71
+ gateRemediation?: { hint: string; steps: string[] };
59
72
  }
60
73
 
61
74
  // Start (or replace) a devbridge host bound to a single port, extract the public
62
75
  // URL, and health-check it. Mirrors the huaweicloud-sandbox skill's Expose flow:
63
- // pre-clean stale tunnels (quota 10006), start host in background, read the
64
- // port-anchored "Tunnel URL: ..." from /tmp/host.log, curl-check, retry once on
65
- // unreachable.
76
+ // selective pre-clean (devbridge-cleanup.ts) runs BEFORE this script in its
77
+ // own execs, so the script itself never blanket-deletes or globally pkills —
78
+ // those kill other sessions'/ports' tunnels on a shared sandbox. The host starts
79
+ // in background; the port-anchored URL is read from /tmp/host.log and
80
+ // curl-checked, retrying once on unreachable.
66
81
  // The host MUST survive the exec session that started it (#919): setsid detaches
67
82
  // it from the session's process group, `< /dev/null` drops the controlling tty
68
83
  // stdin, and `disown` removes it from the shell's job table — without all three
@@ -75,14 +90,14 @@ export function buildDevbridgeExposeScript(port: number, expiryHours: number = D
75
90
  // derived from the shared domain constant, never hardcoded.
76
91
  const domainLiteral = escapeTunnelDomainForRegExp(DEVBRIDGE_TUNNEL_DOMAIN);
77
92
  return [
78
- // #999: the export rides the same first line as the pkill so the fake's
79
- // first-line recognizer (and any reader) sees one stable anchor — the
93
+ // #999: the data-disk PATH export rides the TUNNEL_URL init line — the
80
94
  // one-shot exec shell does NOT inherit the auth probe's PATH, and after
81
95
  // the Layer-3 install + dedup (or a reboot) the only surviving binary
82
- // lives at /workspace/.local/bin.
83
- `export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"; pkill -f "devbridge host" 2>/dev/null || true`,
84
- `sleep 2`,
85
- `devbridge delete-all > /dev/null 2>&1 || true`,
96
+ // lives at /workspace/.local/bin. A standalone export first line would be
97
+ // byte-identical to the auth probe's opening line, which first-line
98
+ // readers cannot tell apart (the anchor doctrine the retired pkill launch
99
+ // line used to carry).
100
+ `export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"; TUNNEL_URL=""`,
86
101
  // #922 (S8): setsid is unavailable on some sandbox images — fall back to a
87
102
  // bare nohup launch so the host still starts; persistence is then judged by
88
103
  // the independent re-verify in exposeTunnel, which emits the 请勿分享 warning
@@ -96,7 +111,8 @@ export function buildDevbridgeExposeScript(port: number, expiryHours: number = D
96
111
  // with 3s gaps (0/3/6/9s, early exit) before concluding the host never
97
112
  // logged a URL. Main's A2 uses a flat sleep 6 + single grep, which halves
98
113
  // the window v2 tuned for slow hosts — deliberate divergence, recorded.
99
- `TUNNEL_URL=""`,
114
+ // (TUNNEL_URL was initialized on the script's first line so the PATH
115
+ // export can ride it — the #999 anchor.)
100
116
  `for i in 1 2 3 4; do`,
101
117
  ` TUNNEL_URL=$(grep -oE "https://[A-Za-z0-9_-]+-${port}\\.${domainLiteral}" ${hostLog} | head -1)`,
102
118
  ` [ -n "$TUNNEL_URL" ] && break`,
@@ -61,6 +61,7 @@ export function buildDevbridgeKeepaliveScript(tunnels: unknown): string {
61
61
  const body = [
62
62
  `#!/bin/bash`,
63
63
  `export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"`,
64
+ `export DBUS_SESSION_BUS_ADDRESS="\${DBUS_SESSION_BUS_ADDRESS:-unix:path=/run/dbus-session}"`,
64
65
  `# entries: tunnelId:url (URLs are stable — tunnel IDs never change)`,
65
66
  `TUNNELS="${entries}"`,
66
67
  `declare -A LAST_RENEW`,
@@ -79,6 +80,29 @@ export function buildDevbridgeKeepaliveScript(tunnels: unknown): string {
79
80
  ` echo "$TS renew $ID ok (${DEVBRIDGE_RENEW_HOURS}h)" >> /tmp/tunnel-keepalive.log`,
80
81
  ` else`,
81
82
  ` echo "$TS renew $ID FAILED: $(head -1 /tmp/keepalive-last-update.log)" >> /tmp/tunnel-keepalive.log`,
83
+ // Self-heal (bde7ae56): a valid key can coexist with an expired CLI token
84
+ // (renew returns 40100 while auth status still prints Logged in) —
85
+ // re-login from keyring/file (never create a key) and retry once now;
86
+ // the next tick retries normally if even that fails.
87
+ ` DB_KEY=""`,
88
+ ` if command -v hwcloud >/dev/null 2>&1; then`,
89
+ ` DB_KEY=$(hwcloud keyring get HW_DEVBRIDGE_API_KEY 2>&1 || true)`,
90
+ ` case "$DB_KEY" in "devbridge_"*) : ;; *) DB_KEY="";; esac`,
91
+ ` fi`,
92
+ ` if [ -z "$DB_KEY" ] && [ -s /tmp/hw_api_key ]; then`,
93
+ ` source /tmp/hw_api_key 2>/dev/null || true`,
94
+ ` DB_KEY="\${HW_API_KEY:-}"`,
95
+ ` fi`,
96
+ ` if [ -n "$DB_KEY" ] && devbridge auth login --api-key "$DB_KEY" >/tmp/keepalive-auth.log 2>&1; then`,
97
+ ` if devbridge update "$ID" -e ${DEVBRIDGE_RENEW_HOURS} > /tmp/keepalive-last-update.log 2>&1; then`,
98
+ ` echo "$TS renew $ID ok after re-login (${DEVBRIDGE_RENEW_HOURS}h)" >> /tmp/tunnel-keepalive.log`,
99
+ ` else`,
100
+ ` echo "$TS renew $ID FAILED after re-login: $(head -1 /tmp/keepalive-last-update.log)" >> /tmp/tunnel-keepalive.log`,
101
+ ` fi`,
102
+ ` else`,
103
+ ` echo "$TS renew $ID AUTH_FAILED: no usable key; next expose_tunnel will auto-create" >> /tmp/tunnel-keepalive.log`,
104
+ ` fi`,
105
+ ` unset DB_KEY HW_API_KEY 2>/dev/null`,
82
106
  ` fi`,
83
107
  ` LAST_RENEW[$ID]=$NOW`,
84
108
  ` fi`,
@@ -126,7 +150,14 @@ export function buildKeepaliveTunnelsReadScript(): string {
126
150
  }
127
151
 
128
152
  // Parse the raw stdout of buildKeepaliveTunnelsReadScript. Empty output (no
129
- // watchdog installed yet) yields [].
153
+ // watchdog installed yet) yields []. Entries are the generated three-field
154
+ // `id:url:port` form (plus the two-field legacy form): the tunnel URL's last
155
+ // segment is the domain, so a trailing `:<digits>` (or the empty port field's
156
+ // bare `:`) is never part of the URL — strip every tail, including the legacy
157
+ // double tails the pre-fix round trip wrote. A kept tail mangles the watchdog's
158
+ // health-check target and grows one field per roster rewrite (interrogate
159
+ // port-pr4 A-F1; the parse shape predates this port — the fix lands with the
160
+ // cleanup sync, the second roster-rewrite path, so both round trips are stable).
130
161
  export function parseKeepaliveTunnelsOutput(stdout: unknown): KeepaliveTunnel[] {
131
162
  const text = stripTerminalEscapes(stdout);
132
163
  const m = text.match(/^DB_KEEPALIVE_TUNNELS=(.*)$/m);
@@ -136,7 +167,15 @@ export function parseKeepaliveTunnelsOutput(stdout: unknown): KeepaliveTunnel[]
136
167
  .split(/\s+/)
137
168
  .map((entry) => {
138
169
  const i = entry.indexOf(':');
139
- return i > 0 ? { tunnelId: entry.slice(0, i), url: entry.slice(i + 1) } : null;
170
+ if (i <= 0) return null;
171
+ let url = entry.slice(i + 1);
172
+ // Strip every generated/legacy tail in one converging loop: digit tails
173
+ // and bare colons alike (the pre-fix shapes could leave one behind for a
174
+ // generation — a `:18082:` tail kept `:18082` after a single pass).
175
+ while (/:$/.test(url) || /:\d+$/.test(url)) {
176
+ url = url.slice(0, url.lastIndexOf(':'));
177
+ }
178
+ return { tunnelId: entry.slice(0, i), url };
140
179
  })
141
180
  .filter((t): t is KeepaliveTunnel => t !== null);
142
181
  }
@@ -19,6 +19,7 @@ import { homedir } from 'node:os';
19
19
  import { createHash } from 'node:crypto';
20
20
 
21
21
  import { hdkitCreateApiKey, hdkitListApiKeys, hdkitDeleteApiKey } from '../lib/hdkit/hdkitservice-api.ts';
22
+ import { isVersionGateError } from '../lib/hdkit/hdkit-gate.ts';
22
23
  import { getCredentials } from '../lib/hdkit/hwlink-api.ts';
23
24
 
24
25
  const POOL_KEY_NAMES: Record<'ephemeral' | 'persistent', string> = {
@@ -123,8 +124,10 @@ export async function ensureDevbridgeKey(poolType: string | undefined | null): P
123
124
  if (orphan && typeof orphan['id'] === 'string') {
124
125
  await hdkitDeleteApiKey(orphan['id']);
125
126
  }
126
- } catch {
127
- // list/delete 失败不阻断创建(可能权限或网络问题,继续尝试创建)
127
+ } catch (error) {
128
+ // 409 版本门禁必须穿透(relay 侧按出口折叠的前提):吞掉它会被后续 create
129
+ // 失败的泛化降级掩盖成凭证误诊;其余 list/delete 失败仍不阻断创建
130
+ if (isVersionGateError(error)) throw error;
128
131
  }
129
132
 
130
133
  // 3. 创建
@@ -168,7 +171,10 @@ export async function listKeysForQuotaHint(): Promise<DevbridgeQuotaKeyHint[]> {
168
171
  id: typeof k['id'] === 'string' ? k['id'] : '',
169
172
  lastUsed: typeof k['last_used_at'] === 'string' ? k['last_used_at'] : '',
170
173
  }));
171
- } catch {
174
+ } catch (error) {
175
+ // 409 门禁必须穿透:配额信封拿着读不出来的 currentKeys 教用户清 key 是误诊
176
+ // (devbridge-auth 侧按出口折叠);其余读取失败仍降级为空清单
177
+ if (isVersionGateError(error)) throw error;
172
178
  return [];
173
179
  }
174
180
  }
@@ -12,6 +12,7 @@
12
12
  // devbridge-verify.ts — the fresh-session re-verify family (#919/#922)
13
13
  // devbridge-renew.ts — the renew flow (script, parser, renewTunnel)
14
14
  // devbridge-keepalive.ts — the keepalive watchdog family + enrollment
15
+ // devbridge-cleanup.ts — the selective tunnel cleanup family
15
16
  // devbridge-expose-flow.ts — the exposeTunnel orchestration
16
17
  // The sandbox siblings import each other's canonical modules directly (the
17
18
  // DEVBRIDGE_* gateway constants from devbridge-gateway.ts, the escape stripper
@@ -73,6 +74,29 @@ export {
73
74
  parseKeepaliveTunnelsOutput,
74
75
  } from './devbridge-keepalive.ts';
75
76
  export type { KeepaliveTunnel, KeepaliveWatchdogResult } from './devbridge-keepalive.ts';
77
+ // The selective-cleanup family (parsers, cleanup plan, lock/state/apply
78
+ // scripts, the cleanup orchestration) lives in devbridge-cleanup.ts;
79
+ // re-exported as the public face (the sandbox pack's handlers and the tests
80
+ // import these names here).
81
+ export {
82
+ buildDevbridgeCleanupApplyScript,
83
+ buildDevbridgeCleanupLockScript,
84
+ buildDevbridgeCleanupStateScript,
85
+ cleanupDevbridgeTunnels,
86
+ normalizeCleanupMode,
87
+ parseDevbridgeHostProcesses,
88
+ parseDevbridgePortQueries,
89
+ parseDevbridgeTunnelList,
90
+ planDevbridgeCleanup,
91
+ } from './devbridge-cleanup.ts';
92
+ export type {
93
+ DevbridgeCleanupMode,
94
+ DevbridgeCleanupOptions,
95
+ DevbridgeCleanupPlan,
96
+ DevbridgeCleanupResult,
97
+ DevbridgeHostProcess,
98
+ DevbridgeTunnelRecord,
99
+ } from './devbridge-cleanup.ts';
76
100
  // The exposeTunnel orchestration lives in devbridge-expose-flow.ts;
77
101
  // re-exported as the public face (the sandbox pack's handlers-tunnel.ts and
78
102
  // the test harness import it here).
@@ -46,13 +46,23 @@ export function validateExpiryHours(hours: unknown): number {
46
46
  return n;
47
47
  }
48
48
 
49
+ // The tunnel-ID charset as one shared pattern: validateTunnelId guards shell
50
+ // splices with it, and the selective-cleanup parsers (devbridge-cleanup.ts)
51
+ // recognize real IDs with it. The real CLI accepts only lowercase base32
52
+ // (a-z2-7, length 8); this superset over-accepts by design — parsing and
53
+ // shell-splice guarding fail SAFE on junk (the CLI's own validation rejects
54
+ // any phantom delete; a phantom matching a real hostless tunnel is a
55
+ // documented orphan-delete), while a strict pattern would silently DROP real
56
+ // IDs on any charset drift.
57
+ export const DEVBRIDGE_TUNNEL_ID_PATTERN = /^[A-Za-z0-9_-]{4,32}$/;
58
+
49
59
  // Validate a DevBridge tunnel ID destined for shell interpolation in
50
60
  // `devbridge update <id>` / `devbridge host <id>` / pgrep patterns. IDs are
51
61
  // short lowercase base36 tokens (e.g. nv2dvv6w, kag7rozs); the strict charset
52
62
  // keeps shell metacharacters out of the splice.
53
63
  export function validateTunnelId(tunnelId: unknown): string {
54
64
  const id = asText(tunnelId ?? '');
55
- if (!/^[A-Za-z0-9_-]{4,32}$/.test(id)) {
65
+ if (!DEVBRIDGE_TUNNEL_ID_PATTERN.test(id)) {
56
66
  throw new Error(
57
67
  `sandbox tunnel: invalid tunnel_id ${JSON.stringify(id.slice(0, 40))}. Expected the short ID from huaweicloud_sandbox_expose_tunnel's "tunnelId" field (URL-safe characters only).`,
58
68
  );
@@ -0,0 +1,304 @@
1
+ import { randomBytes } from 'node:crypto';
2
+
3
+ import { asText } from '../lib/as-text.ts';
4
+ import { stripTerminalEscapes } from './sandbox-output.ts';
5
+
6
+ // The async sandbox-task family — the claim protocol as formalized and
7
+ // TLC-verified (the HwExecClaim spec, 9/9 invariants). One directory per
8
+ // task, /tmp/.hwexec/<taskId>/, whose files ARE the state:
9
+ // claim — the start script's O_EXCL create; existence means some start
10
+ // already won the spawn right, so a retry is structurally
11
+ // unable to spawn a second copy.
12
+ // cmd — the original command line (diagnostics only; poll never
13
+ // reads it; a retry rewrite is harmless).
14
+ // launched — the wrapper's first-action guard file, separating never
15
+ // (claimed, never spawned) from lost (ran, died without
16
+ // writing a status).
17
+ // log — the command's stdout+stderr append stream.
18
+ // status — the terminal `exit:<n>` line; the write is non-atomic, so a
19
+ // torn read must converge to running — the field is matched by
20
+ // CONTENT (full `exit:<digits>` line), never by existence.
21
+ // The claim's deliberate trade: an exec that dies between claim and spawn
22
+ // leaves a task that never runs, and no same-id retry can recover it — the
23
+ // poll's `never` verdict is exactly that state, and the teaching is a NEW
24
+ // task_id. The guard-file variant (check `launched` before spawning — the
25
+ // HwExecGuard3 spec) is falsified by OneCopyRunning (Start, then a retry
26
+ // inside the unconfirmed window, runs two copies); never reintroduce any
27
+ // pre-spawn launched check — the O_EXCL claim create is the only spawn
28
+ // arbiter, and the elif after it only classifies the create failure.
29
+
30
+ // Server-side truth root, one directory per task. /tmp is session-scoped: a
31
+ // sandbox reboot wipes it — the poll's lost/unknown split models exactly
32
+ // that boundary.
33
+ export const HWEXEC_TASK_ROOT = '/tmp/.hwexec';
34
+
35
+ // Task ids are path- and pgrep-safe by charset (lowercase, digits, hyphen,
36
+ // 1-64 chars): they ride file paths AND the pgrep -f pattern, so no shell
37
+ // metacharacter can ever travel through one.
38
+ export const HWEXEC_TASK_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
39
+
40
+ // The poll's bounded wait: sleep-2 intervals checking the status file; the
41
+ // loop count is folded from wait_ms.
42
+ export const HWEXEC_WAIT_STEP_MS = 2000;
43
+
44
+ // The wait_ms ceiling (the zod text and the validator both read this).
45
+ export const HWEXEC_WAIT_MS_MAX = 60000;
46
+
47
+ // Default log-tail size for a poll (and the dup receipt's verdict poll).
48
+ export const HWEXEC_TAIL_BYTES_DEFAULT = 4096;
49
+
50
+ // Log-tail ceiling: the tail rides the poll exec's stdout, and the exec
51
+ // channel is fragile for large single payloads — it stays bounded.
52
+ export const HWEXEC_TAIL_BYTES_MAX = 65536;
53
+
54
+ // The poll exec's headroom over wait_ms (the devbridge-expose-flow A2
55
+ // budget doctrine): the bounded wait plus the field round-trips must sit
56
+ // INSIDE the ws-exec timeout, so the effective timeout folds to
57
+ // wait_ms + 15s and the wait loop can never die as a mid-exec timeout.
58
+ export const HWEXEC_POLL_HEADROOM_MS = 15000;
59
+
60
+ export function hwexecTaskDir(taskId: string): string {
61
+ return `${HWEXEC_TASK_ROOT}/${taskId}`;
62
+ }
63
+
64
+ // Validate a task id destined for path and pgrep-pattern interpolation.
65
+ export function validateHwexecTaskId(id: unknown): string {
66
+ const value = asText(id ?? '');
67
+ if (!HWEXEC_TASK_ID_PATTERN.test(value)) {
68
+ throw new Error(
69
+ `sandbox exec: invalid task_id ${JSON.stringify(value.slice(0, 40))}. ` +
70
+ `Expected ${HWEXEC_TASK_ID_PATTERN.source} (path- and pgrep-safe); omit task_id to let the tool generate one.`,
71
+ );
72
+ }
73
+ return value;
74
+ }
75
+
76
+ // Generate a task id (t-<12 hex>). Collision resistance within one sandbox
77
+ // session is the only requirement — ids scope per-task directories.
78
+ export function generateHwexecTaskId(): string {
79
+ return `t-${randomBytes(6).toString('hex')}`;
80
+ }
81
+
82
+ // Escape a command line for embedding inside a shell single-quoted span —
83
+ // both the cmd-file write and the wrapper's sh -c splice the command this
84
+ // way (close quote, escaped quote, reopen).
85
+ export function escapeHwexecCommand(command: string): string {
86
+ return command.replaceAll("'", "'\\''");
87
+ }
88
+
89
+ // The start script: claim → spawn → receipt, in that line order. The O_EXCL
90
+ // claim create is the only spawn arbiter; the elif only classifies the
91
+ // create failure (dup vs error) and never gates the spawn. The wrapper
92
+ // writes the launched guard as its FIRST action, appends the command's
93
+ // stdout+stderr to the log, then commits `exit:<n>`.
94
+ export function buildHwexecStartScript(taskId: string, command: string): string {
95
+ const id = validateHwexecTaskId(taskId);
96
+ const dir = hwexecTaskDir(id);
97
+ const escaped = escapeHwexecCommand(command);
98
+ // The wrapper's sh -c does not inherit the outer shell's variables, and
99
+ // poll liveness is detected by pgrep -f matching the literal
100
+ // <dir>/launched path inside the wrapper's own command line — so the
101
+ // wrapper's paths are inlined, never $D-expanded.
102
+ const wrapper = `: > "${dir}/launched"; ( ${escaped} ) >> "${dir}/log" 2>&1; echo "exit:$?" > "${dir}/status"`;
103
+ return [
104
+ `D=${dir}`,
105
+ `mkdir -p "$D"`,
106
+ `printf '%s\\n' '${escaped}' > "$D/cmd"`,
107
+ `if (set -C; : > "$D/claim") 2>/dev/null; then`,
108
+ // #919/#922 (the devbridge-expose trio): setsid detaches the process
109
+ // group so the task survives the exec session's teardown, < /dev/null
110
+ // drops the controlling tty, disown removes the job-table entry. A
111
+ // missing setsid falls back to a bare nohup launch — the task still
112
+ // starts; disown is guarded so shells without the builtin survive.
113
+ ` if command -v setsid > /dev/null 2>&1; then setsid nohup sh -c '${wrapper}' >/dev/null 2>&1 < /dev/null & else nohup sh -c '${wrapper}' >/dev/null 2>&1 < /dev/null & fi`,
114
+ ` disown 2>/dev/null || true`,
115
+ ` echo "HW_STARTED=${id}"`,
116
+ `elif [ -f "$D/claim" ]; then`,
117
+ ` echo "HW_DUP=${id}"`,
118
+ `else`,
119
+ ` echo "HW_CLAIM_ERROR=1"`,
120
+ `fi`,
121
+ ].join('\n');
122
+ }
123
+
124
+ // Fold wait_ms into the bounded-wait loop count. Floor division keeps the
125
+ // total sleep ≤ wait_ms — the budget the exec timeout is folded from.
126
+ export function hwexecPollLoops(waitMs: number): number {
127
+ return Math.floor(waitMs / HWEXEC_WAIT_STEP_MS);
128
+ }
129
+
130
+ // Validate wait_ms (0-60000, integer; the default is 0 — no in-poll wait).
131
+ export function validateHwexecWaitMs(waitMs: unknown): number {
132
+ const n = Number(waitMs ?? 0);
133
+ if (!Number.isSafeInteger(n) || n < 0 || n > HWEXEC_WAIT_MS_MAX) {
134
+ throw new Error(
135
+ `sandbox exec poll: invalid wait_ms ${JSON.stringify(waitMs)}. ` +
136
+ `Expected an integer between 0 and ${HWEXEC_WAIT_MS_MAX}.`,
137
+ );
138
+ }
139
+ return n;
140
+ }
141
+
142
+ // Validate tail_bytes (1-65536; the default is 4096).
143
+ export function validateHwexecTailBytes(tailBytes: unknown): number {
144
+ const n = Number(tailBytes ?? HWEXEC_TAIL_BYTES_DEFAULT);
145
+ if (!Number.isSafeInteger(n) || n < 1 || n > HWEXEC_TAIL_BYTES_MAX) {
146
+ throw new Error(
147
+ `sandbox exec poll: invalid tail_bytes ${JSON.stringify(tailBytes)}. ` +
148
+ `Expected an integer between 1 and ${HWEXEC_TAIL_BYTES_MAX}.`,
149
+ );
150
+ }
151
+ return n;
152
+ }
153
+
154
+ // The poll exec timeout: wait_ms + headroom, never below the table default.
155
+ // A timeout on a poll must mean the sandbox is unreachable — never that the
156
+ // script's own bounded wait ran out of clock.
157
+ export function resolveHwexecPollTimeoutMs(waitMs: number, baseTimeoutMs: number): number {
158
+ return Math.max(baseTimeoutMs, waitMs + HWEXEC_POLL_HEADROOM_MS);
159
+ }
160
+
161
+ // The poll script: a bounded wait (sleep-2 intervals, loop count folded from
162
+ // wait_ms, early exit the moment the status line commits), then the one-shot
163
+ // field echo. The HW_* fields are read only from the region before
164
+ // HW_LOG_BEGIN, so log content can never line-inject a verdict field.
165
+ export function buildHwexecPollScript(taskId: string, waitMs: number, tailBytes: number): string {
166
+ const id = validateHwexecTaskId(taskId);
167
+ const loops = hwexecPollLoops(validateHwexecWaitMs(waitMs));
168
+ const bytes = validateHwexecTailBytes(tailBytes);
169
+ return [
170
+ // #999-class guard: the pgrep pattern is assembled from concatenated
171
+ // quoted fragments, so its VALUE never appears literally in this
172
+ // script's own text — a shell whose command line carries the script
173
+ // (an sh -c wrapper) can never match itself. The /launched suffix
174
+ // anchors the pattern to THIS task's wrapper: a bare hwexec/<id>
175
+ // prefix would also match hwexec/<id>-suffix sibling tasks and break
176
+ // the per-task independence the claim protocol's model assumes.
177
+ `P="hwexec/""${id}""/launched"`,
178
+ `D="/tmp/"".hwexec/""${id}"`,
179
+ `i=0`,
180
+ `while [ "$i" -lt ${loops} ]; do`,
181
+ ` grep -q '^exit:[0-9][0-9]*$' "$D/status" 2>/dev/null && break`,
182
+ ` sleep 2`,
183
+ ` i=$((i+1))`,
184
+ `done`,
185
+ `if [ -d "$D" ]; then echo "HW_DIR=1"; else echo "HW_DIR=0"; fi`,
186
+ `S=$(grep -m1 '^exit:[0-9][0-9]*$' "$D/status" 2>/dev/null || true)`,
187
+ `echo "HW_STATUS=$S"`,
188
+ // Missing pgrep (a procps-less image) must not read as dead: an
189
+ // unprobeable aliveness fails SAFE toward alive, because a false
190
+ // 'lost' verdict would send the caller to a new task_id while a copy
191
+ // still runs — the one direction the claim protocol exists to make
192
+ // impossible. The verdict still converges: the task's own completion
193
+ // writes the status file.
194
+ `if command -v pgrep > /dev/null 2>&1 && pgrep -f "$P" > /dev/null 2>&1; then echo "HW_ALIVE=1"; elif command -v pgrep > /dev/null 2>&1; then echo "HW_ALIVE=0"; else echo "HW_ALIVE=1"; fi`,
195
+ `if [ -f "$D/launched" ]; then echo "HW_LAUNCHED=1"; else echo "HW_LAUNCHED=0"; fi`,
196
+ `echo "HW_LOG_BEGIN"`,
197
+ `tail -c ${bytes} "$D/log" 2>/dev/null`,
198
+ `echo "HW_LOG_END"`,
199
+ ].join('\n');
200
+ }
201
+
202
+ // The observable facts one poll reads off the task directory — parsed at
203
+ // the boundary, never re-derived from raw stdout downstream.
204
+ export interface HwexecPollFacts {
205
+ dir: boolean;
206
+ status: string;
207
+ alive: boolean;
208
+ launched: boolean;
209
+ logTail: string;
210
+ }
211
+
212
+ // The judgment label (the verdict table's five states).
213
+ export type HwexecVerdictName = 'done' | 'running' | 'lost' | 'never' | 'unknown';
214
+
215
+ // The judgment the facts induce, as a discriminated union:
216
+ // dir absent → knowTask ? lost (the sandbox rebooted) : unknown
217
+ // status exit: → done (exitCode, logTail)
218
+ // alive → running (logTail)
219
+ // launched → lost (the wrapper died without an exit status)
220
+ // otherwise → never (claimed; the exec died before the spawn)
221
+ export type HwexecVerdict =
222
+ | { verdict: 'done'; exitCode: number; logTail: string }
223
+ | { verdict: 'running'; logTail: string }
224
+ | { verdict: 'lost'; logTail: string }
225
+ | { verdict: 'never' }
226
+ | { verdict: 'unknown' };
227
+
228
+ export function deriveHwexecVerdict(facts: HwexecPollFacts, knowTask: boolean): HwexecVerdict {
229
+ if (!facts.dir) {
230
+ // logTail is '' here by construction: the script's tail on a missing
231
+ // directory produces nothing — the field stays uniform for consumers.
232
+ return knowTask ? { verdict: 'lost', logTail: facts.logTail } : { verdict: 'unknown' };
233
+ }
234
+ const exitMatch = facts.status.match(/^exit:(\d+)$/);
235
+ if (exitMatch) {
236
+ return { verdict: 'done', exitCode: Number(exitMatch[1]), logTail: facts.logTail };
237
+ }
238
+ if (facts.alive) {
239
+ return { verdict: 'running', logTail: facts.logTail };
240
+ }
241
+ if (facts.launched) {
242
+ return { verdict: 'lost', logTail: facts.logTail };
243
+ }
244
+ return { verdict: 'never' };
245
+ }
246
+
247
+ const HW_LOG_BEGIN_MARKER = 'HW_LOG_BEGIN';
248
+ const HW_LOG_END_MARKER = 'HW_LOG_END';
249
+
250
+ // Anchored ^KEY= reader over a field region — the HW_* grammar's single
251
+ // lookup rule (the readDbField doctrine). Returns undefined when the field
252
+ // is absent, so presence and value stay distinguishable.
253
+ function readHwField(text: string, key: string): string | undefined {
254
+ const m = text.match(new RegExp(`^${key}=(.*)$`, 'm'));
255
+ return m === null ? undefined : (m[1] ?? '').trim();
256
+ }
257
+
258
+ // Parse one poll exec's stdout into the facts. #946: strip OSC/CSI escapes
259
+ // and \r before the anchored lookups. The four verdict fields are
260
+ // presence-required — the script emits them unconditionally, so a missing
261
+ // field means the output was truncated or garbled, and an unreadable poll
262
+ // must FAIL instead of misjudging: a defaulted 'never'/'lost' would send
263
+ // the caller to a new task_id while a copy still runs.
264
+ export function parseHwexecPollOutput(stdout: unknown): HwexecPollFacts {
265
+ const text = stripTerminalEscapes(stdout);
266
+ const beginIdx = text.indexOf(HW_LOG_BEGIN_MARKER);
267
+ const head = beginIdx === -1 ? text : text.slice(0, beginIdx);
268
+ let logTail = '';
269
+ if (beginIdx !== -1) {
270
+ const afterBegin = text.slice(beginIdx + HW_LOG_BEGIN_MARKER.length);
271
+ const endIdx = afterBegin.indexOf(HW_LOG_END_MARKER);
272
+ const raw = endIdx === -1 ? afterBegin : afterBegin.slice(0, endIdx);
273
+ logTail = raw.replace(/^\n/, '').replace(/\n$/, '');
274
+ }
275
+ const required = (key: string): string => {
276
+ const value = readHwField(head, key);
277
+ if (value === undefined) {
278
+ throw new Error(
279
+ `sandbox exec poll: unreadable output — the ${key} field is missing, so no verdict can be derived; retry the poll.`,
280
+ );
281
+ }
282
+ return value;
283
+ };
284
+ return {
285
+ dir: required('HW_DIR') === '1',
286
+ status: required('HW_STATUS'),
287
+ alive: required('HW_ALIVE') === '1',
288
+ launched: required('HW_LAUNCHED') === '1',
289
+ logTail,
290
+ };
291
+ }
292
+
293
+ // Classify the start exec's stdout into the receipt outcome. No matching
294
+ // field (truncated or garbled output) reads as 'uncertain' — the receipt
295
+ // was lost, which is exactly what the same-task_id retry ladder covers.
296
+ export type HwexecStartOutcomeKind = 'started' | 'uncertain' | 'dup' | 'claim_error';
297
+
298
+ export function classifyHwexecStartOutput(stdout: unknown, taskId: string): HwexecStartOutcomeKind {
299
+ const text = stripTerminalEscapes(stdout);
300
+ if (readHwField(text, 'HW_STARTED') === taskId) return 'started';
301
+ if (readHwField(text, 'HW_DUP') === taskId) return 'dup';
302
+ if (readHwField(text, 'HW_CLAIM_ERROR') === '1') return 'claim_error';
303
+ return 'uncertain';
304
+ }
@@ -36,6 +36,7 @@ import { removeKooCli, removeObsConfig } from './sandbox/uninstall-cleanup.ts';
36
36
  import { readReceipt, removeReceipt } from './dep/receipts.ts';
37
37
  import { runSecretCommand } from './lib/secret-vault/cli.ts';
38
38
  import { createProcessApproveIo, runApproveCommand, runPinCommand } from './approvals-cli.ts';
39
+ import { readConsentEvents } from './approval-ledger.ts';
39
40
  import { custodyReport } from './lib/secret-vault/custody.ts';
40
41
  import { vaultList } from './lib/secret-vault/store.ts';
41
42
  import { detectCodeartsSandbox } from './codearts-sandbox.ts';
@@ -115,10 +116,12 @@ import {
115
116
  uninstallCodex,
116
117
  } from './agents/codex.ts';
117
118
  import { codexDesktopDoctorMcpConfigured, deployCodexDesktop, uninstallCodexDesktop } from './agents/codex-desktop.ts';
119
+ import { codexDoctorApprovalRow } from './agents/codex-config.ts';
118
120
  import { deployDsh, dshStatus, uninstallDsh } from './agents/dsh.ts';
119
121
  import { dshDoctorMcpConfigured, dshPayloadDoctorSection } from './agents/dsh-patch.ts';
120
122
  import {
121
123
  deployOpenCode,
124
+ opencodeDoctorAskRule,
122
125
  opencodeDoctorMcpConfigured,
123
126
  opencodeDoctorSeam,
124
127
  opencodeStatus,
@@ -178,7 +181,7 @@ async function checkForUpdate(): Promise<void> {
178
181
  // optional chain never short-circuits a reachable path.
179
182
  const tag = distTags?.next && semverCompare(target, distTags.next) === 0 ? 'next' : 'latest';
180
183
  console.log(
181
- `\n\x1b[33mℹ️ 检测到新版本:${target}(当前 ${pkgVersion},${tag} 频道)。建议运行 \`npx --yes huaweicloud-devkit@${tag} update\` 更新。\x1b[0m`,
184
+ `\n\x1b[33mℹ️ 检测到新版本:${target}(当前 ${pkgVersion},${tag} 频道)。建议运行 \`npx --yes --foreground-scripts huaweicloud-devkit@${tag} update\` 更新。\x1b[0m`,
182
185
  );
183
186
  }
184
187
  }
@@ -1047,10 +1050,45 @@ async function cmdDoctor(): Promise<void> {
1047
1050
  mcpCfgTarget ? `Found in ${mcpCfgTarget} config` : 'Run: npx huaweicloud-devkit install',
1048
1051
  );
1049
1052
 
1050
- // Skills-tree permission seam — OpenCode installs only (the section in
1051
- // agents/opencode.ts owns the per-glob kept/missing evaluation).
1053
+ // OpenCode-only installer seams — the skills-tree permission check (the
1054
+ // section in agents/opencode.ts owns the per-glob kept/missing
1055
+ // evaluation) and the ASK approval posture check (the same file owns the
1056
+ // client-rule/server-env pair evaluation).
1052
1057
  if (installedPayload?.id === 'opencode') {
1053
1058
  opencodeDoctorSeam(ctx);
1059
+ opencodeDoctorAskRule(ctx);
1060
+ }
1061
+
1062
+ // The codex client yield (PR-5): the per-tool approval_mode blocks the
1063
+ // devkit payload's .mcp.json carries (agents/codex-config.ts records why
1064
+ // the yield lives there, never in the user's config.toml). The row gates
1065
+ // itself on the machine's codex relationship (no payload, no plugin, no
1066
+ // desktop registration → silent), so it adds nothing to a codex-less
1067
+ // doctor run. The desktop registration bit comes from the candidate the
1068
+ // shell already probed above — passed in so the row never probes twice.
1069
+ codexDoctorApprovalRow(ctx, codexDesktopDoctorMcpConfigured() !== null);
1070
+
1071
+ // Session standing consents (PR-3a's S3): the "remember for this
1072
+ // session" grants the elicitation form's tick recorded in the ask-mode
1073
+ // consent ledger. Listing only, zero rows print nothing: a clean home's
1074
+ // doctor output stays byte-identical. A row is a RECORD of a grant the
1075
+ // user ticked — the grant's operative lifetime is the devkit server
1076
+ // process (it forgets on restart, fail-closed), so the line names what
1077
+ // was consented and when, never a live permission claim.
1078
+ try {
1079
+ const standing = readConsentEvents().filter((event) => event.scope === 'session');
1080
+ if (standing.length > 0) {
1081
+ ctx.info('Session standing consents recorded in the consent ledger (each dies with the devkit server process):');
1082
+ for (const grant of standing) {
1083
+ console.log(
1084
+ ` ${grant.tool} — args hash ${grant.argsHash.slice(0, 16)}, granted ` +
1085
+ `${new Date(grant.grantedAt).toISOString()}, evidence ${grant.evidence}`,
1086
+ );
1087
+ }
1088
+ }
1089
+ } catch {
1090
+ // An unreadable ledger is not a health failure: doctor lists state, it
1091
+ // never gates on it.
1054
1092
  }
1055
1093
 
1056
1094
  // Hermes MCP Python SDK (only checked when Hermes config is found).
@@ -1172,6 +1210,9 @@ async function cmdDoctor(): Promise<void> {
1172
1210
  }
1173
1211
  if (fail > 0) {
1174
1212
  console.log('\x1b[33mFix failures above, then restart your session.\x1b[0m');
1213
+ // A FAIL line is the command's verdict, so CI and scripts can gate on the
1214
+ // exit code: a doctor that prints [FAIL] and exits 0 is not a check.
1215
+ process.exitCode = 1;
1175
1216
  }
1176
1217
  if (fail === 0 && mcpConfigured) {
1177
1218
  console.log('\n\x1b[32mAll checks passed.\x1b[0m You can now describe your Huawei Cloud task');
@@ -1194,6 +1235,7 @@ async function cmdUpdate(): Promise<void> {
1194
1235
  console.log(BANNER);
1195
1236
  resolvePacksFlag(); // fail fast on bogus --packs before any file is copied
1196
1237
  const target = parseTarget();
1238
+ checkNode();
1197
1239
  await checkForUpdate();
1198
1240
  // Reconcile the native dirs only when this run will actually place the new
1199
1241
  // payload somewhere. A target whose server is absent gets "Not installed"