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

52 lines
2.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 читает НЕДОВЕРЕННЫЕ документы (письма, вложения, чеки, выписки): без MCP-коннекторов
* (в письме не должно быть возможности заставить агента писать в QuickBooks) и только с инструментами чтения и shell.
*/
export const UNTRUSTED_DOC_ARGS = ["--strict-mcp-config", "--tools", "Read,Bash"];
/** Запуск 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);
});
}