Files
khb_microservices/packages/khbuild_assistant_prep/src/agents/cli-runner.ts
Yuri Yaryshev 27b9842894
All checks were successful
ci / test (push) Successful in 14s
ci / deploy (push) Successful in 3m7s
Консольные агенты claude -p вместо рутин: шаги 2-4, Slack Socket Mode, миграция 006, удаление agent_mcp
- khbuild_assistant_prep: agents (cli-runner, сессии, проверка и повторы формата, шаг 2), slack (Socket Mode, приём, шаг 4, Drive/rclone), промты в promts/
- миграция 006: память менеджера, списки дня, журналы проблем/сообщений/запусков; удалены active_task*, ap_agent_invocation
- удалён package agent_mcp; Dockerfile с claude/ffmpeg/exiftool/whisper/rclone; compose-шаблон сервиса агентов
- docs: структура approved/proposed (modules, data_objects, roles), скрипт сводок

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-11 23:24:23 +03:00

83 lines
3.4 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";
import { mkdirSync } from "node:fs";
export type ToolSet = "none" | "chat";
export interface ClaudeCall {
prompt: string;
cwd: string;
sessionId: string;
/** true - продолжить существующую сессию (--resume), false - создать новую с этим id (--session-id). */
resume: boolean;
tools: ToolSet;
}
export interface ClaudeResult {
text: string;
sessionId: string;
costUsd?: number;
durationMs?: number;
}
export type ClaudeRunner = (call: ClaudeCall) => Promise<ClaudeResult>;
export class ClaudeError extends Error {
constructor(
message: string,
readonly kind: "no_session" | "failed" | "timeout",
) {
super(message);
}
}
export interface CliRunnerOptions {
bin: string;
timeoutMs: number;
model?: string;
}
/** Инструменты шага 4: Bash (ffmpeg, whisper, exiftool, rclone), ToolSearch и запросы JobTread через коннектор claude.ai. */
const CHAT_TOOLS = ["--tools", "Bash,ToolSearch", "--allowedTools", "Bash", "ToolSearch", "mcp__claude_ai_JobTread__query", "--permission-mode", "acceptEdits"];
/** Запуск консольного агента `claude -p`: промт через stdin, ответ - JSON (result, session_id, total_cost_usd). */
export function createCliRunner(opts: CliRunnerOptions): ClaudeRunner {
return (call) =>
new Promise<ClaudeResult>((resolve, reject) => {
mkdirSync(call.cwd, { recursive: true });
const args = ["-p", "--output-format", "json", call.resume ? "--resume" : "--session-id", call.sessionId];
if (opts.model) args.push("--model", opts.model);
args.push(...(call.tools === "chat" ? CHAT_TOOLS : ["--tools", ""]));
const child = spawn(opts.bin, args, { cwd: call.cwd, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ANTHROPIC_API_KEY: "" } });
let out = "";
let err = "";
let timedOut = false;
const timer = setTimeout(() => {
timedOut = true;
child.kill("SIGKILL");
}, opts.timeoutMs);
child.stdout.on("data", (d) => (out += d));
child.stderr.on("data", (d) => (err += d));
child.on("error", (e) => {
clearTimeout(timer);
reject(new ClaudeError(`не удалось запустить ${opts.bin}: ${e.message}`, "failed"));
});
child.on("close", (code) => {
clearTimeout(timer);
if (timedOut) return reject(new ClaudeError(`таймаут ${opts.timeoutMs} мс`, "timeout"));
if (code !== 0) {
const msg = `${err}${out}`.slice(0, 500);
return reject(new ClaudeError(`claude exit=${code}: ${msg}`, /No conversation found/i.test(msg) ? "no_session" : "failed"));
}
try {
const j = JSON.parse(out) as { result?: string; session_id?: string; total_cost_usd?: number; duration_ms?: number; is_error?: boolean };
if (j.is_error) return reject(new ClaudeError(`claude вернул ошибку: ${String(j.result).slice(0, 300)}`, "failed"));
resolve({ text: j.result ?? "", sessionId: j.session_id ?? call.sessionId, costUsd: j.total_cost_usd, durationMs: j.duration_ms });
} catch {
reject(new ClaudeError(`не удалось разобрать ответ claude: ${out.slice(0, 200)}`, "failed"));
}
});
child.stdin.on("error", () => undefined);
child.stdin.end(call.prompt);
});
}