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
@@ -0,0 +1,509 @@
1
+ import { runOneShot } from './devbridge-exec.ts';
2
+ import { stripTerminalEscapes } from './sandbox-output.ts';
3
+ import { DEVBRIDGE_TUNNEL_ID_PATTERN } from './devbridge-validation.ts';
4
+ import {
5
+ buildKeepaliveTunnelsReadScript,
6
+ installKeepaliveWatchdog,
7
+ parseKeepaliveTunnelsOutput,
8
+ type KeepaliveTunnel,
9
+ } from './devbridge-keepalive.ts';
10
+
11
+ // The DevBridge selective-cleanup family, ported from dev's 1.1.x cleanup wave
12
+ // (97c4bc8a + 7118d61f + 603554d0 + 6100026e + 43fa459e): delete-all is
13
+ // intentionally NOT used in any automated path — it kills other sessions' and
14
+ // other ports' tunnels on a shared sandbox. Cleanup removes only orphan tunnel
15
+ // records/hosts and (for expose) tunnels bound to the same port, preserving
16
+ // other ports, other sessions, and keepalive-protected tunnels. Same-port is
17
+ // the one documented exception: a keepalive-protected tunnel on the target
18
+ // port is replaced, because a port cannot have two tunnels.
19
+ // The lock serializes concurrent cleanups (connect + expose can overlap on one
20
+ // sandbox); the stale threshold (10min) sits above the worst-case hold
21
+ // (state 60x2 + apply 60x2 + sync ~150 + release ≈ 450s) so a second cleanup
22
+ // cannot break a lock that is still legitimately held.
23
+ // v2 divergence from dev (recorded): the state and apply scripts carry the
24
+ // data-disk PATH export on the same first line as a distinguishing token
25
+ // (#999 anchor doctrine — the e2e fake recognizes scripts by first line, and a
26
+ // standalone export first line is byte-identical to the auth probe's opening
27
+ // line; dev has no first-line-recognizing fake, so dev's scripts keep the
28
+ // export standalone).
29
+
30
+ const DEVBRIDGE_PATH_EXPORT = 'export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"';
31
+ const DEVBRIDGE_LOCK_PATH = '/tmp/devbridge-cleanup.lock';
32
+ // Worst-case hold: state 60x2 + apply 60x2 + sync ~150 + release 60 ≈ 450s.
33
+ const DEVBRIDGE_LOCK_STALE_MINUTES = 10;
34
+ const DEVBRIDGE_CLEANUP_TIMEOUT_MS = 60000;
35
+
36
+ export type DevbridgeCleanupMode = 'stale' | 'all' | 'none' | 'quota';
37
+
38
+ export interface DevbridgeTunnelRecord {
39
+ id: string;
40
+ name: string;
41
+ port: number | null;
42
+ expiryText: string;
43
+ expirySeconds: number | null;
44
+ // The authoritative per-tunnel port list (from the state script's
45
+ // `devbridge port list` queries): same-port targeting and host attribution
46
+ // prefer it, falling back to the name-shape/keepalive-URL `port` reads when
47
+ // the query section is absent — a custom-named, non-enrolled tunnel has no
48
+ // name-shape port and no roster URL, so only the query sees it.
49
+ ports?: number[];
50
+ }
51
+
52
+ export interface DevbridgeHostProcess {
53
+ pid: number;
54
+ id: string | null;
55
+ port: number | null;
56
+ }
57
+
58
+ export interface DevbridgeCleanupPlan {
59
+ deleteIds: string[];
60
+ killPids: number[];
61
+ }
62
+
63
+ export interface DevbridgeCleanupOptions {
64
+ mode?: DevbridgeCleanupMode;
65
+ samePort?: number | null;
66
+ maxExtra?: number;
67
+ username?: string;
68
+ }
69
+
70
+ export interface DevbridgeCleanupResult {
71
+ ok: boolean;
72
+ locked?: boolean;
73
+ listFailed?: boolean;
74
+ skipped?: boolean;
75
+ deleteIds: string[];
76
+ killPids: number[];
77
+ tunnelCount?: number;
78
+ }
79
+
80
+ // Tunnel IDs share validateTunnelId's charset — real IDs may contain 0/1/8/9,
81
+ // so parsing must not assume the base32 subset.
82
+ export function normalizeCleanupMode(raw: unknown): 'stale' | 'all' | 'none' {
83
+ return raw === 'stale' || raw === 'all' || raw === 'none' ? raw : 'stale';
84
+ }
85
+
86
+ // Parse `devbridge list` (0.2.x plain table) behind OSC/CRLF noise. The header
87
+ // row is skipped explicitly; data rows start with the tunnel ID. A non-string
88
+ // input reads as empty (the stripTerminalEscapes seam's contract).
89
+ export function parseDevbridgeTunnelList(stdout: unknown): DevbridgeTunnelRecord[] {
90
+ const text = stripTerminalEscapes(stdout);
91
+ const tunnels: DevbridgeTunnelRecord[] = [];
92
+ for (const line of text.split(/\r?\n/)) {
93
+ if (/^\s*Tunnel\s+ID\b/i.test(line)) continue;
94
+ const m = line.match(/^\s*([A-Za-z0-9_-]{4,32})\s+(.+)$/);
95
+ if (!m || !DEVBRIDGE_TUNNEL_ID_PATTERN.test(m[1]!)) continue;
96
+ const id = m[1]!;
97
+ const rest = m[2]!;
98
+ const name = rest.trim().split(/\s{2,}|\t+/)[0] || '';
99
+ const portMatch = rest.match(/tunnel-(\d+)-/);
100
+ // The expiry read is anchored to the expiry column by the trailing Port
101
+ // Count (lookahead, so the matched text stays the clean "N unit"): a
102
+ // description that itself reads like a duration — `1minute`, `5days`,
103
+ // legal because descriptions reject spaces — must not poison the
104
+ // quota-mode oldest-first targeting (interrogate port-pr4 B-F2; dev's
105
+ // 97c4bc8a/43fa459e scan the whole row tail unanchored — deliberate
106
+ // v2 hardening now that the quota wiring makes the expiry load-bearing).
107
+ // A row whose shape no longer matches reads as null → sorts last in quota
108
+ // mode (fail-safe: never deleted on a guess). One arbitration remains:
109
+ // when EVERY candidate reads null the stable sort degenerates to list
110
+ // order and the first listed is deleted — the delete stays confined to
111
+ // live non-protected tunnels (the keepalive invariant holds regardless).
112
+ const expMatch = rest.match(/(\d+)\s*(day|days|hour|hours|minute|minutes)(?=\s+\d+\s*$)/i);
113
+ const unit = expMatch ? expMatch[2]!.toLowerCase() : '';
114
+ const multiplier = { day: 86400, days: 86400, hour: 3600, hours: 3600, minute: 60, minutes: 60 }[unit];
115
+ tunnels.push({
116
+ id,
117
+ name,
118
+ port: portMatch ? Number(portMatch[1]) : null,
119
+ expiryText: expMatch ? expMatch[0] : '',
120
+ expirySeconds: expMatch && multiplier ? Number(expMatch[1]) * multiplier : null,
121
+ });
122
+ }
123
+ return tunnels;
124
+ }
125
+
126
+ // Parse the DB_CLEANUP_PORTS section: one `TUNNEL_PORTS_<id>=<p>,<p>,` line
127
+ // per tunnel (the state script's per-tunnel `devbridge port list` queries).
128
+ // An absent or empty section yields an empty map — the callers then fall back
129
+ // to the name-shape/keepalive-URL port reads.
130
+ export function parseDevbridgePortQueries(stdout: unknown): Map<string, number[]> {
131
+ const text = stripTerminalEscapes(stdout);
132
+ const out = new Map<string, number[]>();
133
+ for (const m of text.matchAll(/^TUNNEL_PORTS_([A-Za-z0-9_-]{4,32})=(.*)$/gm)) {
134
+ const ports = (m[2] ?? '')
135
+ .split(',')
136
+ .map((p) => Number(p))
137
+ .filter((n) => Number.isSafeInteger(n) && n >= 1 && n <= 65535);
138
+ out.set(m[1]!, ports);
139
+ }
140
+ return out;
141
+ }
142
+
143
+ // Parse `pgrep -af "devbridge host"` output. The executable is anchored so a
144
+ // shell wrapper (`bash -c "...devbridge host..."`) is never mistaken for a
145
+ // real host process; the args are tokenized flag-by-flag so an ID can sit in
146
+ // any position. An unparseable host (no id, no port) is dropped — never killed
147
+ // blindly on a guess.
148
+ export function parseDevbridgeHostProcesses(stdout: unknown): DevbridgeHostProcess[] {
149
+ const text = stripTerminalEscapes(stdout);
150
+ const hosts: DevbridgeHostProcess[] = [];
151
+ for (const line of text.split(/\r?\n/)) {
152
+ const m = line.match(/^\s*(\d+)\s+(.*)$/);
153
+ if (!m) continue;
154
+ const execMatch = m[2]!.match(/^(?:\S*\/)?devbridge\s+host\b(.*)$/);
155
+ if (!execMatch) continue;
156
+ const rest = execMatch[1]!.trim();
157
+ const tokens = rest ? rest.split(/\s+/) : [];
158
+ let id: string | null = null;
159
+ let port: number | null = null;
160
+ for (let i = 0; i < tokens.length; i += 1) {
161
+ const token = tokens[i]!;
162
+ if (token === '-p' && /^\d+$/.test(tokens[i + 1] || '')) {
163
+ port = Number(tokens[i + 1]);
164
+ i += 1;
165
+ } else if (token === '-e') {
166
+ i += 1;
167
+ } else if (token.startsWith('-')) {
168
+ // unknown flag: skip it
169
+ } else if (!id && DEVBRIDGE_TUNNEL_ID_PATTERN.test(token) && !/^\d+$/.test(token)) {
170
+ id = token;
171
+ }
172
+ }
173
+ if (!id && port == null) continue;
174
+ hosts.push({ pid: Number(m[1]), id, port });
175
+ }
176
+ return hosts;
177
+ }
178
+
179
+ // Decide which tunnels/hosts to remove.
180
+ // - protected: keepalive TUNNELS entries (never removed unless mode=all or
181
+ // samePort — the one documented exception)
182
+ // - orphan: tunnel record with no live host — removed in stale/quota
183
+ // - orphan host: host process with no matching tunnel record — killed
184
+ // - quota: also removes the oldest non-protected live tunnels (maxExtra per
185
+ // call) until the new tunnel fits
186
+ export function planDevbridgeCleanup({
187
+ tunnels = [],
188
+ hosts = [],
189
+ keepalive = [],
190
+ mode = 'stale',
191
+ samePort = null,
192
+ maxExtra = 1,
193
+ }: DevbridgeCleanupOptions & {
194
+ tunnels?: DevbridgeTunnelRecord[];
195
+ hosts?: DevbridgeHostProcess[];
196
+ keepalive?: KeepaliveTunnel[];
197
+ } = {}): DevbridgeCleanupPlan {
198
+ if (mode === 'none') return { deleteIds: [], killPids: [] };
199
+
200
+ const tunnelIds = new Set(tunnels.map((t) => t.id));
201
+ const protectedIds = new Set(keepalive.map((k) => k.tunnelId).filter(Boolean));
202
+ // Port attribution as a per-tunnel SET: the authoritative port-list queries
203
+ // first (t.ports, any tunnel name), then the name-shape/keepalive-URL single
204
+ // reads. Sets cover multi-port tunnels for every same-port/host match.
205
+ const portsById = new Map<string, number[]>();
206
+ for (const t of tunnels) {
207
+ const set = t.ports && t.ports.length > 0 ? t.ports : t.port != null ? [t.port] : [];
208
+ if (set.length > 0) portsById.set(t.id, set);
209
+ }
210
+ for (const k of keepalive) {
211
+ const m = String(k.url || '').match(/-(\d+)\.devbridge-s2\./);
212
+ if (m && tunnelIds.has(k.tunnelId) && !portsById.has(k.tunnelId)) {
213
+ portsById.set(k.tunnelId, [Number(m[1])]);
214
+ }
215
+ }
216
+ const hasPort = (id: string, port: number) => portsById.get(id)?.includes(port) ?? false;
217
+
218
+ if (mode === 'all') {
219
+ return { deleteIds: [...tunnelIds], killPids: hosts.map((h) => h.pid) };
220
+ }
221
+
222
+ const liveIds = new Set<string>();
223
+ const mappedPids = new Set<number>();
224
+ for (const h of hosts) {
225
+ if (!h.id && h.port == null) continue; // unattributable host: never kill blindly
226
+ if (h.id && tunnelIds.has(h.id)) {
227
+ liveIds.add(h.id);
228
+ mappedPids.add(h.pid);
229
+ } else if (h.port != null) {
230
+ for (const [id] of portsById) {
231
+ if (hasPort(id, h.port)) {
232
+ liveIds.add(id);
233
+ mappedPids.add(h.pid);
234
+ }
235
+ }
236
+ }
237
+ }
238
+
239
+ const killPids = new Set(
240
+ hosts.filter((h) => (h.id || h.port != null) && !mappedPids.has(h.pid)).map((h) => h.pid),
241
+ );
242
+ const samePortIds = samePort == null ? [] : tunnels.filter((t) => hasPort(t.id, samePort)).map((t) => t.id);
243
+ const orphanIds = tunnels.filter((t) => !protectedIds.has(t.id) && !liveIds.has(t.id)).map((t) => t.id);
244
+ const deleteSet = new Set([...orphanIds, ...samePortIds]);
245
+
246
+ if (mode === 'quota') {
247
+ const candidates = tunnels
248
+ .filter((t) => !protectedIds.has(t.id) && !deleteSet.has(t.id) && liveIds.has(t.id))
249
+ .sort((a, b) => (a.expirySeconds ?? Number.MAX_SAFE_INTEGER) - (b.expirySeconds ?? Number.MAX_SAFE_INTEGER));
250
+ for (let i = 0; i < Math.max(0, maxExtra) && i < candidates.length; i += 1) {
251
+ deleteSet.add(candidates[i]!.id);
252
+ }
253
+ }
254
+
255
+ for (const h of hosts) {
256
+ // A host id-attributed to a record we are KEEPING is never a kill target,
257
+ // even when some deleted record's port claim matches the host's port (the
258
+ // structural guard makes the live-host invariant independent of the
259
+ // gateway's one-port-one-record doctrine). A host whose own record IS in
260
+ // the delete set still dies.
261
+ if (h.id && mappedPids.has(h.pid) && !deleteSet.has(h.id)) continue;
262
+ if (h.id && deleteSet.has(h.id)) killPids.add(h.pid);
263
+ else if (h.port != null) {
264
+ // A port-only host (the expose launch form, `devbridge host -p <port>`)
265
+ // cannot be attributed to a specific record. When ANY surviving record
266
+ // still claims the host's port, we cannot prove the host belongs to a
267
+ // deleted record — never kill on that guess; the next cleanup after the
268
+ // survivor is gone (or a same-port expose that replaced every same-port
269
+ // record) still fires.
270
+ const survivorClaimsPort = [...tunnelIds].some((id) => !deleteSet.has(id) && hasPort(id, h.port!));
271
+ if (!survivorClaimsPort && [...deleteSet].some((id) => hasPort(id, h.port!))) killPids.add(h.pid);
272
+ }
273
+ }
274
+
275
+ return { deleteIds: [...deleteSet], killPids: [...killPids] };
276
+ }
277
+
278
+ export function buildDevbridgeCleanupApplyScript({ deleteIds = [], killPids = [] }: Partial<DevbridgeCleanupPlan> = {}): string {
279
+ for (const id of deleteIds) {
280
+ if (!DEVBRIDGE_TUNNEL_ID_PATTERN.test(String(id))) {
281
+ throw new Error(`devbridge cleanup: invalid tunnel id ${JSON.stringify(id)}`);
282
+ }
283
+ }
284
+ for (const pid of killPids) {
285
+ if (!Number.isSafeInteger(pid) || pid <= 0) {
286
+ throw new Error(`devbridge cleanup: invalid pid ${JSON.stringify(pid)}`);
287
+ }
288
+ }
289
+ return [
290
+ // #999 anchor doctrine: the export rides the APPLY marker line so the
291
+ // apply exec can never be misrecognized as the auth probe (a standalone
292
+ // export first line is byte-identical to the probe's).
293
+ `${DEVBRIDGE_PATH_EXPORT}; echo "DB_CLEANUP_APPLY"`,
294
+ // Re-check the process identity before killing: state→apply can take
295
+ // minutes, so a recycled PID must not hit an unrelated process.
296
+ ...killPids.map(
297
+ (pid) => `if ps -p ${pid} -o args= 2>/dev/null | grep -q "devbridge host"; then kill ${pid} >/dev/null 2>&1 || true; fi`,
298
+ ),
299
+ `sleep 1`,
300
+ ...deleteIds.map((id) => `devbridge delete ${id} >/dev/null 2>&1 || true`),
301
+ `echo "DB_CLEANUP_DELETED=${deleteIds.join(',')}"`,
302
+ `echo "DB_CLEANUP_KILLED=${killPids.join(',')}"`,
303
+ ].join('\n');
304
+ }
305
+
306
+ // The candidate-row filter shared by the PORTS query loop: strip the OSC 133
307
+ // shell-integration markers that wrap every line on integration-enabled
308
+ // shells (#946 — the plugin's TS parsers fold stripTerminalEscapes in for
309
+ // exactly this; a raw-ID extraction would hand the CLI glued IDs it rejects),
310
+ // then keep the first token of every non-header row. "No tunnels found." is
311
+ // excluded so an empty world yields zero candidates.
312
+ const DEVBRIDGE_OSC_FILTER = `{gsub(/\\033\\]133;C\\007/, ""); if ($1 !~ /^Tunnel/ && $1 !~ /^No$/) print $1}`;
313
+
314
+ export function buildDevbridgeCleanupStateScript(): string {
315
+ return [
316
+ // #999 anchor doctrine: the export rides the token-refresh init — a
317
+ // standalone export first line is byte-identical to the auth probe's
318
+ // opening line, and first-line readers cannot tell them apart.
319
+ `${DEVBRIDGE_PATH_EXPORT}; DB_KEY=""`,
320
+ // 40100 self-heal: a valid API key can coexist with an expired CLI token;
321
+ // without this refresh `devbridge list` returns 40100 and the cleanup
322
+ // silently skips even though the key is usable. Re-login from
323
+ // keyring/file only — never creates a key here.
324
+ `if command -v hwcloud >/dev/null 2>&1; then`,
325
+ ` DB_KEY=$(hwcloud keyring get HW_DEVBRIDGE_API_KEY 2>&1 || true)`,
326
+ ` case "$DB_KEY" in "devbridge_"*) : ;; *) DB_KEY="";; esac`,
327
+ `fi`,
328
+ `if [ -z "$DB_KEY" ] && [ -s /tmp/hw_api_key ]; then`,
329
+ ` source /tmp/hw_api_key 2>/dev/null || true`,
330
+ ` DB_KEY="\${HW_API_KEY:-}"`,
331
+ `fi`,
332
+ `if [ -n "$DB_KEY" ]; then devbridge auth login --api-key "$DB_KEY" >/dev/null 2>&1 || true; fi`,
333
+ `unset DB_KEY HW_API_KEY 2>/dev/null`,
334
+ `echo "DB_CLEANUP_TUNNELS_BEGIN"`,
335
+ `devbridge list 2>&1 || true`,
336
+ `echo "DB_CLEANUP_TUNNELS_END"`,
337
+ // Port attribution that works for ANY tunnel name: the list table has no
338
+ // port column, so same-port targeting would otherwise key on the
339
+ // auto-name shape `tunnel-<port>-` and miss custom-named tunnels (the
340
+ // remediation's own `devbridge create <name>` flow). Query each tunnel's
341
+ // real port list — the authoritative attribution, with the name-shape and
342
+ // keepalive-URL reads kept as fallbacks when the query is missing. The
343
+ // gsub pair strips BOTH noise postures: the OSC 133 markers (#946) and a
344
+ // CR tail — a single-field port row under CRLF leaves $1 as "8787\r",
345
+ // which fails the digit match and silently empties every TUNNEL_PORTS_
346
+ // line (the attribution collapse the wave's own noise doctrine names).
347
+ `echo "DB_CLEANUP_PORTS_BEGIN"`,
348
+ `for T in $(devbridge list 2>&1 | awk '${DEVBRIDGE_OSC_FILTER}'); do`,
349
+ ` 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}')";`,
350
+ `done`,
351
+ `echo "DB_CLEANUP_PORTS_END"`,
352
+ `echo "DB_CLEANUP_HOSTS_BEGIN"`,
353
+ `pgrep -af "devbridge host" 2>&1 || true`,
354
+ `echo "DB_CLEANUP_HOSTS_END"`,
355
+ buildKeepaliveTunnelsReadScript(),
356
+ ].join('\n');
357
+ }
358
+
359
+ export function buildDevbridgeCleanupLockScript(): string {
360
+ return [
361
+ `LOCK=${DEVBRIDGE_LOCK_PATH}`,
362
+ `if mkdir "$LOCK" 2>/dev/null; then echo LOCK_OK; else`,
363
+ ` if find "$LOCK" -maxdepth 0 -mmin +${DEVBRIDGE_LOCK_STALE_MINUTES} 2>/dev/null | grep -q .; then rmdir "$LOCK" 2>/dev/null || true; fi`,
364
+ ` if mkdir "$LOCK" 2>/dev/null; then echo LOCK_OK; else echo LOCK_BUSY; fi`,
365
+ `fi`,
366
+ ].join('\n');
367
+ }
368
+
369
+ function cleanupSection(text: string, name: string): string {
370
+ const m = String(text || '').match(new RegExp(`DB_CLEANUP_${name}_BEGIN\\r?\\n([\\s\\S]*?)DB_CLEANUP_${name}_END`));
371
+ return m ? (m[1] ?? '') : '';
372
+ }
373
+
374
+ // The sandbox terminal occasionally needs >10s to open, so every cleanup exec
375
+ // gets a generous budget and one retry on a transient timeout (each op is
376
+ // idempotent — a retried lock/apply/release converges to the same state).
377
+ async function execCleanupWithRetry(
378
+ workspaceId: string,
379
+ script: string,
380
+ username: string,
381
+ timeoutMs = DEVBRIDGE_CLEANUP_TIMEOUT_MS,
382
+ ) {
383
+ let lastError: unknown;
384
+ for (let i = 1; i <= 2; i += 1) {
385
+ try {
386
+ return await runOneShot(workspaceId, script, username, timeoutMs);
387
+ } catch (error) {
388
+ lastError = error;
389
+ if (i === 2 || !/timeout|websocket/i.test(String((error as Error)?.message || ''))) throw error;
390
+ await new Promise((r) => setTimeout(r, 1000));
391
+ }
392
+ }
393
+ throw lastError;
394
+ }
395
+
396
+ // Prune the watchdog roster after a cleanup: deleted IDs AND entries that no
397
+ // longer exist in the management plane (ghost tunnels from earlier delete-all
398
+ // calls would otherwise be re-hosted and renewed forever). "Absent" entries
399
+ // are only pruned when at least one live tunnel is confirmed (or an explicit
400
+ // all-mode reset) — a transient empty list must not wipe the watchdog and
401
+ // silently stop renewals. An empty roster stops the watchdog outright.
402
+ async function syncKeepaliveAfterCleanup(
403
+ workspaceId: string,
404
+ {
405
+ deletedIds,
406
+ liveTunnelIds,
407
+ pruneMissing,
408
+ username,
409
+ }: { deletedIds: string[]; liveTunnelIds: Set<string>; pruneMissing: boolean; username: string },
410
+ ): Promise<void> {
411
+ let current: KeepaliveTunnel[];
412
+ try {
413
+ const read = await execCleanupWithRetry(workspaceId, buildKeepaliveTunnelsReadScript(), username, 30000);
414
+ current = parseKeepaliveTunnelsOutput(read.stdout);
415
+ } catch {
416
+ return;
417
+ }
418
+ if (!current.length) return;
419
+ const deleted = new Set(deletedIds || []);
420
+ const remaining = current.filter((t) => !deleted.has(t.tunnelId) && (!pruneMissing || liveTunnelIds.has(t.tunnelId)));
421
+ if (remaining.length === current.length) return;
422
+ if (remaining.length === 0) {
423
+ try {
424
+ await execCleanupWithRetry(
425
+ workspaceId,
426
+ `pkill -f "tunnel-keepalive.sh" 2>/dev/null || true; rm -f /tmp/tunnel-keepalive.sh`,
427
+ username,
428
+ 30000,
429
+ );
430
+ } catch {
431
+ // best-effort: a dead watchdog's leftovers do not need renewal anyway
432
+ }
433
+ return;
434
+ }
435
+ try {
436
+ await installKeepaliveWatchdog(workspaceId, { tunnels: remaining }, username, 30000);
437
+ } catch {
438
+ // best-effort: the pre-existing coverage stands; the deleted tunnels may
439
+ // be re-hosted by the watchdog once more
440
+ }
441
+ }
442
+
443
+ // The cleanup orchestration: lock → refresh token + read state → plan →
444
+ // apply → sync the watchdog roster → release. A busy/failed lock or a failed
445
+ // list NEVER degrades into deleting anything on a guess.
446
+ export async function cleanupDevbridgeTunnels(
447
+ workspaceId: string,
448
+ { mode = 'stale', samePort = null, maxExtra = 1, username = 'root' }: DevbridgeCleanupOptions = {},
449
+ ): Promise<DevbridgeCleanupResult> {
450
+ if (!workspaceId) throw new Error('devbridge cleanup: workspace_id is required.');
451
+ if (mode === 'none') return { ok: true, skipped: true, deleteIds: [], killPids: [] };
452
+
453
+ let lockResult;
454
+ try {
455
+ lockResult = await runOneShot(workspaceId, buildDevbridgeCleanupLockScript(), username, 30000);
456
+ } catch {
457
+ return { ok: false, locked: true, deleteIds: [], killPids: [] };
458
+ }
459
+ if (!stripTerminalEscapes(lockResult.stdout).includes('LOCK_OK')) {
460
+ return { ok: false, locked: true, deleteIds: [], killPids: [] };
461
+ }
462
+
463
+ try {
464
+ const stateResult = await execCleanupWithRetry(workspaceId, buildDevbridgeCleanupStateScript(), username, 60000);
465
+ const text = stripTerminalEscapes(stateResult.stdout);
466
+ const tunnelSection = cleanupSection(text, 'TUNNELS');
467
+ const listOk = /Tunnel ID|No tunnels found/i.test(tunnelSection);
468
+ if (!listOk) {
469
+ // list/auth/network failed — do not delete or kill anything on a guess.
470
+ return { ok: false, listFailed: true, deleteIds: [], killPids: [] };
471
+ }
472
+ const queriedPorts = parseDevbridgePortQueries(cleanupSection(text, 'PORTS'));
473
+ const tunnels = parseDevbridgeTunnelList(tunnelSection).map((t) => {
474
+ const ports = queriedPorts.get(t.id);
475
+ // The queried port list is authoritative (any tunnel name — the
476
+ // name-shape read misses custom-named tunnels, B-R2-3); without a query
477
+ // result the name-shape/keepalive reads stand.
478
+ return ports && ports.length > 0 ? { ...t, ports, port: ports[0]! } : t;
479
+ });
480
+ const hosts = parseDevbridgeHostProcesses(cleanupSection(text, 'HOSTS'));
481
+ // Output-format drift guard: header matched but rows didn't parse, while
482
+ // host processes exist. Never mass-kill hosts on a parse we don't trust.
483
+ if (tunnels.length === 0 && hosts.length > 0 && !/No tunnels found/i.test(tunnelSection)) {
484
+ return { ok: false, listFailed: true, deleteIds: [], killPids: [] };
485
+ }
486
+ const keepalive = parseKeepaliveTunnelsOutput(text);
487
+ const liveTunnelIds = new Set(tunnels.map((t) => t.id));
488
+ const pruneMissing = mode === 'all' || liveTunnelIds.size > 0;
489
+ const plan = planDevbridgeCleanup({ tunnels, hosts, keepalive, mode, samePort, maxExtra });
490
+ if (plan.deleteIds.length === 0 && plan.killPids.length === 0) {
491
+ await syncKeepaliveAfterCleanup(workspaceId, { deletedIds: [], liveTunnelIds, pruneMissing, username });
492
+ return { ok: true, deleteIds: [], killPids: [], tunnelCount: tunnels.length };
493
+ }
494
+ await execCleanupWithRetry(
495
+ workspaceId,
496
+ buildDevbridgeCleanupApplyScript(plan),
497
+ username,
498
+ DEVBRIDGE_CLEANUP_TIMEOUT_MS,
499
+ );
500
+ await syncKeepaliveAfterCleanup(workspaceId, { deletedIds: plan.deleteIds, liveTunnelIds, pruneMissing, username });
501
+ return { ok: true, ...plan, tunnelCount: tunnels.length };
502
+ } finally {
503
+ try {
504
+ await execCleanupWithRetry(workspaceId, `rmdir ${DEVBRIDGE_LOCK_PATH} 2>/dev/null || true`, username, 30000);
505
+ } catch {
506
+ // best-effort: the 10-minute stale threshold reclaims an abandoned lock
507
+ }
508
+ }
509
+ }
@@ -1,6 +1,7 @@
1
1
  import { DEVBRIDGE_HOST_EXPIRY_HOURS, validateExpiryHours, validateTunnelPort } from './devbridge-validation.ts';
2
2
  import { runOneShot, type OneShotResult } from './devbridge-exec.ts';
3
3
  import { gateExposeAuth, type DevbridgeAuthGateOptions } from './devbridge-auth.ts';
4
+ import { cleanupDevbridgeTunnels, normalizeCleanupMode, type DevbridgeCleanupResult } from './devbridge-cleanup.ts';
4
5
  import {
5
6
  buildDevbridgeExposeScript,
6
7
  formatTunnelReachabilityWarning,
@@ -27,6 +28,11 @@ import { buildExposeLifetimeNotice, type PoolContext } from '../lib/hdkit/sandbo
27
28
  // return ok:false (the gateway itself reports the URL dead), while 502 "bad
28
29
  // gateway" deliberately returns ok:true-with-warning — the tunnel IS alive,
29
30
  // the local service is not; the developer needs the URL to debug the service.
31
+ // The selective-cleanup port (dev's 97c4bc8a wave) changed the retry anatomy:
32
+ // every pre-clean/retry-cleanup runs cleanupDevbridgeTunnels (stale/quota,
33
+ // never delete-all — a global wipe kills other sessions' tunnels), the loop
34
+ // gets up to 4 attempts, and a quota that stays full after the selective
35
+ // cleanups returns the structured devbridge_tunnel_quota_exceeded failure.
30
36
  //
31
37
  // The phases live with their concerns and are imported here: the auth/version
32
38
  // gate from devbridge-auth.ts, the no-URL verdict from devbridge-expose.ts,
@@ -100,6 +106,7 @@ export async function exposeTunnel(
100
106
  poolType,
101
107
  poolContext,
102
108
  keyUpgrade,
109
+ cleanupMode,
103
110
  }: {
104
111
  port?: number | string;
105
112
  expiryHours?: number;
@@ -114,6 +121,11 @@ export async function exposeTunnel(
114
121
  // ≠ 沙箱存活期);未传/无缓存(自定义模板)时结果不带 sandboxLifetime 字段。
115
122
  poolContext?: PoolContext;
116
123
  keyUpgrade?: DevbridgeAuthGateOptions['keyUpgrade'];
124
+ // Selective pre-clean before the expose loop (stale default): same-port
125
+ // tunnels + orphan records/hosts are removed; other ports, other sessions
126
+ // and keepalive-protected tunnels are preserved. 'all' is a manual full
127
+ // reset; 'none' skips (a stale same-port host can then conflict).
128
+ cleanupMode?: unknown;
117
129
  },
118
130
  username = 'root',
119
131
  timeoutMs = 90000,
@@ -130,17 +142,33 @@ export async function exposeTunnel(
130
142
  }
131
143
  const { authMode, version: authVersion } = gate;
132
144
 
145
+ // Selective pre-clean: remove same-port tunnels + orphan records/hosts only.
146
+ // Other ports and keepalive-protected tunnels are preserved. Best-effort —
147
+ // a locked/listFailed cleanup must not block the expose itself.
148
+ const validatedCleanupMode = normalizeCleanupMode(cleanupMode);
149
+ try {
150
+ await cleanupDevbridgeTunnels(workspaceId, {
151
+ mode: validatedCleanupMode,
152
+ samePort: validatedPort,
153
+ username,
154
+ });
155
+ } catch {
156
+ // best-effort: cleanup failure must not mask the expose
157
+ }
158
+
133
159
  let result: OneShotResult | undefined;
134
160
  let attempt = 0;
135
- const maxAttempts = 2;
161
+ let lastQuotaCleanup: DevbridgeCleanupResult | null = null;
162
+ const maxAttempts = 4;
136
163
  while (attempt < maxAttempts) {
137
164
  attempt += 1;
138
165
  const exposeScript = buildDevbridgeExposeScript(validatedPort, validatedExpiryHours);
139
166
  // A2 budget guard: the script's worst case is ~63s of bounded waits
140
- // (2s settle + up to 9s URL-extraction + 4×10s probes + 3×5s backoff) plus
141
- // the delete-all round-trip, inside one one-shot exec — a ws-exec timeout
142
- // here must fold into the unreachable envelope (with the outer rebuild
143
- // retry) instead of throwing a raw WebSocketExecError out of the tool.
167
+ // (up to 9s URL-extraction + 4×10s probes + 3×5s backoff) inside one
168
+ // one-shot exec — a ws-exec timeout here must fold into the unreachable
169
+ // envelope (with the outer rebuild retry) instead of throwing a raw
170
+ // WebSocketExecError out of the tool. (The pre-cleans and their execs run
171
+ // outside this budget, each with its own bounded one-shot.)
144
172
  let exposeFailed = false;
145
173
  try {
146
174
  result = await runOneShot(workspaceId, exposeScript, username, timeoutMs);
@@ -150,9 +178,19 @@ export async function exposeTunnel(
150
178
  }
151
179
  const parsed = parseDevbridgeExposeOutput(result.stdout);
152
180
 
153
- // 10006 quota exceeded: clean up stale tunnels and retry.
181
+ // 10006 quota exceeded: remove orphan tunnels first, then the oldest
182
+ // non-protected live tunnel (one per retry) until the new tunnel fits.
183
+ // Never touches keepalive-protected tunnels.
154
184
  if (parsed.quotaError && attempt < maxAttempts) {
155
- continue;
185
+ const quotaCleanup = await cleanupDevbridgeTunnels(workspaceId, {
186
+ mode: 'quota',
187
+ samePort: validatedPort,
188
+ maxExtra: 1,
189
+ username,
190
+ }).catch(() => null);
191
+ lastQuotaCleanup = quotaCleanup || lastQuotaCleanup;
192
+ // Kill-only progress frees no tunnel quota; only a deleted record can.
193
+ if (quotaCleanup?.deleteIds?.length) continue;
156
194
  }
157
195
  // Unreachable (000 — including a timed-out or failed expose exec), a
158
196
  // migrated-gateway placeholder (host-log marker), or gateway-level tunnel
@@ -165,18 +203,17 @@ export async function exposeTunnel(
165
203
  const backendDown = parsed.badGateway === true;
166
204
  if (unreachable || migration || gatewayTunnelError || backendDown) {
167
205
  if (attempt === 1) {
168
- // best-effort cleanup before the retry; the expose script pre-cleans too.
206
+ // Only the same-port tunnel + orphans; other ports/sessions stay
207
+ // untouched. Best-effort — cleanup failure must not mask the expose
208
+ // failure.
169
209
  try {
170
- await runOneShot(
171
- workspaceId,
172
- // #999: same first-line export as the expose script (the cleanup
173
- // one-shot is a fresh shell too).
174
- `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`,
210
+ await cleanupDevbridgeTunnels(workspaceId, {
211
+ mode: 'stale',
212
+ samePort: validatedPort,
175
213
  username,
176
- 20000,
177
- );
214
+ });
178
215
  } catch {
179
- // best-effort: cleanup failure must not mask the expose failure
216
+ // best-effort: the retry still runs
180
217
  }
181
218
  continue;
182
219
  }
@@ -189,8 +226,23 @@ export async function exposeTunnel(
189
226
  }
190
227
 
191
228
  const warnings: string[] = [];
192
- if (parsed.quotaError)
193
- warnings.push('DevBridge tunnel quota (10006) hit — stale tunnels were cleaned up and the host was retried.');
229
+ // A still-full quota is an honest structured failure: keepalive-protected
230
+ // tunnels were preserved and the caller learns exactly that, instead of a
231
+ // generic no_tunnel_url that points at the host.
232
+ if (parsed.quotaError && !parsed.tunnelUrl) {
233
+ return {
234
+ ok: false,
235
+ port: validatedPort,
236
+ error:
237
+ 'DevBridge tunnel quota exceeded (10006) after cleanup. Keepalive-protected tunnels are preserved; ' +
238
+ 'remove unused tunnels or retry with cleanup_mode=all if a full reset is acceptable.',
239
+ error_code: 'devbridge_tunnel_quota_exceeded',
240
+ authMode,
241
+ cleanup: lastQuotaCleanup || undefined,
242
+ warnings: 'tunnel quota (10006) still full after removing orphan/oldest non-protected tunnels',
243
+ hostLog: String(result.stdout ?? '').slice(0, 400),
244
+ };
245
+ }
194
246
  if (parsed.badGateway)
195
247
  warnings.push(
196
248
  'Tunnel reachable but the gateway reports "bad gateway" — the local service on the exposed port is not serving.',