import type { BashOperations } from "@earendil-works/pi-coding-agent"; import type { PwshNativeConfig } from "./config.ts"; import type { PowerShellRuntime } from "./runtime.ts"; import { buildPowerShellArguments, buildPowerShellSource } from "./powershell-source.ts"; import { spawnAndStream } from "./process.ts"; function findEnvironmentKey(env: NodeJS.ProcessEnv, name: string): string | undefined { const normalized = name.toUpperCase(); return Object.keys(env).find((key) => key.toUpperCase() === normalized); } function setDefault(env: NodeJS.ProcessEnv, name: string, value: string): void { const existing = findEnvironmentKey(env, name); if (existing === undefined || env[existing] === undefined) env[name] = value; } export function createRuntimeEnvironment( config: PwshNativeConfig, baseEnvironment: NodeJS.ProcessEnv = process.env, ): NodeJS.ProcessEnv { const env = { ...baseEnvironment }; if (config.pythonUtf8) { setDefault(env, "PYTHONIOENCODING", "utf-8"); setDefault(env, "PYTHONUTF8", "1"); } if (config.pythonUnbuffered) setDefault(env, "PYTHONUNBUFFERED", "1"); return env; } export function createPowerShellOperations( runtime: PowerShellRuntime, config: PwshNativeConfig, ): BashOperations { const args = buildPowerShellArguments(config); return { async exec(command, cwd, options) { const source = buildPowerShellSource(command, config); const result = await spawnAndStream(runtime.executable, args, cwd, { onData: options.onData, signal: options.signal, timeout: options.timeout, env: createRuntimeEnvironment(config, options.env ?? process.env), stdin: Buffer.from(source, "utf8").toString("base64"), }); return { exitCode: result.exitCode }; }, }; }