Files
khb_microservices/packages/accounting_automation/src/claude-runner.ts

46 lines
1.7 KiB
TypeScript

import { spawn } from "node:child_process";
export interface ClaudeRunOptions {
/** Промпт целиком (stdin). */
prompt: string;
cwd?: string;
timeoutMs?: number;
/** Доп. аргументы после `-p` (например, --output-format json). */
extraArgs?: string[];
}
export interface ClaudeRunResult {
ok: boolean;
stdout: string;
stderr: string;
exitCode: number | null;
timedOut: boolean;
}
/** Запуск Claude-агента; в тестах подменяется. */
export type ClaudeRunner = (o: ClaudeRunOptions) => Promise<ClaudeRunResult>;
export function makeClaudeRunner(cfg: { bin: string; workDir: string; timeoutMs: number; extraArgs: string[]; env?: Record<string, string> }): ClaudeRunner {
return (o) =>
new Promise((resolve) => {
const args = ["--print", "--dangerously-skip-permissions", ...cfg.extraArgs, ...(o.extraArgs ?? [])];
const child = spawn(cfg.bin, args, { cwd: o.cwd ?? cfg.workDir, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ...cfg.env }, shell: process.platform === "win32" });
let stdout = "";
let stderr = "";
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
child.kill("SIGKILL");
}, o.timeoutMs ?? cfg.timeoutMs);
child.stdout.on("data", (d) => (stdout += d));
child.stderr.on("data", (d) => (stderr += d));
child.on("error", (e) => {
clearTimeout(timer);
resolve({ ok: false, stdout, stderr: stderr + String(e), exitCode: null, timedOut });
});
child.on("close", (code) => {
clearTimeout(timer);
resolve({ ok: code === 0 && !timedOut, stdout, stderr, exitCode: code, timedOut });
});
child.stdin.end(o.prompt);
});
}