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 crypto from 'node:crypto';6import fs from 'node:fs';7import path from 'node:path';8import os from 'node:os';9import { spawn } from 'node:child_process';10import { fileURLToPath } from 'node:url';11import { WebSocketServer } from 'ws';12import { startMonitor, ecoSummary, ecoSite, ecoIncidents, ecoNodes, getIcon, SITES } from './monitor.js';13import { initSocial, socialState, socialLog, setAuto, generateDraft, publishDraft, runAutoCycle, cardPath, fbLoginState, generateReelDraft, publishReelDraft, runReelCycle, reelPath } from './social.js';14import { execFile } from 'node:child_process';1516const __dirname = path.dirname(fileURLToPath(import.meta.url));17const APP_DIR = path.join(__dirname, '..');18const DATA_DIR = path.join(APP_DIR, 'data');19const TRANSCRIPTS_DIR = path.join(DATA_DIR, 'transcripts');20const PUBLIC_DIR = path.join(APP_DIR, 'public');21const HOME = os.homedir();2223fs.mkdirSync(TRANSCRIPTS_DIR, { recursive: true });2425// ---------- config ----------26const CONFIG_PATH = path.join(DATA_DIR, 'config.json');27if (!fs.existsSync(CONFIG_PATH)) {28 console.error('config.json manquant — exécuter: node server/set-password.js <motdepasse>');29 process.exit(1);30}31const config = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));32const PORT = config.port || 3300;33const CLAUDE_BIN = config.claudeBin || '/opt/homebrew/bin/claude';34const NODE_BIN = config.nodeBin || '/opt/homebrew/bin/node';3536// toutes les variables de ~/.claude/.env (ANTHROPIC_API_KEY, APIFY_TOKEN, …)37// sont injectées dans les runs claude locaux (les runs distants font38// `export $(cat ~/.claude/.env | xargs)` côté nœud)39function loadClaudeEnv() {40 const out = {};41 try {42 for (const line of fs.readFileSync(path.join(HOME, '.claude', '.env'), 'utf8').split('\n')) {43 const m = line.match(/^([A-Z0-9_]+)=(\S+)/);44 if (m) out[m[1]] = m[2];45 }46 } catch {}47 return out;48}49const CLAUDE_ENV = loadClaudeEnv();50const ANTHROPIC_API_KEY = CLAUDE_ENV.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY || '';5152// ---------- Upgradeur de prompt (Anthropic Messages API) ----------53const UPGRADER_KEY = config.anthropicKey || CLAUDE_ENV.ANTHROPIC_API_KEY || process.env.ANTHROPIC_API_KEY || '';54const UPGRADER_MODEL = config.upgraderModel || 'claude-opus-4-8';5556// Connaissance du Groupe KA injectée dans l'upgradeur pour produire des prompts57// Claude Code précis, conformes aux standards de l'écosystème.58const 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é.5960# Écosystème Groupe KA (12 apps web, stack Node/React, cluster MacLustr)61- 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).62- 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).6364# Conventions NON négociables (rappelle-les dans le prompt quand c'est pertinent)65- 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.66- 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.67- 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.68- Design system ka-ui : tokens/couleurs/footer centralisés (ecosystem.json). Toujours valider en mobile (simulateur/Playwright) après un changement d'UI.6970# Outils de scraping/recherche disponibles sur chaque nœud (variables dans ~/.claude/.env)71- 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.72- 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.73- 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).7475# Comment écrire le prompt amélioré761. Écris en français, à l'impératif, adressé à Claude Code.772. Commence par l'objectif clair, puis le périmètre précis (fichiers/zones probables), puis les critères d'acceptation vérifiables.783. Ajoute les détails manquants que la demande sous-entend (edge cases, validation, mobile, i18n fr-CA) sans dénaturer l'intention.794. Rappelle les étapes de clôture attendues (build, pm2 restart, healthcheck, commit+push spbgit) UNIQUEMENT si la tâche modifie du code.805. Demande à Claude Code d'explorer/lire avant de modifier, et de vérifier son travail.816. Reste concis et actionnable : pas de blabla, pas de sections inutiles. N'invente pas de faits spécifiques non fournis.827. Sortie = le prompt amélioré SEUL, sans préambule ("Voici…"), sans guillemets englobants, sans commentaire méta.`;8384async function upgradePrompt(rawPrompt, project) {85 if (!UPGRADER_KEY) throw new Error('Clé Anthropic non configurée (config.anthropicKey).');86 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}).` : '';87 const resp = await fetch('https://api.anthropic.com/v1/messages', {88 method: 'POST',89 headers: {90 'x-api-key': UPGRADER_KEY,91 'anthropic-version': '2023-06-01',92 'content-type': 'application/json',93 },94 body: JSON.stringify({95 model: UPGRADER_MODEL,96 max_tokens: 1500,97 system: KA_KNOWLEDGE,98 messages: [{ role: 'user', content: `Réécris cette demande en un prompt Claude Code excellent.${ctx}\n\nDemande brute :\n${rawPrompt}` }],99 }),100 });101 const data = await resp.json();102 if (data.error) throw new Error(data.error.message || 'Erreur Anthropic');103 const text = (data.content || []).filter(b => b.type === 'text').map(b => b.text).join('').trim();104 if (!text) throw new Error('Réponse vide du modèle');105 return text;106}107108// ---------- audit ----------109const AUDIT_PATH = path.join(DATA_DIR, 'audit.jsonl');110function audit(entry) {111 fs.appendFile(AUDIT_PATH, JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n', () => {});112}113114// ---------- sessions (auth) ----------115const SESSIONS_PATH = path.join(DATA_DIR, 'sessions.json');116let sessions = {};117try { sessions = JSON.parse(fs.readFileSync(SESSIONS_PATH, 'utf8')); } catch {}118function saveSessions() { fs.writeFileSync(SESSIONS_PATH, JSON.stringify(sessions)); }119const SESSION_IDLE_MS = 7 * 24 * 3600 * 1000;120const SESSION_MAX_MS = 30 * 24 * 3600 * 1000;121122function verifyPassword(pw) {123 const hash = crypto.scryptSync(pw, Buffer.from(config.salt, 'hex'), 64).toString('hex');124 return crypto.timingSafeEqual(Buffer.from(hash), Buffer.from(config.passwordHash));125}126function newSession() {127 const token = crypto.randomBytes(32).toString('hex');128 sessions[token] = { created: Date.now(), last: Date.now() };129 saveSessions();130 return token;131}132function getSession(req) {133 const cookie = req.headers.cookie || '';134 const m = cookie.match(/(?:^|;\s*)akid=([a-f0-9]{64})/);135 if (!m) return null;136 const s = sessions[m[1]];137 if (!s) return null;138 const now = Date.now();139 if (now - s.last > SESSION_IDLE_MS || now - s.created > SESSION_MAX_MS) {140 delete sessions[m[1]]; saveSessions(); return null;141 }142 s.last = now;143 return m[1];144}145146const loginFails = new Map();147function clientIp(req) {148 const xf = req.headers['x-forwarded-for'];149 return (xf ? String(xf).split(',')[0].trim() : req.socket.remoteAddress) || '?';150}151function loginAllowed(ip) {152 const rec = loginFails.get(ip);153 if (!rec) return true;154 if (Date.now() - rec.first > 15 * 60 * 1000) { loginFails.delete(ip); return true; }155 return rec.count < 8;156}157function loginFailed(ip) {158 const rec = loginFails.get(ip) || { first: Date.now(), count: 0 };159 rec.count++; loginFails.set(ip, rec);160}161162// ---------- chats ----------163const CHATS_PATH = path.join(DATA_DIR, 'chats.json');164let chats = [];165try { chats = JSON.parse(fs.readFileSync(CHATS_PATH, 'utf8')); } catch {}166// migration v1 → v2167for (const c of chats) {168 if (!c.model) c.model = 'fable';169 if (!c.permMode) c.permMode = c.mode === 'auto' ? 'bypass' : 'default';170 if (!c.state) c.state = 'idle';171 if (c.totalCost === undefined) c.totalCost = 0;172 if (!c.alwaysAllow) c.alwaysAllow = [];173 if (c.autoAllowAll === undefined) c.autoAllowAll = false;174}175function saveChats() { fs.writeFileSync(CHATS_PATH, JSON.stringify(chats, null, 1)); }176function getChat(id) { return chats.find(c => c.id === id); }177function publicChat(c) {178 return {179 id: c.id, title: c.title, projectId: c.projectId, projectName: c.projectName,180 model: c.model, permMode: c.permMode, state: c.state, autoAllowAll: !!c.autoAllowAll,181 claudeSessionId: c.claudeSessionId, lastModel: c.lastModel || null,182 totalCost: c.totalCost || 0, turns: c.turns || 0, contextTokens: c.contextTokens || 0,183 batch: c.batch || null,184 created: c.created, updated: c.updated,185 };186}187function transcriptPath(id) { return path.join(TRANSCRIPTS_DIR, id.replace(/[^a-zA-Z0-9_-]/g, '') + '.jsonl'); }188function appendTranscript(chatId, event) {189 fs.appendFile(transcriptPath(chatId), JSON.stringify(event) + '\n', () => {});190}191function readTranscript(chatId) {192 try {193 return fs.readFileSync(transcriptPath(chatId), 'utf8')194 .split('\n').filter(Boolean).map(l => { try { return JSON.parse(l); } catch { return null; } })195 .filter(Boolean);196 } catch { return []; }197}198199// ---------- prompt bank ----------200const PROMPTS_PATH = path.join(DATA_DIR, 'prompts.json');201let prompts = [];202try { prompts = JSON.parse(fs.readFileSync(PROMPTS_PATH, 'utf8')); } catch {}203function savePrompts() { fs.writeFileSync(PROMPTS_PATH, JSON.stringify(prompts, null, 1)); }204205// ---------- projets (12 apps Groupe KA) ----------206const SELF_NODE = 'M3U96a';207const PROJECTS = [208 { id: 'groupe-ka@M3U96b', name: 'Groupe·Ka', node: 'M3U96b', dir: '~/apps/groupe-ka' },209 { id: 'lou-ka@M3U96b', name: 'Lou·Ka', node: 'M3U96b', dir: '~/apps/lou-ka' },210 { id: 'immo-ka@M4M64a', name: 'Immo·Ka', node: 'M4M64a', dir: '~/apps/immo-ka' },211 { id: 'vrai-prix@M3U96a', name: 'Vrai-Prix', node: null, dir: path.join(HOME, 'apps', 'vrai-prix') },212 { id: 'valoplex@M3U96a', name: 'ValoPlex', node: null, dir: path.join(HOME, 'apps', 'valoplex') },213 { id: 'auto-ka@M4M64b', name: 'Auto·Ka', node: 'M4M64b', dir: '~/auto-ka' },214 { id: 'fabri-ka@M4M64a', name: 'Fabri·Ka', node: 'M4M64a', dir: '~/fabri-ka' },215 { id: 'food-ka@M4M64b', name: 'Food·Ka', node: 'M4M64b', dir: '~/apps/food-ka' },216 { id: 'resto-ka@M3U96b', name: 'Resto·Ka', node: 'M3U96b', dir: '~/apps/resto-ka' },217 { id: 'sorti-ka@M3U96a', name: 'Sorti·Ka', node: null, dir: path.join(HOME, 'apps', 'sorti-ka') },218 { id: 'crea-ka@M3U96b', name: 'Créa·Ka', node: 'M3U96b', dir: '~/apps/crea-ka' },219 { id: 'job-ka@M3U96a', name: 'Job·Ka', node: null, dir: path.join(HOME, 'apps', 'job-ka') },220 { id: 'trouve-ka@M2M32', name: 'Trouve·Ka', node: 'M2M32', dir: '~/trouve-ka' },221];222// Orchestrateur : une seule session sur M3U96a qui pilote les 13 apps via SSH,223// en gardant le contexte complet de la tâche.224const ORCH_PROJECT = { id: 'ORCH', name: '🎛️ Orchestrateur multi-sites', node: null, dir: path.join(HOME, 'ka-orchestrator') };225function listProjects() {226 return [227 { id: ORCH_PROJECT.id, name: ORCH_PROJECT.name, node: SELF_NODE, dir: ORCH_PROJECT.dir },228 ...PROJECTS.map(p => ({ id: p.id, name: p.name, node: p.node || SELF_NODE, dir: p.dir })),229 ];230}231function findProject(id) {232 if (id === 'ORCH') return ORCH_PROJECT;233 return PROJECTS.find(p => p.id === id) || null;234}235236// ---------- exécution Claude Code ----------237const MODELS = ['fable', 'opus', 'sonnet', 'haiku'];238// mappage vers les IDs réels (les alias CLI des nœuds retombent sur d'anciennes versions)239const CLI_MODEL = { fable: 'claude-fable-5', opus: 'claude-opus-5', sonnet: 'claude-sonnet-5', haiku: 'claude-haiku-4-5-20251001' };240const DEFAULT_MODEL = 'fable';241const PERM_MODES = ['default', 'acceptEdits', 'plan', 'bypass'];242const ALLOWED_READONLY = 'Read,Glob,Grep,LS,WebFetch,WebSearch,TodoWrite,NotebookRead,Task';243244const 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.`;245246const 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.`;247248const shq = (s) => `'` + String(s).replace(/'/g, `'\\''`) + `'`;249250// chatId -> { proc, permToken, stderr, remote }251const running = new Map();252// requestId -> { chatId, resolve, timer, input, toolKey }253const pendingPerms = new Map();254255function broadcast(chatId, msg) {256 const data = JSON.stringify(msg);257 for (const ws of wss.clients) {258 if (ws.readyState === 1 && ws.chatId === chatId) ws.send(data);259 }260}261function broadcastAll(msg) {262 const data = JSON.stringify(msg);263 for (const ws of wss.clients) if (ws.readyState === 1) ws.send(data);264}265function broadcastEco(msg) {266 const data = JSON.stringify(msg);267 for (const ws of wss.clients) if (ws.readyState === 1 && ws.eco) ws.send(data);268}269function emitAndLog(chatId, msg) {270 appendTranscript(chatId, msg);271 broadcast(chatId, msg);272}273function setChatState(chat, state) {274 chat.state = state;275 chat.updated = Date.now();276 saveChats();277 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });278}279280function permKey(tool, input) {281 if (tool === 'Bash') {282 const first = String(input?.command || '').trim().split(/\s+/)[0] || '?';283 return 'Bash:' + first;284 }285 return tool;286}287288function startClaude(chat, prompt) {289 if (running.has(chat.id)) throw new Error('Une exécution est déjà en cours pour cette conversation.');290 const permToken = crypto.randomBytes(16).toString('hex');291 const model = MODELS.includes(chat.model) ? chat.model : DEFAULT_MODEL;292 const permMode = PERM_MODES.includes(chat.permMode) ? chat.permMode : 'default';293 let proc;294295 const sysAppend = chat.projectId === 'ORCH' ? ORCH_SYSTEM : SYSTEM_APPEND;296 const baseArgs = ['-p', '--output-format', 'stream-json', '--verbose', '--include-partial-messages',297 '--model', CLI_MODEL[model], '--append-system-prompt', sysAppend];298 if (chat.claudeSessionId) baseArgs.push('--resume', chat.claudeSessionId);299300 if (!chat.node) {301 // exécution locale (app déployée sur M3U96a)302 const args = [...baseArgs];303 if (permMode === 'bypass') {304 args.push('--dangerously-skip-permissions');305 } else {306 args.push('--permission-mode', permMode);307 const mcpCfg = {308 mcpServers: {309 adminka: {310 command: NODE_BIN,311 args: [path.join(__dirname, 'perm-mcp.js')],312 env: {313 ADMIN_KA_PERM_URL: `http://127.0.0.1:${PORT}/internal/perm`,314 ADMIN_KA_PERM_TOKEN: permToken,315 },316 },317 },318 };319 const cfgPath = path.join(DATA_DIR, `mcp-${chat.id}.json`);320 fs.writeFileSync(cfgPath, JSON.stringify(mcpCfg));321 args.push('--mcp-config', cfgPath);322 args.push('--permission-prompt-tool', 'mcp__adminka__approve');323 args.push('--allowedTools', ALLOWED_READONLY);324 }325 proc = spawn(CLAUDE_BIN, args, {326 cwd: chat.dir,327 env: {328 ...process.env, ...CLAUDE_ENV,329 PATH: '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', HOME,330 },331 stdio: ['pipe', 'pipe', 'pipe'],332 detached: false,333 });334 } else {335 // exécution distante : claude tourne SUR le nœud de déploiement de l'app,336 // dans le repo de prod. Permissions via tunnel SSH inverse (IPv4 LAN non routée).337 const sshArgs = ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=15', '-o', 'ServerAliveInterval=30', '-o', 'ServerAliveCountMax=6'];338 let cmd = 'exec /opt/homebrew/bin/claude ' + baseArgs.map(shq).join(' ');339 if (permMode === 'bypass') {340 cmd += ' --dangerously-skip-permissions';341 } else {342 const revPort = 21000 + Math.floor(Math.random() * 3000);343 sshArgs.push('-R', `127.0.0.1:${revPort}:127.0.0.1:${PORT}`);344 const mcpCfg = {345 mcpServers: {346 adminka: {347 command: '/opt/homebrew/bin/node',348 args: ['/Users/simon-pierreboucher/.adminka/perm-mcp.js'],349 env: {350 ADMIN_KA_PERM_URL: `http://127.0.0.1:${revPort}/internal/perm`,351 ADMIN_KA_PERM_TOKEN: permToken,352 },353 },354 },355 };356 const cfgFile = `/tmp/adminka-mcp-${permToken}.json`;357 cmd = `printf '%s' '${JSON.stringify(mcpCfg)}' > ${cfgFile} && ${cmd} --permission-mode ${permMode} --mcp-config ${cfgFile} --permission-prompt-tool mcp__adminka__approve --allowedTools '${ALLOWED_READONLY}'`;358 }359 const remoteCmd = [360 `cd ${chat.dir}`,361 'export PATH=/opt/homebrew/bin:/usr/local/bin:$PATH',362 'export $(cat ~/.claude/.env | xargs)',363 `echo $$ > /tmp/adminka-pid-${permToken}`,364 cmd,365 ].join(' && ');366 proc = spawn('ssh', [...sshArgs, chat.node, remoteCmd], {367 env: { ...process.env, PATH: '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', HOME },368 stdio: ['pipe', 'pipe', 'pipe'],369 });370 }371 proc.stdin.write(prompt);372 proc.stdin.end();373374 const state = { proc, permToken, stderr: '', remote: chat.node || null };375 running.set(chat.id, state);376 audit({ kind: 'prompt', chatId: chat.id, project: chat.projectId, node: chat.node || SELF_NODE, dir: chat.dir, model, permMode, prompt: prompt.slice(0, 2000) });377 emitAndLog(chat.id, { type: 'status', state: 'running' });378 setChatState(chat, 'running');379380 let buf = '';381 proc.stdout.on('data', (d) => {382 buf += d.toString('utf8');383 let idx;384 while ((idx = buf.indexOf('\n')) >= 0) {385 const line = buf.slice(0, idx).trim();386 buf = buf.slice(idx + 1);387 if (!line) continue;388 let ev;389 try { ev = JSON.parse(line); } catch { continue; }390 handleClaudeEvent(chat, ev);391 }392 });393 proc.stderr.on('data', (d) => { state.stderr = (state.stderr + d.toString()).slice(-8000); });394 proc.on('close', (code) => {395 running.delete(chat.id);396 for (const [rid, p] of pendingPerms) {397 if (p.chatId === chat.id) { clearTimeout(p.timer); p.resolve({ behavior: 'deny', message: 'Exécution terminée' }); pendingPerms.delete(rid); }398 }399 if (code !== 0 && code !== null) {400 emitAndLog(chat.id, { type: 'error', message: `claude a quitté (code ${code})\n${state.stderr.slice(-1500)}` });401 }402 emitAndLog(chat.id, { type: 'status', state: 'idle' });403 setChatState(chat, 'idle');404 broadcastAll({ type: 'notify', kind: 'done', chatId: chat.id, title: chat.title, project: chat.projectName });405 });406 proc.on('error', (err) => {407 running.delete(chat.id);408 emitAndLog(chat.id, { type: 'error', message: 'Impossible de lancer claude: ' + err.message });409 emitAndLog(chat.id, { type: 'status', state: 'idle' });410 setChatState(chat, 'idle');411 });412}413414function handleClaudeEvent(chat, ev) {415 if (ev.type === 'system' && ev.subtype === 'init') {416 if (ev.session_id) chat.claudeSessionId = ev.session_id;417 if (ev.model) chat.lastModel = ev.model;418 saveChats();419 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });420 }421 if (ev.type === 'assistant' && ev.message && Array.isArray(ev.message.content)) {422 for (const block of ev.message.content) {423 if (block.type === 'tool_use') {424 audit({ kind: 'tool_use', chatId: chat.id, tool: block.name, input: JSON.stringify(block.input || {}).slice(0, 1000) });425 }426 }427 }428 if (ev.type === 'result') {429 chat.totalCost = (chat.totalCost || 0) + (ev.total_cost_usd || 0);430 chat.turns = (chat.turns || 0) + (ev.num_turns || 0);431 const u = ev.usage || {};432 chat.contextTokens = (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0);433 saveChats();434 audit({ kind: 'result', chatId: chat.id, subtype: ev.subtype, cost: ev.total_cost_usd, duration_ms: ev.duration_ms, turns: ev.num_turns });435 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });436 }437 if (ev.type === 'stream_event') {438 broadcast(chat.id, { type: 'claude', event: ev });439 } else {440 emitAndLog(chat.id, { type: 'claude', event: ev });441 }442}443444function interrupt(chatId) {445 const st = running.get(chatId);446 if (!st) return;447 audit({ kind: 'interrupt', chatId });448 if (st.remote) {449 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}`], {450 env: { ...process.env, HOME }, stdio: 'ignore',451 });452 }453 st.proc.kill('SIGTERM');454 setTimeout(() => { try { st.proc.kill('SIGKILL'); } catch {} }, 5000);455}456457// exécuter un script sur un nœud (local ou ssh) — pour les actions d'admin458function runOnNode(node, script) {459 return new Promise((resolve) => {460 const full = `export PATH=/opt/homebrew/bin:/usr/local/bin:$PATH; ${script}`;461 const bin = node === SELF_NODE ? '/bin/bash' : 'ssh';462 const args = node === SELF_NODE ? ['-c', full] : ['-o', 'BatchMode=yes', '-o', 'ConnectTimeout=12', node, full];463 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 } },464 (err, stdout, stderr) => resolve({ stdout: String(stdout || ''), stderr: String(stderr || ''), error: err ? (stderr || err.message) : null }));465 });466}467468// ---------- HTTP ----------469const 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' };470471function readBody(req, limit = 512 * 1024) {472 return new Promise((resolve, reject) => {473 let data = '';474 req.on('data', (c) => { data += c; if (data.length > limit) { reject(new Error('body trop gros')); req.destroy(); } });475 req.on('end', () => resolve(data));476 req.on('error', reject);477 });478}479function json(res, code, obj) {480 res.writeHead(code, { 'Content-Type': 'application/json' });481 res.end(JSON.stringify(obj));482}483484const server = http.createServer(async (req, res) => {485 const url = new URL(req.url, 'http://x');486 const p = url.pathname;487488 if (p === '/healthz') { res.writeHead(200); return res.end('ok'); }489490 // logos des sites (favicon/apple-touch-icon en cache) — public, léger491 if (p.startsWith('/icons/')) {492 const icon = getIcon(p.split('/')[2]);493 if (!icon) { res.writeHead(404); return res.end(); }494 res.writeHead(200, { 'Content-Type': icon.type, 'Cache-Control': 'public, max-age=86400' });495 return res.end(icon.buf);496 }497498 // --- endpoint interne de permission (long-poll par perm-mcp.js) ---499 if (p === '/internal/perm' && req.method === 'POST') {500 let body;501 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }502 let chatId = null;503 for (const [cid, st] of running) if (st.permToken === body.token) chatId = cid;504 if (!chatId) return json(res, 403, { error: 'bad token' });505 const chat = getChat(chatId);506 const toolKey = permKey(body.tool_name, body.input);507508 // « Tout autoriser » activé → toute la session est auto-approuvée : la tâche509 // va au bout sans jamais attendre l'utilisateur510 if (chat && chat.autoAllowAll) {511 audit({ kind: 'permission_auto_all', chatId, tool: body.tool_name });512 emitAndLog(chatId, { type: 'permission_auto', tool: body.tool_name, key: 'tout autoriser', input: body.input });513 return json(res, 200, { behavior: 'allow', updatedInput: body.input || {} });514 }515516 // « Toujours autoriser » déjà accordé pour cet outil dans cette conversation517 if (chat && (chat.alwaysAllow || []).includes(toolKey)) {518 audit({ kind: 'permission_auto', chatId, tool: body.tool_name, key: toolKey });519 emitAndLog(chatId, { type: 'permission_auto', tool: body.tool_name, key: toolKey, input: body.input });520 return json(res, 200, { behavior: 'allow', updatedInput: body.input || {} });521 }522523 const requestId = crypto.randomBytes(8).toString('hex');524 const p2 = new Promise((resolve) => {525 const timer = setTimeout(() => {526 pendingPerms.delete(requestId);527 emitAndLog(chatId, { type: 'permission_resolved', requestId, allow: false, reason: 'timeout' });528 if (chat && chat.state === 'waiting_perm') setChatState(chat, 'running');529 resolve({ behavior: 'deny', message: "Pas de réponse de l'utilisateur (timeout 30 min)" });530 }, 30 * 60 * 1000);531 pendingPerms.set(requestId, { chatId, resolve, timer, input: body.input, toolKey });532 });533 audit({ kind: 'permission_request', chatId, tool: body.tool_name, input: JSON.stringify(body.input || {}).slice(0, 1000) });534 emitAndLog(chatId, { type: 'permission_request', requestId, tool: body.tool_name, input: body.input });535 if (chat) setChatState(chat, 'waiting_perm');536 broadcastAll({ type: 'notify', kind: 'perm', chatId, title: chat?.title || '', tool: body.tool_name });537 const decision = await p2;538 return json(res, 200, decision);539 }540541 // --- auth ---542 if (p === '/api/login' && req.method === 'POST') {543 const ip = clientIp(req);544 if (!loginAllowed(ip)) return json(res, 429, { error: 'Trop de tentatives — réessayer dans 15 minutes.' });545 let body;546 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }547 if (typeof body.password !== 'string' || !verifyPassword(body.password)) {548 loginFailed(ip);549 audit({ kind: 'login_fail', ip });550 return json(res, 401, { error: 'Mot de passe invalide.' });551 }552 const token = newSession();553 audit({ kind: 'login_ok', ip });554 res.writeHead(200, {555 'Content-Type': 'application/json',556 'Set-Cookie': `akid=${token}; HttpOnly; Path=/; Max-Age=2592000; SameSite=Lax; Secure`,557 });558 return res.end(JSON.stringify({ ok: true }));559 }560 if (p === '/api/logout' && req.method === 'POST') {561 const t = getSession(req);562 if (t) { delete sessions[t]; saveSessions(); }563 res.writeHead(200, { 'Content-Type': 'application/json', 'Set-Cookie': 'akid=; HttpOnly; Path=/; Max-Age=0; SameSite=Lax; Secure' });564 return res.end(JSON.stringify({ ok: true }));565 }566567 // --- API authentifiée ---568 if (p.startsWith('/api/')) {569 if (!getSession(req)) return json(res, 401, { error: 'auth' });570 if (p === '/api/me') return json(res, 200, { ok: true, host: os.hostname(), node: SELF_NODE, version: '2.0.0' });571 if (p === '/api/projects') return json(res, 200, { projects: listProjects() });572 if (p === '/api/chats' && req.method === 'GET') {573 const list = [...chats].sort((a, b) => (b.updated || 0) - (a.updated || 0)).slice(0, 100).map(publicChat);574 return json(res, 200, { chats: list });575 }576 if (p.startsWith('/api/chats/') && req.method === 'DELETE') {577 const id = p.split('/')[3];578 const chat = getChat(id);579 if (chat && !running.has(id)) {580 chats = chats.filter(c => c.id !== id); saveChats();581 try { fs.unlinkSync(transcriptPath(id)); } catch {}582 return json(res, 200, { ok: true });583 }584 return json(res, 400, { error: 'introuvable ou en cours' });585 }586 // --- prompt bank ---587 if (p === '/api/prompts' && req.method === 'GET') {588 const list = [...prompts].sort((a, b) => (b.updated || 0) - (a.updated || 0));589 return json(res, 200, { prompts: list });590 }591 if (p === '/api/prompts' && req.method === 'POST') {592 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }593 const text = String(body.text || '').trim();594 if (!text) return json(res, 400, { error: 'texte vide' });595 const pr = {596 id: crypto.randomBytes(6).toString('hex'),597 title: (String(body.title || '').trim() || text.slice(0, 48)),598 text,599 project: findProject(body.project) ? body.project : null,600 created: Date.now(), updated: Date.now(),601 };602 prompts.push(pr); savePrompts();603 audit({ kind: 'prompt_save', id: pr.id });604 return json(res, 200, { prompt: pr });605 }606 if (p.startsWith('/api/prompts/') && req.method === 'PUT') {607 const id = p.split('/')[3];608 const pr = prompts.find(x => x.id === id);609 if (!pr) return json(res, 404, { error: 'introuvable' });610 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }611 if (typeof body.text === 'string' && body.text.trim()) pr.text = body.text.trim();612 if (typeof body.title === 'string') pr.title = body.title.trim() || pr.text.slice(0, 48);613 if ('project' in body) pr.project = findProject(body.project) ? body.project : null;614 pr.updated = Date.now(); savePrompts();615 return json(res, 200, { prompt: pr });616 }617 if (p.startsWith('/api/prompts/') && req.method === 'DELETE') {618 const id = p.split('/')[3];619 prompts = prompts.filter(x => x.id !== id); savePrompts();620 return json(res, 200, { ok: true });621 }622 if (p === '/api/upgrade-prompt' && req.method === 'POST') {623 let body;624 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }625 const raw = String(body.prompt || '').trim();626 if (!raw) return json(res, 400, { error: 'prompt vide' });627 try {628 const project = findProject(body.project);629 const upgraded = await upgradePrompt(raw, project);630 audit({ kind: 'upgrade_prompt', project: body.project, len_in: raw.length, len_out: upgraded.length });631 return json(res, 200, { upgraded });632 } catch (e) {633 return json(res, 502, { error: e.message });634 }635 }636 if (p === '/api/eco/summary') return json(res, 200, ecoSummary());637 if (p === '/api/eco/incidents') return json(res, 200, { incidents: ecoIncidents() });638 if (p === '/api/eco/nodes') return json(res, 200, ecoNodes());639 if (p.startsWith('/api/eco/site/')) {640 const d = ecoSite(p.split('/')[4]);641 return d ? json(res, 200, d) : json(res, 404, { error: 'site inconnu' });642 }643644 // --- actions d'administration par site (pm2 / logs / commits) ---645 if (p === '/api/admin/action' && req.method === 'POST') {646 let body;647 try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }648 const site = SITES.find(s => s.app === body.app);649 const action = ['restart', 'stop', 'start'].includes(body.action) ? body.action : null;650 if (!site || !action) return json(res, 400, { error: 'app ou action invalide' });651 audit({ kind: 'admin_action', app: site.app, node: site.node, action, ip: clientIp(req) });652 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')"`);653 return json(res, 200, { ok: !out.error, output: (out.stdout || out.error || '').trim().split('\n').pop(), full: (out.stdout || '').slice(-1500) });654 }655 if (p.startsWith('/api/admin/logs/')) {656 const site = SITES.find(s => s.app === p.split('/')[4]);657 if (!site) return json(res, 404, { error: 'site inconnu' });658 const out = await runOnNode(site.node, `pm2 logs ${site.pm2} --nostream --lines 60 2>&1 | tail -70`);659 return json(res, 200, { logs: out.stdout || out.error || '(vide)' });660 }661 if (p.startsWith('/api/admin/commits/')) {662 const site = SITES.find(s => s.app === p.split('/')[4]);663 if (!site) return json(res, 404, { error: 'site inconnu' });664 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 ✓")`);665 return json(res, 200, { text: out.stdout || out.error || '(vide)' });666 }667 // --- Social : publication automatique + a la demande ---668 if (p === '/api/social/state' && req.method === 'GET') {669 return json(res, 200, { state: socialState(), log: socialLog(40) });670 }671 if (p === '/api/social/auto' && req.method === 'POST') {672 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }673 audit({ kind: 'social_auto', on: !!body.on, ip: clientIp(req) });674 return json(res, 200, { state: setAuto(!!body.on) });675 }676 if (p === '/api/social/login' && req.method === 'GET') {677 try { return json(res, 200, { login: await fbLoginState() }); }678 catch (e) { return json(res, 502, { error: e.message }); }679 }680 if (p === '/api/social/generate' && req.method === 'POST') {681 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }682 try {683 const draft = await generateDraft({ site: (body.site || '').trim(), prompt: (body.prompt || '').trim() });684 audit({ kind: 'social_generate', site: draft.insight.site });685 return json(res, 200, { draft });686 } catch (e) { return json(res, 502, { error: e.message }); }687 }688 if (p === '/api/social/publish' && req.method === 'POST') {689 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }690 try {691 await publishDraft({ caption: String(body.caption || ''), image: cardPath(body.image || '') });692 audit({ kind: 'social_publish', ip: clientIp(req) });693 return json(res, 200, { ok: true });694 } catch (e) { return json(res, 502, { error: e.message }); }695 }696 if (p === '/api/social/run' && req.method === 'POST') {697 audit({ kind: 'social_run_now', ip: clientIp(req) });698 const r = await runAutoCycle('manuel');699 return json(res, r.ok ? 200 : 502, r);700 }701 if (p.startsWith('/api/social/card/') && req.method === 'GET') {702 const fp = cardPath(p.split('/')[4] || '');703 if (!fp) { res.writeHead(404); return res.end(); }704 res.writeHead(200, { 'Content-Type': 'image/png', 'Cache-Control': 'no-cache' });705 return res.end(fs.readFileSync(fp));706 }707 if (p === '/api/social/reel/generate' && req.method === 'POST') {708 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }709 try {710 const draft = await generateReelDraft({ site: (body.site || '').trim(), prompt: (body.prompt || '').trim() });711 audit({ kind: 'social_reel_generate', site: draft.insight.site });712 return json(res, 200, { draft });713 } catch (e) { return json(res, 502, { error: e.message }); }714 }715 if (p === '/api/social/reel/publish' && req.method === 'POST') {716 let body; try { body = JSON.parse(await readBody(req)); } catch { return json(res, 400, { error: 'bad json' }); }717 try {718 await publishReelDraft({ caption: String(body.caption || ''), video: reelPath(body.video || '') });719 audit({ kind: 'social_reel_publish', ip: clientIp(req) });720 return json(res, 200, { ok: true });721 } catch (e) { return json(res, 502, { error: e.message }); }722 }723 if (p === '/api/social/reel/run' && req.method === 'POST') {724 audit({ kind: 'social_reel_run', ip: clientIp(req) });725 const r = await runReelCycle('reel-manuel');726 return json(res, r.ok ? 200 : 502, r);727 }728 if (p.startsWith('/api/social/reel/') && req.method === 'GET') {729 const fp = reelPath(p.split('/')[4] || '');730 if (!fp) { res.writeHead(404); return res.end(); }731 const stat = fs.statSync(fp);732 res.writeHead(200, { 'Content-Type': 'video/mp4', 'Content-Length': stat.size, 'Cache-Control': 'no-cache' });733 return res.end(fs.readFileSync(fp));734 }735736 return json(res, 404, { error: 'not found' });737 }738739 // --- statique ---740 let file = p === '/' ? '/index.html' : p;741 file = path.normalize(file).replace(/^(\.\.[/\\])+/, '');742 const full = path.join(PUBLIC_DIR, file);743 if (!full.startsWith(PUBLIC_DIR)) { res.writeHead(403); return res.end(); }744 fs.readFile(full, (err, data) => {745 if (err) { res.writeHead(404); return res.end('not found'); }746 res.writeHead(200, { 'Content-Type': MIME[path.extname(full)] || 'application/octet-stream', 'Cache-Control': full.includes('/vendor/') ? 'public, max-age=86400' : 'no-cache' });747 res.end(data);748 });749});750751// ---------- WebSocket ----------752const wss = new WebSocketServer({ noServer: true });753754server.on('upgrade', (req, socket, head) => {755 const url = new URL(req.url, 'http://x');756 if (url.pathname !== '/ws' || !getSession(req)) {757 socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');758 return socket.destroy();759 }760 wss.handleUpgrade(req, socket, head, (ws) => wss.emit('connection', ws, req));761});762763wss.on('connection', (ws) => {764 ws.chatId = null;765 ws.eco = false;766 ws.isAlive = true;767 ws.on('pong', () => { ws.isAlive = true; });768 ws.on('message', (raw) => {769 let msg;770 try { msg = JSON.parse(raw.toString()); } catch { return; }771 try { handleWsMessage(ws, msg); } catch (e) {772 ws.send(JSON.stringify({ type: 'error', message: e.message }));773 }774 });775 // NB : la fermeture du socket ne touche JAMAIS aux processus claude en cours.776});777778setInterval(() => {779 for (const ws of wss.clients) {780 if (!ws.isAlive) { ws.terminate(); continue; }781 ws.isAlive = false; ws.ping();782 }783}, 30000);784785function handleWsMessage(ws, msg) {786 if (msg.type === 'open') {787 const chat = getChat(msg.chatId);788 if (!chat) return ws.send(JSON.stringify({ type: 'error', message: 'Conversation introuvable' }));789 ws.chatId = chat.id;790 // rejoue tout l'historique persisté puis raccroche le live791 ws.send(JSON.stringify({792 type: 'history',793 chat: publicChat(chat),794 events: readTranscript(chat.id),795 running: running.has(chat.id),796 }));797 return;798 }799 if (msg.type === 'start') {800 const prompt = String(msg.prompt || '').trim();801 if (!prompt) return;802 let chat = msg.chatId ? getChat(msg.chatId) : null;803 if (!chat) {804 const proj = findProject(msg.project) || PROJECTS[0];805 chat = {806 id: crypto.randomBytes(8).toString('hex'),807 title: prompt.slice(0, 60),808 projectId: proj.id, projectName: proj.name,809 node: proj.node, dir: proj.dir,810 model: MODELS.includes(msg.model) ? msg.model : DEFAULT_MODEL,811 permMode: PERM_MODES.includes(msg.permMode) ? msg.permMode : 'default',812 claudeSessionId: null, state: 'idle',813 totalCost: 0, turns: 0, contextTokens: 0, alwaysAllow: [],814 created: Date.now(), updated: Date.now(),815 };816 chats.push(chat); saveChats();817 ws.send(JSON.stringify({ type: 'chat_created', chat: publicChat(chat) }));818 } else {819 if (MODELS.includes(msg.model)) chat.model = msg.model;820 if (PERM_MODES.includes(msg.permMode)) chat.permMode = msg.permMode;821 saveChats();822 }823 ws.chatId = chat.id;824 emitAndLog(chat.id, { type: 'user_prompt', text: prompt, ts: Date.now() });825 startClaude(chat, prompt);826 return;827 }828 if (msg.type === 'start_all') {829 // diffuse le MÊME prompt à TOUTES les apps KA en parallèle (1 session/app)830 const prompt = String(msg.prompt || '').trim();831 if (!prompt) return;832 const model = MODELS.includes(msg.model) ? msg.model : DEFAULT_MODEL;833 const permMode = PERM_MODES.includes(msg.permMode) ? msg.permMode : 'default';834 const created = [];835 const stamp = new Date().toLocaleString('fr-CA', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });836 for (const proj of PROJECTS) {837 const chat = {838 id: crypto.randomBytes(8).toString('hex'),839 title: '🌐 ' + prompt.slice(0, 46),840 projectId: proj.id, projectName: proj.name,841 node: proj.node, dir: proj.dir,842 model, permMode,843 claudeSessionId: null, state: 'idle',844 totalCost: 0, turns: 0, contextTokens: 0, alwaysAllow: [],845 batch: stamp,846 created: Date.now(), updated: Date.now(),847 };848 chats.push(chat);849 emitAndLog(chat.id, { type: 'user_prompt', text: prompt, ts: Date.now() });850 try { startClaude(chat, prompt); created.push(chat.id); }851 catch (e) { emitAndLog(chat.id, { type: 'error', message: e.message }); }852 }853 saveChats();854 audit({ kind: 'start_all', count: created.length, model, permMode, prompt: prompt.slice(0, 500) });855 ws.send(JSON.stringify({ type: 'batch_created', count: created.length, total: PROJECTS.length }));856 return;857 }858 if (msg.type === 'set_opts') {859 const chat = getChat(msg.chatId);860 if (!chat) return;861 if (MODELS.includes(msg.model)) chat.model = msg.model;862 if (PERM_MODES.includes(msg.permMode)) chat.permMode = msg.permMode;863 if (typeof msg.autoAllowAll === 'boolean') chat.autoAllowAll = msg.autoAllowAll;864 saveChats();865 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });866 return;867 }868 if (msg.type === 'clear') {869 const chat = getChat(msg.chatId);870 if (!chat || running.has(chat.id)) return;871 chat.claudeSessionId = null;872 chat.contextTokens = 0;873 saveChats();874 emitAndLog(chat.id, { type: 'notice', text: 'Contexte effacé — la prochaine demande démarre une session Claude Code vierge.' });875 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });876 return;877 }878 if (msg.type === 'perm') {879 const pending = pendingPerms.get(msg.requestId);880 if (!pending) return;881 clearTimeout(pending.timer);882 pendingPerms.delete(msg.requestId);883 const chat = getChat(pending.chatId);884 if (msg.allow && msg.allowAll && chat) {885 // « Tout autoriser » : plus AUCUNE permission ne sera demandée pour cette886 // conversation — le serveur approuve tout jusqu'à la fin de la tâche887 chat.autoAllowAll = true;888 saveChats();889 emitAndLog(chat.id, { type: 'notice', text: '🔓 Tout autoriser activé — la tâche ira au bout sans autre demande de permission.' });890 broadcastAll({ type: 'chat_meta', chat: publicChat(chat) });891 }892 if (msg.allow && msg.always && chat) {893 if (!chat.alwaysAllow.includes(pending.toolKey)) chat.alwaysAllow.push(pending.toolKey);894 saveChats();895 }896 audit({ kind: 'permission_response', chatId: pending.chatId, requestId: msg.requestId, allow: !!msg.allow, always: !!msg.always });897 emitAndLog(pending.chatId, { type: 'permission_resolved', requestId: msg.requestId, allow: !!msg.allow, always: !!msg.always });898 if (chat && chat.state === 'waiting_perm') setChatState(chat, 'running');899 pending.resolve(msg.allow900 ? { behavior: 'allow', updatedInput: pending.input || {} }901 : { behavior: 'deny', message: "Refusé par l'utilisateur depuis administration-ka.com" });902 return;903 }904 if (msg.type === 'interrupt') {905 if (msg.chatId) interrupt(msg.chatId);906 else if (ws.chatId) interrupt(ws.chatId);907 return;908 }909 if (msg.type === 'eco_sub') { ws.eco = true; return; }910 if (msg.type === 'eco_unsub') { ws.eco = false; return; }911}912913// ---------- monitoring Écosystème ----------914startMonitor({915 dataDir: DATA_DIR,916 onEvent: (ev) => {917 if (ev.type === 'eco_alert') broadcastAll(ev); // alertes → tout le monde918 else broadcastEco(ev); // ticks → abonnés à l'onglet919 },920});921922// module Social : publication automatique horaire + génération sur demande923initSocial(924 { anthropicKey: UPGRADER_KEY, upgraderModel: UPGRADER_MODEL,925 socialModel: config.socialModel, socialIntervalMin: config.socialIntervalMin, reelEvery: config.reelEvery },926 (line) => broadcastAll({ type: 'social_log', line }),927);928929// au démarrage, les chats marqués "running" par un ancien processus sont orphelins930for (const c of chats) if (c.state !== 'idle') c.state = 'idle';931saveChats();932933server.listen(PORT, '::', () => {934 console.log(`admin-ka v2 sur port ${PORT} (dual-stack)`);935});936