Агенты: пилот compact вместо явной памяти по простою (п.81): /compact через 4 или 55 минут по статусу диалога от агента, resume с полным промтом, оценка токенов в agent_usage, предупреждение на 50% недельного лимита
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -29,6 +29,16 @@ export interface LiveRunner {
|
||||
close(cwd: string): void;
|
||||
closeAll(): void;
|
||||
activeCount(): number;
|
||||
/**
|
||||
* Переназначает простой живого процесса: через ms без новых ходов вызовется onIdle и процесс закроется.
|
||||
* Агент сам решает, сколько ждать (диалог закрыт - коротко, ждём ответ - долго).
|
||||
*/
|
||||
scheduleIdle(cwd: string, ms: number): void;
|
||||
/**
|
||||
* Ход `/compact`: claude сжимает контекст сессии (резюме вместо истории), следующий resume читает короткий контекст.
|
||||
* null - процесса нет, он занят, не простаивал minIdleMs или claude не подтвердил сжатие (нет compact_boundary).
|
||||
*/
|
||||
compact(cwd: string, minIdleMs?: number): Promise<(ClaudeResult & { idleMs: number }) | null>;
|
||||
}
|
||||
|
||||
interface Turn {
|
||||
@@ -39,6 +49,7 @@ interface Turn {
|
||||
reject(e: Error): void;
|
||||
timer: NodeJS.Timeout;
|
||||
startedAt: number;
|
||||
compact?: { preTokens: number; postTokens: number; durationMs: number };
|
||||
}
|
||||
|
||||
interface Proc {
|
||||
@@ -53,6 +64,10 @@ interface Proc {
|
||||
/** Накопительные счётчики claude на прошлом ходе; null - процесс продолжает старую сессию и первый ход посчитать нельзя (счётчики включают историю сессии). */
|
||||
lastApiMs: number | null;
|
||||
ready: Promise<void>;
|
||||
/** Когда закончился последний ход (для проверки «действительно простаивал»). */
|
||||
lastResultAt: number;
|
||||
/** Простой, назначенный агентом на следующую паузу (scheduleIdle); null - opts.idleMs. */
|
||||
idleMs: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -67,8 +82,9 @@ export function createLiveRunner(opts: LiveRunnerOptions): LiveRunner {
|
||||
if (p.idle) clearTimeout(p.idle);
|
||||
p.idle = null;
|
||||
};
|
||||
const armIdle = (p: Proc) => {
|
||||
const armIdle = (p: Proc, ms?: number) => {
|
||||
clearIdle(p);
|
||||
if (ms !== undefined) p.idleMs = ms;
|
||||
p.idle = setTimeout(() => {
|
||||
if (p.exited || p.turn) return;
|
||||
const closeNow = () => {
|
||||
@@ -79,7 +95,7 @@ export function createLiveRunner(opts: LiveRunnerOptions): LiveRunner {
|
||||
};
|
||||
if (!opts.onIdle) return closeNow();
|
||||
opts.onIdle(p.cwd).catch(() => undefined).finally(closeNow);
|
||||
}, opts.idleMs);
|
||||
}, p.idleMs ?? opts.idleMs);
|
||||
p.idle.unref?.();
|
||||
};
|
||||
|
||||
@@ -91,6 +107,10 @@ export function createLiveRunner(opts: LiveRunnerOptions): LiveRunner {
|
||||
return;
|
||||
}
|
||||
if (o.type === "system" && o.subtype === "init" && typeof o.session_id === "string") p.sessionId = o.session_id;
|
||||
if (o.type === "system" && o.subtype === "compact_boundary" && p.turn) {
|
||||
const m = (o.compact_metadata ?? {}) as { pre_tokens?: number; post_tokens?: number; duration_ms?: number };
|
||||
p.turn.compact = { preTokens: Number(m.pre_tokens ?? 0), postTokens: Number(m.post_tokens ?? 0), durationMs: Number(m.duration_ms ?? 0) };
|
||||
}
|
||||
if (p.turn) {
|
||||
if (p.turn.firstEventMs === null) p.turn.firstEventMs = Date.now() - p.turn.startedAt;
|
||||
if (o.type === "assistant") {
|
||||
@@ -106,10 +126,12 @@ export function createLiveRunner(opts: LiveRunnerOptions): LiveRunner {
|
||||
const apiTotal = typeof o.duration_api_ms === "number" ? o.duration_api_ms : undefined;
|
||||
const apiMs = apiTotal === undefined || p.lastApiMs === null ? undefined : Math.max(0, apiTotal - p.lastApiMs);
|
||||
if (apiTotal !== undefined) p.lastApiMs = apiTotal;
|
||||
p.lastResultAt = Date.now();
|
||||
p.idleMs = null; // назначенный простой действует на одну паузу
|
||||
armIdle(p);
|
||||
if (o.is_error === true) return t.reject(new ClaudeError(`claude вернул ошибку: ${String(o.result).slice(0, 300)}`, "failed"));
|
||||
t.resolve({
|
||||
text: String(o.result ?? ""), sessionId: p.sessionId, usage: parseUsage(o), durationMs: typeof o.duration_ms === "number" ? o.duration_ms : Date.now() - t.startedAt,
|
||||
text: String(o.result ?? ""), sessionId: p.sessionId, usage: parseUsage(o), durationMs: typeof o.duration_ms === "number" ? o.duration_ms : Date.now() - t.startedAt, compact: t.compact,
|
||||
timing: {
|
||||
startMs: t.startMs, turnMs: Date.now() - t.startedAt, apiMs,
|
||||
claudeMs: typeof o.duration_ms === "number" ? o.duration_ms : undefined, numTurns: typeof o.num_turns === "number" ? o.num_turns : undefined,
|
||||
@@ -128,7 +150,7 @@ export function createLiveRunner(opts: LiveRunnerOptions): LiveRunner {
|
||||
if (opts.model) args.push("--model", opts.model);
|
||||
args.push(...CHAT_TOOLS);
|
||||
const child = spawn(opts.bin, args, { cwd: call.cwd, stdio: ["pipe", "pipe", "pipe"], env: { ...process.env, ANTHROPIC_API_KEY: "", ...call.env } });
|
||||
const p: Proc = { cwd: call.cwd, sessionId: call.sessionId, child, buf: "", stderr: "", turn: null, idle: null, exited: false, lastApiMs: call.resume ? null : 0, ready: Promise.resolve() };
|
||||
const p: Proc = { cwd: call.cwd, sessionId: call.sessionId, child, buf: "", stderr: "", turn: null, idle: null, exited: false, lastApiMs: call.resume ? null : 0, ready: Promise.resolve(), lastResultAt: Date.now(), idleMs: null };
|
||||
child.stdout.on("data", (d) => {
|
||||
p.buf += d;
|
||||
let i: number;
|
||||
@@ -192,17 +214,21 @@ export function createLiveRunner(opts: LiveRunnerOptions): LiveRunner {
|
||||
const proc = p;
|
||||
await proc.ready;
|
||||
if (proc.exited) throw new ClaudeError(`агент завершился до первого промта: ${proc.stderr.slice(0, 300)}`, /No conversation found/i.test(proc.stderr) ? "no_session" : "failed");
|
||||
return sendTurn(proc, call.cwd, call.prompt, tCall);
|
||||
};
|
||||
|
||||
function sendTurn(proc: Proc, cwd: string, text: string, tCall: number): Promise<ClaudeResult> {
|
||||
return new Promise<ClaudeResult>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
proc.turn = null;
|
||||
kill(proc, "таймаут хода");
|
||||
procs.delete(call.cwd);
|
||||
procs.delete(cwd);
|
||||
reject(new ClaudeError(`таймаут ${opts.timeoutMs} мс`, "timeout"));
|
||||
}, opts.timeoutMs);
|
||||
proc.turn = { resolve, reject, timer, startedAt: Date.now(), startMs: Date.now() - tCall, toolCalls: 0, firstEventMs: null };
|
||||
proc.child.stdin.write(JSON.stringify({ type: "user", message: { role: "user", content: call.prompt } }) + "\n");
|
||||
proc.child.stdin.write(JSON.stringify({ type: "user", message: { role: "user", content: text } }) + "\n");
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
run,
|
||||
@@ -228,5 +254,19 @@ export function createLiveRunner(opts: LiveRunnerOptions): LiveRunner {
|
||||
}
|
||||
},
|
||||
activeCount: () => procs.size,
|
||||
scheduleIdle: (cwd, ms) => {
|
||||
const p = procs.get(cwd);
|
||||
if (!p || p.exited || p.turn) return;
|
||||
armIdle(p, ms);
|
||||
},
|
||||
compact: async (cwd, minIdleMs = 0) => {
|
||||
const p = procs.get(cwd);
|
||||
if (!p || p.exited || p.turn) return null;
|
||||
const idleMs = Date.now() - p.lastResultAt;
|
||||
if (idleMs < minIdleMs) return null; // с тех пор был новый ход: процесс не простаивал
|
||||
clearIdle(p);
|
||||
const r = await sendTurn(p, cwd, "/compact", Date.now());
|
||||
return r.compact ? { ...r, idleMs } : null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user