|
| 1 | +// SPDX-License-Identifier: Apache-2.0 |
| 2 | +// Copyright 2026 Mark Pickering and PICKBITS LLC. Part of PickBits Weaver. |
| 3 | +import { spawn, spawnSync } from "node:child_process"; |
| 4 | + |
| 5 | +export const DEFAULT_HOST = Object.freeze({ |
| 6 | + command: "claude", |
| 7 | + args: ["-p", "--output-format", "text"], |
| 8 | + concurrency: 2, |
| 9 | + timeout_seconds: 600 |
| 10 | +}); |
| 11 | + |
| 12 | +export function hostConfig(project = {}) { |
| 13 | + const configured = project.host || {}; |
| 14 | + return { |
| 15 | + command: configured.command || DEFAULT_HOST.command, |
| 16 | + args: Array.isArray(configured.args) ? [...configured.args] : [...DEFAULT_HOST.args], |
| 17 | + concurrency: configured.concurrency || DEFAULT_HOST.concurrency, |
| 18 | + timeout_seconds: configured.timeout_seconds || DEFAULT_HOST.timeout_seconds |
| 19 | + }; |
| 20 | +} |
| 21 | + |
| 22 | +function safeEnvironment() { |
| 23 | + const environment = { ...process.env }; |
| 24 | + delete environment.ANTHROPIC_API_KEY; |
| 25 | + return environment; |
| 26 | +} |
| 27 | + |
| 28 | +function executableForShell(command) { |
| 29 | + if (process.platform !== "win32" || !/\s/u.test(command) || /^".*"$/u.test(command)) return command; |
| 30 | + return `"${command.replaceAll('"', '\\"')}"`; |
| 31 | +} |
| 32 | + |
| 33 | +function runAttempt(config, promptText) { |
| 34 | + return new Promise((resolve) => { |
| 35 | + const started = Date.now(); |
| 36 | + let child; |
| 37 | + try { |
| 38 | + child = spawn(executableForShell(config.command), config.args, { |
| 39 | + cwd: config.cwd, |
| 40 | + env: safeEnvironment(), |
| 41 | + shell: process.platform === "win32", |
| 42 | + stdio: ["pipe", "pipe", "pipe"] |
| 43 | + }); |
| 44 | + } catch (error) { |
| 45 | + resolve({ ok: false, text: "", seconds: (Date.now() - started) / 1000, error: `could not start host: ${error.message}` }); |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + let stdout = ""; |
| 50 | + let stderr = ""; |
| 51 | + let settled = false; |
| 52 | + let timedOut = false; |
| 53 | + const finish = (result) => { |
| 54 | + if (settled) return; |
| 55 | + settled = true; |
| 56 | + clearTimeout(timer); |
| 57 | + resolve({ ...result, seconds: (Date.now() - started) / 1000 }); |
| 58 | + }; |
| 59 | + child.stdout.setEncoding("utf8"); |
| 60 | + child.stderr.setEncoding("utf8"); |
| 61 | + child.stdout.on("data", (chunk) => { stdout += chunk; }); |
| 62 | + child.stderr.on("data", (chunk) => { stderr += chunk; }); |
| 63 | + child.stdin.on("error", () => { |
| 64 | + // A host that exits before consuming its prompt may close stdin with EPIPE. |
| 65 | + }); |
| 66 | + child.on("error", (error) => { |
| 67 | + finish({ ok: false, text: stdout, error: `could not start host: ${error.message}` }); |
| 68 | + }); |
| 69 | + child.on("close", (code, signal) => { |
| 70 | + if (timedOut) return; |
| 71 | + if (code !== 0) { |
| 72 | + const detail = stderr.trim() ? `: ${stderr.trim().replace(/\s+/gu, " ").slice(0, 240)}` : ""; |
| 73 | + finish({ ok: false, text: stdout, error: `host exited with ${signal ? `signal ${signal}` : `code ${code}`}${detail}` }); |
| 74 | + } else if (!stdout.trim()) { |
| 75 | + finish({ ok: false, text: stdout, error: "host returned empty output" }); |
| 76 | + } else { |
| 77 | + finish({ ok: true, text: stdout }); |
| 78 | + } |
| 79 | + }); |
| 80 | + const timer = setTimeout(() => { |
| 81 | + timedOut = true; |
| 82 | + child.kill(); |
| 83 | + finish({ ok: false, text: stdout, error: `host timed out after ${config.timeout_seconds} seconds` }); |
| 84 | + }, config.timeout_seconds * 1000); |
| 85 | + try { |
| 86 | + child.stdin.end(promptText, () => {}); |
| 87 | + } catch (error) { |
| 88 | + finish({ ok: false, text: stdout, error: `could not send prompt to host: ${error.message}` }); |
| 89 | + } |
| 90 | + }); |
| 91 | +} |
| 92 | + |
| 93 | +export async function runHost(root, project, promptText) { |
| 94 | + const config = { ...hostConfig(project), cwd: root }; |
| 95 | + const failures = []; |
| 96 | + const started = Date.now(); |
| 97 | + for (let attempt = 1; attempt <= 2; attempt += 1) { |
| 98 | + const result = await runAttempt(config, promptText); |
| 99 | + if (result.ok) { |
| 100 | + return { ok: true, text: result.text, seconds: (Date.now() - started) / 1000, attempts: attempt }; |
| 101 | + } |
| 102 | + failures.push(`attempt ${attempt}: ${result.error}`); |
| 103 | + } |
| 104 | + return { |
| 105 | + ok: false, |
| 106 | + text: "", |
| 107 | + seconds: (Date.now() - started) / 1000, |
| 108 | + attempts: 2, |
| 109 | + error: `host failed after 2 attempts: ${failures.join("; ")}` |
| 110 | + }; |
| 111 | +} |
| 112 | + |
| 113 | +export async function runHostBatch(root, project, prompts, { concurrency } = {}) { |
| 114 | + const limit = Math.min(4, Math.max(1, Number(concurrency || hostConfig(project).concurrency) || 1)); |
| 115 | + const results = new Array(prompts.length); |
| 116 | + let next = 0; |
| 117 | + async function worker() { |
| 118 | + while (true) { |
| 119 | + const index = next; |
| 120 | + next += 1; |
| 121 | + if (index >= prompts.length) return; |
| 122 | + results[index] = await runHost(root, project, prompts[index]); |
| 123 | + } |
| 124 | + } |
| 125 | + await Promise.all(Array.from({ length: Math.min(limit, prompts.length) }, () => worker())); |
| 126 | + return results; |
| 127 | +} |
| 128 | + |
| 129 | +export function hostAvailable(project, timeoutMs = 15_000) { |
| 130 | + const config = hostConfig(project); |
| 131 | + if (!/[\\/]/u.test(config.command)) { |
| 132 | + const locator = process.platform === "win32" ? "where.exe" : "which"; |
| 133 | + const found = spawnSync(locator, [config.command], { encoding: "utf8", timeout: Math.min(timeoutMs, 2_000), stdio: ["ignore", "pipe", "ignore"] }); |
| 134 | + if (found.status !== 0) return false; |
| 135 | + } |
| 136 | + const result = spawnSync(executableForShell(config.command), ["--version"], { |
| 137 | + env: safeEnvironment(), |
| 138 | + shell: process.platform === "win32", |
| 139 | + timeout: timeoutMs, |
| 140 | + encoding: "utf8", |
| 141 | + stdio: ["ignore", "pipe", "pipe"] |
| 142 | + }); |
| 143 | + return result.status === 0 && !result.error; |
| 144 | +} |
0 commit comments