Compare commits
6 commits
3623035ede
...
896148cb25
| Author | SHA1 | Date | |
|---|---|---|---|
| 896148cb25 | |||
| b83f98da85 | |||
| 1349c36797 | |||
| e17cf9bb08 | |||
| 69045dd196 | |||
| a7b2a12bd7 |
16 changed files with 324 additions and 29 deletions
14
README.md
14
README.md
|
|
@ -12,7 +12,10 @@ idées d'évolutions et récap business. Pensé pour un **Raspberry Pi 4 sans ve
|
||||||
- outils Claude restreints à chaque job (lecture seule pour le code, WebSearch/WebFetch pour la prospection) ;
|
- outils Claude restreints à chaque job (lecture seule pour le code, WebSearch/WebFetch pour la prospection) ;
|
||||||
- `--max-turns` borné ;
|
- `--max-turns` borné ;
|
||||||
- fiche projet générée une fois, puis seulement sur « Réanalyser » ;
|
- fiche projet générée une fois, puis seulement sur « Réanalyser » ;
|
||||||
- Haiku par défaut pour la prospection et les mails.
|
- Haiku par défaut partout (prospection, analyse de projet, mails, relances) ; Sonnet/Opus restent
|
||||||
|
disponibles en Réglages (prospection, analyse) ou au lancement (niveau de raisonnement de
|
||||||
|
l'Évolution), uniquement quand Haiku ne suffit pas — utile avec un abonnement Pro dont le quota
|
||||||
|
est limité à la semaine.
|
||||||
- **Sécurité** :
|
- **Sécurité** :
|
||||||
- login Google avec whitelist d'emails ;
|
- login Google avec whitelist d'emails ;
|
||||||
- PKCE + state + nonce ;
|
- PKCE + state + nonce ;
|
||||||
|
|
@ -42,12 +45,21 @@ idées d'évolutions et récap business. Pensé pour un **Raspberry Pi 4 sans ve
|
||||||
- **Budget IA** : plafonds glissants sur 24 h et sur 30 jours, en équivalent $ API remonté par Claude Code. L'abonnement Pro ne facture rien en plus ; c'est un garde-fou pour ton quota.
|
- **Budget IA** : plafonds glissants sur 24 h et sur 30 jours, en équivalent $ API remonté par Claude Code. L'abonnement Pro ne facture rien en plus ; c'est un garde-fou pour ton quota.
|
||||||
- Plafond atteint : les jobs IA **restent en file** et repartent seuls quand la fenêtre glisse. Les envois et relances, qui ne consomment pas d'IA, continuent.
|
- Plafond atteint : les jobs IA **restent en file** et repartent seuls quand la fenêtre glisse. Les envois et relances, qui ne consomment pas d'IA, continuent.
|
||||||
- Un job en cours n'est jamais coupé : le plafond peut donc être dépassé d'un job.
|
- Un job en cours n'est jamais coupé : le plafond peut donc être dépassé d'un job.
|
||||||
|
- **Quota du compte Claude** : la barre du haut affiche, dès qu'un job IA a tourné, le taux d'utilisation
|
||||||
|
remonté par la CLI elle-même — session glissante de 5 h et semaine glissante de 7 jours, avec l'heure de
|
||||||
|
réinitialisation au survol. Orange à partir de 80 %, rouge à 100 %. C'est la vraie limite du compte
|
||||||
|
Pro, à distinguer du budget IA ci-dessus (un garde-fou interne en $ équivalent).
|
||||||
|
- **Report automatique** : au-delà de 85 % (session ou semaine), Analyse et Évolutions — non urgents —
|
||||||
|
restent en file et repartent seuls une fois le quota libéré. Prospection et envois (y compris les
|
||||||
|
relances) continuent normalement : c'est le cœur du métier, jamais mis en pause.
|
||||||
|
- **Alerte Discord** à 80 % puis 95 % (session ou semaine), une seule fois par fenêtre jusqu'au reset.
|
||||||
- **Notifications Discord** via webhook : URL chiffrée, validée, sans mention possible. Tu choisis les événements :
|
- **Notifications Discord** via webhook : URL chiffrée, validée, sans mention possible. Tu choisis les événements :
|
||||||
- fin de job ou erreur ;
|
- fin de job ou erreur ;
|
||||||
- réponses de prospects ;
|
- réponses de prospects ;
|
||||||
- relances envoyées ;
|
- relances envoyées ;
|
||||||
- pause thermique ;
|
- pause thermique ;
|
||||||
- budget atteint ;
|
- budget atteint ;
|
||||||
|
- quota Claude proche de la limite, ou job reporté ;
|
||||||
- rapport hebdo.
|
- rapport hebdo.
|
||||||
|
|
||||||
Un bouton permet d'envoyer une notification de test.
|
Un bouton permet d'envoyer une notification de test.
|
||||||
|
|
|
||||||
|
|
@ -44,6 +44,23 @@
|
||||||
return `<span class="${r >= 1 ? 'error' : r >= 0.8 ? 'warn' : ''}" title="Équivalent API, consommé sur ton quota Pro">IA ${label} : ${used} / ${x.limit} $</span>`;
|
return `<span class="${r >= 1 ? 'error' : r >= 0.8 ? 'warn' : ''}" title="Équivalent API, consommé sur ton quota Pro">IA ${label} : ${used} / ${x.limit} $</span>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Quota du compte Claude Pro lui-même (session glissante de 5 h + semaine glissante de 7 j),
|
||||||
|
// remonté par la CLI à chaque appel. Permet de décider en amont si une tâche vaut le coup.
|
||||||
|
function resetLabel(ts) {
|
||||||
|
if (!ts) return '';
|
||||||
|
return new Date(ts * 1000).toLocaleString('fr-FR', { weekday: 'short', hour: '2-digit', minute: '2-digit', timeZone: 'Europe/Paris' });
|
||||||
|
}
|
||||||
|
function claudeBit(label, w) {
|
||||||
|
if (!w) return '';
|
||||||
|
const cls = w.utilization >= 1 ? 'error' : w.utilization >= 0.8 ? 'warn' : '';
|
||||||
|
const reset = resetLabel(w.resetsAt);
|
||||||
|
return `<span class="${cls}"${reset ? ` title="Réinitialisation ${esc(reset)}"` : ''}>Claude ${label} : ${pct(w.utilization)}</span>`;
|
||||||
|
}
|
||||||
|
function claudeQuota(rl) {
|
||||||
|
if (!rl) return '<span class="muted" title="Mesuré après le premier job IA">Claude : pas encore mesuré</span>';
|
||||||
|
return `${claudeBit('session 5h', rl.fiveHour)} ${claudeBit('semaine', rl.sevenDay)}`.trim();
|
||||||
|
}
|
||||||
|
|
||||||
async function refreshSys() {
|
async function refreshSys() {
|
||||||
const el = $('#sys');
|
const el = $('#sys');
|
||||||
if (!el) return;
|
if (!el) return;
|
||||||
|
|
@ -51,6 +68,7 @@
|
||||||
const s = await api('/api/system');
|
const s = await api('/api/system');
|
||||||
const hot = s.temp !== null && s.temp >= s.thermalMax - 5;
|
const hot = s.temp !== null && s.temp >= s.thermalMax - 5;
|
||||||
el.innerHTML = `${s.temp !== null ? `<span class="${hot ? 'warn' : ''}">${s.temp} °C</span>` : ''}
|
el.innerHTML = `${s.temp !== null ? `<span class="${hot ? 'warn' : ''}">${s.temp} °C</span>` : ''}
|
||||||
|
${claudeQuota(s.claudeRateLimit)}
|
||||||
${gauge('24 h', s.budget.day)} ${gauge('30 j', s.budget.month)}
|
${gauge('24 h', s.budget.day)} ${gauge('30 j', s.budget.month)}
|
||||||
${s.budget.blocked ? '<span class="error">Budget IA atteint : jobs IA en attente</span>' : ''}
|
${s.budget.blocked ? '<span class="error">Budget IA atteint : jobs IA en attente</span>' : ''}
|
||||||
${s.queue ? `<span class="spin-inline"></span>${s.queue} job(s)` : ''}
|
${s.queue ? `<span class="spin-inline"></span>${s.queue} job(s)` : ''}
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,14 @@
|
||||||
// Handlers des jobs en arrière-plan.
|
// Handlers des jobs en arrière-plan.
|
||||||
import { now, getSetting } from './db.js';
|
import { now, getSetting, setSetting } from './db.js';
|
||||||
import { runClaude, extractJson } from './services/claude.js';
|
import { runClaude, extractJson, rateLimitWindows } from './services/claude.js';
|
||||||
import { addUsage } from './services/jobs.js';
|
import { addUsage } from './services/jobs.js';
|
||||||
import { syncRepo } from './services/git.js';
|
import { syncRepo } from './services/git.js';
|
||||||
import { analyzePrompt, prospectPrompt, templatePrompt, followupTemplatePrompt, evolutionPrompt, LEVELS } from './services/prompts.js';
|
import { analyzePrompt, prospectPrompt, templatePrompt, followupTemplatePrompt, evolutionPrompt, LEVELS } from './services/prompts.js';
|
||||||
import { followupCandidates, followupSubject, isBusinessHours } from './services/followup.js';
|
import { followupCandidates, followupSubject, isBusinessHours } from './services/followup.js';
|
||||||
import { EMAIL_RE, createTransport, buildProspectMail, allowedToSend, makeMessageId } from './services/mailer.js';
|
import { EMAIL_RE, createTransport, buildProspectMail, allowedToSend, makeMessageId } from './services/mailer.js';
|
||||||
import { unsubToken } from './crypto.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';
|
import { getProject, repoDir, forgejoToken, globalSmtp, sentSince, getTemplate, saveTemplate, pickVariant } from './projects.js';
|
||||||
|
|
||||||
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
||||||
|
|
@ -38,7 +40,22 @@ export function parseProspectLine(line) {
|
||||||
|
|
||||||
export function makeHandlers(app) {
|
export function makeHandlers(app) {
|
||||||
const { db, cfg } = app;
|
const { db, cfg } = app;
|
||||||
const claude = (o) => runClaude({ bin: cfg.claudeBin, ...o });
|
const claude = async (o) => {
|
||||||
|
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 }));
|
||||||
|
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;
|
||||||
|
};
|
||||||
|
|
||||||
const inHours = () => (app.isBusinessHours || isBusinessHours)();
|
const inHours = () => (app.isBusinessHours || isBusinessHours)();
|
||||||
|
|
||||||
|
|
@ -130,7 +147,8 @@ export function makeHandlers(app) {
|
||||||
|
|
||||||
ctx.progress({ message: 'Analyse du code par Claude…' });
|
ctx.progress({ message: 'Analyse du code par Claude…' });
|
||||||
const { prompt, system } = analyzePrompt(project.name);
|
const { prompt, system } = analyzePrompt(project.name);
|
||||||
const r = await claude({ prompt, system, cwd: dir, model: 'sonnet', maxTurns: 20, tools: ['Read', 'Glob', 'Grep'], signal: ctx.signal });
|
const model = getSetting(db, 'analyze_model', 'haiku');
|
||||||
|
const r = await claude({ prompt, system, cwd: dir, model, maxTurns: 20, tools: ['Read', 'Glob', 'Grep'], signal: ctx.signal });
|
||||||
addUsage(ctx, r);
|
addUsage(ctx, r);
|
||||||
if (!r.ok) throw new Error(`Analyse incomplète (${r.subtype})`);
|
if (!r.ok) throw new Error(`Analyse incomplète (${r.subtype})`);
|
||||||
const profile = extractJson(r.text);
|
const profile = extractJson(r.text);
|
||||||
|
|
|
||||||
|
|
@ -76,6 +76,7 @@ export function registerRoutes(router, app) {
|
||||||
send_delay_min: getSetting(db, 'send_delay_min', '20'),
|
send_delay_min: getSetting(db, 'send_delay_min', '20'),
|
||||||
send_delay_max: getSetting(db, 'send_delay_max', '60'),
|
send_delay_max: getSetting(db, 'send_delay_max', '60'),
|
||||||
prospect_model: getSetting(db, 'prospect_model', 'haiku'),
|
prospect_model: getSetting(db, 'prospect_model', 'haiku'),
|
||||||
|
analyze_model: getSetting(db, 'analyze_model', 'haiku'),
|
||||||
blacklist_count: db.prepare('SELECT COUNT(*) n FROM blacklist').get().n,
|
blacklist_count: db.prepare('SELECT COUNT(*) n FROM blacklist').get().n,
|
||||||
weekly_report: getSetting(db, 'weekly_report', '0') === '1',
|
weekly_report: getSetting(db, 'weekly_report', '0') === '1',
|
||||||
budget_day_usd: getSetting(db, 'budget_day_usd', ''),
|
budget_day_usd: getSetting(db, 'budget_day_usd', ''),
|
||||||
|
|
@ -98,6 +99,7 @@ export function registerRoutes(router, app) {
|
||||||
setSetting(db, 'send_delay_min', String(dmin));
|
setSetting(db, 'send_delay_min', String(dmin));
|
||||||
setSetting(db, 'send_delay_max', String(dmax));
|
setSetting(db, 'send_delay_max', String(dmax));
|
||||||
setSetting(db, 'prospect_model', b.prospect_model === 'sonnet' ? 'sonnet' : 'haiku');
|
setSetting(db, 'prospect_model', b.prospect_model === 'sonnet' ? 'sonnet' : 'haiku');
|
||||||
|
setSetting(db, 'analyze_model', b.analyze_model === 'sonnet' ? 'sonnet' : 'haiku');
|
||||||
const money = (v) => { const n = Number(String(v || '').replace(',', '.')); return Number.isFinite(n) && n > 0 ? String(Math.round(n * 100) / 100) : ''; };
|
const money = (v) => { const n = Number(String(v || '').replace(',', '.')); return Number.isFinite(n) && n > 0 ? String(Math.round(n * 100) / 100) : ''; };
|
||||||
setSetting(db, 'weekly_report', b.weekly_report === 'on' ? '1' : '0');
|
setSetting(db, 'weekly_report', b.weekly_report === 'on' ? '1' : '0');
|
||||||
setSetting(db, 'budget_day_usd', money(b.budget_day_usd));
|
setSetting(db, 'budget_day_usd', money(b.budget_day_usd));
|
||||||
|
|
@ -133,7 +135,11 @@ export function registerRoutes(router, app) {
|
||||||
const queue = db.prepare(`SELECT COUNT(*) n FROM jobs WHERE status = 'running'
|
const queue = db.prepare(`SELECT COUNT(*) n FROM jobs WHERE status = 'running'
|
||||||
OR (status = 'queued' AND (run_after IS NULL OR run_after <= ?))`).get(now()).n;
|
OR (status = 'queued' AND (run_after IS NULL OR run_after <= ?))`).get(now()).n;
|
||||||
const scheduled = db.prepare("SELECT COUNT(*) n FROM jobs WHERE status = 'queued' AND run_after > ?").get(now()).n;
|
const scheduled = db.prepare("SELECT COUNT(*) n FROM jobs WHERE status = 'queued' AND run_after > ?").get(now()).n;
|
||||||
json(res, { temp: cpuTemp(), queue, scheduled, usage: usageSummary(db), budget: budgetState(db), thermalMax: cfg.thermalMax });
|
const rlRaw = getSetting(db, 'claude_rate_limit_json');
|
||||||
|
json(res, {
|
||||||
|
temp: cpuTemp(), queue, scheduled, usage: usageSummary(db), budget: budgetState(db), thermalMax: cfg.thermalMax,
|
||||||
|
claudeRateLimit: rlRaw ? JSON.parse(rlRaw) : null,
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/api/projects', async ({ req, res }) => {
|
router.post('/api/projects', async ({ req, res }) => {
|
||||||
|
|
@ -225,7 +231,7 @@ export function registerRoutes(router, app) {
|
||||||
}));
|
}));
|
||||||
router.post('/api/projects/:id/evolution', jobRoute('evolution', (b) => ({
|
router.post('/api/projects/:id/evolution', jobRoute('evolution', (b) => ({
|
||||||
count: int(b.count, 1, 20, 5),
|
count: int(b.count, 1, 20, 5),
|
||||||
level: ['rapide', 'normal', 'approfondi'].includes(b.level) ? b.level : 'normal',
|
level: ['rapide', 'normal', 'approfondi'].includes(b.level) ? b.level : 'rapide',
|
||||||
})));
|
})));
|
||||||
router.post('/api/projects/:id/send', jobRoute('send', (b) => ({ count: int(b.count, 1, 100, 10) }), (p, b) => {
|
router.post('/api/projects/:id/send', jobRoute('send', (b) => ({ count: int(b.count, 1, 100, 10) }), (p, b) => {
|
||||||
if (!b.confirm) throw new HttpError(400, 'Confirmation requise');
|
if (!b.confirm) throw new HttpError(400, 'Confirmation requise');
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,7 @@ import { Worker } from './services/jobs.js';
|
||||||
import { makeHandlers } from './handlers.js';
|
import { makeHandlers } from './handlers.js';
|
||||||
import { Scheduler } from './services/scheduler.js';
|
import { Scheduler } from './services/scheduler.js';
|
||||||
import { notify, notifyJob } from './services/notify.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';
|
import { layout } from './views.js';
|
||||||
|
|
||||||
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
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',
|
title: 'Budget IA atteint', level: 'warn',
|
||||||
description: `${reason[0].toUpperCase()}${reason.slice(1)}. Les jobs IA attendent ; les envois et relances continuent.`,
|
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', {
|
onThermal: (t) => notify(app, 'thermal', {
|
||||||
title: 'Pause thermique', level: 'warn',
|
title: 'Pause thermique', level: 'warn',
|
||||||
description: `CPU à ${t} °C : les jobs IA attendent que le Pi redescende sous ${cfg.thermalMax - 5} °C.`,
|
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.
|
// 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.
|
// 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)
|
// Jobs qui appellent Claude (les envois et relances n'en consomment pas)
|
||||||
export const AI_JOBS = new Set(['analyze', 'prospect', 'template', 'followup_template', 'evolution']);
|
export const AI_JOBS = new Set(['analyze', 'prospect', 'template', 'followup_template', 'evolution']);
|
||||||
|
|
@ -27,3 +27,52 @@ export function budgetState(db, { at = now() } = {}) {
|
||||||
: null;
|
: null;
|
||||||
return { day, month, blocked: !!reason, reason };
|
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;
|
||||||
|
}
|
||||||
|
|
|
||||||
|
|
@ -37,6 +37,7 @@ export function runClaude(o) {
|
||||||
let buf = '';
|
let buf = '';
|
||||||
let stderr = '';
|
let stderr = '';
|
||||||
let result = null;
|
let result = null;
|
||||||
|
let rateLimit = null;
|
||||||
const texts = [];
|
const texts = [];
|
||||||
|
|
||||||
const timer = setTimeout(() => child.kill('SIGTERM'), o.timeoutMs || 30 * 60_000);
|
const timer = setTimeout(() => child.kill('SIGTERM'), o.timeoutMs || 30 * 60_000);
|
||||||
|
|
@ -62,6 +63,9 @@ export function runClaude(o) {
|
||||||
}
|
}
|
||||||
} else if (ev.type === 'result') {
|
} else if (ev.type === 'result') {
|
||||||
result = ev;
|
result = ev;
|
||||||
|
} else if (ev.type === 'rate_limit_event' && ev.rate_limit_info) {
|
||||||
|
// Dernier reçu = état le plus à jour (session 5h + semaine), remonté à chaque appel
|
||||||
|
rateLimit = ev.rate_limit_info;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -80,11 +84,24 @@ export function runClaude(o) {
|
||||||
tokensIn: (usage.input_tokens || 0) + (usage.cache_read_input_tokens || 0) + (usage.cache_creation_input_tokens || 0),
|
tokensIn: (usage.input_tokens || 0) + (usage.cache_read_input_tokens || 0) + (usage.cache_creation_input_tokens || 0),
|
||||||
tokensOut: usage.output_tokens || 0,
|
tokensOut: usage.output_tokens || 0,
|
||||||
turns: result.num_turns,
|
turns: result.num_turns,
|
||||||
|
rateLimit,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Normalise la session (5h glissantes) et la semaine (7j glissants) quel que soit le détail
|
||||||
|
// exact remonté par la CLI. Pour afficher où en est le quota Pro avant de lancer un job.
|
||||||
|
export function rateLimitWindows(info) {
|
||||||
|
if (!info) return null;
|
||||||
|
const w = info.unifiedWindows || {};
|
||||||
|
const pick = (k) => (w[k] && typeof w[k].utilization === 'number' ? { utilization: w[k].utilization, resetsAt: w[k].resetsAt ?? null } : null);
|
||||||
|
const fiveHour = pick('five_hour');
|
||||||
|
const sevenDay = pick('seven_day');
|
||||||
|
if (!fiveHour && !sevenDay) return null;
|
||||||
|
return { fiveHour, sevenDay };
|
||||||
|
}
|
||||||
|
|
||||||
// Extrait le premier objet JSON d'une réponse (Claude entoure parfois de ```json)
|
// Extrait le premier objet JSON d'une réponse (Claude entoure parfois de ```json)
|
||||||
export function extractJson(text) {
|
export function extractJson(text) {
|
||||||
const fenced = /```(?:json)?\s*([\s\S]*?)```/.exec(text);
|
const fenced = /```(?:json)?\s*([\s\S]*?)```/.exec(text);
|
||||||
|
|
|
||||||
|
|
@ -39,12 +39,19 @@ export function latestJobs(db, projectId) {
|
||||||
}
|
}
|
||||||
|
|
||||||
export class Worker {
|
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.clock = clock;
|
||||||
this.budget = budget; // () => {blocked, reason}
|
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.onBudget = onBudget; // (reason) → une notif quand le blocage commence
|
||||||
this.budgetBlocked = false;
|
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.onFinish = onFinish; // (job, {status, result, error}) → notifications
|
||||||
this.onThermal = onThermal; // (°C) → une fois par pause
|
this.onThermal = onThermal; // (°C) → une fois par pause
|
||||||
this.db = db;
|
this.db = db;
|
||||||
|
|
@ -86,22 +93,28 @@ export class Worker {
|
||||||
AND (run_after IS NULL OR run_after <= ?) ORDER BY id`).all(this.clock());
|
AND (run_after IS NULL OR run_after <= ?) ORDER BY id`).all(this.clock());
|
||||||
if (!due.length) return false;
|
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 budget = this.budget?.() || { blocked: false };
|
||||||
let job = null;
|
const quota = this.quota?.() || { blocked: false };
|
||||||
let waiting = false;
|
const hold = (j, reason) => {
|
||||||
for (const j of due) {
|
const msg = JSON.stringify({ message: `En attente : ${reason}` });
|
||||||
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);
|
if (j.progress_json !== msg) this.db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(msg, j.id);
|
||||||
continue;
|
};
|
||||||
}
|
let job = null;
|
||||||
|
let waiting = false, quotaWaiting = false;
|
||||||
|
for (const j of due) {
|
||||||
|
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;
|
job = j;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (waiting && !this.budgetBlocked) this.emit('onBudget', budget.reason);
|
if (waiting && !this.budgetBlocked) this.emit('onBudget', budget.reason);
|
||||||
this.budgetBlocked = waiting;
|
this.budgetBlocked = waiting;
|
||||||
|
if (quotaWaiting && !this.quotaBlocked) this.emit('onQuotaHold', quota.reason);
|
||||||
|
this.quotaBlocked = quotaWaiting;
|
||||||
if (!job) return false;
|
if (!job) return false;
|
||||||
const handler = this.handlers[job.type];
|
const handler = this.handlers[job.type];
|
||||||
if (!handler) {
|
if (!handler) {
|
||||||
|
|
|
||||||
|
|
@ -12,6 +12,7 @@ export const EVENTS = {
|
||||||
followup: 'Relances envoyées',
|
followup: 'Relances envoyées',
|
||||||
thermal: 'Pause thermique du Pi',
|
thermal: 'Pause thermique du Pi',
|
||||||
budget: 'Budget IA atteint',
|
budget: 'Budget IA atteint',
|
||||||
|
quota: 'Quota Claude proche de la limite, ou job reporté',
|
||||||
weekly: 'Rapport hebdo',
|
weekly: 'Rapport hebdo',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -202,8 +202,8 @@ function projectItem(p, smtp, dbCfg, imap) {
|
||||||
<form data-action="evolution" data-id="${p.id}" class="inline">
|
<form data-action="evolution" data-id="${p.id}" class="inline">
|
||||||
<label>Nombre d'évolutions<input name="count" type="number" min="1" max="20" value="5"></label>
|
<label>Nombre d'évolutions<input name="count" type="number" min="1" max="20" value="5"></label>
|
||||||
<label>Raisonnement<select name="level">
|
<label>Raisonnement<select name="level">
|
||||||
<option value="rapide">Rapide (Haiku)</option>
|
<option value="rapide" selected>Rapide (Haiku, économe)</option>
|
||||||
<option value="normal" selected>Normal (Sonnet)</option>
|
<option value="normal">Normal (Sonnet, plus cher)</option>
|
||||||
<option value="approfondi">Approfondi (Opus, coûteux)</option>
|
<option value="approfondi">Approfondi (Opus, coûteux)</option>
|
||||||
</select></label>
|
</select></label>
|
||||||
<label>Quand<select name="when"><option value="now">Maintenant</option><option value="night">Cette nuit (1h-6h)</option></select></label>
|
<label>Quand<select name="when"><option value="now">Maintenant</option><option value="night">Cette nuit (1h-6h)</option></select></label>
|
||||||
|
|
@ -295,6 +295,11 @@ ${saved ? '<p class="ok">Enregistré.</p>' : ''}
|
||||||
<option value="haiku" ${s.prospect_model === 'haiku' ? 'selected' : ''}>Haiku (économe)</option>
|
<option value="haiku" ${s.prospect_model === 'haiku' ? 'selected' : ''}>Haiku (économe)</option>
|
||||||
<option value="sonnet" ${s.prospect_model === 'sonnet' ? 'selected' : ''}>Sonnet (plus précis, plus cher)</option>
|
<option value="sonnet" ${s.prospect_model === 'sonnet' ? 'selected' : ''}>Sonnet (plus précis, plus cher)</option>
|
||||||
</select></label>
|
</select></label>
|
||||||
|
<label>Modèle pour l'analyse de projet<select name="analyze_model">
|
||||||
|
<option value="haiku" ${s.analyze_model === 'haiku' ? 'selected' : ''}>Haiku (économe)</option>
|
||||||
|
<option value="sonnet" ${s.analyze_model === 'sonnet' ? 'selected' : ''}>Sonnet (plus précis, plus cher)</option>
|
||||||
|
</select></label>
|
||||||
|
<p class="muted small">Haiku suffit pour la plupart des projets. Repasse en Sonnet uniquement si la fiche générée manque de précision.</p>
|
||||||
<button class="btn primary">Enregistrer</button>
|
<button class="btn primary">Enregistrer</button>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { openDb, now, setSetting } from '../src/db.js';
|
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';
|
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
||||||
|
|
||||||
function setup() {
|
function setup() {
|
||||||
|
|
@ -73,3 +73,70 @@ test('budget atteint : les jobs IA attendent (pas perdus), les envois passent, u
|
||||||
await w.tick();
|
await w.tick();
|
||||||
assert.equal(alerts.length, 2, 'nouvelle notif pour un nouveau blocage');
|
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 }]);
|
||||||
|
});
|
||||||
|
|
|
||||||
6
test/fixtures/fake-claude.js
vendored
6
test/fixtures/fake-claude.js
vendored
|
|
@ -15,4 +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"}']
|
'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```'];
|
: ['```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 }] } });
|
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.
|
||||||
|
// 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: 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 } });
|
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 } });
|
||||||
|
|
|
||||||
14
test/fixtures/spy-claude.js
vendored
Executable file
14
test/fixtures/spy-claude.js
vendored
Executable file
|
|
@ -0,0 +1,14 @@
|
||||||
|
#!/usr/bin/env node
|
||||||
|
// Enregistre le modèle demandé (variable MODEL_SPY_FILE), puis délègue à fake-claude.js.
|
||||||
|
// Sert uniquement à vérifier quel modèle handlers.js choisit réellement.
|
||||||
|
import { appendFileSync } from 'node:fs';
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { resolve, dirname } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const model = process.argv[process.argv.indexOf('--model') + 1] || '';
|
||||||
|
if (process.env.MODEL_SPY_FILE) appendFileSync(process.env.MODEL_SPY_FILE, model + '\n');
|
||||||
|
|
||||||
|
const fakeClaude = resolve(dirname(fileURLToPath(import.meta.url)), 'fake-claude.js');
|
||||||
|
const out = execFileSync(process.execPath, [fakeClaude, ...process.argv.slice(2)]);
|
||||||
|
process.stdout.write(out);
|
||||||
|
|
@ -1,18 +1,18 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { execFileSync } from 'node:child_process';
|
import { execFileSync } from 'node:child_process';
|
||||||
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
|
import { mkdtempSync, writeFileSync, readFileSync, rmSync } from 'node:fs';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join, resolve } from 'node:path';
|
import { join, resolve } from 'node:path';
|
||||||
import { randomBytes } from 'node:crypto';
|
import { randomBytes } from 'node:crypto';
|
||||||
import { openDb, setSetting, now } from '../src/db.js';
|
import { openDb, setSetting, getSetting, now } from '../src/db.js';
|
||||||
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
import { Worker, enqueue, latestJobs } from '../src/services/jobs.js';
|
||||||
import { makeHandlers, parseProspectLine } from '../src/handlers.js';
|
import { makeHandlers, parseProspectLine } from '../src/handlers.js';
|
||||||
import { createProject, saveSecretConfig, getProject, prospectStats, pickVariant } from '../src/projects.js';
|
import { createProject, saveSecretConfig, getProject, prospectStats, pickVariant } from '../src/projects.js';
|
||||||
import { allowedToSend, buildProspectMail, fillTemplate } from '../src/services/mailer.js';
|
import { allowedToSend, buildProspectMail, fillTemplate } from '../src/services/mailer.js';
|
||||||
import { validateSelect, firstValue } from '../src/services/recap.js';
|
import { validateSelect, firstValue } from '../src/services/recap.js';
|
||||||
import { validateGitUrl } from '../src/services/git.js';
|
import { validateGitUrl } from '../src/services/git.js';
|
||||||
import { verifyUnsubToken } from '../src/crypto.js';
|
import { verifyUnsubToken, encrypt } from '../src/crypto.js';
|
||||||
|
|
||||||
function setup() {
|
function setup() {
|
||||||
const tmp = mkdtempSync(join(tmpdir(), 'aitools-'));
|
const tmp = mkdtempSync(join(tmpdir(), 'aitools-'));
|
||||||
|
|
@ -48,6 +48,9 @@ test('flux complet : analyse → cible → prospection → modèle → envoi →
|
||||||
assert.equal(p.target.zone, 'Bretagne');
|
assert.equal(p.target.zone, 'Bretagne');
|
||||||
assert.equal(p.targetValidated, false);
|
assert.equal(p.targetValidated, false);
|
||||||
assert.match(p.profileCommit, /^[0-9a-f]{40}$/);
|
assert.match(p.profileCommit, /^[0-9a-f]{40}$/);
|
||||||
|
const rl = JSON.parse(getSetting(s.db, 'claude_rate_limit_json'));
|
||||||
|
assert.equal(rl.fiveHour.utilization, 0.33, 'quota Claude (session) enregistré après l\'appel');
|
||||||
|
assert.equal(rl.sevenDay.utilization, 0.5, 'quota Claude (semaine) enregistré après l\'appel');
|
||||||
|
|
||||||
const refused = await run(s, 'prospect', { count: 3 });
|
const refused = await run(s, 'prospect', { count: 3 });
|
||||||
assert.match(refused.error, /Valide la cible/);
|
assert.match(refused.error, /Valide la cible/);
|
||||||
|
|
@ -184,3 +187,43 @@ test('sans objet B : tout part en A', () => {
|
||||||
assert.equal(pickVariant(db, 1, { subject_b: null }), 'A');
|
assert.equal(pickVariant(db, 1, { subject_b: null }), 'A');
|
||||||
assert.equal(pickVariant(db, 1, { subject_b: '' }), 'A');
|
assert.equal(pickVariant(db, 1, { subject_b: '' }), 'A');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('analyse : modèle économique (Haiku) par défaut, Sonnet uniquement sur demande', async () => {
|
||||||
|
const s = setup();
|
||||||
|
const spyFile = join(s.tmp, 'models.log');
|
||||||
|
s.app.cfg.claudeBin = resolve('test/fixtures/spy-claude.js');
|
||||||
|
process.env.MODEL_SPY_FILE = spyFile;
|
||||||
|
try {
|
||||||
|
const a = await run(s, 'analyze');
|
||||||
|
assert.equal(a.status, 'done', a.error);
|
||||||
|
setSetting(s.db, 'analyze_model', 'sonnet');
|
||||||
|
const a2 = await run(s, 'analyze');
|
||||||
|
assert.equal(a2.status, 'done', a2.error);
|
||||||
|
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 }); }
|
||||||
|
});
|
||||||
|
|
|
||||||
|
|
@ -4,7 +4,7 @@ import { randomBytes } from 'node:crypto';
|
||||||
import { mkdtempSync, rmSync } from 'node:fs';
|
import { mkdtempSync, rmSync } from 'node:fs';
|
||||||
import { tmpdir } from 'node:os';
|
import { tmpdir } from 'node:os';
|
||||||
import { join } from 'node:path';
|
import { join } from 'node:path';
|
||||||
import { openDb, now } from '../src/db.js';
|
import { openDb, now, setSetting } from '../src/db.js';
|
||||||
import { createApp } from '../src/server.js';
|
import { createApp } from '../src/server.js';
|
||||||
import { unsubToken } from '../src/crypto.js';
|
import { unsubToken } from '../src/crypto.js';
|
||||||
|
|
||||||
|
|
@ -77,13 +77,14 @@ test('dashboard, réglages, création de projet et statut', async () => {
|
||||||
assert.equal(r.status, 400);
|
assert.equal(r.status, 400);
|
||||||
assert.match((await r.json()).error, /Forgejo/);
|
assert.match((await r.json()).error, /Forgejo/);
|
||||||
|
|
||||||
r = await post('/settings', { notify_email: 'moi@x.fr', forgejo_host: 'https://git.tony-averty.dev/', forgejo_token: 'tok123', global_daily_cap: '9999', send_delay_min: '1', send_delay_max: '2', prospect_model: 'opus' }, { form: true });
|
r = await post('/settings', { notify_email: 'moi@x.fr', forgejo_host: 'https://git.tony-averty.dev/', forgejo_token: 'tok123', global_daily_cap: '9999', send_delay_min: '1', send_delay_max: '2', prospect_model: 'opus', analyze_model: 'opus' }, { form: true });
|
||||||
assert.equal(r.status, 303);
|
assert.equal(r.status, 303);
|
||||||
const s = (k) => app.db.prepare('SELECT value FROM settings WHERE key = ?').get(k)?.value;
|
const s = (k) => app.db.prepare('SELECT value FROM settings WHERE key = ?').get(k)?.value;
|
||||||
assert.equal(s('forgejo_host'), 'git.tony-averty.dev');
|
assert.equal(s('forgejo_host'), 'git.tony-averty.dev');
|
||||||
assert.equal(s('global_daily_cap'), '300', 'plafond borné');
|
assert.equal(s('global_daily_cap'), '300', 'plafond borné');
|
||||||
assert.equal(s('send_delay_min'), '5');
|
assert.equal(s('send_delay_min'), '5');
|
||||||
assert.equal(s('prospect_model'), 'haiku', 'opus refusé pour la prospection');
|
assert.equal(s('prospect_model'), 'haiku', 'opus refusé pour la prospection');
|
||||||
|
assert.equal(s('analyze_model'), 'haiku', 'opus refusé pour l\'analyse');
|
||||||
assert.ok(!s('forgejo_token_enc').includes('tok123'), 'token chiffré');
|
assert.ok(!s('forgejo_token_enc').includes('tok123'), 'token chiffré');
|
||||||
|
|
||||||
r = await post('/api/projects', { name: 'MEP', gitUrl: 'https://github.com/Tony/MEP.git' });
|
r = await post('/api/projects', { name: 'MEP', gitUrl: 'https://github.com/Tony/MEP.git' });
|
||||||
|
|
@ -201,8 +202,13 @@ test('budget : réglages, jauge et avertissement au lancement', async () => {
|
||||||
assert.equal(s('budget_day_usd'), '0.5', 'virgule française acceptée');
|
assert.equal(s('budget_day_usd'), '0.5', 'virgule française acceptée');
|
||||||
assert.equal(s('budget_month_usd'), '', 'valeur invalide = pas de limite');
|
assert.equal(s('budget_month_usd'), '', 'valeur invalide = pas de limite');
|
||||||
app.db.prepare("INSERT INTO jobs(type, status, cost_usd, created_at, finished_at) VALUES('evolution', 'done', 0.8, ?, ?)").run(now(), now());
|
app.db.prepare("INSERT INTO jobs(type, status, cost_usd, created_at, finished_at) VALUES('evolution', 'done', 0.8, ?, ?)").run(now(), now());
|
||||||
const sys = await (await get('/api/system')).json();
|
let sys = await (await get('/api/system')).json();
|
||||||
assert.equal(sys.budget.blocked, true);
|
assert.equal(sys.budget.blocked, true);
|
||||||
|
assert.equal(sys.claudeRateLimit, null, 'pas encore mesuré sans appel Claude');
|
||||||
|
setSetting(app.db, 'claude_rate_limit_json', JSON.stringify({ at: now(), fiveHour: { utilization: 0.42, resetsAt: 123 }, sevenDay: { utilization: 0.1, resetsAt: 456 } }));
|
||||||
|
sys = await (await get('/api/system')).json();
|
||||||
|
assert.equal(sys.claudeRateLimit.fiveHour.utilization, 0.42);
|
||||||
|
assert.equal(sys.claudeRateLimit.sevenDay.utilization, 0.1);
|
||||||
const id = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
const id = app.db.prepare('SELECT id FROM projects LIMIT 1').get().id;
|
||||||
app.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status IN ('queued', 'running')").run();
|
app.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status IN ('queued', 'running')").run();
|
||||||
r = await post(`/api/projects/${id}/evolution`, { count: 2, level: 'rapide' });
|
r = await post(`/api/projects/${id}/evolution`, { count: 2, level: 'rapide' });
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
import { test } from 'node:test';
|
import { test } from 'node:test';
|
||||||
import assert from 'node:assert/strict';
|
import assert from 'node:assert/strict';
|
||||||
import { resolve } from 'node:path';
|
import { resolve } from 'node:path';
|
||||||
import { runClaude, extractJson } from '../src/services/claude.js';
|
import { runClaude, extractJson, rateLimitWindows } from '../src/services/claude.js';
|
||||||
import { waitCool } from '../src/services/thermal.js';
|
import { waitCool } from '../src/services/thermal.js';
|
||||||
import { openDb, now } from '../src/db.js';
|
import { openDb, now } from '../src/db.js';
|
||||||
import { enqueue, Worker, latestJobs, cancelJob, addUsage, usageSummary } from '../src/services/jobs.js';
|
import { enqueue, Worker, latestJobs, cancelJob, addUsage, usageSummary } from '../src/services/jobs.js';
|
||||||
|
|
@ -20,12 +20,26 @@ test('runClaude parse le flux et la conso', async () => {
|
||||||
assert.ok(j.args.includes('Read,Grep'));
|
assert.ok(j.args.includes('Read,Grep'));
|
||||||
assert.ok(j.args.join(' ').includes('Bash,Edit,Write'));
|
assert.ok(j.args.join(' ').includes('Bash,Edit,Write'));
|
||||||
assert.equal(seen.length, 1);
|
assert.equal(seen.length, 1);
|
||||||
|
assert.deepEqual(r.rateLimit.unifiedWindows.five_hour, { utilization: 0.33, resetsAt: 1_700_000_000 });
|
||||||
});
|
});
|
||||||
|
|
||||||
test('runClaude remonte une erreur si le process meurt', async () => {
|
test('runClaude remonte une erreur si le process meurt', async () => {
|
||||||
await assert.rejects(runClaude({ bin, prompt: 'CRASH' }), /sans résultat/);
|
await assert.rejects(runClaude({ bin, prompt: 'CRASH' }), /sans résultat/);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('rateLimitWindows normalise la session (5h) et la semaine, quel que soit le format reçu', () => {
|
||||||
|
assert.deepEqual(rateLimitWindows({ unifiedWindows: {
|
||||||
|
five_hour: { utilization: 0.1, resetsAt: 111 },
|
||||||
|
seven_day: { utilization: 0.2, resetsAt: 222 },
|
||||||
|
} }), { fiveHour: { utilization: 0.1, resetsAt: 111 }, sevenDay: { utilization: 0.2, resetsAt: 222 } });
|
||||||
|
// Une seule fenêtre présente : l'autre reste null plutôt que de tout rejeter
|
||||||
|
assert.deepEqual(rateLimitWindows({ unifiedWindows: { five_hour: { utilization: 0.4 } } }),
|
||||||
|
{ fiveHour: { utilization: 0.4, resetsAt: null }, sevenDay: null });
|
||||||
|
assert.equal(rateLimitWindows(null), null);
|
||||||
|
assert.equal(rateLimitWindows({}), null);
|
||||||
|
assert.equal(rateLimitWindows({ unifiedWindows: { five_hour: { utilization: 'beaucoup' } } }), null, 'valeur non numérique ignorée');
|
||||||
|
});
|
||||||
|
|
||||||
test('extractJson gère texte, fences et accolades dans les chaînes', () => {
|
test('extractJson gère texte, fences et accolades dans les chaînes', () => {
|
||||||
assert.deepEqual(extractJson('Voilà : {"a":"x}y","b":[1,{"c":2}]} fin'), { a: 'x}y', b: [1, { c: 2 }] });
|
assert.deepEqual(extractJson('Voilà : {"a":"x}y","b":[1,{"c":2}]} fin'), { a: 'x}y', b: [1, { c: 2 }] });
|
||||||
assert.deepEqual(extractJson('```json\n[1,2]\n```'), [1, 2]);
|
assert.deepEqual(extractJson('```json\n[1,2]\n```'), [1, 2]);
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue