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
@@ -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`,
@@ -47,6 +47,7 @@ export function buildDevbridgeKeepaliveScript(tunnels) {
47
47
  const body = [
48
48
  `#!/bin/bash`,
49
49
  `export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"`,
50
+ `export DBUS_SESSION_BUS_ADDRESS="\${DBUS_SESSION_BUS_ADDRESS:-unix:path=/run/dbus-session}"`,
50
51
  `# entries: tunnelId:url (URLs are stable — tunnel IDs never change)`,
51
52
  `TUNNELS="${entries}"`,
52
53
  `declare -A LAST_RENEW`,
@@ -65,6 +66,29 @@ export function buildDevbridgeKeepaliveScript(tunnels) {
65
66
  ` echo "$TS renew $ID ok (${DEVBRIDGE_RENEW_HOURS}h)" >> /tmp/tunnel-keepalive.log`,
66
67
  ` else`,
67
68
  ` echo "$TS renew $ID FAILED: $(head -1 /tmp/keepalive-last-update.log)" >> /tmp/tunnel-keepalive.log`,
69
+ // Self-heal (bde7ae56): a valid key can coexist with an expired CLI token
70
+ // (renew returns 40100 while auth status still prints Logged in) —
71
+ // re-login from keyring/file (never create a key) and retry once now;
72
+ // the next tick retries normally if even that fails.
73
+ ` DB_KEY=""`,
74
+ ` if command -v hwcloud >/dev/null 2>&1; then`,
75
+ ` DB_KEY=$(hwcloud keyring get HW_DEVBRIDGE_API_KEY 2>&1 || true)`,
76
+ ` case "$DB_KEY" in "devbridge_"*) : ;; *) DB_KEY="";; esac`,
77
+ ` fi`,
78
+ ` if [ -z "$DB_KEY" ] && [ -s /tmp/hw_api_key ]; then`,
79
+ ` source /tmp/hw_api_key 2>/dev/null || true`,
80
+ ` DB_KEY="\${HW_API_KEY:-}"`,
81
+ ` fi`,
82
+ ` if [ -n "$DB_KEY" ] && devbridge auth login --api-key "$DB_KEY" >/tmp/keepalive-auth.log 2>&1; then`,
83
+ ` if devbridge update "$ID" -e ${DEVBRIDGE_RENEW_HOURS} > /tmp/keepalive-last-update.log 2>&1; then`,
84
+ ` echo "$TS renew $ID ok after re-login (${DEVBRIDGE_RENEW_HOURS}h)" >> /tmp/tunnel-keepalive.log`,
85
+ ` else`,
86
+ ` echo "$TS renew $ID FAILED after re-login: $(head -1 /tmp/keepalive-last-update.log)" >> /tmp/tunnel-keepalive.log`,
87
+ ` fi`,
88
+ ` else`,
89
+ ` echo "$TS renew $ID AUTH_FAILED: no usable key; next expose_tunnel will auto-create" >> /tmp/tunnel-keepalive.log`,
90
+ ` fi`,
91
+ ` unset DB_KEY HW_API_KEY 2>/dev/null`,
68
92
  ` fi`,
69
93
  ` LAST_RENEW[$ID]=$NOW`,
70
94
  ` fi`,
@@ -110,7 +134,14 @@ export function buildKeepaliveTunnelsReadScript() {
110
134
  ].join('\n');
111
135
  }
112
136
  // Parse the raw stdout of buildKeepaliveTunnelsReadScript. Empty output (no
113
- // watchdog installed yet) yields [].
137
+ // watchdog installed yet) yields []. Entries are the generated three-field
138
+ // `id:url:port` form (plus the two-field legacy form): the tunnel URL's last
139
+ // segment is the domain, so a trailing `:<digits>` (or the empty port field's
140
+ // bare `:`) is never part of the URL — strip every tail, including the legacy
141
+ // double tails the pre-fix round trip wrote. A kept tail mangles the watchdog's
142
+ // health-check target and grows one field per roster rewrite (interrogate
143
+ // port-pr4 A-F1; the parse shape predates this port — the fix lands with the
144
+ // cleanup sync, the second roster-rewrite path, so both round trips are stable).
114
145
  export function parseKeepaliveTunnelsOutput(stdout) {
115
146
  const text = stripTerminalEscapes(stdout);
116
147
  const m = text.match(/^DB_KEEPALIVE_TUNNELS=(.*)$/m);
@@ -121,7 +152,16 @@ export function parseKeepaliveTunnelsOutput(stdout) {
121
152
  .split(/\s+/)
122
153
  .map((entry) => {
123
154
  const i = entry.indexOf(':');
124
- return i > 0 ? { tunnelId: entry.slice(0, i), url: entry.slice(i + 1) } : null;
155
+ if (i <= 0)
156
+ return null;
157
+ let url = entry.slice(i + 1);
158
+ // Strip every generated/legacy tail in one converging loop: digit tails
159
+ // and bare colons alike (the pre-fix shapes could leave one behind for a
160
+ // generation — a `:18082:` tail kept `:18082` after a single pass).
161
+ while (/:$/.test(url) || /:\d+$/.test(url)) {
162
+ url = url.slice(0, url.lastIndexOf(':'));
163
+ }
164
+ return { tunnelId: entry.slice(0, i), url };
125
165
  })
126
166
  .filter((t) => t !== null);
127
167
  }
@@ -17,6 +17,7 @@ import { join, dirname } from 'node:path';
17
17
  import { homedir } from 'node:os';
18
18
  import { createHash } from 'node:crypto';
19
19
  import { hdkitCreateApiKey, hdkitListApiKeys, hdkitDeleteApiKey } from "../lib/hdkit/hdkitservice-api.js";
20
+ import { isVersionGateError } from "../lib/hdkit/hdkit-gate.js";
20
21
  import { getCredentials } from "../lib/hdkit/hwlink-api.js";
21
22
  const POOL_KEY_NAMES = {
22
23
  ephemeral: 'devkit-ephemeral',
@@ -107,8 +108,11 @@ export async function ensureDevbridgeKey(poolType) {
107
108
  await hdkitDeleteApiKey(orphan['id']);
108
109
  }
109
110
  }
110
- catch {
111
- // list/delete 失败不阻断创建(可能权限或网络问题,继续尝试创建)
111
+ catch (error) {
112
+ // 409 版本门禁必须穿透(relay 侧按出口折叠的前提):吞掉它会被后续 create
113
+ // 失败的泛化降级掩盖成凭证误诊;其余 list/delete 失败仍不阻断创建
114
+ if (isVersionGateError(error))
115
+ throw error;
112
116
  }
113
117
  // 3. 创建
114
118
  const created = await hdkitCreateApiKey(name, 'devbridge');
@@ -142,7 +146,11 @@ export async function listKeysForQuotaHint() {
142
146
  lastUsed: typeof k['last_used_at'] === 'string' ? k['last_used_at'] : '',
143
147
  }));
144
148
  }
145
- catch {
149
+ catch (error) {
150
+ // 409 门禁必须穿透:配额信封拿着读不出来的 currentKeys 教用户清 key 是误诊
151
+ // (devbridge-auth 侧按出口折叠);其余读取失败仍降级为空清单
152
+ if (isVersionGateError(error))
153
+ throw error;
146
154
  return [];
147
155
  }
148
156
  }
@@ -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
@@ -42,6 +43,11 @@ export { buildDevbridgeRenewScript, parseDevbridgeRenewOutput, renewTunnel } fro
42
43
  // The keepalive watchdog family lives in devbridge-keepalive.ts; re-exported
43
44
  // as the public face.
44
45
  export { buildDevbridgeKeepaliveScript, buildKeepaliveTunnelsReadScript, installKeepaliveWatchdog, mergeKeepaliveTunnels, parseKeepaliveTunnelsOutput, } from "./devbridge-keepalive.js";
46
+ // The selective-cleanup family (parsers, cleanup plan, lock/state/apply
47
+ // scripts, the cleanup orchestration) lives in devbridge-cleanup.ts;
48
+ // re-exported as the public face (the sandbox pack's handlers and the tests
49
+ // import these names here).
50
+ export { buildDevbridgeCleanupApplyScript, buildDevbridgeCleanupLockScript, buildDevbridgeCleanupStateScript, cleanupDevbridgeTunnels, normalizeCleanupMode, parseDevbridgeHostProcesses, parseDevbridgePortQueries, parseDevbridgeTunnelList, planDevbridgeCleanup, } from "./devbridge-cleanup.js";
45
51
  // The exposeTunnel orchestration lives in devbridge-expose-flow.ts;
46
52
  // re-exported as the public face (the sandbox pack's handlers-tunnel.ts and
47
53
  // the test harness import it here).
@@ -35,13 +35,22 @@ export function validateExpiryHours(hours) {
35
35
  }
36
36
  return n;
37
37
  }
38
+ // The tunnel-ID charset as one shared pattern: validateTunnelId guards shell
39
+ // splices with it, and the selective-cleanup parsers (devbridge-cleanup.ts)
40
+ // recognize real IDs with it. The real CLI accepts only lowercase base32
41
+ // (a-z2-7, length 8); this superset over-accepts by design — parsing and
42
+ // shell-splice guarding fail SAFE on junk (the CLI's own validation rejects
43
+ // any phantom delete; a phantom matching a real hostless tunnel is a
44
+ // documented orphan-delete), while a strict pattern would silently DROP real
45
+ // IDs on any charset drift.
46
+ export const DEVBRIDGE_TUNNEL_ID_PATTERN = /^[A-Za-z0-9_-]{4,32}$/;
38
47
  // Validate a DevBridge tunnel ID destined for shell interpolation in
39
48
  // `devbridge update <id>` / `devbridge host <id>` / pgrep patterns. IDs are
40
49
  // short lowercase base36 tokens (e.g. nv2dvv6w, kag7rozs); the strict charset
41
50
  // keeps shell metacharacters out of the splice.
42
51
  export function validateTunnelId(tunnelId) {
43
52
  const id = asText(tunnelId ?? '');
44
- if (!/^[A-Za-z0-9_-]{4,32}$/.test(id)) {
53
+ if (!DEVBRIDGE_TUNNEL_ID_PATTERN.test(id)) {
45
54
  throw new Error(`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).`);
46
55
  }
47
56
  return id;
@@ -0,0 +1,244 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { asText } from "../lib/as-text.js";
3
+ import { stripTerminalEscapes } from "./sandbox-output.js";
4
+ // The async sandbox-task family — the claim protocol as formalized and
5
+ // TLC-verified (the HwExecClaim spec, 9/9 invariants). One directory per
6
+ // task, /tmp/.hwexec/<taskId>/, whose files ARE the state:
7
+ // claim — the start script's O_EXCL create; existence means some start
8
+ // already won the spawn right, so a retry is structurally
9
+ // unable to spawn a second copy.
10
+ // cmd — the original command line (diagnostics only; poll never
11
+ // reads it; a retry rewrite is harmless).
12
+ // launched — the wrapper's first-action guard file, separating never
13
+ // (claimed, never spawned) from lost (ran, died without
14
+ // writing a status).
15
+ // log — the command's stdout+stderr append stream.
16
+ // status — the terminal `exit:<n>` line; the write is non-atomic, so a
17
+ // torn read must converge to running — the field is matched by
18
+ // CONTENT (full `exit:<digits>` line), never by existence.
19
+ // The claim's deliberate trade: an exec that dies between claim and spawn
20
+ // leaves a task that never runs, and no same-id retry can recover it — the
21
+ // poll's `never` verdict is exactly that state, and the teaching is a NEW
22
+ // task_id. The guard-file variant (check `launched` before spawning — the
23
+ // HwExecGuard3 spec) is falsified by OneCopyRunning (Start, then a retry
24
+ // inside the unconfirmed window, runs two copies); never reintroduce any
25
+ // pre-spawn launched check — the O_EXCL claim create is the only spawn
26
+ // arbiter, and the elif after it only classifies the create failure.
27
+ // Server-side truth root, one directory per task. /tmp is session-scoped: a
28
+ // sandbox reboot wipes it — the poll's lost/unknown split models exactly
29
+ // that boundary.
30
+ export const HWEXEC_TASK_ROOT = '/tmp/.hwexec';
31
+ // Task ids are path- and pgrep-safe by charset (lowercase, digits, hyphen,
32
+ // 1-64 chars): they ride file paths AND the pgrep -f pattern, so no shell
33
+ // metacharacter can ever travel through one.
34
+ export const HWEXEC_TASK_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,63}$/;
35
+ // The poll's bounded wait: sleep-2 intervals checking the status file; the
36
+ // loop count is folded from wait_ms.
37
+ export const HWEXEC_WAIT_STEP_MS = 2000;
38
+ // The wait_ms ceiling (the zod text and the validator both read this).
39
+ export const HWEXEC_WAIT_MS_MAX = 60000;
40
+ // Default log-tail size for a poll (and the dup receipt's verdict poll).
41
+ export const HWEXEC_TAIL_BYTES_DEFAULT = 4096;
42
+ // Log-tail ceiling: the tail rides the poll exec's stdout, and the exec
43
+ // channel is fragile for large single payloads — it stays bounded.
44
+ export const HWEXEC_TAIL_BYTES_MAX = 65536;
45
+ // The poll exec's headroom over wait_ms (the devbridge-expose-flow A2
46
+ // budget doctrine): the bounded wait plus the field round-trips must sit
47
+ // INSIDE the ws-exec timeout, so the effective timeout folds to
48
+ // wait_ms + 15s and the wait loop can never die as a mid-exec timeout.
49
+ export const HWEXEC_POLL_HEADROOM_MS = 15000;
50
+ export function hwexecTaskDir(taskId) {
51
+ return `${HWEXEC_TASK_ROOT}/${taskId}`;
52
+ }
53
+ // Validate a task id destined for path and pgrep-pattern interpolation.
54
+ export function validateHwexecTaskId(id) {
55
+ const value = asText(id ?? '');
56
+ if (!HWEXEC_TASK_ID_PATTERN.test(value)) {
57
+ throw new Error(`sandbox exec: invalid task_id ${JSON.stringify(value.slice(0, 40))}. ` +
58
+ `Expected ${HWEXEC_TASK_ID_PATTERN.source} (path- and pgrep-safe); omit task_id to let the tool generate one.`);
59
+ }
60
+ return value;
61
+ }
62
+ // Generate a task id (t-<12 hex>). Collision resistance within one sandbox
63
+ // session is the only requirement — ids scope per-task directories.
64
+ export function generateHwexecTaskId() {
65
+ return `t-${randomBytes(6).toString('hex')}`;
66
+ }
67
+ // Escape a command line for embedding inside a shell single-quoted span —
68
+ // both the cmd-file write and the wrapper's sh -c splice the command this
69
+ // way (close quote, escaped quote, reopen).
70
+ export function escapeHwexecCommand(command) {
71
+ return command.replaceAll("'", "'\\''");
72
+ }
73
+ // The start script: claim → spawn → receipt, in that line order. The O_EXCL
74
+ // claim create is the only spawn arbiter; the elif only classifies the
75
+ // create failure (dup vs error) and never gates the spawn. The wrapper
76
+ // writes the launched guard as its FIRST action, appends the command's
77
+ // stdout+stderr to the log, then commits `exit:<n>`.
78
+ export function buildHwexecStartScript(taskId, command) {
79
+ const id = validateHwexecTaskId(taskId);
80
+ const dir = hwexecTaskDir(id);
81
+ const escaped = escapeHwexecCommand(command);
82
+ // The wrapper's sh -c does not inherit the outer shell's variables, and
83
+ // poll liveness is detected by pgrep -f matching the literal
84
+ // <dir>/launched path inside the wrapper's own command line — so the
85
+ // wrapper's paths are inlined, never $D-expanded.
86
+ const wrapper = `: > "${dir}/launched"; ( ${escaped} ) >> "${dir}/log" 2>&1; echo "exit:$?" > "${dir}/status"`;
87
+ return [
88
+ `D=${dir}`,
89
+ `mkdir -p "$D"`,
90
+ `printf '%s\\n' '${escaped}' > "$D/cmd"`,
91
+ `if (set -C; : > "$D/claim") 2>/dev/null; then`,
92
+ // #919/#922 (the devbridge-expose trio): setsid detaches the process
93
+ // group so the task survives the exec session's teardown, < /dev/null
94
+ // drops the controlling tty, disown removes the job-table entry. A
95
+ // missing setsid falls back to a bare nohup launch — the task still
96
+ // starts; disown is guarded so shells without the builtin survive.
97
+ ` 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`,
98
+ ` disown 2>/dev/null || true`,
99
+ ` echo "HW_STARTED=${id}"`,
100
+ `elif [ -f "$D/claim" ]; then`,
101
+ ` echo "HW_DUP=${id}"`,
102
+ `else`,
103
+ ` echo "HW_CLAIM_ERROR=1"`,
104
+ `fi`,
105
+ ].join('\n');
106
+ }
107
+ // Fold wait_ms into the bounded-wait loop count. Floor division keeps the
108
+ // total sleep ≤ wait_ms — the budget the exec timeout is folded from.
109
+ export function hwexecPollLoops(waitMs) {
110
+ return Math.floor(waitMs / HWEXEC_WAIT_STEP_MS);
111
+ }
112
+ // Validate wait_ms (0-60000, integer; the default is 0 — no in-poll wait).
113
+ export function validateHwexecWaitMs(waitMs) {
114
+ const n = Number(waitMs ?? 0);
115
+ if (!Number.isSafeInteger(n) || n < 0 || n > HWEXEC_WAIT_MS_MAX) {
116
+ throw new Error(`sandbox exec poll: invalid wait_ms ${JSON.stringify(waitMs)}. ` +
117
+ `Expected an integer between 0 and ${HWEXEC_WAIT_MS_MAX}.`);
118
+ }
119
+ return n;
120
+ }
121
+ // Validate tail_bytes (1-65536; the default is 4096).
122
+ export function validateHwexecTailBytes(tailBytes) {
123
+ const n = Number(tailBytes ?? HWEXEC_TAIL_BYTES_DEFAULT);
124
+ if (!Number.isSafeInteger(n) || n < 1 || n > HWEXEC_TAIL_BYTES_MAX) {
125
+ throw new Error(`sandbox exec poll: invalid tail_bytes ${JSON.stringify(tailBytes)}. ` +
126
+ `Expected an integer between 1 and ${HWEXEC_TAIL_BYTES_MAX}.`);
127
+ }
128
+ return n;
129
+ }
130
+ // The poll exec timeout: wait_ms + headroom, never below the table default.
131
+ // A timeout on a poll must mean the sandbox is unreachable — never that the
132
+ // script's own bounded wait ran out of clock.
133
+ export function resolveHwexecPollTimeoutMs(waitMs, baseTimeoutMs) {
134
+ return Math.max(baseTimeoutMs, waitMs + HWEXEC_POLL_HEADROOM_MS);
135
+ }
136
+ // The poll script: a bounded wait (sleep-2 intervals, loop count folded from
137
+ // wait_ms, early exit the moment the status line commits), then the one-shot
138
+ // field echo. The HW_* fields are read only from the region before
139
+ // HW_LOG_BEGIN, so log content can never line-inject a verdict field.
140
+ export function buildHwexecPollScript(taskId, waitMs, tailBytes) {
141
+ const id = validateHwexecTaskId(taskId);
142
+ const loops = hwexecPollLoops(validateHwexecWaitMs(waitMs));
143
+ const bytes = validateHwexecTailBytes(tailBytes);
144
+ return [
145
+ // #999-class guard: the pgrep pattern is assembled from concatenated
146
+ // quoted fragments, so its VALUE never appears literally in this
147
+ // script's own text — a shell whose command line carries the script
148
+ // (an sh -c wrapper) can never match itself. The /launched suffix
149
+ // anchors the pattern to THIS task's wrapper: a bare hwexec/<id>
150
+ // prefix would also match hwexec/<id>-suffix sibling tasks and break
151
+ // the per-task independence the claim protocol's model assumes.
152
+ `P="hwexec/""${id}""/launched"`,
153
+ `D="/tmp/"".hwexec/""${id}"`,
154
+ `i=0`,
155
+ `while [ "$i" -lt ${loops} ]; do`,
156
+ ` grep -q '^exit:[0-9][0-9]*$' "$D/status" 2>/dev/null && break`,
157
+ ` sleep 2`,
158
+ ` i=$((i+1))`,
159
+ `done`,
160
+ `if [ -d "$D" ]; then echo "HW_DIR=1"; else echo "HW_DIR=0"; fi`,
161
+ `S=$(grep -m1 '^exit:[0-9][0-9]*$' "$D/status" 2>/dev/null || true)`,
162
+ `echo "HW_STATUS=$S"`,
163
+ // Missing pgrep (a procps-less image) must not read as dead: an
164
+ // unprobeable aliveness fails SAFE toward alive, because a false
165
+ // 'lost' verdict would send the caller to a new task_id while a copy
166
+ // still runs — the one direction the claim protocol exists to make
167
+ // impossible. The verdict still converges: the task's own completion
168
+ // writes the status file.
169
+ `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`,
170
+ `if [ -f "$D/launched" ]; then echo "HW_LAUNCHED=1"; else echo "HW_LAUNCHED=0"; fi`,
171
+ `echo "HW_LOG_BEGIN"`,
172
+ `tail -c ${bytes} "$D/log" 2>/dev/null`,
173
+ `echo "HW_LOG_END"`,
174
+ ].join('\n');
175
+ }
176
+ export function deriveHwexecVerdict(facts, knowTask) {
177
+ if (!facts.dir) {
178
+ // logTail is '' here by construction: the script's tail on a missing
179
+ // directory produces nothing — the field stays uniform for consumers.
180
+ return knowTask ? { verdict: 'lost', logTail: facts.logTail } : { verdict: 'unknown' };
181
+ }
182
+ const exitMatch = facts.status.match(/^exit:(\d+)$/);
183
+ if (exitMatch) {
184
+ return { verdict: 'done', exitCode: Number(exitMatch[1]), logTail: facts.logTail };
185
+ }
186
+ if (facts.alive) {
187
+ return { verdict: 'running', logTail: facts.logTail };
188
+ }
189
+ if (facts.launched) {
190
+ return { verdict: 'lost', logTail: facts.logTail };
191
+ }
192
+ return { verdict: 'never' };
193
+ }
194
+ const HW_LOG_BEGIN_MARKER = 'HW_LOG_BEGIN';
195
+ const HW_LOG_END_MARKER = 'HW_LOG_END';
196
+ // Anchored ^KEY= reader over a field region — the HW_* grammar's single
197
+ // lookup rule (the readDbField doctrine). Returns undefined when the field
198
+ // is absent, so presence and value stay distinguishable.
199
+ function readHwField(text, key) {
200
+ const m = text.match(new RegExp(`^${key}=(.*)$`, 'm'));
201
+ return m === null ? undefined : (m[1] ?? '').trim();
202
+ }
203
+ // Parse one poll exec's stdout into the facts. #946: strip OSC/CSI escapes
204
+ // and \r before the anchored lookups. The four verdict fields are
205
+ // presence-required — the script emits them unconditionally, so a missing
206
+ // field means the output was truncated or garbled, and an unreadable poll
207
+ // must FAIL instead of misjudging: a defaulted 'never'/'lost' would send
208
+ // the caller to a new task_id while a copy still runs.
209
+ export function parseHwexecPollOutput(stdout) {
210
+ const text = stripTerminalEscapes(stdout);
211
+ const beginIdx = text.indexOf(HW_LOG_BEGIN_MARKER);
212
+ const head = beginIdx === -1 ? text : text.slice(0, beginIdx);
213
+ let logTail = '';
214
+ if (beginIdx !== -1) {
215
+ const afterBegin = text.slice(beginIdx + HW_LOG_BEGIN_MARKER.length);
216
+ const endIdx = afterBegin.indexOf(HW_LOG_END_MARKER);
217
+ const raw = endIdx === -1 ? afterBegin : afterBegin.slice(0, endIdx);
218
+ logTail = raw.replace(/^\n/, '').replace(/\n$/, '');
219
+ }
220
+ const required = (key) => {
221
+ const value = readHwField(head, key);
222
+ if (value === undefined) {
223
+ throw new Error(`sandbox exec poll: unreadable output — the ${key} field is missing, so no verdict can be derived; retry the poll.`);
224
+ }
225
+ return value;
226
+ };
227
+ return {
228
+ dir: required('HW_DIR') === '1',
229
+ status: required('HW_STATUS'),
230
+ alive: required('HW_ALIVE') === '1',
231
+ launched: required('HW_LAUNCHED') === '1',
232
+ logTail,
233
+ };
234
+ }
235
+ export function classifyHwexecStartOutput(stdout, taskId) {
236
+ const text = stripTerminalEscapes(stdout);
237
+ if (readHwField(text, 'HW_STARTED') === taskId)
238
+ return 'started';
239
+ if (readHwField(text, 'HW_DUP') === taskId)
240
+ return 'dup';
241
+ if (readHwField(text, 'HW_CLAIM_ERROR') === '1')
242
+ return 'claim_error';
243
+ return 'uncertain';
244
+ }