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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/README.md +3 -1
  2. package/package.json +3 -1
  3. package/plugins/huaweicloud-core/.claude-plugin/plugin.json +1 -1
  4. package/plugins/huaweicloud-core/.codex-plugin/plugin.json +1 -1
  5. package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +1 -1
  6. package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +1 -1
  7. package/plugins/huaweicloud-core/.mcp.json +55 -1
  8. package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +1 -1
  9. package/plugins/huaweicloud-core/dist/agents/codex-config.js +374 -0
  10. package/plugins/huaweicloud-core/dist/agents/codex-desktop.js +8 -1
  11. package/plugins/huaweicloud-core/dist/agents/codex.js +9 -0
  12. package/plugins/huaweicloud-core/dist/agents/opencode-config.js +141 -86
  13. package/plugins/huaweicloud-core/dist/agents/opencode.js +106 -39
  14. package/plugins/huaweicloud-core/dist/approval-gate.js +1185 -0
  15. package/plugins/huaweicloud-core/dist/approval-ledger.js +2331 -0
  16. package/plugins/huaweicloud-core/dist/approval-roster.js +89 -0
  17. package/plugins/huaweicloud-core/dist/approval-types.js +1 -0
  18. package/plugins/huaweicloud-core/dist/approvals-cli.js +4 -4
  19. package/plugins/huaweicloud-core/dist/data/icons-manifest.v1.json +23 -5
  20. package/plugins/huaweicloud-core/dist/dep/receipts.js +65 -5
  21. package/plugins/huaweicloud-core/dist/explain-error.js +9 -1
  22. package/plugins/huaweicloud-core/dist/hcloud-cli.js +1 -1
  23. package/plugins/huaweicloud-core/dist/hcloud-plan.js +68 -62
  24. package/plugins/huaweicloud-core/dist/lib/approval-mode.js +7 -5
  25. package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +18 -4
  26. package/plugins/huaweicloud-core/dist/lib/call-trace.js +7 -14
  27. package/plugins/huaweicloud-core/dist/lib/confirm-language.js +50 -0
  28. package/plugins/huaweicloud-core/dist/lib/credentials.js +9 -9
  29. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkit-gate.js +1398 -0
  30. package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +371 -32
  31. package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +6 -16
  32. package/plugins/huaweicloud-core/dist/lib/opencode-ask-rule.js +224 -78
  33. package/plugins/huaweicloud-core/dist/lib/opencode-saved-perms.js +282 -0
  34. package/plugins/huaweicloud-core/dist/lib/supplemental-redaction.js +116 -0
  35. package/plugins/huaweicloud-core/dist/lib/tool-schema-parts.js +31 -0
  36. package/plugins/huaweicloud-core/dist/lib/workspace-glob.js +442 -0
  37. package/plugins/huaweicloud-core/dist/mcp-config-io.js +28 -1
  38. package/plugins/huaweicloud-core/dist/mcp-protocol.js +68 -16
  39. package/plugins/huaweicloud-core/dist/mcp-server.js +6933 -1186
  40. package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
  41. package/plugins/huaweicloud-core/dist/mcp-stdio-transport.js +14 -4
  42. package/plugins/huaweicloud-core/dist/packs/auth/approval.js +249 -0
  43. package/plugins/huaweicloud-core/dist/packs/auth/tools.js +44 -44
  44. package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +85 -130
  45. package/plugins/huaweicloud-core/dist/packs/obs/approval.js +110 -0
  46. package/plugins/huaweicloud-core/dist/packs/obs/tools.js +7 -2
  47. package/plugins/huaweicloud-core/dist/packs/registry.js +20 -1
  48. package/plugins/huaweicloud-core/dist/packs/sandbox/approval.js +245 -0
  49. package/plugins/huaweicloud-core/dist/packs/sandbox/expose-task.js +71 -0
  50. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +180 -23
  51. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +13 -1
  52. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-hwexec.js +136 -0
  53. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +11 -1
  54. package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +29 -3
  55. package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +93 -9
  56. package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +37 -10
  57. package/plugins/huaweicloud-core/dist/packs/secrets/approval.js +46 -0
  58. package/plugins/huaweicloud-core/dist/packs/secrets/tools.js +4 -1
  59. package/plugins/huaweicloud-core/dist/packs/update/approval.js +79 -0
  60. package/plugins/huaweicloud-core/dist/packs/update/tools.js +8 -1
  61. package/plugins/huaweicloud-core/dist/packs/voucher/tools.js +1 -1
  62. package/plugins/huaweicloud-core/dist/packs-configure.js +74 -0
  63. package/plugins/huaweicloud-core/dist/risk-rule-engine.js +20 -4
  64. package/plugins/huaweicloud-core/dist/safety/classify-hcloud.js +6 -6
  65. package/plugins/huaweicloud-core/dist/safety/classify-text.js +36 -0
  66. package/plugins/huaweicloud-core/dist/safety/policy.js +2 -0
  67. package/plugins/huaweicloud-core/dist/safety/redact.js +21 -3
  68. package/plugins/huaweicloud-core/dist/safety/risk-merge.js +24 -4
  69. package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +1 -1
  70. package/plugins/huaweicloud-core/dist/sandbox/devbridge-auth.js +65 -14
  71. package/plugins/huaweicloud-core/dist/sandbox/devbridge-cleanup.js +422 -0
  72. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose-flow.js +66 -16
  73. package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose.js +13 -10
  74. package/plugins/huaweicloud-core/dist/sandbox/devbridge-keepalive.js +42 -2
  75. package/plugins/huaweicloud-core/dist/sandbox/devbridge-key.js +11 -3
  76. package/plugins/huaweicloud-core/dist/sandbox/devbridge-tunnel.js +6 -0
  77. package/plugins/huaweicloud-core/dist/sandbox/devbridge-validation.js +10 -1
  78. package/plugins/huaweicloud-core/dist/sandbox/hwexec-task.js +244 -0
  79. package/plugins/huaweicloud-core/dist/setup-cli.js +36 -1
  80. package/plugins/huaweicloud-core/dist/tool-definitions.js +13 -1
  81. package/plugins/huaweicloud-core/dist/tool-schemas.js +32 -6
  82. package/plugins/huaweicloud-core/dist/tools.js +76 -9
  83. package/plugins/huaweicloud-core/dist/update-registry.js +358 -5
  84. package/plugins/huaweicloud-core/dist/update-upgrade.js +1083 -14
  85. package/plugins/huaweicloud-core/dist/vendor-gate.js +2 -2
  86. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +150 -1
  87. package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +67 -4
  88. package/plugins/huaweicloud-core/openclaw.plugin.json +2 -2
  89. package/plugins/huaweicloud-core/safety/policy.json +18 -11
  90. package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +115 -11
  91. package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +198 -143
  92. package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +36 -12
  93. package/plugins/huaweicloud-core/skills/huawei-voucher/SKILL.md +2 -0
  94. package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +2 -2
  95. package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +11 -7
  96. package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +74 -29
  97. package/plugins/huaweicloud-core/skills/huaweicloud-troubleshooting/SKILL.md +21 -19
  98. package/plugins/huaweicloud-core/src/agents/codex-config.ts +432 -0
  99. package/plugins/huaweicloud-core/src/agents/codex-desktop.ts +8 -1
  100. package/plugins/huaweicloud-core/src/agents/codex.ts +10 -0
  101. package/plugins/huaweicloud-core/src/agents/opencode-config.ts +176 -88
  102. package/plugins/huaweicloud-core/src/agents/opencode.ts +125 -54
  103. package/plugins/huaweicloud-core/src/approval-gate.ts +1306 -0
  104. package/plugins/huaweicloud-core/src/approval-ledger.ts +2446 -0
  105. package/plugins/huaweicloud-core/src/approval-roster.ts +127 -0
  106. package/plugins/huaweicloud-core/src/approval-types.ts +237 -0
  107. package/plugins/huaweicloud-core/src/approvals-cli.ts +4 -4
  108. package/plugins/huaweicloud-core/src/data/icons-manifest.v1.json +23 -5
  109. package/plugins/huaweicloud-core/src/dep/receipts.ts +84 -5
  110. package/plugins/huaweicloud-core/src/explain-error.ts +9 -1
  111. package/plugins/huaweicloud-core/src/hcloud-cli.ts +3 -0
  112. package/plugins/huaweicloud-core/src/hcloud-plan.ts +74 -71
  113. package/plugins/huaweicloud-core/src/lib/approval-mode.ts +7 -5
  114. package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +19 -4
  115. package/plugins/huaweicloud-core/src/lib/call-trace.ts +7 -17
  116. package/plugins/huaweicloud-core/src/lib/confirm-language.ts +51 -0
  117. package/plugins/huaweicloud-core/src/lib/credentials.ts +9 -8
  118. package/plugins/huaweicloud-core/src/lib/hdkit/hdkit-gate.ts +1428 -0
  119. package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +408 -30
  120. package/plugins/huaweicloud-core/src/lib/hdkit/sandbox-pool.ts +8 -15
  121. package/plugins/huaweicloud-core/src/lib/opencode-ask-rule.ts +302 -83
  122. package/plugins/huaweicloud-core/src/lib/opencode-saved-perms.ts +354 -0
  123. package/plugins/huaweicloud-core/src/lib/supplemental-redaction.ts +129 -0
  124. package/plugins/huaweicloud-core/src/lib/tool-schema-parts.ts +40 -0
  125. package/plugins/huaweicloud-core/src/lib/workspace-glob.ts +414 -0
  126. package/plugins/huaweicloud-core/src/mcp-config-io.ts +27 -1
  127. package/plugins/huaweicloud-core/src/mcp-protocol.ts +81 -17
  128. package/plugins/huaweicloud-core/src/mcp-server.ts +7 -7
  129. package/plugins/huaweicloud-core/src/mcp-stdio-transport.ts +14 -4
  130. package/plugins/huaweicloud-core/src/packs/auth/approval.ts +302 -0
  131. package/plugins/huaweicloud-core/src/packs/auth/tools.ts +54 -45
  132. package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +99 -137
  133. package/plugins/huaweicloud-core/src/packs/obs/approval.ts +122 -0
  134. package/plugins/huaweicloud-core/src/packs/obs/tools.ts +7 -2
  135. package/plugins/huaweicloud-core/src/packs/registry.ts +43 -1
  136. package/plugins/huaweicloud-core/src/packs/sandbox/approval.ts +296 -0
  137. package/plugins/huaweicloud-core/src/packs/sandbox/expose-task.ts +105 -0
  138. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +195 -23
  139. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +11 -1
  140. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-hwexec.ts +228 -0
  141. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +11 -1
  142. package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +41 -14
  143. package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +120 -8
  144. package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +42 -9
  145. package/plugins/huaweicloud-core/src/packs/secrets/approval.ts +50 -0
  146. package/plugins/huaweicloud-core/src/packs/secrets/tools.ts +4 -1
  147. package/plugins/huaweicloud-core/src/packs/update/approval.ts +87 -0
  148. package/plugins/huaweicloud-core/src/packs/update/tools.ts +8 -1
  149. package/plugins/huaweicloud-core/src/packs/voucher/tools.ts +1 -1
  150. package/plugins/huaweicloud-core/src/packs-configure.ts +75 -0
  151. package/plugins/huaweicloud-core/src/risk-rule-engine.ts +20 -7
  152. package/plugins/huaweicloud-core/src/safety/classify-hcloud.ts +28 -16
  153. package/plugins/huaweicloud-core/src/safety/classify-text.ts +40 -0
  154. package/plugins/huaweicloud-core/src/safety/policy.ts +7 -0
  155. package/plugins/huaweicloud-core/src/safety/redact.ts +24 -6
  156. package/plugins/huaweicloud-core/src/safety/risk-merge.ts +26 -5
  157. package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +1 -1
  158. package/plugins/huaweicloud-core/src/sandbox/devbridge-auth.ts +74 -14
  159. package/plugins/huaweicloud-core/src/sandbox/devbridge-cleanup.ts +511 -0
  160. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose-flow.ts +70 -18
  161. package/plugins/huaweicloud-core/src/sandbox/devbridge-expose.ts +26 -10
  162. package/plugins/huaweicloud-core/src/sandbox/devbridge-keepalive.ts +41 -2
  163. package/plugins/huaweicloud-core/src/sandbox/devbridge-key.ts +9 -3
  164. package/plugins/huaweicloud-core/src/sandbox/devbridge-tunnel.ts +24 -0
  165. package/plugins/huaweicloud-core/src/sandbox/devbridge-validation.ts +11 -1
  166. package/plugins/huaweicloud-core/src/sandbox/hwexec-task.ts +304 -0
  167. package/plugins/huaweicloud-core/src/setup-cli.ts +39 -1
  168. package/plugins/huaweicloud-core/src/tool-definitions.ts +13 -1
  169. package/plugins/huaweicloud-core/src/tool-schemas.ts +39 -6
  170. package/plugins/huaweicloud-core/src/tools.ts +124 -10
  171. package/plugins/huaweicloud-core/src/update-registry.ts +340 -5
  172. package/plugins/huaweicloud-core/src/update-upgrade.ts +1130 -14
  173. package/plugins/huaweicloud-core/src/vendor-gate.ts +2 -2
@@ -0,0 +1,422 @@
1
+ import { runOneShot } from "./devbridge-exec.js";
2
+ import { stripTerminalEscapes } from "./sandbox-output.js";
3
+ import { DEVBRIDGE_TUNNEL_ID_PATTERN } from "./devbridge-validation.js";
4
+ import { buildKeepaliveTunnelsReadScript, installKeepaliveWatchdog, parseKeepaliveTunnelsOutput, } from "./devbridge-keepalive.js";
5
+ // The DevBridge selective-cleanup family, ported from dev's 1.1.x cleanup wave
6
+ // (97c4bc8a + 7118d61f + 603554d0 + 6100026e + 43fa459e): delete-all is
7
+ // intentionally NOT used in any automated path — it kills other sessions' and
8
+ // other ports' tunnels on a shared sandbox. Cleanup removes only orphan tunnel
9
+ // records/hosts and (for expose) tunnels bound to the same port, preserving
10
+ // other ports, other sessions, and keepalive-protected tunnels. Same-port is
11
+ // the one documented exception: a keepalive-protected tunnel on the target
12
+ // port is replaced, because a port cannot have two tunnels.
13
+ // The lock serializes concurrent cleanups (connect + expose can overlap on one
14
+ // sandbox); the stale threshold (10min) sits above the worst-case hold
15
+ // (state 60x2 + apply 60x2 + sync ~150 + release ≈ 450s) so a second cleanup
16
+ // cannot break a lock that is still legitimately held.
17
+ // v2 divergence from dev (recorded): the state and apply scripts carry the
18
+ // data-disk PATH export on the same first line as a distinguishing token
19
+ // (#999 anchor doctrine — the e2e fake recognizes scripts by first line, and a
20
+ // standalone export first line is byte-identical to the auth probe's opening
21
+ // line; dev has no first-line-recognizing fake, so dev's scripts keep the
22
+ // export standalone).
23
+ const DEVBRIDGE_PATH_EXPORT = 'export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"';
24
+ const DEVBRIDGE_LOCK_PATH = '/tmp/devbridge-cleanup.lock';
25
+ // Worst-case hold: state 60x2 + apply 60x2 + sync ~150 + release 60 ≈ 450s.
26
+ const DEVBRIDGE_LOCK_STALE_MINUTES = 10;
27
+ const DEVBRIDGE_CLEANUP_TIMEOUT_MS = 60000;
28
+ // Tunnel IDs share validateTunnelId's charset — real IDs may contain 0/1/8/9,
29
+ // so parsing must not assume the base32 subset.
30
+ export function normalizeCleanupMode(raw) {
31
+ return raw === 'stale' || raw === 'all' || raw === 'none' ? raw : 'stale';
32
+ }
33
+ // Parse `devbridge list` (0.2.x plain table) behind OSC/CRLF noise. The header
34
+ // row is skipped explicitly; data rows start with the tunnel ID. A non-string
35
+ // input reads as empty (the stripTerminalEscapes seam's contract).
36
+ export function parseDevbridgeTunnelList(stdout) {
37
+ const text = stripTerminalEscapes(stdout);
38
+ const tunnels = [];
39
+ for (const line of text.split(/\r?\n/)) {
40
+ if (/^\s*Tunnel\s+ID\b/i.test(line))
41
+ continue;
42
+ const m = line.match(/^\s*([A-Za-z0-9_-]{4,32})\s+(.+)$/);
43
+ if (!m || !DEVBRIDGE_TUNNEL_ID_PATTERN.test(m[1]))
44
+ continue;
45
+ const id = m[1];
46
+ const rest = m[2];
47
+ const name = rest.trim().split(/\s{2,}|\t+/)[0] || '';
48
+ const portMatch = rest.match(/tunnel-(\d+)-/);
49
+ // The expiry read is anchored to the expiry column by the trailing Port
50
+ // Count (lookahead, so the matched text stays the clean "N unit"): a
51
+ // description that itself reads like a duration — `1minute`, `5days`,
52
+ // legal because descriptions reject spaces — must not poison the
53
+ // quota-mode oldest-first targeting (interrogate port-pr4 B-F2; dev's
54
+ // 97c4bc8a/43fa459e scan the whole row tail unanchored — deliberate
55
+ // v2 hardening now that the quota wiring makes the expiry load-bearing).
56
+ // A row whose shape no longer matches reads as null → sorts last in quota
57
+ // mode (fail-safe: never deleted on a guess). One arbitration remains:
58
+ // when EVERY candidate reads null the stable sort degenerates to list
59
+ // order and the first listed is deleted — the delete stays confined to
60
+ // live non-protected tunnels (the keepalive invariant holds regardless).
61
+ const expMatch = rest.match(/(\d+)\s*(day|days|hour|hours|minute|minutes)(?=\s+\d+\s*$)/i);
62
+ const unit = expMatch ? expMatch[2].toLowerCase() : '';
63
+ const multiplier = { day: 86400, days: 86400, hour: 3600, hours: 3600, minute: 60, minutes: 60 }[unit];
64
+ tunnels.push({
65
+ id,
66
+ name,
67
+ port: portMatch ? Number(portMatch[1]) : null,
68
+ expiryText: expMatch ? expMatch[0] : '',
69
+ expirySeconds: expMatch && multiplier ? Number(expMatch[1]) * multiplier : null,
70
+ });
71
+ }
72
+ return tunnels;
73
+ }
74
+ // Parse the DB_CLEANUP_PORTS section: one `TUNNEL_PORTS_<id>=<p>,<p>,` line
75
+ // per tunnel (the state script's per-tunnel `devbridge port list` queries).
76
+ // An absent or empty section yields an empty map — the callers then fall back
77
+ // to the name-shape/keepalive-URL port reads.
78
+ export function parseDevbridgePortQueries(stdout) {
79
+ const text = stripTerminalEscapes(stdout);
80
+ const out = new Map();
81
+ for (const m of text.matchAll(/^TUNNEL_PORTS_([A-Za-z0-9_-]{4,32})=(.*)$/gm)) {
82
+ const ports = (m[2] ?? '')
83
+ .split(',')
84
+ .map((p) => Number(p))
85
+ .filter((n) => Number.isSafeInteger(n) && n >= 1 && n <= 65535);
86
+ out.set(m[1], ports);
87
+ }
88
+ return out;
89
+ }
90
+ // Parse `pgrep -af "devbridge host"` output. The executable is anchored so a
91
+ // shell wrapper (`bash -c "...devbridge host..."`) is never mistaken for a
92
+ // real host process; the args are tokenized flag-by-flag so an ID can sit in
93
+ // any position. An unparseable host (no id, no port) is dropped — never killed
94
+ // blindly on a guess.
95
+ export function parseDevbridgeHostProcesses(stdout) {
96
+ const text = stripTerminalEscapes(stdout);
97
+ const hosts = [];
98
+ for (const line of text.split(/\r?\n/)) {
99
+ const m = line.match(/^\s*(\d+)\s+(.*)$/);
100
+ if (!m)
101
+ continue;
102
+ const execMatch = m[2].match(/^(?:\S*\/)?devbridge\s+host\b(.*)$/);
103
+ if (!execMatch)
104
+ continue;
105
+ const rest = execMatch[1].trim();
106
+ const tokens = rest ? rest.split(/\s+/) : [];
107
+ let id = null;
108
+ let port = null;
109
+ for (let i = 0; i < tokens.length; i += 1) {
110
+ const token = tokens[i];
111
+ if (token === '-p' && /^\d+$/.test(tokens[i + 1] || '')) {
112
+ port = Number(tokens[i + 1]);
113
+ i += 1;
114
+ }
115
+ else if (token === '-e') {
116
+ i += 1;
117
+ }
118
+ else if (token.startsWith('-')) {
119
+ // unknown flag: skip it
120
+ }
121
+ else if (!id && DEVBRIDGE_TUNNEL_ID_PATTERN.test(token) && !/^\d+$/.test(token)) {
122
+ id = token;
123
+ }
124
+ }
125
+ if (!id && port == null)
126
+ continue;
127
+ hosts.push({ pid: Number(m[1]), id, port });
128
+ }
129
+ return hosts;
130
+ }
131
+ // Decide which tunnels/hosts to remove.
132
+ // - protected: keepalive TUNNELS entries (never removed unless mode=all or
133
+ // samePort — the one documented exception)
134
+ // - orphan: tunnel record with no live host — removed in stale/quota
135
+ // - orphan host: host process with no matching tunnel record — killed
136
+ // - quota: also removes the oldest non-protected live tunnels (maxExtra per
137
+ // call) until the new tunnel fits
138
+ export function planDevbridgeCleanup({ tunnels = [], hosts = [], keepalive = [], mode = 'stale', samePort = null, maxExtra = 1, } = {}) {
139
+ if (mode === 'none')
140
+ return { deleteIds: [], killPids: [] };
141
+ const tunnelIds = new Set(tunnels.map((t) => t.id));
142
+ const protectedIds = new Set(keepalive.map((k) => k.tunnelId).filter(Boolean));
143
+ // Port attribution as a per-tunnel SET: the authoritative port-list queries
144
+ // first (t.ports, any tunnel name), then the name-shape/keepalive-URL single
145
+ // reads. Sets cover multi-port tunnels for every same-port/host match.
146
+ const portsById = new Map();
147
+ for (const t of tunnels) {
148
+ const set = t.ports && t.ports.length > 0 ? t.ports : t.port != null ? [t.port] : [];
149
+ if (set.length > 0)
150
+ portsById.set(t.id, set);
151
+ }
152
+ for (const k of keepalive) {
153
+ const m = String(k.url || '').match(/-(\d+)\.devbridge-s2\./);
154
+ if (m && tunnelIds.has(k.tunnelId) && !portsById.has(k.tunnelId)) {
155
+ portsById.set(k.tunnelId, [Number(m[1])]);
156
+ }
157
+ }
158
+ const hasPort = (id, port) => portsById.get(id)?.includes(port) ?? false;
159
+ if (mode === 'all') {
160
+ return { deleteIds: [...tunnelIds], killPids: hosts.map((h) => h.pid) };
161
+ }
162
+ const liveIds = new Set();
163
+ const mappedPids = new Set();
164
+ for (const h of hosts) {
165
+ if (!h.id && h.port == null)
166
+ continue; // unattributable host: never kill blindly
167
+ if (h.id && tunnelIds.has(h.id)) {
168
+ liveIds.add(h.id);
169
+ mappedPids.add(h.pid);
170
+ }
171
+ else if (h.port != null) {
172
+ for (const [id] of portsById) {
173
+ if (hasPort(id, h.port)) {
174
+ liveIds.add(id);
175
+ mappedPids.add(h.pid);
176
+ }
177
+ }
178
+ }
179
+ }
180
+ const killPids = new Set(hosts.filter((h) => (h.id || h.port != null) && !mappedPids.has(h.pid)).map((h) => h.pid));
181
+ const samePortIds = samePort == null ? [] : tunnels.filter((t) => hasPort(t.id, samePort)).map((t) => t.id);
182
+ const orphanIds = tunnels.filter((t) => !protectedIds.has(t.id) && !liveIds.has(t.id)).map((t) => t.id);
183
+ const deleteSet = new Set([...orphanIds, ...samePortIds]);
184
+ if (mode === 'quota') {
185
+ const candidates = tunnels
186
+ .filter((t) => !protectedIds.has(t.id) && !deleteSet.has(t.id) && liveIds.has(t.id))
187
+ .sort((a, b) => (a.expirySeconds ?? Number.MAX_SAFE_INTEGER) - (b.expirySeconds ?? Number.MAX_SAFE_INTEGER));
188
+ for (let i = 0; i < Math.max(0, maxExtra) && i < candidates.length; i += 1) {
189
+ deleteSet.add(candidates[i].id);
190
+ }
191
+ }
192
+ for (const h of hosts) {
193
+ // A host id-attributed to a record we are KEEPING is never a kill target,
194
+ // even when some deleted record's port claim matches the host's port (the
195
+ // structural guard makes the live-host invariant independent of the
196
+ // gateway's one-port-one-record doctrine). A host whose own record IS in
197
+ // the delete set still dies.
198
+ if (h.id && mappedPids.has(h.pid) && !deleteSet.has(h.id))
199
+ continue;
200
+ if (h.id && deleteSet.has(h.id))
201
+ killPids.add(h.pid);
202
+ else if (h.port != null) {
203
+ // A port-only host (the expose launch form, `devbridge host -p <port>`)
204
+ // cannot be attributed to a specific record. When ANY surviving record
205
+ // still claims the host's port, we cannot prove the host belongs to a
206
+ // deleted record — never kill on that guess; the next cleanup after the
207
+ // survivor is gone (or a same-port expose that replaced every same-port
208
+ // record) still fires.
209
+ const survivorClaimsPort = [...tunnelIds].some((id) => !deleteSet.has(id) && hasPort(id, h.port));
210
+ if (!survivorClaimsPort && [...deleteSet].some((id) => hasPort(id, h.port)))
211
+ killPids.add(h.pid);
212
+ }
213
+ }
214
+ return { deleteIds: [...deleteSet], killPids: [...killPids] };
215
+ }
216
+ export function buildDevbridgeCleanupApplyScript({ deleteIds = [], killPids = [], } = {}) {
217
+ for (const id of deleteIds) {
218
+ if (!DEVBRIDGE_TUNNEL_ID_PATTERN.test(String(id))) {
219
+ throw new Error(`devbridge cleanup: invalid tunnel id ${JSON.stringify(id)}`);
220
+ }
221
+ }
222
+ for (const pid of killPids) {
223
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
224
+ throw new Error(`devbridge cleanup: invalid pid ${JSON.stringify(pid)}`);
225
+ }
226
+ }
227
+ return [
228
+ // #999 anchor doctrine: the export rides the APPLY marker line so the
229
+ // apply exec can never be misrecognized as the auth probe (a standalone
230
+ // export first line is byte-identical to the probe's).
231
+ `${DEVBRIDGE_PATH_EXPORT}; echo "DB_CLEANUP_APPLY"`,
232
+ // Re-check the process identity before killing: state→apply can take
233
+ // minutes, so a recycled PID must not hit an unrelated process.
234
+ ...killPids.map((pid) => `if ps -p ${pid} -o args= 2>/dev/null | grep -q "devbridge host"; then kill ${pid} >/dev/null 2>&1 || true; fi`),
235
+ `sleep 1`,
236
+ ...deleteIds.map((id) => `devbridge delete ${id} >/dev/null 2>&1 || true`),
237
+ `echo "DB_CLEANUP_DELETED=${deleteIds.join(',')}"`,
238
+ `echo "DB_CLEANUP_KILLED=${killPids.join(',')}"`,
239
+ ].join('\n');
240
+ }
241
+ // The candidate-row filter shared by the PORTS query loop: strip the OSC 133
242
+ // shell-integration markers that wrap every line on integration-enabled
243
+ // shells (#946 — the plugin's TS parsers fold stripTerminalEscapes in for
244
+ // exactly this; a raw-ID extraction would hand the CLI glued IDs it rejects),
245
+ // then keep the first token of every non-header row. "No tunnels found." is
246
+ // excluded so an empty world yields zero candidates.
247
+ const DEVBRIDGE_OSC_FILTER = `{gsub(/\\033\\]133;C\\007/, ""); if ($1 !~ /^Tunnel/ && $1 !~ /^No$/) print $1}`;
248
+ export function buildDevbridgeCleanupStateScript() {
249
+ return [
250
+ // #999 anchor doctrine: the export rides the token-refresh init — a
251
+ // standalone export first line is byte-identical to the auth probe's
252
+ // opening line, and first-line readers cannot tell them apart.
253
+ `${DEVBRIDGE_PATH_EXPORT}; DB_KEY=""`,
254
+ // 40100 self-heal: a valid API key can coexist with an expired CLI token;
255
+ // without this refresh `devbridge list` returns 40100 and the cleanup
256
+ // silently skips even though the key is usable. Re-login from
257
+ // keyring/file only — never creates a key here.
258
+ `if command -v hwcloud >/dev/null 2>&1; then`,
259
+ ` DB_KEY=$(hwcloud keyring get HW_DEVBRIDGE_API_KEY 2>&1 || true)`,
260
+ ` case "$DB_KEY" in "devbridge_"*) : ;; *) DB_KEY="";; esac`,
261
+ `fi`,
262
+ `if [ -z "$DB_KEY" ] && [ -s /tmp/hw_api_key ]; then`,
263
+ ` source /tmp/hw_api_key 2>/dev/null || true`,
264
+ ` DB_KEY="\${HW_API_KEY:-}"`,
265
+ `fi`,
266
+ `if [ -n "$DB_KEY" ]; then devbridge auth login --api-key "$DB_KEY" >/dev/null 2>&1 || true; fi`,
267
+ `unset DB_KEY HW_API_KEY 2>/dev/null`,
268
+ `echo "DB_CLEANUP_TUNNELS_BEGIN"`,
269
+ `devbridge list 2>&1 || true`,
270
+ `echo "DB_CLEANUP_TUNNELS_END"`,
271
+ // Port attribution that works for ANY tunnel name: the list table has no
272
+ // port column, so same-port targeting would otherwise key on the
273
+ // auto-name shape `tunnel-<port>-` and miss custom-named tunnels (the
274
+ // remediation's own `devbridge create <name>` flow). Query each tunnel's
275
+ // real port list — the authoritative attribution, with the name-shape and
276
+ // keepalive-URL reads kept as fallbacks when the query is missing. The
277
+ // gsub pair strips BOTH noise postures: the OSC 133 markers (#946) and a
278
+ // CR tail — a single-field port row under CRLF leaves $1 as "8787\r",
279
+ // which fails the digit match and silently empties every TUNNEL_PORTS_
280
+ // line (the attribution collapse the wave's own noise doctrine names).
281
+ `echo "DB_CLEANUP_PORTS_BEGIN"`,
282
+ `for T in $(devbridge list 2>&1 | awk '${DEVBRIDGE_OSC_FILTER}'); do`,
283
+ ` echo "TUNNEL_PORTS_$T=$(devbridge port list "$T" 2>/dev/null | awk '{gsub(/\\033\\]133;C\\007/, ""); gsub(/\\r/, ""); if ($1 ~ /^[0-9]+$/) printf "%s,", $1}')";`,
284
+ `done`,
285
+ `echo "DB_CLEANUP_PORTS_END"`,
286
+ `echo "DB_CLEANUP_HOSTS_BEGIN"`,
287
+ `pgrep -af "devbridge host" 2>&1 || true`,
288
+ `echo "DB_CLEANUP_HOSTS_END"`,
289
+ buildKeepaliveTunnelsReadScript(),
290
+ ].join('\n');
291
+ }
292
+ export function buildDevbridgeCleanupLockScript() {
293
+ return [
294
+ `LOCK=${DEVBRIDGE_LOCK_PATH}`,
295
+ `if mkdir "$LOCK" 2>/dev/null; then echo LOCK_OK; else`,
296
+ ` if find "$LOCK" -maxdepth 0 -mmin +${DEVBRIDGE_LOCK_STALE_MINUTES} 2>/dev/null | grep -q .; then rmdir "$LOCK" 2>/dev/null || true; fi`,
297
+ ` if mkdir "$LOCK" 2>/dev/null; then echo LOCK_OK; else echo LOCK_BUSY; fi`,
298
+ `fi`,
299
+ ].join('\n');
300
+ }
301
+ function cleanupSection(text, name) {
302
+ const m = String(text || '').match(new RegExp(`DB_CLEANUP_${name}_BEGIN\\r?\\n([\\s\\S]*?)DB_CLEANUP_${name}_END`));
303
+ return m ? (m[1] ?? '') : '';
304
+ }
305
+ // The sandbox terminal occasionally needs >10s to open, so every cleanup exec
306
+ // gets a generous budget and one retry on a transient timeout (each op is
307
+ // idempotent — a retried lock/apply/release converges to the same state).
308
+ async function execCleanupWithRetry(workspaceId, script, username, timeoutMs = DEVBRIDGE_CLEANUP_TIMEOUT_MS) {
309
+ let lastError;
310
+ for (let i = 1; i <= 2; i += 1) {
311
+ try {
312
+ return await runOneShot(workspaceId, script, username, timeoutMs);
313
+ }
314
+ catch (error) {
315
+ lastError = error;
316
+ if (i === 2 || !/timeout|websocket/i.test(String(error?.message || '')))
317
+ throw error;
318
+ await new Promise((r) => setTimeout(r, 1000));
319
+ }
320
+ }
321
+ throw lastError;
322
+ }
323
+ // Prune the watchdog roster after a cleanup: deleted IDs AND entries that no
324
+ // longer exist in the management plane (ghost tunnels from earlier delete-all
325
+ // calls would otherwise be re-hosted and renewed forever). "Absent" entries
326
+ // are only pruned when at least one live tunnel is confirmed (or an explicit
327
+ // all-mode reset) — a transient empty list must not wipe the watchdog and
328
+ // silently stop renewals. An empty roster stops the watchdog outright.
329
+ async function syncKeepaliveAfterCleanup(workspaceId, { deletedIds, liveTunnelIds, pruneMissing, username, }) {
330
+ let current;
331
+ try {
332
+ const read = await execCleanupWithRetry(workspaceId, buildKeepaliveTunnelsReadScript(), username, 30000);
333
+ current = parseKeepaliveTunnelsOutput(read.stdout);
334
+ }
335
+ catch {
336
+ return;
337
+ }
338
+ if (!current.length)
339
+ return;
340
+ const deleted = new Set(deletedIds || []);
341
+ const remaining = current.filter((t) => !deleted.has(t.tunnelId) && (!pruneMissing || liveTunnelIds.has(t.tunnelId)));
342
+ if (remaining.length === current.length)
343
+ return;
344
+ if (remaining.length === 0) {
345
+ try {
346
+ await execCleanupWithRetry(workspaceId, `pkill -f "tunnel-keepalive.sh" 2>/dev/null || true; rm -f /tmp/tunnel-keepalive.sh`, username, 30000);
347
+ }
348
+ catch {
349
+ // best-effort: a dead watchdog's leftovers do not need renewal anyway
350
+ }
351
+ return;
352
+ }
353
+ try {
354
+ await installKeepaliveWatchdog(workspaceId, { tunnels: remaining }, username, 30000);
355
+ }
356
+ catch {
357
+ // best-effort: the pre-existing coverage stands; the deleted tunnels may
358
+ // be re-hosted by the watchdog once more
359
+ }
360
+ }
361
+ // The cleanup orchestration: lock → refresh token + read state → plan →
362
+ // apply → sync the watchdog roster → release. A busy/failed lock or a failed
363
+ // list NEVER degrades into deleting anything on a guess.
364
+ export async function cleanupDevbridgeTunnels(workspaceId, { mode = 'stale', samePort = null, maxExtra = 1, username = 'root' } = {}) {
365
+ if (!workspaceId)
366
+ throw new Error('devbridge cleanup: workspace_id is required.');
367
+ if (mode === 'none')
368
+ return { ok: true, skipped: true, deleteIds: [], killPids: [] };
369
+ let lockResult;
370
+ try {
371
+ lockResult = await runOneShot(workspaceId, buildDevbridgeCleanupLockScript(), username, 30000);
372
+ }
373
+ catch {
374
+ return { ok: false, locked: true, deleteIds: [], killPids: [] };
375
+ }
376
+ if (!stripTerminalEscapes(lockResult.stdout).includes('LOCK_OK')) {
377
+ return { ok: false, locked: true, deleteIds: [], killPids: [] };
378
+ }
379
+ try {
380
+ const stateResult = await execCleanupWithRetry(workspaceId, buildDevbridgeCleanupStateScript(), username, 60000);
381
+ const text = stripTerminalEscapes(stateResult.stdout);
382
+ const tunnelSection = cleanupSection(text, 'TUNNELS');
383
+ const listOk = /Tunnel ID|No tunnels found/i.test(tunnelSection);
384
+ if (!listOk) {
385
+ // list/auth/network failed — do not delete or kill anything on a guess.
386
+ return { ok: false, listFailed: true, deleteIds: [], killPids: [] };
387
+ }
388
+ const queriedPorts = parseDevbridgePortQueries(cleanupSection(text, 'PORTS'));
389
+ const tunnels = parseDevbridgeTunnelList(tunnelSection).map((t) => {
390
+ const ports = queriedPorts.get(t.id);
391
+ // The queried port list is authoritative (any tunnel name — the
392
+ // name-shape read misses custom-named tunnels, B-R2-3); without a query
393
+ // result the name-shape/keepalive reads stand.
394
+ return ports && ports.length > 0 ? { ...t, ports, port: ports[0] } : t;
395
+ });
396
+ const hosts = parseDevbridgeHostProcesses(cleanupSection(text, 'HOSTS'));
397
+ // Output-format drift guard: header matched but rows didn't parse, while
398
+ // host processes exist. Never mass-kill hosts on a parse we don't trust.
399
+ if (tunnels.length === 0 && hosts.length > 0 && !/No tunnels found/i.test(tunnelSection)) {
400
+ return { ok: false, listFailed: true, deleteIds: [], killPids: [] };
401
+ }
402
+ const keepalive = parseKeepaliveTunnelsOutput(text);
403
+ const liveTunnelIds = new Set(tunnels.map((t) => t.id));
404
+ const pruneMissing = mode === 'all' || liveTunnelIds.size > 0;
405
+ const plan = planDevbridgeCleanup({ tunnels, hosts, keepalive, mode, samePort, maxExtra });
406
+ if (plan.deleteIds.length === 0 && plan.killPids.length === 0) {
407
+ await syncKeepaliveAfterCleanup(workspaceId, { deletedIds: [], liveTunnelIds, pruneMissing, username });
408
+ return { ok: true, deleteIds: [], killPids: [], tunnelCount: tunnels.length };
409
+ }
410
+ await execCleanupWithRetry(workspaceId, buildDevbridgeCleanupApplyScript(plan), username, DEVBRIDGE_CLEANUP_TIMEOUT_MS);
411
+ await syncKeepaliveAfterCleanup(workspaceId, { deletedIds: plan.deleteIds, liveTunnelIds, pruneMissing, username });
412
+ return { ok: true, ...plan, tunnelCount: tunnels.length };
413
+ }
414
+ finally {
415
+ try {
416
+ await execCleanupWithRetry(workspaceId, `rmdir ${DEVBRIDGE_LOCK_PATH} 2>/dev/null || true`, username, 30000);
417
+ }
418
+ catch {
419
+ // best-effort: the 10-minute stale threshold reclaims an abandoned lock
420
+ }
421
+ }
422
+ }
@@ -1,6 +1,7 @@
1
1
  import { DEVBRIDGE_HOST_EXPIRY_HOURS, validateExpiryHours, validateTunnelPort } from "./devbridge-validation.js";
2
2
  import { runOneShot } from "./devbridge-exec.js";
3
3
  import { gateExposeAuth } from "./devbridge-auth.js";
4
+ import { cleanupDevbridgeTunnels, normalizeCleanupMode } from "./devbridge-cleanup.js";
4
5
  import { buildDevbridgeExposeScript, formatTunnelReachabilityWarning, parseDevbridgeExposeOutput, reportUnusableExpose, } from "./devbridge-expose.js";
5
6
  import { verifyTunnelPersistence } from "./devbridge-verify.js";
6
7
  import { enrollKeepalive } from "./devbridge-keepalive.js";
@@ -19,6 +20,11 @@ import { buildExposeLifetimeNotice } from "../lib/hdkit/sandbox-pool.js";
19
20
  // return ok:false (the gateway itself reports the URL dead), while 502 "bad
20
21
  // gateway" deliberately returns ok:true-with-warning — the tunnel IS alive,
21
22
  // the local service is not; the developer needs the URL to debug the service.
23
+ // The selective-cleanup port (dev's 97c4bc8a wave) changed the retry anatomy:
24
+ // every pre-clean/retry-cleanup runs cleanupDevbridgeTunnels (stale/quota,
25
+ // never delete-all — a global wipe kills other sessions' tunnels), the loop
26
+ // gets up to 4 attempts, and a quota that stays full after the selective
27
+ // cleanups returns the structured devbridge_tunnel_quota_exceeded failure.
22
28
  //
23
29
  // The phases live with their concerns and are imported here: the auth/version
24
30
  // gate from devbridge-auth.ts, the no-URL verdict from devbridge-expose.ts,
@@ -73,7 +79,7 @@ function keepaliveResultField(enrollment) {
73
79
  // tunnelUrl, or HTTP 000) returns ok:false — main returned ok:true with a dead
74
80
  // publicUrl, which contradicted the skill's "the returned publicUrl is the
75
81
  // deployment result" contract.
76
- export async function exposeTunnel(workspaceId, { port, expiryHours, keepalive, poolType, poolContext, keyUpgrade, }, username = 'root', timeoutMs = 90000) {
82
+ export async function exposeTunnel(workspaceId, { port, expiryHours, keepalive, poolType, poolContext, keyUpgrade, cleanupMode, }, username = 'root', timeoutMs = 90000) {
77
83
  if (!workspaceId) {
78
84
  throw new Error('sandbox expose tunnel: workspace_id is required.');
79
85
  }
@@ -84,17 +90,33 @@ export async function exposeTunnel(workspaceId, { port, expiryHours, keepalive,
84
90
  return gate.failure;
85
91
  }
86
92
  const { authMode, version: authVersion } = gate;
93
+ // Selective pre-clean: remove same-port tunnels + orphan records/hosts only.
94
+ // Other ports and keepalive-protected tunnels are preserved. Best-effort —
95
+ // a locked/listFailed cleanup must not block the expose itself.
96
+ const validatedCleanupMode = normalizeCleanupMode(cleanupMode);
97
+ try {
98
+ await cleanupDevbridgeTunnels(workspaceId, {
99
+ mode: validatedCleanupMode,
100
+ samePort: validatedPort,
101
+ username,
102
+ });
103
+ }
104
+ catch {
105
+ // best-effort: cleanup failure must not mask the expose
106
+ }
87
107
  let result;
88
108
  let attempt = 0;
89
- const maxAttempts = 2;
109
+ let lastQuotaCleanup = null;
110
+ const maxAttempts = 4;
90
111
  while (attempt < maxAttempts) {
91
112
  attempt += 1;
92
113
  const exposeScript = buildDevbridgeExposeScript(validatedPort, validatedExpiryHours);
93
114
  // A2 budget guard: the script's worst case is ~63s of bounded waits
94
- // (2s settle + up to 9s URL-extraction + 4×10s probes + 3×5s backoff) plus
95
- // the delete-all round-trip, inside one one-shot exec — a ws-exec timeout
96
- // here must fold into the unreachable envelope (with the outer rebuild
97
- // retry) instead of throwing a raw WebSocketExecError out of the tool.
115
+ // (up to 9s URL-extraction + 4×10s probes + 3×5s backoff) inside one
116
+ // one-shot exec — a ws-exec timeout here must fold into the unreachable
117
+ // envelope (with the outer rebuild retry) instead of throwing a raw
118
+ // WebSocketExecError out of the tool. (The pre-cleans and their execs run
119
+ // outside this budget, each with its own bounded one-shot.)
98
120
  let exposeFailed = false;
99
121
  try {
100
122
  result = await runOneShot(workspaceId, exposeScript, username, timeoutMs);
@@ -104,9 +126,20 @@ export async function exposeTunnel(workspaceId, { port, expiryHours, keepalive,
104
126
  result = { stdout: '', exitCode: 124 };
105
127
  }
106
128
  const parsed = parseDevbridgeExposeOutput(result.stdout);
107
- // 10006 quota exceeded: clean up stale tunnels and retry.
129
+ // 10006 quota exceeded: remove orphan tunnels first, then the oldest
130
+ // non-protected live tunnel (one per retry) until the new tunnel fits.
131
+ // Never touches keepalive-protected tunnels.
108
132
  if (parsed.quotaError && attempt < maxAttempts) {
109
- continue;
133
+ const quotaCleanup = await cleanupDevbridgeTunnels(workspaceId, {
134
+ mode: 'quota',
135
+ samePort: validatedPort,
136
+ maxExtra: 1,
137
+ username,
138
+ }).catch(() => null);
139
+ lastQuotaCleanup = quotaCleanup || lastQuotaCleanup;
140
+ // Kill-only progress frees no tunnel quota; only a deleted record can.
141
+ if (quotaCleanup?.deleteIds?.length)
142
+ continue;
110
143
  }
111
144
  // Unreachable (000 — including a timed-out or failed expose exec), a
112
145
  // migrated-gateway placeholder (host-log marker), or gateway-level tunnel
@@ -119,15 +152,18 @@ export async function exposeTunnel(workspaceId, { port, expiryHours, keepalive,
119
152
  const backendDown = parsed.badGateway === true;
120
153
  if (unreachable || migration || gatewayTunnelError || backendDown) {
121
154
  if (attempt === 1) {
122
- // best-effort cleanup before the retry; the expose script pre-cleans too.
155
+ // Only the same-port tunnel + orphans; other ports/sessions stay
156
+ // untouched. Best-effort — cleanup failure must not mask the expose
157
+ // failure.
123
158
  try {
124
- await runOneShot(workspaceId,
125
- // #999: same first-line export as the expose script (the cleanup
126
- // one-shot is a fresh shell too).
127
- `export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"; pkill -f "devbridge host" 2>/dev/null || true; sleep 2; devbridge delete-all > /dev/null 2>&1 || true`, username, 20000);
159
+ await cleanupDevbridgeTunnels(workspaceId, {
160
+ mode: 'stale',
161
+ samePort: validatedPort,
162
+ username,
163
+ });
128
164
  }
129
165
  catch {
130
- // best-effort: cleanup failure must not mask the expose failure
166
+ // best-effort: the retry still runs
131
167
  }
132
168
  continue;
133
169
  }
@@ -139,8 +175,22 @@ export async function exposeTunnel(workspaceId, { port, expiryHours, keepalive,
139
175
  }
140
176
  }
141
177
  const warnings = [];
142
- if (parsed.quotaError)
143
- warnings.push('DevBridge tunnel quota (10006) hit — stale tunnels were cleaned up and the host was retried.');
178
+ // A still-full quota is an honest structured failure: keepalive-protected
179
+ // tunnels were preserved and the caller learns exactly that, instead of a
180
+ // generic no_tunnel_url that points at the host.
181
+ if (parsed.quotaError && !parsed.tunnelUrl) {
182
+ return {
183
+ ok: false,
184
+ port: validatedPort,
185
+ error: 'DevBridge tunnel quota exceeded (10006) after cleanup. Keepalive-protected tunnels are preserved; ' +
186
+ 'remove unused tunnels or retry with cleanup_mode=all if a full reset is acceptable.',
187
+ error_code: 'devbridge_tunnel_quota_exceeded',
188
+ authMode,
189
+ cleanup: lastQuotaCleanup || undefined,
190
+ warnings: 'tunnel quota (10006) still full after removing orphan/oldest non-protected tunnels',
191
+ hostLog: String(result.stdout ?? '').slice(0, 400),
192
+ };
193
+ }
144
194
  if (parsed.badGateway)
145
195
  warnings.push('Tunnel reachable but the gateway reports "bad gateway" — the local service on the exposed port is not serving.');
146
196
  if (exposeFailed) {
@@ -4,9 +4,11 @@ import { stripTerminalEscapes } from "./sandbox-output.js";
4
4
  import { runOneShot } from "./devbridge-exec.js";
5
5
  // Start (or replace) a devbridge host bound to a single port, extract the public
6
6
  // URL, and health-check it. Mirrors the huaweicloud-sandbox skill's Expose flow:
7
- // pre-clean stale tunnels (quota 10006), start host in background, read the
8
- // port-anchored "Tunnel URL: ..." from /tmp/host.log, curl-check, retry once on
9
- // unreachable.
7
+ // selective pre-clean (devbridge-cleanup.ts) runs BEFORE this script in its
8
+ // own execs, so the script itself never blanket-deletes or globally pkills —
9
+ // those kill other sessions'/ports' tunnels on a shared sandbox. The host starts
10
+ // in background; the port-anchored URL is read from /tmp/host.log and
11
+ // curl-checked, retrying once on unreachable.
10
12
  // The host MUST survive the exec session that started it (#919): setsid detaches
11
13
  // it from the session's process group, `< /dev/null` drops the controlling tty
12
14
  // stdin, and `disown` removes it from the shell's job table — without all three
@@ -19,14 +21,14 @@ export function buildDevbridgeExposeScript(port, expiryHours = DEVBRIDGE_HOST_EX
19
21
  // derived from the shared domain constant, never hardcoded.
20
22
  const domainLiteral = escapeTunnelDomainForRegExp(DEVBRIDGE_TUNNEL_DOMAIN);
21
23
  return [
22
- // #999: the export rides the same first line as the pkill so the fake's
23
- // first-line recognizer (and any reader) sees one stable anchor — the
24
+ // #999: the data-disk PATH export rides the TUNNEL_URL init line — the
24
25
  // one-shot exec shell does NOT inherit the auth probe's PATH, and after
25
26
  // the Layer-3 install + dedup (or a reboot) the only surviving binary
26
- // lives at /workspace/.local/bin.
27
- `export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"; pkill -f "devbridge host" 2>/dev/null || true`,
28
- `sleep 2`,
29
- `devbridge delete-all > /dev/null 2>&1 || true`,
27
+ // lives at /workspace/.local/bin. A standalone export first line would be
28
+ // byte-identical to the auth probe's opening line, which first-line
29
+ // readers cannot tell apart (the anchor doctrine the retired pkill launch
30
+ // line used to carry).
31
+ `export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"; TUNNEL_URL=""`,
30
32
  // #922 (S8): setsid is unavailable on some sandbox images — fall back to a
31
33
  // bare nohup launch so the host still starts; persistence is then judged by
32
34
  // the independent re-verify in exposeTunnel, which emits the 请勿分享 warning
@@ -40,7 +42,8 @@ export function buildDevbridgeExposeScript(port, expiryHours = DEVBRIDGE_HOST_EX
40
42
  // with 3s gaps (0/3/6/9s, early exit) before concluding the host never
41
43
  // logged a URL. Main's A2 uses a flat sleep 6 + single grep, which halves
42
44
  // the window v2 tuned for slow hosts — deliberate divergence, recorded.
43
- `TUNNEL_URL=""`,
45
+ // (TUNNEL_URL was initialized on the script's first line so the PATH
46
+ // export can ride it — the #999 anchor.)
44
47
  `for i in 1 2 3 4; do`,
45
48
  ` TUNNEL_URL=$(grep -oE "https://[A-Za-z0-9_-]+-${port}\\.${domainLiteral}" ${hostLog} | head -1)`,
46
49
  ` [ -n "$TUNNEL_URL" ] && break`,