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