feat: pause non-urgent AI jobs and alert on Claude Pro quota
Deux garde-fous construits sur la jauge de quota ajoutée précédemment : - Analyse et Évolutions (non urgents) restent en file au-delà de 85 % de la session (5h) ou de la semaine, et repartent seuls une fois le quota libéré. Prospection et envois ne sont jamais retardés. - Alerte Discord à 80 % puis 95 %, une seule fois par fenêtre jusqu'au reset, sur le nouvel événement "quota". Le Worker gagne un second garde-fou indépendant du budget $ existant (périmètre différent : seuls les jobs non urgents sont concernés). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01SfihHazrSHXgndJtSNLubJ
This commit is contained in:
parent
1349c36797
commit
b83f98da85
8 changed files with 191 additions and 18 deletions
|
|
@ -7,6 +7,8 @@ import { analyzePrompt, prospectPrompt, templatePrompt, followupTemplatePrompt,
|
|||
import { followupCandidates, followupSubject, isBusinessHours } from './services/followup.js';
|
||||
import { EMAIL_RE, createTransport, buildProspectMail, allowedToSend, makeMessageId } from './services/mailer.js';
|
||||
import { unsubToken } from './crypto.js';
|
||||
import { quotaAlerts } from './services/budget.js';
|
||||
import { notify } from './services/notify.js';
|
||||
import { getProject, repoDir, forgejoToken, globalSmtp, sentSince, getTemplate, saveTemplate, pickVariant } from './projects.js';
|
||||
|
||||
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
||||
|
|
@ -42,7 +44,16 @@ export function makeHandlers(app) {
|
|||
const r = await runClaude({ bin: cfg.claudeBin, ...o });
|
||||
// État du quota Pro (session 5h + semaine), affiché dans la barre système
|
||||
const w = rateLimitWindows(r.rateLimit);
|
||||
if (w) setSetting(db, 'claude_rate_limit_json', JSON.stringify({ at: now(), ...w }));
|
||||
if (w) {
|
||||
setSetting(db, 'claude_rate_limit_json', JSON.stringify({ at: now(), ...w }));
|
||||
for (const a of quotaAlerts(db, w)) {
|
||||
notify(app, 'quota', {
|
||||
title: `Quota Claude : ${a.level}+ % (${a.label})`,
|
||||
level: a.level >= 95 ? 'error' : 'warn',
|
||||
description: `${Math.round(a.utilization * 100)} % utilisé sur la ${a.label}.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
return r;
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ import { Worker } from './services/jobs.js';
|
|||
import { makeHandlers } from './handlers.js';
|
||||
import { Scheduler } from './services/scheduler.js';
|
||||
import { notify, notifyJob } from './services/notify.js';
|
||||
import { budgetState, AI_JOBS } from './services/budget.js';
|
||||
import { budgetState, AI_JOBS, quotaState, isQuotaSensitive } from './services/budget.js';
|
||||
import { layout } from './views.js';
|
||||
|
||||
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
|
|
@ -81,6 +81,12 @@ export function createApp(cfg, { db = openDb(cfg.dataDir), worker = true, create
|
|||
title: 'Budget IA atteint', level: 'warn',
|
||||
description: `${reason[0].toUpperCase()}${reason.slice(1)}. Les jobs IA attendent ; les envois et relances continuent.`,
|
||||
}),
|
||||
quota: () => quotaState(db),
|
||||
isQuotaSensitive,
|
||||
onQuotaHold: (reason) => notify(app, 'quota', {
|
||||
title: 'Job IA reporté (quota serré)', level: 'warn',
|
||||
description: `${reason[0].toUpperCase()}${reason.slice(1)}. Analyse et évolutions attendent ; prospection et envois continuent.`,
|
||||
}),
|
||||
onThermal: (t) => notify(app, 'thermal', {
|
||||
title: 'Pause thermique', level: 'warn',
|
||||
description: `CPU à ${t} °C : les jobs IA attendent que le Pi redescende sous ${cfg.thermalMax - 5} °C.`,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
// Budget IA : plafonds glissants 24 h / 30 j, en équivalent $ API remonté par Claude Code.
|
||||
// Avec un abonnement Pro rien n'est facturé en plus : c'est un garde-fou pour ne pas épuiser le quota.
|
||||
import { getSetting, now } from '../db.js';
|
||||
import { getSetting, setSetting, now } from '../db.js';
|
||||
|
||||
// Jobs qui appellent Claude (les envois et relances n'en consomment pas)
|
||||
export const AI_JOBS = new Set(['analyze', 'prospect', 'template', 'followup_template', 'evolution']);
|
||||
|
|
@ -27,3 +27,52 @@ export function budgetState(db, { at = now() } = {}) {
|
|||
: null;
|
||||
return { day, month, blocked: !!reason, reason };
|
||||
}
|
||||
|
||||
// Jobs IA non urgents : on peut les retarder sans perdre une occasion commerciale.
|
||||
// La prospection et l'envoi (y compris les relances) continuent même quota serré.
|
||||
const QUOTA_SENSITIVE_JOBS = new Set(['analyze', 'evolution']);
|
||||
export const isQuotaSensitive = (type) => QUOTA_SENSITIVE_JOBS.has(type);
|
||||
|
||||
// Palier à partir duquel on reporte : garde de la marge sur le quota du compte Claude
|
||||
// lui-même (pas le budget $ ci-dessus) pour les tâches qui comptent vraiment.
|
||||
export const QUOTA_PAUSE_THRESHOLD = 0.85;
|
||||
|
||||
const WINDOW_LABELS = { fiveHour: 'session Claude (5 h)', sevenDay: 'semaine Claude' };
|
||||
|
||||
/** @returns {{blocked: boolean, reason: string|null}} */
|
||||
export function quotaState(db) {
|
||||
const raw = getSetting(db, 'claude_rate_limit_json');
|
||||
if (!raw) return { blocked: false, reason: null };
|
||||
let rl;
|
||||
try { rl = JSON.parse(raw); } catch { return { blocked: false, reason: null }; }
|
||||
for (const [key, label] of Object.entries(WINDOW_LABELS)) {
|
||||
const w = rl[key];
|
||||
if (w?.utilization >= QUOTA_PAUSE_THRESHOLD) {
|
||||
return { blocked: true, reason: `quota de la ${label} à ${Math.round(w.utilization * 100)} %` };
|
||||
}
|
||||
}
|
||||
return { blocked: false, reason: null };
|
||||
}
|
||||
|
||||
// Alerte Discord à 80 % puis 95 % d'utilisation, une seule fois par fenêtre (jusqu'au reset).
|
||||
const ALERT_LEVELS = [0.95, 0.80];
|
||||
|
||||
/** Renvoie les paliers nouvellement franchis et enregistre l'état pour ne pas re-notifier. */
|
||||
export function quotaAlerts(db, windows) {
|
||||
if (!windows) return [];
|
||||
let prev = {};
|
||||
try { prev = JSON.parse(getSetting(db, 'claude_quota_notified_json', '{}') || '{}'); } catch { prev = {}; }
|
||||
const next = { ...prev };
|
||||
const alerts = [];
|
||||
for (const [key, label] of Object.entries(WINDOW_LABELS)) {
|
||||
const w = windows[key];
|
||||
if (!w) continue;
|
||||
// Une fenêtre qui a tourné (reset passé) repart de zéro : les mêmes paliers peuvent re-sonner
|
||||
const state = prev[key]?.resetsAt === w.resetsAt ? prev[key] : { resetsAt: w.resetsAt, level: 0 };
|
||||
const crossed = ALERT_LEVELS.find((l) => w.utilization >= l && state.level < Math.round(l * 100));
|
||||
if (crossed) alerts.push({ label, level: Math.round(crossed * 100), utilization: w.utilization });
|
||||
next[key] = { resetsAt: w.resetsAt, level: crossed ? Math.round(crossed * 100) : state.level };
|
||||
}
|
||||
setSetting(db, 'claude_quota_notified_json', JSON.stringify(next));
|
||||
return alerts;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,12 +39,19 @@ export function latestJobs(db, projectId) {
|
|||
}
|
||||
|
||||
export class Worker {
|
||||
constructor(db, handlers, { thermalMax = 75, pollMs = 3000, log = console, clock = now, onFinish, onThermal, budget, isAiJob, onBudget } = {}) {
|
||||
constructor(db, handlers, {
|
||||
thermalMax = 75, pollMs = 3000, log = console, clock = now, onFinish, onThermal,
|
||||
budget, isAiJob, onBudget, quota, isQuotaSensitive, onQuotaHold,
|
||||
} = {}) {
|
||||
this.clock = clock;
|
||||
this.budget = budget; // () => {blocked, reason}
|
||||
this.isAiJob = isAiJob; // (type) => bool : jobs à mettre en attente si budget atteint
|
||||
this.isAiJob = isAiJob; // (type) => bool : jobs à mettre en attente si budget ($ équivalent) atteint
|
||||
this.onBudget = onBudget; // (reason) → une notif quand le blocage commence
|
||||
this.budgetBlocked = false;
|
||||
this.quota = quota; // () => {blocked, reason} : quota du compte Claude lui-même (session/semaine)
|
||||
this.isQuotaSensitive = isQuotaSensitive; // (type) => bool : jobs à reporter si le quota est serré (pas la prospection/l'envoi)
|
||||
this.onQuotaHold = onQuotaHold; // (reason) → une notif quand le report commence
|
||||
this.quotaBlocked = false;
|
||||
this.onFinish = onFinish; // (job, {status, result, error}) → notifications
|
||||
this.onThermal = onThermal; // (°C) → une fois par pause
|
||||
this.db = db;
|
||||
|
|
@ -86,22 +93,28 @@ export class Worker {
|
|||
AND (run_after IS NULL OR run_after <= ?) ORDER BY id`).all(this.clock());
|
||||
if (!due.length) return false;
|
||||
|
||||
// Budget atteint : les jobs IA restent en file (pas perdus), les autres passent devant
|
||||
// Budget $ atteint ou quota du compte Claude serré : les jobs concernés restent en file
|
||||
// (pas perdus), les autres passent devant. Deux garde-fous indépendants, deux périmètres :
|
||||
// le budget met en pause TOUS les jobs IA, le quota ne retarde que les jobs non urgents
|
||||
// (analyse, évolutions) — la prospection et les envois continuent.
|
||||
const budget = this.budget?.() || { blocked: false };
|
||||
const quota = this.quota?.() || { blocked: false };
|
||||
const hold = (j, reason) => {
|
||||
const msg = JSON.stringify({ message: `En attente : ${reason}` });
|
||||
if (j.progress_json !== msg) this.db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(msg, j.id);
|
||||
};
|
||||
let job = null;
|
||||
let waiting = false;
|
||||
let waiting = false, quotaWaiting = false;
|
||||
for (const j of due) {
|
||||
if (budget.blocked && this.isAiJob?.(j.type)) {
|
||||
waiting = true;
|
||||
const msg = JSON.stringify({ message: `En attente : ${budget.reason}` });
|
||||
if (j.progress_json !== msg) this.db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(msg, j.id);
|
||||
continue;
|
||||
}
|
||||
if (budget.blocked && this.isAiJob?.(j.type)) { waiting = true; hold(j, budget.reason); continue; }
|
||||
if (quota.blocked && this.isQuotaSensitive?.(j.type)) { quotaWaiting = true; hold(j, quota.reason); continue; }
|
||||
job = j;
|
||||
break;
|
||||
}
|
||||
if (waiting && !this.budgetBlocked) this.emit('onBudget', budget.reason);
|
||||
this.budgetBlocked = waiting;
|
||||
if (quotaWaiting && !this.quotaBlocked) this.emit('onQuotaHold', quota.reason);
|
||||
this.quotaBlocked = quotaWaiting;
|
||||
if (!job) return false;
|
||||
const handler = this.handlers[job.type];
|
||||
if (!handler) {
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ export const EVENTS = {
|
|||
followup: 'Relances envoyées',
|
||||
thermal: 'Pause thermique du Pi',
|
||||
budget: 'Budget IA atteint',
|
||||
quota: 'Quota Claude proche de la limite, ou job reporté',
|
||||
weekly: 'Rapport hebdo',
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { openDb, now, setSetting } from '../src/db.js';
|
||||
import { budgetState, AI_JOBS } from '../src/services/budget.js';
|
||||
import { budgetState, AI_JOBS, quotaState, isQuotaSensitive, quotaAlerts } from '../src/services/budget.js';
|
||||
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
||||
|
||||
function setup() {
|
||||
|
|
@ -73,3 +73,70 @@ test('budget atteint : les jobs IA attendent (pas perdus), les envois passent, u
|
|||
await w.tick();
|
||||
assert.equal(alerts.length, 2, 'nouvelle notif pour un nouveau blocage');
|
||||
});
|
||||
|
||||
test('analyse et évolutions sont "non urgents", pas la prospection ni l\'envoi', () => {
|
||||
for (const t of ['analyze', 'evolution']) assert.equal(isQuotaSensitive(t), true);
|
||||
for (const t of ['prospect', 'template', 'followup_template', 'send', 'followup']) assert.equal(isQuotaSensitive(t), false);
|
||||
});
|
||||
|
||||
test('quotaState : pas mesuré, en dessous du seuil, puis bloqué à 85 %', () => {
|
||||
const s = setup();
|
||||
assert.deepEqual(quotaState(s.db), { blocked: false, reason: null });
|
||||
setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.5 }, sevenDay: { utilization: 0.6 } }));
|
||||
assert.equal(quotaState(s.db).blocked, false);
|
||||
setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.9 }, sevenDay: { utilization: 0.6 } }));
|
||||
let q = quotaState(s.db);
|
||||
assert.equal(q.blocked, true);
|
||||
assert.equal(q.reason, 'quota de la session Claude (5 h) à 90 %');
|
||||
setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.1 }, sevenDay: { utilization: 0.99 } }));
|
||||
q = quotaState(s.db);
|
||||
assert.equal(q.reason, 'quota de la semaine Claude à 99 %');
|
||||
setSetting(s.db, 'claude_rate_limit_json', 'pas du json');
|
||||
assert.deepEqual(quotaState(s.db), { blocked: false, reason: null }, 'jamais planter sur une valeur corrompue');
|
||||
});
|
||||
|
||||
test('quota serré : analyse/évolution attendent, la prospection et l\'envoi continuent', async () => {
|
||||
const s = setup();
|
||||
setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.9 } }));
|
||||
const ran = [];
|
||||
const alerts = [];
|
||||
const h = (name) => async () => { ran.push(name); };
|
||||
const w = new Worker(s.db, { prospect: h('prospect'), evolution: h('evolution'), analyze: h('analyze') }, {
|
||||
thermalMax: 999, log: { error() {} },
|
||||
quota: () => quotaState(s.db), isQuotaSensitive, onQuotaHold: (r) => alerts.push(r),
|
||||
});
|
||||
enqueue(s.db, { projectId: 1, type: 'evolution' });
|
||||
enqueue(s.db, { projectId: 1, type: 'analyze' });
|
||||
enqueue(s.db, { projectId: 1, type: 'prospect' });
|
||||
|
||||
assert.equal(await w.tick(), true);
|
||||
assert.deepEqual(ran, ['prospect'], 'la prospection passe devant les jobs reportés');
|
||||
assert.equal(alerts.length, 1);
|
||||
assert.match(alerts[0], /quota de la session Claude \(5 h\) à 90 %/);
|
||||
const jobs = latestJobs(s.db, 1);
|
||||
assert.match(jobs.evolution.progress.message, /^En attente : quota de la session/);
|
||||
|
||||
setSetting(s.db, 'claude_rate_limit_json', JSON.stringify({ fiveHour: { utilization: 0.1 } }));
|
||||
await w.tick(); await w.tick();
|
||||
assert.deepEqual(ran, ['prospect', 'evolution', 'analyze'], 'repartent tout seuls une fois le quota libéré');
|
||||
});
|
||||
|
||||
test('quotaAlerts : un palier (80 %, 95 %) une seule fois, re-sonne si la fenêtre a tourné', () => {
|
||||
const s = setup();
|
||||
let a = quotaAlerts(s.db, { fiveHour: { utilization: 0.5, resetsAt: 100 } });
|
||||
assert.deepEqual(a, []);
|
||||
a = quotaAlerts(s.db, { fiveHour: { utilization: 0.82, resetsAt: 100 } });
|
||||
assert.deepEqual(a, [{ label: 'session Claude (5 h)', level: 80, utilization: 0.82 }]);
|
||||
// toujours au-dessus de 80 %, même fenêtre : pas de redite
|
||||
a = quotaAlerts(s.db, { fiveHour: { utilization: 0.88, resetsAt: 100 } });
|
||||
assert.deepEqual(a, []);
|
||||
// passe 95 % : nouveau palier
|
||||
a = quotaAlerts(s.db, { fiveHour: { utilization: 0.97, resetsAt: 100 } });
|
||||
assert.deepEqual(a, [{ label: 'session Claude (5 h)', level: 95, utilization: 0.97 }]);
|
||||
// la fenêtre a tourné (nouveau resetsAt) : 80 % re-sonne
|
||||
a = quotaAlerts(s.db, { fiveHour: { utilization: 0.81, resetsAt: 200 } });
|
||||
assert.deepEqual(a, [{ label: 'session Claude (5 h)', level: 80, utilization: 0.81 }]);
|
||||
// saut direct à 95 % : un seul palier notifié, pas 80 puis 95
|
||||
a = quotaAlerts(s.db, { sevenDay: { utilization: 0.97, resetsAt: 300 } });
|
||||
assert.deepEqual(a, [{ label: 'semaine Claude', level: 95, utilization: 0.97 }]);
|
||||
});
|
||||
|
|
|
|||
7
test/fixtures/fake-claude.js
vendored
7
test/fixtures/fake-claude.js
vendored
|
|
@ -15,9 +15,10 @@ const lines = prompt.includes('fiche commerciale') ? ['```json\n' + JSON.stringi
|
|||
'PROSPECT {"company":"Coiffure Zen","email":"Hello@Zen.fr","website":"https://zen.fr","city":"Vern","score":6,"source":"https://zen.fr"}']
|
||||
: ['```json\n{"ok":true,"args":' + JSON.stringify(process.argv.slice(2)) + '}\n```'];
|
||||
for (const t of lines) out({ type: 'assistant', message: { content: [{ type: 'text', text: t }] } });
|
||||
// Quota du compte (session 5h + semaine), remonté par la vraie CLI à chaque appel
|
||||
// Quota du compte (session 5h + semaine), remonté par la vraie CLI à chaque appel.
|
||||
// Surchargeable par les tests qui veulent simuler un quota serré (FAKE_FIVE_HOUR / FAKE_SEVEN_DAY).
|
||||
out({ type: 'rate_limit_event', rate_limit_info: { status: 'allowed', unifiedWindows: {
|
||||
five_hour: { utilization: 0.33, resetsAt: 1_700_000_000 },
|
||||
seven_day: { utilization: 0.5, resetsAt: 1_700_300_000 },
|
||||
five_hour: { utilization: Number(process.env.FAKE_FIVE_HOUR ?? 0.33), resetsAt: 1_700_000_000 },
|
||||
seven_day: { utilization: Number(process.env.FAKE_SEVEN_DAY ?? 0.5), resetsAt: 1_700_300_000 },
|
||||
} } });
|
||||
out({ type: 'result', subtype: 'success', is_error: false, result: lines[lines.length - 1], total_cost_usd: 0.0123, num_turns: 2, usage: { input_tokens: 100, cache_read_input_tokens: 50, output_tokens: 20 } });
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import { createProject, saveSecretConfig, getProject, prospectStats, pickVariant
|
|||
import { allowedToSend, buildProspectMail, fillTemplate } from '../src/services/mailer.js';
|
||||
import { validateSelect, firstValue } from '../src/services/recap.js';
|
||||
import { validateGitUrl } from '../src/services/git.js';
|
||||
import { verifyUnsubToken } from '../src/crypto.js';
|
||||
import { verifyUnsubToken, encrypt } from '../src/crypto.js';
|
||||
|
||||
function setup() {
|
||||
const tmp = mkdtempSync(join(tmpdir(), 'aitools-'));
|
||||
|
|
@ -202,3 +202,28 @@ test('analyse : modèle économique (Haiku) par défaut, Sonnet uniquement sur d
|
|||
assert.deepEqual(readFileSync(spyFile, 'utf8').trim().split('\n'), ['haiku', 'sonnet']);
|
||||
} finally { delete process.env.MODEL_SPY_FILE; rmSync(s.tmp, { recursive: true, force: true }); }
|
||||
});
|
||||
|
||||
test('quota Claude serré : alerte Discord à 80 %, pas en dessous', async () => {
|
||||
const s = setup();
|
||||
const sent = [];
|
||||
s.app.fetch = async (url, opts) => { sent.push({ url, body: JSON.parse(opts.body) }); return { ok: true, status: 204 }; };
|
||||
const hook = 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz-ABC_123';
|
||||
setSetting(s.db, 'discord_webhook_enc', encrypt(s.app.cfg.secretKey, hook));
|
||||
try {
|
||||
const a = await run(s, 'analyze'); // fake-claude : 33 % / 50 % par défaut
|
||||
assert.equal(a.status, 'done', a.error);
|
||||
assert.equal(sent.length, 0, 'sous le seuil : pas d\'alerte');
|
||||
|
||||
process.env.FAKE_FIVE_HOUR = '0.84';
|
||||
const a2 = await run(s, 'analyze');
|
||||
assert.equal(a2.status, 'done', a2.error);
|
||||
assert.equal(sent.length, 1);
|
||||
assert.equal(sent[0].url, hook);
|
||||
assert.match(sent[0].body.embeds[0].title, /80\+ % \(session Claude \(5 h\)\)/);
|
||||
|
||||
// reste au-dessus de 80 % : pas de redite
|
||||
const a3 = await run(s, 'analyze');
|
||||
assert.equal(a3.status, 'done', a3.error);
|
||||
assert.equal(sent.length, 1);
|
||||
} finally { delete process.env.FAKE_FIVE_HOUR; rmSync(s.tmp, { recursive: true, force: true }); }
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue