feat: add headless claude runner, sqlite job queue and thermal guard

This commit is contained in:
Tony Averty 2026-10-21 13:46:25 +02:00
parent 7ef87ce20c
commit 31aab93068
No known key found for this signature in database
5 changed files with 338 additions and 0 deletions

110
src/services/claude.js Normal file
View file

@ -0,0 +1,110 @@
// Lance Claude Code en headless (`claude -p`) avec un périmètre d'outils restreint,
// et parse le flux stream-json pour remonter la progression en direct.
import { spawn } from 'node:child_process';
export const MODELS = { rapide: 'haiku', normal: 'sonnet', approfondi: 'opus' };
/**
* @param {object} o
* @param {string} o.prompt
* @param {string} [o.cwd] dossier de travail (clone du repo pour l'analyse)
* @param {string} [o.model] haiku | sonnet | opus
* @param {number} [o.maxTurns] borne dure sur le nombre d'allers-retours (= tokens)
* @param {string[]} [o.tools] outils autorisés, tout le reste est refusé
* @param {string} [o.system] consignes ajoutées au prompt système
* @param {(text:string)=>void} [o.onText] appelé à chaque bloc texte de Claude
* @param {AbortSignal} [o.signal]
* @param {number} [o.timeoutMs]
* @param {string} [o.bin]
*/
export function runClaude(o) {
const args = [
'-p', o.prompt,
'--output-format', 'stream-json', '--verbose',
'--model', o.model || 'haiku',
'--max-turns', String(o.maxTurns || 10),
'--allowedTools', (o.tools || []).join(','),
'--disallowedTools', 'Bash,Edit,Write,MultiEdit,NotebookEdit,Task',
];
if (o.system) args.push('--append-system-prompt', o.system);
// nice : le serveur web reste réactif pendant qu'un job tourne
const child = spawn('nice', ['-n', '10', o.bin || 'claude', ...args], {
cwd: o.cwd, env: process.env, stdio: ['ignore', 'pipe', 'pipe'],
});
return new Promise((resolve, reject) => {
let buf = '';
let stderr = '';
let result = null;
const texts = [];
const timer = setTimeout(() => child.kill('SIGTERM'), o.timeoutMs || 30 * 60_000);
o.signal?.addEventListener('abort', () => child.kill('SIGTERM'), { once: true });
child.stdout.on('data', (chunk) => {
buf += chunk;
let i;
while ((i = buf.indexOf('\n')) >= 0) {
const line = buf.slice(0, i).trim();
buf = buf.slice(i + 1);
if (line) handle(line);
}
});
child.stderr.on('data', (c) => { stderr = (stderr + c).slice(-4000); });
function handle(line) {
let ev;
try { ev = JSON.parse(line); } catch { return; }
if (ev.type === 'assistant') {
for (const block of ev.message?.content || []) {
if (block.type === 'text' && block.text) { texts.push(block.text); o.onText?.(block.text); }
}
} else if (ev.type === 'result') {
result = ev;
}
}
child.on('error', (e) => { clearTimeout(timer); reject(new Error(`Impossible de lancer Claude : ${e.message}`)); });
child.on('close', (code) => {
clearTimeout(timer);
if (buf.trim()) handle(buf.trim());
if (!result) return reject(new Error(`Claude s'est arrêté sans résultat (code ${code}). ${stderr.trim()}`));
const usage = result.usage || {};
resolve({
ok: !result.is_error,
subtype: result.subtype, // success | error_max_turns | ...
text: result.result ?? texts.join('\n'),
allText: texts.join('\n'),
costUsd: result.total_cost_usd ?? null,
tokensIn: (usage.input_tokens || 0) + (usage.cache_read_input_tokens || 0) + (usage.cache_creation_input_tokens || 0),
tokensOut: usage.output_tokens || 0,
turns: result.num_turns,
});
});
});
}
// Extrait le premier objet JSON d'une réponse (Claude entoure parfois de ```json)
export function extractJson(text) {
const fenced = /```(?:json)?\s*([\s\S]*?)```/.exec(text);
const src = fenced ? fenced[1] : text;
const start = src.search(/[[{]/);
if (start < 0) throw new Error('Aucun JSON dans la réponse de Claude');
const open = src[start];
const close = open === '{' ? '}' : ']';
let depth = 0, inStr = false, escNext = false;
for (let i = start; i < src.length; i++) {
const c = src[i];
if (inStr) {
if (escNext) escNext = false;
else if (c === '\\') escNext = true;
else if (c === '"') inStr = false;
continue;
}
if (c === '"') inStr = true;
else if (c === open) depth++;
else if (c === close && --depth === 0) return JSON.parse(src.slice(start, i + 1));
}
throw new Error('JSON incomplet dans la réponse de Claude');
}

129
src/services/jobs.js Normal file
View file

@ -0,0 +1,129 @@
// File de jobs dans SQLite, UN seul worker : un seul `claude` à la fois sur le Pi.
import { now } from '../db.js';
import { waitCool } from './thermal.js';
export function enqueue(db, { projectId, type, params = {} }) {
const running = db.prepare(
"SELECT id FROM jobs WHERE project_id IS ? AND type = ? AND status IN ('queued','running')"
).get(projectId ?? null, type);
if (running) return { id: running.id, existing: true };
const r = db.prepare('INSERT INTO jobs(project_id, type, params_json, created_at) VALUES(?, ?, ?, ?)')
.run(projectId ?? null, type, JSON.stringify(params), now());
return { id: Number(r.lastInsertRowid), existing: false };
}
export function setProgress(db, jobId, progress) {
db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(JSON.stringify(progress), jobId);
}
export function cancelJob(db, jobId) {
db.prepare("UPDATE jobs SET status = 'cancelled', finished_at = ? WHERE id = ? AND status IN ('queued','running')")
.run(now(), jobId);
}
export function latestJobs(db, projectId) {
const rows = db.prepare(`
SELECT j.* FROM jobs j
JOIN (SELECT type, MAX(id) id FROM jobs WHERE project_id = ? GROUP BY type) last ON last.id = j.id
`).all(projectId);
const out = {};
for (const r of rows) {
out[r.type] = {
id: r.id, status: r.status, error: r.error,
progress: r.progress_json ? JSON.parse(r.progress_json) : null,
result: r.result_json ? JSON.parse(r.result_json) : null,
createdAt: r.created_at, finishedAt: r.finished_at,
};
}
return out;
}
export class Worker {
constructor(db, handlers, { thermalMax = 75, pollMs = 3000, log = console } = {}) {
this.db = db;
this.handlers = handlers;
this.thermalMax = thermalMax;
this.pollMs = pollMs;
this.log = log;
this.current = null;
this.stopped = false;
}
start() {
// Un job "running" au démarrage = crash/reboot pendant l'exécution
this.db.prepare("UPDATE jobs SET status = 'error', error = 'Interrompu (redémarrage)', finished_at = ? WHERE status = 'running'").run(now());
this.loop();
}
stop() { this.stopped = true; this.current?.abort(); }
isCancelled(jobId) {
return this.db.prepare('SELECT status FROM jobs WHERE id = ?').get(jobId)?.status === 'cancelled';
}
async loop() {
while (!this.stopped) {
const ran = await this.tick();
if (!ran) await new Promise((r) => setTimeout(r, this.pollMs));
}
}
async tick() {
const job = this.db.prepare("SELECT * FROM jobs WHERE status = 'queued' ORDER BY id LIMIT 1").get();
if (!job) return false;
const handler = this.handlers[job.type];
if (!handler) {
this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=? WHERE id=?").run(`Type inconnu : ${job.type}`, now(), job.id);
return true;
}
await waitCool(this.thermalMax, { onWait: (t) => setProgress(this.db, job.id, { message: `Pause thermique (${t} °C)` }) });
this.db.prepare("UPDATE jobs SET status='running', started_at=? WHERE id=? AND status='queued'").run(now(), job.id);
const ctrl = new AbortController();
this.current = ctrl;
const ctx = {
job,
params: JSON.parse(job.params_json || '{}'),
signal: ctrl.signal,
progress: (p) => setProgress(this.db, job.id, p),
cancelled: () => this.isCancelled(job.id),
usage: { costUsd: 0, tokensIn: 0, tokensOut: 0 },
};
// Annulation depuis l'UI : on surveille la BDD
const watch = setInterval(() => { if (this.isCancelled(job.id)) ctrl.abort(); }, 2000);
try {
const result = await handler(ctx);
if (!this.isCancelled(job.id)) {
this.db.prepare("UPDATE jobs SET status='done', result_json=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?")
.run(JSON.stringify(result ?? null), now(), ctx.usage.costUsd, ctx.usage.tokensIn, ctx.usage.tokensOut, job.id);
}
} catch (e) {
this.log.error(`[job ${job.id} ${job.type}]`, e.message);
if (!this.isCancelled(job.id)) {
this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?")
.run(String(e.message).slice(0, 2000), now(), ctx.usage.costUsd, ctx.usage.tokensIn, ctx.usage.tokensOut, job.id);
}
} finally {
clearInterval(watch);
this.current = null;
}
return true;
}
}
// Ajoute la conso d'un appel Claude au job courant
export function addUsage(ctx, r) {
ctx.usage.costUsd += r.costUsd || 0;
ctx.usage.tokensIn += r.tokensIn || 0;
ctx.usage.tokensOut += r.tokensOut || 0;
}
// Conso des 30 derniers jours, pour la jauge
export function usageSummary(db) {
const since = now() - 30 * 86400;
const day = now() - 86400;
const q = (s) => db.prepare('SELECT COALESCE(SUM(cost_usd),0) cost, COALESCE(SUM(tokens_in),0) tin, COALESCE(SUM(tokens_out),0) tout, COUNT(*) n FROM jobs WHERE created_at > ?').get(s);
return { month: q(since), day: q(day) };
}

18
src/services/thermal.js Normal file
View file

@ -0,0 +1,18 @@
import { readFileSync } from 'node:fs';
// Température CPU en °C (null hors Raspberry / Linux sans capteur)
export function cpuTemp(path = '/sys/class/thermal/thermal_zone0/temp') {
try { return Math.round(Number(readFileSync(path, 'utf8')) / 100) / 10; }
catch { return null; }
}
// Attend que le CPU repasse sous le seuil (hystérésis de 5 °C pour éviter le yo-yo)
export async function waitCool(max, { read = cpuTemp, sleep = (ms) => new Promise((r) => setTimeout(r, ms)), onWait } = {}) {
let t = read();
if (t === null || t < max) return;
while (t !== null && t >= max - 5) {
onWait?.(t);
await sleep(30_000);
t = read();
}
}

13
test/fixtures/fake-claude.js vendored Executable file
View file

@ -0,0 +1,13 @@
#!/usr/bin/env node
// Faux `claude -p` : émet un flux stream-json réaliste. Le prompt pilote le scénario.
const prompt = process.argv[process.argv.indexOf('-p') + 1] || '';
const out = (o) => process.stdout.write(JSON.stringify(o) + '\n');
out({ type: 'system', subtype: 'init', args: process.argv.slice(2) });
if (prompt.includes('CRASH')) process.exit(3);
const lines = prompt.includes('PROSPECTS')
? ['Je cherche...', 'PROSPECT {"company":"Boulangerie Le Fournil","email":"contact@fournil.fr","website":"https://fournil.fr","city":"Rennes","sector":"boulangerie","hook":"Votre fidélité client mérite mieux que le carton.","source":"https://fournil.fr/contact","score":8}',
'PROSPECT {"company":"Bad","email":"pas-un-email","score":5}',
'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 }] } });
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 } });

68
test/services.test.js Normal file
View file

@ -0,0 +1,68 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { resolve } from 'node:path';
import { runClaude, extractJson } from '../src/services/claude.js';
import { waitCool } from '../src/services/thermal.js';
import { openDb, now } from '../src/db.js';
import { enqueue, Worker, latestJobs, cancelJob, addUsage, usageSummary } from '../src/services/jobs.js';
const bin = resolve('test/fixtures/fake-claude.js');
test('runClaude parse le flux et la conso', async () => {
const seen = [];
const r = await runClaude({ bin, prompt: 'hello', model: 'haiku', maxTurns: 3, tools: ['Read', 'Grep'], onText: (t) => seen.push(t) });
assert.equal(r.ok, true);
assert.equal(r.costUsd, 0.0123);
assert.equal(r.tokensIn, 150);
assert.equal(r.tokensOut, 20);
const j = extractJson(r.text);
assert.ok(j.args.includes('--max-turns') && j.args.includes('3'));
assert.ok(j.args.includes('Read,Grep'));
assert.ok(j.args.join(' ').includes('Bash,Edit,Write'));
assert.equal(seen.length, 1);
});
test('runClaude remonte une erreur si le process meurt', async () => {
await assert.rejects(runClaude({ bin, prompt: 'CRASH' }), /sans résultat/);
});
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('```json\n[1,2]\n```'), [1, 2]);
assert.throws(() => extractJson('rien'), /Aucun JSON/);
});
test('waitCool attend la redescente avec hystérésis', async () => {
const temps = [80, 78, 72, 69];
let waits = 0;
await waitCool(75, { read: () => temps.shift(), sleep: async () => {}, onWait: () => waits++ });
assert.equal(waits, 3);
await waitCool(75, { read: () => null });
});
test('worker : exécution, dédoublonnage, erreurs, annulation, conso', async () => {
const db = openDb(':memory:');
db.prepare("INSERT INTO projects(name, git_url, created_at) VALUES('p','u',?)").run(now());
const a = enqueue(db, { projectId: 1, type: 'ok', params: { x: 2 } });
assert.equal(enqueue(db, { projectId: 1, type: 'ok' }).existing, true);
const handlers = {
ok: async (ctx) => { ctx.progress({ found: 1 }); addUsage(ctx, { costUsd: 0.5, tokensIn: 10, tokensOut: 5 }); return { double: ctx.params.x * 2 }; },
boom: async () => { throw new Error('raté'); },
};
const w = new Worker(db, handlers, { thermalMax: 999, log: { error() {} } });
assert.equal(await w.tick(), true);
enqueue(db, { projectId: 1, type: 'boom' });
await w.tick();
const c = enqueue(db, { projectId: 1, type: 'ok' });
cancelJob(db, c.id);
assert.equal(await w.tick(), false);
const jobs = latestJobs(db, 1);
assert.equal(a.id, 1);
assert.equal(jobs.boom.status, 'error');
assert.equal(jobs.boom.error, 'raté');
assert.equal(jobs.ok.status, 'cancelled');
const first = db.prepare('SELECT * FROM jobs WHERE id = 1').get();
assert.equal(first.status, 'done');
assert.deepEqual(JSON.parse(first.result_json), { double: 4 });
assert.equal(usageSummary(db).month.cost, 0.5);
});