|
| 1 | +// Qa Lab plugin module runs CLI processes and parses their structured output. |
| 2 | +import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process"; |
| 3 | +import path from "node:path"; |
| 4 | +import { resolveTimerTimeoutMs } from "openclaw/plugin-sdk/number-runtime"; |
| 5 | +import { truncateUtf16Safe } from "openclaw/plugin-sdk/text-utility-runtime"; |
| 6 | +import { |
| 7 | + appendQaChildOutput, |
| 8 | + appendQaChildOutputTail, |
| 9 | + createQaChildOutputCapture, |
| 10 | + createQaChildOutputTail, |
| 11 | + formatQaChildOutputTail, |
| 12 | + QA_CHILD_STDOUT_MAX_BYTES, |
| 13 | + readQaChildOutput, |
| 14 | +} from "./child-output.js"; |
| 15 | +import { QaSuiteInfraError } from "./errors.js"; |
| 16 | +import { resolveQaNodeExecPath } from "./node-exec.js"; |
| 17 | +import { createQaPosixCommandSettlement } from "./posix-command-settlement.js"; |
| 18 | +import type { QaSuiteRuntimeEnv } from "./suite-runtime-types.js"; |
| 19 | +import { resolveQaWindowsSystem32ExePath } from "./windows-system-tools.js"; |
| 20 | + |
| 21 | +const ANSI_ESCAPE_PATTERN = new RegExp(String.raw`\x1B\[[0-?]*[ -/]*[@-~]`, "g"); |
| 22 | + |
| 23 | +function stripAnsiCodes(text: string) { |
| 24 | + return text.replace(ANSI_ESCAPE_PATTERN, ""); |
| 25 | +} |
| 26 | + |
| 27 | +function findBalancedJsonEnd(text: string, startIndex: number) { |
| 28 | + const opening = text[startIndex]; |
| 29 | + const firstClosing = opening === "{" ? "}" : opening === "[" ? "]" : ""; |
| 30 | + if (!firstClosing) { |
| 31 | + return -1; |
| 32 | + } |
| 33 | + |
| 34 | + const stack = [firstClosing]; |
| 35 | + let inString = false; |
| 36 | + let escaping = false; |
| 37 | + for (let index = startIndex + 1; index < text.length; index += 1) { |
| 38 | + const char = text[index]; |
| 39 | + if (inString) { |
| 40 | + if (escaping) { |
| 41 | + escaping = false; |
| 42 | + } else if (char === "\\") { |
| 43 | + escaping = true; |
| 44 | + } else if (char === '"') { |
| 45 | + inString = false; |
| 46 | + } |
| 47 | + continue; |
| 48 | + } |
| 49 | + if (char === '"') { |
| 50 | + inString = true; |
| 51 | + } else if (char === "{" || char === "[") { |
| 52 | + stack.push(char === "{" ? "}" : "]"); |
| 53 | + } else if (char === "}" || char === "]") { |
| 54 | + if (stack.at(-1) !== char) { |
| 55 | + return -1; |
| 56 | + } |
| 57 | + stack.pop(); |
| 58 | + if (stack.length === 0) { |
| 59 | + return index; |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + return -1; |
| 64 | +} |
| 65 | + |
| 66 | +function parseBalancedJsonPayloadStart(text: string) { |
| 67 | + const trimmedStart = text.search(/\S/u); |
| 68 | + if (trimmedStart < 0) { |
| 69 | + return undefined; |
| 70 | + } |
| 71 | + const char = text[trimmedStart]; |
| 72 | + if (char !== "{" && char !== "[") { |
| 73 | + return undefined; |
| 74 | + } |
| 75 | + const end = findBalancedJsonEnd(text, trimmedStart); |
| 76 | + if (end <= trimmedStart) { |
| 77 | + return undefined; |
| 78 | + } |
| 79 | + try { |
| 80 | + return JSON.parse(text.slice(trimmedStart, end + 1)) as unknown; |
| 81 | + } catch { |
| 82 | + return undefined; |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +function isJsonRecord(value: unknown): value is Record<string, unknown> { |
| 87 | + return Boolean(value && typeof value === "object" && !Array.isArray(value)); |
| 88 | +} |
| 89 | + |
| 90 | +function isStructuredDiagnosticJson(value: unknown) { |
| 91 | + if (!isJsonRecord(value)) { |
| 92 | + return false; |
| 93 | + } |
| 94 | + const level = value.level ?? value.logLevel ?? value.severity; |
| 95 | + if (typeof level !== "string") { |
| 96 | + return false; |
| 97 | + } |
| 98 | + return ( |
| 99 | + typeof value.message === "string" || |
| 100 | + typeof value.msg === "string" || |
| 101 | + typeof value.time === "string" || |
| 102 | + typeof value.timestamp === "string" |
| 103 | + ); |
| 104 | +} |
| 105 | + |
| 106 | +function isMemorySearchJsonPayload(value: unknown) { |
| 107 | + return isJsonRecord(value) && Array.isArray(value.results); |
| 108 | +} |
| 109 | + |
| 110 | +function isMemoryStatusJsonPayload(value: unknown) { |
| 111 | + if (Array.isArray(value)) { |
| 112 | + return true; |
| 113 | + } |
| 114 | + return isJsonRecord(value) && value.command === "memory" && value.subcommand === "status"; |
| 115 | +} |
| 116 | + |
| 117 | +function resolveQaCliJsonPayloadMatcher(args: readonly string[]) { |
| 118 | + if (!args.includes("--json")) { |
| 119 | + return undefined; |
| 120 | + } |
| 121 | + if (args[0] === "memory" && args[1] === "search") { |
| 122 | + return isMemorySearchJsonPayload; |
| 123 | + } |
| 124 | + if (args[0] === "memory" && args[1] === "status") { |
| 125 | + return isMemoryStatusJsonPayload; |
| 126 | + } |
| 127 | + return undefined; |
| 128 | +} |
| 129 | + |
| 130 | +function parseQaCliJsonOutput(text: string, args: readonly string[]) { |
| 131 | + const cleaned = stripAnsiCodes(text).trim(); |
| 132 | + if (!cleaned) { |
| 133 | + return {}; |
| 134 | + } |
| 135 | + const matchesExpectedPayload = resolveQaCliJsonPayloadMatcher(args); |
| 136 | + try { |
| 137 | + return JSON.parse(cleaned) as unknown; |
| 138 | + } catch { |
| 139 | + // Some startup repair logs are emitted on stdout before command JSON. |
| 140 | + const lines = cleaned.split(/\r?\n/); |
| 141 | + const candidates: unknown[] = []; |
| 142 | + for (const [index, line] of lines.entries()) { |
| 143 | + const candidate = line.trimStart(); |
| 144 | + if (candidate !== line || (!candidate.startsWith("{") && !candidate.startsWith("["))) { |
| 145 | + continue; |
| 146 | + } |
| 147 | + const jsonTail = lines.slice(index).join("\n"); |
| 148 | + try { |
| 149 | + candidates.push(JSON.parse(jsonTail) as unknown); |
| 150 | + } catch { |
| 151 | + const balanced = parseBalancedJsonPayloadStart(jsonTail); |
| 152 | + if (balanced !== undefined) { |
| 153 | + candidates.push(balanced); |
| 154 | + } |
| 155 | + } |
| 156 | + } |
| 157 | + const expectedPayload = candidates.find((value) => matchesExpectedPayload?.(value) === true); |
| 158 | + if (expectedPayload !== undefined) { |
| 159 | + return expectedPayload; |
| 160 | + } |
| 161 | + const payload = candidates.toReversed().find((value) => !isStructuredDiagnosticJson(value)); |
| 162 | + if (payload !== undefined) { |
| 163 | + return payload; |
| 164 | + } |
| 165 | + const diagnosticOnly = candidates.at(-1); |
| 166 | + if (diagnosticOnly !== undefined) { |
| 167 | + return diagnosticOnly; |
| 168 | + } |
| 169 | + |
| 170 | + // Keep a line-oriented fallback for compact payloads followed by diagnostics. |
| 171 | + for (const line of lines.toReversed()) { |
| 172 | + const candidate = line.trim(); |
| 173 | + if (!candidate.startsWith("{") && !candidate.startsWith("[")) { |
| 174 | + continue; |
| 175 | + } |
| 176 | + try { |
| 177 | + return JSON.parse(candidate) as unknown; |
| 178 | + } catch { |
| 179 | + // Keep looking for the actual payload line. |
| 180 | + } |
| 181 | + } |
| 182 | + throw new Error(`qa cli returned non-JSON stdout: ${truncateUtf16Safe(cleaned, 240)}`); |
| 183 | + } |
| 184 | +} |
| 185 | + |
| 186 | +function killQaCliWindowsProcessTree(child: Pick<ChildProcessWithoutNullStreams, "kill" | "pid">) { |
| 187 | + if (child.pid) { |
| 188 | + const result = spawnSync( |
| 189 | + resolveQaWindowsSystem32ExePath("taskkill.exe"), |
| 190 | + ["/PID", String(child.pid), "/T", "/F"], |
| 191 | + { |
| 192 | + stdio: "ignore", |
| 193 | + windowsHide: true, |
| 194 | + timeout: 5_000, |
| 195 | + }, |
| 196 | + ); |
| 197 | + if (!result.error && result.status === 0) { |
| 198 | + return; |
| 199 | + } |
| 200 | + } |
| 201 | + child.kill("SIGKILL"); |
| 202 | +} |
| 203 | + |
| 204 | +async function runQaCli( |
| 205 | + env: Pick< |
| 206 | + QaSuiteRuntimeEnv, |
| 207 | + "gateway" | "repoRoot" | "primaryModel" | "alternateModel" | "providerMode" |
| 208 | + >, |
| 209 | + args: string[], |
| 210 | + opts?: { timeoutMs?: number; json?: boolean; env?: NodeJS.ProcessEnv }, |
| 211 | +) { |
| 212 | + const stdout = createQaChildOutputCapture(); |
| 213 | + const stdoutTail = createQaChildOutputTail(); |
| 214 | + const stderr = createQaChildOutputTail(); |
| 215 | + const distEntryPath = path.join(env.repoRoot, "dist", "index.js"); |
| 216 | + const nodeExecPath = await resolveQaNodeExecPath(); |
| 217 | + await new Promise<void>((resolve, reject) => { |
| 218 | + const child = spawn(nodeExecPath, [distEntryPath, ...args], { |
| 219 | + cwd: env.gateway.tempRoot, |
| 220 | + env: { |
| 221 | + ...env.gateway.runtimeEnv, |
| 222 | + ...opts?.env, |
| 223 | + }, |
| 224 | + detached: process.platform !== "win32", |
| 225 | + stdio: ["ignore", "pipe", "pipe"], |
| 226 | + }); |
| 227 | + const timeoutMs = resolveTimerTimeoutMs(opts?.timeoutMs, 60_000); |
| 228 | + const rejectTimeout = () => { |
| 229 | + const stdoutText = formatQaChildOutputTail(stdoutTail, "qa cli stdout"); |
| 230 | + const stderrText = formatQaChildOutputTail(stderr, "qa cli stderr"); |
| 231 | + const diagnostics = [ |
| 232 | + stdoutText ? `stdout:\n${stdoutText}` : "", |
| 233 | + stderrText ? `stderr:\n${stderrText}` : "", |
| 234 | + ] |
| 235 | + .filter(Boolean) |
| 236 | + .join("\n"); |
| 237 | + return new QaSuiteInfraError( |
| 238 | + "qa_cli_timeout", |
| 239 | + `qa cli timed out: openclaw ${args.join(" ")}${diagnostics ? `\n${diagnostics}` : ""}`, |
| 240 | + ); |
| 241 | + }; |
| 242 | + const getExitError = (code: number | null) => { |
| 243 | + if (code === 0) { |
| 244 | + if (stdout.exceeded) { |
| 245 | + return new Error( |
| 246 | + `qa cli stdout exceeded ${QA_CHILD_STDOUT_MAX_BYTES} bytes; refusing to parse truncated output`, |
| 247 | + ); |
| 248 | + } |
| 249 | + return undefined; |
| 250 | + } |
| 251 | + const stderrText = formatQaChildOutputTail(stderr, "qa cli stderr"); |
| 252 | + return new Error(`qa cli failed (${code ?? "unknown"}): ${stderrText}`); |
| 253 | + }; |
| 254 | + if (process.platform !== "win32") { |
| 255 | + createQaPosixCommandSettlement({ |
| 256 | + child, |
| 257 | + settlementFailureMessage: "qa cli settlement failed", |
| 258 | + executionTimeoutMs: timeoutMs, |
| 259 | + forceKillAfterMs: 0, |
| 260 | + initialSignal: "SIGKILL", |
| 261 | + onSettled: (outcome) => { |
| 262 | + const primary = outcome.primary; |
| 263 | + const primaryError = |
| 264 | + primary.type === "spawn-error" || primary.type === "stream-error" |
| 265 | + ? primary.error |
| 266 | + : primary.type === "timeout" |
| 267 | + ? rejectTimeout() |
| 268 | + : getExitError(primary.type === "exit" ? primary.exitCode : 1); |
| 269 | + if (outcome.settlementFailure) { |
| 270 | + reject( |
| 271 | + primaryError |
| 272 | + ? new AggregateError( |
| 273 | + [primaryError, outcome.settlementFailure], |
| 274 | + "qa cli command and settlement failed", |
| 275 | + ) |
| 276 | + : outcome.settlementFailure, |
| 277 | + ); |
| 278 | + return; |
| 279 | + } |
| 280 | + if (primaryError) { |
| 281 | + reject(primaryError); |
| 282 | + return; |
| 283 | + } |
| 284 | + resolve(); |
| 285 | + }, |
| 286 | + onStderrData: (chunk) => appendQaChildOutputTail(stderr, chunk), |
| 287 | + onStdoutData: (chunk) => { |
| 288 | + appendQaChildOutput(stdout, chunk); |
| 289 | + appendQaChildOutputTail(stdoutTail, chunk); |
| 290 | + }, |
| 291 | + processGroupId: child.pid, |
| 292 | + verifyAfterMs: 500, |
| 293 | + }); |
| 294 | + return; |
| 295 | + } |
| 296 | + const timeout = setTimeout(() => { |
| 297 | + killQaCliWindowsProcessTree(child); |
| 298 | + reject(rejectTimeout()); |
| 299 | + }, timeoutMs); |
| 300 | + child.stdout.on("data", (chunk) => { |
| 301 | + appendQaChildOutput(stdout, chunk); |
| 302 | + appendQaChildOutputTail(stdoutTail, chunk); |
| 303 | + }); |
| 304 | + child.stderr.on("data", (chunk) => appendQaChildOutputTail(stderr, chunk)); |
| 305 | + child.once("error", (error) => { |
| 306 | + clearTimeout(timeout); |
| 307 | + reject(error); |
| 308 | + }); |
| 309 | + child.once("close", (code) => { |
| 310 | + clearTimeout(timeout); |
| 311 | + const error = getExitError(code); |
| 312 | + return error ? reject(error) : resolve(); |
| 313 | + }); |
| 314 | + }); |
| 315 | + const text = readQaChildOutput(stdout).trim(); |
| 316 | + if (!opts?.json) { |
| 317 | + return text; |
| 318 | + } |
| 319 | + return parseQaCliJsonOutput(text, args); |
| 320 | +} |
| 321 | + |
| 322 | +export { runQaCli }; |
0 commit comments