1// admin-ka v2 — backend : pont HTTP/WebSocket ⇄ Claude Code CLI (stream-json)2// Sessions détachées (survivent à la déconnexion du client), permissions3// relayées en cartes, monitoring Écosystème temps réel.4import http from 'node:http';5import net from 'node:net';6import crypto from 'node:crypto';7import fs from 'node:fs';8import path from 'node:path';9import os from 'node:os';10import { spawn } from 'node:child_process';11import { fileURLToPath } from 'node:url';12import { WebSocketServer } from 'ws';13import { startMonitor, ecoSummary, ecoSite, ecoIncidents, ecoNodes, getIcon, SITES } from './monitor.js';14import { initAnalytics, recordHit, analyticsSummary, analyticsSeries, PIXEL } from './analytics.js';15import { initSocial, socialState, socialLog, setAuto, generateDraft, publishDraft, runAutoCycle, cardPath, fbLoginState, generateReelDraft, publishReelDraft, runReelCycle, reelPath, startReelBatch, batchStatus, REEL_BATCH_DEFAULT, getGallery, startGenBatch, genBatchStatus } from './social.js';16import { execFile } from 'node:child_process';1718const __dirname = path.dirname(fileURLToPath(import.meta.url));19const APP_DIR = path.join(__dirname, '..');20const DATA_DIR = path.join(APP_DIR, 'data');21const TRANSCRIPTS_DIR = path.join(DATA_DIR, 'transcripts');22const PUBLIC_DIR = path.join(APP_DIR, 'public');23const HOME = os.homedir();2425fs.mkdirSync(TRANSCRIPTS_DIR, { recursive: true });2627// ---------- config ----------28const CONFIG_PATH = path.join(DATA_DIR, 'config.json');29if (!fs.existsSync(CONFIG_PATH)) {30 console.error('config.json manquant — exécuter: node server/set-password.js <motdepasse>');31 process.exit(1);32}33const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));34const PORT = config.port || 3300;35const CLAUDE_BIN = config.claudeBin || '/opt/homebrew/bin/claude';36const NODE_BIN = config.nodeBin || '/opt/homebrew/bin/node';3738// toutes les variables de ~/.claude/.env (ANTHROPIC_API_KEY, APIFY_TOKEN, …)39// sont injectées dans les runs claude locaux (les runs distants font40// `export $(cat ~/.claude/.env | xargs)` côté nœud)41function loadClaudeEnv() {42 const out = {};43 try {44 for (const line of fs.readFileSync(path.join(HOME, '.claude', '.env'), 'utf8').split('\n')) {45 const m = line.match(/^([A-Z0-9_]+)=(\S+)/);46 if (m) out[m[1]] = m[2];47 }48 } catch {}49 return out;50}51const CLAUDE_ENV = loadClaudeEnv();52const ANTHROPIC_API_KEY = CLAUDE_ENV.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY || '';5354// ---------- Upgradeur de prompt (Anthropic Messages API) ----------55const UPGRADER_KEY = config.anthropicKey || CLAUDE_ENV.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY || '';56const UPGRADER_MODEL = config.upgraderModel || 'claude-opus-4-8';5758// Connaissance du Groupe KA injectée dans l'upgradeur pour produire des prompts59// Claude Code précis, conformes aux standards de l'écosystème.60const KA_KNOWLEDGE = `Tu es l'"upgradeur de prompt" de la console administration-ka.com. Ta seule tâche : réécrire la demande brute de l'utilisateur en un prompt EXCELLENT destiné à Claude Code, qui s'exécute sur le nœud d'une app du Groupe KA. Tu ne réponds jamais à la demande toi-même, tu ne codes pas : tu produis UNIQUEMENT le prompt amélioré, prêt à être envoyé.6162# Écosystème Groupe KA (12 apps web, stack Node/React, cluster MacLustr)63- lou-ka (lou-ka.com) : location immobilière/logements. immo-ka (immo-ka.com) : achat/vente immobilier. vrai-prix (vrai-prix.com) : comparateur de prix. valoplex : immobilier/valorisation. auto-ka (auto-ka.com) : véhicules. fabri-ka (fabri-ka.com) : fabricants/artisans/friperies. food-ka (food-ka.com) : alimentation/épicerie. resto-ka (resto-ka.com) : restaurants. sorti-ka (sorti-ka.com) : sorties/événements. crea-ka (crea-ka.com) : créateurs de contenu QC (multi-plateforme). job-ka (job-ka.com) : emplois. trouve-ka (trouve-ka.com) : recherche/annuaire. groupe-ka.com : hub + KA ID (SSO). Marché cible : Québec (fr-CA).64- Architecture commune : back Node (souvent Express/Fastify), front React/Next ou Vite, données via connecteurs (scrapers) + SQLite/Postgres, PM2 pour les process, ngrok pour les domaines. Beaucoup d'apps ont un backend "sync"/crawler et une couche qualité (published/quarantaine).6566# Conventions NON négociables (rappelle-les dans le prompt quand c'est pertinent)67- Remote-first : la source de vérité est le repo de PROD sur le nœud de déploiement ; on édite là, on build, on redémarre PM2, puis git add/commit/push origin main. origin = spbgit (git perso, git.spboucher.ai), PAS GitHub.68- Après toute modif : rebuild si nécessaire + pm2 restart <app> + vérifier le healthcheck/site + commit & push spbgit. Ne jamais laisser de modif non commitée/non déployée.69- Standards UI Groupe KA : header/nav opaques fixes ; échelle de z-index par variables --z-* ; mobile-first, contenu jamais masqué par le clavier (dvh + safe-area) ; anti-zoom iOS (inputs 16px). Pages détail : l'ordre du DOM = l'ordre visuel identique mobile ET desktop (galerie → prix/adresse → description → inclusions → détails → analyses → carte → KA Scores → quartier), JAMAIS de réordonnancement via order:/column-reverse entre breakpoints.70- Design system ka-ui : tokens/couleurs/footer centralisés (ecosystem.json). Toujours valider en mobile (simulateur/Playwright) après un changement d'UI.7172# Outils de scraping/recherche disponibles sur chaque nœud (variables dans ~/.claude/.env)73- Serper (SERPER_API_KEY, recherche Google, gl:ca hl:fr) et Tavily (TAVILY_API_KEY, search/map/extract/crawl) pour DÉCOUVRIR des sources de connecteurs.74- Scrapfly (SCRAPFLY_KEY) et Bright Data Web Unlocker (BRIGHTDATA_API_KEY, zone web_unlocker1) et Oxylabs (Realtime API OXYLABS_USER/PASS + proxies résidentiels OXYLABS_PROXY_* avec ciblage -cc-CA) pour l'anti-bot.75- Apify : 13 acteurs maison gorgeous_thistle/ka-<plateforme> (instagram, tiktok, x, youtube, twitch, kick, fansly, onlyfans, facebook, threads, snapchat, discord, patreon) pour l'enrichissement multi-plateforme de crea-ka ; apify-cli installé (apify push pour builder).7677# Comment écrire le prompt amélioré781. Écris en français, à l'impératif, adressé à Claude Code.792. Commence par l'objectif clair, puis le périmètre précis (fichiers/zones probables), puis les critères d'acceptation vérifiables.803. Ajoute les détails manquants que la demande sous-entend (edge cases, validation, mobile, i18n fr-CA) sans dénaturer l'intention.814. Rappelle les étapes de clôture attendues (build, pm2 restart, healthcheck, commit+push spbgit) UNIQUEMENT si la tâche modifie du code.825. Demande à Claude Code d'explorer/lire avant de modifier, et de vérifier son travail.836. Reste concis et actionnable : pas de blabla, pas de sections inutiles. N'invente pas de faits spécifiques non fournis.847. Sortie = le prompt amélioré SEUL, sans préambule ("Voici…"), sans guillemets englobants, sans commentaire méta.`;8586async function upgradePrompt(rawPrompt, project) {87 if (!UPGRADER_KEY) throw new Error('Clé Anthropic non configurée (config.anthropicKey).');88 const ctx = project ? `\n\nContexte : la demande vise le projet "${project.name}" (déployé sur le nœud ${project.node || SELF_NODE}, répertoire ${project.dir}).` : '';89 const resp = await fetch('https://api.anthropic.com/v1/messages', {90 method: 'POST',91 headers: {92 'x-api-key': UPGRADER_KEY,93 'anthropic-version': '2023-06-01',94 'content-type': 'application/json',95 },96 body: JSON.stringify({97 model: UPGRADER_MODEL,98 max_tokens: 1500,99 system: KA_KNOWLEDGE,100 messages: [{ role: 'user', content: `Réécris cette demande en un prompt Claude Code excellent.${ctx}\n\nDemande brute :\n${rawPrompt}` }],101 }),102 });103 const data = await resp.json();104 if (data.error) throw new Error(data.error.message || 'Erreur Anthropic');105 const text = (data.content || []).filter(b => b.type === 'text').map(b => b.text).join('').trim();106 if (!text) throw new Error('Réponse vide du modèle');107 return text;108}109110// ---------- audit ----------111const AUDIT_PATH = path.join(DATA_DIR, 'audit.jsonl');112function audit(entry) {113 fs.appendFile(AUDIT_PATH, JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n', () => {});114}115116// ---------- sessions (auth) ----------117const SESSIONS_PATH = path.join(DATA_DIR, 'sessions.json');118let sessions = {};119try { sessions = JSON.parse(fs.readFileSync(SESSIONS_PATH, 'utf8')); } catch {}120function saveSessions() { fs.writeFileSync(SESSIONS_PATH, JSON.stringify(sessions)); }121const SESSION_IDLE_MS = 7 * 24 * 3600 * 1000;122const SESSION_MAX_MS = 30 * 24 * 3600 * 1000;123124function verifyPassword(pw) {125 const hash = crypto.scryptSync(pw, Buffer.from(config.salt, 'hex'), 64).toString('hex');126 return crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(config.passwordHash));127}128function newSession() {129 const token = crypto.randomBytes(32).toString('hex');130 sessions[token] = { created: Date.now(), last: Date.now() };131 saveSessions();132 return token;133}134function getSession(req) {135 const cookie = req.headers.cookie || '';136 const m = cookie.match(/(?:^|;\s*)akid=([a-f0-9]{64})/);137 if (!m) return null;138 const s = sessions[m[1]];139 if (!s) return null;140 const now = Date.now();141 if (now - s.last > SESSION_IDLE_MS || now - s.created > SESSION_MAX_MS) {142 delete sessions[m[1]]; saveSessions(); return null;143 }144 s.last = now;145 return m[1];146}147148const loginFails = new Map();149function clientIp(req) {150 const xf = req.headers['x-forwarded-for'];151 return (xf ? String(xf).split(',')[0].trim() : req.socket.remoteAddress) || '?';152}153function loginAllowed(ip) {154 const rec = loginFails.get(ip);155 if (!rec) return true;156 if (Date.now() - rec.first > 15 * 60 * 1000) { loginFails.delete(ip); return true; }157 return rec.count < 8;158}159function loginFailed(ip) {160 const rec = loginFails.get(ip) || { first: Date.now(), count: 0 };161 rec.count++; loginFails.set(ip, rec);162}163164// ---------- chats ----------165const CHATS_PATH = path.join(DATA_DIR, 'chats.json');166let chats = [];167try { chats = JSON.parse(fs.readFileSync(CHATS_PATH, 'utf8')); } catch {}168// migration v1 → v2169for (const c of chats) {170 if (!c.model) c.model = 'fable';171 if (!c.permMode) c.permMode = c.mode === 'auto' ? 'bypass' : 'default';172 if (!c.state) c.state = 'idle';173 if (c.totalCost === undefined) c.totalCost = 0;174 if (!c.alwaysAllow) c.alwaysAllow = [];175 if (c.autoAllowAll === undefined) c.autoAllowAll = false;176}177function saveChats() { fs.writeFileSync(CHATS_PATH, JSON.stringify(chats, null, 1)); }178function getChat(id) { return chats.find(c => c.id === id); }179function publicChat(c) {180 return {181 id: c.id, title: c.title, projectId: c.projectId, projectName: c.projectName,182 model: c.model, permMode: c.permMode, state: c.state, autoAllowAll: !!c.autoAllowAll,183 claudeSessionId: c.claudeSessionId, lastModel: c.lastModel || null,184 totalCost: c.totalCost || 0, turns: c.turns || 0, contextTokens: c.contextTokens || 0,185 batch: c.batch || null,186 created: c.created, updated: c.updated,187 };188}189function transcriptPath(id) { return path.join(TRANSCRIPTS_DIR, id.replace(/[^a-zA-Z0-9_-]/g, '') + '.jsonl'); }190function appendTranscript(chatId, event) {191 fs.appendFile(transcriptPath(chatId), JSON.stringify(event) + '\n', () => {});192}193function readTranscript(chatId) {194 try {195 return fs.readFileSync(transcriptPath(chatId), 'utf8')196 .split('\n').filter(Boolean).map(l => { try { return JSON.parse(l); } catch { return null; } })197 .filter(Boolean);198 } catch { return []; }199}200201// ---------- prompt bank ----------202const PROMPTS_PATH = path.join(DATA_DIR, 'prompts.json');203let prompts = [];204try { prompts = JSON.parse(fs.readFileSync(PROMPTS_PATH, 'utf8')); } catch {}205function savePrompts() { fs.writeFileSync(PROMPTS_PATH, JSON.stringify(prompts, null, 1)); }206207// ---------- projets (12 apps Groupe KA) ----------208const SELF_NODE = 'M3U96a';209const PROJECTS = [210 { id: 'groupe-ka@M3U96b', name: 'Groupe·Ka', node: 'M3U96b', dir: '~/apps/groupe-ka' },211 { id: 'lou-ka@M3U96b', name: 'Lou·Ka', node: 'M3U96b', dir: '~/apps/lou-ka' },212 { id: 'immo-ka@M4M64a', name: 'Immo·Ka', node: 'M4M64a', dir: '~/apps/immo-ka' },213 { id: 'vrai-prix@M3U96a', name: 'Vrai-Prix', node: null, dir: path.join(HOME, 'apps', 'vrai-prix') },214 { id: 'valoplex@M3U96a', name: 'ValoPlex', node: null, dir: path.join(HOME, 'apps', 'valoplex') },215 { id: 'auto-ka@M4M64b', name: 'Auto·Ka', node: 'M4M64b', dir: '~/auto-ka' },216 { id: 'fabri-ka@M4M64a', name: 'Fabri·Ka', node: 'M4M64a', dir: '~/fabri-ka' },217 { id: 'food-ka@M4M64b', name: 'Food·Ka', node: 'M4M64b', dir: '~/apps/food-ka' },218 { id: 'resto-ka@M3U96b', name: 'Resto·Ka', node: 'M3U96b', dir: '~/apps/resto-ka' },219 { id: 'sorti-ka@M3U96a', name: 'Sorti·Ka', node: null, dir: path.join(HOME, 'apps', 'sorti-ka') },220 { id: 'crea-ka@M3U96b', name: 'Créa·Ka', node: 'M3U96b', dir: '~/apps/crea-ka' },221 { id: 'job-ka@M3U96a', name: 'Job·Ka', node: null, dir: path.join(HOME, 'apps', 'job-ka') },222 { id: 'trouve-ka@M2M32', name: 'Trouve·Ka', node: 'M2M32', dir: '~/trouve-ka' },223];224// Orchestrateur : une seule session sur M3U96a qui pilote les 13 apps via SSH,225// en gardant le contexte complet de la tâche.226const ORCH_PROJECT = { id: 'ORCH', name: '🎛️ Orchestrateur multi-sites', node: null, dir: path.join(HOME, 'ka-orchestrator') };227function listProjects() {228 return [229 { id: ORCH_PROJECT.id, name: ORCH_PROJECT.name, node: SELF_NODE, dir: ORCH_PROJECT.dir },230 ...PROJECTS.map(p => ({ id: p.id, name: p.name, node: p.node || SELF_NODE, dir: p.dir })),231 ];232}233function findProject(id) {234 if (id === 'ORCH') return ORCH_PROJECT;235 return PROJECTS.find(p => p.id === id) || null;236}237238// ---------- exécution Claude Code ----------239const MODELS = ['fable', 'opus', 'sonnet', 'haiku'];240// mappage vers les IDs réels (les alias CLI des nœuds retombent sur d'anciennes versions)241const CLI_MODEL = { fable: 'claude-fable-5', opus: 'claude-opus-5', sonnet: 'claude-sonnet-5', haiku: 'claude-haiku-4-5-20251001' };242const DEFAULT_MODEL = 'fable';243const PERM_MODES = ['default', 'acceptEdits', 'plan', 'bypass'];244const ALLOWED_READONLY = 'Read,Glob,Grep,LS,WebFetch,WebSearch,TodoWrite,NotebookRead,Task';245246const SYSTEM_APPEND = `RÈGLE OBLIGATOIRE (console administration-ka) : si tu as modifié des fichiers du projet pendant ce tour, tu DOIS avant de conclure : (1) rebuild si le projet a une étape de build ; (2) redéployer — pm2 restart <app> (ou le mécanisme en place) — et VÉRIFIER que l'app répond (healthcheck/port/site) ; (3) committer et pousser : git add + git commit + git push origin main — le remote origin est spbgit (git perso git.spboucher.ai), PAS GitHub. Ne termine jamais en laissant des modifications non commitées ou non redéployées. Si aucun fichier n'a été modifié, ignore cette règle.`;247248const ORCH_SYSTEM = `Tu es la session ORCHESTRATRICE multi-sites du Groupe KA, lancée sur M3U96a. La tâche demandée peut concerner PLUSIEURS apps KA à la fois — tu gardes le contexte complet du début à la fin. Le fichier CLAUDE.md de ton répertoire (~/ka-orchestrator) contient la table app→nœud→répertoire de prod et la méthode : lis-le et suis-le. Tu modifies les repos de PROD à distance via SSH (ssh <nœud> 'cd <dir> && …') ; les apps sur M3U96a se font en local. Planifie avec TodoWrite, explore le pattern commun avant d'agir, applique app par app, et pour CHAQUE app modifiée : build si besoin + pm2 restart + healthcheck + git add/commit/push origin main (spbgit). Termine par un bilan (apps modifiées, commits, restes). Ne laisse aucune app en état incohérent.`;249250const shq = (s) => `'` + String(s).replace(/'/g, `'\\''`) + `'`;251252// chatId -> { proc, permToken, stderr, remote }253const running = new Map();254// requestId -> { chatId, resolve, timer, input, toolKey }255const pendingPerms = new Map();256257function broadcast(chatId, msg) {258 const data = JSON.stringify(msg);259 for (const ws of wss.clients) {260 if (ws.readyState === 1 && ws.chatId === chatId) ws.send(data);261 }262}263function broadcastAll(msg) {264 const data = JSON.stringify(msg);265 for (const ws of wss.clients) if (ws.readyState === 1) ws.send(data);266}267function broadcastEco(msg) {268 const data = JSON.stringify(msg);269 for (const ws of wss.clients) if (ws.readyState === 1 && ws.eco) ws.send(data);270}271function emitAndLog(chatId, msg) {272 appendTranscript(chatId, msg);273 broadcast(chatId, msg);274}275function setChatState(chat, state) {276 chat.state = state;277 chat.updated = Date.now();278 saveChats();279 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });280}281282function permKey(tool, input) {283 if (tool === 'Bash') {284 const first = String(input?.command || '').trim().split(/\s+/)[0] || '?';285 return 'Bash:' + first;286 }287 return tool;288}289290function startClaude(chat, prompt) {291 if (running.has(chat.id)) throw new Error('Une exécution est déjà en cours pour cette conversation.');292 const permToken = crypto.randomBytes(16).toString('hex');293 const model = MODELS.includes(chat.model) ? chat.model : DEFAULT_MODEL;294 const permMode = PERM_MODES.includes(chat.permMode) ? chat.permMode : 'default';295 let proc;296297 const sysAppend = chat.projectId === 'ORCH' ? ORCH_SYSTEM : SYSTEM_APPEND;298 const baseArgs = ['-p', '--output-format', 'stream-json', '--verbose', '--include-partial-messages',299 '--model', CLI_MODEL[model], '--append-system-prompt', sysAppend];300 if (chat.claudeSessionId) baseArgs.push('--resume', chat.claudeSessionId);301302 if (!chat.node) {303 // exécution locale (app déployée sur M3U96a)304 const args = [...baseArgs];305 if (permMode === 'bypass') {306 args.push('--dangerously-skip-permissions');307 } else {308 args.push('--permission-mode', permMode);309 const mcpCfg = {310 mcpServers: {311 adminka: {312 command: NODE_BIN,313 args: [path.join(__dirname, 'perm-mcp.js')],314 env: {315 ADMIN_KA_PERM_URL: `http://127.0.0.1:${PORT}/internal/perm`,316 ADMIN_KA_PERM_TOKEN: permToken,317 },318 },319 },320 };321 const cfgPath = path.join(DATA_DIR, `mcp-${chat.id}.json`);322 fs.writeFileSync(cfgPath, JSON.stringify(mcpCfg));323 args.push('--mcp-config', cfgPath);324 args.push('--permission-prompt-tool', 'mcp__adminka__approve');325 args.push('--allowedTools', ALLOWED_READONLY);326 }327 proc = spawn(CLAUDE_BIN, args, {328 cwd: chat.dir,329 env: {330 ...process.env, ...CLAUDE_ENV,331 PATH: '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', HOME,332 },333 stdio: ['pipe', 'pipe', 'pipe'],334 detached: false,335 });336 } else {337 // exécution distante : claude tourne SUR le nœud de déploiement de l'app,338 // dans le repo de prod. Permissions via tunnel SSH inverse (IPv4 LAN non routée).339 const sshArgs = ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', '-o', 'ServerAliveInterval=30', '-o', 'ServerAliveCountMax=6'];340 let cmd = 'exec /opt/homebrew/bin/claude ' + baseArgs.map(shq).join(' ');341 if (permMode === 'bypass') {342 cmd += ' --dangerously-skip-permissions';343 } else {344 const revPort = 21000 + Math.floor(Math.random() * 3000);345 sshArgs.push('-R', `127.0.0.1:${revPort}:127.0.0.1:${PORT}`);346 const mcpCfg = {347 mcpServers: {348 adminka: {349 command: '/opt/homebrew/bin/node',350 args: ['/Users/simon-pierreboucher/.adminka/perm-mcp.js'],351 env: {352 ADMIN_KA_PERM_URL: `http://127.0.0.1:${revPort}/internal/perm`,353 ADMIN_KA_PERM_TOKEN: permToken,354 },355 },356 },357 };358 const cfgFile = `/tmp/adminka-mcp-${permToken}.json`;359 cmd = `printf '%s' '${JSON.stringify(mcpCfg)}' > ${cfgFile} && ${cmd} --permission-mode ${permMode} --mcp-config ${cfgFile} --permission-prompt-tool mcp__adminka__approve --allowedTools '${ALLOWED_READONLY}'`;360 }361 const remoteCmd = [362 `cd ${chat.dir}`,363 'export PATH=/opt/homebrew/bin:/usr/local/bin:$PATH',364 'export $(cat ~/.claude/.env | xargs)',365 `echo $$ > /tmp/adminka-pid-${permToken}`,366 cmd,367 ].join(' && ');368 proc = spawn('ssh', [...sshArgs, chat.node, remoteCmd], {369 env: { ...process.env, PATH: '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', HOME },370 stdio: ['pipe', 'pipe', 'pipe'],371 });372 }373 proc.stdin.write(prompt);374 proc.stdin.end();375376 const state = { proc, permToken, stderr: '', remote: chat.node || null };377 running.set(chat.id, state);378 audit({ kind: 'prompt', chatId: chat.id, project: chat.projectId, node: chat.node || SELF_NODE, dir: chat.dir, model, permMode, prompt: prompt.slice(0, 2000) });379 emitAndLog(chat.id, { type: 'status', state: 'running' });380 setChatState(chat, 'running');381382 let buf = '';383 proc.stdout.on('data', (d) => {384 buf += d.toString('utf8');385 let idx;386 while ((idx = buf.indexOf('\n')) >= 0) {387 const line = buf.slice(0, idx).trim();388 buf = buf.slice(idx + 1);389 if (!line) continue;390 let ev;391 try { ev = JSON.parse(line); } catch { continue; }392 handleClaudeEvent(chat, ev);393 }394 });395 proc.stderr.on('data', (d) => { state.stderr = (state.stderr + d.toString()).slice(-8000); });396 proc.on('close', (code) => {397 running.delete(chat.id);398 for (const [rid, p] of pendingPerms) {399 if (p.chatId === chat.id) { clearTimeout(p.timer); p.resolve({ behavior: 'deny', message: 'Exécution terminée' }); pendingPerms.delete(rid); }400 }401 if (code !== 0 && code !== null) {402 emitAndLog(chat.id, { type: 'error', message: `claude a quitté (code ${code})\n${state.stderr.slice(-1500)}` });403 }404 emitAndLog(chat.id, { type: 'status', state: 'idle' });405 setChatState(chat, 'idle');406 broadcastAll({ type: 'notify', kind: 'done', chatId: chat.id, title: chat.title, project: chat.projectName });407 });408 proc.on('error', (err) => {409 running.delete(chat.id);410 emitAndLog(chat.id, { type: 'error', message: 'Impossible de lancer claude: ' + err.message });411 emitAndLog(chat.id, { type: 'status', state: 'idle' });412 setChatState(chat, 'idle');413 });414}415416function handleClaudeEvent(chat, ev) {417 if (ev.type === 'system' && ev.subtype === 'init') {418 if (ev.session_id) chat.claudeSessionId = ev.session_id;419 if (ev.model) chat.lastModel = ev.model;420 saveChats();421 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });422 }423 if (ev.type === 'assistant' && ev.message && Array.isArray(ev.message.content)) {424 for (const block of ev.message.content) {425 if (block.type === 'tool_use') {426 audit({ kind: 'tool_use', chatId: chat.id, tool: block.name, input: JSON.stringify(block.input || {}).slice(0, 1000) });427 }428 }429 }430 if (ev.type === 'result') {431 chat.totalCost = (chat.totalCost || 0) + (ev.total_cost_usd || 0);432 chat.turns = (chat.turns || 0) + (ev.num_turns || 0);433 const u = ev.usage || {};434 chat.contextTokens = (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0);435 saveChats();436 audit({ kind: 'result', chatId: chat.id, subtype: ev.subtype, cost: ev.total_cost_usd, duration_ms: ev.duration_ms, turns: ev.num_turns });437 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });438 }439 if (ev.type === 'stream_event') {440 broadcast(chat.id, { type: 'claude', event: ev });441 } else {442 emitAndLog(chat.id, { type: 'claude', event: ev });443 }444}445446function interrupt(chatId) {447 const st = running.get(chatId);448 if (!st) return;449 audit({ kind: 'interrupt', chatId });450 if (st.remote) {451 spawn('ssh', ['-o', 'BatchMode=yes', st.remote, `kill -TERM $(cat /tmp/adminka-pid-${st.permToken} 2>/dev/null) 2>/dev/null; rm -f /tmp/adminka-pid-${st.permToken}`], {452 env: { ...process.env, HOME }, stdio: 'ignore',453 });454 }455 st.proc.kill('SIGTERM');456 setTimeout(() => { try { st.proc.kill('SIGKILL'); } catch {} }, 5000);457}458459// exécuter un script sur un nœud (local ou ssh) — pour les actions d'admin460function runOnNode(node, script) {461 return new Promise((resolve) => {462 const full = `export PATH=/opt/homebrew/bin:/usr/local/bin:$PATH; ${script}`;463 const bin = node === SELF_NODE ? '/bin/bash' : 'ssh';464 const args = node === SELF_NODE ? ['-c', full] : ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=12', node, full];465 execFile(bin, args, { timeout: 60_000, maxBuffer: 4 * 1024 * 1024, env: { ...process.env, PATH: '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', HOME } },466 (err, stdout, stderr) => resolve({ stdout: String(stdout || ''), stderr: String(stderr || ''), error: err ? (stderr || err.message) : null }));467 });468}469470// ---------- HTTP ----------471const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.json': 'application/json', '.woff2': 'font/woff2' };472473function readBody(req, limit = 512 * 1024) {474 return new Promise((resolve, reject) => {475 let data = '';476 req.on('data', (c) => { data += c; if (data.length > limit) { reject(new Error('body trop gros')); req.destroy(); } });477 req.on('end', () => resolve(data));478 req.on('error', reject);479 });480}481function json(res, code, obj) {482 res.writeHead(code, { 'Content-Type': 'application/json' });483 res.end(JSON.stringify(obj));484}485486const server = http.createServer(async (req, res) => {487 const url = new URL(req.url, 'http://x');488 const p = url.pathname;489490 if (p === '/healthz') { res.writeHead(200); return res.end('ok'); }491492 // --- beacon analytics (public, sans auth) : compte les visiteurs uniques ---493 if (p === '/collect') {494 try { recordHit(url.searchParams.get('site'), url.searchParams.get('vid'), url.searchParams.get('p')); } catch {}495 res.writeHead(200, { 'Content-Type': 'image/gif', 'Cache-Control': 'no-store, no-cache, must-revalidate', 'Access-Control-Allow-Origin': '*' });496 return res.end(PIXEL);497 }498499 // logos des sites (favicon/apple-touch-icon en cache) — public, léger500 if (p.startsWith('/icons/')) {501 const icon = getIcon(p.split('/')[2]);502 if (!icon) { res.writeHead(404); return res.end(); }503 res.writeHead(200, { 'Content-Type': icon.type, 'Cache-Control': 'public, max-age=86400' });504 return res.end(icon.buf);505 }506507 // --- endpoint interne de permission (long-poll par perm-mcp.js) ---508 if (p === '/internal/perm' && req.method === 'POST') {509 let body;510 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }511 let chatId = null;512 for (const [cid, st] of running) if (st.permToken === body.token) chatId = cid;513 if (!chatId) return json(res, 403, { error: 'bad token' });514 const chat = getChat(chatId);515 const toolKey = permKey(body.tool_name, body.input);516517 // « Tout autoriser » activé → toute la session est auto-approuvée : la tâche518 // va au bout sans jamais attendre l'utilisateur519 if (chat && chat.autoAllowAll) {520 audit({ kind: 'permission_auto_all', chatId, tool: body.tool_name });521 emitAndLog(chatId, { type: 'permission_auto', tool: body.tool_name, key: 'tout autoriser', input: body.input });522 return json(res, 200, { behavior: 'allow', updatedInput: body.input || {} });523 }524525 // « Toujours autoriser » déjà accordé pour cet outil dans cette conversation526 if (chat && (chat.alwaysAllow || []).includes(toolKey)) {527 audit({ kind: 'permission_auto', chatId, tool: body.tool_name, key: toolKey });528 emitAndLog(chatId, { type: 'permission_auto', tool: body.tool_name, key: toolKey, input: body.input });529 return json(res, 200, { behavior: 'allow', updatedInput: body.input || {} });530 }531532 const requestId = crypto.randomBytes(8).toString('hex');533 const p2 = new Promise((resolve) => {534 const timer = setTimeout(() => {535 pendingPerms.delete(requestId);536 emitAndLog(chatId, { type: 'permission_resolved', requestId, allow: false, reason: 'timeout' });537 if (chat && chat.state === 'waiting_perm') setChatState(chat, 'running');538 resolve({ behavior: 'deny', message: "Pas de réponse de l'utilisateur (timeout 30 min)" });539 }, 30 * 60 * 1000);540 pendingPerms.set(requestId, { chatId, resolve, timer, input: body.input, toolKey });541 });542 audit({ kind: 'permission_request', chatId, tool: body.tool_name, input: JSON.stringify(body.input || {}).slice(0, 1000) });543 emitAndLog(chatId, { type: 'permission_request', requestId, tool: body.tool_name, input: body.input });544 if (chat) setChatState(chat, 'waiting_perm');545 broadcastAll({ type: 'notify', kind: 'perm', chatId, title: chat?.title || '', tool: body.tool_name });546 const decision = await p2;547 return json(res, 200, decision);548 }549550 // --- auth ---551 if (p === '/api/login' && req.method === 'POST') {552 const ip = clientIp(req);553 if (!loginAllowed(ip)) return json(res, 429, { error: 'Trop de tentatives — réessayer dans 15 minutes.' });554 let body;555 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }556 if (typeof body.password !== 'string' || !verifyPassword(body.password)) {557 loginFailed(ip);558 audit({ kind: 'login_fail', ip });559 return json(res, 401, { error: 'Mot de passe invalide.' });560 }561 const token = newSession();562 audit({ kind: 'login_ok', ip });563 res.writeHead(200, {564 'Content-Type': 'application/json',565 'Set-Cookie': `akid=${token}; HttpOnly; Path=/; Max-Age=2592000; SameSite=Lax; Secure`,566 });567 return res.end(JSON.stringify({ ok: true }));568 }569 if (p === '/api/logout' && req.method === 'POST') {570 const t = getSession(req);571 if (t) { delete sessions[t]; saveSessions(); }572 res.writeHead(200, { 'Content-Type': 'application/json', 'Set-Cookie': 'akid=; HttpOnly; Path=/; Max-Age=0; SameSite=Lax; Secure' });573 return res.end(JSON.stringify({ ok: true }));574 }575576 // --- API authentifiée ---577 if (p.startsWith('/api/')) {578 if (!getSession(req)) return json(res, 401, { error: 'auth' });579 if (p === '/api/me') return json(res, 200, { ok: true, host: os.hostname(), node: SELF_NODE, version: '2.0.0' });580 if (p === '/api/projects') return json(res, 200, { projects: listProjects() });581 if (p === '/api/chats' && req.method === 'GET') {582 const list = [...chats].sort((a, b) => (b.updated || 0) - (a.updated || 0)).slice(0, 100).map(publicChat);583 return json(res, 200, { chats: list });584 }585 if (p.startsWith('/api/chats/') && req.method === 'DELETE') {586 const id = p.split('/')[3];587 const chat = getChat(id);588 if (chat && !running.has(id)) {589 chats = chats.filter(c => c.id !== id); saveChats();590 try { fs.unlinkSync(transcriptPath(id)); } catch {}591 return json(res, 200, { ok: true });592 }593 return json(res, 400, { error: 'introuvable ou en cours' });594 }595 // --- prompt bank ---596 if (p === '/api/prompts' && req.method === 'GET') {597 const list = [...prompts].sort((a, b) => (b.updated || 0) - (a.updated || 0));598 return json(res, 200, { prompts: list });599 }600 if (p === '/api/prompts' && req.method === 'POST') {601 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }602 const text = String(body.text || '').trim();603 if (!text) return json(res, 400, { error: 'texte vide' });604 const pr = {605 id: crypto.randomBytes(6).toString('hex'),606 title: (String(body.title || '').trim() || text.slice(0, 48)),607 text,608 project: findProject(body.project) ? body.project : null,609 created: Date.now(), updated: Date.now(),610 };611 prompts.push(pr); savePrompts();612 audit({ kind: 'prompt_save', id: pr.id });613 return json(res, 200, { prompt: pr });614 }615 if (p.startsWith('/api/prompts/') && req.method === 'PUT') {616 const id = p.split('/')[3];617 const pr = prompts.find(x => x.id === id);618 if (!pr) return json(res, 404, { error: 'introuvable' });619 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }620 if (typeof body.text === 'string' && body.text.trim()) pr.text = body.text.trim();621 if (typeof body.title === 'string') pr.title = body.title.trim() || pr.text.slice(0, 48);622 if ('project' in body) pr.project = findProject(body.project) ? body.project : null;623 pr.updated = Date.now(); savePrompts();624 return json(res, 200, { prompt: pr });625 }626 if (p.startsWith('/api/prompts/') && req.method === 'DELETE') {627 const id = p.split('/')[3];628 prompts = prompts.filter(x => x.id !== id); savePrompts();629 return json(res, 200, { ok: true });630 }631 if (p === '/api/upgrade-prompt' && req.method === 'POST') {632 let body;633 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }634 const raw = String(body.prompt || '').trim();635 if (!raw) return json(res, 400, { error: 'prompt vide' });636 try {637 const project = findProject(body.project);638 const upgraded = await upgradePrompt(raw, project);639 audit({ kind: 'upgrade_prompt', project: body.project, len_in: raw.length, len_out: upgraded.length });640 return json(res, 200, { upgraded });641 } catch (e) {642 return json(res, 502, { error: e.message });643 }644 }645 if (p === '/api/analytics/summary') return json(res, 200, analyticsSummary(SITES));646 if (p.startsWith('/api/analytics/series/')) return json(res, 200, { series: analyticsSeries(p.split('/')[4], 30) });647 if (p === '/api/eco/summary') return json(res, 200, ecoSummary());648 if (p === '/api/eco/incidents') return json(res, 200, { incidents: ecoIncidents() });649 if (p === '/api/eco/nodes') return json(res, 200, ecoNodes());650 if (p.startsWith('/api/eco/site/')) {651 const d = ecoSite(p.split('/')[4]);652 return d ? json(res, 200, d) : json(res, 404, { error: 'site inconnu' });653 }654655 // --- actions d'administration par site (pm2 / logs / commits) ---656 if (p === '/api/admin/action' && req.method === 'POST') {657 let body;658 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }659 const site = SITES.find(s => s.app === body.app);660 const action = ['restart', 'stop', 'start'].includes(body.action) ? body.action : null;661 if (!site || !action) return json(res, 400, { error: 'app ou action invalide' });662 audit({ kind: 'admin_action', app: site.app, node: site.node, action, ip: clientIp(req) });663 const out = await runOnNode(site.node, `pm2 ${action} ${site.pm2} && pm2 jlist | python3 -c "import json,sys; l=json.load(sys.stdin); p=[x for x in l if x['name']=='${site.pm2}']; print(p[0]['pm2_env']['status'] if p else 'introuvable')"`);664 return json(res, 200, { ok: !out.error, output: (out.stdout || out.error || '').trim().split('\n').pop(), full: (out.stdout || '').slice(-1500) });665 }666 if (p.startsWith('/api/admin/logs/')) {667 const site = SITES.find(s => s.app === p.split('/')[4]);668 if (!site) return json(res, 404, { error: 'site inconnu' });669 const out = await runOnNode(site.node, `pm2 logs ${site.pm2} --nostream --lines 60 2>&1 | tail -70`);670 return json(res, 200, { logs: out.stdout || out.error || '(vide)' });671 }672 if (p.startsWith('/api/admin/commits/')) {673 const site = SITES.find(s => s.app === p.split('/')[4]);674 if (!site) return json(res, 404, { error: 'site inconnu' });675 const out = await runOnNode(site.node, `cd ${site.dir} && echo "=== derniers commits ===" && git log --oneline -8 && echo && echo "=== statut ===" && (git status --short | head -10; [ -z "$(git status --short)" ] && echo "propre ✓")`);676 return json(res, 200, { text: out.stdout || out.error || '(vide)' });677 }678 // --- Social : publication automatique + a la demande ---679 if (p === '/api/social/vncpw' && req.method === 'GET') return json(res, 200, { password: config.vncPassword || '492592' });680 if (p === '/api/social/state' && req.method === 'GET') {681 return json(res, 200, { state: socialState(), log: socialLog(40) });682 }683 if (p === '/api/social/auto' && req.method === 'POST') {684 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }685 audit({ kind: 'social_auto', on: !!body.on, ip: clientIp(req) });686 return json(res, 200, { state: setAuto(!!body.on) });687 }688 if (p === '/api/social/login' && req.method === 'GET') {689 try { return json(res, 200, { login: await fbLoginState() }); }690 catch (e) { return json(res, 502, { error: e.message }); }691 }692 if (p === '/api/social/generate' && req.method === 'POST') {693 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }694 try {695 const draft = await generateDraft({ site: (body.site || '').trim(), prompt: (body.prompt || '').trim() });696 audit({ kind: 'social_generate', site: draft.insight.site });697 return json(res, 200, { draft });698 } catch (e) { return json(res, 502, { error: e.message }); }699 }700 if (p === '/api/social/publish' && req.method === 'POST') {701 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }702 try {703 await publishDraft({ caption: String(body.caption || ''), image: cardPath(body.image || '') });704 audit({ kind: 'social_publish', ip: clientIp(req) });705 return json(res, 200, { ok: true });706 } catch (e) { return json(res, 502, { error: e.message }); }707 }708 if (p === '/api/social/run' && req.method === 'POST') {709 audit({ kind: 'social_run_now', ip: clientIp(req) });710 const r = await runAutoCycle('manuel');711 return json(res, r.ok ? 200 : 502, r);712 }713 if (p.startsWith('/api/social/card/') && req.method === 'GET') {714 const fp = cardPath(p.split('/')[4] || '');715 if (!fp) { res.writeHead(404); return res.end(); }716 res.writeHead(200, { 'Content-Type': 'image/png', 'Cache-Control': 'no-cache' });717 return res.end(fs.readFileSync(fp));718 }719 if (p === '/api/social/reel/generate' && req.method === 'POST') {720 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }721 try {722 const draft = await generateReelDraft({ site: (body.site || '').trim(), prompt: (body.prompt || '').trim() });723 audit({ kind: 'social_reel_generate', site: draft.insight.site });724 return json(res, 200, { draft });725 } catch (e) { return json(res, 502, { error: e.message }); }726 }727 if (p === '/api/social/reel/publish' && req.method === 'POST') {728 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }729 try {730 await publishReelDraft({ caption: String(body.caption || ''), video: reelPath(body.video || '') });731 audit({ kind: 'social_reel_publish', ip: clientIp(req) });732 return json(res, 200, { ok: true });733 } catch (e) { return json(res, 502, { error: e.message }); }734 }735 if (p === '/api/social/reel/run' && req.method === 'POST') {736 audit({ kind: 'social_reel_run', ip: clientIp(req) });737 const r = await runReelCycle('reel-manuel');738 return json(res, r.ok ? 200 : 502, r);739 }740 if (p === '/api/social/gallery' && req.method === 'GET') return json(res, 200, { items: getGallery(), gen: genBatchStatus() });741 if (p === '/api/social/reel/genbatch' && req.method === 'POST') {742 let body; try { body = JSON.parse(await readBody(req)); } catch { body = {}; }743 const sites = (Array.isArray(body.sites) && body.sites.length) ? body.sites : REEL_BATCH_DEFAULT;744 audit({ kind: 'social_genbatch', n: sites.length, ip: clientIp(req) });745 const r = startGenBatch(sites);746 return json(res, r.started ? 200 : 409, r);747 }748 if (p === '/api/social/reel/batch' && req.method === 'POST') {749 let body; try { body = JSON.parse(await readBody(req)); } catch { body = {}; }750 const sites = (Array.isArray(body.sites) && body.sites.length) ? body.sites : REEL_BATCH_DEFAULT;751 audit({ kind: 'social_reel_batch', n: sites.length, ip: clientIp(req) });752 const r = startReelBatch(sites);753 return json(res, r.started ? 200 : 409, r);754 }755 if (p === '/api/social/reel/batchstatus' && req.method === 'GET') return json(res, 200, batchStatus());756 if (p.startsWith('/api/social/reel/') && req.method === 'GET') {757 const fp = reelPath(p.split('/')[4] || '');758 if (!fp) { res.writeHead(404); return res.end(); }759 const stat = fs.statSync(fp);760 res.writeHead(200, { 'Content-Type': 'video/mp4', 'Content-Length': stat.size, 'Cache-Control': 'no-cache' });761 return res.end(fs.readFileSync(fp));762 }763764 return json(res, 404, { error: 'not found' });765 }766767 // --- statique ---768 let file = p === '/' ? '/index.html' : p;769 file = path.normalize(file).replace(/^(\.\.[/\\])+/, '');770 const full = path.join(PUBLIC_DIR, file);771 if (!full.startsWith(PUBLIC_DIR)) { res.writeHead(403); return res.end(); }772 fs.readFile(full, (err, data) => {773 if (err) { res.writeHead(404); return res.end('not found'); }774 res.writeHead(200, { 'Content-Type': MIME[path.extname(full)] || 'application/octet-stream', 'Cache-Control': full.includes('/vendor/') ? 'public, max-age=86400' : 'no-cache' });775 res.end(data);776 });777});778779// ---------- WebSocket ----------780const wss = new WebSocketServer({ noServer: true });781782// --- pont VNC : WebSocket (noVNC dans l'admin) <-> Partage d'écran du nœud (127.0.0.1:5900) ---783const vncWss = new WebSocketServer({ noServer: true });784vncWss.on('connection', (ws) => {785 const tcp = net.connect(5900, '127.0.0.1');786 tcp.on('data', (d) => { if (ws.readyState === 1) ws.send(d); });787 tcp.on('close', () => { try { ws.close(); } catch {} });788 tcp.on('error', () => { try { ws.close(); } catch {} });789 ws.on('message', (d) => { try { tcp.write(d); } catch {} });790 ws.on('close', () => { try { tcp.end(); } catch {} });791 ws.on('error', () => { try { tcp.destroy(); } catch {} });792});793794server.on('upgrade', (req, socket, head) => {795 const url = new URL(req.url, 'http://x');796 if (!getSession(req)) {797 socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');798 return socket.destroy();799 }800 if (url.pathname === '/ws') {801 wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req));802 } else if (url.pathname === '/vncws') {803 vncWss.handleUpgrade(req, socket, head, (ws) => vncWss.emit('connection', ws, req));804 } else {805 socket.write('HTTP/1.1 404 Not Found\r\n\r\n');806 socket.destroy();807 }808});809810wss.on('connection', (ws) => {811 ws.chatId = null;812 ws.eco = false;813 ws.isAlive = true;814 ws.on('pong', () => { ws.isAlive = true; });815 ws.on('message', (raw) => {816 let msg;817 try { msg = JSON.parse(raw.toString()); } catch { return; }818 try { handleWsMessage(ws, msg); } catch (e) {819 ws.send(JSON.stringify({ type: 'error', message: e.message }));820 }821 });822 // NB : la fermeture du socket ne touche JAMAIS aux processus claude en cours.823});824825setInterval(() => {826 for (const ws of wss.clients) {827 if (!ws.isAlive) { ws.terminate(); continue; }828 ws.isAlive = false; ws.ping();829 }830}, 30000);831832function handleWsMessage(ws, msg) {833 if (msg.type === 'open') {834 const chat = getChat(msg.chatId);835 if (!chat) return ws.send(JSON.stringify({ type: 'error', message: 'Conversation introuvable' }));836 ws.chatId = chat.id;837 // rejoue tout l'historique persisté puis raccroche le live838 ws.send(JSON.stringify({839 type: 'history',840 chat: publicChat(chat),841 events: readTranscript(chat.id),842 running: running.has(chat.id),843 }));844 return;845 }846 if (msg.type === 'start') {847 const prompt = String(msg.prompt || '').trim();848 if (!prompt) return;849 let chat = msg.chatId ? getChat(msg.chatId) : null;850 if (!chat) {851 const proj = findProject(msg.project) || PROJECTS[0];852 chat = {853 id: crypto.randomBytes(8).toString('hex'),854 title: prompt.slice(0, 60),855 projectId: proj.id, projectName: proj.name,856 node: proj.node, dir: proj.dir,857 model: MODELS.includes(msg.model) ? msg.model : DEFAULT_MODEL,858 permMode: PERM_MODES.includes(msg.permMode) ? msg.permMode : 'default',859 claudeSessionId: null, state: 'idle',860 totalCost: 0, turns: 0, contextTokens: 0, alwaysAllow: [],861 created: Date.now(), updated: Date.now(),862 };863 chats.push(chat); saveChats();864 ws.send(JSON.stringify({ type: 'chat_created', chat: publicChat(chat) }));865 } else {866 if (MODELS.includes(msg.model)) chat.model = msg.model;867 if (PERM_MODES.includes(msg.permMode)) chat.permMode = msg.permMode;868 saveChats();869 }870 ws.chatId = chat.id;871 emitAndLog(chat.id, { type: 'user_prompt', text: prompt, ts: Date.now() });872 startClaude(chat, prompt);873 return;874 }875 if (msg.type === 'start_all') {876 // diffuse le MÊME prompt à TOUTES les apps KA en parallèle (1 session/app)877 const prompt = String(msg.prompt || '').trim();878 if (!prompt) return;879 const model = MODELS.includes(msg.model) ? msg.model : DEFAULT_MODEL;880 const permMode = PERM_MODES.includes(msg.permMode) ? msg.permMode : 'default';881 const created = [];882 const stamp = new Date().toLocaleString('fr-CA', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });883 for (const proj of PROJECTS) {884 const chat = {885 id: crypto.randomBytes(8).toString('hex'),886 title: '🌐 ' + prompt.slice(0, 46),887 projectId: proj.id, projectName: proj.name,888 node: proj.node, dir: proj.dir,889 model, permMode,890 claudeSessionId: null, state: 'idle',891 totalCost: 0, turns: 0, contextTokens: 0, alwaysAllow: [],892 batch: stamp,893 created: Date.now(), updated: Date.now(),894 };895 chats.push(chat);896 emitAndLog(chat.id, { type: 'user_prompt', text: prompt, ts: Date.now() });897 try { startClaude(chat, prompt); created.push(chat.id); }898 catch (e) { emitAndLog(chat.id, { type: 'error', message: e.message }); }899 }900 saveChats();901 audit({ kind: 'start_all', count: created.length, model, permMode, prompt: prompt.slice(0, 500) });902 ws.send(JSON.stringify({ type: 'batch_created', count: created.length, total: PROJECTS.length }));903 return;904 }905 if (msg.type === 'set_opts') {906 const chat = getChat(msg.chatId);907 if (!chat) return;908 if (MODELS.includes(msg.model)) chat.model = msg.model;909 if (PERM_MODES.includes(msg.permMode)) chat.permMode = msg.permMode;910 if (typeof msg.autoAllowAll === 'boolean') chat.autoAllowAll = msg.autoAllowAll;911 saveChats();912 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });913 return;914 }915 if (msg.type === 'clear') {916 const chat = getChat(msg.chatId);917 if (!chat || running.has(chat.id)) return;918 chat.claudeSessionId = null;919 chat.contextTokens = 0;920 saveChats();921 emitAndLog(chat.id, { type: 'notice', text: 'Contexte effacé — la prochaine demande démarre une session Claude Code vierge.' });922 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });923 return;924 }925 if (msg.type === 'perm') {926 const pending = pendingPerms.get(msg.requestId);927 if (!pending) return;928 clearTimeout(pending.timer);929 pendingPerms.delete(msg.requestId);930 const chat = getChat(pending.chatId);931 if (msg.allow && msg.allowAll && chat) {932 // « Tout autoriser » : plus AUCUNE permission ne sera demandée pour cette933 // conversation — le serveur approuve tout jusqu'à la fin de la tâche934 chat.autoAllowAll = true;935 saveChats();936 emitAndLog(chat.id, { type: 'notice', text: '🔓 Tout autoriser activé — la tâche ira au bout sans autre demande de permission.' });937 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });938 }939 if (msg.allow && msg.always && chat) {940 if (!chat.alwaysAllow.includes(pending.toolKey)) chat.alwaysAllow.push(pending.toolKey);941 saveChats();942 }943 audit({ kind: 'permission_response', chatId: pending.chatId, requestId: msg.requestId, allow: !!msg.allow, always: !!msg.always });944 emitAndLog(pending.chatId, { type: 'permission_resolved', requestId: msg.requestId, allow: !!msg.allow, always: !!msg.always });945 if (chat && chat.state === 'waiting_perm') setChatState(chat, 'running');946 pending.resolve(msg.allow947 ? { behavior: 'allow', updatedInput: pending.input || {} }948 : { behavior: 'deny', message: "Refusé par l'utilisateur depuis administration-ka.com" });949 return;950 }951 if (msg.type === 'interrupt') {952 if (msg.chatId) interrupt(msg.chatId);953 else if (ws.chatId) interrupt(ws.chatId);954 return;955 }956 if (msg.type === 'eco_sub') { ws.eco = true; return; }957 if (msg.type === 'eco_unsub') { ws.eco = false; return; }958}959960// ---------- monitoring Écosystème ----------961startMonitor({962 dataDir: DATA_DIR,963 onEvent: (ev) => {964 if (ev.type === 'eco_alert') broadcastAll(ev); // alertes → tout le monde965 else broadcastEco(ev); // ticks → abonnés à l'onglet966 },967});968969// module Social : publication automatique horaire + génération sur demande970initSocial(971 { anthropicKey: UPGRADER_KEY, upgraderModel: UPGRADER_MODEL,972 socialModel: config.socialModel, socialIntervalMin: config.socialIntervalMin, reelEvery: config.reelEvery },973 (line) => broadcastAll({ type: 'social_log', line }),974);975976initAnalytics();977978// au démarrage, les chats marqués "running" par un ancien processus sont orphelins979for (const c of chats) if (c.state !== 'idle') c.state = 'idle';980saveChats();981982server.listen(PORT, '::', () => {983 console.log(`admin-ka v2 sur port ${PORT} (dual-stack)`);984});985