|
1 | | -import { spawnSync } from "node:child_process"; |
| 1 | +import { spawn, spawnSync, type ChildProcessWithoutNullStreams } from "node:child_process"; |
| 2 | +import { createHash, randomBytes } from "node:crypto"; |
2 | 3 | import { existsSync } from "node:fs"; |
3 | 4 | import path from "node:path"; |
| 5 | +import { createInterface, type Interface as ReadlineInterface } from "node:readline"; |
4 | 6 | import { Command } from "commander"; |
5 | 7 | import { expect, it } from "vitest"; |
6 | 8 | import { getCompletionScript } from "./completion-cli.js"; |
@@ -102,32 +104,291 @@ function findPowerShell(): string | null { |
102 | 104 | const powerShellPath = findPowerShell(); |
103 | 105 | export const itWithPowerShell = powerShellPath ? it : it.skip; |
104 | 106 |
|
105 | | -export function runGeneratedPowerShellCompletion(program: Command, commandLine: string): string[] { |
106 | | - if (!powerShellPath) { |
107 | | - throw new Error("PowerShell is unavailable"); |
| 107 | +type PowerShellCompletionResponse = |
| 108 | + | { version: 1; id: string; ok: true; completions: string[] } |
| 109 | + | { version: 1; id: string; ok: false; error: string }; |
| 110 | + |
| 111 | +type PendingPowerShellCompletion = { |
| 112 | + reject: (error: Error) => void; |
| 113 | + resolve: (completions: string[]) => void; |
| 114 | + timeout: ReturnType<typeof setTimeout>; |
| 115 | +}; |
| 116 | + |
| 117 | +const POWERSHELL_CASE_TIMEOUT_MS = 15_000; |
| 118 | +const POWERSHELL_CLOSE_TIMEOUT_MS = 5_000; |
| 119 | + |
| 120 | +function encodePowerShellHostScript(framePrefix: string): string { |
| 121 | + const script = String.raw` |
| 122 | +$ErrorActionPreference = 'Stop' |
| 123 | +[Console]::Out.WriteLine('${framePrefix}READY') |
| 124 | +[Console]::Out.Flush() |
| 125 | +while (($encodedRequest = [Console]::In.ReadLine()) -ne $null) { |
| 126 | + $request = $null |
| 127 | + try { |
| 128 | + $requestJson = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($encodedRequest)) |
| 129 | + $request = $requestJson | ConvertFrom-Json |
| 130 | + $completionScript = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([string]$request.script)) |
| 131 | + $commandLine = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([string]$request.commandLine)) |
| 132 | + Register-ArgumentCompleter -Native -CommandName openclaw -ScriptBlock $null |
| 133 | + Invoke-Expression $completionScript | Out-Null |
| 134 | + $completions = @( |
| 135 | + [System.Management.Automation.CommandCompletion]::CompleteInput( |
| 136 | + $commandLine, |
| 137 | + $commandLine.Length, |
| 138 | + $null |
| 139 | + ).CompletionMatches | ForEach-Object { [string]$_.CompletionText } |
| 140 | + ) |
| 141 | + $response = @{ version = 1; id = [string]$request.id; ok = $true; completions = $completions } |
| 142 | + } catch { |
| 143 | + $responseId = if ($null -ne $request -and $null -ne $request.id) { |
| 144 | + [string]$request.id |
| 145 | + } else { |
| 146 | + 'unknown' |
| 147 | + } |
| 148 | + $response = @{ version = 1; id = $responseId; ok = $false; error = ($_ | Out-String).Trim() } |
| 149 | + } finally { |
| 150 | + Register-ArgumentCompleter -Native -CommandName openclaw -ScriptBlock $null |
108 | 151 | } |
| 152 | + $responseJson = $response | ConvertTo-Json -Compress -Depth 5 |
| 153 | + $encodedResponse = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($responseJson)) |
| 154 | + [Console]::Out.WriteLine('${framePrefix}' + $encodedResponse) |
| 155 | + [Console]::Out.Flush() |
| 156 | +} |
| 157 | +`; |
| 158 | + return Buffer.from(script, "utf16le").toString("base64"); |
| 159 | +} |
109 | 160 |
|
110 | | - const script = getCompletionScript("powershell", program); |
111 | | - const quotedCommandLine = commandLine.replaceAll("'", "''"); |
112 | | - const result = spawnSync( |
113 | | - powerShellPath, |
114 | | - [ |
115 | | - "-NoLogo", |
116 | | - "-NoProfile", |
117 | | - "-NonInteractive", |
118 | | - "-Command", |
119 | | - `${script} |
120 | | -$line = '${quotedCommandLine}' |
121 | | -[System.Management.Automation.CommandCompletion]::CompleteInput($line, $line.Length, $null).CompletionMatches | ForEach-Object { $_.CompletionText } |
122 | | -`, |
123 | | - ], |
124 | | - { encoding: "utf8" }, |
125 | | - ); |
| 161 | +function decodePowerShellCompletionResponse(encoded: string): PowerShellCompletionResponse { |
| 162 | + const value = JSON.parse(Buffer.from(encoded, "base64").toString("utf8")) as unknown; |
| 163 | + if (!value || typeof value !== "object" || Array.isArray(value)) { |
| 164 | + throw new Error("PowerShell completion response was not an object"); |
| 165 | + } |
| 166 | + const response = value as Record<string, unknown>; |
| 167 | + if ( |
| 168 | + response.version !== 1 || |
| 169 | + typeof response.id !== "string" || |
| 170 | + typeof response.ok !== "boolean" |
| 171 | + ) { |
| 172 | + throw new Error("PowerShell completion response had an invalid envelope"); |
| 173 | + } |
| 174 | + if (response.ok) { |
| 175 | + if ( |
| 176 | + !Array.isArray(response.completions) || |
| 177 | + !response.completions.every((completion) => typeof completion === "string") |
| 178 | + ) { |
| 179 | + throw new Error("PowerShell completion response had invalid completions"); |
| 180 | + } |
| 181 | + return { |
| 182 | + version: 1, |
| 183 | + id: response.id, |
| 184 | + ok: true, |
| 185 | + completions: response.completions, |
| 186 | + }; |
| 187 | + } |
| 188 | + if (typeof response.error !== "string") { |
| 189 | + throw new Error("PowerShell completion response had no error text"); |
| 190 | + } |
| 191 | + return { version: 1, id: response.id, ok: false, error: response.error }; |
| 192 | +} |
126 | 193 |
|
127 | | - if (result.error) { |
128 | | - throw result.error; |
| 194 | +/** One live PowerShell process per test file; cases remain sequential and state-isolated. */ |
| 195 | +export class PowerShellCompletionRunner { |
| 196 | + private child: ChildProcessWithoutNullStreams | undefined; |
| 197 | + private closing = false; |
| 198 | + private exitPromise: Promise<{ code: number | null; signal: NodeJS.Signals | null }> | undefined; |
| 199 | + private failure: Error | undefined; |
| 200 | + private readonly framePrefix = `OPENCLAW_PWSH_V1:${randomBytes(8).toString("hex")}:`; |
| 201 | + private pending = new Map<string, PendingPowerShellCompletion>(); |
| 202 | + private queue: Promise<void> = Promise.resolve(); |
| 203 | + private readyPromise: Promise<void> | undefined; |
| 204 | + private stdoutLines: ReadlineInterface | undefined; |
| 205 | + |
| 206 | + complete(program: Command, commandLine: string): Promise<string[]> { |
| 207 | + const script = getCompletionScript("powershell", program); |
| 208 | + const caseId = createHash("sha256") |
| 209 | + .update(script) |
| 210 | + .update("\0") |
| 211 | + .update(commandLine) |
| 212 | + .digest("hex") |
| 213 | + .slice(0, 20); |
| 214 | + const result = this.queue.then(() => this.completeCase(caseId, script, commandLine)); |
| 215 | + this.queue = result.then( |
| 216 | + () => undefined, |
| 217 | + () => undefined, |
| 218 | + ); |
| 219 | + return result; |
| 220 | + } |
| 221 | + |
| 222 | + async close(): Promise<void> { |
| 223 | + await this.queue; |
| 224 | + if (!this.child || !this.exitPromise) { |
| 225 | + return; |
| 226 | + } |
| 227 | + this.closing = true; |
| 228 | + this.child.stdin.end(); |
| 229 | + let closeTimer: ReturnType<typeof setTimeout> | undefined; |
| 230 | + try { |
| 231 | + const outcome = await Promise.race([ |
| 232 | + this.exitPromise, |
| 233 | + new Promise<never>((_resolve, reject) => { |
| 234 | + closeTimer = setTimeout( |
| 235 | + () => reject(new Error("PowerShell completion runner did not exit after stdin closed")), |
| 236 | + POWERSHELL_CLOSE_TIMEOUT_MS, |
| 237 | + ); |
| 238 | + }), |
| 239 | + ]); |
| 240 | + if (outcome.code !== 0 || outcome.signal !== null) { |
| 241 | + throw new Error( |
| 242 | + `PowerShell completion runner exited with code ${String(outcome.code)} signal ${String(outcome.signal)}`, |
| 243 | + ); |
| 244 | + } |
| 245 | + if (this.failure) { |
| 246 | + throw this.failure; |
| 247 | + } |
| 248 | + } catch (error) { |
| 249 | + this.child.kill("SIGTERM"); |
| 250 | + setTimeout(() => this.child?.kill("SIGKILL"), 1_000).unref(); |
| 251 | + throw error; |
| 252 | + } finally { |
| 253 | + if (closeTimer) { |
| 254 | + clearTimeout(closeTimer); |
| 255 | + } |
| 256 | + this.stdoutLines?.close(); |
| 257 | + } |
| 258 | + } |
| 259 | + |
| 260 | + private async completeCase( |
| 261 | + caseId: string, |
| 262 | + script: string, |
| 263 | + commandLine: string, |
| 264 | + ): Promise<string[]> { |
| 265 | + await this.start(); |
| 266 | + if (this.failure) { |
| 267 | + throw this.failure; |
| 268 | + } |
| 269 | + const child = this.child; |
| 270 | + if (!child) { |
| 271 | + throw new Error("PowerShell completion runner did not start"); |
| 272 | + } |
| 273 | + const request = Buffer.from( |
| 274 | + JSON.stringify({ |
| 275 | + version: 1, |
| 276 | + id: caseId, |
| 277 | + script: Buffer.from(script, "utf8").toString("base64"), |
| 278 | + commandLine: Buffer.from(commandLine, "utf8").toString("base64"), |
| 279 | + }), |
| 280 | + "utf8", |
| 281 | + ).toString("base64"); |
| 282 | + return await new Promise<string[]>((resolve, reject) => { |
| 283 | + const timeout = setTimeout(() => { |
| 284 | + this.poison(new Error(`PowerShell completion case ${caseId} timed out`)); |
| 285 | + }, POWERSHELL_CASE_TIMEOUT_MS); |
| 286 | + this.pending.set(caseId, { reject, resolve, timeout }); |
| 287 | + child.stdin.write(`${request}\n`, (error) => { |
| 288 | + if (error) { |
| 289 | + this.poison(new Error(`PowerShell completion write failed: ${error.message}`)); |
| 290 | + } |
| 291 | + }); |
| 292 | + }); |
| 293 | + } |
| 294 | + |
| 295 | + private start(): Promise<void> { |
| 296 | + if (this.readyPromise) { |
| 297 | + return this.readyPromise; |
| 298 | + } |
| 299 | + if (!powerShellPath) { |
| 300 | + return Promise.reject(new Error("PowerShell is unavailable")); |
| 301 | + } |
| 302 | + const child = spawn( |
| 303 | + powerShellPath, |
| 304 | + [ |
| 305 | + "-NoLogo", |
| 306 | + "-NoProfile", |
| 307 | + "-NonInteractive", |
| 308 | + "-EncodedCommand", |
| 309 | + encodePowerShellHostScript(this.framePrefix), |
| 310 | + ], |
| 311 | + { stdio: "pipe" }, |
| 312 | + ); |
| 313 | + this.child = child; |
| 314 | + child.stdout.setEncoding("utf8"); |
| 315 | + child.stderr.setEncoding("utf8"); |
| 316 | + this.stdoutLines = createInterface({ input: child.stdout }); |
| 317 | + this.readyPromise = new Promise<void>((resolve, reject) => { |
| 318 | + const readyTimeout = setTimeout(() => { |
| 319 | + const error = new Error("PowerShell completion runner did not become ready"); |
| 320 | + reject(error); |
| 321 | + this.poison(error); |
| 322 | + }, POWERSHELL_CASE_TIMEOUT_MS); |
| 323 | + this.stdoutLines?.on("line", (line) => { |
| 324 | + if (line === `${this.framePrefix}READY`) { |
| 325 | + clearTimeout(readyTimeout); |
| 326 | + resolve(); |
| 327 | + return; |
| 328 | + } |
| 329 | + if (!line.startsWith(this.framePrefix)) { |
| 330 | + this.poison(new Error(`Unexpected PowerShell completion stdout: ${line}`)); |
| 331 | + return; |
| 332 | + } |
| 333 | + try { |
| 334 | + const response = decodePowerShellCompletionResponse(line.slice(this.framePrefix.length)); |
| 335 | + const pending = this.pending.get(response.id); |
| 336 | + if (!pending) { |
| 337 | + this.poison(new Error(`Unexpected PowerShell completion response id: ${response.id}`)); |
| 338 | + return; |
| 339 | + } |
| 340 | + clearTimeout(pending.timeout); |
| 341 | + this.pending.delete(response.id); |
| 342 | + if (response.ok) { |
| 343 | + pending.resolve(response.completions); |
| 344 | + } else { |
| 345 | + pending.reject( |
| 346 | + new Error(`PowerShell completion case ${response.id} failed: ${response.error}`), |
| 347 | + ); |
| 348 | + } |
| 349 | + } catch (error) { |
| 350 | + this.poison(error instanceof Error ? error : new Error(String(error))); |
| 351 | + } |
| 352 | + }); |
| 353 | + child.once("error", (error) => { |
| 354 | + reject(error); |
| 355 | + this.poison(error); |
| 356 | + }); |
| 357 | + child.stderr.on("data", (chunk: string) => { |
| 358 | + const stderr = chunk.trim(); |
| 359 | + if (stderr) { |
| 360 | + this.poison(new Error(`Unexpected PowerShell completion stderr: ${stderr}`)); |
| 361 | + } |
| 362 | + }); |
| 363 | + this.exitPromise = new Promise((exitResolve) => { |
| 364 | + child.once("exit", (code, signal) => { |
| 365 | + clearTimeout(readyTimeout); |
| 366 | + exitResolve({ code, signal }); |
| 367 | + if (!this.closing || code !== 0 || signal !== null) { |
| 368 | + this.poison( |
| 369 | + new Error( |
| 370 | + `PowerShell completion runner exited unexpectedly with code ${String(code)} signal ${String(signal)}`, |
| 371 | + ), |
| 372 | + ); |
| 373 | + } |
| 374 | + }); |
| 375 | + }); |
| 376 | + }); |
| 377 | + return this.readyPromise; |
| 378 | + } |
| 379 | + |
| 380 | + private poison(error: Error): void { |
| 381 | + if (this.failure) { |
| 382 | + return; |
| 383 | + } |
| 384 | + this.failure = error; |
| 385 | + for (const pending of this.pending.values()) { |
| 386 | + clearTimeout(pending.timeout); |
| 387 | + pending.reject(error); |
| 388 | + } |
| 389 | + this.pending.clear(); |
| 390 | + if (!this.closing) { |
| 391 | + this.child?.kill("SIGTERM"); |
| 392 | + } |
129 | 393 | } |
130 | | - expect(result.stderr).toBe(""); |
131 | | - expect(result.status).toBe(0); |
132 | | - return result.stdout.split(/\r?\n/).filter(Boolean); |
133 | 394 | } |
0 commit comments