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, analyticsSite, analyticsRealtime, analyticsAnomalies, analyticsInspect, analyticsClasses, analyticsConfig, setAnalyticsConfig, 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. ka-stats (ka-stats.com) : Ka·Stats, l'observatoire de statistiques de l'écosystème — agrège les dashboards /api/stats/dashboard des 12 sites (Node zéro-dépendance, nœud M1M32, pm2 ka-stats + ka-stats-ngrok, dir ~/apps/ka-stats). groupe-ka.com : hub + KA ID (SSO). ka2/ka4/ka6 (ka2.bot/ka4.bot/ka6.bot) : agents gardiens autonomes des connecteurs (KA Guardian — un seul repo Python/FastAPI sur M4M36, process launchd com.kaX.guardian, PAS pm2). 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 { id: 'ka-stats@M1M32', name: 'Ka·Stats', node: 'M1M32', dir: '~/apps/ka-stats' },224 // Agents gardiens KA Guardian — 3 sites, 1 seul repo sur M4M36 (launchd, pas pm2)225 { id: 'ka2@M4M36', name: 'KA·2 Guardian', node: 'M4M36', dir: '~/cluster-projects/ka-guardian' },226 { id: 'ka4@M4M36', name: 'KA·4 Guardian', node: 'M4M36', dir: '~/cluster-projects/ka-guardian' },227 { id: 'ka6@M4M36', name: 'KA·6 Guardian', node: 'M4M36', dir: '~/cluster-projects/ka-guardian' },228];229// Orchestrateur : une seule session sur M3U96a qui pilote les 13 apps via SSH,230// en gardant le contexte complet de la tâche.231const ORCH_PROJECT = { id: 'ORCH', name: '🎛️ Orchestrateur multi-sites', node: null, dir: path.join(HOME, 'ka-orchestrator') };232function listProjects() {233 return [234 { id: ORCH_PROJECT.id, name: ORCH_PROJECT.name, node: SELF_NODE, dir: ORCH_PROJECT.dir },235 ...PROJECTS.map(p => ({ id: p.id, name: p.name, node: p.node || SELF_NODE, dir: p.dir })),236 ];237}238function findProject(id) {239 if (id === 'ORCH') return ORCH_PROJECT;240 return PROJECTS.find(p => p.id === id) || null;241}242243// ---------- exécution Claude Code ----------244const MODELS = ['fable', 'opus', 'sonnet', 'haiku'];245// mappage vers les IDs réels (les alias CLI des nœuds retombent sur d'anciennes versions)246const CLI_MODEL = { fable: 'claude-fable-5', opus: 'claude-opus-5', sonnet: 'claude-sonnet-5', haiku: 'claude-haiku-4-5-20251001' };247const DEFAULT_MODEL = 'fable';248const PERM_MODES = ['default', 'acceptEdits', 'plan', 'bypass'];249const ALLOWED_READONLY = 'Read,Glob,Grep,LS,WebFetch,WebSearch,TodoWrite,NotebookRead,Task';250251const 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.`;252253const 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.`;254255const shq = (s) => `'` + String(s).replace(/'/g, `'\\''`) + `'`;256257// chatId -> { proc, permToken, stderr, remote }258const running = new Map();259// requestId -> { chatId, resolve, timer, input, toolKey }260const pendingPerms = new Map();261262function broadcast(chatId, msg) {263 const data = JSON.stringify(msg);264 for (const ws of wss.clients) {265 if (ws.readyState === 1 && ws.chatId === chatId) ws.send(data);266 }267}268function broadcastAll(msg) {269 const data = JSON.stringify(msg);270 for (const ws of wss.clients) if (ws.readyState === 1) ws.send(data);271}272function broadcastEco(msg) {273 const data = JSON.stringify(msg);274 for (const ws of wss.clients) if (ws.readyState === 1 && ws.eco) ws.send(data);275}276function emitAndLog(chatId, msg) {277 appendTranscript(chatId, msg);278 broadcast(chatId, msg);279}280function setChatState(chat, state) {281 chat.state = state;282 chat.updated = Date.now();283 saveChats();284 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });285}286287function permKey(tool, input) {288 if (tool === 'Bash') {289 const first = String(input?.command || '').trim().split(/\s+/)[0] || '?';290 return 'Bash:' + first;291 }292 return tool;293}294295function startClaude(chat, prompt) {296 if (running.has(chat.id)) throw new Error('Une exécution est déjà en cours pour cette conversation.');297 const permToken = crypto.randomBytes(16).toString('hex');298 const model = MODELS.includes(chat.model) ? chat.model : DEFAULT_MODEL;299 const permMode = PERM_MODES.includes(chat.permMode) ? chat.permMode : 'default';300 let proc;301302 const sysAppend = chat.projectId === 'ORCH' ? ORCH_SYSTEM : SYSTEM_APPEND;303 const baseArgs = ['-p', '--output-format', 'stream-json', '--verbose', '--include-partial-messages',304 '--model', CLI_MODEL[model], '--append-system-prompt', sysAppend];305 if (chat.claudeSessionId) baseArgs.push('--resume', chat.claudeSessionId);306307 if (!chat.node) {308 // exécution locale (app déployée sur M3U96a)309 const args = [...baseArgs];310 if (permMode === 'bypass') {311 args.push('--dangerously-skip-permissions');312 } else {313 args.push('--permission-mode', permMode);314 const mcpCfg = {315 mcpServers: {316 adminka: {317 command: NODE_BIN,318 args: [path.join(__dirname, 'perm-mcp.js')],319 env: {320 ADMIN_KA_PERM_URL: `http://127.0.0.1:${PORT}/internal/perm`,321 ADMIN_KA_PERM_TOKEN: permToken,322 },323 },324 },325 };326 const cfgPath = path.join(DATA_DIR, `mcp-${chat.id}.json`);327 fs.writeFileSync(cfgPath, JSON.stringify(mcpCfg));328 args.push('--mcp-config', cfgPath);329 args.push('--permission-prompt-tool', 'mcp__adminka__approve');330 args.push('--allowedTools', ALLOWED_READONLY);331 }332 proc = spawn(CLAUDE_BIN, args, {333 cwd: chat.dir,334 env: {335 ...process.env, ...CLAUDE_ENV,336 PATH: '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', HOME,337 },338 stdio: ['pipe', 'pipe', 'pipe'],339 detached: false,340 });341 } else {342 // exécution distante : claude tourne SUR le nœud de déploiement de l'app,343 // dans le repo de prod. Permissions via tunnel SSH inverse (IPv4 LAN non routée).344 const sshArgs = ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', '-o', 'ServerAliveInterval=30', '-o', 'ServerAliveCountMax=6'];345 let cmd = 'exec /opt/homebrew/bin/claude ' + baseArgs.map(shq).join(' ');346 if (permMode === 'bypass') {347 cmd += ' --dangerously-skip-permissions';348 } else {349 const revPort = 21000 + Math.floor(Math.random() * 3000);350 sshArgs.push('-R', `127.0.0.1:${revPort}:127.0.0.1:${PORT}`);351 const mcpCfg = {352 mcpServers: {353 adminka: {354 command: '/opt/homebrew/bin/node',355 args: ['/Users/simon-pierreboucher/.adminka/perm-mcp.js'],356 env: {357 ADMIN_KA_PERM_URL: `http://127.0.0.1:${revPort}/internal/perm`,358 ADMIN_KA_PERM_TOKEN: permToken,359 },360 },361 },362 };363 const cfgFile = `/tmp/adminka-mcp-${permToken}.json`;364 cmd = `printf '%s' '${JSON.stringify(mcpCfg)}' > ${cfgFile} && ${cmd} --permission-mode ${permMode} --mcp-config ${cfgFile} --permission-prompt-tool mcp__adminka__approve --allowedTools '${ALLOWED_READONLY}'`;365 }366 const remoteCmd = [367 `cd ${chat.dir}`,368 'export PATH=/opt/homebrew/bin:/usr/local/bin:$PATH',369 'export $(cat ~/.claude/.env | xargs)',370 `echo $$ > /tmp/adminka-pid-${permToken}`,371 cmd,372 ].join(' && ');373 proc = spawn('ssh', [...sshArgs, chat.node, remoteCmd], {374 env: { ...process.env, PATH: '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', HOME },375 stdio: ['pipe', 'pipe', 'pipe'],376 });377 }378 proc.stdin.write(prompt);379 proc.stdin.end();380381 const state = { proc, permToken, stderr: '', remote: chat.node || null };382 running.set(chat.id, state);383 audit({ kind: 'prompt', chatId: chat.id, project: chat.projectId, node: chat.node || SELF_NODE, dir: chat.dir, model, permMode, prompt: prompt.slice(0, 2000) });384 emitAndLog(chat.id, { type: 'status', state: 'running' });385 setChatState(chat, 'running');386387 let buf = '';388 proc.stdout.on('data', (d) => {389 buf += d.toString('utf8');390 let idx;391 while ((idx = buf.indexOf('\n')) >= 0) {392 const line = buf.slice(0, idx).trim();393 buf = buf.slice(idx + 1);394 if (!line) continue;395 let ev;396 try { ev = JSON.parse(line); } catch { continue; }397 handleClaudeEvent(chat, ev);398 }399 });400 proc.stderr.on('data', (d) => { state.stderr = (state.stderr + d.toString()).slice(-8000); });401 proc.on('close', (code) => {402 running.delete(chat.id);403 for (const [rid, p] of pendingPerms) {404 if (p.chatId === chat.id) { clearTimeout(p.timer); p.resolve({ behavior: 'deny', message: 'Exécution terminée' }); pendingPerms.delete(rid); }405 }406 if (code !== 0 && code !== null) {407 emitAndLog(chat.id, { type: 'error', message: `claude a quitté (code ${code})\n${state.stderr.slice(-1500)}` });408 }409 emitAndLog(chat.id, { type: 'status', state: 'idle' });410 setChatState(chat, 'idle');411 broadcastAll({ type: 'notify', kind: 'done', chatId: chat.id, title: chat.title, project: chat.projectName });412 });413 proc.on('error', (err) => {414 running.delete(chat.id);415 emitAndLog(chat.id, { type: 'error', message: 'Impossible de lancer claude: ' + err.message });416 emitAndLog(chat.id, { type: 'status', state: 'idle' });417 setChatState(chat, 'idle');418 });419}420421function handleClaudeEvent(chat, ev) {422 if (ev.type === 'system' && ev.subtype === 'init') {423 if (ev.session_id) chat.claudeSessionId = ev.session_id;424 if (ev.model) chat.lastModel = ev.model;425 saveChats();426 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });427 }428 if (ev.type === 'assistant' && ev.message && Array.isArray(ev.message.content)) {429 for (const block of ev.message.content) {430 if (block.type === 'tool_use') {431 audit({ kind: 'tool_use', chatId: chat.id, tool: block.name, input: JSON.stringify(block.input || {}).slice(0, 1000) });432 }433 }434 }435 if (ev.type === 'result') {436 chat.totalCost = (chat.totalCost || 0) + (ev.total_cost_usd || 0);437 chat.turns = (chat.turns || 0) + (ev.num_turns || 0);438 const u = ev.usage || {};439 chat.contextTokens = (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0);440 saveChats();441 audit({ kind: 'result', chatId: chat.id, subtype: ev.subtype, cost: ev.total_cost_usd, duration_ms: ev.duration_ms, turns: ev.num_turns });442 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });443 }444 if (ev.type === 'stream_event') {445 broadcast(chat.id, { type: 'claude', event: ev });446 } else {447 emitAndLog(chat.id, { type: 'claude', event: ev });448 }449}450451function interrupt(chatId) {452 const st = running.get(chatId);453 if (!st) return;454 audit({ kind: 'interrupt', chatId });455 if (st.remote) {456 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}`], {457 env: { ...process.env, HOME }, stdio: 'ignore',458 });459 }460 st.proc.kill('SIGTERM');461 setTimeout(() => { try { st.proc.kill('SIGKILL'); } catch {} }, 5000);462}463464// exécuter un script sur un nœud (local ou ssh) — pour les actions d'admin465function runOnNode(node, script) {466 return new Promise((resolve) => {467 const full = `export PATH=/opt/homebrew/bin:/usr/local/bin:$PATH; ${script}`;468 const bin = node === SELF_NODE ? '/bin/bash' : 'ssh';469 const args = node === SELF_NODE ? ['-c', full] : ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=12', node, full];470 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 } },471 (err, stdout, stderr) => resolve({ stdout: String(stdout || ''), stderr: String(stderr || ''), error: err ? (stderr || err.message) : null }));472 });473}474475// ---------- HTTP ----------476const 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' };477478function readBody(req, limit = 512 * 1024) {479 return new Promise((resolve, reject) => {480 let data = '';481 req.on('data', (c) => { data += c; if (data.length > limit) { reject(new Error('body trop gros')); req.destroy(); } });482 req.on('end', () => resolve(data));483 req.on('error', reject);484 });485}486function json(res, code, obj) {487 res.writeHead(code, { 'Content-Type': 'application/json' });488 res.end(JSON.stringify(obj));489}490491const server = http.createServer(async (req, res) => {492 const url = new URL(req.url, 'http://x');493 const p = url.pathname;494495 if (p === '/healthz') { res.writeHead(200); return res.end('ok'); }496497 // --- beacon analytics (public, sans auth) : v1 (pings 60 s) et v2 (pv/hb) ---498 if (p === '/collect') {499 try { recordHit(url.searchParams, req); } catch {}500 res.writeHead(200, { 'Content-Type': 'image/gif', 'Cache-Control': 'no-store, no-cache, must-revalidate', 'Access-Control-Allow-Origin': '*' });501 return res.end(PIXEL);502 }503504 // logos des sites (favicon/apple-touch-icon en cache) — public, léger505 if (p.startsWith('/icons/')) {506 const icon = getIcon(p.split('/')[2]);507 if (!icon) { res.writeHead(404); return res.end(); }508 res.writeHead(200, { 'Content-Type': icon.type, 'Cache-Control': 'public, max-age=86400' });509 return res.end(icon.buf);510 }511512 // --- endpoint interne de permission (long-poll par perm-mcp.js) ---513 if (p === '/internal/perm' && req.method === 'POST') {514 let body;515 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }516 let chatId = null;517 for (const [cid, st] of running) if (st.permToken === body.token) chatId = cid;518 if (!chatId) return json(res, 403, { error: 'bad token' });519 const chat = getChat(chatId);520 const toolKey = permKey(body.tool_name, body.input);521522 // « Tout autoriser » activé → toute la session est auto-approuvée : la tâche523 // va au bout sans jamais attendre l'utilisateur524 if (chat && chat.autoAllowAll) {525 audit({ kind: 'permission_auto_all', chatId, tool: body.tool_name });526 emitAndLog(chatId, { type: 'permission_auto', tool: body.tool_name, key: 'tout autoriser', input: body.input });527 return json(res, 200, { behavior: 'allow', updatedInput: body.input || {} });528 }529530 // « Toujours autoriser » déjà accordé pour cet outil dans cette conversation531 if (chat && (chat.alwaysAllow || []).includes(toolKey)) {532 audit({ kind: 'permission_auto', chatId, tool: body.tool_name, key: toolKey });533 emitAndLog(chatId, { type: 'permission_auto', tool: body.tool_name, key: toolKey, input: body.input });534 return json(res, 200, { behavior: 'allow', updatedInput: body.input || {} });535 }536537 const requestId = crypto.randomBytes(8).toString('hex');538 const p2 = new Promise((resolve) => {539 const timer = setTimeout(() => {540 pendingPerms.delete(requestId);541 emitAndLog(chatId, { type: 'permission_resolved', requestId, allow: false, reason: 'timeout' });542 if (chat && chat.state === 'waiting_perm') setChatState(chat, 'running');543 resolve({ behavior: 'deny', message: "Pas de réponse de l'utilisateur (timeout 30 min)" });544 }, 30 * 60 * 1000);545 pendingPerms.set(requestId, { chatId, resolve, timer, input: body.input, toolKey });546 });547 audit({ kind: 'permission_request', chatId, tool: body.tool_name, input: JSON.stringify(body.input || {}).slice(0, 1000) });548 emitAndLog(chatId, { type: 'permission_request', requestId, tool: body.tool_name, input: body.input });549 if (chat) setChatState(chat, 'waiting_perm');550 broadcastAll({ type: 'notify', kind: 'perm', chatId, title: chat?.title || '', tool: body.tool_name });551 const decision = await p2;552 return json(res, 200, decision);553 }554555 // --- auth ---556 if (p === '/api/login' && req.method === 'POST') {557 const ip = clientIp(req);558 if (!loginAllowed(ip)) return json(res, 429, { error: 'Trop de tentatives — réessayer dans 15 minutes.' });559 let body;560 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }561 if (typeof body.password !== 'string' || !verifyPassword(body.password)) {562 loginFailed(ip);563 audit({ kind: 'login_fail', ip });564 return json(res, 401, { error: 'Mot de passe invalide.' });565 }566 const token = newSession();567 audit({ kind: 'login_ok', ip });568 res.writeHead(200, {569 'Content-Type': 'application/json',570 'Set-Cookie': `akid=${token}; HttpOnly; Path=/; Max-Age=2592000; SameSite=Lax; Secure`,571 });572 return res.end(JSON.stringify({ ok: true }));573 }574 if (p === '/api/logout' && req.method === 'POST') {575 const t = getSession(req);576 if (t) { delete sessions[t]; saveSessions(); }577 res.writeHead(200, { 'Content-Type': 'application/json', 'Set-Cookie': 'akid=; HttpOnly; Path=/; Max-Age=0; SameSite=Lax; Secure' });578 return res.end(JSON.stringify({ ok: true }));579 }580581 // --- API authentifiée ---582 if (p.startsWith('/api/')) {583 if (!getSession(req)) return json(res, 401, { error: 'auth' });584 if (p === '/api/me') return json(res, 200, { ok: true, host: os.hostname(), node: SELF_NODE, version: '3.0.0' });585 if (p === '/api/projects') return json(res, 200, { projects: listProjects() });586 if (p === '/api/chats' && req.method === 'GET') {587 const list = [...chats].sort((a, b) => (b.updated || 0) - (a.updated || 0)).slice(0, 100).map(publicChat);588 return json(res, 200, { chats: list });589 }590 if (p.startsWith('/api/chats/') && req.method === 'DELETE') {591 const id = p.split('/')[3];592 const chat = getChat(id);593 if (chat && !running.has(id)) {594 chats = chats.filter(c => c.id !== id); saveChats();595 try { fs.unlinkSync(transcriptPath(id)); } catch {}596 return json(res, 200, { ok: true });597 }598 return json(res, 400, { error: 'introuvable ou en cours' });599 }600 // --- prompt bank ---601 if (p === '/api/prompts' && req.method === 'GET') {602 const list = [...prompts].sort((a, b) => (b.updated || 0) - (a.updated || 0));603 return json(res, 200, { prompts: list });604 }605 if (p === '/api/prompts' && req.method === 'POST') {606 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }607 const text = String(body.text || '').trim();608 if (!text) return json(res, 400, { error: 'texte vide' });609 const pr = {610 id: crypto.randomBytes(6).toString('hex'),611 title: (String(body.title || '').trim() || text.slice(0, 48)),612 text,613 project: findProject(body.project) ? body.project : null,614 fav: !!body.fav, uses: 0,615 created: Date.now(), updated: Date.now(),616 };617 prompts.push(pr); savePrompts();618 audit({ kind: 'prompt_save', id: pr.id });619 return json(res, 200, { prompt: pr });620 }621 if (p.startsWith('/api/prompts/') && req.method === 'PUT') {622 const id = p.split('/')[3];623 const pr = prompts.find(x => x.id === id);624 if (!pr) return json(res, 404, { error: 'introuvable' });625 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }626 if (typeof body.text === 'string' && body.text.trim()) pr.text = body.text.trim();627 if (typeof body.title === 'string') pr.title = body.title.trim() || pr.text.slice(0, 48);628 if ('project' in body) pr.project = findProject(body.project) ? body.project : null;629 if (typeof body.fav === 'boolean') pr.fav = body.fav;630 if (body.bumpUse) pr.uses = (pr.uses || 0) + 1;631 pr.updated = Date.now(); savePrompts();632 return json(res, 200, { prompt: pr });633 }634 if (p.startsWith('/api/prompts/') && req.method === 'DELETE') {635 const id = p.split('/')[3];636 prompts = prompts.filter(x => x.id !== id); savePrompts();637 return json(res, 200, { ok: true });638 }639 if (p === '/api/upgrade-prompt' && req.method === 'POST') {640 let body;641 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }642 const raw = String(body.prompt || '').trim();643 if (!raw) return json(res, 400, { error: 'prompt vide' });644 try {645 const project = findProject(body.project);646 const upgraded = await upgradePrompt(raw, project);647 audit({ kind: 'upgrade_prompt', project: body.project, len_in: raw.length, len_out: upgraded.length });648 return json(res, 200, { upgraded });649 } catch (e) {650 return json(res, 502, { error: e.message });651 }652 }653 if (p === '/api/analytics/summary') return json(res, 200, analyticsSummary(SITES));654 if (p.startsWith('/api/analytics/series/')) return json(res, 200, analyticsSeries(p.split('/')[4], 30));655 if (p.startsWith('/api/analytics/site/')) return json(res, 200, analyticsSite(p.split('/')[4], Number(url.searchParams.get('days')) || 7));656 if (p === '/api/analytics/realtime') return json(res, 200, analyticsRealtime(SITES));657 if (p === '/api/analytics/anomalies') return json(res, 200, analyticsAnomalies());658 if (p === '/api/analytics/inspect') return json(res, 200, analyticsInspect({ ip: url.searchParams.get('ip'), vid: url.searchParams.get('vid'), ua: url.searchParams.get('ua') }));659 if (p === '/api/analytics/classes') return json(res, 200, analyticsClasses(Number(url.searchParams.get('ms')) || 864e5));660 if (p === '/api/analytics/config' && req.method === 'GET') return json(res, 200, analyticsConfig());661 if (p === '/api/analytics/config' && req.method === 'PUT') {662 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }663 audit({ kind: 'analytics_config', ip: clientIp(req) });664 return json(res, 200, setAnalyticsConfig(body));665 }666 if (p === '/api/eco/summary') return json(res, 200, ecoSummary());667 if (p === '/api/eco/incidents') return json(res, 200, { incidents: ecoIncidents() });668 if (p === '/api/eco/nodes') return json(res, 200, ecoNodes());669 if (p.startsWith('/api/eco/site/')) {670 const d = ecoSite(p.split('/')[4]);671 return d ? json(res, 200, d) : json(res, 404, { error: 'site inconnu' });672 }673674 // --- actions d'administration par site (pm2 / logs / commits) ---675 if (p === '/api/admin/action' && req.method === 'POST') {676 let body;677 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }678 const site = SITES.find(s => s.app === body.app);679 const action = ['restart', 'stop', 'start'].includes(body.action) ? body.action : null;680 if (!site || !action) return json(res, 400, { error: 'app ou action invalide' });681 audit({ kind: 'admin_action', app: site.app, node: site.node, action, ip: clientIp(req) });682 let out;683 if (site.unit) {684 // sites sous launchd (KA Guardian sur M4M36) — pas de pm2 sur ce nœud685 const cmds = {686 restart: `launchctl kickstart -k gui/$(id -u)/${site.unit}`,687 stop: `launchctl unload ~/Library/LaunchAgents/${site.unit}.plist`,688 start: `launchctl load ~/Library/LaunchAgents/${site.unit}.plist`,689 };690 out = await runOnNode(site.node, `${cmds[action]} && sleep 1 && (launchctl list | awk '$3=="${site.unit}"{print ($1=="-")?"arrêté":"online"; f=1} END{if(!f)print "déchargé"}')`);691 } else {692 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')"`);693 }694 return json(res, 200, { ok: !out.error, output: (out.stdout || out.error || '').trim().split('\n').pop(), full: (out.stdout || '').slice(-1500) });695 }696 if (p.startsWith('/api/admin/logs/')) {697 const site = SITES.find(s => s.app === p.split('/')[4]);698 if (!site) return json(res, 404, { error: 'site inconnu' });699 const out = site.log700 ? await runOnNode(site.node, `tail -70 ${site.log} 2>&1`)701 : await runOnNode(site.node, `pm2 logs ${site.pm2} --nostream --lines 60 2>&1 | tail -70`);702 return json(res, 200, { logs: out.stdout || out.error || '(vide)' });703 }704 if (p.startsWith('/api/admin/commits/')) {705 const site = SITES.find(s => s.app === p.split('/')[4]);706 if (!site) return json(res, 404, { error: 'site inconnu' });707 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 ✓")`);708 return json(res, 200, { text: out.stdout || out.error || '(vide)' });709 }710 // --- Social : publication automatique + a la demande ---711 if (p === '/api/social/vncpw' && req.method === 'GET') return json(res, 200, { password: config.vncPassword || '492592' });712 if (p === '/api/social/state' && req.method === 'GET') {713 return json(res, 200, { state: socialState(), log: socialLog(40) });714 }715 if (p === '/api/social/auto' && req.method === 'POST') {716 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }717 audit({ kind: 'social_auto', on: !!body.on, ip: clientIp(req) });718 return json(res, 200, { state: setAuto(!!body.on) });719 }720 if (p === '/api/social/login' && req.method === 'GET') {721 try { return json(res, 200, { login: await fbLoginState() }); }722 catch (e) { return json(res, 502, { error: e.message }); }723 }724 if (p === '/api/social/generate' && req.method === 'POST') {725 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }726 try {727 const draft = await generateDraft({ site: (body.site || '').trim(), prompt: (body.prompt || '').trim() });728 audit({ kind: 'social_generate', site: draft.insight.site });729 return json(res, 200, { draft });730 } catch (e) { return json(res, 502, { error: e.message }); }731 }732 if (p === '/api/social/publish' && req.method === 'POST') {733 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }734 try {735 await publishDraft({ caption: String(body.caption || ''), image: cardPath(body.image || '') });736 audit({ kind: 'social_publish', ip: clientIp(req) });737 return json(res, 200, { ok: true });738 } catch (e) { return json(res, 502, { error: e.message }); }739 }740 if (p === '/api/social/run' && req.method === 'POST') {741 audit({ kind: 'social_run_now', ip: clientIp(req) });742 const r = await runAutoCycle('manuel');743 return json(res, r.ok ? 200 : 502, r);744 }745 if (p.startsWith('/api/social/card/') && req.method === 'GET') {746 const fp = cardPath(p.split('/')[4] || '');747 if (!fp) { res.writeHead(404); return res.end(); }748 res.writeHead(200, { 'Content-Type': 'image/png', 'Cache-Control': 'no-cache' });749 return res.end(fs.readFileSync(fp));750 }751 if (p === '/api/social/reel/generate' && req.method === 'POST') {752 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }753 try {754 const draft = await generateReelDraft({ site: (body.site || '').trim(), prompt: (body.prompt || '').trim() });755 audit({ kind: 'social_reel_generate', site: draft.insight.site });756 return json(res, 200, { draft });757 } catch (e) { return json(res, 502, { error: e.message }); }758 }759 if (p === '/api/social/reel/publish' && req.method === 'POST') {760 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }761 try {762 await publishReelDraft({ caption: String(body.caption || ''), video: reelPath(body.video || '') });763 audit({ kind: 'social_reel_publish', ip: clientIp(req) });764 return json(res, 200, { ok: true });765 } catch (e) { return json(res, 502, { error: e.message }); }766 }767 if (p === '/api/social/reel/run' && req.method === 'POST') {768 audit({ kind: 'social_reel_run', ip: clientIp(req) });769 const r = await runReelCycle('reel-manuel');770 return json(res, r.ok ? 200 : 502, r);771 }772 if (p === '/api/social/gallery' && req.method === 'GET') return json(res, 200, { items: getGallery(), gen: genBatchStatus() });773 if (p === '/api/social/reel/genbatch' && req.method === 'POST') {774 let body; try { body = JSON.parse(await readBody(req)); } catch { body = {}; }775 const sites = (Array.isArray(body.sites) && body.sites.length) ? body.sites : REEL_BATCH_DEFAULT;776 audit({ kind: 'social_genbatch', n: sites.length, ip: clientIp(req) });777 const r = startGenBatch(sites);778 return json(res, r.started ? 200 : 409, r);779 }780 if (p === '/api/social/reel/batch' && req.method === 'POST') {781 let body; try { body = JSON.parse(await readBody(req)); } catch { body = {}; }782 const sites = (Array.isArray(body.sites) && body.sites.length) ? body.sites : REEL_BATCH_DEFAULT;783 audit({ kind: 'social_reel_batch', n: sites.length, ip: clientIp(req) });784 const r = startReelBatch(sites);785 return json(res, r.started ? 200 : 409, r);786 }787 if (p === '/api/social/reel/batchstatus' && req.method === 'GET') return json(res, 200, batchStatus());788 if (p.startsWith('/api/social/reel/') && req.method === 'GET') {789 const fp = reelPath(p.split('/')[4] || '');790 if (!fp) { res.writeHead(404); return res.end(); }791 const stat = fs.statSync(fp);792 res.writeHead(200, { 'Content-Type': 'video/mp4', 'Content-Length': stat.size, 'Cache-Control': 'no-cache' });793 return res.end(fs.readFileSync(fp));794 }795796 return json(res, 404, { error: 'not found' });797 }798799 // --- statique ---800 let file = p === '/' ? '/index.html' : p;801 file = path.normalize(file).replace(/^(\.\.[/\\])+/, '');802 const full = path.join(PUBLIC_DIR, file);803 if (!full.startsWith(PUBLIC_DIR)) { res.writeHead(403); return res.end(); }804 fs.readFile(full, (err, data) => {805 if (err) { res.writeHead(404); return res.end('not found'); }806 res.writeHead(200, { 'Content-Type': MIME[path.extname(full)] || 'application/octet-stream', 'Cache-Control': full.includes('/vendor/') ? 'public, max-age=86400' : 'no-cache' });807 res.end(data);808 });809});810811// ---------- WebSocket ----------812const wss = new WebSocketServer({ noServer: true });813814// --- pont VNC : WebSocket (noVNC dans l'admin) <-> Partage d'écran du nœud (127.0.0.1:5900) ---815const vncWss = new WebSocketServer({ noServer: true });816vncWss.on('connection', (ws) => {817 const tcp = net.connect(5900, '127.0.0.1');818 tcp.on('data', (d) => { if (ws.readyState === 1) ws.send(d); });819 tcp.on('close', () => { try { ws.close(); } catch {} });820 tcp.on('error', () => { try { ws.close(); } catch {} });821 ws.on('message', (d) => { try { tcp.write(d); } catch {} });822 ws.on('close', () => { try { tcp.end(); } catch {} });823 ws.on('error', () => { try { tcp.destroy(); } catch {} });824});825826server.on('upgrade', (req, socket, head) => {827 const url = new URL(req.url, 'http://x');828 if (!getSession(req)) {829 socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');830 return socket.destroy();831 }832 if (url.pathname === '/ws') {833 wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req));834 } else if (url.pathname === '/vncws') {835 vncWss.handleUpgrade(req, socket, head, (ws) => vncWss.emit('connection', ws, req));836 } else {837 socket.write('HTTP/1.1 404 Not Found\r\n\r\n');838 socket.destroy();839 }840});841842wss.on('connection', (ws) => {843 ws.chatId = null;844 ws.eco = false;845 ws.isAlive = true;846 ws.on('pong', () => { ws.isAlive = true; });847 ws.on('message', (raw) => {848 let msg;849 try { msg = JSON.parse(raw.toString()); } catch { return; }850 try { handleWsMessage(ws, msg); } catch (e) {851 ws.send(JSON.stringify({ type: 'error', message: e.message }));852 }853 });854 // NB : la fermeture du socket ne touche JAMAIS aux processus claude en cours.855});856857setInterval(() => {858 for (const ws of wss.clients) {859 if (!ws.isAlive) { ws.terminate(); continue; }860 ws.isAlive = false; ws.ping();861 }862}, 30000);863864function handleWsMessage(ws, msg) {865 if (msg.type === 'open') {866 const chat = getChat(msg.chatId);867 if (!chat) return ws.send(JSON.stringify({ type: 'error', message: 'Conversation introuvable' }));868 ws.chatId = chat.id;869 // rejoue tout l'historique persisté puis raccroche le live870 ws.send(JSON.stringify({871 type: 'history',872 chat: publicChat(chat),873 events: readTranscript(chat.id),874 running: running.has(chat.id),875 }));876 return;877 }878 if (msg.type === 'start') {879 const prompt = String(msg.prompt || '').trim();880 if (!prompt) return;881 let chat = msg.chatId ? getChat(msg.chatId) : null;882 if (!chat) {883 const proj = findProject(msg.project) || PROJECTS[0];884 chat = {885 id: crypto.randomBytes(8).toString('hex'),886 title: prompt.slice(0, 60),887 projectId: proj.id, projectName: proj.name,888 node: proj.node, dir: proj.dir,889 model: MODELS.includes(msg.model) ? msg.model : DEFAULT_MODEL,890 permMode: PERM_MODES.includes(msg.permMode) ? msg.permMode : 'default',891 claudeSessionId: null, state: 'idle',892 totalCost: 0, turns: 0, contextTokens: 0, alwaysAllow: [],893 created: Date.now(), updated: Date.now(),894 };895 chats.push(chat); saveChats();896 ws.send(JSON.stringify({ type: 'chat_created', chat: publicChat(chat) }));897 } else {898 if (MODELS.includes(msg.model)) chat.model = msg.model;899 if (PERM_MODES.includes(msg.permMode)) chat.permMode = msg.permMode;900 saveChats();901 }902 ws.chatId = chat.id;903 emitAndLog(chat.id, { type: 'user_prompt', text: prompt, ts: Date.now() });904 startClaude(chat, prompt);905 return;906 }907 if (msg.type === 'start_all') {908 // diffuse le MÊME prompt à TOUTES les apps KA en parallèle (1 session/app)909 const prompt = String(msg.prompt || '').trim();910 if (!prompt) return;911 const model = MODELS.includes(msg.model) ? msg.model : DEFAULT_MODEL;912 const permMode = PERM_MODES.includes(msg.permMode) ? msg.permMode : 'default';913 const created = [];914 const stamp = new Date().toLocaleString('fr-CA', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });915 for (const proj of PROJECTS) {916 const chat = {917 id: crypto.randomBytes(8).toString('hex'),918 title: '🌐 ' + prompt.slice(0, 46),919 projectId: proj.id, projectName: proj.name,920 node: proj.node, dir: proj.dir,921 model, permMode,922 claudeSessionId: null, state: 'idle',923 totalCost: 0, turns: 0, contextTokens: 0, alwaysAllow: [],924 batch: stamp,925 created: Date.now(), updated: Date.now(),926 };927 chats.push(chat);928 emitAndLog(chat.id, { type: 'user_prompt', text: prompt, ts: Date.now() });929 try { startClaude(chat, prompt); created.push(chat.id); }930 catch (e) { emitAndLog(chat.id, { type: 'error', message: e.message }); }931 }932 saveChats();933 audit({ kind: 'start_all', count: created.length, model, permMode, prompt: prompt.slice(0, 500) });934 ws.send(JSON.stringify({ type: 'batch_created', count: created.length, total: PROJECTS.length }));935 return;936 }937 if (msg.type === 'set_opts') {938 const chat = getChat(msg.chatId);939 if (!chat) return;940 if (MODELS.includes(msg.model)) chat.model = msg.model;941 if (PERM_MODES.includes(msg.permMode)) chat.permMode = msg.permMode;942 if (typeof msg.autoAllowAll === 'boolean') chat.autoAllowAll = msg.autoAllowAll;943 saveChats();944 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });945 return;946 }947 if (msg.type === 'clear') {948 const chat = getChat(msg.chatId);949 if (!chat || running.has(chat.id)) return;950 chat.claudeSessionId = null;951 chat.contextTokens = 0;952 saveChats();953 emitAndLog(chat.id, { type: 'notice', text: 'Contexte effacé — la prochaine demande démarre une session Claude Code vierge.' });954 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });955 return;956 }957 if (msg.type === 'perm') {958 const pending = pendingPerms.get(msg.requestId);959 if (!pending) return;960 clearTimeout(pending.timer);961 pendingPerms.delete(msg.requestId);962 const chat = getChat(pending.chatId);963 if (msg.allow && msg.allowAll && chat) {964 // « Tout autoriser » : plus AUCUNE permission ne sera demandée pour cette965 // conversation — le serveur approuve tout jusqu'à la fin de la tâche966 chat.autoAllowAll = true;967 saveChats();968 emitAndLog(chat.id, { type: 'notice', text: '🔓 Tout autoriser activé — la tâche ira au bout sans autre demande de permission.' });969 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });970 }971 if (msg.allow && msg.always && chat) {972 if (!chat.alwaysAllow.includes(pending.toolKey)) chat.alwaysAllow.push(pending.toolKey);973 saveChats();974 }975 audit({ kind: 'permission_response', chatId: pending.chatId, requestId: msg.requestId, allow: !!msg.allow, always: !!msg.always });976 emitAndLog(pending.chatId, { type: 'permission_resolved', requestId: msg.requestId, allow: !!msg.allow, always: !!msg.always });977 if (chat && chat.state === 'waiting_perm') setChatState(chat, 'running');978 pending.resolve(msg.allow979 ? { behavior: 'allow', updatedInput: pending.input || {} }980 : { behavior: 'deny', message: "Refusé par l'utilisateur depuis administration-ka.com" });981 return;982 }983 if (msg.type === 'interrupt') {984 if (msg.chatId) interrupt(msg.chatId);985 else if (ws.chatId) interrupt(ws.chatId);986 return;987 }988 if (msg.type === 'eco_sub') { ws.eco = true; return; }989 if (msg.type === 'eco_unsub') { ws.eco = false; return; }990}991992// ---------- monitoring Écosystème ----------993startMonitor({994 dataDir: DATA_DIR,995 onEvent: (ev) => {996 if (ev.type === 'eco_alert') broadcastAll(ev); // alertes → tout le monde997 else broadcastEco(ev); // ticks → abonnés à l'onglet998 },999});10001001// module Social : publication automatique horaire + génération sur demande1002initSocial(1003 { anthropicKey: UPGRADER_KEY, upgraderModel: UPGRADER_MODEL,1004 socialModel: config.socialModel, socialIntervalMin: config.socialIntervalMin, reelEvery: config.reelEvery },1005 (line) => broadcastAll({ type: 'social_log', line }),1006);10071008initAnalytics();10091010// au démarrage, les chats marqués "running" par un ancien processus sont orphelins1011for (const c of chats) if (c.state !== 'idle') c.state = 'idle';1012saveChats();10131014server.listen(PORT, '::', () => {1015 console.log(`admin-ka v2 sur port ${PORT} (dual-stack)`);1016});1017